[project @ 2003-06-24 07:58:18 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcUnify.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Type subsumption and unification}
5
6 \begin{code}
7 module TcUnify (
8         -- Full-blown subsumption
9   tcSubOff, tcSubExp, tcGen, 
10   checkSigTyVars, checkSigTyVarsWrt, sigCtxt, findGlobals,
11
12         -- Various unifications
13   unifyTauTy, unifyTauTyList, unifyTauTyLists, 
14   unifyKind, unifyKinds, unifyOpenTypeKind, unifyFunKind,
15
16   --------------------------------
17   -- Holes
18   Expected(..), newHole, readExpectedType, 
19   zapExpectedType, zapExpectedTo, zapExpectedBranches,
20   subFunTys,    unifyFunTy, 
21   zapToListTy,  unifyListTy, 
22   zapToPArrTy,  unifyPArrTy, 
23   zapToTupleTy, unifyTupleTy
24
25   ) where
26
27 #include "HsVersions.h"
28
29
30 import HsSyn            ( HsExpr(..) )
31 import TcHsSyn          ( mkHsLet,
32                           ExprCoFn, idCoercion, isIdCoercion, mkCoercion, (<.>), (<$>) )
33 import TypeRep          ( Type(..), SourceType(..), TyNote(..), openKindCon )
34
35 import TcRnMonad         -- TcType, amongst others
36 import TcType           ( TcKind, TcType, TcSigmaType, TcRhoType, TcTyVar, TcTauType,
37                           TcTyVarSet, TcThetaType, TyVarDetails(SigTv),
38                           isTauTy, isSigmaTy, mkFunTys,
39                           tcSplitAppTy_maybe, tcSplitTyConApp_maybe, 
40                           tcGetTyVar_maybe, tcGetTyVar, 
41                           mkFunTy, tyVarsOfType, mkPhiTy,
42                           typeKind, tcSplitFunTy_maybe, mkForAllTys,
43                           isSkolemTyVar, isUserTyVar, 
44                           tidyOpenType, tidyOpenTypes, tidyOpenTyVar, tidyOpenTyVars,
45                           eqKind, openTypeKind, liftedTypeKind, isTypeKind, mkArrowKind,
46                           hasMoreBoxityInfo, allDistinctTyVars
47                         )
48 import Inst             ( newDicts, instToId, tcInstCall )
49 import TcMType          ( getTcTyVar, putTcTyVar, tcInstType, newKindVar,
50                           newTyVarTy, newTyVarTys, newOpenTypeKind, 
51                           zonkTcType, zonkTcTyVars, zonkTcTyVarsAndFV )
52 import TcSimplify       ( tcSimplifyCheck )
53 import TysWiredIn       ( listTyCon, parrTyCon, mkListTy, mkPArrTy, mkTupleTy )
54 import TcEnv            ( tcGetGlobalTyVars, findGlobals )
55 import TyCon            ( tyConArity, isTupleTyCon, tupleTyConBoxity )
56 import PprType          ( pprType )
57 import Id               ( Id, mkSysLocal )
58 import Var              ( Var, varName, tyVarKind )
59 import VarSet           ( emptyVarSet, unitVarSet, unionVarSet, elemVarSet, varSetElems )
60 import VarEnv
61 import Name             ( isSystemName )
62 import ErrUtils         ( Message )
63 import BasicTypes       ( Boxity, Arity, isBoxed )
64 import Util             ( equalLength, lengthExceeds, notNull )
65 import Outputable
66 \end{code}
67
68 Notes on holes
69 ~~~~~~~~~~~~~~
70 * A hole is always filled in with an ordinary type, not another hole.
71
72 %************************************************************************
73 %*                                                                      *
74 \subsection{'hole' type variables}
75 %*                                                                      *
76 %************************************************************************
77
78 \begin{code}
79 data Expected ty = Infer (TcRef ty)     -- The hole to fill in for type inference
80                  | Check ty             -- The type to check during type checking
81
82 newHole :: TcM (TcRef ty)
83 newHole = newMutVar (error "Empty hole in typechecker")
84
85 readExpectedType :: Expected ty -> TcM ty
86 readExpectedType (Infer hole) = readMutVar hole
87 readExpectedType (Check ty)   = returnM ty
88
89 zapExpectedType :: Expected TcType -> TcM TcTauType
90 -- In the inference case, ensure we have a monotype
91 zapExpectedType (Infer hole)
92   = do { ty <- newTyVarTy openTypeKind ;
93          writeMutVar hole ty ;
94          return ty }
95
96 zapExpectedType (Check ty) = return ty
97
98 zapExpectedTo :: Expected TcType -> TcTauType -> TcM ()
99 zapExpectedTo (Infer hole) ty2 = writeMutVar hole ty2
100 zapExpectedTo (Check ty1)  ty2 = unifyTauTy ty1 ty2
101
102 zapExpectedBranches :: [a] -> Expected TcType -> TcM (Expected TcType)
103 -- Zap the expected type to a monotype if there is more than one branch
104 zapExpectedBranches branches exp_ty
105   | lengthExceeds branches 1 = zapExpectedType exp_ty   `thenM` \ exp_ty' -> 
106                                return (Check exp_ty')
107   | otherwise                = returnM exp_ty           
108
109 instance Outputable ty => Outputable (Expected ty) where
110   ppr (Check ty)   = ptext SLIT("Expected type") <+> ppr ty
111   ppr (Infer hole) = ptext SLIT("Inferring type")
112 \end{code}                 
113
114
115 %************************************************************************
116 %*                                                                      *
117 \subsection[Unify-fun]{@unifyFunTy@}
118 %*                                                                      *
119 %************************************************************************
120
121 @subFunTy@ and @unifyFunTy@ is used to avoid the fruitless 
122 creation of type variables.
123
124 * subFunTy is used when we might be faced with a "hole" type variable,
125   in which case we should create two new holes. 
126
127 * unifyFunTy is used when we expect to encounter only "ordinary" 
128   type variables, so we should create new ordinary type variables
129
130 \begin{code}
131 subFunTys :: [pat]
132          -> Expected TcRhoType  -- Fail if ty isn't a function type
133          -> ([(pat, Expected TcRhoType)] -> Expected TcRhoType -> TcM a)
134          -> TcM a
135
136 subFunTys pats (Infer hole) thing_inside
137   =     -- This is the interesting case
138     mapM new_pat_hole pats      `thenM` \ pats_w_holes ->
139     newHole                     `thenM` \ res_hole ->
140
141         -- Do the business
142     thing_inside pats_w_holes (Infer res_hole)  `thenM` \ answer ->
143
144         -- Extract the answers
145     mapM read_pat_hole pats_w_holes     `thenM` \ arg_tys ->
146     readMutVar res_hole                 `thenM` \ res_ty ->
147
148         -- Write the answer into the incoming hole
149     writeMutVar hole (mkFunTys arg_tys res_ty)  `thenM_` 
150
151         -- And return the answer
152     returnM answer
153   where
154     new_pat_hole pat = newHole `thenM` \ hole -> return (pat, Infer hole)
155     read_pat_hole (pat, Infer hole) = readMutVar hole
156
157 subFunTys pats (Check ty) thing_inside
158   = go pats ty          `thenM` \ (pats_w_tys, res_ty) ->
159     thing_inside pats_w_tys res_ty
160   where
161     go []         ty = return ([], Check ty)
162     go (pat:pats) ty = unifyFunTy ty    `thenM` \ (arg,res) ->
163                        go pats res      `thenM` \ (pats_w_tys, final_res) ->
164                        return ((pat, Check arg) : pats_w_tys, final_res)
165                  
166 unifyFunTy :: TcRhoType                 -- Fail if ty isn't a function type
167            -> TcM (TcType, TcType)      -- otherwise return arg and result types
168
169 unifyFunTy ty@(TyVarTy tyvar)
170   = getTcTyVar tyvar    `thenM` \ maybe_ty ->
171     case maybe_ty of
172         Just ty' -> unifyFunTy ty'
173         Nothing  -> unify_fun_ty_help ty
174
175 unifyFunTy ty
176   = case tcSplitFunTy_maybe ty of
177         Just arg_and_res -> returnM arg_and_res
178         Nothing          -> unify_fun_ty_help ty
179
180 unify_fun_ty_help ty    -- Special cases failed, so revert to ordinary unification
181   = newTyVarTy openTypeKind     `thenM` \ arg ->
182     newTyVarTy openTypeKind     `thenM` \ res ->
183     unifyTauTy ty (mkFunTy arg res)     `thenM_`
184     returnM (arg,res)
185 \end{code}
186
187 \begin{code}
188 zapToListTy :: Expected TcType -- expected list type
189             -> TcM TcType      -- list element type
190
191 zapToListTy (Check ty)   = unifyListTy ty
192 zapToListTy (Infer hole) = do { elt_ty <- newTyVarTy liftedTypeKind ;
193                                 writeMutVar hole (mkListTy elt_ty) ;
194                                 return elt_ty }
195
196 unifyListTy :: TcType -> TcM TcType
197 unifyListTy ty@(TyVarTy tyvar)
198   = getTcTyVar tyvar    `thenM` \ maybe_ty ->
199     case maybe_ty of
200         Just ty' -> unifyListTy ty'
201         other    -> unify_list_ty_help ty
202
203 unifyListTy ty
204   = case tcSplitTyConApp_maybe ty of
205         Just (tycon, [arg_ty]) | tycon == listTyCon -> returnM arg_ty
206         other                                       -> unify_list_ty_help ty
207
208 unify_list_ty_help ty   -- Revert to ordinary unification
209   = newTyVarTy liftedTypeKind           `thenM` \ elt_ty ->
210     unifyTauTy ty (mkListTy elt_ty)     `thenM_`
211     returnM elt_ty
212
213 -- variant for parallel arrays
214 --
215 zapToPArrTy :: Expected TcType     -- Expected list type
216             -> TcM TcType          -- List element type
217
218 zapToPArrTy (Check ty)   = unifyPArrTy ty
219 zapToPArrTy (Infer hole) = do { elt_ty <- newTyVarTy liftedTypeKind ;
220                                 writeMutVar hole (mkPArrTy elt_ty) ;
221                                 return elt_ty }
222
223 unifyPArrTy :: TcType -> TcM TcType
224
225 unifyPArrTy ty@(TyVarTy tyvar)
226   = getTcTyVar tyvar    `thenM` \ maybe_ty ->
227     case maybe_ty of
228       Just ty' -> unifyPArrTy ty'
229       _        -> unify_parr_ty_help ty
230 unifyPArrTy ty
231   = case tcSplitTyConApp_maybe ty of
232       Just (tycon, [arg_ty]) | tycon == parrTyCon -> returnM arg_ty
233       _                                           -> unify_parr_ty_help ty
234
235 unify_parr_ty_help ty   -- Revert to ordinary unification
236   = newTyVarTy liftedTypeKind           `thenM` \ elt_ty ->
237     unifyTauTy ty (mkPArrTy elt_ty)     `thenM_`
238     returnM elt_ty
239 \end{code}
240
241 \begin{code}
242 zapToTupleTy :: Boxity -> Arity -> Expected TcType -> TcM [TcType]
243 zapToTupleTy boxity arity (Check ty)   = unifyTupleTy boxity arity ty
244 zapToTupleTy boxity arity (Infer hole) = do { (tup_ty, arg_tys) <- new_tuple_ty boxity arity ;
245                                               writeMutVar hole tup_ty ;
246                                               return arg_tys }
247
248 unifyTupleTy boxity arity ty@(TyVarTy tyvar)
249   = getTcTyVar tyvar    `thenM` \ maybe_ty ->
250     case maybe_ty of
251         Just ty' -> unifyTupleTy boxity arity ty'
252         other    -> unify_tuple_ty_help boxity arity ty
253
254 unifyTupleTy boxity arity ty
255   = case tcSplitTyConApp_maybe ty of
256         Just (tycon, arg_tys)
257                 |  isTupleTyCon tycon 
258                 && tyConArity tycon == arity
259                 && tupleTyConBoxity tycon == boxity
260                 -> returnM arg_tys
261         other -> unify_tuple_ty_help boxity arity ty
262
263 unify_tuple_ty_help boxity arity ty
264   = new_tuple_ty boxity arity   `thenM` \ (tup_ty, arg_tys) ->
265     unifyTauTy ty tup_ty        `thenM_`
266     returnM arg_tys
267
268 new_tuple_ty boxity arity
269   = newTyVarTys arity kind      `thenM` \ arg_tys ->
270     return (mkTupleTy boxity arity arg_tys, arg_tys)
271   where
272     kind | isBoxed boxity = liftedTypeKind
273          | otherwise      = openTypeKind
274 \end{code}
275
276
277 %************************************************************************
278 %*                                                                      *
279 \subsection{Subsumption}
280 %*                                                                      *
281 %************************************************************************
282
283 All the tcSub calls have the form
284         
285                 tcSub expected_ty offered_ty
286 which checks
287                 offered_ty <= expected_ty
288
289 That is, that a value of type offered_ty is acceptable in
290 a place expecting a value of type expected_ty.
291
292 It returns a coercion function 
293         co_fn :: offered_ty -> expected_ty
294 which takes an HsExpr of type offered_ty into one of type
295 expected_ty.
296
297 \begin{code}
298 tcSubExp :: Expected TcRhoType -> TcRhoType  -> TcM ExprCoFn
299 tcSubOff :: TcSigmaType  -> Expected TcSigmaType -> TcM ExprCoFn
300 \end{code}
301
302 These two check for holes
303
304 \begin{code}
305 tcSubExp expected_ty offered_ty
306   = traceTc (text "tcSubExp" <+> (ppr expected_ty $$ ppr offered_ty))   `thenM_`
307     checkHole expected_ty offered_ty tcSub
308
309 tcSubOff expected_ty offered_ty
310   = checkHole offered_ty expected_ty (\ off exp -> tcSub exp off)
311
312 -- checkHole looks for a hole in its first arg; 
313 -- If so, and it is uninstantiated, it fills in the hole 
314 --        with its second arg
315 -- Otherwise it calls thing_inside, passing the two args, looking
316 -- through any instantiated hole
317
318 checkHole (Infer hole) other_ty thing_inside
319   = do { writeMutVar hole other_ty; return idCoercion }
320
321 checkHole (Check ty) other_ty thing_inside 
322   = thing_inside ty other_ty
323 \end{code}
324
325 No holes expected now.  Add some error-check context info.
326
327 \begin{code}
328 tcSub :: TcSigmaType -> TcSigmaType -> TcM ExprCoFn     -- Locally used only
329 tcSub expected_ty actual_ty
330   = traceTc (text "tcSub" <+> details)          `thenM_`
331     addErrCtxtM (unifyCtxt "type" expected_ty actual_ty)
332                 (tc_sub expected_ty expected_ty actual_ty actual_ty)
333   where
334     details = vcat [text "Expected:" <+> ppr expected_ty,
335                     text "Actual:  " <+> ppr actual_ty]
336 \end{code}
337
338 tc_sub carries the types before and after expanding type synonyms
339
340 \begin{code}
341 tc_sub :: TcSigmaType           -- expected_ty, before expanding synonyms
342        -> TcSigmaType           --              ..and after
343        -> TcSigmaType           -- actual_ty, before
344        -> TcSigmaType           --              ..and after
345        -> TcM ExprCoFn
346
347 -----------------------------------
348 -- Expand synonyms
349 tc_sub exp_sty (NoteTy _ exp_ty) act_sty act_ty = tc_sub exp_sty exp_ty act_sty act_ty
350 tc_sub exp_sty exp_ty act_sty (NoteTy _ act_ty) = tc_sub exp_sty exp_ty act_sty act_ty
351
352 -----------------------------------
353 -- Generalisation case
354 --      actual_ty:   d:Eq b => b->b
355 --      expected_ty: forall a. Ord a => a->a
356 --      co_fn e      /\a. \d2:Ord a. let d = eqFromOrd d2 in e
357
358 -- It is essential to do this *before* the specialisation case
359 -- Example:  f :: (Eq a => a->a) -> ...
360 --           g :: Ord b => b->b
361 -- Consider  f g !
362
363 tc_sub exp_sty expected_ty act_sty actual_ty
364   | isSigmaTy expected_ty
365   = tcGen expected_ty (tyVarsOfType actual_ty) (
366         -- It's really important to check for escape wrt the free vars of
367         -- both expected_ty *and* actual_ty
368         \ body_exp_ty -> tc_sub body_exp_ty body_exp_ty act_sty actual_ty
369     )                           `thenM` \ (gen_fn, co_fn) ->
370     returnM (gen_fn <.> co_fn)
371
372 -----------------------------------
373 -- Specialisation case:
374 --      actual_ty:   forall a. Ord a => a->a
375 --      expected_ty: Int -> Int
376 --      co_fn e =    e Int dOrdInt
377
378 tc_sub exp_sty expected_ty act_sty actual_ty
379   | isSigmaTy actual_ty
380   = tcInstCall Rank2Origin actual_ty            `thenM` \ (inst_fn, body_ty) ->
381     tc_sub exp_sty expected_ty body_ty body_ty  `thenM` \ co_fn ->
382     returnM (co_fn <.> inst_fn)
383
384 -----------------------------------
385 -- Function case
386
387 tc_sub _ (FunTy exp_arg exp_res) _ (FunTy act_arg act_res)
388   = tcSub_fun exp_arg exp_res act_arg act_res
389
390 -----------------------------------
391 -- Type variable meets function: imitate
392 --
393 -- NB 1: we can't just unify the type variable with the type
394 --       because the type might not be a tau-type, and we aren't
395 --       allowed to instantiate an ordinary type variable with
396 --       a sigma-type
397 --
398 -- NB 2: can we short-cut to an error case?
399 --       when the arg/res is not a tau-type?
400 -- NO!  e.g.   f :: ((forall a. a->a) -> Int) -> Int
401 --      then   x = (f,f)
402 --      is perfectly fine, because we can instantiat f's type to a monotype
403 --
404 -- However, we get can get jolly unhelpful error messages.  
405 --      e.g.    foo = id runST
406 --
407 --    Inferred type is less polymorphic than expected
408 --      Quantified type variable `s' escapes
409 --      Expected type: ST s a -> t
410 --      Inferred type: (forall s1. ST s1 a) -> a
411 --    In the first argument of `id', namely `runST'
412 --    In a right-hand side of function `foo': id runST
413 --
414 -- I'm not quite sure what to do about this!
415
416 tc_sub exp_sty exp_ty@(FunTy exp_arg exp_res) _ (TyVarTy tv)
417   = getTcTyVar tv       `thenM` \ maybe_ty ->
418     case maybe_ty of
419         Just ty -> tc_sub exp_sty exp_ty ty ty
420         Nothing -> imitateFun tv exp_sty        `thenM` \ (act_arg, act_res) ->
421                    tcSub_fun exp_arg exp_res act_arg act_res
422
423 tc_sub _ (TyVarTy tv) act_sty act_ty@(FunTy act_arg act_res)
424   = getTcTyVar tv       `thenM` \ maybe_ty ->
425     case maybe_ty of
426         Just ty -> tc_sub ty ty act_sty act_ty
427         Nothing -> imitateFun tv act_sty        `thenM` \ (exp_arg, exp_res) ->
428                    tcSub_fun exp_arg exp_res act_arg act_res
429
430 -----------------------------------
431 -- Unification case
432 -- If none of the above match, we revert to the plain unifier
433 tc_sub exp_sty expected_ty act_sty actual_ty
434   = uTys exp_sty expected_ty act_sty actual_ty  `thenM_`
435     returnM idCoercion
436 \end{code}    
437     
438 %************************************************************************
439 %*                                                                      *
440 \subsection{Functions}
441 %*                                                                      *
442 %************************************************************************
443
444 \begin{code}
445 tcSub_fun exp_arg exp_res act_arg act_res
446   = tc_sub act_arg act_arg exp_arg exp_arg      `thenM` \ co_fn_arg ->
447     tc_sub exp_res exp_res act_res act_res      `thenM` \ co_fn_res ->
448     newUnique                                   `thenM` \ uniq ->
449     let
450         -- co_fn_arg :: HsExpr exp_arg -> HsExpr act_arg
451         -- co_fn_res :: HsExpr act_res -> HsExpr exp_res
452         -- co_fn     :: HsExpr (act_arg -> act_res) -> HsExpr (exp_arg -> exp_res)
453         arg_id = mkSysLocal FSLIT("sub") uniq exp_arg
454         coercion | isIdCoercion co_fn_arg,
455                    isIdCoercion co_fn_res = idCoercion
456                  | otherwise              = mkCoercion co_fn
457
458         co_fn e = DictLam [arg_id] 
459                      (co_fn_res <$> (HsApp e (co_fn_arg <$> (HsVar arg_id))))
460                 -- Slight hack; using a "DictLam" to get an ordinary simple lambda
461                 --      HsVar arg_id :: HsExpr exp_arg
462                 --      co_fn_arg $it :: HsExpr act_arg
463                 --      HsApp e $it   :: HsExpr act_res
464                 --      co_fn_res $it :: HsExpr exp_res
465     in
466     returnM coercion
467
468 imitateFun :: TcTyVar -> TcType -> TcM (TcType, TcType)
469 imitateFun tv ty
470   =     -- NB: tv is an *ordinary* tyvar and so are the new ones
471
472         -- Check that tv isn't a type-signature type variable
473         -- (This would be found later in checkSigTyVars, but
474         --  we get a better error message if we do it here.)
475     checkM (not (isSkolemTyVar tv))
476            (failWithTcM (unifyWithSigErr tv ty))        `thenM_`
477
478     newTyVarTy openTypeKind             `thenM` \ arg ->
479     newTyVarTy openTypeKind             `thenM` \ res ->
480     putTcTyVar tv (mkFunTy arg res)     `thenM_`
481     returnM (arg,res)
482 \end{code}
483
484
485 %************************************************************************
486 %*                                                                      *
487 \subsection{Generalisation}
488 %*                                                                      *
489 %************************************************************************
490
491 \begin{code}
492 tcGen :: TcSigmaType                            -- expected_ty
493       -> TcTyVarSet                             -- Extra tyvars that the universally
494                                                 --      quantified tyvars of expected_ty
495                                                 --      must not be unified
496       -> (TcRhoType -> TcM result)              -- spec_ty
497       -> TcM (ExprCoFn, result)
498         -- The expression has type: spec_ty -> expected_ty
499
500 tcGen expected_ty extra_tvs thing_inside        -- We expect expected_ty to be a forall-type
501                                                 -- If not, the call is a no-op
502   = tcInstType SigTv expected_ty        `thenM` \ (forall_tvs, theta, phi_ty) ->
503
504         -- Type-check the arg and unify with poly type
505     getLIE (thing_inside phi_ty)        `thenM` \ (result, lie) ->
506
507         -- Check that the "forall_tvs" havn't been constrained
508         -- The interesting bit here is that we must include the free variables
509         -- of the expected_ty.  Here's an example:
510         --       runST (newVar True)
511         -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
512         -- for (newVar True), with s fresh.  Then we unify with the runST's arg type
513         -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
514         -- So now s' isn't unconstrained because it's linked to a.
515         -- Conclusion: include the free vars of the expected_ty in the
516         -- list of "free vars" for the signature check.
517
518     newDicts SignatureOrigin theta                      `thenM` \ dicts ->
519     tcSimplifyCheck sig_msg forall_tvs dicts lie        `thenM` \ inst_binds ->
520
521 #ifdef DEBUG
522     zonkTcTyVars forall_tvs `thenM` \ forall_tys ->
523     traceTc (text "tcGen" <+> vcat [text "extra_tvs" <+> ppr extra_tvs,
524                                     text "expected_ty" <+> ppr expected_ty,
525                                     text "inst ty" <+> ppr forall_tvs <+> ppr theta <+> ppr phi_ty,
526                                     text "free_tvs" <+> ppr free_tvs,
527                                     text "forall_tys" <+> ppr forall_tys])      `thenM_`
528 #endif
529
530     checkSigTyVarsWrt free_tvs forall_tvs               `thenM` \ zonked_tvs ->
531
532     traceTc (text "tcGen:done") `thenM_`
533
534     let
535             -- This HsLet binds any Insts which came out of the simplification.
536             -- It's a bit out of place here, but using AbsBind involves inventing
537             -- a couple of new names which seems worse.
538         dict_ids = map instToId dicts
539         co_fn e  = TyLam zonked_tvs (DictLam dict_ids (mkHsLet inst_binds e))
540     in
541     returnM (mkCoercion co_fn, result)
542   where
543     free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
544     sig_msg  = ptext SLIT("expected type of an expression")
545 \end{code}    
546
547     
548
549 %************************************************************************
550 %*                                                                      *
551 \subsection[Unify-exported]{Exported unification functions}
552 %*                                                                      *
553 %************************************************************************
554
555 The exported functions are all defined as versions of some
556 non-exported generic functions.
557
558 Unify two @TauType@s.  Dead straightforward.
559
560 \begin{code}
561 unifyTauTy :: TcTauType -> TcTauType -> TcM ()
562 unifyTauTy ty1 ty2      -- ty1 expected, ty2 inferred
563   =     -- The unifier should only ever see tau-types 
564         -- (no quantification whatsoever)
565     ASSERT2( isTauTy ty1, ppr ty1 )
566     ASSERT2( isTauTy ty2, ppr ty2 )
567     addErrCtxtM (unifyCtxt "type" ty1 ty2) $
568     uTys ty1 ty1 ty2 ty2
569 \end{code}
570
571 @unifyTauTyList@ unifies corresponding elements of two lists of
572 @TauType@s.  It uses @uTys@ to do the real work.  The lists should be
573 of equal length.  We charge down the list explicitly so that we can
574 complain if their lengths differ.
575
576 \begin{code}
577 unifyTauTyLists :: [TcTauType] -> [TcTauType] ->  TcM ()
578 unifyTauTyLists []           []         = returnM ()
579 unifyTauTyLists (ty1:tys1) (ty2:tys2) = uTys ty1 ty1 ty2 ty2   `thenM_`
580                                         unifyTauTyLists tys1 tys2
581 unifyTauTyLists ty1s ty2s = panic "Unify.unifyTauTyLists: mismatched type lists!"
582 \end{code}
583
584 @unifyTauTyList@ takes a single list of @TauType@s and unifies them
585 all together.  It is used, for example, when typechecking explicit
586 lists, when all the elts should be of the same type.
587
588 \begin{code}
589 unifyTauTyList :: [TcTauType] -> TcM ()
590 unifyTauTyList []                = returnM ()
591 unifyTauTyList [ty]              = returnM ()
592 unifyTauTyList (ty1:tys@(ty2:_)) = unifyTauTy ty1 ty2   `thenM_`
593                                    unifyTauTyList tys
594 \end{code}
595
596 %************************************************************************
597 %*                                                                      *
598 \subsection[Unify-uTys]{@uTys@: getting down to business}
599 %*                                                                      *
600 %************************************************************************
601
602 @uTys@ is the heart of the unifier.  Each arg happens twice, because
603 we want to report errors in terms of synomyms if poss.  The first of
604 the pair is used in error messages only; it is always the same as the
605 second, except that if the first is a synonym then the second may be a
606 de-synonym'd version.  This way we get better error messages.
607
608 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
609
610 \begin{code}
611 uTys :: TcTauType -> TcTauType  -- Error reporting ty1 and real ty1
612                                 -- ty1 is the *expected* type
613
614      -> TcTauType -> TcTauType  -- Error reporting ty2 and real ty2
615                                 -- ty2 is the *actual* type
616      -> TcM ()
617
618         -- Always expand synonyms (see notes at end)
619         -- (this also throws away FTVs)
620 uTys ps_ty1 (NoteTy n1 ty1) ps_ty2 ty2 = uTys ps_ty1 ty1 ps_ty2 ty2
621 uTys ps_ty1 ty1 ps_ty2 (NoteTy n2 ty2) = uTys ps_ty1 ty1 ps_ty2 ty2
622
623         -- Variables; go for uVar
624 uTys ps_ty1 (TyVarTy tyvar1) ps_ty2 ty2 = uVar False tyvar1 ps_ty2 ty2
625 uTys ps_ty1 ty1 ps_ty2 (TyVarTy tyvar2) = uVar True  tyvar2 ps_ty1 ty1
626                                         -- "True" means args swapped
627
628         -- Predicates
629 uTys _ (SourceTy (IParam n1 t1)) _ (SourceTy (IParam n2 t2))
630   | n1 == n2 = uTys t1 t1 t2 t2
631 uTys _ (SourceTy (ClassP c1 tys1)) _ (SourceTy (ClassP c2 tys2))
632   | c1 == c2 = unifyTauTyLists tys1 tys2
633 uTys _ (SourceTy (NType tc1 tys1)) _ (SourceTy (NType tc2 tys2))
634   | tc1 == tc2 = unifyTauTyLists tys1 tys2
635
636         -- Functions; just check the two parts
637 uTys _ (FunTy fun1 arg1) _ (FunTy fun2 arg2)
638   = uTys fun1 fun1 fun2 fun2    `thenM_`    uTys arg1 arg1 arg2 arg2
639
640         -- Type constructors must match
641 uTys ps_ty1 (TyConApp con1 tys1) ps_ty2 (TyConApp con2 tys2)
642   | con1 == con2 && equalLength tys1 tys2
643   = unifyTauTyLists tys1 tys2
644
645   | con1 == openKindCon
646         -- When we are doing kind checking, we might match a kind '?' 
647         -- against a kind '*' or '#'.  Notably, CCallable :: ? -> *, and
648         -- (CCallable Int) and (CCallable Int#) are both OK
649   = unifyOpenTypeKind ps_ty2
650
651         -- Applications need a bit of care!
652         -- They can match FunTy and TyConApp, so use splitAppTy_maybe
653         -- NB: we've already dealt with type variables and Notes,
654         -- so if one type is an App the other one jolly well better be too
655 uTys ps_ty1 (AppTy s1 t1) ps_ty2 ty2
656   = case tcSplitAppTy_maybe ty2 of
657         Just (s2,t2) -> uTys s1 s1 s2 s2        `thenM_`    uTys t1 t1 t2 t2
658         Nothing      -> unifyMisMatch ps_ty1 ps_ty2
659
660         -- Now the same, but the other way round
661         -- Don't swap the types, because the error messages get worse
662 uTys ps_ty1 ty1 ps_ty2 (AppTy s2 t2)
663   = case tcSplitAppTy_maybe ty1 of
664         Just (s1,t1) -> uTys s1 s1 s2 s2        `thenM_`    uTys t1 t1 t2 t2
665         Nothing      -> unifyMisMatch ps_ty1 ps_ty2
666
667         -- Not expecting for-alls in unification
668         -- ... but the error message from the unifyMisMatch more informative
669         -- than a panic message!
670
671         -- Anything else fails
672 uTys ps_ty1 ty1 ps_ty2 ty2  = unifyMisMatch ps_ty1 ps_ty2
673 \end{code}
674
675
676 Notes on synonyms
677 ~~~~~~~~~~~~~~~~~
678 If you are tempted to make a short cut on synonyms, as in this
679 pseudocode...
680
681 \begin{verbatim}
682 -- NO   uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
683 -- NO     = if (con1 == con2) then
684 -- NO   -- Good news!  Same synonym constructors, so we can shortcut
685 -- NO   -- by unifying their arguments and ignoring their expansions.
686 -- NO   unifyTauTypeLists args1 args2
687 -- NO    else
688 -- NO   -- Never mind.  Just expand them and try again
689 -- NO   uTys ty1 ty2
690 \end{verbatim}
691
692 then THINK AGAIN.  Here is the whole story, as detected and reported
693 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
694 \begin{quotation}
695 Here's a test program that should detect the problem:
696
697 \begin{verbatim}
698         type Bogus a = Int
699         x = (1 :: Bogus Char) :: Bogus Bool
700 \end{verbatim}
701
702 The problem with [the attempted shortcut code] is that
703 \begin{verbatim}
704         con1 == con2
705 \end{verbatim}
706 is not a sufficient condition to be able to use the shortcut!
707 You also need to know that the type synonym actually USES all
708 its arguments.  For example, consider the following type synonym
709 which does not use all its arguments.
710 \begin{verbatim}
711         type Bogus a = Int
712 \end{verbatim}
713
714 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
715 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
716 would fail, even though the expanded forms (both \tr{Int}) should
717 match.
718
719 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
720 unnecessarily bind \tr{t} to \tr{Char}.
721
722 ... You could explicitly test for the problem synonyms and mark them
723 somehow as needing expansion, perhaps also issuing a warning to the
724 user.
725 \end{quotation}
726
727
728 %************************************************************************
729 %*                                                                      *
730 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
731 %*                                                                      *
732 %************************************************************************
733
734 @uVar@ is called when at least one of the types being unified is a
735 variable.  It does {\em not} assume that the variable is a fixed point
736 of the substitution; rather, notice that @uVar@ (defined below) nips
737 back into @uTys@ if it turns out that the variable is already bound.
738
739 \begin{code}
740 uVar :: Bool            -- False => tyvar is the "expected"
741                         -- True  => ty    is the "expected" thing
742      -> TcTyVar
743      -> TcTauType -> TcTauType  -- printing and real versions
744      -> TcM ()
745
746 uVar swapped tv1 ps_ty2 ty2
747   = traceTc (text "uVar" <+> ppr swapped <+> ppr tv1 <+> (ppr ps_ty2 $$ ppr ty2))       `thenM_`
748     getTcTyVar tv1      `thenM` \ maybe_ty1 ->
749     case maybe_ty1 of
750         Just ty1 | swapped   -> uTys ps_ty2 ty2 ty1 ty1 -- Swap back
751                  | otherwise -> uTys ty1 ty1 ps_ty2 ty2 -- Same order
752         other       -> uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2
753
754         -- Expand synonyms; ignore FTVs
755 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 (NoteTy n2 ty2)
756   = uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2
757
758
759         -- The both-type-variable case
760 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2@(TyVarTy tv2)
761
762         -- Same type variable => no-op
763   | tv1 == tv2
764   = returnM ()
765
766         -- Distinct type variables
767         -- ASSERT maybe_ty1 /= Just
768   | otherwise
769   = getTcTyVar tv2      `thenM` \ maybe_ty2 ->
770     case maybe_ty2 of
771         Just ty2' -> uUnboundVar swapped tv1 maybe_ty1 ty2' ty2'
772
773         Nothing | update_tv2
774
775                 -> WARN( not (k1 `hasMoreBoxityInfo` k2), (ppr tv1 <+> ppr k1) $$ (ppr tv2 <+> ppr k2) )
776                    putTcTyVar tv2 (TyVarTy tv1)         `thenM_`
777                    returnM ()
778                 |  otherwise
779
780                 -> WARN( not (k2 `hasMoreBoxityInfo` k1), (ppr tv2 <+> ppr k2) $$ (ppr tv1 <+> ppr k1) )
781                    putTcTyVar tv1 ps_ty2                `thenM_`
782                    returnM ()
783   where
784     k1 = tyVarKind tv1
785     k2 = tyVarKind tv2
786     update_tv2 = (k2 `eqKind` openTypeKind) || (not (k1 `eqKind` openTypeKind) && nicer_to_update_tv2)
787                         -- Try to get rid of open type variables as soon as poss
788
789     nicer_to_update_tv2 =  isUserTyVar tv1
790                                 -- Don't unify a signature type variable if poss
791                         || isSystemName (varName tv2)
792                                 -- Try to update sys-y type variables in preference to sig-y ones
793
794         -- Second one isn't a type variable
795 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 non_var_ty2
796   =     -- Check that tv1 isn't a type-signature type variable
797     checkM (not (isSkolemTyVar tv1))
798            (failWithTcM (unifyWithSigErr tv1 ps_ty2))   `thenM_`
799
800         -- Do the occurs check, and check that we are not
801         -- unifying a type variable with a polytype
802         -- Returns a zonked type ready for the update
803     checkValue tv1 ps_ty2 non_var_ty2   `thenM` \ ty2 ->
804
805         -- Check that the kinds match
806     checkKinds swapped tv1 ty2          `thenM_`
807
808         -- Perform the update
809     putTcTyVar tv1 ty2                  `thenM_`
810     returnM ()
811 \end{code}
812
813 \begin{code}
814 checkKinds swapped tv1 ty2
815 -- We're about to unify a type variable tv1 with a non-tyvar-type ty2.
816 -- ty2 has been zonked at this stage, which ensures that
817 -- its kind has as much boxity information visible as possible.
818   | tk2 `hasMoreBoxityInfo` tk1 = returnM ()
819
820   | otherwise
821         -- Either the kinds aren't compatible
822         --      (can happen if we unify (a b) with (c d))
823         -- or we are unifying a lifted type variable with an
824         --      unlifted type: e.g.  (id 3#) is illegal
825   = addErrCtxtM (unifyKindCtxt swapped tv1 ty2) $
826     unifyMisMatch k1 k2
827
828   where
829     (k1,k2) | swapped   = (tk2,tk1)
830             | otherwise = (tk1,tk2)
831     tk1 = tyVarKind tv1
832     tk2 = typeKind ty2
833 \end{code}
834
835 \begin{code}
836 checkValue tv1 ps_ty2 non_var_ty2
837 -- Do the occurs check, and check that we are not
838 -- unifying a type variable with a polytype
839 -- Return the type to update the type variable with, or fail
840
841 -- Basically we want to update     tv1 := ps_ty2
842 -- because ps_ty2 has type-synonym info, which improves later error messages
843 -- 
844 -- But consider 
845 --      type A a = ()
846 --
847 --      f :: (A a -> a -> ()) -> ()
848 --      f = \ _ -> ()
849 --
850 --      x :: ()
851 --      x = f (\ x p -> p x)
852 --
853 -- In the application (p x), we try to match "t" with "A t".  If we go
854 -- ahead and bind t to A t (= ps_ty2), we'll lead the type checker into 
855 -- an infinite loop later.
856 -- But we should not reject the program, because A t = ().
857 -- Rather, we should bind t to () (= non_var_ty2).
858 -- 
859 -- That's why we have this two-state occurs-check
860   = zonkTcType ps_ty2                   `thenM` \ ps_ty2' ->
861     case okToUnifyWith tv1 ps_ty2' of {
862         Nothing -> returnM ps_ty2' ;    -- Success
863         other ->
864
865     zonkTcType non_var_ty2              `thenM` \ non_var_ty2' ->
866     case okToUnifyWith tv1 non_var_ty2' of
867         Nothing ->      -- This branch rarely succeeds, except in strange cases
868                         -- like that in the example above
869                     returnM non_var_ty2'
870
871         Just problem -> failWithTcM (unifyCheck problem tv1 ps_ty2')
872     }
873
874 data Problem = OccurCheck | NotMonoType
875
876 okToUnifyWith :: TcTyVar -> TcType -> Maybe Problem
877 -- (okToUnifyWith tv ty) checks whether it's ok to unify
878 --      tv :=: ty
879 -- Nothing => ok
880 -- Just p  => not ok, problem p
881
882 okToUnifyWith tv ty
883   = ok ty
884   where
885     ok (TyVarTy tv') | tv == tv' = Just OccurCheck
886                      | otherwise = Nothing
887     ok (AppTy t1 t2)            = ok t1 `and` ok t2
888     ok (FunTy t1 t2)            = ok t1 `and` ok t2
889     ok (TyConApp _ ts)          = oks ts
890     ok (ForAllTy _ _)           = Just NotMonoType
891     ok (SourceTy st)            = ok_st st
892     ok (NoteTy (FTVNote _) t)   = ok t
893     ok (NoteTy (SynNote t1) t2) = ok t1 `and` ok t2
894                 -- Type variables may be free in t1 but not t2
895                 -- A forall may be in t2 but not t1
896
897     oks ts = foldr (and . ok) Nothing ts
898
899     ok_st (ClassP _ ts) = oks ts
900     ok_st (IParam _ t)  = ok t
901     ok_st (NType _ ts)  = oks ts
902
903     Nothing `and` m = m
904     Just p  `and` m = Just p
905 \end{code}
906
907 %************************************************************************
908 %*                                                                      *
909 \subsection{Kind unification}
910 %*                                                                      *
911 %************************************************************************
912
913 \begin{code}
914 unifyKind :: TcKind                 -- Expected
915           -> TcKind                 -- Actual
916           -> TcM ()
917 unifyKind k1 k2 = uTys k1 k1 k2 k2
918
919 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
920 unifyKinds []       []       = returnM ()
921 unifyKinds (k1:ks1) (k2:ks2) = unifyKind k1 k2  `thenM_`
922                                unifyKinds ks1 ks2
923 unifyKinds _ _ = panic "unifyKinds: length mis-match"
924 \end{code}
925
926 \begin{code}
927 unifyOpenTypeKind :: TcKind -> TcM ()   
928 -- Ensures that the argument kind is of the form (Type bx)
929 -- for some boxity bx
930
931 unifyOpenTypeKind ty@(TyVarTy tyvar)
932   = getTcTyVar tyvar    `thenM` \ maybe_ty ->
933     case maybe_ty of
934         Just ty' -> unifyOpenTypeKind ty'
935         other    -> unify_open_kind_help ty
936
937 unifyOpenTypeKind ty
938   | isTypeKind ty = returnM ()
939   | otherwise     = unify_open_kind_help ty
940
941 unify_open_kind_help ty -- Revert to ordinary unification
942   = newOpenTypeKind     `thenM` \ open_kind ->
943     unifyKind ty open_kind
944 \end{code}
945
946 \begin{code}
947 unifyFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
948 -- Like unifyFunTy, but does not fail; instead just returns Nothing
949
950 unifyFunKind (TyVarTy tyvar)
951   = getTcTyVar tyvar    `thenM` \ maybe_ty ->
952     case maybe_ty of
953         Just fun_kind -> unifyFunKind fun_kind
954         Nothing       -> newKindVar     `thenM` \ arg_kind ->
955                          newKindVar     `thenM` \ res_kind ->
956                          putTcTyVar tyvar (mkArrowKind arg_kind res_kind)       `thenM_`
957                          returnM (Just (arg_kind,res_kind))
958     
959 unifyFunKind (FunTy arg_kind res_kind) = returnM (Just (arg_kind,res_kind))
960 unifyFunKind (NoteTy _ ty)             = unifyFunKind ty
961 unifyFunKind other                     = returnM Nothing
962 \end{code}
963
964 %************************************************************************
965 %*                                                                      *
966 \subsection[Unify-context]{Errors and contexts}
967 %*                                                                      *
968 %************************************************************************
969
970 Errors
971 ~~~~~~
972
973 \begin{code}
974 unifyCtxt s ty1 ty2 tidy_env    -- ty1 expected, ty2 inferred
975   = zonkTcType ty1      `thenM` \ ty1' ->
976     zonkTcType ty2      `thenM` \ ty2' ->
977     returnM (err ty1' ty2')
978   where
979     err ty1 ty2 = (env1, 
980                    nest 4 
981                         (vcat [
982                            text "Expected" <+> text s <> colon <+> ppr tidy_ty1,
983                            text "Inferred" <+> text s <> colon <+> ppr tidy_ty2
984                         ]))
985                   where
986                     (env1, [tidy_ty1,tidy_ty2]) = tidyOpenTypes tidy_env [ty1,ty2]
987
988 unifyKindCtxt swapped tv1 ty2 tidy_env  -- not swapped => tv1 expected, ty2 inferred
989         -- tv1 is zonked already
990   = zonkTcType ty2      `thenM` \ ty2' ->
991     returnM (err ty2')
992   where
993     err ty2 = (env2, ptext SLIT("When matching types") <+> 
994                      sep [quotes pp_expected, ptext SLIT("and"), quotes pp_actual])
995             where
996               (pp_expected, pp_actual) | swapped   = (pp2, pp1)
997                                        | otherwise = (pp1, pp2)
998               (env1, tv1') = tidyOpenTyVar tidy_env tv1
999               (env2, ty2') = tidyOpenType  env1 ty2
1000               pp1 = ppr tv1'
1001               pp2 = ppr ty2'
1002
1003 unifyMisMatch ty1 ty2
1004   = zonkTcType ty1      `thenM` \ ty1' ->
1005     zonkTcType ty2      `thenM` \ ty2' ->
1006     let
1007         (env, [tidy_ty1, tidy_ty2]) = tidyOpenTypes emptyTidyEnv [ty1',ty2']
1008         msg = hang (ptext SLIT("Couldn't match"))
1009                    4 (sep [quotes (ppr tidy_ty1), 
1010                            ptext SLIT("against"), 
1011                            quotes (ppr tidy_ty2)])
1012     in
1013     failWithTcM (env, msg)
1014
1015 unifyWithSigErr tyvar ty
1016   = (env2, hang (ptext SLIT("Cannot unify the type-signature variable") <+> quotes (ppr tidy_tyvar))
1017               4 (ptext SLIT("with the type") <+> quotes (ppr tidy_ty)))
1018   where
1019     (env1, tidy_tyvar) = tidyOpenTyVar emptyTidyEnv tyvar
1020     (env2, tidy_ty)    = tidyOpenType  env1         ty
1021
1022 unifyCheck problem tyvar ty
1023   = (env2, hang msg
1024               4 (sep [ppr tidy_tyvar, char '=', ppr tidy_ty]))
1025   where
1026     (env1, tidy_tyvar) = tidyOpenTyVar emptyTidyEnv tyvar
1027     (env2, tidy_ty)    = tidyOpenType  env1         ty
1028
1029     msg = case problem of
1030             OccurCheck  -> ptext SLIT("Occurs check: cannot construct the infinite type:")
1031             NotMonoType -> ptext SLIT("Cannot unify a type variable with a type scheme:")
1032 \end{code}
1033
1034
1035
1036 %************************************************************************
1037 %*                                                                      *
1038 \subsection{Checking signature type variables}
1039 %*                                                                      *
1040 %************************************************************************
1041
1042 @checkSigTyVars@ is used after the type in a type signature has been unified with
1043 the actual type found.  It then checks that the type variables of the type signature
1044 are
1045         (a) Still all type variables
1046                 eg matching signature [a] against inferred type [(p,q)]
1047                 [then a will be unified to a non-type variable]
1048
1049         (b) Still all distinct
1050                 eg matching signature [(a,b)] against inferred type [(p,p)]
1051                 [then a and b will be unified together]
1052
1053         (c) Not mentioned in the environment
1054                 eg the signature for f in this:
1055
1056                         g x = ... where
1057                                         f :: a->[a]
1058                                         f y = [x,y]
1059
1060                 Here, f is forced to be monorphic by the free occurence of x.
1061
1062         (d) Not (unified with another type variable that is) in scope.
1063                 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1064             when checking the expression type signature, we find that
1065             even though there is nothing in scope whose type mentions r,
1066             nevertheless the type signature for the expression isn't right.
1067
1068             Another example is in a class or instance declaration:
1069                 class C a where
1070                    op :: forall b. a -> b
1071                    op x = x
1072             Here, b gets unified with a
1073
1074 Before doing this, the substitution is applied to the signature type variable.
1075
1076 We used to have the notion of a "DontBind" type variable, which would
1077 only be bound to itself or nothing.  Then points (a) and (b) were 
1078 self-checking.  But it gave rise to bogus consequential error messages.
1079 For example:
1080
1081    f = (*)      -- Monomorphic
1082
1083    g :: Num a => a -> a
1084    g x = f x x
1085
1086 Here, we get a complaint when checking the type signature for g,
1087 that g isn't polymorphic enough; but then we get another one when
1088 dealing with the (Num x) context arising from f's definition;
1089 we try to unify x with Int (to default it), but find that x has already
1090 been unified with the DontBind variable "a" from g's signature.
1091 This is really a problem with side-effecting unification; we'd like to
1092 undo g's effects when its type signature fails, but unification is done
1093 by side effect, so we can't (easily).
1094
1095 So we revert to ordinary type variables for signatures, and try to
1096 give a helpful message in checkSigTyVars.
1097
1098 \begin{code}
1099 checkSigTyVars :: [TcTyVar] -> TcM [TcTyVar]
1100 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1101
1102 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM [TcTyVar]
1103 checkSigTyVarsWrt extra_tvs sig_tvs
1104   = zonkTcTyVarsAndFV (varSetElems extra_tvs)   `thenM` \ extra_tvs' ->
1105     check_sig_tyvars extra_tvs' sig_tvs
1106
1107 check_sig_tyvars
1108         :: TcTyVarSet           -- Global type variables. The universally quantified
1109                                 --      tyvars should not mention any of these
1110                                 --      Guaranteed already zonked.
1111         -> [TcTyVar]            -- Universally-quantified type variables in the signature
1112                                 --      Not guaranteed zonked.
1113         -> TcM [TcTyVar]        -- Zonked signature type variables
1114
1115 check_sig_tyvars extra_tvs []
1116   = returnM []
1117 check_sig_tyvars extra_tvs sig_tvs 
1118   = zonkTcTyVars sig_tvs        `thenM` \ sig_tys ->
1119     tcGetGlobalTyVars           `thenM` \ gbl_tvs ->
1120     let
1121         env_tvs = gbl_tvs `unionVarSet` extra_tvs
1122     in
1123     traceTc (text "check_sig_tyvars" <+> (vcat [text "sig_tys" <+> ppr sig_tys,
1124                                       text "gbl_tvs" <+> ppr gbl_tvs,
1125                                       text "extra_tvs" <+> ppr extra_tvs]))     `thenM_`
1126
1127     checkM (allDistinctTyVars sig_tys env_tvs)
1128            (complain sig_tys env_tvs)           `thenM_`
1129
1130     returnM (map (tcGetTyVar "checkSigTyVars") sig_tys)
1131
1132   where
1133     complain sig_tys globals
1134       = -- "check" checks each sig tyvar in turn
1135         foldlM check
1136                (env2, emptyVarEnv, [])
1137                (tidy_tvs `zip` tidy_tys)        `thenM` \ (env3, _, msgs) ->
1138
1139         failWithTcM (env3, main_msg $$ nest 4 (vcat msgs))
1140       where
1141         (env1, tidy_tvs) = tidyOpenTyVars emptyTidyEnv sig_tvs
1142         (env2, tidy_tys) = tidyOpenTypes  env1         sig_tys
1143
1144         main_msg = ptext SLIT("Inferred type is less polymorphic than expected")
1145
1146         check (tidy_env, acc, msgs) (sig_tyvar,ty)
1147                 -- sig_tyvar is from the signature;
1148                 -- ty is what you get if you zonk sig_tyvar and then tidy it
1149                 --
1150                 -- acc maps a zonked type variable back to a signature type variable
1151           = case tcGetTyVar_maybe ty of {
1152               Nothing ->                        -- Error (a)!
1153                         returnM (tidy_env, acc, unify_msg sig_tyvar (quotes (ppr ty)) : msgs) ;
1154
1155               Just tv ->
1156
1157             case lookupVarEnv acc tv of {
1158                 Just sig_tyvar' ->      -- Error (b)!
1159                         returnM (tidy_env, acc, unify_msg sig_tyvar thing : msgs)
1160                     where
1161                         thing = ptext SLIT("another quantified type variable") <+> quotes (ppr sig_tyvar')
1162
1163               ; Nothing ->
1164
1165             if tv `elemVarSet` globals  -- Error (c) or (d)! Type variable escapes
1166                                         -- The least comprehensible, so put it last
1167                         -- Game plan: 
1168                         --       get the local TcIds and TyVars from the environment,
1169                         --       and pass them to find_globals (they might have tv free)
1170             then   findGlobals (unitVarSet tv) tidy_env         `thenM` \ (tidy_env1, globs) ->
1171                    returnM (tidy_env1, acc, escape_msg sig_tyvar tv globs : msgs)
1172
1173             else        -- All OK
1174             returnM (tidy_env, extendVarEnv acc tv sig_tyvar, msgs)
1175             }}
1176 \end{code}
1177
1178
1179 \begin{code}
1180 -----------------------
1181 escape_msg sig_tv tv globs
1182   = mk_msg sig_tv <+> ptext SLIT("escapes") $$
1183     if notNull globs then
1184         vcat [pp_it <+> ptext SLIT("is mentioned in the environment:"), 
1185               nest 2 (vcat globs)]
1186      else
1187         empty   -- Sigh.  It's really hard to give a good error message
1188                 -- all the time.   One bad case is an existential pattern match.
1189                 -- We rely on the "When..." context to help.
1190   where
1191     pp_it | sig_tv /= tv = ptext SLIT("It unifies with") <+> quotes (ppr tv) <> comma <+> ptext SLIT("which")
1192           | otherwise    = ptext SLIT("It")
1193
1194
1195 unify_msg tv thing = mk_msg tv <+> ptext SLIT("is unified with") <+> thing
1196 mk_msg tv          = ptext SLIT("Quantified type variable") <+> quotes (ppr tv)
1197 \end{code}
1198
1199 These two context are used with checkSigTyVars
1200     
1201 \begin{code}
1202 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
1203         -> TidyEnv -> TcM (TidyEnv, Message)
1204 sigCtxt id sig_tvs sig_theta sig_tau tidy_env
1205   = zonkTcType sig_tau          `thenM` \ actual_tau ->
1206     let
1207         (env1, tidy_sig_tvs)    = tidyOpenTyVars tidy_env sig_tvs
1208         (env2, tidy_sig_rho)    = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
1209         (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
1210         sub_msg = vcat [ptext SLIT("Signature type:    ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
1211                         ptext SLIT("Type to generalise:") <+> pprType tidy_actual_tau
1212                    ]
1213         msg = vcat [ptext SLIT("When trying to generalise the type inferred for") <+> quotes (ppr id),
1214                     nest 4 sub_msg]
1215     in
1216     returnM (env3, msg)
1217 \end{code}