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, TcTauType, TcPredType, TcThetaType, TcRhoType,
21 TcTyVar, TcTyVarSet, TcKind,
23 --------------------------------
25 TyVarDetails(..), isUserTyVar, isSkolemTyVar,
27 --------------------------------
31 --------------------------------
33 -- These are important because they do not look through newtypes
34 tcSplitForAllTys, tcSplitRhoTy,
35 tcSplitFunTy_maybe, tcSplitFunTys, tcFunArgTy, tcFunResultTy,
36 tcSplitTyConApp, tcSplitTyConApp_maybe, tcTyConAppTyCon, tcTyConAppArgs,
37 tcSplitAppTy_maybe, tcSplitAppTy, tcSplitSigmaTy,
38 tcSplitMethodTy, tcGetTyVar_maybe, tcGetTyVar,
40 ---------------------------------
42 -- Again, newtypes are opaque
43 tcEqType, tcEqPred, tcCmpType, tcCmpTypes, tcCmpPred,
44 isQualifiedTy, isOverloadedTy,
45 isDoubleTy, isFloatTy, isIntTy,
46 isIntegerTy, isAddrTy, isBoolTy, isUnitTy, isForeignPtrTy,
47 isTauTy, tcIsTyVarTy, tcIsForAllTy,
49 ---------------------------------
50 -- Misc type manipulators
51 hoistForAllTys, deNoteType,
52 namesOfType, namesOfDFunHead,
55 ---------------------------------
57 PredType, getClassPredTys_maybe, getClassPredTys,
58 isPredTy, isClassPred, isTyVarClassPred, predHasFDs,
59 mkDictTy, tcSplitPredTy_maybe, predTyUnique,
60 isDictTy, tcSplitDFunTy, predTyUnique,
61 mkClassPred, inheritablePred, isIPPred, mkPredName,
63 ---------------------------------
64 -- Foreign import and export
65 isFFIArgumentTy, -- :: DynFlags -> Safety -> Type -> Bool
66 isFFIImportResultTy, -- :: DynFlags -> Type -> Bool
67 isFFIExportResultTy, -- :: Type -> Bool
68 isFFIExternalTy, -- :: Type -> Bool
69 isFFIDynArgumentTy, -- :: Type -> Bool
70 isFFIDynResultTy, -- :: Type -> Bool
71 isFFILabelTy, -- :: Type -> Bool
73 ---------------------------------
74 -- Unifier and matcher
75 unifyTysX, unifyTyListsX, unifyExtendTysX,
77 matchTy, matchTys, match,
79 --------------------------------
80 -- Rexported from Type
81 Kind, -- Stuff to do with kinds is insensitive to pre/post Tc
82 unliftedTypeKind, liftedTypeKind, openTypeKind, mkArrowKind, mkArrowKinds,
83 superBoxity, liftedBoxity, hasMoreBoxityInfo, defaultKind, superKind,
86 Type, SourceType(..), PredType, ThetaType,
87 mkForAllTy, mkForAllTys,
88 mkFunTy, mkFunTys, zipFunTys,
89 mkTyConApp, mkAppTy, mkAppTys, mkSynTy, applyTy, applyTys,
90 mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys,
92 isUnLiftedType, -- Source types are always lifted
93 isUnboxedTupleType, -- Ditto
96 tidyTopType, tidyType, tidyPred, tidyTypes, tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
97 tidyTyVarBndr, tidyOpenTyVar, tidyOpenTyVars,
98 typeKind, eqKind, eqUsage,
100 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta
103 #include "HsVersions.h"
106 import {-# SOURCE #-} PprType( pprType )
109 import TypeRep ( Type(..), TyNote(..), funTyCon ) -- friend
110 import Type ( mkUTyM, unUTy ) -- Used locally
112 import Type ( -- Re-exports
113 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
114 Kind, Type, TauType, SourceType(..), PredType, ThetaType,
115 unliftedTypeKind, liftedTypeKind, openTypeKind, mkArrowKind, mkArrowKinds,
116 mkForAllTy, mkForAllTys, defaultKind, isTypeKind,
117 mkFunTy, mkFunTys, zipFunTys,
118 mkTyConApp, mkAppTy, mkAppTys, mkSynTy, applyTy, applyTys,
119 mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys,
120 isUnLiftedType, isUnboxedTupleType, isPrimitiveType,
121 splitNewType_maybe, splitTyConApp_maybe,
122 tidyTopType, tidyType, tidyPred, tidyTypes, tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
123 tidyTyVarBndr, tidyOpenTyVar, tidyOpenTyVars, eqKind, eqUsage,
124 hasMoreBoxityInfo, liftedBoxity, superBoxity, typeKind, superKind
126 import TyCon ( TyCon, isUnLiftedTyCon )
127 import Class ( classHasFDs, Class )
128 import Var ( TyVar, tyVarKind )
129 import ForeignCall ( Safety, playSafe )
134 import CmdLineOpts ( DynFlags, DynFlag( Opt_GlasgowExts ), dopt )
135 import Name ( Name, NamedThing(..), mkLocalName )
136 import OccName ( OccName, mkDictOcc )
138 import PrelNames -- Lots (e.g. in isFFIArgumentTy)
139 import TysWiredIn ( ptrTyCon, funPtrTyCon, addrTyCon, unitTyCon )
140 import Unique ( Unique, Uniquable(..) )
141 import SrcLoc ( SrcLoc )
142 import Util ( cmpList, thenCmp, equalLength )
143 import Maybes ( maybeToBool, expectJust )
148 %************************************************************************
152 %************************************************************************
155 type TcTyVar = TyVar -- Might be a mutable tyvar
156 type TcTyVarSet = TyVarSet
158 type TcType = Type -- A TcType can have mutable type variables
159 -- Invariant on ForAllTy in TcTypes:
161 -- a cannot occur inside a MutTyVar in T; that is,
162 -- T is "flattened" before quantifying over a
164 type TcPredType = PredType
165 type TcThetaType = ThetaType
166 type TcRhoType = Type
167 type TcTauType = TauType
172 %************************************************************************
174 \subsection{TyVarDetails}
176 %************************************************************************
178 TyVarDetails gives extra info about type variables, used during type
179 checking. It's attached to mutable type variables only.
183 = SigTv -- Introduced when instantiating a type signature,
184 -- prior to checking that the defn of a fn does
185 -- have the expected type. Should not be instantiated.
187 -- f :: forall a. a -> a
189 -- When checking e, with expected type (a->a), we
190 -- should not instantiate a
192 | ClsTv -- Scoped type variable introduced by a class decl
193 -- class C a where ...
195 | InstTv -- Ditto, but instance decl
197 | PatSigTv -- Scoped type variable, introduced by a pattern
201 | VanillaTv -- Everything else
203 isUserTyVar :: TyVarDetails -> Bool -- Avoid unifying these if possible
204 isUserTyVar VanillaTv = False
205 isUserTyVar other = True
207 isSkolemTyVar :: TyVarDetails -> Bool
208 isSkolemTyVar SigTv = True
209 isSkolemTyVar other = False
211 instance Outputable TyVarDetails where
212 ppr SigTv = ptext SLIT("type signature")
213 ppr ClsTv = ptext SLIT("class declaration")
214 ppr InstTv = ptext SLIT("instance declaration")
215 ppr PatSigTv = ptext SLIT("pattern type signature")
216 ppr VanillaTv = ptext SLIT("???")
220 %************************************************************************
222 \subsection{Tau, sigma and rho}
224 %************************************************************************
227 mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkRhoTy theta tau)
229 mkRhoTy :: [SourceType] -> Type -> Type
230 mkRhoTy theta ty = UASSERT2( not (isUTy ty), pprType ty )
231 foldr (\p r -> FunTy (mkUTyM (mkPredTy p)) (mkUTyM r)) ty theta
236 @isTauTy@ tests for nested for-alls.
239 isTauTy :: Type -> Bool
240 isTauTy (TyVarTy v) = True
241 isTauTy (TyConApp _ tys) = all isTauTy tys
242 isTauTy (AppTy a b) = isTauTy a && isTauTy b
243 isTauTy (FunTy a b) = isTauTy a && isTauTy b
244 isTauTy (SourceTy p) = True -- Don't look through source types
245 isTauTy (NoteTy _ ty) = isTauTy ty
246 isTauTy (UsageTy _ ty) = isTauTy ty
247 isTauTy other = False
251 getDFunTyKey :: Type -> OccName -- Get some string from a type, to be used to
252 -- construct a dictionary function name
253 getDFunTyKey (TyVarTy tv) = getOccName tv
254 getDFunTyKey (TyConApp tc _) = getOccName tc
255 getDFunTyKey (AppTy fun _) = getDFunTyKey fun
256 getDFunTyKey (NoteTy _ t) = getDFunTyKey t
257 getDFunTyKey (FunTy arg _) = getOccName funTyCon
258 getDFunTyKey (ForAllTy _ t) = getDFunTyKey t
259 getDFunTyKey (UsageTy _ t) = getDFunTyKey t
260 getDFunTyKey (SourceTy (NType tc _)) = getOccName tc -- Newtypes are quite reasonable
261 getDFunTyKey ty = pprPanic "getDFunTyKey" (pprType ty)
262 -- SourceTy shouldn't happen
266 %************************************************************************
268 \subsection{Expanding and splitting}
270 %************************************************************************
272 These tcSplit functions are like their non-Tc analogues, but
273 a) they do not look through newtypes
274 b) they do not look through PredTys
275 c) [future] they ignore usage-type annotations
277 However, they are non-monadic and do not follow through mutable type
278 variables. It's up to you to make sure this doesn't matter.
281 tcSplitForAllTys :: Type -> ([TyVar], Type)
282 tcSplitForAllTys ty = split ty ty []
284 split orig_ty (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
285 split orig_ty (NoteTy n ty) tvs = split orig_ty ty tvs
286 split orig_ty (UsageTy _ ty) tvs = split orig_ty ty tvs
287 split orig_ty t tvs = (reverse tvs, orig_ty)
289 tcIsForAllTy (ForAllTy tv ty) = True
290 tcIsForAllTy (NoteTy n ty) = tcIsForAllTy ty
291 tcIsForAllTy (UsageTy n ty) = tcIsForAllTy ty
292 tcIsForAllTy t = False
294 tcSplitRhoTy :: Type -> ([PredType], Type)
295 tcSplitRhoTy ty = split ty ty []
297 split orig_ty (FunTy arg res) ts = case tcSplitPredTy_maybe arg of
298 Just p -> split res res (p:ts)
299 Nothing -> (reverse ts, orig_ty)
300 split orig_ty (NoteTy n ty) ts = split orig_ty ty ts
301 split orig_ty (UsageTy _ ty) ts = split orig_ty ty ts
302 split orig_ty ty ts = (reverse ts, orig_ty)
304 tcSplitSigmaTy ty = case tcSplitForAllTys ty of
305 (tvs, rho) -> case tcSplitRhoTy rho of
306 (theta, tau) -> (tvs, theta, tau)
308 tcTyConAppTyCon :: Type -> TyCon
309 tcTyConAppTyCon ty = fst (tcSplitTyConApp ty)
311 tcTyConAppArgs :: Type -> [Type]
312 tcTyConAppArgs ty = snd (tcSplitTyConApp ty)
314 tcSplitTyConApp :: Type -> (TyCon, [Type])
315 tcSplitTyConApp ty = case tcSplitTyConApp_maybe ty of
317 Nothing -> pprPanic "tcSplitTyConApp" (pprType ty)
319 tcSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
320 -- Newtypes are opaque, so they may be split
321 tcSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
322 tcSplitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [unUTy arg,unUTy res])
323 tcSplitTyConApp_maybe (NoteTy n ty) = tcSplitTyConApp_maybe ty
324 tcSplitTyConApp_maybe (UsageTy _ ty) = tcSplitTyConApp_maybe ty
325 tcSplitTyConApp_maybe (SourceTy (NType tc tys)) = Just (tc,tys)
326 -- However, predicates are not treated
327 -- as tycon applications by the type checker
328 tcSplitTyConApp_maybe other = Nothing
330 tcSplitFunTys :: Type -> ([Type], Type)
331 tcSplitFunTys ty = case tcSplitFunTy_maybe ty of
333 Just (arg,res) -> (arg:args, res')
335 (args,res') = tcSplitFunTys res
337 tcSplitFunTy_maybe :: Type -> Maybe (Type, Type)
338 tcSplitFunTy_maybe (FunTy arg res) = Just (arg, res)
339 tcSplitFunTy_maybe (NoteTy n ty) = tcSplitFunTy_maybe ty
340 tcSplitFunTy_maybe (UsageTy _ ty) = tcSplitFunTy_maybe ty
341 tcSplitFunTy_maybe other = Nothing
343 tcFunArgTy ty = case tcSplitFunTy_maybe ty of { Just (arg,res) -> arg }
344 tcFunResultTy ty = case tcSplitFunTy_maybe ty of { Just (arg,res) -> res }
347 tcSplitAppTy_maybe :: Type -> Maybe (Type, Type)
348 tcSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [unUTy ty1], unUTy ty2)
349 tcSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
350 tcSplitAppTy_maybe (NoteTy n ty) = tcSplitAppTy_maybe ty
351 tcSplitAppTy_maybe (UsageTy _ ty) = tcSplitAppTy_maybe ty
352 tcSplitAppTy_maybe (SourceTy (NType tc tys)) = tc_split_app tc tys
353 --- Don't forget that newtype!
354 tcSplitAppTy_maybe (TyConApp tc tys) = tc_split_app tc tys
355 tcSplitAppTy_maybe other = Nothing
357 tc_split_app tc [] = Nothing
358 tc_split_app tc tys = split tys []
360 split [ty2] acc = Just (TyConApp tc (reverse acc), ty2)
361 split (ty:tys) acc = split tys (ty:acc)
363 tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
365 Nothing -> pprPanic "tcSplitAppTy" (pprType ty)
367 tcGetTyVar_maybe :: Type -> Maybe TyVar
368 tcGetTyVar_maybe (TyVarTy tv) = Just tv
369 tcGetTyVar_maybe (NoteTy _ t) = tcGetTyVar_maybe t
370 tcGetTyVar_maybe ty@(UsageTy _ _) = pprPanic "tcGetTyVar_maybe: UTy:" (pprType ty)
371 tcGetTyVar_maybe other = Nothing
373 tcGetTyVar :: String -> Type -> TyVar
374 tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty)
376 tcIsTyVarTy :: Type -> Bool
377 tcIsTyVarTy ty = maybeToBool (tcGetTyVar_maybe ty)
380 The type of a method for class C is always of the form:
381 Forall a1..an. C a1..an => sig_ty
382 where sig_ty is the type given by the method's signature, and thus in general
383 is a ForallTy. At the point that splitMethodTy is called, it is expected
384 that the outer Forall has already been stripped off. splitMethodTy then
385 returns (C a1..an, sig_ty') where sig_ty' is sig_ty with any Notes or
389 tcSplitMethodTy :: Type -> (PredType, Type)
390 tcSplitMethodTy ty = split ty
392 split (FunTy arg res) = case tcSplitPredTy_maybe arg of
394 Nothing -> panic "splitMethodTy"
395 split (NoteTy n ty) = split ty
396 split (UsageTy _ ty) = split ty
397 split _ = panic "splitMethodTy"
399 tcSplitDFunTy :: Type -> ([TyVar], [SourceType], Class, [Type])
400 -- Split the type of a dictionary function
402 = case tcSplitSigmaTy ty of { (tvs, theta, tau) ->
403 case tcSplitPredTy_maybe tau of { Just (ClassP clas tys) ->
404 (tvs, theta, clas, tys) }}
408 %************************************************************************
410 \subsection{Predicate types}
412 %************************************************************************
414 "Predicates" are particular source types, namelyClassP or IParams
417 isPred :: SourceType -> Bool
418 isPred (ClassP _ _) = True
419 isPred (IParam _ _) = True
420 isPred (NType _ __) = False
422 isPredTy :: Type -> Bool
423 isPredTy (NoteTy _ ty) = isPredTy ty
424 isPredTy (UsageTy _ ty) = isPredTy ty
425 isPredTy (SourceTy sty) = isPred sty
428 tcSplitPredTy_maybe :: Type -> Maybe PredType
429 -- Returns Just for predicates only
430 tcSplitPredTy_maybe (NoteTy _ ty) = tcSplitPredTy_maybe ty
431 tcSplitPredTy_maybe (UsageTy _ ty) = tcSplitPredTy_maybe ty
432 tcSplitPredTy_maybe (SourceTy p) | isPred p = Just p
433 tcSplitPredTy_maybe other = Nothing
435 predTyUnique :: PredType -> Unique
436 predTyUnique (IParam n _) = getUnique n
437 predTyUnique (ClassP clas tys) = getUnique clas
439 predHasFDs :: PredType -> Bool
440 -- True if the predicate has functional depenencies;
441 -- I.e. should participate in improvement
442 predHasFDs (IParam _ _) = True
443 predHasFDs (ClassP cls _) = classHasFDs cls
445 mkPredName :: Unique -> SrcLoc -> SourceType -> Name
446 mkPredName uniq loc (ClassP cls tys) = mkLocalName uniq (mkDictOcc (getOccName cls)) loc
447 mkPredName uniq loc (IParam name ty) = name
451 --------------------- Dictionary types ---------------------------------
454 mkClassPred clas tys = UASSERT2( not (any isUTy tys), ppr clas <+> fsep (map pprType tys) )
457 isClassPred :: SourceType -> Bool
458 isClassPred (ClassP clas tys) = True
459 isClassPred other = False
461 isTyVarClassPred (ClassP clas tys) = all tcIsTyVarTy tys
462 isTyVarClassPred other = False
464 getClassPredTys_maybe :: SourceType -> Maybe (Class, [Type])
465 getClassPredTys_maybe (ClassP clas tys) = Just (clas, tys)
466 getClassPredTys_maybe _ = Nothing
468 getClassPredTys :: PredType -> (Class, [Type])
469 getClassPredTys (ClassP clas tys) = (clas, tys)
471 mkDictTy :: Class -> [Type] -> Type
472 mkDictTy clas tys = UASSERT2( not (any isUTy tys), ppr clas <+> fsep (map pprType tys) )
473 mkPredTy (ClassP clas tys)
475 isDictTy :: Type -> Bool
476 isDictTy (SourceTy p) = isClassPred p
477 isDictTy (NoteTy _ ty) = isDictTy ty
478 isDictTy (UsageTy _ ty) = isDictTy ty
479 isDictTy other = False
482 --------------------- Implicit parameters ---------------------------------
485 isIPPred :: SourceType -> Bool
486 isIPPred (IParam _ _) = True
487 isIPPred other = False
489 inheritablePred :: PredType -> Bool
490 -- Can be inherited by a context. For example, consider
491 -- f x = let g y = (?v, y+x)
492 -- in (g 3 with ?v = 8,
494 -- The point is that g's type must be quantifed over ?v:
495 -- g :: (?v :: a) => a -> a
496 -- but it doesn't need to be quantified over the Num a dictionary
497 -- which can be free in g's rhs, and shared by both calls to g
498 inheritablePred (ClassP _ _) = True
499 inheritablePred other = False
503 %************************************************************************
505 \subsection{Comparison}
507 %************************************************************************
509 Comparison, taking note of newtypes, predicates, etc,
510 But ignoring usage types
513 tcEqType :: Type -> Type -> Bool
514 tcEqType ty1 ty2 = case ty1 `tcCmpType` ty2 of { EQ -> True; other -> False }
516 tcEqPred :: PredType -> PredType -> Bool
517 tcEqPred p1 p2 = case p1 `tcCmpPred` p2 of { EQ -> True; other -> False }
520 tcCmpType :: Type -> Type -> Ordering
521 tcCmpType ty1 ty2 = cmpTy emptyVarEnv ty1 ty2
523 tcCmpTypes tys1 tys2 = cmpTys emptyVarEnv tys1 tys2
525 tcCmpPred p1 p2 = cmpSourceTy emptyVarEnv p1 p2
527 cmpTys env tys1 tys2 = cmpList (cmpTy env) tys1 tys2
530 cmpTy :: TyVarEnv TyVar -> Type -> Type -> Ordering
531 -- The "env" maps type variables in ty1 to type variables in ty2
532 -- So when comparing for-alls.. (forall tv1 . t1) (forall tv2 . t2)
533 -- we in effect substitute tv2 for tv1 in t1 before continuing
535 -- Look through NoteTy and UsageTy
536 cmpTy env (NoteTy _ ty1) ty2 = cmpTy env ty1 ty2
537 cmpTy env ty1 (NoteTy _ ty2) = cmpTy env ty1 ty2
538 cmpTy env (UsageTy _ ty1) ty2 = cmpTy env ty1 ty2
539 cmpTy env ty1 (UsageTy _ ty2) = cmpTy env ty1 ty2
541 -- Deal with equal constructors
542 cmpTy env (TyVarTy tv1) (TyVarTy tv2) = case lookupVarEnv env tv1 of
543 Just tv1a -> tv1a `compare` tv2
544 Nothing -> tv1 `compare` tv2
546 cmpTy env (SourceTy p1) (SourceTy p2) = cmpSourceTy env p1 p2
547 cmpTy env (AppTy f1 a1) (AppTy f2 a2) = cmpTy env f1 f2 `thenCmp` cmpTy env a1 a2
548 cmpTy env (FunTy f1 a1) (FunTy f2 a2) = cmpTy env f1 f2 `thenCmp` cmpTy env a1 a2
549 cmpTy env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` (cmpTys env tys1 tys2)
550 cmpTy env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTy (extendVarEnv env tv1 tv2) t1 t2
552 -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < SourceTy
553 cmpTy env (AppTy _ _) (TyVarTy _) = GT
555 cmpTy env (FunTy _ _) (TyVarTy _) = GT
556 cmpTy env (FunTy _ _) (AppTy _ _) = GT
558 cmpTy env (TyConApp _ _) (TyVarTy _) = GT
559 cmpTy env (TyConApp _ _) (AppTy _ _) = GT
560 cmpTy env (TyConApp _ _) (FunTy _ _) = GT
562 cmpTy env (ForAllTy _ _) (TyVarTy _) = GT
563 cmpTy env (ForAllTy _ _) (AppTy _ _) = GT
564 cmpTy env (ForAllTy _ _) (FunTy _ _) = GT
565 cmpTy env (ForAllTy _ _) (TyConApp _ _) = GT
567 cmpTy env (SourceTy _) t2 = GT
573 cmpSourceTy :: TyVarEnv TyVar -> SourceType -> SourceType -> Ordering
574 cmpSourceTy env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` (cmpTy env ty1 ty2)
575 -- Compare types as well as names for implicit parameters
576 -- This comparison is used exclusively (I think) for the
577 -- finite map built in TcSimplify
578 cmpSourceTy env (IParam _ _) sty = LT
580 cmpSourceTy env (ClassP _ _) (IParam _ _) = GT
581 cmpSourceTy env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTys env tys1 tys2)
582 cmpSourceTy env (ClassP _ _) (NType _ _) = LT
584 cmpSourceTy env (NType tc1 tys1) (NType tc2 tys2) = (tc1 `compare` tc2) `thenCmp` (cmpTys env tys1 tys2)
585 cmpSourceTy env (NType _ _) sty = GT
588 PredTypes are used as a FM key in TcSimplify,
589 so we take the easy path and make them an instance of Ord
592 instance Eq SourceType where { (==) = tcEqPred }
593 instance Ord SourceType where { compare = tcCmpPred }
597 %************************************************************************
599 \subsection{Predicates}
601 %************************************************************************
603 isQualifiedTy returns true of any qualified type. It doesn't *necessarily* have
605 f :: (?x::Int) => Int -> Int
608 isQualifiedTy :: Type -> Bool
609 isQualifiedTy (ForAllTy tyvar ty) = True
610 isQualifiedTy (FunTy a b) = isPredTy a
611 isQualifiedTy (NoteTy n ty) = isQualifiedTy ty
612 isQualifiedTy (UsageTy _ ty) = isQualifiedTy ty
613 isQualifiedTy _ = False
615 isOverloadedTy :: Type -> Bool
616 isOverloadedTy (ForAllTy tyvar ty) = isOverloadedTy ty
617 isOverloadedTy (FunTy a b) = isPredTy a
618 isOverloadedTy (NoteTy n ty) = isOverloadedTy ty
619 isOverloadedTy (UsageTy _ ty) = isOverloadedTy ty
620 isOverloadedTy _ = False
624 isFloatTy = is_tc floatTyConKey
625 isDoubleTy = is_tc doubleTyConKey
626 isForeignPtrTy = is_tc foreignPtrTyConKey
627 isIntegerTy = is_tc integerTyConKey
628 isIntTy = is_tc intTyConKey
629 isAddrTy = is_tc addrTyConKey
630 isBoolTy = is_tc boolTyConKey
631 isUnitTy = is_tc unitTyConKey
633 is_tc :: Unique -> Type -> Bool
634 -- Newtypes are opaque to this
635 is_tc uniq ty = case tcSplitTyConApp_maybe ty of
636 Just (tc, _) -> uniq == getUnique tc
641 %************************************************************************
645 %************************************************************************
648 hoistForAllTys :: Type -> Type
649 -- Move all the foralls to the top
650 -- e.g. T -> forall a. a ==> forall a. T -> a
651 -- Careful: LOSES USAGE ANNOTATIONS!
653 = case hoist ty of { (tvs, body) -> mkForAllTys tvs body }
655 hoist :: Type -> ([TyVar], Type)
656 hoist ty = case tcSplitFunTys ty of { (args, res) ->
657 case tcSplitForAllTys res of {
658 ([], body) -> ([], ty) ;
659 (tvs1, body1) -> case hoist body1 of { (tvs2,body2) ->
660 (tvs1 ++ tvs2, mkFunTys args body2)
666 deNoteType :: Type -> Type
667 -- Remove synonyms, but not source types
668 deNoteType ty@(TyVarTy tyvar) = ty
669 deNoteType (TyConApp tycon tys) = TyConApp tycon (map deNoteType tys)
670 deNoteType (SourceTy p) = SourceTy (deNoteSourceType p)
671 deNoteType (NoteTy _ ty) = deNoteType ty
672 deNoteType (AppTy fun arg) = AppTy (deNoteType fun) (deNoteType arg)
673 deNoteType (FunTy fun arg) = FunTy (deNoteType fun) (deNoteType arg)
674 deNoteType (ForAllTy tv ty) = ForAllTy tv (deNoteType ty)
675 deNoteType (UsageTy u ty) = UsageTy u (deNoteType ty)
677 deNoteSourceType :: SourceType -> SourceType
678 deNoteSourceType (ClassP c tys) = ClassP c (map deNoteType tys)
679 deNoteSourceType (IParam n ty) = IParam n (deNoteType ty)
680 deNoteSourceType (NType tc tys) = NType tc (map deNoteType tys)
683 Find the free names of a type, including the type constructors and classes it mentions
684 This is used in the front end of the compiler
687 namesOfType :: Type -> NameSet
688 namesOfType (TyVarTy tv) = unitNameSet (getName tv)
689 namesOfType (TyConApp tycon tys) = unitNameSet (getName tycon) `unionNameSets` namesOfTypes tys
690 namesOfType (NoteTy (SynNote ty1) ty2) = namesOfType ty1
691 namesOfType (NoteTy other_note ty2) = namesOfType ty2
692 namesOfType (SourceTy (IParam n ty)) = namesOfType ty
693 namesOfType (SourceTy (ClassP cl tys)) = unitNameSet (getName cl) `unionNameSets` namesOfTypes tys
694 namesOfType (SourceTy (NType tc tys)) = unitNameSet (getName tc) `unionNameSets` namesOfTypes tys
695 namesOfType (FunTy arg res) = namesOfType arg `unionNameSets` namesOfType res
696 namesOfType (AppTy fun arg) = namesOfType fun `unionNameSets` namesOfType arg
697 namesOfType (ForAllTy tyvar ty) = namesOfType ty `delFromNameSet` getName tyvar
698 namesOfType (UsageTy u ty) = namesOfType u `unionNameSets` namesOfType ty
700 namesOfTypes tys = foldr (unionNameSets . namesOfType) emptyNameSet tys
702 namesOfDFunHead :: Type -> NameSet
703 -- Find the free type constructors and classes
704 -- of the head of the dfun instance type
705 -- The 'dfun_head_type' is because of
706 -- instance Foo a => Baz T where ...
707 -- The decl is an orphan if Baz and T are both not locally defined,
708 -- even if Foo *is* locally defined
709 namesOfDFunHead dfun_ty = case tcSplitSigmaTy dfun_ty of
710 (tvs,_,head_ty) -> delListFromNameSet (namesOfType head_ty)
715 %************************************************************************
717 \subsection[TysWiredIn-ext-type]{External types}
719 %************************************************************************
721 The compiler's foreign function interface supports the passing of a
722 restricted set of types as arguments and results (the restricting factor
726 isFFIArgumentTy :: DynFlags -> Safety -> Type -> Bool
727 -- Checks for valid argument type for a 'foreign import'
728 isFFIArgumentTy dflags safety ty
729 = checkRepTyCon (legalOutgoingTyCon dflags safety) ty
731 isFFIExternalTy :: Type -> Bool
732 -- Types that are allowed as arguments of a 'foreign export'
733 isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty
735 isFFIImportResultTy :: DynFlags -> Type -> Bool
736 isFFIImportResultTy dflags ty
737 = checkRepTyCon (legalFIResultTyCon dflags) ty
739 isFFIExportResultTy :: Type -> Bool
740 isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty
742 isFFIDynArgumentTy :: Type -> Bool
743 -- The argument type of a foreign import dynamic must be Ptr, FunPtr, Addr,
744 -- or a newtype of either.
745 isFFIDynArgumentTy = checkRepTyCon (\tc -> tc == ptrTyCon || tc == funPtrTyCon || tc == addrTyCon)
747 isFFIDynResultTy :: Type -> Bool
748 -- The result type of a foreign export dynamic must be Ptr, FunPtr, Addr,
749 -- or a newtype of either.
750 isFFIDynResultTy = checkRepTyCon (\tc -> tc == ptrTyCon || tc == funPtrTyCon || tc == addrTyCon)
752 isFFILabelTy :: Type -> Bool
753 -- The type of a foreign label must be Ptr, FunPtr, Addr,
754 -- or a newtype of either.
755 isFFILabelTy = checkRepTyCon (\tc -> tc == ptrTyCon || tc == funPtrTyCon || tc == addrTyCon)
757 checkRepTyCon :: (TyCon -> Bool) -> Type -> Bool
758 -- Look through newtypes
759 -- Non-recursive ones are transparent to splitTyConApp,
760 -- but recursive ones aren't; hence the splitNewType_maybe
761 checkRepTyCon check_tc ty
762 | Just ty' <- splitNewType_maybe ty = checkRepTyCon check_tc ty'
763 | Just (tc,_) <- splitTyConApp_maybe ty = check_tc tc
767 ----------------------------------------------
768 These chaps do the work; they are not exported
769 ----------------------------------------------
772 legalFEArgTyCon :: TyCon -> Bool
773 -- It's illegal to return foreign objects and (mutable)
774 -- bytearrays from a _ccall_ / foreign declaration
775 -- (or be passed them as arguments in foreign exported functions).
777 | getUnique tc `elem` [ foreignObjTyConKey, foreignPtrTyConKey,
778 byteArrayTyConKey, mutableByteArrayTyConKey ]
780 -- It's also illegal to make foreign exports that take unboxed
781 -- arguments. The RTS API currently can't invoke such things. --SDM 7/2000
783 = boxedMarshalableTyCon tc
785 legalFIResultTyCon :: DynFlags -> TyCon -> Bool
786 legalFIResultTyCon dflags tc
787 | getUnique tc `elem`
788 [ foreignObjTyConKey, foreignPtrTyConKey,
789 byteArrayTyConKey, mutableByteArrayTyConKey ] = False
790 | tc == unitTyCon = True
791 | otherwise = marshalableTyCon dflags tc
793 legalFEResultTyCon :: TyCon -> Bool
794 legalFEResultTyCon tc
795 | getUnique tc `elem`
796 [ foreignObjTyConKey, foreignPtrTyConKey,
797 byteArrayTyConKey, mutableByteArrayTyConKey ] = False
798 | tc == unitTyCon = True
799 | otherwise = boxedMarshalableTyCon tc
801 legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Bool
802 -- Checks validity of types going from Haskell -> external world
803 legalOutgoingTyCon dflags safety tc
804 | playSafe safety && getUnique tc `elem` [byteArrayTyConKey, mutableByteArrayTyConKey]
807 = marshalableTyCon dflags tc
809 marshalableTyCon dflags tc
810 = (dopt Opt_GlasgowExts dflags && isUnLiftedTyCon tc)
811 || boxedMarshalableTyCon tc
813 boxedMarshalableTyCon tc
814 = getUnique tc `elem` [ intTyConKey, int8TyConKey, int16TyConKey
815 , int32TyConKey, int64TyConKey
816 , wordTyConKey, word8TyConKey, word16TyConKey
817 , word32TyConKey, word64TyConKey
818 , floatTyConKey, doubleTyConKey
819 , addrTyConKey, ptrTyConKey, funPtrTyConKey
820 , charTyConKey, foreignObjTyConKey
823 , byteArrayTyConKey, mutableByteArrayTyConKey
829 %************************************************************************
831 \subsection{Unification with an explicit substitution}
833 %************************************************************************
835 (allDistinctTyVars tys tvs) = True
837 all the types tys are type variables,
838 distinct from each other and from tvs.
840 This is useful when checking that unification hasn't unified signature
841 type variables. For example, if the type sig is
842 f :: forall a b. a -> b -> b
843 we want to check that 'a' and 'b' havn't
844 (a) been unified with a non-tyvar type
845 (b) been unified with each other (all distinct)
846 (c) been unified with a variable free in the environment
849 allDistinctTyVars :: [Type] -> TyVarSet -> Bool
851 allDistinctTyVars [] acc
853 allDistinctTyVars (ty:tys) acc
854 = case tcGetTyVar_maybe ty of
855 Nothing -> False -- (a)
856 Just tv | tv `elemVarSet` acc -> False -- (b) or (c)
857 | otherwise -> allDistinctTyVars tys (acc `extendVarSet` tv)
861 %************************************************************************
863 \subsection{Unification with an explicit substitution}
865 %************************************************************************
867 Unify types with an explicit substitution and no monad.
868 Ignore usage annotations.
872 = (TyVarSet, -- Set of template tyvars
873 TyVarSubstEnv) -- Not necessarily idempotent
875 unifyTysX :: TyVarSet -- Template tyvars
878 -> Maybe TyVarSubstEnv
879 unifyTysX tmpl_tyvars ty1 ty2
880 = uTysX ty1 ty2 (\(_,s) -> Just s) (tmpl_tyvars, emptySubstEnv)
882 unifyExtendTysX :: TyVarSet -- Template tyvars
883 -> TyVarSubstEnv -- Substitution to start with
886 -> Maybe TyVarSubstEnv -- Extended substitution
887 unifyExtendTysX tmpl_tyvars subst ty1 ty2
888 = uTysX ty1 ty2 (\(_,s) -> Just s) (tmpl_tyvars, subst)
890 unifyTyListsX :: TyVarSet -> [Type] -> [Type]
891 -> Maybe TyVarSubstEnv
892 unifyTyListsX tmpl_tyvars tys1 tys2
893 = uTyListsX tys1 tys2 (\(_,s) -> Just s) (tmpl_tyvars, emptySubstEnv)
898 -> (MySubst -> Maybe result)
902 uTysX (NoteTy _ ty1) ty2 k subst = uTysX ty1 ty2 k subst
903 uTysX ty1 (NoteTy _ ty2) k subst = uTysX ty1 ty2 k subst
905 -- Variables; go for uVar
906 uTysX (TyVarTy tyvar1) (TyVarTy tyvar2) k subst
909 uTysX (TyVarTy tyvar1) ty2 k subst@(tmpls,_)
910 | tyvar1 `elemVarSet` tmpls
911 = uVarX tyvar1 ty2 k subst
912 uTysX ty1 (TyVarTy tyvar2) k subst@(tmpls,_)
913 | tyvar2 `elemVarSet` tmpls
914 = uVarX tyvar2 ty1 k subst
917 uTysX (SourceTy (IParam n1 t1)) (SourceTy (IParam n2 t2)) k subst
918 | n1 == n2 = uTysX t1 t2 k subst
919 uTysX (SourceTy (ClassP c1 tys1)) (SourceTy (ClassP c2 tys2)) k subst
920 | c1 == c2 = uTyListsX tys1 tys2 k subst
921 uTysX (SourceTy (NType tc1 tys1)) (SourceTy (NType tc2 tys2)) k subst
922 | tc1 == tc2 = uTyListsX tys1 tys2 k subst
924 -- Functions; just check the two parts
925 uTysX (FunTy fun1 arg1) (FunTy fun2 arg2) k subst
926 = uTysX fun1 fun2 (uTysX arg1 arg2 k) subst
928 -- Type constructors must match
929 uTysX (TyConApp con1 tys1) (TyConApp con2 tys2) k subst
930 | (con1 == con2 && equalLength tys1 tys2)
931 = uTyListsX tys1 tys2 k subst
933 -- Applications need a bit of care!
934 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
935 -- NB: we've already dealt with type variables and Notes,
936 -- so if one type is an App the other one jolly well better be too
937 uTysX (AppTy s1 t1) ty2 k subst
938 = case tcSplitAppTy_maybe ty2 of
939 Just (s2, t2) -> uTysX s1 s2 (uTysX t1 t2 k) subst
940 Nothing -> Nothing -- Fail
942 uTysX ty1 (AppTy s2 t2) k subst
943 = case tcSplitAppTy_maybe ty1 of
944 Just (s1, t1) -> uTysX s1 s2 (uTysX t1 t2 k) subst
945 Nothing -> Nothing -- Fail
947 -- Not expecting for-alls in unification
949 uTysX (ForAllTy _ _) ty2 k subst = panic "Unify.uTysX subst:ForAllTy (1st arg)"
950 uTysX ty1 (ForAllTy _ _) k subst = panic "Unify.uTysX subst:ForAllTy (2nd arg)"
954 uTysX (UsageTy _ t1) t2 k subst = uTysX t1 t2 k subst
955 uTysX t1 (UsageTy _ t2) k subst = uTysX t1 t2 k subst
957 -- Anything else fails
958 uTysX ty1 ty2 k subst = Nothing
961 uTyListsX [] [] k subst = k subst
962 uTyListsX (ty1:tys1) (ty2:tys2) k subst = uTysX ty1 ty2 (uTyListsX tys1 tys2 k) subst
963 uTyListsX tys1 tys2 k subst = Nothing -- Fail if the lists are different lengths
967 -- Invariant: tv1 is a unifiable variable
968 uVarX tv1 ty2 k subst@(tmpls, env)
969 = case lookupSubstEnv env tv1 of
970 Just (DoneTy ty1) -> -- Already bound
971 uTysX ty1 ty2 k subst
973 Nothing -- Not already bound
974 | typeKind ty2 `eqKind` tyVarKind tv1
975 && occur_check_ok ty2
976 -> -- No kind mismatch nor occur check
977 UASSERT( not (isUTy ty2) )
978 k (tmpls, extendSubstEnv env tv1 (DoneTy ty2))
980 | otherwise -> Nothing -- Fail if kind mis-match or occur check
982 occur_check_ok ty = all occur_check_ok_tv (varSetElems (tyVarsOfType ty))
983 occur_check_ok_tv tv | tv1 == tv = False
984 | otherwise = case lookupSubstEnv env tv of
986 Just (DoneTy ty) -> occur_check_ok ty
991 %************************************************************************
993 \subsection{Matching on types}
995 %************************************************************************
997 Matching is a {\em unidirectional} process, matching a type against a
998 template (which is just a type with type variables in it). The
999 matcher assumes that there are no repeated type variables in the
1000 template, so that it simply returns a mapping of type variables to
1001 types. It also fails on nested foralls.
1003 @matchTys@ matches corresponding elements of a list of templates and
1004 types. It and @matchTy@ both ignore usage annotations, unlike the
1005 main function @match@.
1008 matchTy :: TyVarSet -- Template tyvars
1010 -> Type -- Proposed instance of template
1011 -> Maybe TyVarSubstEnv -- Matching substitution
1014 matchTys :: TyVarSet -- Template tyvars
1015 -> [Type] -- Templates
1016 -> [Type] -- Proposed instance of template
1017 -> Maybe (TyVarSubstEnv, -- Matching substitution
1018 [Type]) -- Left over instance types
1020 matchTy tmpls ty1 ty2 = match ty1 ty2 tmpls (\ senv -> Just senv) emptySubstEnv
1022 matchTys tmpls tys1 tys2 = match_list tys1 tys2 tmpls
1023 (\ (senv,tys) -> Just (senv,tys))
1027 @match@ is the main function. It takes a flag indicating whether
1028 usage annotations are to be respected.
1031 match :: Type -> Type -- Current match pair
1032 -> TyVarSet -- Template vars
1033 -> (TyVarSubstEnv -> Maybe result) -- Continuation
1034 -> TyVarSubstEnv -- Current subst
1037 -- When matching against a type variable, see if the variable
1038 -- has already been bound. If so, check that what it's bound to
1039 -- is the same as ty; if not, bind it and carry on.
1041 match (TyVarTy v) ty tmpls k senv
1042 | v `elemVarSet` tmpls
1043 = -- v is a template variable
1044 case lookupSubstEnv senv v of
1045 Nothing -> UASSERT( not (isUTy ty) )
1046 k (extendSubstEnv senv v (DoneTy ty))
1047 Just (DoneTy ty') | ty' `tcEqType` ty -> k senv -- Succeeds
1048 | otherwise -> Nothing -- Fails
1051 = -- v is not a template variable; ty had better match
1052 -- Can't use (==) because types differ
1053 case tcGetTyVar_maybe ty of
1054 Just v' | v == v' -> k senv -- Success
1055 other -> Nothing -- Failure
1056 -- This tcGetTyVar_maybe is *required* because it must strip Notes.
1057 -- I guess the reason the Note-stripping case is *last* rather than first
1058 -- is to preserve type synonyms etc., so I'm not moving it to the
1059 -- top; but this means that (without the deNotetype) a type
1060 -- variable may not match the pattern (TyVarTy v') as one would
1061 -- expect, due to an intervening Note. KSW 2000-06.
1064 match (SourceTy (IParam n1 t1)) (SourceTy (IParam n2 t2)) tmpls k senv
1065 | n1 == n2 = match t1 t2 tmpls k senv
1066 match (SourceTy (ClassP c1 tys1)) (SourceTy (ClassP c2 tys2)) tmpls k senv
1067 | c1 == c2 = match_list_exactly tys1 tys2 tmpls k senv
1068 match (SourceTy (NType tc1 tys1)) (SourceTy (NType tc2 tys2)) tmpls k senv
1069 | tc1 == tc2 = match_list_exactly tys1 tys2 tmpls k senv
1071 -- Functions; just check the two parts
1072 match (FunTy arg1 res1) (FunTy arg2 res2) tmpls k senv
1073 = match arg1 arg2 tmpls (match res1 res2 tmpls k) senv
1075 match (AppTy fun1 arg1) ty2 tmpls k senv
1076 = case tcSplitAppTy_maybe ty2 of
1077 Just (fun2,arg2) -> match fun1 fun2 tmpls (match arg1 arg2 tmpls k) senv
1078 Nothing -> Nothing -- Fail
1080 match (TyConApp tc1 tys1) (TyConApp tc2 tys2) tmpls k senv
1081 | tc1 == tc2 = match_list_exactly tys1 tys2 tmpls k senv
1083 -- Newtypes are opaque; other source types should not happen
1084 match (SourceTy (NType tc1 tys1)) (SourceTy (NType tc2 tys2)) tmpls k senv
1085 | tc1 == tc2 = match_list_exactly tys1 tys2 tmpls k senv
1087 match (UsageTy _ ty1) ty2 tmpls k senv = match ty1 ty2 tmpls k senv
1088 match ty1 (UsageTy _ ty2) tmpls k senv = match ty1 ty2 tmpls k senv
1090 -- With type synonyms, we have to be careful for the exact
1091 -- same reasons as in the unifier. Please see the
1092 -- considerable commentary there before changing anything
1093 -- here! (WDP 95/05)
1094 match (NoteTy n1 ty1) ty2 tmpls k senv = match ty1 ty2 tmpls k senv
1095 match ty1 (NoteTy n2 ty2) tmpls k senv = match ty1 ty2 tmpls k senv
1098 match _ _ _ _ _ = Nothing
1100 match_list_exactly tys1 tys2 tmpls k senv
1101 = match_list tys1 tys2 tmpls k' senv
1103 k' (senv', tys2') | null tys2' = k senv' -- Succeed
1104 | otherwise = Nothing -- Fail
1106 match_list [] tys2 tmpls k senv = k (senv, tys2)
1107 match_list (ty1:tys1) [] tmpls k senv = Nothing -- Not enough arg tys => failure
1108 match_list (ty1:tys1) (ty2:tys2) tmpls k senv
1109 = match ty1 ty2 tmpls (match_list tys1 tys2 tmpls k) senv