[project @ 2003-02-04 15:09:38 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcType.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcType]{Types used in the typechecker}
5
6 This module provides the Type interface for front-end parts of the 
7 compiler.  These parts 
8
9         * treat "source types" as opaque: 
10                 newtypes, and predicates are meaningful. 
11         * look through usage types
12
13 The "tc" prefix is for "typechechecker", because the type checker
14 is the principal client.
15
16 \begin{code}
17 module TcType (
18   --------------------------------
19   -- Types 
20   TcType, TcSigmaType, TcRhoType, TcTauType, TcPredType, TcThetaType, 
21   TcTyVar, TcTyVarSet, TcKind, 
22
23   --------------------------------
24   -- TyVarDetails
25   TyVarDetails(..), isUserTyVar, isSkolemTyVar, isHoleTyVar, 
26   tyVarBindingInfo,
27
28   --------------------------------
29   -- Builders
30   mkPhiTy, mkSigmaTy, 
31
32   --------------------------------
33   -- Splitters  
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,
40
41   ---------------------------------
42   -- Predicates. 
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,
49   allDistinctTyVars,
50
51   ---------------------------------
52   -- Misc type manipulators
53   deNoteType, classNamesOfTheta,
54   tyClsNamesOfType, tyClsNamesOfDFunHead, 
55   getDFunTyKey,
56
57   ---------------------------------
58   -- Predicate types  
59   getClassPredTys_maybe, getClassPredTys, 
60   isPredTy, isClassPred, isTyVarClassPred, predHasFDs,
61   mkDictTy, tcSplitPredTy_maybe, 
62   isDictTy, tcSplitDFunTy, predTyUnique, 
63   mkClassPred, isInheritablePred, isLinearPred, isIPPred, mkPredName, 
64
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
74
75   ---------------------------------
76   -- Unifier and matcher  
77   unifyTysX, unifyTyListsX, unifyExtendTysX,
78   matchTy, matchTys, match,
79
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,
86
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, 
92
93   isUnLiftedType,       -- Source types are always lifted
94   isUnboxedTupleType,   -- Ditto
95   isPrimitiveType, isTyVarTy,
96
97   tidyTopType, tidyType, tidyPred, tidyTypes, tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
98   tidyTyVarBndr, tidyOpenTyVar, tidyOpenTyVars,
99   typeKind, eqKind,
100
101   tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta
102   ) where
103
104 #include "HsVersions.h"
105
106
107 import {-# SOURCE #-} PprType( pprType )
108 -- PprType imports TcType so that it can print intelligently
109
110 -- friends:
111 import TypeRep          ( Type(..), TyNote(..), funTyCon )  -- friend
112
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
133                         )
134 import TyCon            ( TyCon, isUnLiftedTyCon )
135 import Class            ( classHasFDs, Class )
136 import Var              ( TyVar, tyVarKind, isMutTyVar, mutTyVarDetails )
137 import ForeignCall      ( Safety, playSafe )
138 import VarEnv
139 import VarSet
140
141 -- others:
142 import CmdLineOpts      ( DynFlags, DynFlag( Opt_GlasgowExts ), dopt )
143 import Name             ( Name, NamedThing(..), mkInternalName, getSrcLoc )
144 import OccName          ( OccName, mkDictOcc )
145 import NameSet
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 )
153 import Outputable
154 \end{code}
155
156
157 %************************************************************************
158 %*                                                                      *
159 \subsection{Types}
160 %*                                                                      *
161 %************************************************************************
162
163 The type checker divides the generic Type world into the 
164 following more structured beasts:
165
166 sigma ::= forall tyvars. phi
167         -- A sigma type is a qualified type
168         --
169         -- Note that even if 'tyvars' is empty, theta
170         -- may not be: e.g.   (?x::Int) => Int
171
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
175         -- an arrow
176
177 phi :: theta => rho
178
179 rho ::= sigma -> rho
180      |  tau
181
182 -- A 'tau' type has no quantification anywhere
183 -- Note that the args of a type constructor must be taus
184 tau ::= tyvar
185      |  tycon tau_1 .. tau_n
186      |  tau_1 tau_2
187      |  tau_1 -> tau_2
188
189 -- In all cases, a (saturated) type synonym application is legal,
190 -- provided it expands to the required form.
191
192
193 \begin{code}
194 type SigmaType = Type
195 type RhoType   = Type
196 type TauType   = Type
197 \end{code}
198
199 \begin{code}
200 type TcTyVar    = TyVar         -- Might be a mutable tyvar
201 type TcTyVarSet = TyVarSet
202
203 type TcType = Type              -- A TcType can have mutable type variables
204         -- Invariant on ForAllTy in TcTypes:
205         --      forall a. T
206         -- a cannot occur inside a MutTyVar in T; that is,
207         -- T is "flattened" before quantifying over a
208
209 type TcPredType     = PredType
210 type TcThetaType    = ThetaType
211 type TcSigmaType    = TcType
212 type TcRhoType      = TcType
213 type TcTauType      = TcType
214 type TcKind         = TcType
215 \end{code}
216
217
218 %************************************************************************
219 %*                                                                      *
220 \subsection{TyVarDetails}
221 %*                                                                      *
222 %************************************************************************
223
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.
228
229 \begin{code}
230 data TyVarDetails
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
235
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.
239                 --
240                 --      f :: forall a. a -> a
241                 --      f = e
242                 -- When checking e, with expected type (a->a), we 
243                 -- should not instantiate a
244
245    | ClsTv      -- Scoped type variable introduced by a class decl
246                 --      class C a where ...
247
248    | InstTv     -- Ditto, but instance decl
249
250    | PatSigTv   -- Scoped type variable, introduced by a pattern
251                 -- type signature
252                 --      \ x::a -> e
253
254    | VanillaTv  -- Everything else
255
256 isUserTyVar :: TcTyVar -> Bool  -- Avoid unifying these if possible
257 isUserTyVar tv = case mutTyVarDetails tv of
258                    VanillaTv -> False
259                    other     -> True
260
261 isSkolemTyVar :: TcTyVar -> Bool
262 isSkolemTyVar tv = case mutTyVarDetails tv of
263                       SigTv  -> True
264                       ClsTv  -> True
265                       InstTv -> True
266                       oteher -> False
267
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
273                         HoleTv -> True
274                         other  -> False
275
276 tyVarBindingInfo :: TyVar -> SDoc       -- Used in checkSigTyVars
277 tyVarBindingInfo tv
278   | isMutTyVar tv
279   = sep [ptext SLIT("is bound by the") <+> details (mutTyVarDetails tv),
280          ptext SLIT("at") <+> ppr (getSrcLoc tv)]
281   | otherwise
282   = empty
283   where
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
290 \end{code}
291
292
293 %************************************************************************
294 %*                                                                      *
295 \subsection{Tau, sigma and rho}
296 %*                                                                      *
297 %************************************************************************
298
299 \begin{code}
300 mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkPhiTy theta tau)
301
302 mkPhiTy :: [SourceType] -> Type -> Type
303 mkPhiTy theta ty = foldr (\p r -> FunTy (mkPredTy p) r) ty theta
304 \end{code}
305
306
307 @isTauTy@ tests for nested for-alls.
308
309 \begin{code}
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
318 \end{code}
319
320 \begin{code}
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
332 \end{code}
333
334
335 %************************************************************************
336 %*                                                                      *
337 \subsection{Expanding and splitting}
338 %*                                                                      *
339 %************************************************************************
340
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
345
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.
348
349 \begin{code}
350 tcSplitForAllTys :: Type -> ([TyVar], Type)
351 tcSplitForAllTys ty = split ty ty []
352    where
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)
356
357 tcIsForAllTy (ForAllTy tv ty) = True
358 tcIsForAllTy (NoteTy n ty)    = tcIsForAllTy ty
359 tcIsForAllTy t                = False
360
361 tcSplitPhiTy :: Type -> ([PredType], Type)
362 tcSplitPhiTy ty = split ty ty []
363  where
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)
369
370 tcSplitSigmaTy ty = case tcSplitForAllTys ty of
371                         (tvs, rho) -> case tcSplitPhiTy rho of
372                                         (theta, tau) -> (tvs, theta, tau)
373
374 tcTyConAppTyCon :: Type -> TyCon
375 tcTyConAppTyCon ty = fst (tcSplitTyConApp ty)
376
377 tcTyConAppArgs :: Type -> [Type]
378 tcTyConAppArgs ty = snd (tcSplitTyConApp ty)
379
380 tcSplitTyConApp :: Type -> (TyCon, [Type])
381 tcSplitTyConApp ty = case tcSplitTyConApp_maybe ty of
382                         Just stuff -> stuff
383                         Nothing    -> pprPanic "tcSplitTyConApp" (pprType ty)
384
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
394
395 tcSplitFunTys :: Type -> ([Type], Type)
396 tcSplitFunTys ty = case tcSplitFunTy_maybe ty of
397                         Nothing        -> ([], ty)
398                         Just (arg,res) -> (arg:args, res')
399                                        where
400                                           (args,res') = tcSplitFunTys res
401
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
406
407 tcFunArgTy    ty = case tcSplitFunTy_maybe ty of { Just (arg,res) -> arg }
408 tcFunResultTy ty = case tcSplitFunTy_maybe ty of { Just (arg,res) -> res }
409
410
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
418
419 tc_split_app tc tys = case snocView tys of
420                         Just (tys',ty') -> Just (TyConApp tc tys', ty')
421                         Nothing         -> Nothing
422
423 tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
424                     Just stuff -> stuff
425                     Nothing    -> pprPanic "tcSplitAppTy" (pprType ty)
426
427 tcSplitAppTys :: Type -> (Type, [Type])
428 tcSplitAppTys ty
429   = go ty []
430   where
431     go ty args = case tcSplitAppTy_maybe ty of
432                    Just (ty', arg) -> go ty' (arg:args)
433                    Nothing         -> (ty,args)
434
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
439
440 tcGetTyVar :: String -> Type -> TyVar
441 tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty)
442
443 tcIsTyVarTy :: Type -> Bool
444 tcIsTyVarTy ty = maybeToBool (tcGetTyVar_maybe ty)
445 \end{code}
446
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.
453
454 \begin{code}
455 tcSplitMethodTy :: Type -> (PredType, Type)
456 tcSplitMethodTy ty = split ty
457  where
458   split (FunTy arg res) = case tcSplitPredTy_maybe arg of
459                             Just p  -> (p, res)
460                             Nothing -> panic "splitMethodTy"
461   split (NoteTy n ty)   = split ty
462   split _               = panic "splitMethodTy"
463
464 tcSplitDFunTy :: Type -> ([TyVar], [SourceType], Class, [Type])
465 -- Split the type of a dictionary function
466 tcSplitDFunTy ty 
467   = case tcSplitSigmaTy ty       of { (tvs, theta, tau) ->
468     case tcSplitPredTy_maybe tau of { Just (ClassP clas tys) -> 
469     (tvs, theta, clas, tys) }}
470 \end{code}
471
472 (allDistinctTyVars tys tvs) = True 
473         iff 
474 all the types tys are type variables, 
475 distinct from each other and from tvs.
476
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
484
485 \begin{code}
486 allDistinctTyVars :: [Type] -> TyVarSet -> Bool
487
488 allDistinctTyVars []       acc
489   = True
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)
495 \end{code}    
496
497
498 %************************************************************************
499 %*                                                                      *
500 \subsection{Predicate types}
501 %*                                                                      *
502 %************************************************************************
503
504 "Predicates" are particular source types, namelyClassP or IParams
505
506 \begin{code}
507 isPred :: SourceType -> Bool
508 isPred (ClassP _ _) = True
509 isPred (IParam _ _) = True
510 isPred (NType _ _)  = False
511
512 isPredTy :: Type -> Bool
513 isPredTy (NoteTy _ ty)  = isPredTy ty
514 isPredTy (SourceTy sty) = isPred sty
515 isPredTy _              = False
516
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
522         
523 predTyUnique :: PredType -> Unique
524 predTyUnique (IParam n _)      = getUnique (ipNameName n)
525 predTyUnique (ClassP clas tys) = getUnique clas
526
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
532
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
536 \end{code}
537
538
539 --------------------- Dictionary types ---------------------------------
540
541 \begin{code}
542 mkClassPred clas tys = ClassP clas tys
543
544 isClassPred :: SourceType -> Bool
545 isClassPred (ClassP clas tys) = True
546 isClassPred other             = False
547
548 isTyVarClassPred (ClassP clas tys) = all tcIsTyVarTy tys
549 isTyVarClassPred other             = False
550
551 getClassPredTys_maybe :: SourceType -> Maybe (Class, [Type])
552 getClassPredTys_maybe (ClassP clas tys) = Just (clas, tys)
553 getClassPredTys_maybe _                 = Nothing
554
555 getClassPredTys :: PredType -> (Class, [Type])
556 getClassPredTys (ClassP clas tys) = (clas, tys)
557
558 mkDictTy :: Class -> [Type] -> Type
559 mkDictTy clas tys = mkPredTy (ClassP clas tys)
560
561 isDictTy :: Type -> Bool
562 isDictTy (SourceTy p)   = isClassPred p
563 isDictTy (NoteTy _ ty)  = isDictTy ty
564 isDictTy other          = False
565 \end{code}
566
567 --------------------- Implicit parameters ---------------------------------
568
569 \begin{code}
570 isIPPred :: SourceType -> Bool
571 isIPPred (IParam _ _) = True
572 isIPPred other        = False
573
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, 
578 --                g 4 with ?v = 9)
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
585
586 isLinearPred :: TcPredType -> Bool
587 isLinearPred (IParam (Linear n) _) = True
588 isLinearPred other                 = False
589 \end{code}
590
591
592 %************************************************************************
593 %*                                                                      *
594 \subsection{Comparison}
595 %*                                                                      *
596 %************************************************************************
597
598 Comparison, taking note of newtypes, predicates, etc,
599 But ignoring usage types
600
601 \begin{code}
602 tcEqType :: Type -> Type -> Bool
603 tcEqType ty1 ty2 = case ty1 `tcCmpType` ty2 of { EQ -> True; other -> False }
604
605 tcEqTypes :: [Type] -> [Type] -> Bool
606 tcEqTypes ty1 ty2 = case ty1 `tcCmpTypes` ty2 of { EQ -> True; other -> False }
607
608 tcEqPred :: PredType -> PredType -> Bool
609 tcEqPred p1 p2 = case p1 `tcCmpPred` p2 of { EQ -> True; other -> False }
610
611 -------------
612 tcCmpType :: Type -> Type -> Ordering
613 tcCmpType ty1 ty2 = cmpTy emptyVarEnv ty1 ty2
614
615 tcCmpTypes tys1 tys2 = cmpTys emptyVarEnv tys1 tys2
616
617 tcCmpPred p1 p2 = cmpSourceTy emptyVarEnv p1 p2
618 -------------
619 cmpTys env tys1 tys2 = cmpList (cmpTy env) tys1 tys2
620
621 -------------
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
626
627     -- Look through NoteTy
628 cmpTy env (NoteTy _ ty1) ty2 = cmpTy env ty1 ty2
629 cmpTy env ty1 (NoteTy _ ty2) = cmpTy env ty1 ty2
630
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
635
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
641     
642     -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < SourceTy
643 cmpTy env (AppTy _ _) (TyVarTy _) = GT
644     
645 cmpTy env (FunTy _ _) (TyVarTy _) = GT
646 cmpTy env (FunTy _ _) (AppTy _ _) = GT
647     
648 cmpTy env (TyConApp _ _) (TyVarTy _) = GT
649 cmpTy env (TyConApp _ _) (AppTy _ _) = GT
650 cmpTy env (TyConApp _ _) (FunTy _ _) = GT
651     
652 cmpTy env (ForAllTy _ _) (TyVarTy _)    = GT
653 cmpTy env (ForAllTy _ _) (AppTy _ _)    = GT
654 cmpTy env (ForAllTy _ _) (FunTy _ _)    = GT
655 cmpTy env (ForAllTy _ _) (TyConApp _ _) = GT
656
657 cmpTy env (SourceTy _)   t2             = GT
658
659 cmpTy env _ _ = LT
660 \end{code}
661
662 \begin{code}
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
669
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
673
674 cmpSourceTy env (NType tc1 tys1) (NType tc2 tys2) = (tc1 `compare` tc2) `thenCmp` (cmpTys env tys1 tys2)
675 cmpSourceTy env (NType _ _)      sty              = GT
676 \end{code}
677
678 PredTypes are used as a FM key in TcSimplify, 
679 so we take the easy path and make them an instance of Ord
680
681 \begin{code}
682 instance Eq  SourceType where { (==)    = tcEqPred }
683 instance Ord SourceType where { compare = tcCmpPred }
684 \end{code}
685
686
687 %************************************************************************
688 %*                                                                      *
689 \subsection{Predicates}
690 %*                                                                      *
691 %************************************************************************
692
693 isSigmaTy returns true of any qualified type.  It doesn't *necessarily* have 
694 any foralls.  E.g.
695         f :: (?x::Int) => Int -> Int
696
697 \begin{code}
698 isSigmaTy :: Type -> Bool
699 isSigmaTy (ForAllTy tyvar ty) = True
700 isSigmaTy (FunTy a b)         = isPredTy a
701 isSigmaTy (NoteTy n ty)       = isSigmaTy ty
702 isSigmaTy _                   = False
703
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
709 \end{code}
710
711 \begin{code}
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
719
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
724                         Nothing      -> False
725 \end{code}
726
727
728 %************************************************************************
729 %*                                                                      *
730 \subsection{Misc}
731 %*                                                                      *
732 %************************************************************************
733
734 \begin{code}
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)
744
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)
749 \end{code}
750
751 Find the free tycons and classes of a type.  This is used in the front
752 end of the compiler.
753
754 \begin{code}
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
766
767 tyClsNamesOfTypes tys = foldr (unionNameSets . tyClsNamesOfType) emptyNameSet tys
768
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
779
780 classNamesOfTheta :: ThetaType -> [Name]
781 -- Looks just for ClassP things; maybe it should check
782 classNamesOfTheta preds = [ getName c | ClassP c _ <- preds ]
783 \end{code}
784
785
786 %************************************************************************
787 %*                                                                      *
788 \subsection[TysWiredIn-ext-type]{External types}
789 %*                                                                      *
790 %************************************************************************
791
792 The compiler's foreign function interface supports the passing of a
793 restricted set of types as arguments and results (the restricting factor
794 being the )
795
796 \begin{code}
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
801
802 isFFIExternalTy :: Type -> Bool
803 -- Types that are allowed as arguments of a 'foreign export'
804 isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty
805
806 isFFIImportResultTy :: DynFlags -> Type -> Bool
807 isFFIImportResultTy dflags ty 
808   = checkRepTyCon (legalFIResultTyCon dflags) ty
809
810 isFFIExportResultTy :: Type -> Bool
811 isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty
812
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)
817
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)
822
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)
827
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
834   | otherwise                                       = False
835 \end{code}
836
837 ----------------------------------------------
838 These chaps do the work; they are not exported
839 ----------------------------------------------
840
841 \begin{code}
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).
846 legalFEArgTyCon tc
847   | getUnique tc `elem` [ byteArrayTyConKey, mutableByteArrayTyConKey ] 
848   = False
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
851   | otherwise
852   = boxedMarshalableTyCon tc
853
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
860
861 legalFEResultTyCon :: TyCon -> Bool
862 legalFEResultTyCon tc
863   | getUnique tc `elem` 
864         [ byteArrayTyConKey, mutableByteArrayTyConKey ]  = False
865   | tc == unitTyCon = True
866   | otherwise       = boxedMarshalableTyCon tc
867
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]
872   = False
873   | otherwise
874   = marshalableTyCon dflags tc
875
876 marshalableTyCon dflags tc
877   =  (dopt Opt_GlasgowExts dflags && isUnLiftedTyCon tc)
878   || boxedMarshalableTyCon tc
879
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
887                          , charTyConKey
888                          , stablePtrTyConKey
889                          , byteArrayTyConKey, mutableByteArrayTyConKey
890                          , boolTyConKey
891                          ]
892 \end{code}
893
894
895 %************************************************************************
896 %*                                                                      *
897 \subsection{Unification with an explicit substitution}
898 %*                                                                      *
899 %************************************************************************
900
901 Unify types with an explicit substitution and no monad.
902 Ignore usage annotations.
903
904 \begin{code}
905 type MySubst
906    = (TyVarSet,         -- Set of template tyvars
907       TyVarSubstEnv)    -- Not necessarily idempotent
908
909 unifyTysX :: TyVarSet           -- Template tyvars
910           -> Type
911           -> Type
912           -> Maybe TyVarSubstEnv
913 unifyTysX tmpl_tyvars ty1 ty2
914   = uTysX ty1 ty2 (\(_,s) -> Just s) (tmpl_tyvars, emptySubstEnv)
915
916 unifyExtendTysX :: TyVarSet             -- Template tyvars
917                 -> TyVarSubstEnv        -- Substitution to start with
918                 -> Type
919                 -> Type
920                 -> Maybe TyVarSubstEnv  -- Extended substitution
921 unifyExtendTysX tmpl_tyvars subst ty1 ty2
922   = uTysX ty1 ty2 (\(_,s) -> Just s) (tmpl_tyvars, subst)
923
924 unifyTyListsX :: TyVarSet -> [Type] -> [Type]
925               -> Maybe TyVarSubstEnv
926 unifyTyListsX tmpl_tyvars tys1 tys2
927   = uTyListsX tys1 tys2 (\(_,s) -> Just s) (tmpl_tyvars, emptySubstEnv)
928
929
930 uTysX :: Type
931       -> Type
932       -> (MySubst -> Maybe result)
933       -> MySubst
934       -> Maybe result
935
936 uTysX (NoteTy _ ty1) ty2 k subst = uTysX ty1 ty2 k subst
937 uTysX ty1 (NoteTy _ ty2) k subst = uTysX ty1 ty2 k subst
938
939         -- Variables; go for uVar
940 uTysX (TyVarTy tyvar1) (TyVarTy tyvar2) k subst 
941   | tyvar1 == tyvar2
942   = 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
949
950         -- Predicates
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
957
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
961
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
966
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
975
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
980
981         -- Not expecting for-alls in unification
982 #ifdef DEBUG
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)"
985 #endif
986
987         -- Anything else fails
988 uTysX ty1 ty2 k subst = Nothing
989
990
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
994 \end{code}
995
996 \begin{code}
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
1002
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))
1008
1009                | otherwise -> Nothing   -- Fail if kind mis-match or occur check
1010   where
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
1014                                          Nothing           -> True
1015                                          Just (DoneTy ty)  -> occur_check_ok ty
1016 \end{code}
1017
1018
1019
1020 %************************************************************************
1021 %*                                                                      *
1022 \subsection{Matching on types}
1023 %*                                                                      *
1024 %************************************************************************
1025
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.
1031
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@.
1035
1036 \begin{code}
1037 matchTy :: TyVarSet                     -- Template tyvars
1038         -> Type                         -- Template
1039         -> Type                         -- Proposed instance of template
1040         -> Maybe TyVarSubstEnv          -- Matching substitution
1041                                         
1042
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
1048
1049 matchTy tmpls ty1 ty2 = match ty1 ty2 tmpls (\ senv -> Just senv) emptySubstEnv
1050
1051 matchTys tmpls tys1 tys2 = match_list tys1 tys2 tmpls 
1052                                       (\ (senv,tys) -> Just (senv,tys))
1053                                       emptySubstEnv
1054 \end{code}
1055
1056 @match@ is the main function.  It takes a flag indicating whether
1057 usage annotations are to be respected.
1058
1059 \begin{code}
1060 match :: Type -> Type                           -- Current match pair
1061       -> TyVarSet                               -- Template vars
1062       -> (TyVarSubstEnv -> Maybe result)        -- Continuation
1063       -> TyVarSubstEnv                          -- Current subst
1064       -> Maybe result
1065
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.
1069
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))
1080
1081                 | otherwise  -> Nothing -- Fails
1082
1083         Just (DoneTy ty')  | ty' `tcEqType` ty   -> k senv   -- Succeeds
1084                            | otherwise           -> Nothing  -- Fails
1085
1086   | otherwise
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.
1098
1099         -- Predicates
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
1106
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
1110
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
1115
1116 match (TyConApp tc1 tys1) (TyConApp tc2 tys2) tmpls k senv
1117   | tc1 == tc2 = match_list_exactly tys1 tys2 tmpls k senv
1118
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
1122
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
1129
1130 -- Catch-all fails
1131 match _ _ _ _ _ = Nothing
1132
1133 match_list_exactly tys1 tys2 tmpls k senv
1134   = match_list tys1 tys2 tmpls k' senv
1135   where
1136     k' (senv', tys2') | null tys2' = k senv'    -- Succeed
1137                       | otherwise  = Nothing    -- Fail 
1138
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
1143 \end{code}