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, TcPhiType, TcTauType, TcPredType, TcThetaType,
21 TcTyVar, TcTyVarSet, TcKind,
23 --------------------------------
25 TyVarDetails(..), isUserTyVar, isSkolemTyVar, isHoleTyVar,
28 --------------------------------
32 --------------------------------
34 -- These are important because they do not look through newtypes
35 tcSplitForAllTys, tcSplitRhoTy,
36 tcSplitFunTy_maybe, tcSplitFunTys, tcFunArgTy, tcFunResultTy,
37 tcSplitTyConApp, tcSplitTyConApp_maybe, tcTyConAppTyCon, tcTyConAppArgs,
38 tcSplitAppTy_maybe, tcSplitAppTy, tcSplitSigmaTy,
39 tcSplitMethodTy, tcGetTyVar_maybe, tcGetTyVar,
41 ---------------------------------
43 -- Again, newtypes are opaque
44 tcEqType, tcEqPred, tcCmpType, tcCmpTypes, tcCmpPred,
45 isSigmaTy, isOverloadedTy,
46 isDoubleTy, isFloatTy, isIntTy,
47 isIntegerTy, isAddrTy, isBoolTy, isUnitTy, isForeignPtrTy,
48 isTauTy, tcIsTyVarTy, tcIsForAllTy,
50 ---------------------------------
51 -- Misc type manipulators
52 hoistForAllTys, deNoteType,
53 namesOfType, namesOfDFunHead,
56 ---------------------------------
58 PredType, getClassPredTys_maybe, getClassPredTys,
59 isPredTy, isClassPred, isTyVarClassPred, predHasFDs,
60 mkDictTy, tcSplitPredTy_maybe, predTyUnique,
61 isDictTy, tcSplitDFunTy, predTyUnique,
62 mkClassPred, inheritablePred, isIPPred, mkPredName,
64 ---------------------------------
65 -- Foreign import and export
66 isFFIArgumentTy, -- :: DynFlags -> Safety -> Type -> Bool
67 isFFIImportResultTy, -- :: DynFlags -> Type -> Bool
68 isFFIExportResultTy, -- :: Type -> Bool
69 isFFIExternalTy, -- :: Type -> Bool
70 isFFIDynArgumentTy, -- :: Type -> Bool
71 isFFIDynResultTy, -- :: Type -> Bool
72 isFFILabelTy, -- :: Type -> Bool
74 ---------------------------------
75 -- Unifier and matcher
76 unifyTysX, unifyTyListsX, unifyExtendTysX,
78 matchTy, matchTys, match,
80 --------------------------------
81 -- Rexported from Type
82 Kind, -- Stuff to do with kinds is insensitive to pre/post Tc
83 unliftedTypeKind, liftedTypeKind, openTypeKind, mkArrowKind, mkArrowKinds,
84 superBoxity, liftedBoxity, hasMoreBoxityInfo, defaultKind, superKind,
87 IPName, ipNameName, mapIPName,
89 Type, SourceType(..), PredType, ThetaType,
90 mkForAllTy, mkForAllTys,
91 mkFunTy, mkFunTys, zipFunTys,
92 mkTyConApp, mkAppTy, mkAppTys, mkSynTy, applyTy, applyTys,
93 mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys,
95 isUnLiftedType, -- Source types are always lifted
96 isUnboxedTupleType, -- Ditto
99 tidyTopType, tidyType, tidyPred, tidyTypes, tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
100 tidyTyVarBndr, tidyOpenTyVar, tidyOpenTyVars,
101 typeKind, eqKind, eqUsage,
103 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta
106 #include "HsVersions.h"
109 import {-# SOURCE #-} PprType( pprType )
112 import TypeRep ( Type(..), TyNote(..), funTyCon ) -- friend
113 import Type ( mkUTyM, unUTy ) -- Used locally
115 import Type ( -- Re-exports
116 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
117 IPName, Kind, Type, SourceType(..), PredType, ThetaType,
118 unliftedTypeKind, liftedTypeKind, openTypeKind, mkArrowKind, mkArrowKinds,
119 mkForAllTy, mkForAllTys, defaultKind, isTypeKind,
120 mkFunTy, mkFunTys, zipFunTys,
121 mkTyConApp, mkAppTy, mkAppTys, mkSynTy, applyTy, applyTys,
122 mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys,
123 isUnLiftedType, isUnboxedTupleType, isPrimitiveType,
124 splitNewType_maybe, splitTyConApp_maybe,
125 tidyTopType, tidyType, tidyPred, tidyTypes, tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
126 tidyTyVarBndr, tidyOpenTyVar, tidyOpenTyVars, eqKind, eqUsage,
127 hasMoreBoxityInfo, liftedBoxity, superBoxity, typeKind, superKind,
128 ipNameName, mapIPName
130 import TyCon ( TyCon, isUnLiftedTyCon )
131 import Class ( classHasFDs, Class )
132 import Var ( TyVar, tyVarKind, isMutTyVar, mutTyVarDetails )
133 import ForeignCall ( Safety, playSafe )
138 import CmdLineOpts ( DynFlags, DynFlag( Opt_GlasgowExts ), dopt )
139 import Name ( Name, NamedThing(..), mkLocalName, getSrcLoc )
140 import OccName ( OccName, mkDictOcc )
142 import PrelNames -- Lots (e.g. in isFFIArgumentTy)
143 import TysWiredIn ( ptrTyCon, funPtrTyCon, addrTyCon, unitTyCon )
144 import Unique ( Unique, Uniquable(..) )
145 import SrcLoc ( SrcLoc )
146 import Util ( cmpList, thenCmp, equalLength )
147 import Maybes ( maybeToBool, expectJust )
152 %************************************************************************
156 %************************************************************************
158 The type checker divides the generic Type world into the
159 following more structured beasts:
161 sigma ::= forall tyvars. theta => phi
162 -- A sigma type is a qualified type
164 -- Note that even if 'tyvars' is empty, theta
165 -- may not be: e.g. (?x::Int) => Int
167 -- Note that 'sigma' is in prenex form:
168 -- all the foralls are at the front.
169 -- A 'phi' type has no foralls to the right of
175 -- A 'tau' type has no quantification anywhere
176 -- Note that the args of a type constructor must be taus
178 | tycon tau_1 .. tau_n
182 -- In all cases, a (saturated) type synonym application is legal,
183 -- provided it expands to the required form.
187 type SigmaType = Type
193 type TcTyVar = TyVar -- Might be a mutable tyvar
194 type TcTyVarSet = TyVarSet
196 type TcType = Type -- A TcType can have mutable type variables
197 -- Invariant on ForAllTy in TcTypes:
199 -- a cannot occur inside a MutTyVar in T; that is,
200 -- T is "flattened" before quantifying over a
202 type TcPredType = PredType
203 type TcThetaType = ThetaType
204 type TcSigmaType = TcType
205 type TcPhiType = TcType
206 type TcTauType = TcType
211 %************************************************************************
213 \subsection{TyVarDetails}
215 %************************************************************************
217 TyVarDetails gives extra info about type variables, used during type
218 checking. It's attached to mutable type variables only.
219 It's knot-tied back to Var.lhs. There is no reason in principle
220 why Var.lhs shouldn't actually have the definition, but it "belongs" here.
224 = HoleTv -- Used *only* by the type checker when passing in a type
225 -- variable that should be side-effected to the result type.
226 -- Always has kind openTypeKind.
227 -- Never appears in types
229 | SigTv -- Introduced when instantiating a type signature,
230 -- prior to checking that the defn of a fn does
231 -- have the expected type. Should not be instantiated.
233 -- f :: forall a. a -> a
235 -- When checking e, with expected type (a->a), we
236 -- should not instantiate a
238 | ClsTv -- Scoped type variable introduced by a class decl
239 -- class C a where ...
241 | InstTv -- Ditto, but instance decl
243 | PatSigTv -- Scoped type variable, introduced by a pattern
247 | VanillaTv -- Everything else
249 isUserTyVar :: TcTyVar -> Bool -- Avoid unifying these if possible
250 isUserTyVar tv = case mutTyVarDetails tv of
254 isSkolemTyVar :: TcTyVar -> Bool
255 isSkolemTyVar tv = case mutTyVarDetails tv of
259 isHoleTyVar :: TcTyVar -> Bool
260 -- NB: the hole might be filled in by now, and this
261 -- function does not check for that
262 isHoleTyVar tv = ASSERT( isMutTyVar tv )
263 case mutTyVarDetails tv of
267 tyVarBindingInfo :: TyVar -> SDoc -- Used in checkSigTyVars
270 = sep [ptext SLIT("is bound by the") <+> details (mutTyVarDetails tv),
271 ptext SLIT("at") <+> ppr (getSrcLoc tv)]
275 details SigTv = ptext SLIT("type signature")
276 details ClsTv = ptext SLIT("class declaration")
277 details InstTv = ptext SLIT("instance declaration")
278 details PatSigTv = ptext SLIT("pattern type signature")
279 details HoleTv = ptext SLIT("//hole//") -- Should not happen
280 details VanillaTv = ptext SLIT("//vanilla//") -- Ditto
284 %************************************************************************
286 \subsection{Tau, sigma and rho}
288 %************************************************************************
291 mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkRhoTy theta tau)
293 mkRhoTy :: [SourceType] -> Type -> Type
294 mkRhoTy theta ty = UASSERT2( not (isUTy ty), pprType ty )
295 foldr (\p r -> FunTy (mkUTyM (mkPredTy p)) (mkUTyM r)) ty theta
300 @isTauTy@ tests for nested for-alls.
303 isTauTy :: Type -> Bool
304 isTauTy (TyVarTy v) = True
305 isTauTy (TyConApp _ tys) = all isTauTy tys
306 isTauTy (AppTy a b) = isTauTy a && isTauTy b
307 isTauTy (FunTy a b) = isTauTy a && isTauTy b
308 isTauTy (SourceTy p) = True -- Don't look through source types
309 isTauTy (NoteTy _ ty) = isTauTy ty
310 isTauTy (UsageTy _ ty) = isTauTy ty
311 isTauTy other = False
315 getDFunTyKey :: Type -> OccName -- Get some string from a type, to be used to
316 -- construct a dictionary function name
317 getDFunTyKey (TyVarTy tv) = getOccName tv
318 getDFunTyKey (TyConApp tc _) = getOccName tc
319 getDFunTyKey (AppTy fun _) = getDFunTyKey fun
320 getDFunTyKey (NoteTy _ t) = getDFunTyKey t
321 getDFunTyKey (FunTy arg _) = getOccName funTyCon
322 getDFunTyKey (ForAllTy _ t) = getDFunTyKey t
323 getDFunTyKey (UsageTy _ t) = getDFunTyKey t
324 getDFunTyKey (SourceTy (NType tc _)) = getOccName tc -- Newtypes are quite reasonable
325 getDFunTyKey ty = pprPanic "getDFunTyKey" (pprType ty)
326 -- SourceTy shouldn't happen
330 %************************************************************************
332 \subsection{Expanding and splitting}
334 %************************************************************************
336 These tcSplit functions are like their non-Tc analogues, but
337 a) they do not look through newtypes
338 b) they do not look through PredTys
339 c) [future] they ignore usage-type annotations
341 However, they are non-monadic and do not follow through mutable type
342 variables. It's up to you to make sure this doesn't matter.
345 tcSplitForAllTys :: Type -> ([TyVar], Type)
346 tcSplitForAllTys ty = split ty ty []
348 split orig_ty (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
349 split orig_ty (NoteTy n ty) tvs = split orig_ty ty tvs
350 split orig_ty (UsageTy _ ty) tvs = split orig_ty ty tvs
351 split orig_ty t tvs = (reverse tvs, orig_ty)
353 tcIsForAllTy (ForAllTy tv ty) = True
354 tcIsForAllTy (NoteTy n ty) = tcIsForAllTy ty
355 tcIsForAllTy (UsageTy n ty) = tcIsForAllTy ty
356 tcIsForAllTy t = False
358 tcSplitRhoTy :: Type -> ([PredType], Type)
359 tcSplitRhoTy ty = split ty ty []
361 split orig_ty (FunTy arg res) ts = case tcSplitPredTy_maybe arg of
362 Just p -> split res res (p:ts)
363 Nothing -> (reverse ts, orig_ty)
364 split orig_ty (NoteTy n ty) ts = split orig_ty ty ts
365 split orig_ty (UsageTy _ ty) ts = split orig_ty ty ts
366 split orig_ty ty ts = (reverse ts, orig_ty)
368 tcSplitSigmaTy ty = case tcSplitForAllTys ty of
369 (tvs, rho) -> case tcSplitRhoTy rho of
370 (theta, tau) -> (tvs, theta, tau)
372 tcTyConAppTyCon :: Type -> TyCon
373 tcTyConAppTyCon ty = fst (tcSplitTyConApp ty)
375 tcTyConAppArgs :: Type -> [Type]
376 tcTyConAppArgs ty = snd (tcSplitTyConApp ty)
378 tcSplitTyConApp :: Type -> (TyCon, [Type])
379 tcSplitTyConApp ty = case tcSplitTyConApp_maybe ty of
381 Nothing -> pprPanic "tcSplitTyConApp" (pprType ty)
383 tcSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
384 -- Newtypes are opaque, so they may be split
385 tcSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
386 tcSplitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [unUTy arg,unUTy res])
387 tcSplitTyConApp_maybe (NoteTy n ty) = tcSplitTyConApp_maybe ty
388 tcSplitTyConApp_maybe (UsageTy _ ty) = tcSplitTyConApp_maybe ty
389 tcSplitTyConApp_maybe (SourceTy (NType tc tys)) = Just (tc,tys)
390 -- However, predicates are not treated
391 -- as tycon applications by the type checker
392 tcSplitTyConApp_maybe other = Nothing
394 tcSplitFunTys :: Type -> ([Type], Type)
395 tcSplitFunTys ty = case tcSplitFunTy_maybe ty of
397 Just (arg,res) -> (arg:args, res')
399 (args,res') = tcSplitFunTys res
401 tcSplitFunTy_maybe :: Type -> Maybe (Type, Type)
402 tcSplitFunTy_maybe (FunTy arg res) = Just (arg, res)
403 tcSplitFunTy_maybe (NoteTy n ty) = tcSplitFunTy_maybe ty
404 tcSplitFunTy_maybe (UsageTy _ ty) = tcSplitFunTy_maybe ty
405 tcSplitFunTy_maybe other = Nothing
407 tcFunArgTy ty = case tcSplitFunTy_maybe ty of { Just (arg,res) -> arg }
408 tcFunResultTy ty = case tcSplitFunTy_maybe ty of { Just (arg,res) -> res }
411 tcSplitAppTy_maybe :: Type -> Maybe (Type, Type)
412 tcSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [unUTy ty1], unUTy ty2)
413 tcSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
414 tcSplitAppTy_maybe (NoteTy n ty) = tcSplitAppTy_maybe ty
415 tcSplitAppTy_maybe (UsageTy _ ty) = tcSplitAppTy_maybe ty
416 tcSplitAppTy_maybe (SourceTy (NType tc tys)) = tc_split_app tc tys
417 --- Don't forget that newtype!
418 tcSplitAppTy_maybe (TyConApp tc tys) = tc_split_app tc tys
419 tcSplitAppTy_maybe other = Nothing
421 tc_split_app tc [] = Nothing
422 tc_split_app tc tys = split tys []
424 split [ty2] acc = Just (TyConApp tc (reverse acc), ty2)
425 split (ty:tys) acc = split tys (ty:acc)
427 tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
429 Nothing -> pprPanic "tcSplitAppTy" (pprType ty)
431 tcGetTyVar_maybe :: Type -> Maybe TyVar
432 tcGetTyVar_maybe (TyVarTy tv) = Just tv
433 tcGetTyVar_maybe (NoteTy _ t) = tcGetTyVar_maybe t
434 tcGetTyVar_maybe ty@(UsageTy _ _) = pprPanic "tcGetTyVar_maybe: UTy:" (pprType ty)
435 tcGetTyVar_maybe other = Nothing
437 tcGetTyVar :: String -> Type -> TyVar
438 tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty)
440 tcIsTyVarTy :: Type -> Bool
441 tcIsTyVarTy ty = maybeToBool (tcGetTyVar_maybe ty)
444 The type of a method for class C is always of the form:
445 Forall a1..an. C a1..an => sig_ty
446 where sig_ty is the type given by the method's signature, and thus in general
447 is a ForallTy. At the point that splitMethodTy is called, it is expected
448 that the outer Forall has already been stripped off. splitMethodTy then
449 returns (C a1..an, sig_ty') where sig_ty' is sig_ty with any Notes or
453 tcSplitMethodTy :: Type -> (PredType, Type)
454 tcSplitMethodTy ty = split ty
456 split (FunTy arg res) = case tcSplitPredTy_maybe arg of
458 Nothing -> panic "splitMethodTy"
459 split (NoteTy n ty) = split ty
460 split (UsageTy _ ty) = split ty
461 split _ = panic "splitMethodTy"
463 tcSplitDFunTy :: Type -> ([TyVar], [SourceType], Class, [Type])
464 -- Split the type of a dictionary function
466 = case tcSplitSigmaTy ty of { (tvs, theta, tau) ->
467 case tcSplitPredTy_maybe tau of { Just (ClassP clas tys) ->
468 (tvs, theta, clas, tys) }}
472 %************************************************************************
474 \subsection{Predicate types}
476 %************************************************************************
478 "Predicates" are particular source types, namelyClassP or IParams
481 isPred :: SourceType -> Bool
482 isPred (ClassP _ _) = True
483 isPred (IParam _ _) = True
484 isPred (NType _ _) = False
486 isPredTy :: Type -> Bool
487 isPredTy (NoteTy _ ty) = isPredTy ty
488 isPredTy (UsageTy _ ty) = isPredTy ty
489 isPredTy (SourceTy sty) = isPred sty
492 tcSplitPredTy_maybe :: Type -> Maybe PredType
493 -- Returns Just for predicates only
494 tcSplitPredTy_maybe (NoteTy _ ty) = tcSplitPredTy_maybe ty
495 tcSplitPredTy_maybe (UsageTy _ ty) = tcSplitPredTy_maybe ty
496 tcSplitPredTy_maybe (SourceTy p) | isPred p = Just p
497 tcSplitPredTy_maybe other = Nothing
499 predTyUnique :: PredType -> Unique
500 predTyUnique (IParam n _) = getUnique (ipNameName n)
501 predTyUnique (ClassP clas tys) = getUnique clas
503 predHasFDs :: PredType -> Bool
504 -- True if the predicate has functional depenencies;
505 -- I.e. should participate in improvement
506 predHasFDs (IParam _ _) = True
507 predHasFDs (ClassP cls _) = classHasFDs cls
509 mkPredName :: Unique -> SrcLoc -> SourceType -> Name
510 mkPredName uniq loc (ClassP cls tys) = mkLocalName uniq (mkDictOcc (getOccName cls)) loc
511 mkPredName uniq loc (IParam ip ty) = mkLocalName uniq (getOccName (ipNameName ip)) loc
515 --------------------- Dictionary types ---------------------------------
518 mkClassPred clas tys = UASSERT2( not (any isUTy tys), ppr clas <+> fsep (map pprType tys) )
521 isClassPred :: SourceType -> Bool
522 isClassPred (ClassP clas tys) = True
523 isClassPred other = False
525 isTyVarClassPred (ClassP clas tys) = all tcIsTyVarTy tys
526 isTyVarClassPred other = False
528 getClassPredTys_maybe :: SourceType -> Maybe (Class, [Type])
529 getClassPredTys_maybe (ClassP clas tys) = Just (clas, tys)
530 getClassPredTys_maybe _ = Nothing
532 getClassPredTys :: PredType -> (Class, [Type])
533 getClassPredTys (ClassP clas tys) = (clas, tys)
535 mkDictTy :: Class -> [Type] -> Type
536 mkDictTy clas tys = UASSERT2( not (any isUTy tys), ppr clas <+> fsep (map pprType tys) )
537 mkPredTy (ClassP clas tys)
539 isDictTy :: Type -> Bool
540 isDictTy (SourceTy p) = isClassPred p
541 isDictTy (NoteTy _ ty) = isDictTy ty
542 isDictTy (UsageTy _ ty) = isDictTy ty
543 isDictTy other = False
546 --------------------- Implicit parameters ---------------------------------
549 isIPPred :: SourceType -> Bool
550 isIPPred (IParam _ _) = True
551 isIPPred other = False
553 inheritablePred :: PredType -> Bool
554 -- Can be inherited by a context. For example, consider
555 -- f x = let g y = (?v, y+x)
556 -- in (g 3 with ?v = 8,
558 -- The point is that g's type must be quantifed over ?v:
559 -- g :: (?v :: a) => a -> a
560 -- but it doesn't need to be quantified over the Num a dictionary
561 -- which can be free in g's rhs, and shared by both calls to g
562 inheritablePred (ClassP _ _) = True
563 inheritablePred other = False
567 %************************************************************************
569 \subsection{Comparison}
571 %************************************************************************
573 Comparison, taking note of newtypes, predicates, etc,
574 But ignoring usage types
577 tcEqType :: Type -> Type -> Bool
578 tcEqType ty1 ty2 = case ty1 `tcCmpType` ty2 of { EQ -> True; other -> False }
580 tcEqPred :: PredType -> PredType -> Bool
581 tcEqPred p1 p2 = case p1 `tcCmpPred` p2 of { EQ -> True; other -> False }
584 tcCmpType :: Type -> Type -> Ordering
585 tcCmpType ty1 ty2 = cmpTy emptyVarEnv ty1 ty2
587 tcCmpTypes tys1 tys2 = cmpTys emptyVarEnv tys1 tys2
589 tcCmpPred p1 p2 = cmpSourceTy emptyVarEnv p1 p2
591 cmpTys env tys1 tys2 = cmpList (cmpTy env) tys1 tys2
594 cmpTy :: TyVarEnv TyVar -> Type -> Type -> Ordering
595 -- The "env" maps type variables in ty1 to type variables in ty2
596 -- So when comparing for-alls.. (forall tv1 . t1) (forall tv2 . t2)
597 -- we in effect substitute tv2 for tv1 in t1 before continuing
599 -- Look through NoteTy and UsageTy
600 cmpTy env (NoteTy _ ty1) ty2 = cmpTy env ty1 ty2
601 cmpTy env ty1 (NoteTy _ ty2) = cmpTy env ty1 ty2
602 cmpTy env (UsageTy _ ty1) ty2 = cmpTy env ty1 ty2
603 cmpTy env ty1 (UsageTy _ ty2) = cmpTy env ty1 ty2
605 -- Deal with equal constructors
606 cmpTy env (TyVarTy tv1) (TyVarTy tv2) = case lookupVarEnv env tv1 of
607 Just tv1a -> tv1a `compare` tv2
608 Nothing -> tv1 `compare` tv2
610 cmpTy env (SourceTy p1) (SourceTy p2) = cmpSourceTy env p1 p2
611 cmpTy env (AppTy f1 a1) (AppTy f2 a2) = cmpTy env f1 f2 `thenCmp` cmpTy env a1 a2
612 cmpTy env (FunTy f1 a1) (FunTy f2 a2) = cmpTy env f1 f2 `thenCmp` cmpTy env a1 a2
613 cmpTy env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` (cmpTys env tys1 tys2)
614 cmpTy env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTy (extendVarEnv env tv1 tv2) t1 t2
616 -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < SourceTy
617 cmpTy env (AppTy _ _) (TyVarTy _) = GT
619 cmpTy env (FunTy _ _) (TyVarTy _) = GT
620 cmpTy env (FunTy _ _) (AppTy _ _) = GT
622 cmpTy env (TyConApp _ _) (TyVarTy _) = GT
623 cmpTy env (TyConApp _ _) (AppTy _ _) = GT
624 cmpTy env (TyConApp _ _) (FunTy _ _) = GT
626 cmpTy env (ForAllTy _ _) (TyVarTy _) = GT
627 cmpTy env (ForAllTy _ _) (AppTy _ _) = GT
628 cmpTy env (ForAllTy _ _) (FunTy _ _) = GT
629 cmpTy env (ForAllTy _ _) (TyConApp _ _) = GT
631 cmpTy env (SourceTy _) t2 = GT
637 cmpSourceTy :: TyVarEnv TyVar -> SourceType -> SourceType -> Ordering
638 cmpSourceTy env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` (cmpTy env ty1 ty2)
639 -- Compare types as well as names for implicit parameters
640 -- This comparison is used exclusively (I think) for the
641 -- finite map built in TcSimplify
642 cmpSourceTy env (IParam _ _) sty = LT
644 cmpSourceTy env (ClassP _ _) (IParam _ _) = GT
645 cmpSourceTy env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTys env tys1 tys2)
646 cmpSourceTy env (ClassP _ _) (NType _ _) = LT
648 cmpSourceTy env (NType tc1 tys1) (NType tc2 tys2) = (tc1 `compare` tc2) `thenCmp` (cmpTys env tys1 tys2)
649 cmpSourceTy env (NType _ _) sty = GT
652 PredTypes are used as a FM key in TcSimplify,
653 so we take the easy path and make them an instance of Ord
656 instance Eq SourceType where { (==) = tcEqPred }
657 instance Ord SourceType where { compare = tcCmpPred }
661 %************************************************************************
663 \subsection{Predicates}
665 %************************************************************************
667 isSigmaTy returns true of any qualified type. It doesn't *necessarily* have
669 f :: (?x::Int) => Int -> Int
672 isSigmaTy :: Type -> Bool
673 isSigmaTy (ForAllTy tyvar ty) = True
674 isSigmaTy (FunTy a b) = isPredTy a
675 isSigmaTy (NoteTy n ty) = isSigmaTy ty
676 isSigmaTy (UsageTy _ ty) = isSigmaTy ty
679 isOverloadedTy :: Type -> Bool
680 isOverloadedTy (ForAllTy tyvar ty) = isOverloadedTy ty
681 isOverloadedTy (FunTy a b) = isPredTy a
682 isOverloadedTy (NoteTy n ty) = isOverloadedTy ty
683 isOverloadedTy (UsageTy _ ty) = isOverloadedTy ty
684 isOverloadedTy _ = False
688 isFloatTy = is_tc floatTyConKey
689 isDoubleTy = is_tc doubleTyConKey
690 isForeignPtrTy = is_tc foreignPtrTyConKey
691 isIntegerTy = is_tc integerTyConKey
692 isIntTy = is_tc intTyConKey
693 isAddrTy = is_tc addrTyConKey
694 isBoolTy = is_tc boolTyConKey
695 isUnitTy = is_tc unitTyConKey
697 is_tc :: Unique -> Type -> Bool
698 -- Newtypes are opaque to this
699 is_tc uniq ty = case tcSplitTyConApp_maybe ty of
700 Just (tc, _) -> uniq == getUnique tc
705 %************************************************************************
709 %************************************************************************
712 hoistForAllTys :: Type -> Type
713 -- Move all the foralls to the top
714 -- e.g. T -> forall a. a ==> forall a. T -> a
715 -- Careful: LOSES USAGE ANNOTATIONS!
717 = case hoist ty of { (tvs, body) -> mkForAllTys tvs body }
719 hoist :: Type -> ([TyVar], Type)
720 hoist ty = case tcSplitFunTys ty of { (args, res) ->
721 case tcSplitForAllTys res of {
722 ([], body) -> ([], ty) ;
723 (tvs1, body1) -> case hoist body1 of { (tvs2,body2) ->
724 (tvs1 ++ tvs2, mkFunTys args body2)
730 deNoteType :: Type -> Type
731 -- Remove synonyms, but not source types
732 deNoteType ty@(TyVarTy tyvar) = ty
733 deNoteType (TyConApp tycon tys) = TyConApp tycon (map deNoteType tys)
734 deNoteType (SourceTy p) = SourceTy (deNoteSourceType p)
735 deNoteType (NoteTy _ ty) = deNoteType ty
736 deNoteType (AppTy fun arg) = AppTy (deNoteType fun) (deNoteType arg)
737 deNoteType (FunTy fun arg) = FunTy (deNoteType fun) (deNoteType arg)
738 deNoteType (ForAllTy tv ty) = ForAllTy tv (deNoteType ty)
739 deNoteType (UsageTy u ty) = UsageTy u (deNoteType ty)
741 deNoteSourceType :: SourceType -> SourceType
742 deNoteSourceType (ClassP c tys) = ClassP c (map deNoteType tys)
743 deNoteSourceType (IParam n ty) = IParam n (deNoteType ty)
744 deNoteSourceType (NType tc tys) = NType tc (map deNoteType tys)
747 Find the free names of a type, including the type constructors and classes it mentions
748 This is used in the front end of the compiler
751 namesOfType :: Type -> NameSet
752 namesOfType (TyVarTy tv) = unitNameSet (getName tv)
753 namesOfType (TyConApp tycon tys) = unitNameSet (getName tycon) `unionNameSets` namesOfTypes tys
754 namesOfType (NoteTy (SynNote ty1) ty2) = namesOfType ty1
755 namesOfType (NoteTy other_note ty2) = namesOfType ty2
756 namesOfType (SourceTy (IParam n ty)) = namesOfType ty
757 namesOfType (SourceTy (ClassP cl tys)) = unitNameSet (getName cl) `unionNameSets` namesOfTypes tys
758 namesOfType (SourceTy (NType tc tys)) = unitNameSet (getName tc) `unionNameSets` namesOfTypes tys
759 namesOfType (FunTy arg res) = namesOfType arg `unionNameSets` namesOfType res
760 namesOfType (AppTy fun arg) = namesOfType fun `unionNameSets` namesOfType arg
761 namesOfType (ForAllTy tyvar ty) = namesOfType ty `delFromNameSet` getName tyvar
762 namesOfType (UsageTy u ty) = namesOfType u `unionNameSets` namesOfType ty
764 namesOfTypes tys = foldr (unionNameSets . namesOfType) emptyNameSet tys
766 namesOfDFunHead :: Type -> NameSet
767 -- Find the free type constructors and classes
768 -- of the head of the dfun instance type
769 -- The 'dfun_head_type' is because of
770 -- instance Foo a => Baz T where ...
771 -- The decl is an orphan if Baz and T are both not locally defined,
772 -- even if Foo *is* locally defined
773 namesOfDFunHead dfun_ty = case tcSplitSigmaTy dfun_ty of
774 (tvs,_,head_ty) -> delListFromNameSet (namesOfType head_ty)
779 %************************************************************************
781 \subsection[TysWiredIn-ext-type]{External types}
783 %************************************************************************
785 The compiler's foreign function interface supports the passing of a
786 restricted set of types as arguments and results (the restricting factor
790 isFFIArgumentTy :: DynFlags -> Safety -> Type -> Bool
791 -- Checks for valid argument type for a 'foreign import'
792 isFFIArgumentTy dflags safety ty
793 = checkRepTyCon (legalOutgoingTyCon dflags safety) ty
795 isFFIExternalTy :: Type -> Bool
796 -- Types that are allowed as arguments of a 'foreign export'
797 isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty
799 isFFIImportResultTy :: DynFlags -> Type -> Bool
800 isFFIImportResultTy dflags ty
801 = checkRepTyCon (legalFIResultTyCon dflags) ty
803 isFFIExportResultTy :: Type -> Bool
804 isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty
806 isFFIDynArgumentTy :: Type -> Bool
807 -- The argument type of a foreign import dynamic must be Ptr, FunPtr, Addr,
808 -- or a newtype of either.
809 isFFIDynArgumentTy = checkRepTyCon (\tc -> tc == ptrTyCon || tc == funPtrTyCon || tc == addrTyCon)
811 isFFIDynResultTy :: Type -> Bool
812 -- The result type of a foreign export dynamic must be Ptr, FunPtr, Addr,
813 -- or a newtype of either.
814 isFFIDynResultTy = checkRepTyCon (\tc -> tc == ptrTyCon || tc == funPtrTyCon || tc == addrTyCon)
816 isFFILabelTy :: Type -> Bool
817 -- The type of a foreign label must be Ptr, FunPtr, Addr,
818 -- or a newtype of either.
819 isFFILabelTy = checkRepTyCon (\tc -> tc == ptrTyCon || tc == funPtrTyCon || tc == addrTyCon)
821 checkRepTyCon :: (TyCon -> Bool) -> Type -> Bool
822 -- Look through newtypes
823 -- Non-recursive ones are transparent to splitTyConApp,
824 -- but recursive ones aren't; hence the splitNewType_maybe
825 checkRepTyCon check_tc ty
826 | Just ty' <- splitNewType_maybe ty = checkRepTyCon check_tc ty'
827 | Just (tc,_) <- splitTyConApp_maybe ty = check_tc tc
831 ----------------------------------------------
832 These chaps do the work; they are not exported
833 ----------------------------------------------
836 legalFEArgTyCon :: TyCon -> Bool
837 -- It's illegal to return foreign objects and (mutable)
838 -- bytearrays from a _ccall_ / foreign declaration
839 -- (or be passed them as arguments in foreign exported functions).
841 | getUnique tc `elem` [ foreignObjTyConKey, foreignPtrTyConKey,
842 byteArrayTyConKey, mutableByteArrayTyConKey ]
844 -- It's also illegal to make foreign exports that take unboxed
845 -- arguments. The RTS API currently can't invoke such things. --SDM 7/2000
847 = boxedMarshalableTyCon tc
849 legalFIResultTyCon :: DynFlags -> TyCon -> Bool
850 legalFIResultTyCon dflags tc
851 | getUnique tc `elem`
852 [ foreignObjTyConKey, foreignPtrTyConKey,
853 byteArrayTyConKey, mutableByteArrayTyConKey ] = False
854 | tc == unitTyCon = True
855 | otherwise = marshalableTyCon dflags tc
857 legalFEResultTyCon :: TyCon -> Bool
858 legalFEResultTyCon tc
859 | getUnique tc `elem`
860 [ foreignObjTyConKey, foreignPtrTyConKey,
861 byteArrayTyConKey, mutableByteArrayTyConKey ] = False
862 | tc == unitTyCon = True
863 | otherwise = boxedMarshalableTyCon tc
865 legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Bool
866 -- Checks validity of types going from Haskell -> external world
867 legalOutgoingTyCon dflags safety tc
868 | playSafe safety && getUnique tc `elem` [byteArrayTyConKey, mutableByteArrayTyConKey]
871 = marshalableTyCon dflags tc
873 marshalableTyCon dflags tc
874 = (dopt Opt_GlasgowExts dflags && isUnLiftedTyCon tc)
875 || boxedMarshalableTyCon tc
877 boxedMarshalableTyCon tc
878 = getUnique tc `elem` [ intTyConKey, int8TyConKey, int16TyConKey
879 , int32TyConKey, int64TyConKey
880 , wordTyConKey, word8TyConKey, word16TyConKey
881 , word32TyConKey, word64TyConKey
882 , floatTyConKey, doubleTyConKey
883 , addrTyConKey, ptrTyConKey, funPtrTyConKey
884 , charTyConKey, foreignObjTyConKey
887 , byteArrayTyConKey, mutableByteArrayTyConKey
893 %************************************************************************
895 \subsection{Unification with an explicit substitution}
897 %************************************************************************
899 (allDistinctTyVars tys tvs) = True
901 all the types tys are type variables,
902 distinct from each other and from tvs.
904 This is useful when checking that unification hasn't unified signature
905 type variables. For example, if the type sig is
906 f :: forall a b. a -> b -> b
907 we want to check that 'a' and 'b' havn't
908 (a) been unified with a non-tyvar type
909 (b) been unified with each other (all distinct)
910 (c) been unified with a variable free in the environment
913 allDistinctTyVars :: [Type] -> TyVarSet -> Bool
915 allDistinctTyVars [] acc
917 allDistinctTyVars (ty:tys) acc
918 = case tcGetTyVar_maybe ty of
919 Nothing -> False -- (a)
920 Just tv | tv `elemVarSet` acc -> False -- (b) or (c)
921 | otherwise -> allDistinctTyVars tys (acc `extendVarSet` tv)
925 %************************************************************************
927 \subsection{Unification with an explicit substitution}
929 %************************************************************************
931 Unify types with an explicit substitution and no monad.
932 Ignore usage annotations.
936 = (TyVarSet, -- Set of template tyvars
937 TyVarSubstEnv) -- Not necessarily idempotent
939 unifyTysX :: TyVarSet -- Template tyvars
942 -> Maybe TyVarSubstEnv
943 unifyTysX tmpl_tyvars ty1 ty2
944 = uTysX ty1 ty2 (\(_,s) -> Just s) (tmpl_tyvars, emptySubstEnv)
946 unifyExtendTysX :: TyVarSet -- Template tyvars
947 -> TyVarSubstEnv -- Substitution to start with
950 -> Maybe TyVarSubstEnv -- Extended substitution
951 unifyExtendTysX tmpl_tyvars subst ty1 ty2
952 = uTysX ty1 ty2 (\(_,s) -> Just s) (tmpl_tyvars, subst)
954 unifyTyListsX :: TyVarSet -> [Type] -> [Type]
955 -> Maybe TyVarSubstEnv
956 unifyTyListsX tmpl_tyvars tys1 tys2
957 = uTyListsX tys1 tys2 (\(_,s) -> Just s) (tmpl_tyvars, emptySubstEnv)
962 -> (MySubst -> Maybe result)
966 uTysX (NoteTy _ ty1) ty2 k subst = uTysX ty1 ty2 k subst
967 uTysX ty1 (NoteTy _ ty2) k subst = uTysX ty1 ty2 k subst
969 -- Variables; go for uVar
970 uTysX (TyVarTy tyvar1) (TyVarTy tyvar2) k subst
973 uTysX (TyVarTy tyvar1) ty2 k subst@(tmpls,_)
974 | tyvar1 `elemVarSet` tmpls
975 = uVarX tyvar1 ty2 k subst
976 uTysX ty1 (TyVarTy tyvar2) k subst@(tmpls,_)
977 | tyvar2 `elemVarSet` tmpls
978 = uVarX tyvar2 ty1 k subst
981 uTysX (SourceTy (IParam n1 t1)) (SourceTy (IParam n2 t2)) k subst
982 | n1 == n2 = uTysX t1 t2 k subst
983 uTysX (SourceTy (ClassP c1 tys1)) (SourceTy (ClassP c2 tys2)) k subst
984 | c1 == c2 = uTyListsX tys1 tys2 k subst
985 uTysX (SourceTy (NType tc1 tys1)) (SourceTy (NType tc2 tys2)) k subst
986 | tc1 == tc2 = uTyListsX tys1 tys2 k subst
988 -- Functions; just check the two parts
989 uTysX (FunTy fun1 arg1) (FunTy fun2 arg2) k subst
990 = uTysX fun1 fun2 (uTysX arg1 arg2 k) subst
992 -- Type constructors must match
993 uTysX (TyConApp con1 tys1) (TyConApp con2 tys2) k subst
994 | (con1 == con2 && equalLength tys1 tys2)
995 = uTyListsX tys1 tys2 k subst
997 -- Applications need a bit of care!
998 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
999 -- NB: we've already dealt with type variables and Notes,
1000 -- so if one type is an App the other one jolly well better be too
1001 uTysX (AppTy s1 t1) ty2 k subst
1002 = case tcSplitAppTy_maybe ty2 of
1003 Just (s2, t2) -> uTysX s1 s2 (uTysX t1 t2 k) subst
1004 Nothing -> Nothing -- Fail
1006 uTysX ty1 (AppTy s2 t2) k subst
1007 = case tcSplitAppTy_maybe ty1 of
1008 Just (s1, t1) -> uTysX s1 s2 (uTysX t1 t2 k) subst
1009 Nothing -> Nothing -- Fail
1011 -- Not expecting for-alls in unification
1013 uTysX (ForAllTy _ _) ty2 k subst = panic "Unify.uTysX subst:ForAllTy (1st arg)"
1014 uTysX ty1 (ForAllTy _ _) k subst = panic "Unify.uTysX subst:ForAllTy (2nd arg)"
1018 uTysX (UsageTy _ t1) t2 k subst = uTysX t1 t2 k subst
1019 uTysX t1 (UsageTy _ t2) k subst = uTysX t1 t2 k subst
1021 -- Anything else fails
1022 uTysX ty1 ty2 k subst = Nothing
1025 uTyListsX [] [] k subst = k subst
1026 uTyListsX (ty1:tys1) (ty2:tys2) k subst = uTysX ty1 ty2 (uTyListsX tys1 tys2 k) subst
1027 uTyListsX tys1 tys2 k subst = Nothing -- Fail if the lists are different lengths
1031 -- Invariant: tv1 is a unifiable variable
1032 uVarX tv1 ty2 k subst@(tmpls, env)
1033 = case lookupSubstEnv env tv1 of
1034 Just (DoneTy ty1) -> -- Already bound
1035 uTysX ty1 ty2 k subst
1037 Nothing -- Not already bound
1038 | typeKind ty2 `eqKind` tyVarKind tv1
1039 && occur_check_ok ty2
1040 -> -- No kind mismatch nor occur check
1041 UASSERT( not (isUTy ty2) )
1042 k (tmpls, extendSubstEnv env tv1 (DoneTy ty2))
1044 | otherwise -> Nothing -- Fail if kind mis-match or occur check
1046 occur_check_ok ty = all occur_check_ok_tv (varSetElems (tyVarsOfType ty))
1047 occur_check_ok_tv tv | tv1 == tv = False
1048 | otherwise = case lookupSubstEnv env tv of
1050 Just (DoneTy ty) -> occur_check_ok ty
1055 %************************************************************************
1057 \subsection{Matching on types}
1059 %************************************************************************
1061 Matching is a {\em unidirectional} process, matching a type against a
1062 template (which is just a type with type variables in it). The
1063 matcher assumes that there are no repeated type variables in the
1064 template, so that it simply returns a mapping of type variables to
1065 types. It also fails on nested foralls.
1067 @matchTys@ matches corresponding elements of a list of templates and
1068 types. It and @matchTy@ both ignore usage annotations, unlike the
1069 main function @match@.
1072 matchTy :: TyVarSet -- Template tyvars
1074 -> Type -- Proposed instance of template
1075 -> Maybe TyVarSubstEnv -- Matching substitution
1078 matchTys :: TyVarSet -- Template tyvars
1079 -> [Type] -- Templates
1080 -> [Type] -- Proposed instance of template
1081 -> Maybe (TyVarSubstEnv, -- Matching substitution
1082 [Type]) -- Left over instance types
1084 matchTy tmpls ty1 ty2 = match ty1 ty2 tmpls (\ senv -> Just senv) emptySubstEnv
1086 matchTys tmpls tys1 tys2 = match_list tys1 tys2 tmpls
1087 (\ (senv,tys) -> Just (senv,tys))
1091 @match@ is the main function. It takes a flag indicating whether
1092 usage annotations are to be respected.
1095 match :: Type -> Type -- Current match pair
1096 -> TyVarSet -- Template vars
1097 -> (TyVarSubstEnv -> Maybe result) -- Continuation
1098 -> TyVarSubstEnv -- Current subst
1101 -- When matching against a type variable, see if the variable
1102 -- has already been bound. If so, check that what it's bound to
1103 -- is the same as ty; if not, bind it and carry on.
1105 match (TyVarTy v) ty tmpls k senv
1106 | v `elemVarSet` tmpls
1107 = -- v is a template variable
1108 case lookupSubstEnv senv v of
1109 Nothing -> UASSERT( not (isUTy ty) )
1110 k (extendSubstEnv senv v (DoneTy ty))
1111 Just (DoneTy ty') | ty' `tcEqType` ty -> k senv -- Succeeds
1112 | otherwise -> Nothing -- Fails
1115 = -- v is not a template variable; ty had better match
1116 -- Can't use (==) because types differ
1117 case tcGetTyVar_maybe ty of
1118 Just v' | v == v' -> k senv -- Success
1119 other -> Nothing -- Failure
1120 -- This tcGetTyVar_maybe is *required* because it must strip Notes.
1121 -- I guess the reason the Note-stripping case is *last* rather than first
1122 -- is to preserve type synonyms etc., so I'm not moving it to the
1123 -- top; but this means that (without the deNotetype) a type
1124 -- variable may not match the pattern (TyVarTy v') as one would
1125 -- expect, due to an intervening Note. KSW 2000-06.
1128 match (SourceTy (IParam n1 t1)) (SourceTy (IParam n2 t2)) tmpls k senv
1129 | n1 == n2 = match t1 t2 tmpls k senv
1130 match (SourceTy (ClassP c1 tys1)) (SourceTy (ClassP c2 tys2)) tmpls k senv
1131 | c1 == c2 = match_list_exactly tys1 tys2 tmpls k senv
1132 match (SourceTy (NType tc1 tys1)) (SourceTy (NType tc2 tys2)) tmpls k senv
1133 | tc1 == tc2 = match_list_exactly tys1 tys2 tmpls k senv
1135 -- Functions; just check the two parts
1136 match (FunTy arg1 res1) (FunTy arg2 res2) tmpls k senv
1137 = match arg1 arg2 tmpls (match res1 res2 tmpls k) senv
1139 match (AppTy fun1 arg1) ty2 tmpls k senv
1140 = case tcSplitAppTy_maybe ty2 of
1141 Just (fun2,arg2) -> match fun1 fun2 tmpls (match arg1 arg2 tmpls k) senv
1142 Nothing -> Nothing -- Fail
1144 match (TyConApp tc1 tys1) (TyConApp tc2 tys2) tmpls k senv
1145 | tc1 == tc2 = match_list_exactly tys1 tys2 tmpls k senv
1147 -- Newtypes are opaque; other source types should not happen
1148 match (SourceTy (NType tc1 tys1)) (SourceTy (NType tc2 tys2)) tmpls k senv
1149 | tc1 == tc2 = match_list_exactly tys1 tys2 tmpls k senv
1151 match (UsageTy _ ty1) ty2 tmpls k senv = match ty1 ty2 tmpls k senv
1152 match ty1 (UsageTy _ ty2) tmpls k senv = match ty1 ty2 tmpls k senv
1154 -- With type synonyms, we have to be careful for the exact
1155 -- same reasons as in the unifier. Please see the
1156 -- considerable commentary there before changing anything
1157 -- here! (WDP 95/05)
1158 match (NoteTy n1 ty1) ty2 tmpls k senv = match ty1 ty2 tmpls k senv
1159 match ty1 (NoteTy n2 ty2) tmpls k senv = match ty1 ty2 tmpls k senv
1162 match _ _ _ _ _ = Nothing
1164 match_list_exactly tys1 tys2 tmpls k senv
1165 = match_list tys1 tys2 tmpls k' senv
1167 k' (senv', tys2') | null tys2' = k senv' -- Succeed
1168 | otherwise = Nothing -- Fail
1170 match_list [] tys2 tmpls k senv = k (senv, tys2)
1171 match_list (ty1:tys1) [] tmpls k senv = Nothing -- Not enough arg tys => failure
1172 match_list (ty1:tys1) (ty2:tys2) tmpls k senv
1173 = match ty1 ty2 tmpls (match_list tys1 tys2 tmpls k) senv