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 TyVarDetails(..), isUserTyVar, isSkolemTyVar, isHoleTyVar,
28 --------------------------------
32 --------------------------------
34 -- These are important because they do not look through newtypes
35 tcSplitForAllTys, tcSplitPhiTy,
36 tcSplitFunTy_maybe, tcSplitFunTys, tcFunArgTy, tcFunResultTy,
37 tcSplitTyConApp, tcSplitTyConApp_maybe, tcTyConAppTyCon, tcTyConAppArgs,
38 tcSplitAppTy_maybe, tcSplitAppTy, tcSplitAppTys, tcSplitSigmaTy,
39 tcSplitMethodTy, tcGetTyVar_maybe, tcGetTyVar,
41 ---------------------------------
43 -- Again, newtypes are opaque
44 tcEqType, tcEqTypes, tcEqPred, tcCmpType, tcCmpTypes, tcCmpPred,
45 isSigmaTy, isOverloadedTy,
46 isDoubleTy, isFloatTy, isIntTy,
47 isIntegerTy, isAddrTy, isBoolTy, isUnitTy,
48 isTauTy, tcIsTyVarTy, tcIsForAllTy,
51 ---------------------------------
52 -- Misc type manipulators
53 deNoteType, classNamesOfTheta,
54 tyClsNamesOfType, tyClsNamesOfDFunHead,
57 ---------------------------------
59 getClassPredTys_maybe, getClassPredTys,
60 isPredTy, isClassPred, isTyVarClassPred, predHasFDs,
61 mkDictTy, tcSplitPredTy_maybe,
62 isDictTy, tcSplitDFunTy, predTyUnique,
63 mkClassPred, isInheritablePred, isLinearPred, isIPPred, mkPredName,
65 ---------------------------------
66 -- Foreign import and export
67 isFFIArgumentTy, -- :: DynFlags -> Safety -> Type -> Bool
68 isFFIImportResultTy, -- :: DynFlags -> Type -> Bool
69 isFFIExportResultTy, -- :: Type -> Bool
70 isFFIExternalTy, -- :: Type -> Bool
71 isFFIDynArgumentTy, -- :: Type -> Bool
72 isFFIDynResultTy, -- :: Type -> Bool
73 isFFILabelTy, -- :: Type -> Bool
75 ---------------------------------
76 -- Unifier and matcher
77 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,
85 isTypeKind, isAnyTypeKind,
87 Type, SourceType(..), PredType, ThetaType,
88 mkForAllTy, mkForAllTys,
89 mkFunTy, mkFunTys, zipFunTys,
90 mkTyConApp, mkGenTyConApp, mkAppTy, mkAppTys, mkSynTy, applyTy, applyTys,
91 mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys,
93 isUnLiftedType, -- Source types are always lifted
94 isUnboxedTupleType, -- Ditto
95 isPrimitiveType, isTyVarTy,
97 tidyTopType, tidyType, tidyPred, tidyTypes, tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
98 tidyTyVarBndr, tidyOpenTyVar, tidyOpenTyVars,
101 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta
104 #include "HsVersions.h"
107 import {-# SOURCE #-} PprType( pprType )
108 -- PprType imports TcType so that it can print intelligently
111 import TypeRep ( Type(..), TyNote(..), funTyCon ) -- friend
113 import Type ( -- Re-exports
114 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred,
115 tyVarsOfTheta, Kind, Type, SourceType(..),
116 PredType, ThetaType, unliftedTypeKind,
117 liftedTypeKind, openTypeKind, mkArrowKind,
118 mkArrowKinds, mkForAllTy, mkForAllTys,
119 defaultKind, isTypeKind, isAnyTypeKind,
120 mkFunTy, mkFunTys, zipFunTys, isTyVarTy,
121 mkTyConApp, mkGenTyConApp, mkAppTy,
122 mkAppTys, mkSynTy, applyTy, applyTys,
123 mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy,
124 mkPredTys, isUnLiftedType,
125 isUnboxedTupleType, isPrimitiveType,
126 splitNewType_maybe, splitTyConApp_maybe,
127 tidyTopType, tidyType, tidyPred, tidyTypes,
128 tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
129 tidyTyVarBndr, tidyOpenTyVar,
130 tidyOpenTyVars, eqKind,
131 hasMoreBoxityInfo, liftedBoxity,
132 superBoxity, typeKind, superKind, repType
134 import TyCon ( TyCon, isUnLiftedTyCon )
135 import Class ( classHasFDs, Class )
136 import Var ( TyVar, tyVarKind, isMutTyVar, mutTyVarDetails )
137 import ForeignCall ( Safety, playSafe )
142 import CmdLineOpts ( DynFlags, DynFlag( Opt_GlasgowExts ), dopt )
143 import Name ( Name, NamedThing(..), mkInternalName, getSrcLoc )
144 import OccName ( OccName, mkDictOcc )
146 import PrelNames -- Lots (e.g. in isFFIArgumentTy)
147 import TysWiredIn ( ptrTyCon, funPtrTyCon, addrTyCon, unitTyCon )
148 import BasicTypes ( IPName(..), ipNameName )
149 import Unique ( Unique, Uniquable(..) )
150 import SrcLoc ( SrcLoc )
151 import Util ( cmpList, thenCmp, equalLength, snocView )
152 import Maybes ( maybeToBool, expectJust )
157 %************************************************************************
161 %************************************************************************
163 The type checker divides the generic Type world into the
164 following more structured beasts:
166 sigma ::= forall tyvars. phi
167 -- A sigma type is a qualified type
169 -- Note that even if 'tyvars' is empty, theta
170 -- may not be: e.g. (?x::Int) => Int
172 -- Note that 'sigma' is in prenex form:
173 -- all the foralls are at the front.
174 -- A 'phi' type has no foralls to the right of
182 -- A 'tau' type has no quantification anywhere
183 -- Note that the args of a type constructor must be taus
185 | tycon tau_1 .. tau_n
189 -- In all cases, a (saturated) type synonym application is legal,
190 -- provided it expands to the required form.
194 type SigmaType = Type
200 type TcTyVar = TyVar -- Might be a mutable tyvar
201 type TcTyVarSet = TyVarSet
203 type TcType = Type -- A TcType can have mutable type variables
204 -- Invariant on ForAllTy in TcTypes:
206 -- a cannot occur inside a MutTyVar in T; that is,
207 -- T is "flattened" before quantifying over a
209 type TcPredType = PredType
210 type TcThetaType = ThetaType
211 type TcSigmaType = TcType
212 type TcRhoType = TcType
213 type TcTauType = TcType
218 %************************************************************************
220 \subsection{TyVarDetails}
222 %************************************************************************
224 TyVarDetails gives extra info about type variables, used during type
225 checking. It's attached to mutable type variables only.
226 It's knot-tied back to Var.lhs. There is no reason in principle
227 why Var.lhs shouldn't actually have the definition, but it "belongs" here.
231 = HoleTv -- Used *only* by the type checker when passing in a type
232 -- variable that should be side-effected to the result type.
233 -- Always has kind openTypeKind.
234 -- Never appears in types
236 | SigTv -- Introduced when instantiating a type signature,
237 -- prior to checking that the defn of a fn does
238 -- have the expected type. Should not be instantiated.
240 -- f :: forall a. a -> a
242 -- When checking e, with expected type (a->a), we
243 -- should not instantiate a
245 | ClsTv -- Scoped type variable introduced by a class decl
246 -- class C a where ...
248 | InstTv -- Ditto, but instance decl
250 | PatSigTv -- Scoped type variable, introduced by a pattern
254 | VanillaTv -- Everything else
256 isUserTyVar :: TcTyVar -> Bool -- Avoid unifying these if possible
257 isUserTyVar tv = case mutTyVarDetails tv of
261 isSkolemTyVar :: TcTyVar -> Bool
262 isSkolemTyVar tv = case mutTyVarDetails tv of
268 isHoleTyVar :: TcTyVar -> Bool
269 -- NB: the hole might be filled in by now, and this
270 -- function does not check for that
271 isHoleTyVar tv = ASSERT( isMutTyVar tv )
272 case mutTyVarDetails tv of
276 tyVarBindingInfo :: TyVar -> SDoc -- Used in checkSigTyVars
279 = sep [ptext SLIT("is bound by the") <+> details (mutTyVarDetails tv),
280 ptext SLIT("at") <+> ppr (getSrcLoc tv)]
284 details SigTv = ptext SLIT("type signature")
285 details ClsTv = ptext SLIT("class declaration")
286 details InstTv = ptext SLIT("instance declaration")
287 details PatSigTv = ptext SLIT("pattern type signature")
288 details HoleTv = ptext SLIT("//hole//") -- Should not happen
289 details VanillaTv = ptext SLIT("//vanilla//") -- Ditto
293 %************************************************************************
295 \subsection{Tau, sigma and rho}
297 %************************************************************************
300 mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkPhiTy theta tau)
302 mkPhiTy :: [SourceType] -> Type -> Type
303 mkPhiTy theta ty = foldr (\p r -> FunTy (mkPredTy p) r) ty theta
307 @isTauTy@ tests for nested for-alls.
310 isTauTy :: Type -> Bool
311 isTauTy (TyVarTy v) = True
312 isTauTy (TyConApp _ tys) = all isTauTy tys
313 isTauTy (AppTy a b) = isTauTy a && isTauTy b
314 isTauTy (FunTy a b) = isTauTy a && isTauTy b
315 isTauTy (SourceTy p) = True -- Don't look through source types
316 isTauTy (NoteTy _ ty) = isTauTy ty
317 isTauTy other = False
321 getDFunTyKey :: Type -> OccName -- Get some string from a type, to be used to
322 -- construct a dictionary function name
323 getDFunTyKey (TyVarTy tv) = getOccName tv
324 getDFunTyKey (TyConApp tc _) = getOccName tc
325 getDFunTyKey (AppTy fun _) = getDFunTyKey fun
326 getDFunTyKey (NoteTy _ t) = getDFunTyKey t
327 getDFunTyKey (FunTy arg _) = getOccName funTyCon
328 getDFunTyKey (ForAllTy _ t) = getDFunTyKey t
329 getDFunTyKey (SourceTy (NType tc _)) = getOccName tc -- Newtypes are quite reasonable
330 getDFunTyKey ty = pprPanic "getDFunTyKey" (pprType ty)
331 -- SourceTy shouldn't happen
335 %************************************************************************
337 \subsection{Expanding and splitting}
339 %************************************************************************
341 These tcSplit functions are like their non-Tc analogues, but
342 a) they do not look through newtypes
343 b) they do not look through PredTys
344 c) [future] they ignore usage-type annotations
346 However, they are non-monadic and do not follow through mutable type
347 variables. It's up to you to make sure this doesn't matter.
350 tcSplitForAllTys :: Type -> ([TyVar], Type)
351 tcSplitForAllTys ty = split ty ty []
353 split orig_ty (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
354 split orig_ty (NoteTy n ty) tvs = split orig_ty ty tvs
355 split orig_ty t tvs = (reverse tvs, orig_ty)
357 tcIsForAllTy (ForAllTy tv ty) = True
358 tcIsForAllTy (NoteTy n ty) = tcIsForAllTy ty
359 tcIsForAllTy t = False
361 tcSplitPhiTy :: Type -> ([PredType], Type)
362 tcSplitPhiTy ty = split ty ty []
364 split orig_ty (FunTy arg res) ts = case tcSplitPredTy_maybe arg of
365 Just p -> split res res (p:ts)
366 Nothing -> (reverse ts, orig_ty)
367 split orig_ty (NoteTy n ty) ts = split orig_ty ty ts
368 split orig_ty ty ts = (reverse ts, orig_ty)
370 tcSplitSigmaTy ty = case tcSplitForAllTys ty of
371 (tvs, rho) -> case tcSplitPhiTy rho of
372 (theta, tau) -> (tvs, theta, tau)
374 tcTyConAppTyCon :: Type -> TyCon
375 tcTyConAppTyCon ty = fst (tcSplitTyConApp ty)
377 tcTyConAppArgs :: Type -> [Type]
378 tcTyConAppArgs ty = snd (tcSplitTyConApp ty)
380 tcSplitTyConApp :: Type -> (TyCon, [Type])
381 tcSplitTyConApp ty = case tcSplitTyConApp_maybe ty of
383 Nothing -> pprPanic "tcSplitTyConApp" (pprType ty)
385 tcSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
386 tcSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
387 tcSplitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
388 tcSplitTyConApp_maybe (NoteTy n ty) = tcSplitTyConApp_maybe ty
389 tcSplitTyConApp_maybe (SourceTy (NType tc tys)) = Just (tc,tys)
390 -- Newtypes are opaque, so they may be split
391 -- However, predicates are not treated
392 -- as tycon applications by the type checker
393 tcSplitTyConApp_maybe other = Nothing
395 tcSplitFunTys :: Type -> ([Type], Type)
396 tcSplitFunTys ty = case tcSplitFunTy_maybe ty of
398 Just (arg,res) -> (arg:args, res')
400 (args,res') = tcSplitFunTys res
402 tcSplitFunTy_maybe :: Type -> Maybe (Type, Type)
403 tcSplitFunTy_maybe (FunTy arg res) = Just (arg, res)
404 tcSplitFunTy_maybe (NoteTy n 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 [ty1], ty2)
413 tcSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
414 tcSplitAppTy_maybe (NoteTy n ty) = tcSplitAppTy_maybe ty
415 tcSplitAppTy_maybe (SourceTy (NType tc tys)) = tc_split_app tc tys --- Don't forget that newtype!
416 tcSplitAppTy_maybe (TyConApp tc tys) = tc_split_app tc tys
417 tcSplitAppTy_maybe other = Nothing
419 tc_split_app tc tys = case snocView tys of
420 Just (tys',ty') -> Just (TyConApp tc tys', ty')
423 tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
425 Nothing -> pprPanic "tcSplitAppTy" (pprType ty)
427 tcSplitAppTys :: Type -> (Type, [Type])
431 go ty args = case tcSplitAppTy_maybe ty of
432 Just (ty', arg) -> go ty' (arg:args)
435 tcGetTyVar_maybe :: Type -> Maybe TyVar
436 tcGetTyVar_maybe (TyVarTy tv) = Just tv
437 tcGetTyVar_maybe (NoteTy _ t) = tcGetTyVar_maybe t
438 tcGetTyVar_maybe other = Nothing
440 tcGetTyVar :: String -> Type -> TyVar
441 tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty)
443 tcIsTyVarTy :: Type -> Bool
444 tcIsTyVarTy ty = maybeToBool (tcGetTyVar_maybe ty)
447 The type of a method for class C is always of the form:
448 Forall a1..an. C a1..an => sig_ty
449 where sig_ty is the type given by the method's signature, and thus in general
450 is a ForallTy. At the point that splitMethodTy is called, it is expected
451 that the outer Forall has already been stripped off. splitMethodTy then
452 returns (C a1..an, sig_ty') where sig_ty' is sig_ty with any Notes stripped off.
455 tcSplitMethodTy :: Type -> (PredType, Type)
456 tcSplitMethodTy ty = split ty
458 split (FunTy arg res) = case tcSplitPredTy_maybe arg of
460 Nothing -> panic "splitMethodTy"
461 split (NoteTy n ty) = split ty
462 split _ = panic "splitMethodTy"
464 tcSplitDFunTy :: Type -> ([TyVar], [SourceType], Class, [Type])
465 -- Split the type of a dictionary function
467 = case tcSplitSigmaTy ty of { (tvs, theta, tau) ->
468 case tcSplitPredTy_maybe tau of { Just (ClassP clas tys) ->
469 (tvs, theta, clas, tys) }}
472 (allDistinctTyVars tys tvs) = True
474 all the types tys are type variables,
475 distinct from each other and from tvs.
477 This is useful when checking that unification hasn't unified signature
478 type variables. For example, if the type sig is
479 f :: forall a b. a -> b -> b
480 we want to check that 'a' and 'b' havn't
481 (a) been unified with a non-tyvar type
482 (b) been unified with each other (all distinct)
483 (c) been unified with a variable free in the environment
486 allDistinctTyVars :: [Type] -> TyVarSet -> Bool
488 allDistinctTyVars [] acc
490 allDistinctTyVars (ty:tys) acc
491 = case tcGetTyVar_maybe ty of
492 Nothing -> False -- (a)
493 Just tv | tv `elemVarSet` acc -> False -- (b) or (c)
494 | otherwise -> allDistinctTyVars tys (acc `extendVarSet` tv)
498 %************************************************************************
500 \subsection{Predicate types}
502 %************************************************************************
504 "Predicates" are particular source types, namelyClassP or IParams
507 isPred :: SourceType -> Bool
508 isPred (ClassP _ _) = True
509 isPred (IParam _ _) = True
510 isPred (NType _ _) = False
512 isPredTy :: Type -> Bool
513 isPredTy (NoteTy _ ty) = isPredTy ty
514 isPredTy (SourceTy sty) = isPred sty
517 tcSplitPredTy_maybe :: Type -> Maybe PredType
518 -- Returns Just for predicates only
519 tcSplitPredTy_maybe (NoteTy _ ty) = tcSplitPredTy_maybe ty
520 tcSplitPredTy_maybe (SourceTy p) | isPred p = Just p
521 tcSplitPredTy_maybe other = Nothing
523 predTyUnique :: PredType -> Unique
524 predTyUnique (IParam n _) = getUnique (ipNameName n)
525 predTyUnique (ClassP clas tys) = getUnique clas
527 predHasFDs :: PredType -> Bool
528 -- True if the predicate has functional depenencies;
529 -- I.e. should participate in improvement
530 predHasFDs (IParam _ _) = True
531 predHasFDs (ClassP cls _) = classHasFDs cls
533 mkPredName :: Unique -> SrcLoc -> SourceType -> Name
534 mkPredName uniq loc (ClassP cls tys) = mkInternalName uniq (mkDictOcc (getOccName cls)) loc
535 mkPredName uniq loc (IParam ip ty) = mkInternalName uniq (getOccName (ipNameName ip)) loc
539 --------------------- Dictionary types ---------------------------------
542 mkClassPred clas tys = ClassP clas tys
544 isClassPred :: SourceType -> Bool
545 isClassPred (ClassP clas tys) = True
546 isClassPred other = False
548 isTyVarClassPred (ClassP clas tys) = all tcIsTyVarTy tys
549 isTyVarClassPred other = False
551 getClassPredTys_maybe :: SourceType -> Maybe (Class, [Type])
552 getClassPredTys_maybe (ClassP clas tys) = Just (clas, tys)
553 getClassPredTys_maybe _ = Nothing
555 getClassPredTys :: PredType -> (Class, [Type])
556 getClassPredTys (ClassP clas tys) = (clas, tys)
558 mkDictTy :: Class -> [Type] -> Type
559 mkDictTy clas tys = mkPredTy (ClassP clas tys)
561 isDictTy :: Type -> Bool
562 isDictTy (SourceTy p) = isClassPred p
563 isDictTy (NoteTy _ ty) = isDictTy ty
564 isDictTy other = False
567 --------------------- Implicit parameters ---------------------------------
570 isIPPred :: SourceType -> Bool
571 isIPPred (IParam _ _) = True
572 isIPPred other = False
574 isInheritablePred :: PredType -> Bool
575 -- Can be inherited by a context. For example, consider
576 -- f x = let g y = (?v, y+x)
577 -- in (g 3 with ?v = 8,
579 -- The point is that g's type must be quantifed over ?v:
580 -- g :: (?v :: a) => a -> a
581 -- but it doesn't need to be quantified over the Num a dictionary
582 -- which can be free in g's rhs, and shared by both calls to g
583 isInheritablePred (ClassP _ _) = True
584 isInheritablePred other = False
586 isLinearPred :: TcPredType -> Bool
587 isLinearPred (IParam (Linear n) _) = True
588 isLinearPred other = False
592 %************************************************************************
594 \subsection{Comparison}
596 %************************************************************************
598 Comparison, taking note of newtypes, predicates, etc,
599 But ignoring usage types
602 tcEqType :: Type -> Type -> Bool
603 tcEqType ty1 ty2 = case ty1 `tcCmpType` ty2 of { EQ -> True; other -> False }
605 tcEqTypes :: [Type] -> [Type] -> Bool
606 tcEqTypes ty1 ty2 = case ty1 `tcCmpTypes` ty2 of { EQ -> True; other -> False }
608 tcEqPred :: PredType -> PredType -> Bool
609 tcEqPred p1 p2 = case p1 `tcCmpPred` p2 of { EQ -> True; other -> False }
612 tcCmpType :: Type -> Type -> Ordering
613 tcCmpType ty1 ty2 = cmpTy emptyVarEnv ty1 ty2
615 tcCmpTypes tys1 tys2 = cmpTys emptyVarEnv tys1 tys2
617 tcCmpPred p1 p2 = cmpSourceTy emptyVarEnv p1 p2
619 cmpTys env tys1 tys2 = cmpList (cmpTy env) tys1 tys2
622 cmpTy :: TyVarEnv TyVar -> Type -> Type -> Ordering
623 -- The "env" maps type variables in ty1 to type variables in ty2
624 -- So when comparing for-alls.. (forall tv1 . t1) (forall tv2 . t2)
625 -- we in effect substitute tv2 for tv1 in t1 before continuing
627 -- Look through NoteTy
628 cmpTy env (NoteTy _ ty1) ty2 = cmpTy env ty1 ty2
629 cmpTy env ty1 (NoteTy _ ty2) = cmpTy env ty1 ty2
631 -- Deal with equal constructors
632 cmpTy env (TyVarTy tv1) (TyVarTy tv2) = case lookupVarEnv env tv1 of
633 Just tv1a -> tv1a `compare` tv2
634 Nothing -> tv1 `compare` tv2
636 cmpTy env (SourceTy p1) (SourceTy p2) = cmpSourceTy env p1 p2
637 cmpTy env (AppTy f1 a1) (AppTy f2 a2) = cmpTy env f1 f2 `thenCmp` cmpTy env a1 a2
638 cmpTy env (FunTy f1 a1) (FunTy f2 a2) = cmpTy env f1 f2 `thenCmp` cmpTy env a1 a2
639 cmpTy env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` (cmpTys env tys1 tys2)
640 cmpTy env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTy (extendVarEnv env tv1 tv2) t1 t2
642 -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < SourceTy
643 cmpTy env (AppTy _ _) (TyVarTy _) = GT
645 cmpTy env (FunTy _ _) (TyVarTy _) = GT
646 cmpTy env (FunTy _ _) (AppTy _ _) = GT
648 cmpTy env (TyConApp _ _) (TyVarTy _) = GT
649 cmpTy env (TyConApp _ _) (AppTy _ _) = GT
650 cmpTy env (TyConApp _ _) (FunTy _ _) = GT
652 cmpTy env (ForAllTy _ _) (TyVarTy _) = GT
653 cmpTy env (ForAllTy _ _) (AppTy _ _) = GT
654 cmpTy env (ForAllTy _ _) (FunTy _ _) = GT
655 cmpTy env (ForAllTy _ _) (TyConApp _ _) = GT
657 cmpTy env (SourceTy _) t2 = GT
663 cmpSourceTy :: TyVarEnv TyVar -> SourceType -> SourceType -> Ordering
664 cmpSourceTy env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` (cmpTy env ty1 ty2)
665 -- Compare types as well as names for implicit parameters
666 -- This comparison is used exclusively (I think) for the
667 -- finite map built in TcSimplify
668 cmpSourceTy env (IParam _ _) sty = LT
670 cmpSourceTy env (ClassP _ _) (IParam _ _) = GT
671 cmpSourceTy env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTys env tys1 tys2)
672 cmpSourceTy env (ClassP _ _) (NType _ _) = LT
674 cmpSourceTy env (NType tc1 tys1) (NType tc2 tys2) = (tc1 `compare` tc2) `thenCmp` (cmpTys env tys1 tys2)
675 cmpSourceTy env (NType _ _) sty = GT
678 PredTypes are used as a FM key in TcSimplify,
679 so we take the easy path and make them an instance of Ord
682 instance Eq SourceType where { (==) = tcEqPred }
683 instance Ord SourceType where { compare = tcCmpPred }
687 %************************************************************************
689 \subsection{Predicates}
691 %************************************************************************
693 isSigmaTy returns true of any qualified type. It doesn't *necessarily* have
695 f :: (?x::Int) => Int -> Int
698 isSigmaTy :: Type -> Bool
699 isSigmaTy (ForAllTy tyvar ty) = True
700 isSigmaTy (FunTy a b) = isPredTy a
701 isSigmaTy (NoteTy n ty) = isSigmaTy ty
704 isOverloadedTy :: Type -> Bool
705 isOverloadedTy (ForAllTy tyvar ty) = isOverloadedTy ty
706 isOverloadedTy (FunTy a b) = isPredTy a
707 isOverloadedTy (NoteTy n ty) = isOverloadedTy ty
708 isOverloadedTy _ = False
712 isFloatTy = is_tc floatTyConKey
713 isDoubleTy = is_tc doubleTyConKey
714 isIntegerTy = is_tc integerTyConKey
715 isIntTy = is_tc intTyConKey
716 isAddrTy = is_tc addrTyConKey
717 isBoolTy = is_tc boolTyConKey
718 isUnitTy = is_tc unitTyConKey
720 is_tc :: Unique -> Type -> Bool
721 -- Newtypes are opaque to this
722 is_tc uniq ty = case tcSplitTyConApp_maybe ty of
723 Just (tc, _) -> uniq == getUnique tc
728 %************************************************************************
732 %************************************************************************
735 deNoteType :: Type -> Type
736 -- Remove synonyms, but not source types
737 deNoteType ty@(TyVarTy tyvar) = ty
738 deNoteType (TyConApp tycon tys) = TyConApp tycon (map deNoteType tys)
739 deNoteType (SourceTy p) = SourceTy (deNoteSourceType p)
740 deNoteType (NoteTy _ ty) = deNoteType ty
741 deNoteType (AppTy fun arg) = AppTy (deNoteType fun) (deNoteType arg)
742 deNoteType (FunTy fun arg) = FunTy (deNoteType fun) (deNoteType arg)
743 deNoteType (ForAllTy tv ty) = ForAllTy tv (deNoteType ty)
745 deNoteSourceType :: SourceType -> SourceType
746 deNoteSourceType (ClassP c tys) = ClassP c (map deNoteType tys)
747 deNoteSourceType (IParam n ty) = IParam n (deNoteType ty)
748 deNoteSourceType (NType tc tys) = NType tc (map deNoteType tys)
751 Find the free tycons and classes of a type. This is used in the front
755 tyClsNamesOfType :: Type -> NameSet
756 tyClsNamesOfType (TyVarTy tv) = emptyNameSet
757 tyClsNamesOfType (TyConApp tycon tys) = unitNameSet (getName tycon) `unionNameSets` tyClsNamesOfTypes tys
758 tyClsNamesOfType (NoteTy (SynNote ty1) ty2) = tyClsNamesOfType ty1
759 tyClsNamesOfType (NoteTy other_note ty2) = tyClsNamesOfType ty2
760 tyClsNamesOfType (SourceTy (IParam n ty)) = tyClsNamesOfType ty
761 tyClsNamesOfType (SourceTy (ClassP cl tys)) = unitNameSet (getName cl) `unionNameSets` tyClsNamesOfTypes tys
762 tyClsNamesOfType (SourceTy (NType tc tys)) = unitNameSet (getName tc) `unionNameSets` tyClsNamesOfTypes tys
763 tyClsNamesOfType (FunTy arg res) = tyClsNamesOfType arg `unionNameSets` tyClsNamesOfType res
764 tyClsNamesOfType (AppTy fun arg) = tyClsNamesOfType fun `unionNameSets` tyClsNamesOfType arg
765 tyClsNamesOfType (ForAllTy tyvar ty) = tyClsNamesOfType ty
767 tyClsNamesOfTypes tys = foldr (unionNameSets . tyClsNamesOfType) emptyNameSet tys
769 tyClsNamesOfDFunHead :: Type -> NameSet
770 -- Find the free type constructors and classes
771 -- of the head of the dfun instance type
772 -- The 'dfun_head_type' is because of
773 -- instance Foo a => Baz T where ...
774 -- The decl is an orphan if Baz and T are both not locally defined,
775 -- even if Foo *is* locally defined
776 tyClsNamesOfDFunHead dfun_ty
777 = case tcSplitSigmaTy dfun_ty of
778 (tvs,_,head_ty) -> tyClsNamesOfType head_ty
780 classNamesOfTheta :: ThetaType -> [Name]
781 -- Looks just for ClassP things; maybe it should check
782 classNamesOfTheta preds = [ getName c | ClassP c _ <- preds ]
786 %************************************************************************
788 \subsection[TysWiredIn-ext-type]{External types}
790 %************************************************************************
792 The compiler's foreign function interface supports the passing of a
793 restricted set of types as arguments and results (the restricting factor
797 isFFIArgumentTy :: DynFlags -> Safety -> Type -> Bool
798 -- Checks for valid argument type for a 'foreign import'
799 isFFIArgumentTy dflags safety ty
800 = checkRepTyCon (legalOutgoingTyCon dflags safety) ty
802 isFFIExternalTy :: Type -> Bool
803 -- Types that are allowed as arguments of a 'foreign export'
804 isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty
806 isFFIImportResultTy :: DynFlags -> Type -> Bool
807 isFFIImportResultTy dflags ty
808 = checkRepTyCon (legalFIResultTyCon dflags) ty
810 isFFIExportResultTy :: Type -> Bool
811 isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty
813 isFFIDynArgumentTy :: Type -> Bool
814 -- The argument type of a foreign import dynamic must be Ptr, FunPtr, Addr,
815 -- or a newtype of either.
816 isFFIDynArgumentTy = checkRepTyCon (\tc -> tc == ptrTyCon || tc == funPtrTyCon || tc == addrTyCon)
818 isFFIDynResultTy :: Type -> Bool
819 -- The result type of a foreign export dynamic must be Ptr, FunPtr, Addr,
820 -- or a newtype of either.
821 isFFIDynResultTy = checkRepTyCon (\tc -> tc == ptrTyCon || tc == funPtrTyCon || tc == addrTyCon)
823 isFFILabelTy :: Type -> Bool
824 -- The type of a foreign label must be Ptr, FunPtr, Addr,
825 -- or a newtype of either.
826 isFFILabelTy = checkRepTyCon (\tc -> tc == ptrTyCon || tc == funPtrTyCon || tc == addrTyCon)
828 checkRepTyCon :: (TyCon -> Bool) -> Type -> Bool
829 -- Look through newtypes
830 -- Non-recursive ones are transparent to splitTyConApp,
831 -- but recursive ones aren't; hence the splitNewType_maybe
832 checkRepTyCon check_tc ty
833 | Just (tc,_) <- splitTyConApp_maybe (repType ty) = check_tc tc
837 ----------------------------------------------
838 These chaps do the work; they are not exported
839 ----------------------------------------------
842 legalFEArgTyCon :: TyCon -> Bool
843 -- It's illegal to return foreign objects and (mutable)
844 -- bytearrays from a _ccall_ / foreign declaration
845 -- (or be passed them as arguments in foreign exported functions).
847 | getUnique tc `elem` [ byteArrayTyConKey, mutableByteArrayTyConKey ]
849 -- It's also illegal to make foreign exports that take unboxed
850 -- arguments. The RTS API currently can't invoke such things. --SDM 7/2000
852 = boxedMarshalableTyCon tc
854 legalFIResultTyCon :: DynFlags -> TyCon -> Bool
855 legalFIResultTyCon dflags tc
856 | getUnique tc `elem`
857 [ byteArrayTyConKey, mutableByteArrayTyConKey ] = False
858 | tc == unitTyCon = True
859 | otherwise = marshalableTyCon dflags tc
861 legalFEResultTyCon :: TyCon -> Bool
862 legalFEResultTyCon tc
863 | getUnique tc `elem`
864 [ byteArrayTyConKey, mutableByteArrayTyConKey ] = False
865 | tc == unitTyCon = True
866 | otherwise = boxedMarshalableTyCon tc
868 legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Bool
869 -- Checks validity of types going from Haskell -> external world
870 legalOutgoingTyCon dflags safety tc
871 | playSafe safety && getUnique tc `elem` [byteArrayTyConKey, mutableByteArrayTyConKey]
874 = marshalableTyCon dflags tc
876 marshalableTyCon dflags tc
877 = (dopt Opt_GlasgowExts dflags && isUnLiftedTyCon tc)
878 || boxedMarshalableTyCon tc
880 boxedMarshalableTyCon tc
881 = getUnique tc `elem` [ intTyConKey, int8TyConKey, int16TyConKey
882 , int32TyConKey, int64TyConKey
883 , wordTyConKey, word8TyConKey, word16TyConKey
884 , word32TyConKey, word64TyConKey
885 , floatTyConKey, doubleTyConKey
886 , addrTyConKey, ptrTyConKey, funPtrTyConKey
889 , byteArrayTyConKey, mutableByteArrayTyConKey
895 %************************************************************************
897 \subsection{Unification with an explicit substitution}
899 %************************************************************************
901 Unify types with an explicit substitution and no monad.
902 Ignore usage annotations.
906 = (TyVarSet, -- Set of template tyvars
907 TyVarSubstEnv) -- Not necessarily idempotent
909 unifyTysX :: TyVarSet -- Template tyvars
912 -> Maybe TyVarSubstEnv
913 unifyTysX tmpl_tyvars ty1 ty2
914 = uTysX ty1 ty2 (\(_,s) -> Just s) (tmpl_tyvars, emptySubstEnv)
916 unifyExtendTysX :: TyVarSet -- Template tyvars
917 -> TyVarSubstEnv -- Substitution to start with
920 -> Maybe TyVarSubstEnv -- Extended substitution
921 unifyExtendTysX tmpl_tyvars subst ty1 ty2
922 = uTysX ty1 ty2 (\(_,s) -> Just s) (tmpl_tyvars, subst)
924 unifyTyListsX :: TyVarSet -> [Type] -> [Type]
925 -> Maybe TyVarSubstEnv
926 unifyTyListsX tmpl_tyvars tys1 tys2
927 = uTyListsX tys1 tys2 (\(_,s) -> Just s) (tmpl_tyvars, emptySubstEnv)
932 -> (MySubst -> Maybe result)
936 uTysX (NoteTy _ ty1) ty2 k subst = uTysX ty1 ty2 k subst
937 uTysX ty1 (NoteTy _ ty2) k subst = uTysX ty1 ty2 k subst
939 -- Variables; go for uVar
940 uTysX (TyVarTy tyvar1) (TyVarTy tyvar2) k subst
943 uTysX (TyVarTy tyvar1) ty2 k subst@(tmpls,_)
944 | tyvar1 `elemVarSet` tmpls
945 = uVarX tyvar1 ty2 k subst
946 uTysX ty1 (TyVarTy tyvar2) k subst@(tmpls,_)
947 | tyvar2 `elemVarSet` tmpls
948 = uVarX tyvar2 ty1 k subst
951 uTysX (SourceTy (IParam n1 t1)) (SourceTy (IParam n2 t2)) k subst
952 | n1 == n2 = uTysX t1 t2 k subst
953 uTysX (SourceTy (ClassP c1 tys1)) (SourceTy (ClassP c2 tys2)) k subst
954 | c1 == c2 = uTyListsX tys1 tys2 k subst
955 uTysX (SourceTy (NType tc1 tys1)) (SourceTy (NType tc2 tys2)) k subst
956 | tc1 == tc2 = uTyListsX tys1 tys2 k subst
958 -- Functions; just check the two parts
959 uTysX (FunTy fun1 arg1) (FunTy fun2 arg2) k subst
960 = uTysX fun1 fun2 (uTysX arg1 arg2 k) subst
962 -- Type constructors must match
963 uTysX (TyConApp con1 tys1) (TyConApp con2 tys2) k subst
964 | (con1 == con2 && equalLength tys1 tys2)
965 = uTyListsX tys1 tys2 k subst
967 -- Applications need a bit of care!
968 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
969 -- NB: we've already dealt with type variables and Notes,
970 -- so if one type is an App the other one jolly well better be too
971 uTysX (AppTy s1 t1) ty2 k subst
972 = case tcSplitAppTy_maybe ty2 of
973 Just (s2, t2) -> uTysX s1 s2 (uTysX t1 t2 k) subst
974 Nothing -> Nothing -- Fail
976 uTysX ty1 (AppTy s2 t2) k subst
977 = case tcSplitAppTy_maybe ty1 of
978 Just (s1, t1) -> uTysX s1 s2 (uTysX t1 t2 k) subst
979 Nothing -> Nothing -- Fail
981 -- Not expecting for-alls in unification
983 uTysX (ForAllTy _ _) ty2 k subst = panic "Unify.uTysX subst:ForAllTy (1st arg)"
984 uTysX ty1 (ForAllTy _ _) k subst = panic "Unify.uTysX subst:ForAllTy (2nd arg)"
987 -- Anything else fails
988 uTysX ty1 ty2 k subst = Nothing
991 uTyListsX [] [] k subst = k subst
992 uTyListsX (ty1:tys1) (ty2:tys2) k subst = uTysX ty1 ty2 (uTyListsX tys1 tys2 k) subst
993 uTyListsX tys1 tys2 k subst = Nothing -- Fail if the lists are different lengths
997 -- Invariant: tv1 is a unifiable variable
998 uVarX tv1 ty2 k subst@(tmpls, env)
999 = case lookupSubstEnv env tv1 of
1000 Just (DoneTy ty1) -> -- Already bound
1001 uTysX ty1 ty2 k subst
1003 Nothing -- Not already bound
1004 | typeKind ty2 `eqKind` tyVarKind tv1
1005 && occur_check_ok ty2
1006 -> -- No kind mismatch nor occur check
1007 k (tmpls, extendSubstEnv env tv1 (DoneTy ty2))
1009 | otherwise -> Nothing -- Fail if kind mis-match or occur check
1011 occur_check_ok ty = all occur_check_ok_tv (varSetElems (tyVarsOfType ty))
1012 occur_check_ok_tv tv | tv1 == tv = False
1013 | otherwise = case lookupSubstEnv env tv of
1015 Just (DoneTy ty) -> occur_check_ok ty
1020 %************************************************************************
1022 \subsection{Matching on types}
1024 %************************************************************************
1026 Matching is a {\em unidirectional} process, matching a type against a
1027 template (which is just a type with type variables in it). The
1028 matcher assumes that there are no repeated type variables in the
1029 template, so that it simply returns a mapping of type variables to
1030 types. It also fails on nested foralls.
1032 @matchTys@ matches corresponding elements of a list of templates and
1033 types. It and @matchTy@ both ignore usage annotations, unlike the
1034 main function @match@.
1037 matchTy :: TyVarSet -- Template tyvars
1039 -> Type -- Proposed instance of template
1040 -> Maybe TyVarSubstEnv -- Matching substitution
1043 matchTys :: TyVarSet -- Template tyvars
1044 -> [Type] -- Templates
1045 -> [Type] -- Proposed instance of template
1046 -> Maybe (TyVarSubstEnv, -- Matching substitution
1047 [Type]) -- Left over instance types
1049 matchTy tmpls ty1 ty2 = match ty1 ty2 tmpls (\ senv -> Just senv) emptySubstEnv
1051 matchTys tmpls tys1 tys2 = match_list tys1 tys2 tmpls
1052 (\ (senv,tys) -> Just (senv,tys))
1056 @match@ is the main function. It takes a flag indicating whether
1057 usage annotations are to be respected.
1060 match :: Type -> Type -- Current match pair
1061 -> TyVarSet -- Template vars
1062 -> (TyVarSubstEnv -> Maybe result) -- Continuation
1063 -> TyVarSubstEnv -- Current subst
1066 -- When matching against a type variable, see if the variable
1067 -- has already been bound. If so, check that what it's bound to
1068 -- is the same as ty; if not, bind it and carry on.
1070 match (TyVarTy v) ty tmpls k senv
1071 | v `elemVarSet` tmpls
1072 = -- v is a template variable
1073 case lookupSubstEnv senv v of
1074 Nothing | typeKind ty `eqKind` tyVarKind v
1075 -- We do a kind check, just as in the uVarX above
1076 -- The kind check is needed to avoid bogus matches
1077 -- of (a b) with (c d), where the kinds don't match
1078 -- An occur check isn't needed when matching.
1079 -> k (extendSubstEnv senv v (DoneTy ty))
1081 | otherwise -> Nothing -- Fails
1083 Just (DoneTy ty') | ty' `tcEqType` ty -> k senv -- Succeeds
1084 | otherwise -> Nothing -- Fails
1087 = -- v is not a template variable; ty had better match
1088 -- Can't use (==) because types differ
1089 case tcGetTyVar_maybe ty of
1090 Just v' | v == v' -> k senv -- Success
1091 other -> Nothing -- Failure
1092 -- This tcGetTyVar_maybe is *required* because it must strip Notes.
1093 -- I guess the reason the Note-stripping case is *last* rather than first
1094 -- is to preserve type synonyms etc., so I'm not moving it to the
1095 -- top; but this means that (without the deNotetype) a type
1096 -- variable may not match the pattern (TyVarTy v') as one would
1097 -- expect, due to an intervening Note. KSW 2000-06.
1100 match (SourceTy (IParam n1 t1)) (SourceTy (IParam n2 t2)) tmpls k senv
1101 | n1 == n2 = match t1 t2 tmpls k senv
1102 match (SourceTy (ClassP c1 tys1)) (SourceTy (ClassP c2 tys2)) tmpls k senv
1103 | c1 == c2 = match_list_exactly tys1 tys2 tmpls k senv
1104 match (SourceTy (NType tc1 tys1)) (SourceTy (NType tc2 tys2)) tmpls k senv
1105 | tc1 == tc2 = match_list_exactly tys1 tys2 tmpls k senv
1107 -- Functions; just check the two parts
1108 match (FunTy arg1 res1) (FunTy arg2 res2) tmpls k senv
1109 = match arg1 arg2 tmpls (match res1 res2 tmpls k) senv
1111 match (AppTy fun1 arg1) ty2 tmpls k senv
1112 = case tcSplitAppTy_maybe ty2 of
1113 Just (fun2,arg2) -> match fun1 fun2 tmpls (match arg1 arg2 tmpls k) senv
1114 Nothing -> Nothing -- Fail
1116 match (TyConApp tc1 tys1) (TyConApp tc2 tys2) tmpls k senv
1117 | tc1 == tc2 = match_list_exactly tys1 tys2 tmpls k senv
1119 -- Newtypes are opaque; other source types should not happen
1120 match (SourceTy (NType tc1 tys1)) (SourceTy (NType tc2 tys2)) tmpls k senv
1121 | tc1 == tc2 = match_list_exactly tys1 tys2 tmpls k senv
1123 -- With type synonyms, we have to be careful for the exact
1124 -- same reasons as in the unifier. Please see the
1125 -- considerable commentary there before changing anything
1126 -- here! (WDP 95/05)
1127 match (NoteTy n1 ty1) ty2 tmpls k senv = match ty1 ty2 tmpls k senv
1128 match ty1 (NoteTy n2 ty2) tmpls k senv = match ty1 ty2 tmpls k senv
1131 match _ _ _ _ _ = Nothing
1133 match_list_exactly tys1 tys2 tmpls k senv
1134 = match_list tys1 tys2 tmpls k' senv
1136 k' (senv', tys2') | null tys2' = k senv' -- Succeed
1137 | otherwise = Nothing -- Fail
1139 match_list [] tys2 tmpls k senv = k (senv, tys2)
1140 match_list (ty1:tys1) [] tmpls k senv = Nothing -- Not enough arg tys => failure
1141 match_list (ty1:tys1) (ty2:tys2) tmpls k senv
1142 = match ty1 ty2 tmpls (match_list tys1 tys2 tmpls k) senv