2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcType]{Types used in the typechecker}
6 This module provides the Type interface for front-end parts of the
9 * treat "source types" as opaque:
10 newtypes, and predicates are meaningful.
11 * look through usage types
13 The "tc" prefix is for "typechechecker", because the type checker
14 is the principal client.
18 --------------------------------
20 TcType, TcSigmaType, TcRhoType, TcTauType, TcPredType, TcThetaType,
21 TcTyVar, TcTyVarSet, TcKind,
23 --------------------------------
25 Expected(..), TcRef, TcTyVarDetails(..),
26 MetaDetails(Flexi, Indirect), SkolemInfo(..), pprSkolemTyVar,
27 isImmutableTyVar, isSkolemTyVar, isMetaTyVar, isExistentialTyVar, skolemTvInfo, metaTvRef,
30 --------------------------------
32 mkPhiTy, mkSigmaTy, hoistForAllTys,
34 --------------------------------
36 -- These are important because they do not look through newtypes
37 tcSplitForAllTys, tcSplitPhiTy,
38 tcSplitFunTy_maybe, tcSplitFunTys, tcFunArgTy, tcFunResultTy,
39 tcSplitTyConApp, tcSplitTyConApp_maybe, tcTyConAppTyCon, tcTyConAppArgs,
40 tcSplitAppTy_maybe, tcSplitAppTy, tcSplitAppTys, tcSplitSigmaTy,
41 tcGetTyVar_maybe, tcGetTyVar,
43 ---------------------------------
45 -- Again, newtypes are opaque
46 tcEqType, tcEqTypes, tcEqPred, tcCmpType, tcCmpTypes, tcCmpPred, tcEqTypeX,
47 isSigmaTy, isOverloadedTy,
48 isDoubleTy, isFloatTy, isIntTy,
49 isIntegerTy, isAddrTy, isBoolTy, isUnitTy,
50 isTauTy, tcIsTyVarTy, tcIsForAllTy,
52 ---------------------------------
53 -- Misc type manipulators
54 deNoteType, classesOfTheta,
55 tyClsNamesOfType, tyClsNamesOfDFunHead,
58 ---------------------------------
60 getClassPredTys_maybe, getClassPredTys,
61 isClassPred, isTyVarClassPred,
62 mkDictTy, tcSplitPredTy_maybe,
63 isPredTy, isDictTy, tcSplitDFunTy, tcSplitDFunHead, predTyUnique,
64 mkClassPred, isInheritablePred, isLinearPred, isIPPred, mkPredName,
66 ---------------------------------
67 -- Foreign import and export
68 isFFIArgumentTy, -- :: DynFlags -> Safety -> Type -> Bool
69 isFFIImportResultTy, -- :: DynFlags -> Type -> Bool
70 isFFIExportResultTy, -- :: Type -> Bool
71 isFFIExternalTy, -- :: Type -> Bool
72 isFFIDynArgumentTy, -- :: Type -> Bool
73 isFFIDynResultTy, -- :: Type -> Bool
74 isFFILabelTy, -- :: Type -> Bool
75 isFFIDotnetTy, -- :: DynFlags -> Type -> Bool
76 isFFIDotnetObjTy, -- :: Type -> Bool
77 isFFITy, -- :: Type -> Bool
79 toDNType, -- :: Type -> DNType
81 --------------------------------
82 -- Rexported from Type
83 Kind, -- Stuff to do with kinds is insensitive to pre/post Tc
84 unliftedTypeKind, liftedTypeKind, openTypeKind, mkArrowKind, mkArrowKinds,
85 isLiftedTypeKind, isUnliftedTypeKind, isOpenTypeKind,
86 isArgTypeKind, isSubKind, defaultKind,
88 Type, PredType(..), ThetaType,
89 mkForAllTy, mkForAllTys,
90 mkFunTy, mkFunTys, zipFunTys,
91 mkTyConApp, mkGenTyConApp, mkAppTy, mkAppTys, mkSynTy, applyTy, applyTys,
92 mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys,
95 TvSubst(..), -- Representation visible to a few friends
96 TvSubstEnv, emptyTvSubst,
97 mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst,
98 getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope,
99 extendTvSubst, extendTvSubstList, isInScope,
100 substTy, substTys, substTyWith, substTheta, substTyVar, substTyVarBndr,
102 isUnLiftedType, -- Source types are always lifted
103 isUnboxedTupleType, -- Ditto
106 tidyTopType, tidyType, tidyPred, tidyTypes, tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
107 tidyTyVarBndr, tidyOpenTyVar, tidyOpenTyVars, tidySkolemTyVar,
110 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
112 pprKind, pprParendKind,
113 pprType, pprParendType, pprTyThingCategory,
114 pprPred, pprTheta, pprThetaArrow, pprClassPred
118 #include "HsVersions.h"
121 import TypeRep ( Type(..), TyNote(..), funTyCon ) -- friend
123 import Type ( -- Re-exports
124 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred,
125 tyVarsOfTheta, Kind, PredType(..),
126 ThetaType, unliftedTypeKind,
127 liftedTypeKind, openTypeKind, mkArrowKind,
128 isLiftedTypeKind, isUnliftedTypeKind,
129 mkArrowKinds, mkForAllTy, mkForAllTys,
130 defaultKind, isArgTypeKind, isOpenTypeKind,
131 mkFunTy, mkFunTys, zipFunTys,
132 mkTyConApp, mkGenTyConApp, mkAppTy,
133 mkAppTys, mkSynTy, applyTy, applyTys,
134 mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy,
135 mkPredTys, isUnLiftedType,
136 isUnboxedTupleType, isPrimitiveType,
138 tidyTopType, tidyType, tidyPred, tidyTypes,
139 tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
140 tidyTyVarBndr, tidyOpenTyVar,
142 isSubKind, deShadowTy,
144 tcEqType, tcEqTypes, tcCmpType, tcCmpTypes,
145 tcEqPred, tcCmpPred, tcEqTypeX,
148 TvSubstEnv, emptyTvSubst,
149 mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst,
150 getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope,
151 extendTvSubst, extendTvSubstList, isInScope,
152 substTy, substTys, substTyWith, substTheta, substTyVar, substTyVarBndr,
155 pprKind, pprParendKind,
156 pprType, pprParendType, pprTyThingCategory,
157 pprPred, pprTheta, pprThetaArrow, pprClassPred
159 import TyCon ( TyCon, isUnLiftedTyCon, tyConUnique )
160 import DataCon ( DataCon )
161 import Class ( Class )
162 import Var ( TyVar, Id, isTcTyVar, mkTcTyVar, tyVarName, tyVarKind, tcTyVarDetails )
163 import ForeignCall ( Safety, playSafe, DNType(..) )
167 import CmdLineOpts ( DynFlags, DynFlag( Opt_GlasgowExts ), dopt )
168 import Name ( Name, NamedThing(..), mkInternalName, getSrcLoc )
170 import VarEnv ( TidyEnv )
171 import OccName ( OccName, mkDictOcc )
172 import PrelNames -- Lots (e.g. in isFFIArgumentTy)
173 import TysWiredIn ( unitTyCon, charTyCon, listTyCon )
174 import BasicTypes ( IPName(..), ipNameName )
175 import SrcLoc ( SrcLoc, SrcSpan )
176 import Util ( snocView )
177 import Maybes ( maybeToBool, expectJust )
183 %************************************************************************
187 %************************************************************************
189 The type checker divides the generic Type world into the
190 following more structured beasts:
192 sigma ::= forall tyvars. phi
193 -- A sigma type is a qualified type
195 -- Note that even if 'tyvars' is empty, theta
196 -- may not be: e.g. (?x::Int) => Int
198 -- Note that 'sigma' is in prenex form:
199 -- all the foralls are at the front.
200 -- A 'phi' type has no foralls to the right of
208 -- A 'tau' type has no quantification anywhere
209 -- Note that the args of a type constructor must be taus
211 | tycon tau_1 .. tau_n
215 -- In all cases, a (saturated) type synonym application is legal,
216 -- provided it expands to the required form.
219 type TcType = Type -- A TcType can have mutable type variables
220 -- Invariant on ForAllTy in TcTypes:
222 -- a cannot occur inside a MutTyVar in T; that is,
223 -- T is "flattened" before quantifying over a
225 type TcPredType = PredType
226 type TcThetaType = ThetaType
227 type TcSigmaType = TcType
228 type TcRhoType = TcType
229 type TcTauType = TcType
231 type TcTyVarSet = TyVarSet
233 type TcRef a = IORef a
234 data Expected ty = Infer (TcRef ty) -- The hole to fill in for type inference
235 | Check ty -- The type to check during type checking
239 %************************************************************************
241 \subsection{TyVarDetails}
243 %************************************************************************
245 TyVarDetails gives extra info about type variables, used during type
246 checking. It's attached to mutable type variables only.
247 It's knot-tied back to Var.lhs. There is no reason in principle
248 why Var.lhs shouldn't actually have the definition, but it "belongs" here.
251 type TcTyVar = TyVar -- Used only during type inference
253 -- A TyVarDetails is inside a TyVar
255 = SkolemTv SkolemInfo -- A skolem constant
256 | MetaTv (IORef MetaDetails) -- A meta type variable stands for a tau-type
259 = SigSkol Name -- Bound at a type signature
260 | ClsSkol Class -- Bound at a class decl
261 | InstSkol Id -- Bound at an instance decl
262 | PatSkol DataCon -- An existential type variable bound by a pattern for
263 SrcSpan -- a data constructor with an existential type. E.g.
264 -- data T = forall a. Eq a => MkT a
266 -- The pattern MkT x will allocate an existential type
268 | ArrowSkol SrcSpan -- An arrow form (see TcArrows)
270 | GenSkol [TcTyVar] -- Bound when doing a subsumption check for
271 TcType -- (forall tvs. ty)
275 = Flexi -- Flexi type variables unify to become
278 | Indirect TcType -- Type indirections, treated as wobbly
279 -- for the purpose of GADT unification.
281 tidySkolemTyVar :: TidyEnv -> TcTyVar -> (TidyEnv, TcTyVar)
282 -- Tidy the type inside a GenSkol, preparatory to printing it
283 tidySkolemTyVar env tv
284 = ASSERT( isSkolemTyVar tv )
285 (env1, mkTcTyVar (tyVarName tv) (tyVarKind tv) (SkolemTv info1))
287 (env1, info1) = case skolemTvInfo tv of
288 GenSkol tvs ty loc -> (env2, GenSkol tvs1 ty1 loc)
290 (env1, tvs1) = tidyOpenTyVars env tvs
291 (env2, ty1) = tidyOpenType env1 ty
294 pprSkolemTyVar :: TcTyVar -> SDoc
296 = ASSERT( isSkolemTyVar tv )
297 quotes (ppr tv) <+> ptext SLIT("is bound by") <+> ppr (skolemTvInfo tv)
299 instance Outputable SkolemInfo where
300 ppr (SigSkol id) = ptext SLIT("the type signature for") <+> quotes (ppr id)
301 ppr (ClsSkol cls) = ptext SLIT("the class declaration for") <+> quotes (ppr cls)
302 ppr (InstSkol df) = ptext SLIT("the instance declaration at") <+> ppr (getSrcLoc df)
303 ppr (ArrowSkol loc) = ptext SLIT("the arrow form at") <+> ppr loc
304 ppr (PatSkol dc loc) = sep [ptext SLIT("the pattern for") <+> quotes (ppr dc),
305 nest 2 (ptext SLIT("at") <+> ppr loc)]
306 ppr (GenSkol tvs ty loc) = sep [ptext SLIT("the polymorphic type")
307 <+> quotes (ppr (mkForAllTys tvs ty)),
308 nest 2 (ptext SLIT("at") <+> ppr loc)]
310 instance Outputable MetaDetails where
311 ppr Flexi = ptext SLIT("Flexi")
312 ppr (Indirect ty) = ptext SLIT("Indirect") <+> ppr ty
314 isImmutableTyVar, isSkolemTyVar, isExistentialTyVar, isMetaTyVar :: TyVar -> Bool
316 | isTcTyVar tv = isSkolemTyVar tv
320 = ASSERT( isTcTyVar tv )
321 case tcTyVarDetails tv of
325 isExistentialTyVar tv -- Existential type variable, bound by a pattern
326 = ASSERT( isTcTyVar tv )
327 case tcTyVarDetails tv of
328 SkolemTv (PatSkol _ _) -> True
332 = ASSERT( isTcTyVar tv )
333 case tcTyVarDetails tv of
337 skolemTvInfo :: TyVar -> SkolemInfo
339 = ASSERT( isTcTyVar tv )
340 case tcTyVarDetails tv of
341 SkolemTv info -> info
343 metaTvRef :: TyVar -> IORef MetaDetails
345 = ASSERT( isTcTyVar tv )
346 case tcTyVarDetails tv of
349 isFlexi, isIndirect :: MetaDetails -> Bool
351 isFlexi other = False
353 isIndirect (Indirect _) = True
354 isIndirect other = False
358 %************************************************************************
360 \subsection{Tau, sigma and rho}
362 %************************************************************************
365 mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkPhiTy theta tau)
367 mkPhiTy :: [PredType] -> Type -> Type
368 mkPhiTy theta ty = foldr (\p r -> FunTy (mkPredTy p) r) ty theta
371 @isTauTy@ tests for nested for-alls.
374 isTauTy :: Type -> Bool
375 isTauTy (TyVarTy v) = True
376 isTauTy (TyConApp _ tys) = all isTauTy tys
377 isTauTy (AppTy a b) = isTauTy a && isTauTy b
378 isTauTy (FunTy a b) = isTauTy a && isTauTy b
379 isTauTy (PredTy p) = True -- Don't look through source types
380 isTauTy (NoteTy _ ty) = isTauTy ty
381 isTauTy other = False
385 getDFunTyKey :: Type -> OccName -- Get some string from a type, to be used to
386 -- construct a dictionary function name
387 getDFunTyKey (TyVarTy tv) = getOccName tv
388 getDFunTyKey (TyConApp tc _) = getOccName tc
389 getDFunTyKey (AppTy fun _) = getDFunTyKey fun
390 getDFunTyKey (NoteTy _ t) = getDFunTyKey t
391 getDFunTyKey (FunTy arg _) = getOccName funTyCon
392 getDFunTyKey (ForAllTy _ t) = getDFunTyKey t
393 getDFunTyKey ty = pprPanic "getDFunTyKey" (pprType ty)
394 -- PredTy shouldn't happen
398 %************************************************************************
400 \subsection{Expanding and splitting}
402 %************************************************************************
404 These tcSplit functions are like their non-Tc analogues, but
405 a) they do not look through newtypes
406 b) they do not look through PredTys
407 c) [future] they ignore usage-type annotations
409 However, they are non-monadic and do not follow through mutable type
410 variables. It's up to you to make sure this doesn't matter.
413 tcSplitForAllTys :: Type -> ([TyVar], Type)
414 tcSplitForAllTys ty = split ty ty []
416 split orig_ty (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
417 split orig_ty (NoteTy n ty) tvs = split orig_ty ty tvs
418 split orig_ty t tvs = (reverse tvs, orig_ty)
420 tcIsForAllTy (ForAllTy tv ty) = True
421 tcIsForAllTy (NoteTy n ty) = tcIsForAllTy ty
422 tcIsForAllTy t = False
424 tcSplitPhiTy :: Type -> ([PredType], Type)
425 tcSplitPhiTy ty = split ty ty []
427 split orig_ty (FunTy arg res) ts = case tcSplitPredTy_maybe arg of
428 Just p -> split res res (p:ts)
429 Nothing -> (reverse ts, orig_ty)
430 split orig_ty (NoteTy n ty) ts = split orig_ty ty ts
431 split orig_ty ty ts = (reverse ts, orig_ty)
433 tcSplitSigmaTy ty = case tcSplitForAllTys ty of
434 (tvs, rho) -> case tcSplitPhiTy rho of
435 (theta, tau) -> (tvs, theta, tau)
437 tcTyConAppTyCon :: Type -> TyCon
438 tcTyConAppTyCon ty = fst (tcSplitTyConApp ty)
440 tcTyConAppArgs :: Type -> [Type]
441 tcTyConAppArgs ty = snd (tcSplitTyConApp ty)
443 tcSplitTyConApp :: Type -> (TyCon, [Type])
444 tcSplitTyConApp ty = case tcSplitTyConApp_maybe ty of
446 Nothing -> pprPanic "tcSplitTyConApp" (pprType ty)
448 tcSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
449 tcSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
450 tcSplitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
451 tcSplitTyConApp_maybe (NoteTy n ty) = tcSplitTyConApp_maybe ty
452 -- Newtypes are opaque, so they may be split
453 -- However, predicates are not treated
454 -- as tycon applications by the type checker
455 tcSplitTyConApp_maybe other = Nothing
457 tcSplitFunTys :: Type -> ([Type], Type)
458 tcSplitFunTys ty = case tcSplitFunTy_maybe ty of
460 Just (arg,res) -> (arg:args, res')
462 (args,res') = tcSplitFunTys res
464 tcSplitFunTy_maybe :: Type -> Maybe (Type, Type)
465 tcSplitFunTy_maybe (FunTy arg res) = Just (arg, res)
466 tcSplitFunTy_maybe (NoteTy n ty) = tcSplitFunTy_maybe ty
467 tcSplitFunTy_maybe other = Nothing
469 tcFunArgTy ty = case tcSplitFunTy_maybe ty of { Just (arg,res) -> arg }
470 tcFunResultTy ty = case tcSplitFunTy_maybe ty of { Just (arg,res) -> res }
473 tcSplitAppTy_maybe :: Type -> Maybe (Type, Type)
474 tcSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
475 tcSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
476 tcSplitAppTy_maybe (NoteTy n ty) = tcSplitAppTy_maybe ty
477 tcSplitAppTy_maybe (TyConApp tc tys) = case snocView tys of
478 Just (tys', ty') -> Just (TyConApp tc tys', ty')
480 tcSplitAppTy_maybe other = Nothing
482 tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
484 Nothing -> pprPanic "tcSplitAppTy" (pprType ty)
486 tcSplitAppTys :: Type -> (Type, [Type])
490 go ty args = case tcSplitAppTy_maybe ty of
491 Just (ty', arg) -> go ty' (arg:args)
494 tcGetTyVar_maybe :: Type -> Maybe TyVar
495 tcGetTyVar_maybe (TyVarTy tv) = Just tv
496 tcGetTyVar_maybe (NoteTy _ t) = tcGetTyVar_maybe t
497 tcGetTyVar_maybe other = Nothing
499 tcGetTyVar :: String -> Type -> TyVar
500 tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty)
502 tcIsTyVarTy :: Type -> Bool
503 tcIsTyVarTy ty = maybeToBool (tcGetTyVar_maybe ty)
505 tcSplitDFunTy :: Type -> ([TyVar], [PredType], Class, [Type])
506 -- Split the type of a dictionary function
508 = case tcSplitSigmaTy ty of { (tvs, theta, tau) ->
509 case tcSplitDFunHead tau of { (clas, tys) ->
510 (tvs, theta, clas, tys) }}
512 tcSplitDFunHead :: Type -> (Class, [Type])
514 = case tcSplitPredTy_maybe tau of
515 Just (ClassP clas tys) -> (clas, tys)
520 %************************************************************************
522 \subsection{Predicate types}
524 %************************************************************************
527 tcSplitPredTy_maybe :: Type -> Maybe PredType
528 -- Returns Just for predicates only
529 tcSplitPredTy_maybe (NoteTy _ ty) = tcSplitPredTy_maybe ty
530 tcSplitPredTy_maybe (PredTy p) = Just p
531 tcSplitPredTy_maybe other = Nothing
533 predTyUnique :: PredType -> Unique
534 predTyUnique (IParam n _) = getUnique (ipNameName n)
535 predTyUnique (ClassP clas tys) = getUnique clas
537 mkPredName :: Unique -> SrcLoc -> PredType -> Name
538 mkPredName uniq loc (ClassP cls tys) = mkInternalName uniq (mkDictOcc (getOccName cls)) loc
539 mkPredName uniq loc (IParam ip ty) = mkInternalName uniq (getOccName (ipNameName ip)) loc
543 --------------------- Dictionary types ---------------------------------
546 mkClassPred clas tys = ClassP clas tys
548 isClassPred :: PredType -> Bool
549 isClassPred (ClassP clas tys) = True
550 isClassPred other = False
552 isTyVarClassPred (ClassP clas tys) = all tcIsTyVarTy tys
553 isTyVarClassPred other = False
555 getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
556 getClassPredTys_maybe (ClassP clas tys) = Just (clas, tys)
557 getClassPredTys_maybe _ = Nothing
559 getClassPredTys :: PredType -> (Class, [Type])
560 getClassPredTys (ClassP clas tys) = (clas, tys)
562 mkDictTy :: Class -> [Type] -> Type
563 mkDictTy clas tys = mkPredTy (ClassP clas tys)
565 isDictTy :: Type -> Bool
566 isDictTy (PredTy p) = isClassPred p
567 isDictTy (NoteTy _ ty) = isDictTy ty
568 isDictTy other = False
571 --------------------- Implicit parameters ---------------------------------
574 isIPPred :: PredType -> Bool
575 isIPPred (IParam _ _) = True
576 isIPPred other = False
578 isInheritablePred :: PredType -> Bool
579 -- Can be inherited by a context. For example, consider
580 -- f x = let g y = (?v, y+x)
581 -- in (g 3 with ?v = 8,
583 -- The point is that g's type must be quantifed over ?v:
584 -- g :: (?v :: a) => a -> a
585 -- but it doesn't need to be quantified over the Num a dictionary
586 -- which can be free in g's rhs, and shared by both calls to g
587 isInheritablePred (ClassP _ _) = True
588 isInheritablePred other = False
590 isLinearPred :: TcPredType -> Bool
591 isLinearPred (IParam (Linear n) _) = True
592 isLinearPred other = False
596 %************************************************************************
598 \subsection{Predicates}
600 %************************************************************************
602 isSigmaTy returns true of any qualified type. It doesn't *necessarily* have
604 f :: (?x::Int) => Int -> Int
607 isSigmaTy :: Type -> Bool
608 isSigmaTy (ForAllTy tyvar ty) = True
609 isSigmaTy (FunTy a b) = isPredTy a
610 isSigmaTy (NoteTy n ty) = isSigmaTy ty
613 isOverloadedTy :: Type -> Bool
614 isOverloadedTy (ForAllTy tyvar ty) = isOverloadedTy ty
615 isOverloadedTy (FunTy a b) = isPredTy a
616 isOverloadedTy (NoteTy n ty) = isOverloadedTy ty
617 isOverloadedTy _ = False
619 isPredTy :: Type -> Bool -- Belongs in TcType because it does
620 -- not look through newtypes, or predtypes (of course)
621 isPredTy (NoteTy _ ty) = isPredTy ty
622 isPredTy (PredTy sty) = True
627 isFloatTy = is_tc floatTyConKey
628 isDoubleTy = is_tc doubleTyConKey
629 isIntegerTy = is_tc integerTyConKey
630 isIntTy = is_tc intTyConKey
631 isAddrTy = is_tc addrTyConKey
632 isBoolTy = is_tc boolTyConKey
633 isUnitTy = is_tc unitTyConKey
635 is_tc :: Unique -> Type -> Bool
636 -- Newtypes are opaque to this
637 is_tc uniq ty = case tcSplitTyConApp_maybe ty of
638 Just (tc, _) -> uniq == getUnique tc
645 %************************************************************************
649 %************************************************************************
651 hoistForAllTys is used for user-written type signatures only
652 We want to 'look through' type synonyms when doing this
653 so it's better done on the Type than the HsType
655 It moves all the foralls and constraints to the top
656 e.g. T -> forall a. a ==> forall a. T -> a
657 T -> (?x::Int) -> Int ==> (?x::Int) -> T -> Int
659 Also: it eliminates duplicate constraints. These can show up
660 when hoisting constraints, notably implicit parameters.
662 It tries hard to retain type synonyms if hoisting does not break one
663 up. Not only does this improve error messages, but there's a tricky
664 interaction with Haskell 98. H98 requires no unsaturated type
665 synonyms, which is checked by checkValidType. This runs after
666 hoisting, so we don't want hoisting to remove the SynNotes! (We can't
667 run validity checking before hoisting because in mutually-recursive
668 type definitions we postpone validity checking until after the knot is
672 hoistForAllTys :: Type -> Type
675 -- Running over ty with an empty substitution gives it the
676 -- no-shadowing property. This is important. For example:
677 -- type Foo r = forall a. a -> r
678 -- foo :: Foo (Foo ())
679 -- Here the hoisting should give
680 -- foo :: forall a a1. a -> a1 -> ()
682 -- What about type vars that are lexically in scope in the envt?
683 -- We simply rely on them having a different unique to any
684 -- binder in 'ty'. Otherwise we'd have to slurp the in-scope-tyvars
685 -- out of the envt, which is boring and (I think) not necessary.
688 go (TyVarTy tv) = TyVarTy tv
689 go (TyConApp tc tys) = TyConApp tc (map go tys)
690 go (PredTy pred) = PredTy pred -- No nested foralls
691 go (NoteTy (SynNote ty1) ty2) = NoteTy (SynNote (go ty1)) (go ty2)
692 go (NoteTy (FTVNote _) ty2) = go ty2 -- Discard the free tyvar note
693 go (FunTy arg res) = mk_fun_ty (go arg) (go res)
694 go (AppTy fun arg) = AppTy (go fun) (go arg)
695 go (ForAllTy tv ty) = ForAllTy tv (go ty)
697 -- mk_fun_ty does all the work.
698 -- It's building t1 -> t2:
699 -- if t2 is a for-all type, push t1 inside it
700 -- if t2 is (pred -> t3), check for duplicates
702 | not (isSigmaTy ty2) -- No forall's, or context =>
704 | PredTy p1 <- ty1 -- ty1 is a predicate
705 = if p1 `elem` theta then -- so check for duplicates
708 mkSigmaTy tvs (p1:theta) tau
710 = mkSigmaTy tvs theta (FunTy ty1 tau)
712 (tvs, theta, tau) = tcSplitSigmaTy ty2
716 %************************************************************************
720 %************************************************************************
723 deNoteType :: Type -> Type
724 -- Remove synonyms, but not predicate types
725 deNoteType ty@(TyVarTy tyvar) = ty
726 deNoteType (TyConApp tycon tys) = TyConApp tycon (map deNoteType tys)
727 deNoteType (PredTy p) = PredTy (deNotePredType p)
728 deNoteType (NoteTy _ ty) = deNoteType ty
729 deNoteType (AppTy fun arg) = AppTy (deNoteType fun) (deNoteType arg)
730 deNoteType (FunTy fun arg) = FunTy (deNoteType fun) (deNoteType arg)
731 deNoteType (ForAllTy tv ty) = ForAllTy tv (deNoteType ty)
733 deNotePredType :: PredType -> PredType
734 deNotePredType (ClassP c tys) = ClassP c (map deNoteType tys)
735 deNotePredType (IParam n ty) = IParam n (deNoteType ty)
738 Find the free tycons and classes of a type. This is used in the front
742 tyClsNamesOfType :: Type -> NameSet
743 tyClsNamesOfType (TyVarTy tv) = emptyNameSet
744 tyClsNamesOfType (TyConApp tycon tys) = unitNameSet (getName tycon) `unionNameSets` tyClsNamesOfTypes tys
745 tyClsNamesOfType (NoteTy (SynNote ty1) ty2) = tyClsNamesOfType ty1
746 tyClsNamesOfType (NoteTy other_note ty2) = tyClsNamesOfType ty2
747 tyClsNamesOfType (PredTy (IParam n ty)) = tyClsNamesOfType ty
748 tyClsNamesOfType (PredTy (ClassP cl tys)) = unitNameSet (getName cl) `unionNameSets` tyClsNamesOfTypes tys
749 tyClsNamesOfType (FunTy arg res) = tyClsNamesOfType arg `unionNameSets` tyClsNamesOfType res
750 tyClsNamesOfType (AppTy fun arg) = tyClsNamesOfType fun `unionNameSets` tyClsNamesOfType arg
751 tyClsNamesOfType (ForAllTy tyvar ty) = tyClsNamesOfType ty
753 tyClsNamesOfTypes tys = foldr (unionNameSets . tyClsNamesOfType) emptyNameSet tys
755 tyClsNamesOfDFunHead :: Type -> NameSet
756 -- Find the free type constructors and classes
757 -- of the head of the dfun instance type
758 -- The 'dfun_head_type' is because of
759 -- instance Foo a => Baz T where ...
760 -- The decl is an orphan if Baz and T are both not locally defined,
761 -- even if Foo *is* locally defined
762 tyClsNamesOfDFunHead dfun_ty
763 = case tcSplitSigmaTy dfun_ty of
764 (tvs,_,head_ty) -> tyClsNamesOfType head_ty
766 classesOfTheta :: ThetaType -> [Class]
767 -- Looks just for ClassP things; maybe it should check
768 classesOfTheta preds = [ c | ClassP c _ <- preds ]
772 %************************************************************************
774 \subsection[TysWiredIn-ext-type]{External types}
776 %************************************************************************
778 The compiler's foreign function interface supports the passing of a
779 restricted set of types as arguments and results (the restricting factor
783 isFFITy :: Type -> Bool
784 -- True for any TyCon that can possibly be an arg or result of an FFI call
785 isFFITy ty = checkRepTyCon legalFFITyCon ty
787 isFFIArgumentTy :: DynFlags -> Safety -> Type -> Bool
788 -- Checks for valid argument type for a 'foreign import'
789 isFFIArgumentTy dflags safety ty
790 = checkRepTyCon (legalOutgoingTyCon dflags safety) ty
792 isFFIExternalTy :: Type -> Bool
793 -- Types that are allowed as arguments of a 'foreign export'
794 isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty
796 isFFIImportResultTy :: DynFlags -> Type -> Bool
797 isFFIImportResultTy dflags ty
798 = checkRepTyCon (legalFIResultTyCon dflags) ty
800 isFFIExportResultTy :: Type -> Bool
801 isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty
803 isFFIDynArgumentTy :: Type -> Bool
804 -- The argument type of a foreign import dynamic must be Ptr, FunPtr, Addr,
805 -- or a newtype of either.
806 isFFIDynArgumentTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey, addrTyConKey]
808 isFFIDynResultTy :: Type -> Bool
809 -- The result type of a foreign export dynamic must be Ptr, FunPtr, Addr,
810 -- or a newtype of either.
811 isFFIDynResultTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey, addrTyConKey]
813 isFFILabelTy :: Type -> Bool
814 -- The type of a foreign label must be Ptr, FunPtr, Addr,
815 -- or a newtype of either.
816 isFFILabelTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey, addrTyConKey]
818 isFFIDotnetTy :: DynFlags -> Type -> Bool
819 isFFIDotnetTy dflags ty
820 = checkRepTyCon (\ tc -> not (isByteArrayLikeTyCon tc) &&
821 (legalFIResultTyCon dflags tc ||
822 isFFIDotnetObjTy ty || isStringTy ty)) ty
824 -- Support String as an argument or result from a .NET FFI call.
826 case tcSplitTyConApp_maybe (repType ty) of
829 case tcSplitTyConApp_maybe (repType arg_ty) of
830 Just (cc,[]) -> cc == charTyCon
834 -- Support String as an argument or result from a .NET FFI call.
835 isFFIDotnetObjTy ty =
837 (_, t_ty) = tcSplitForAllTys ty
839 case tcSplitTyConApp_maybe (repType t_ty) of
840 Just (tc, [arg_ty]) | getName tc == objectTyConName -> True
843 toDNType :: Type -> DNType
845 | isStringTy ty = DNString
846 | isFFIDotnetObjTy ty = DNObject
847 | Just (tc,argTys) <- tcSplitTyConApp_maybe ty =
848 case lookup (getUnique tc) dn_assoc of
851 | tc `hasKey` ioTyConKey -> toDNType (head argTys)
852 | otherwise -> pprPanic ("toDNType: unsupported .NET type") (pprType ty <+> parens (hcat (map pprType argTys)) <+> ppr tc)
854 dn_assoc :: [ (Unique, DNType) ]
855 dn_assoc = [ (unitTyConKey, DNUnit)
856 , (intTyConKey, DNInt)
857 , (int8TyConKey, DNInt8)
858 , (int16TyConKey, DNInt16)
859 , (int32TyConKey, DNInt32)
860 , (int64TyConKey, DNInt64)
861 , (wordTyConKey, DNInt)
862 , (word8TyConKey, DNWord8)
863 , (word16TyConKey, DNWord16)
864 , (word32TyConKey, DNWord32)
865 , (word64TyConKey, DNWord64)
866 , (floatTyConKey, DNFloat)
867 , (doubleTyConKey, DNDouble)
868 , (addrTyConKey, DNPtr)
869 , (ptrTyConKey, DNPtr)
870 , (funPtrTyConKey, DNPtr)
871 , (charTyConKey, DNChar)
872 , (boolTyConKey, DNBool)
875 checkRepTyCon :: (TyCon -> Bool) -> Type -> Bool
876 -- Look through newtypes
877 -- Non-recursive ones are transparent to splitTyConApp,
878 -- but recursive ones aren't. Manuel had:
879 -- newtype T = MkT (Ptr T)
880 -- and wanted it to work...
881 checkRepTyCon check_tc ty
882 | Just (tc,_) <- splitTyConApp_maybe (repType ty) = check_tc tc
885 checkRepTyConKey :: [Unique] -> Type -> Bool
886 -- Like checkRepTyCon, but just looks at the TyCon key
887 checkRepTyConKey keys
888 = checkRepTyCon (\tc -> tyConUnique tc `elem` keys)
891 ----------------------------------------------
892 These chaps do the work; they are not exported
893 ----------------------------------------------
896 legalFEArgTyCon :: TyCon -> Bool
897 -- It's illegal to return foreign objects and (mutable)
898 -- bytearrays from a _ccall_ / foreign declaration
899 -- (or be passed them as arguments in foreign exported functions).
901 | isByteArrayLikeTyCon tc
903 -- It's also illegal to make foreign exports that take unboxed
904 -- arguments. The RTS API currently can't invoke such things. --SDM 7/2000
906 = boxedMarshalableTyCon tc
908 legalFIResultTyCon :: DynFlags -> TyCon -> Bool
909 legalFIResultTyCon dflags tc
910 | isByteArrayLikeTyCon tc = False
911 | tc == unitTyCon = True
912 | otherwise = marshalableTyCon dflags tc
914 legalFEResultTyCon :: TyCon -> Bool
915 legalFEResultTyCon tc
916 | isByteArrayLikeTyCon tc = False
917 | tc == unitTyCon = True
918 | otherwise = boxedMarshalableTyCon tc
920 legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Bool
921 -- Checks validity of types going from Haskell -> external world
922 legalOutgoingTyCon dflags safety tc
923 | playSafe safety && isByteArrayLikeTyCon tc
926 = marshalableTyCon dflags tc
928 legalFFITyCon :: TyCon -> Bool
929 -- True for any TyCon that can possibly be an arg or result of an FFI call
931 = isUnLiftedTyCon tc || boxedMarshalableTyCon tc || tc == unitTyCon
933 marshalableTyCon dflags tc
934 = (dopt Opt_GlasgowExts dflags && isUnLiftedTyCon tc)
935 || boxedMarshalableTyCon tc
937 boxedMarshalableTyCon tc
938 = getUnique tc `elem` [ intTyConKey, int8TyConKey, int16TyConKey
939 , int32TyConKey, int64TyConKey
940 , wordTyConKey, word8TyConKey, word16TyConKey
941 , word32TyConKey, word64TyConKey
942 , floatTyConKey, doubleTyConKey
943 , addrTyConKey, ptrTyConKey, funPtrTyConKey
946 , byteArrayTyConKey, mutableByteArrayTyConKey
950 isByteArrayLikeTyCon :: TyCon -> Bool
951 isByteArrayLikeTyCon tc =
952 getUnique tc `elem` [byteArrayTyConKey, mutableByteArrayTyConKey]