[project @ 2001-08-14 06:35:56 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcMType.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Monadic type operations}
5
6 This module contains monadic operations over types that contain mutable type variables
7
8 \begin{code}
9 module TcMType (
10   TcTyVar, TcKind, TcType, TcTauType, TcThetaType, TcRhoType, TcTyVarSet,
11
12   --------------------------------
13   -- Creating new mutable type variables
14   newTyVar,
15   newTyVarTy,           -- Kind -> NF_TcM TcType
16   newTyVarTys,          -- Int -> Kind -> NF_TcM [TcType]
17   newKindVar, newKindVars, newBoxityVar,
18
19   --------------------------------
20   -- Instantiation
21   tcInstTyVar, tcInstTyVars,
22   tcInstSigVars, tcInstType,
23   tcSplitRhoTyM,
24
25   --------------------------------
26   -- Checking type validity
27   Rank, UserTypeCtxt(..), checkValidType, pprUserTypeCtxt,
28   SourceTyCtxt(..), checkValidTheta,
29
30   --------------------------------
31   -- Unification
32   unifyTauTy, unifyTauTyList, unifyTauTyLists, 
33   unifyFunTy, unifyListTy, unifyTupleTy,
34   unifyKind, unifyKinds, unifyOpenTypeKind,
35
36   --------------------------------
37   -- Zonking
38   zonkTcTyVar, zonkTcTyVars, zonkTcTyVarsAndFV, zonkTcSigTyVars,
39   zonkTcType, zonkTcTypes, zonkTcClassConstraints, zonkTcThetaType,
40   zonkTcPredType, zonkTcTypeToType, zonkTcTyVarToTyVar, zonkKindEnv,
41
42   ) where
43
44 #include "HsVersions.h"
45
46
47 -- friends:
48 import TypeRep          ( Type(..), SourceType(..), TyNote(..),  -- Friend; can see representation
49                           Kind, TauType, ThetaType, 
50                           openKindCon, typeCon
51                         ) 
52 import TcType           ( tcEqType, tcCmpPred,
53                           tcSplitRhoTy, tcSplitPredTy_maybe, tcSplitAppTy_maybe, 
54                           tcSplitTyConApp_maybe, tcSplitFunTy_maybe, tcSplitForAllTys,
55                           tcGetTyVar, tcIsTyVarTy, tcSplitSigmaTy, isUnLiftedType, isIPPred,
56
57                           mkAppTy, mkTyVarTy, mkTyVarTys, mkFunTy, mkTyConApp,
58                           tyVarsOfPred,
59
60                           liftedTypeKind, unliftedTypeKind, openTypeKind, defaultKind, superKind,
61                           superBoxity, liftedBoxity, hasMoreBoxityInfo, typeKind,
62                           tyVarsOfType, tyVarsOfTypes, tidyOpenType, tidyOpenTypes, tidyTyVar,
63                           eqKind, isTypeKind
64                         )
65 import Subst            ( Subst, mkTopTyVarSubst, substTy )
66 import Class            ( classArity, className )
67 import TyCon            ( TyCon, mkPrimTyCon, isSynTyCon, isUnboxedTupleTyCon, 
68                           isTupleTyCon, tyConArity, tupleTyConBoxity, tyConName )
69 import PrimRep          ( PrimRep(VoidRep) )
70 import Var              ( TyVar, varName, tyVarKind, tyVarName, isTyVar, mkTyVar,
71                           isMutTyVar, isSigTyVar )
72
73 -- others:
74 import TcMonad          -- TcType, amongst others
75 import TysWiredIn       ( voidTy, listTyCon, mkListTy, mkTupleTy )
76 import FunDeps          ( grow )
77 import PprType          ( pprPred, pprSourceType, pprTheta )
78 import Name             ( Name, NamedThing(..), setNameUnique, mkSysLocalName,
79                           mkLocalName, mkDerivedTyConOcc, isSystemName
80                         )
81 import VarSet
82 import BasicTypes       ( Boxity, Arity, isBoxed )
83 import CmdLineOpts      ( dopt, DynFlag(..) )
84 import Unique           ( Uniquable(..) )
85 import SrcLoc           ( noSrcLoc )
86 import Util             ( nOfThem )
87 import ListSetOps       ( removeDups )
88 import Outputable
89 \end{code}
90
91
92 %************************************************************************
93 %*                                                                      *
94 \subsection{New type variables}
95 %*                                                                      *
96 %************************************************************************
97
98 \begin{code}
99 newTyVar :: Kind -> NF_TcM TcTyVar
100 newTyVar kind
101   = tcGetUnique         `thenNF_Tc` \ uniq ->
102     tcNewMutTyVar (mkSysLocalName uniq SLIT("t")) kind
103
104 newTyVarTy  :: Kind -> NF_TcM TcType
105 newTyVarTy kind
106   = newTyVar kind       `thenNF_Tc` \ tc_tyvar ->
107     returnNF_Tc (TyVarTy tc_tyvar)
108
109 newTyVarTys :: Int -> Kind -> NF_TcM [TcType]
110 newTyVarTys n kind = mapNF_Tc newTyVarTy (nOfThem n kind)
111
112 newKindVar :: NF_TcM TcKind
113 newKindVar
114   = tcGetUnique                                                 `thenNF_Tc` \ uniq ->
115     tcNewMutTyVar (mkSysLocalName uniq SLIT("k")) superKind     `thenNF_Tc` \ kv ->
116     returnNF_Tc (TyVarTy kv)
117
118 newKindVars :: Int -> NF_TcM [TcKind]
119 newKindVars n = mapNF_Tc (\ _ -> newKindVar) (nOfThem n ())
120
121 newBoxityVar :: NF_TcM TcKind
122 newBoxityVar
123   = tcGetUnique                                                 `thenNF_Tc` \ uniq ->
124     tcNewMutTyVar (mkSysLocalName uniq SLIT("bx")) superBoxity  `thenNF_Tc` \ kv ->
125     returnNF_Tc (TyVarTy kv)
126 \end{code}
127
128
129 %************************************************************************
130 %*                                                                      *
131 \subsection{Type instantiation}
132 %*                                                                      *
133 %************************************************************************
134
135 I don't understand why this is needed
136 An old comments says "No need for tcSplitForAllTyM because a type 
137         variable can't be instantiated to a for-all type"
138 But the same is true of rho types!
139
140 \begin{code}
141 tcSplitRhoTyM :: TcType -> NF_TcM (TcThetaType, TcType)
142 tcSplitRhoTyM t
143   = go t t []
144  where
145         -- A type variable is never instantiated to a dictionary type,
146         -- so we don't need to do a tcReadVar on the "arg".
147     go syn_t (FunTy arg res) ts = case tcSplitPredTy_maybe arg of
148                                         Just pair -> go res res (pair:ts)
149                                         Nothing   -> returnNF_Tc (reverse ts, syn_t)
150     go syn_t (NoteTy n t)    ts = go syn_t t ts
151     go syn_t (TyVarTy tv)    ts = getTcTyVar tv         `thenNF_Tc` \ maybe_ty ->
152                                   case maybe_ty of
153                                     Just ty | not (tcIsTyVarTy ty) -> go syn_t ty ts
154                                     other                          -> returnNF_Tc (reverse ts, syn_t)
155     go syn_t (UsageTy _ t)   ts = go syn_t t ts
156     go syn_t t               ts = returnNF_Tc (reverse ts, syn_t)
157 \end{code}
158
159
160 %************************************************************************
161 %*                                                                      *
162 \subsection{Type instantiation}
163 %*                                                                      *
164 %************************************************************************
165
166 Instantiating a bunch of type variables
167
168 \begin{code}
169 tcInstTyVars :: [TyVar] 
170              -> NF_TcM ([TcTyVar], [TcType], Subst)
171
172 tcInstTyVars tyvars
173   = mapNF_Tc tcInstTyVar tyvars `thenNF_Tc` \ tc_tyvars ->
174     let
175         tys = mkTyVarTys tc_tyvars
176     in
177     returnNF_Tc (tc_tyvars, tys, mkTopTyVarSubst tyvars tys)
178                 -- Since the tyvars are freshly made,
179                 -- they cannot possibly be captured by
180                 -- any existing for-alls.  Hence mkTopTyVarSubst
181
182 tcInstTyVar tyvar
183   = tcGetUnique                 `thenNF_Tc` \ uniq ->
184     let
185         name = setNameUnique (tyVarName tyvar) uniq
186         -- Note that we don't change the print-name
187         -- This won't confuse the type checker but there's a chance
188         -- that two different tyvars will print the same way 
189         -- in an error message.  -dppr-debug will show up the difference
190         -- Better watch out for this.  If worst comes to worst, just
191         -- use mkSysLocalName.
192     in
193     tcNewMutTyVar name (tyVarKind tyvar)
194
195 tcInstSigVars tyvars    -- Very similar to tcInstTyVar
196   = tcGetUniques        `thenNF_Tc` \ uniqs ->
197     listTc [ ASSERT( not (kind `eqKind` openTypeKind) ) -- Shouldn't happen
198              tcNewSigTyVar name kind 
199            | (tyvar, uniq) <- tyvars `zip` uniqs,
200              let name = setNameUnique (tyVarName tyvar) uniq, 
201              let kind = tyVarKind tyvar
202            ]
203 \end{code}
204
205 @tcInstType@ instantiates the outer-level for-alls of a TcType with
206 fresh type variables, splits off the dictionary part, and returns the results.
207
208 \begin{code}
209 tcInstType :: TcType -> NF_TcM ([TcTyVar], TcThetaType, TcType)
210 tcInstType ty
211   = case tcSplitForAllTys ty of
212         ([],     rho) ->        -- There may be overloading but no type variables;
213                                 --      (?x :: Int) => Int -> Int
214                          let
215                            (theta, tau) = tcSplitRhoTy rho      -- Used to be tcSplitRhoTyM
216                          in
217                          returnNF_Tc ([], theta, tau)
218
219         (tyvars, rho) -> tcInstTyVars tyvars                    `thenNF_Tc` \ (tyvars', _, tenv)  ->
220                          let
221                            (theta, tau) = tcSplitRhoTy (substTy tenv rho)       -- Used to be tcSplitRhoTyM
222                          in
223                          returnNF_Tc (tyvars', theta, tau)
224 \end{code}
225
226
227
228 %************************************************************************
229 %*                                                                      *
230 \subsection{Putting and getting  mutable type variables}
231 %*                                                                      *
232 %************************************************************************
233
234 \begin{code}
235 putTcTyVar :: TcTyVar -> TcType -> NF_TcM TcType
236 getTcTyVar :: TcTyVar -> NF_TcM (Maybe TcType)
237 \end{code}
238
239 Putting is easy:
240
241 \begin{code}
242 putTcTyVar tyvar ty 
243   | not (isMutTyVar tyvar)
244   = pprTrace "putTcTyVar" (ppr tyvar) $
245     returnNF_Tc ty
246
247   | otherwise
248   = ASSERT( isMutTyVar tyvar )
249     UASSERT2( not (isUTy ty), ppr tyvar <+> ppr ty )
250     tcWriteMutTyVar tyvar (Just ty)     `thenNF_Tc_`
251     returnNF_Tc ty
252 \end{code}
253
254 Getting is more interesting.  The easy thing to do is just to read, thus:
255
256 \begin{verbatim}
257 getTcTyVar tyvar = tcReadMutTyVar tyvar
258 \end{verbatim}
259
260 But it's more fun to short out indirections on the way: If this
261 version returns a TyVar, then that TyVar is unbound.  If it returns
262 any other type, then there might be bound TyVars embedded inside it.
263
264 We return Nothing iff the original box was unbound.
265
266 \begin{code}
267 getTcTyVar tyvar
268   | not (isMutTyVar tyvar)
269   = pprTrace "getTcTyVar" (ppr tyvar) $
270     returnNF_Tc (Just (mkTyVarTy tyvar))
271
272   | otherwise
273   = ASSERT2( isMutTyVar tyvar, ppr tyvar )
274     tcReadMutTyVar tyvar                                `thenNF_Tc` \ maybe_ty ->
275     case maybe_ty of
276         Just ty -> short_out ty                         `thenNF_Tc` \ ty' ->
277                    tcWriteMutTyVar tyvar (Just ty')     `thenNF_Tc_`
278                    returnNF_Tc (Just ty')
279
280         Nothing    -> returnNF_Tc Nothing
281
282 short_out :: TcType -> NF_TcM TcType
283 short_out ty@(TyVarTy tyvar)
284   | not (isMutTyVar tyvar)
285   = returnNF_Tc ty
286
287   | otherwise
288   = tcReadMutTyVar tyvar        `thenNF_Tc` \ maybe_ty ->
289     case maybe_ty of
290         Just ty' -> short_out ty'                       `thenNF_Tc` \ ty' ->
291                     tcWriteMutTyVar tyvar (Just ty')    `thenNF_Tc_`
292                     returnNF_Tc ty'
293
294         other    -> returnNF_Tc ty
295
296 short_out other_ty = returnNF_Tc other_ty
297 \end{code}
298
299
300 %************************************************************************
301 %*                                                                      *
302 \subsection{Zonking -- the exernal interfaces}
303 %*                                                                      *
304 %************************************************************************
305
306 -----------------  Type variables
307
308 \begin{code}
309 zonkTcTyVars :: [TcTyVar] -> NF_TcM [TcType]
310 zonkTcTyVars tyvars = mapNF_Tc zonkTcTyVar tyvars
311
312 zonkTcTyVarsAndFV :: [TcTyVar] -> NF_TcM TcTyVarSet
313 zonkTcTyVarsAndFV tyvars = mapNF_Tc zonkTcTyVar tyvars  `thenNF_Tc` \ tys ->
314                            returnNF_Tc (tyVarsOfTypes tys)
315
316 zonkTcTyVar :: TcTyVar -> NF_TcM TcType
317 zonkTcTyVar tyvar = zonkTyVar (\ tv -> returnNF_Tc (TyVarTy tv)) tyvar
318
319 zonkTcSigTyVars :: [TcTyVar] -> NF_TcM [TcTyVar]
320 -- This guy is to zonk the tyvars we're about to feed into tcSimplify
321 -- Usually this job is done by checkSigTyVars, but in a couple of places
322 -- that is overkill, so we use this simpler chap
323 zonkTcSigTyVars tyvars
324   = zonkTcTyVars tyvars `thenNF_Tc` \ tys ->
325     returnNF_Tc (map (tcGetTyVar "zonkTcSigTyVars") tys)
326 \end{code}
327
328 -----------------  Types
329
330 \begin{code}
331 zonkTcType :: TcType -> NF_TcM TcType
332 zonkTcType ty = zonkType (\ tv -> returnNF_Tc (TyVarTy tv)) ty
333
334 zonkTcTypes :: [TcType] -> NF_TcM [TcType]
335 zonkTcTypes tys = mapNF_Tc zonkTcType tys
336
337 zonkTcClassConstraints cts = mapNF_Tc zonk cts
338     where zonk (clas, tys)
339             = zonkTcTypes tys   `thenNF_Tc` \ new_tys ->
340               returnNF_Tc (clas, new_tys)
341
342 zonkTcThetaType :: TcThetaType -> NF_TcM TcThetaType
343 zonkTcThetaType theta = mapNF_Tc zonkTcPredType theta
344
345 zonkTcPredType :: TcPredType -> NF_TcM TcPredType
346 zonkTcPredType (ClassP c ts) =
347     zonkTcTypes ts      `thenNF_Tc` \ new_ts ->
348     returnNF_Tc (ClassP c new_ts)
349 zonkTcPredType (IParam n t) =
350     zonkTcType t        `thenNF_Tc` \ new_t ->
351     returnNF_Tc (IParam n new_t)
352 \end{code}
353
354 -------------------  These ...ToType, ...ToKind versions
355                      are used at the end of type checking
356
357 \begin{code}
358 zonkKindEnv :: [(Name, TcKind)] -> NF_TcM [(Name, Kind)]
359 zonkKindEnv pairs 
360   = mapNF_Tc zonk_it pairs
361  where
362     zonk_it (name, tc_kind) = zonkType zonk_unbound_kind_var tc_kind `thenNF_Tc` \ kind ->
363                               returnNF_Tc (name, kind)
364
365         -- When zonking a kind, we want to
366         --      zonk a *kind* variable to (Type *)
367         --      zonk a *boxity* variable to *
368     zonk_unbound_kind_var kv | tyVarKind kv `eqKind` superKind   = putTcTyVar kv liftedTypeKind
369                              | tyVarKind kv `eqKind` superBoxity = putTcTyVar kv liftedBoxity
370                              | otherwise                         = pprPanic "zonkKindEnv" (ppr kv)
371                         
372 zonkTcTypeToType :: TcType -> NF_TcM Type
373 zonkTcTypeToType ty = zonkType zonk_unbound_tyvar ty
374   where
375         -- Zonk a mutable but unbound type variable to
376         --      Void            if it has kind Lifted
377         --      :Void           otherwise
378         -- We know it's unbound even though we don't carry an environment,
379         -- because at the binding site for a type variable we bind the
380         -- mutable tyvar to a fresh immutable one.  So the mutable store
381         -- plays the role of an environment.  If we come across a mutable
382         -- type variable that isn't so bound, it must be completely free.
383     zonk_unbound_tyvar tv
384         | kind `eqKind` liftedTypeKind || kind `eqKind` openTypeKind
385         = putTcTyVar tv voidTy  -- Just to avoid creating a new tycon in
386                                 -- this vastly common case
387         | otherwise
388         = putTcTyVar tv (TyConApp (mk_void_tycon tv kind) [])
389         where
390           kind = tyVarKind tv
391
392     mk_void_tycon tv kind       -- Make a new TyCon with the same kind as the 
393                                 -- type variable tv.  Same name too, apart from
394                                 -- making it start with a colon (sigh)
395                 -- I dread to think what will happen if this gets out into an 
396                 -- interface file.  Catastrophe likely.  Major sigh.
397         = pprTrace "Urk! Inventing strangely-kinded void TyCon" (ppr tc_name) $
398           mkPrimTyCon tc_name kind 0 [] VoidRep
399         where
400           tc_name = mkLocalName (getUnique tv) (mkDerivedTyConOcc (getOccName tv)) noSrcLoc
401
402 -- zonkTcTyVarToTyVar is applied to the *binding* occurrence 
403 -- of a type variable, at the *end* of type checking.  It changes
404 -- the *mutable* type variable into an *immutable* one.
405 -- 
406 -- It does this by making an immutable version of tv and binds tv to it.
407 -- Now any bound occurences of the original type variable will get 
408 -- zonked to the immutable version.
409
410 zonkTcTyVarToTyVar :: TcTyVar -> NF_TcM TyVar
411 zonkTcTyVarToTyVar tv
412   = let
413                 -- Make an immutable version, defaulting 
414                 -- the kind to lifted if necessary
415         immut_tv    = mkTyVar (tyVarName tv) (defaultKind (tyVarKind tv))
416         immut_tv_ty = mkTyVarTy immut_tv
417
418         zap tv = putTcTyVar tv immut_tv_ty
419                 -- Bind the mutable version to the immutable one
420     in 
421         -- If the type variable is mutable, then bind it to immut_tv_ty
422         -- so that all other occurrences of the tyvar will get zapped too
423     zonkTyVar zap tv            `thenNF_Tc` \ ty2 ->
424
425     WARN( not (immut_tv_ty `tcEqType` ty2), ppr tv $$ ppr immut_tv $$ ppr ty2 )
426
427     returnNF_Tc immut_tv
428 \end{code}
429
430
431 %************************************************************************
432 %*                                                                      *
433 \subsection{Zonking -- the main work-horses: zonkType, zonkTyVar}
434 %*                                                                      *
435 %*              For internal use only!                                  *
436 %*                                                                      *
437 %************************************************************************
438
439 \begin{code}
440 -- zonkType is used for Kinds as well
441
442 -- For unbound, mutable tyvars, zonkType uses the function given to it
443 -- For tyvars bound at a for-all, zonkType zonks them to an immutable
444 --      type variable and zonks the kind too
445
446 zonkType :: (TcTyVar -> NF_TcM Type)    -- What to do with unbound mutable type variables
447                                         -- see zonkTcType, and zonkTcTypeToType
448          -> TcType
449          -> NF_TcM Type
450 zonkType unbound_var_fn ty
451   = go ty
452   where
453     go (TyConApp tycon tys)       = mapNF_Tc go tys     `thenNF_Tc` \ tys' ->
454                                     returnNF_Tc (TyConApp tycon tys')
455
456     go (NoteTy (SynNote ty1) ty2) = go ty1              `thenNF_Tc` \ ty1' ->
457                                     go ty2              `thenNF_Tc` \ ty2' ->
458                                     returnNF_Tc (NoteTy (SynNote ty1') ty2')
459
460     go (NoteTy (FTVNote _) ty2)   = go ty2      -- Discard free-tyvar annotations
461
462     go (SourceTy p)               = go_pred p           `thenNF_Tc` \ p' ->
463                                     returnNF_Tc (SourceTy p')
464
465     go (FunTy arg res)            = go arg              `thenNF_Tc` \ arg' ->
466                                     go res              `thenNF_Tc` \ res' ->
467                                     returnNF_Tc (FunTy arg' res')
468  
469     go (AppTy fun arg)            = go fun              `thenNF_Tc` \ fun' ->
470                                     go arg              `thenNF_Tc` \ arg' ->
471                                     returnNF_Tc (mkAppTy fun' arg')
472
473     go (UsageTy u ty)             = go u                `thenNF_Tc` \ u'  ->
474                                     go ty               `thenNF_Tc` \ ty' ->
475                                     returnNF_Tc (UsageTy u' ty')
476
477         -- The two interesting cases!
478     go (TyVarTy tyvar)     = zonkTyVar unbound_var_fn tyvar
479
480     go (ForAllTy tyvar ty) = zonkTcTyVarToTyVar tyvar   `thenNF_Tc` \ tyvar' ->
481                              go ty                      `thenNF_Tc` \ ty' ->
482                              returnNF_Tc (ForAllTy tyvar' ty')
483
484     go_pred (ClassP c tys) = mapNF_Tc go tys    `thenNF_Tc` \ tys' ->
485                              returnNF_Tc (ClassP c tys')
486     go_pred (NType tc tys) = mapNF_Tc go tys    `thenNF_Tc` \ tys' ->
487                              returnNF_Tc (NType tc tys')
488     go_pred (IParam n ty) = go ty               `thenNF_Tc` \ ty' ->
489                             returnNF_Tc (IParam n ty')
490
491 zonkTyVar :: (TcTyVar -> NF_TcM Type)           -- What to do for an unbound mutable variable
492           -> TcTyVar -> NF_TcM TcType
493 zonkTyVar unbound_var_fn tyvar 
494   | not (isMutTyVar tyvar)      -- Not a mutable tyvar.  This can happen when
495                                 -- zonking a forall type, when the bound type variable
496                                 -- needn't be mutable
497   = ASSERT( isTyVar tyvar )             -- Should not be any immutable kind vars
498     returnNF_Tc (TyVarTy tyvar)
499
500   | otherwise
501   =  getTcTyVar tyvar   `thenNF_Tc` \ maybe_ty ->
502      case maybe_ty of
503           Nothing       -> unbound_var_fn tyvar                 -- Mutable and unbound
504           Just other_ty -> zonkType unbound_var_fn other_ty     -- Bound
505 \end{code}
506
507
508
509 %************************************************************************
510 %*                                                                      *
511 \subsection{Checking a user type}
512 %*                                                                      *
513 %************************************************************************
514
515 When dealing with a user-written type, we first translate it from an HsType
516 to a Type, performing kind checking, and then check various things that should 
517 be true about it.  We don't want to perform these checks at the same time
518 as the initial translation because (a) they are unnecessary for interface-file
519 types and (b) when checking a mutually recursive group of type and class decls,
520 we can't "look" at the tycons/classes yet.
521
522 One thing we check for is 'rank'.  
523
524         Rank 0:         monotypes (no foralls)
525         Rank 1:         foralls at the front only, Rank 0 inside
526         Rank 2:         foralls at the front, Rank 1 on left of fn arrow,
527
528         basic ::= tyvar | T basic ... basic
529
530         r2  ::= forall tvs. cxt => r2a
531         r2a ::= r1 -> r2a | basic
532         r1  ::= forall tvs. cxt => r0
533         r0  ::= r0 -> r0 | basic
534         
535
536 \begin{code}
537 data UserTypeCtxt 
538   = FunSigCtxt Name     -- Function type signature
539   | ExprSigCtxt         -- Expression type signature
540   | ConArgCtxt Name     -- Data constructor argument
541   | TySynCtxt Name      -- RHS of a type synonym decl
542   | GenPatCtxt          -- Pattern in generic decl
543                         --      f{| a+b |} (Inl x) = ...
544   | PatSigCtxt          -- Type sig in pattern
545                         --      f (x::t) = ...
546   | ResSigCtxt          -- Result type sig
547                         --      f x :: t = ....
548   | ForSigCtxt Name     -- Foreign inport or export signature
549
550 pprUserTypeCtxt (FunSigCtxt n) = ptext SLIT("the type signature for") <+> quotes (ppr n)
551 pprUserTypeCtxt ExprSigCtxt    = ptext SLIT("an expression type signature")
552 pprUserTypeCtxt (ConArgCtxt c) = ptext SLIT("the type of constructor") <+> quotes (ppr c)
553 pprUserTypeCtxt (TySynCtxt c)  = ptext SLIT("the RHS of a type synonym declaration") <+> quotes (ppr c)
554 pprUserTypeCtxt GenPatCtxt     = ptext SLIT("the type pattern of a generic definition")
555 pprUserTypeCtxt PatSigCtxt     = ptext SLIT("a pattern type signature")
556 pprUserTypeCtxt ResSigCtxt     = ptext SLIT("a result type signature")
557 pprUserTypeCtxt (ForSigCtxt n) = ptext SLIT("the foreign signature for") <+> quotes (ppr n)
558 \end{code}
559
560 \begin{code}
561 checkValidType :: UserTypeCtxt -> Type -> TcM ()
562 -- Checks that the type is valid for the given context
563 checkValidType ctxt ty
564   = doptsTc Opt_GlasgowExts     `thenNF_Tc` \ gla_exts ->
565     let 
566         rank = case ctxt of
567                  GenPatCtxt               -> 0
568                  PatSigCtxt               -> 0
569                  ResSigCtxt               -> 0
570                  ExprSigCtxt              -> 1
571                  FunSigCtxt _ | gla_exts  -> 2
572                               | otherwise -> 1
573                  ConArgCtxt _ | gla_exts  -> 2  -- We are given the type of the entire
574                               | otherwise -> 1  -- constructor; hence rank 1 is ok
575                  TySynCtxt _  | gla_exts  -> 1
576                               | otherwise -> 0
577                  ForSigCtxt _             -> 1
578
579         actual_kind = typeKind ty
580
581         actual_kind_is_lifted = actual_kind `eqKind` liftedTypeKind
582
583         kind_ok = case ctxt of
584                         TySynCtxt _  -> True    -- Any kind will do
585                         GenPatCtxt   -> actual_kind_is_lifted
586                         ForSigCtxt _ -> actual_kind_is_lifted
587                         other        -> isTypeKind actual_kind
588     in
589     tcAddErrCtxt (checkTypeCtxt ctxt ty)        $
590
591         -- Check that the thing has kind Type, and is lifted if necessary
592     checkTc kind_ok (kindErr actual_kind)       `thenTc_`
593
594         -- Check the internal validity of the type itself
595     check_poly_type rank ty
596
597 -- Notes re TySynCtxt
598 -- We allow type synonyms that aren't types; e.g.  type List = []
599 --
600 -- If the RHS mentions tyvars that aren't in scope, we'll 
601 -- quantify over them:
602 --      e.g.    type T = a->a
603 -- will become  type T = forall a. a->a
604 --
605 -- With gla-exts that's right, but for H98 we should complain. 
606
607
608 ----------------------------------------
609 type Rank = Int
610 check_poly_type :: Rank -> Type -> TcM ()
611 check_poly_type rank ty 
612   | rank == 0 
613   = check_tau_type 0 False ty
614   | otherwise   -- rank > 0
615   = let
616         (tvs, theta, tau) = tcSplitSigmaTy ty
617     in
618     check_valid_theta SigmaCtxt theta   `thenTc_`
619     check_tau_type (rank-1) False tau   `thenTc_`
620     checkAmbiguity tvs theta tau
621
622 ----------------------------------------
623 check_arg_type :: Type -> TcM ()
624 -- The sort of type that can instantiate a type variable,
625 -- or be the argument of a type constructor.
626 -- Not an unboxed tuple, not a forall.
627 -- Other unboxed types are very occasionally allowed as type
628 -- arguments depending on the kind of the type constructor
629 -- 
630 -- For example, we want to reject things like:
631 --
632 --      instance Ord a => Ord (forall s. T s a)
633 -- and
634 --      g :: T s (forall b.b)
635 --
636 -- NB: unboxed tuples can have polymorphic or unboxed args.
637 --     This happens in the workers for functions returning
638 --     product types with polymorphic components.
639 --     But not in user code
640 -- 
641 -- Question: what about nested unboxed tuples?
642 --           Currently rejected.
643 check_arg_type ty 
644   = check_tau_type 0 False ty   `thenTc_` 
645     checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty)
646
647 ----------------------------------------
648 check_tau_type :: Rank -> Bool -> Type -> TcM ()
649 -- Rank is allowed rank for function args
650 -- No foralls otherwise
651 -- Bool is True iff unboxed tuple are allowed here
652
653 check_tau_type rank ubx_tup_ok ty@(UsageTy _ _)  = addErrTc (usageTyErr ty)
654 check_tau_type rank ubx_tup_ok ty@(ForAllTy _ _) = addErrTc (forAllTyErr ty)
655 check_tau_type rank ubx_tup_ok (SourceTy sty)    = getDOptsTc           `thenNF_Tc` \ dflags ->
656                                                    check_source_ty dflags TypeCtxt sty
657 check_tau_type rank ubx_tup_ok (TyVarTy _)       = returnTc ()
658 check_tau_type rank ubx_tup_ok ty@(FunTy arg_ty res_ty)
659   = check_poly_type rank      arg_ty    `thenTc_`
660     check_tau_type  rank True res_ty
661
662 check_tau_type rank ubx_tup_ok (AppTy ty1 ty2)
663   = check_arg_type ty1 `thenTc_` check_arg_type ty2
664
665 check_tau_type rank ubx_tup_ok (NoteTy note ty)
666   = check_note note `thenTc_` check_tau_type rank ubx_tup_ok ty
667
668 check_tau_type rank ubx_tup_ok ty@(TyConApp tc tys)
669   = mapTc_ check_arg_type tys                                           `thenTc_`
670     checkTc (not (isSynTyCon tc)          || syn_arity_ok) arity_msg    `thenTc_`
671     checkTc (not (isUnboxedTupleTyCon tc) || ubx_tup_ok)   ubx_tup_msg
672   where
673     syn_arity_ok = tc_arity <= n_args
674                 -- It's OK to have an *over-applied* type synonym
675                 --      data Tree a b = ...
676                 --      type Foo a = Tree [a]
677                 --      f :: Foo a b -> ...
678     n_args    = length tys
679     tc_arity  = tyConArity tc
680
681     arity_msg   = arityErr "Type synonym" (tyConName tc) tc_arity n_args
682     ubx_tup_msg = ubxArgTyErr ty
683
684 ----------------------------------------
685 check_note (FTVNote _)  = returnTc ()
686 check_note (SynNote ty) = check_tau_type 0 False ty
687 \end{code}
688
689
690 \begin{code}
691 data SourceTyCtxt
692   = ClassSCCtxt Name    -- Superclasses of clas
693   | SigmaCtxt           -- Context of a normal for-all type
694   | DataTyCtxt Name     -- Context of a data decl
695   | TypeCtxt            -- Source type in an ordinary type
696   | InstDeclCtxt        -- Context of an instance decl
697                 
698 pprSourceTyCtxt (ClassSCCtxt c) = ptext SLIT("the super-classes of class") <+> quotes (ppr c)
699 pprSourceTyCtxt SigmaCtxt       = ptext SLIT("the context of a polymorphic type")
700 pprSourceTyCtxt (DataTyCtxt tc) = ptext SLIT("the context of the data type declaration for") <+> quotes (ppr tc)
701 pprSourceTyCtxt InstDeclCtxt    = ptext SLIT("the context of an instance declaration")
702 pprSourceTyCtxt TypeCtxt        = ptext SLIT("the context of a type")
703 \end{code}
704
705 \begin{code}
706 checkValidTheta :: SourceTyCtxt -> ThetaType -> TcM ()
707 checkValidTheta ctxt theta 
708   = tcAddErrCtxt (checkThetaCtxt ctxt theta) (check_valid_theta ctxt theta)
709
710 -------------------------
711 check_valid_theta ctxt []
712   = returnTc ()
713 check_valid_theta ctxt theta
714   = getDOptsTc                                  `thenNF_Tc` \ dflags ->
715     warnTc (not (null dups)) (dupPredWarn dups) `thenNF_Tc_`
716     mapTc_ (check_source_ty dflags ctxt) theta
717   where
718     (_,dups) = removeDups tcCmpPred theta
719
720 -------------------------
721 check_source_ty dflags ctxt pred@(ClassP cls tys)
722   =     -- Class predicates are valid in all contexts
723     mapTc_ check_arg_type tys                   `thenTc_`
724     checkTc (arity == n_tys) arity_err          `thenTc_`
725     checkTc (all tyvar_head tys || arby_preds_ok) (predTyVarErr pred)
726
727   where
728     class_name = className cls
729     arity      = classArity cls
730     n_tys      = length tys
731     arity_err  = arityErr "Class" class_name arity n_tys
732
733     arby_preds_ok = case ctxt of
734                         InstDeclCtxt -> dopt Opt_AllowUndecidableInstances dflags
735                         other        -> dopt Opt_GlasgowExts               dflags
736
737 check_source_ty dflags SigmaCtxt (IParam name ty) = check_arg_type ty
738 check_source_ty dflags TypeCtxt  (NType tc tys)   = mapTc_ check_arg_type tys
739
740 -- Catch-all
741 check_source_ty dflags ctxt sty = failWithTc (badSourceTyErr sty)
742
743 -------------------------
744 tyvar_head ty                   -- Haskell 98 allows predicates of form 
745   | tcIsTyVarTy ty = True       --      C (a ty1 .. tyn)
746   | otherwise                   -- where a is a type variable
747   = case tcSplitAppTy_maybe ty of
748         Just (ty, _) -> tyvar_head ty
749         Nothing      -> False
750 \end{code}
751
752 Check for ambiguity
753 ~~~~~~~~~~~~~~~~~~~
754           forall V. P => tau
755 is ambiguous if P contains generic variables
756 (i.e. one of the Vs) that are not mentioned in tau
757
758 However, we need to take account of functional dependencies
759 when we speak of 'mentioned in tau'.  Example:
760         class C a b | a -> b where ...
761 Then the type
762         forall x y. (C x y) => x
763 is not ambiguous because x is mentioned and x determines y
764
765 NOTE: In addition, GHC insists that at least one type variable
766 in each constraint is in V.  So we disallow a type like
767         forall a. Eq b => b -> b
768 even in a scope where b is in scope.
769 This is the is_free test below.
770
771 NB; the ambiguity check is only used for *user* types, not for types
772 coming from inteface files.  The latter can legitimately have
773 ambiguous types. Example
774
775    class S a where s :: a -> (Int,Int)
776    instance S Char where s _ = (1,1)
777    f:: S a => [a] -> Int -> (Int,Int)
778    f (_::[a]) x = (a*x,b)
779         where (a,b) = s (undefined::a)
780
781 Here the worker for f gets the type
782         fw :: forall a. S a => Int -> (# Int, Int #)
783
784 If the list of tv_names is empty, we have a monotype, and then we
785 don't need to check for ambiguity either, because the test can't fail
786 (see is_ambig).
787
788 \begin{code}
789 checkAmbiguity :: [TyVar] -> ThetaType -> TauType -> TcM ()
790 checkAmbiguity forall_tyvars theta tau
791   = mapTc_ check_pred theta     `thenTc_`
792     returnTc ()
793   where
794     tau_vars          = tyVarsOfType tau
795     extended_tau_vars = grow theta tau_vars
796
797     is_ambig ct_var   = (ct_var `elem` forall_tyvars) &&
798                         not (ct_var `elemVarSet` extended_tau_vars)
799     is_free ct_var    = not (ct_var `elem` forall_tyvars)
800     
801     check_pred pred = checkTc (not any_ambig)                 (ambigErr pred) `thenTc_`
802                       checkTc (isIPPred pred || not all_free) (freeErr  pred)
803              where 
804                 ct_vars   = varSetElems (tyVarsOfPred pred)
805                 all_free  = all is_free ct_vars
806                 any_ambig = any is_ambig ct_vars
807 \end{code}
808
809
810 \begin{code}
811 ambigErr pred
812   = sep [ptext SLIT("Ambiguous constraint") <+> quotes (pprPred pred),
813          nest 4 (ptext SLIT("At least one of the forall'd type variables mentioned by the constraint") $$
814                  ptext SLIT("must be reachable from the type after the =>"))]
815
816 freeErr pred
817   = sep [ptext SLIT("All of the type variables in the constraint") <+> quotes (pprPred pred) <+>
818                    ptext SLIT("are already in scope"),
819          nest 4 (ptext SLIT("At least one must be universally quantified here"))
820     ]
821
822 forAllTyErr     ty = ptext SLIT("Illegal polymorphic type:") <+> ppr ty
823 usageTyErr      ty = ptext SLIT("Illegal usage type:") <+> ppr ty
824 unliftedArgErr  ty = ptext SLIT("Illegal unlifted type argument:") <+> ppr ty
825 ubxArgTyErr     ty = ptext SLIT("Illegal unboxed tuple type as function argument:") <+> ppr ty
826 badSourceTyErr sty = ptext SLIT("Illegal constraint") <+> pprSourceType sty
827 predTyVarErr pred  = ptext SLIT("Non-type variables in constraint:") <+> pprPred pred
828 kindErr kind       = ptext SLIT("Expecting an ordinary type, but found a type of kind") <+> ppr kind
829 dupPredWarn dups   = ptext SLIT("Duplicate constraint(s):") <+> pprWithCommas pprPred (map head dups)
830
831 checkTypeCtxt ctxt ty
832   = vcat [ptext SLIT("In the type:") <+> ppr_ty,
833           ptext SLIT("While checking") <+> pprUserTypeCtxt ctxt ]
834   where  
835         -- Hack alert.  If there are no tyvars, (ppr sigma_ty) will print
836         -- something strange like {Eq k} -> k -> k, because there is no
837         -- ForAll at the top of the type.  Since this is going to the user
838         -- we want it to look like a proper Haskell type even then; hence the hack
839         -- 
840         -- This shows up in the complaint about
841         --      case C a where
842         --        op :: Eq a => a -> a
843     ppr_ty | null forall_tyvars = pprTheta theta <+> ptext SLIT("=>") <+> ppr tau
844            | otherwise          = ppr ty
845     (forall_tyvars, theta, tau) = tcSplitSigmaTy ty
846
847 checkThetaCtxt ctxt theta
848   = vcat [ptext SLIT("In the context:") <+> pprTheta theta,
849           ptext SLIT("While checking") <+> pprSourceTyCtxt ctxt ]
850 \end{code}
851
852
853 %************************************************************************
854 %*                                                                      *
855 \subsection{Kind unification}
856 %*                                                                      *
857 %************************************************************************
858
859 \begin{code}
860 unifyKind :: TcKind                 -- Expected
861           -> TcKind                 -- Actual
862           -> TcM ()
863 unifyKind k1 k2 
864   = tcAddErrCtxtM (unifyCtxt "kind" k1 k2) $
865     uTys k1 k1 k2 k2
866
867 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
868 unifyKinds []       []       = returnTc ()
869 unifyKinds (k1:ks1) (k2:ks2) = unifyKind k1 k2  `thenTc_`
870                                unifyKinds ks1 ks2
871 unifyKinds _ _ = panic "unifyKinds: length mis-match"
872 \end{code}
873
874 \begin{code}
875 unifyOpenTypeKind :: TcKind -> TcM ()   
876 -- Ensures that the argument kind is of the form (Type bx)
877 -- for some boxity bx
878
879 unifyOpenTypeKind ty@(TyVarTy tyvar)
880   = getTcTyVar tyvar    `thenNF_Tc` \ maybe_ty ->
881     case maybe_ty of
882         Just ty' -> unifyOpenTypeKind ty'
883         other    -> unify_open_kind_help ty
884
885 unifyOpenTypeKind ty
886   | isTypeKind ty = returnTc ()
887   | otherwise     = unify_open_kind_help ty
888
889 unify_open_kind_help ty -- Revert to ordinary unification
890   = newBoxityVar        `thenNF_Tc` \ boxity ->
891     unifyKind ty (mkTyConApp typeCon [boxity])
892 \end{code}
893
894
895 %************************************************************************
896 %*                                                                      *
897 \subsection[Unify-exported]{Exported unification functions}
898 %*                                                                      *
899 %************************************************************************
900
901 The exported functions are all defined as versions of some
902 non-exported generic functions.
903
904 Unify two @TauType@s.  Dead straightforward.
905
906 \begin{code}
907 unifyTauTy :: TcTauType -> TcTauType -> TcM ()
908 unifyTauTy ty1 ty2      -- ty1 expected, ty2 inferred
909   = tcAddErrCtxtM (unifyCtxt "type" ty1 ty2) $
910     uTys ty1 ty1 ty2 ty2
911 \end{code}
912
913 @unifyTauTyList@ unifies corresponding elements of two lists of
914 @TauType@s.  It uses @uTys@ to do the real work.  The lists should be
915 of equal length.  We charge down the list explicitly so that we can
916 complain if their lengths differ.
917
918 \begin{code}
919 unifyTauTyLists :: [TcTauType] -> [TcTauType] ->  TcM ()
920 unifyTauTyLists []           []         = returnTc ()
921 unifyTauTyLists (ty1:tys1) (ty2:tys2) = uTys ty1 ty1 ty2 ty2   `thenTc_`
922                                         unifyTauTyLists tys1 tys2
923 unifyTauTyLists ty1s ty2s = panic "Unify.unifyTauTyLists: mismatched type lists!"
924 \end{code}
925
926 @unifyTauTyList@ takes a single list of @TauType@s and unifies them
927 all together.  It is used, for example, when typechecking explicit
928 lists, when all the elts should be of the same type.
929
930 \begin{code}
931 unifyTauTyList :: [TcTauType] -> TcM ()
932 unifyTauTyList []                = returnTc ()
933 unifyTauTyList [ty]              = returnTc ()
934 unifyTauTyList (ty1:tys@(ty2:_)) = unifyTauTy ty1 ty2   `thenTc_`
935                                    unifyTauTyList tys
936 \end{code}
937
938 %************************************************************************
939 %*                                                                      *
940 \subsection[Unify-uTys]{@uTys@: getting down to business}
941 %*                                                                      *
942 %************************************************************************
943
944 @uTys@ is the heart of the unifier.  Each arg happens twice, because
945 we want to report errors in terms of synomyms if poss.  The first of
946 the pair is used in error messages only; it is always the same as the
947 second, except that if the first is a synonym then the second may be a
948 de-synonym'd version.  This way we get better error messages.
949
950 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
951
952 \begin{code}
953 uTys :: TcTauType -> TcTauType  -- Error reporting ty1 and real ty1
954                                 -- ty1 is the *expected* type
955
956      -> TcTauType -> TcTauType  -- Error reporting ty2 and real ty2
957                                 -- ty2 is the *actual* type
958      -> TcM ()
959
960         -- Always expand synonyms (see notes at end)
961         -- (this also throws away FTVs)
962 uTys ps_ty1 (NoteTy n1 ty1) ps_ty2 ty2 = uTys ps_ty1 ty1 ps_ty2 ty2
963 uTys ps_ty1 ty1 ps_ty2 (NoteTy n2 ty2) = uTys ps_ty1 ty1 ps_ty2 ty2
964
965         -- Ignore usage annotations inside typechecker
966 uTys ps_ty1 (UsageTy _ ty1) ps_ty2 ty2 = uTys ps_ty1 ty1 ps_ty2 ty2
967 uTys ps_ty1 ty1 ps_ty2 (UsageTy _ ty2) = uTys ps_ty1 ty1 ps_ty2 ty2
968
969         -- Variables; go for uVar
970 uTys ps_ty1 (TyVarTy tyvar1) ps_ty2 ty2 = uVar False tyvar1 ps_ty2 ty2
971 uTys ps_ty1 ty1 ps_ty2 (TyVarTy tyvar2) = uVar True  tyvar2 ps_ty1 ty1
972                                         -- "True" means args swapped
973
974         -- Predicates
975 uTys _ (SourceTy (IParam n1 t1)) _ (SourceTy (IParam n2 t2))
976   | n1 == n2 = uTys t1 t1 t2 t2
977 uTys _ (SourceTy (ClassP c1 tys1)) _ (SourceTy (ClassP c2 tys2))
978   | c1 == c2 = unifyTauTyLists tys1 tys2
979 uTys _ (SourceTy (NType tc1 tys1)) _ (SourceTy (NType tc2 tys2))
980   | tc1 == tc2 = unifyTauTyLists tys1 tys2
981
982         -- Functions; just check the two parts
983 uTys _ (FunTy fun1 arg1) _ (FunTy fun2 arg2)
984   = uTys fun1 fun1 fun2 fun2    `thenTc_`    uTys arg1 arg1 arg2 arg2
985
986         -- Type constructors must match
987 uTys ps_ty1 (TyConApp con1 tys1) ps_ty2 (TyConApp con2 tys2)
988   | con1 == con2 && length tys1 == length tys2
989   = unifyTauTyLists tys1 tys2
990
991   | con1 == openKindCon
992         -- When we are doing kind checking, we might match a kind '?' 
993         -- against a kind '*' or '#'.  Notably, CCallable :: ? -> *, and
994         -- (CCallable Int) and (CCallable Int#) are both OK
995   = unifyOpenTypeKind ps_ty2
996
997         -- Applications need a bit of care!
998         -- They can match FunTy and TyConApp, so use splitAppTy_maybe
999         -- NB: we've already dealt with type variables and Notes,
1000         -- so if one type is an App the other one jolly well better be too
1001 uTys ps_ty1 (AppTy s1 t1) ps_ty2 ty2
1002   = case tcSplitAppTy_maybe ty2 of
1003         Just (s2,t2) -> uTys s1 s1 s2 s2        `thenTc_`    uTys t1 t1 t2 t2
1004         Nothing      -> unifyMisMatch ps_ty1 ps_ty2
1005
1006         -- Now the same, but the other way round
1007         -- Don't swap the types, because the error messages get worse
1008 uTys ps_ty1 ty1 ps_ty2 (AppTy s2 t2)
1009   = case tcSplitAppTy_maybe ty1 of
1010         Just (s1,t1) -> uTys s1 s1 s2 s2        `thenTc_`    uTys t1 t1 t2 t2
1011         Nothing      -> unifyMisMatch ps_ty1 ps_ty2
1012
1013         -- Not expecting for-alls in unification
1014         -- ... but the error message from the unifyMisMatch more informative
1015         -- than a panic message!
1016
1017         -- Anything else fails
1018 uTys ps_ty1 ty1 ps_ty2 ty2  = unifyMisMatch ps_ty1 ps_ty2
1019 \end{code}
1020
1021
1022 Notes on synonyms
1023 ~~~~~~~~~~~~~~~~~
1024 If you are tempted to make a short cut on synonyms, as in this
1025 pseudocode...
1026
1027 \begin{verbatim}
1028 -- NO   uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
1029 -- NO     = if (con1 == con2) then
1030 -- NO   -- Good news!  Same synonym constructors, so we can shortcut
1031 -- NO   -- by unifying their arguments and ignoring their expansions.
1032 -- NO   unifyTauTypeLists args1 args2
1033 -- NO    else
1034 -- NO   -- Never mind.  Just expand them and try again
1035 -- NO   uTys ty1 ty2
1036 \end{verbatim}
1037
1038 then THINK AGAIN.  Here is the whole story, as detected and reported
1039 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
1040 \begin{quotation}
1041 Here's a test program that should detect the problem:
1042
1043 \begin{verbatim}
1044         type Bogus a = Int
1045         x = (1 :: Bogus Char) :: Bogus Bool
1046 \end{verbatim}
1047
1048 The problem with [the attempted shortcut code] is that
1049 \begin{verbatim}
1050         con1 == con2
1051 \end{verbatim}
1052 is not a sufficient condition to be able to use the shortcut!
1053 You also need to know that the type synonym actually USES all
1054 its arguments.  For example, consider the following type synonym
1055 which does not use all its arguments.
1056 \begin{verbatim}
1057         type Bogus a = Int
1058 \end{verbatim}
1059
1060 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
1061 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
1062 would fail, even though the expanded forms (both \tr{Int}) should
1063 match.
1064
1065 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
1066 unnecessarily bind \tr{t} to \tr{Char}.
1067
1068 ... You could explicitly test for the problem synonyms and mark them
1069 somehow as needing expansion, perhaps also issuing a warning to the
1070 user.
1071 \end{quotation}
1072
1073
1074 %************************************************************************
1075 %*                                                                      *
1076 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
1077 %*                                                                      *
1078 %************************************************************************
1079
1080 @uVar@ is called when at least one of the types being unified is a
1081 variable.  It does {\em not} assume that the variable is a fixed point
1082 of the substitution; rather, notice that @uVar@ (defined below) nips
1083 back into @uTys@ if it turns out that the variable is already bound.
1084
1085 \begin{code}
1086 uVar :: Bool            -- False => tyvar is the "expected"
1087                         -- True  => ty    is the "expected" thing
1088      -> TcTyVar
1089      -> TcTauType -> TcTauType  -- printing and real versions
1090      -> TcM ()
1091
1092 uVar swapped tv1 ps_ty2 ty2
1093   = getTcTyVar tv1      `thenNF_Tc` \ maybe_ty1 ->
1094     case maybe_ty1 of
1095         Just ty1 | swapped   -> uTys ps_ty2 ty2 ty1 ty1 -- Swap back
1096                  | otherwise -> uTys ty1 ty1 ps_ty2 ty2 -- Same order
1097         other       -> uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2
1098
1099         -- Expand synonyms; ignore FTVs
1100 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 (NoteTy n2 ty2)
1101   = uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2
1102
1103
1104         -- The both-type-variable case
1105 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2@(TyVarTy tv2)
1106
1107         -- Same type variable => no-op
1108   | tv1 == tv2
1109   = returnTc ()
1110
1111         -- Distinct type variables
1112         -- ASSERT maybe_ty1 /= Just
1113   | otherwise
1114   = getTcTyVar tv2      `thenNF_Tc` \ maybe_ty2 ->
1115     case maybe_ty2 of
1116         Just ty2' -> uUnboundVar swapped tv1 maybe_ty1 ty2' ty2'
1117
1118         Nothing | update_tv2
1119
1120                 -> WARN( not (k1 `hasMoreBoxityInfo` k2), (ppr tv1 <+> ppr k1) $$ (ppr tv2 <+> ppr k2) )
1121                    putTcTyVar tv2 (TyVarTy tv1)         `thenNF_Tc_`
1122                    returnTc ()
1123                 |  otherwise
1124
1125                 -> WARN( not (k2 `hasMoreBoxityInfo` k1), (ppr tv2 <+> ppr k2) $$ (ppr tv1 <+> ppr k1) )
1126                    (putTcTyVar tv1 ps_ty2               `thenNF_Tc_`
1127                     returnTc ())
1128   where
1129     k1 = tyVarKind tv1
1130     k2 = tyVarKind tv2
1131     update_tv2 = (k2 `eqKind` openTypeKind) || (not (k1 `eqKind` openTypeKind) && nicer_to_update_tv2)
1132                         -- Try to get rid of open type variables as soon as poss
1133
1134     nicer_to_update_tv2 =  isSigTyVar tv1 
1135                                 -- Don't unify a signature type variable if poss
1136                         || isSystemName (varName tv2)
1137                                 -- Try to update sys-y type variables in preference to sig-y ones
1138
1139         -- Second one isn't a type variable
1140 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 non_var_ty2
1141   =     -- Check that the kinds match
1142     checkKinds swapped tv1 non_var_ty2                  `thenTc_`
1143
1144         -- Check that tv1 isn't a type-signature type variable
1145     checkTcM (not (isSigTyVar tv1))
1146              (failWithTcM (unifyWithSigErr tv1 ps_ty2)) `thenTc_`
1147
1148         -- Check that we aren't losing boxity info (shouldn't happen)
1149     warnTc (not (typeKind non_var_ty2 `hasMoreBoxityInfo` tyVarKind tv1))
1150            ((ppr tv1 <+> ppr (tyVarKind tv1)) $$ 
1151              (ppr non_var_ty2 <+> ppr (typeKind non_var_ty2)))          `thenNF_Tc_` 
1152
1153         -- Occurs check
1154         -- Basically we want to update     tv1 := ps_ty2
1155         -- because ps_ty2 has type-synonym info, which improves later error messages
1156         -- 
1157         -- But consider 
1158         --      type A a = ()
1159         --
1160         --      f :: (A a -> a -> ()) -> ()
1161         --      f = \ _ -> ()
1162         --
1163         --      x :: ()
1164         --      x = f (\ x p -> p x)
1165         --
1166         -- In the application (p x), we try to match "t" with "A t".  If we go
1167         -- ahead and bind t to A t (= ps_ty2), we'll lead the type checker into 
1168         -- an infinite loop later.
1169         -- But we should not reject the program, because A t = ().
1170         -- Rather, we should bind t to () (= non_var_ty2).
1171         -- 
1172         -- That's why we have this two-state occurs-check
1173     zonkTcType ps_ty2                                   `thenNF_Tc` \ ps_ty2' ->
1174     if not (tv1 `elemVarSet` tyVarsOfType ps_ty2') then
1175         putTcTyVar tv1 ps_ty2'                          `thenNF_Tc_`
1176         returnTc ()
1177     else
1178     zonkTcType non_var_ty2                              `thenNF_Tc` \ non_var_ty2' ->
1179     if not (tv1 `elemVarSet` tyVarsOfType non_var_ty2') then
1180         -- This branch rarely succeeds, except in strange cases
1181         -- like that in the example above
1182         putTcTyVar tv1 non_var_ty2'                     `thenNF_Tc_`
1183         returnTc ()
1184     else
1185     failWithTcM (unifyOccurCheck tv1 ps_ty2')
1186
1187
1188 checkKinds swapped tv1 ty2
1189 -- We're about to unify a type variable tv1 with a non-tyvar-type ty2.
1190 -- We need to check that we don't unify a lifted type variable with an
1191 -- unlifted type: e.g.  (id 3#) is illegal
1192   | tk1 `eqKind` liftedTypeKind && tk2 `eqKind` unliftedTypeKind
1193   = tcAddErrCtxtM (unifyKindCtxt swapped tv1 ty2)       $
1194     unifyMisMatch k1 k2
1195   | otherwise
1196   = returnTc ()
1197   where
1198     (k1,k2) | swapped   = (tk2,tk1)
1199             | otherwise = (tk1,tk2)
1200     tk1 = tyVarKind tv1
1201     tk2 = typeKind ty2
1202 \end{code}
1203
1204
1205 %************************************************************************
1206 %*                                                                      *
1207 \subsection[Unify-fun]{@unifyFunTy@}
1208 %*                                                                      *
1209 %************************************************************************
1210
1211 @unifyFunTy@ is used to avoid the fruitless creation of type variables.
1212
1213 \begin{code}
1214 unifyFunTy :: TcType                            -- Fail if ty isn't a function type
1215            -> TcM (TcType, TcType)      -- otherwise return arg and result types
1216
1217 unifyFunTy ty@(TyVarTy tyvar)
1218   = getTcTyVar tyvar    `thenNF_Tc` \ maybe_ty ->
1219     case maybe_ty of
1220         Just ty' -> unifyFunTy ty'
1221         other       -> unify_fun_ty_help ty
1222
1223 unifyFunTy ty
1224   = case tcSplitFunTy_maybe ty of
1225         Just arg_and_res -> returnTc arg_and_res
1226         Nothing          -> unify_fun_ty_help ty
1227
1228 unify_fun_ty_help ty    -- Special cases failed, so revert to ordinary unification
1229   = newTyVarTy openTypeKind     `thenNF_Tc` \ arg ->
1230     newTyVarTy openTypeKind     `thenNF_Tc` \ res ->
1231     unifyTauTy ty (mkFunTy arg res)     `thenTc_`
1232     returnTc (arg,res)
1233 \end{code}
1234
1235 \begin{code}
1236 unifyListTy :: TcType              -- expected list type
1237             -> TcM TcType      -- list element type
1238
1239 unifyListTy ty@(TyVarTy tyvar)
1240   = getTcTyVar tyvar    `thenNF_Tc` \ maybe_ty ->
1241     case maybe_ty of
1242         Just ty' -> unifyListTy ty'
1243         other    -> unify_list_ty_help ty
1244
1245 unifyListTy ty
1246   = case tcSplitTyConApp_maybe ty of
1247         Just (tycon, [arg_ty]) | tycon == listTyCon -> returnTc arg_ty
1248         other                                       -> unify_list_ty_help ty
1249
1250 unify_list_ty_help ty   -- Revert to ordinary unification
1251   = newTyVarTy liftedTypeKind           `thenNF_Tc` \ elt_ty ->
1252     unifyTauTy ty (mkListTy elt_ty)     `thenTc_`
1253     returnTc elt_ty
1254 \end{code}
1255
1256 \begin{code}
1257 unifyTupleTy :: Boxity -> Arity -> TcType -> TcM [TcType]
1258 unifyTupleTy boxity arity ty@(TyVarTy tyvar)
1259   = getTcTyVar tyvar    `thenNF_Tc` \ maybe_ty ->
1260     case maybe_ty of
1261         Just ty' -> unifyTupleTy boxity arity ty'
1262         other    -> unify_tuple_ty_help boxity arity ty
1263
1264 unifyTupleTy boxity arity ty
1265   = case tcSplitTyConApp_maybe ty of
1266         Just (tycon, arg_tys)
1267                 |  isTupleTyCon tycon 
1268                 && tyConArity tycon == arity
1269                 && tupleTyConBoxity tycon == boxity
1270                 -> returnTc arg_tys
1271         other -> unify_tuple_ty_help boxity arity ty
1272
1273 unify_tuple_ty_help boxity arity ty
1274   = newTyVarTys arity kind                              `thenNF_Tc` \ arg_tys ->
1275     unifyTauTy ty (mkTupleTy boxity arity arg_tys)      `thenTc_`
1276     returnTc arg_tys
1277   where
1278     kind | isBoxed boxity = liftedTypeKind
1279          | otherwise      = openTypeKind
1280 \end{code}
1281
1282
1283 %************************************************************************
1284 %*                                                                      *
1285 \subsection[Unify-context]{Errors and contexts}
1286 %*                                                                      *
1287 %************************************************************************
1288
1289 Errors
1290 ~~~~~~
1291
1292 \begin{code}
1293 unifyCtxt s ty1 ty2 tidy_env    -- ty1 expected, ty2 inferred
1294   = zonkTcType ty1      `thenNF_Tc` \ ty1' ->
1295     zonkTcType ty2      `thenNF_Tc` \ ty2' ->
1296     returnNF_Tc (err ty1' ty2')
1297   where
1298     err ty1 ty2 = (env1, 
1299                    nest 4 
1300                         (vcat [
1301                            text "Expected" <+> text s <> colon <+> ppr tidy_ty1,
1302                            text "Inferred" <+> text s <> colon <+> ppr tidy_ty2
1303                         ]))
1304                   where
1305                     (env1, [tidy_ty1,tidy_ty2]) = tidyOpenTypes tidy_env [ty1,ty2]
1306
1307 unifyKindCtxt swapped tv1 ty2 tidy_env  -- not swapped => tv1 expected, ty2 inferred
1308         -- tv1 is zonked already
1309   = zonkTcType ty2      `thenNF_Tc` \ ty2' ->
1310     returnNF_Tc (err ty2')
1311   where
1312     err ty2 = (env2, ptext SLIT("When matching types") <+> 
1313                      sep [quotes pp_expected, ptext SLIT("and"), quotes pp_actual])
1314             where
1315               (pp_expected, pp_actual) | swapped   = (pp2, pp1)
1316                                        | otherwise = (pp1, pp2)
1317               (env1, tv1') = tidyTyVar tidy_env tv1
1318               (env2, ty2') = tidyOpenType  env1 ty2
1319               pp1 = ppr tv1'
1320               pp2 = ppr ty2'
1321
1322 unifyMisMatch ty1 ty2
1323   = zonkTcType ty1      `thenNF_Tc` \ ty1' ->
1324     zonkTcType ty2      `thenNF_Tc` \ ty2' ->
1325     let
1326         (env, [tidy_ty1, tidy_ty2]) = tidyOpenTypes emptyTidyEnv [ty1',ty2']
1327         msg = hang (ptext SLIT("Couldn't match"))
1328                    4 (sep [quotes (ppr tidy_ty1), 
1329                            ptext SLIT("against"), 
1330                            quotes (ppr tidy_ty2)])
1331     in
1332     failWithTcM (env, msg)
1333
1334 unifyWithSigErr tyvar ty
1335   = (env2, hang (ptext SLIT("Cannot unify the type-signature variable") <+> quotes (ppr tidy_tyvar))
1336               4 (ptext SLIT("with the type") <+> quotes (ppr tidy_ty)))
1337   where
1338     (env1, tidy_tyvar) = tidyTyVar emptyTidyEnv tyvar
1339     (env2, tidy_ty)    = tidyOpenType  env1     ty
1340
1341 unifyOccurCheck tyvar ty
1342   = (env2, hang (ptext SLIT("Occurs check: cannot construct the infinite type:"))
1343               4 (sep [ppr tidy_tyvar, char '=', ppr tidy_ty]))
1344   where
1345     (env1, tidy_tyvar) = tidyTyVar emptyTidyEnv tyvar
1346     (env2, tidy_ty)    = tidyOpenType  env1     ty
1347 \end{code}