[project @ 1999-11-30 16:10:07 by lewie]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcMonoType.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcMonoType]{Typechecking user-specified @MonoTypes@}
5
6 \begin{code}
7 module TcMonoType ( tcHsType, tcHsTypeKind, tcHsTopType, tcHsTopBoxedType, tcHsTopTypeKind,
8                     tcContext, tcHsTyVar, kcHsTyVar,
9                     tcExtendTyVarScope, tcExtendTopTyVarScope,
10                     TcSigInfo(..), tcTySig, mkTcSig, maybeSig,
11                     checkSigTyVars, sigCtxt, sigPatCtxt
12                   ) where
13
14 #include "HsVersions.h"
15
16 import HsSyn            ( HsType(..), HsTyVar(..), MonoUsageAnn(..),
17                           Sig(..), pprClassAssertion, pprParendHsType )
18 import RnHsSyn          ( RenamedHsType, RenamedContext, RenamedSig )
19 import TcHsSyn          ( TcId )
20
21 import TcMonad
22 import TcEnv            ( tcExtendTyVarEnv, tcLookupTy, tcGetValueEnv, tcGetInScopeTyVars,
23                           tcExtendUVarEnv, tcLookupUVar,
24                           tcGetGlobalTyVars, valueEnvIds, TcTyThing(..)
25                         )
26 import TcType           ( TcType, TcKind, TcTyVar, TcThetaType, TcTauType,
27                           typeToTcType, kindToTcKind,
28                           newKindVar, tcInstSigVar,
29                           zonkTcKindToKind, zonkTcTypeToType, zonkTcTyVars, zonkTcType
30                         )
31 import Inst             ( Inst, InstOrigin(..), newMethodWithGivenTy, instToIdBndr )
32 import TcUnify          ( unifyKind, unifyKinds, unifyTypeKind )
33 import Type             ( Type, ThetaType, UsageAnn(..),
34                           mkTyVarTy, mkTyVarTys, mkFunTy, mkSynTy, mkUsgTy,
35                           mkUsForAllTy, zipFunTys,
36                           mkSigmaTy, mkDictTy, mkTyConApp, mkAppTys, splitForAllTys, splitRhoTy,
37                           boxedTypeKind, unboxedTypeKind, tyVarsOfType,
38                           mkArrowKinds, getTyVar_maybe, getTyVar,
39                           tidyOpenType, tidyOpenTypes, tidyTyVar,
40                           tyVarsOfType, tyVarsOfTypes
41                         )
42 import PprType          ( pprConstraint )
43 import Subst            ( mkTopTyVarSubst, substTy )
44 import Id               ( mkVanillaId, idName, idType, idFreeTyVars )
45 import Var              ( TyVar, mkTyVar, mkNamedUVar, varName )
46 import VarEnv
47 import VarSet
48 import Bag              ( bagToList )
49 import ErrUtils         ( Message )
50 import PrelInfo         ( cCallishClassKeys )
51 import TyCon            ( TyCon )
52 import Name             ( Name, OccName, isLocallyDefined )
53 import TysWiredIn       ( mkListTy, mkTupleTy, mkUnboxedTupleTy )
54 import UniqFM           ( elemUFM, foldUFM )
55 import SrcLoc           ( SrcLoc )
56 import Unique           ( Unique, Uniquable(..) )
57 import Util             ( zipWithEqual, zipLazy, mapAccumL )
58 import Outputable
59 \end{code}
60
61
62 %************************************************************************
63 %*                                                                      *
64 \subsection{Checking types}
65 %*                                                                      *
66 %************************************************************************
67
68 tcHsType and tcHsTypeKind
69 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
70
71 tcHsType checks that the type really is of kind Type!
72
73 \begin{code}
74 tcHsType :: RenamedHsType -> TcM s TcType
75 tcHsType ty
76   = -- tcAddErrCtxt (typeCtxt ty)               $
77     tc_type ty
78
79 tcHsTypeKind    :: RenamedHsType -> TcM s (TcKind, TcType)
80 tcHsTypeKind ty 
81   = -- tcAddErrCtxt (typeCtxt ty)               $
82     tc_type_kind ty
83
84 -- Type-check a type, *and* then lazily zonk it.  The important
85 -- point is that this zonks all the uncommitted *kind* variables
86 -- in kinds of any any nested for-all tyvars.
87 -- There won't be any mutable *type* variables at all.
88 --
89 -- NOTE the forkNF_Tc.  This makes the zonking lazy, which is
90 -- absolutely necessary.  During the type-checking of a recursive
91 -- group of tycons/classes (TcTyClsDecls.tcGroup) we use an
92 -- environment in which we aren't allowed to look at the actual
93 -- tycons/classes returned from a lookup. Because tc_app does
94 -- look at the tycon to build the type, we can't look at the type
95 -- either, until we get out of the loop.   The fork delays the
96 -- zonking till we've completed the loop.  Sigh.
97
98 tcHsTopType :: RenamedHsType -> TcM s Type
99 tcHsTopType ty
100   = -- tcAddErrCtxt (typeCtxt ty)               $
101     tc_type ty                          `thenTc` \ ty' ->
102     forkNF_Tc (zonkTcTypeToType ty')
103
104 tcHsTopTypeKind :: RenamedHsType -> TcM s (TcKind, Type)
105 tcHsTopTypeKind ty
106   = -- tcAddErrCtxt (typeCtxt ty)               $
107     tc_type_kind ty                             `thenTc` \ (kind, ty') ->
108     forkNF_Tc (zonkTcTypeToType ty')            `thenTc` \ zonked_ty ->
109     returnNF_Tc (kind, zonked_ty)
110
111 tcHsTopBoxedType :: RenamedHsType -> TcM s Type
112 tcHsTopBoxedType ty
113   = -- tcAddErrCtxt (typeCtxt ty)               $
114     tc_boxed_type ty                    `thenTc` \ ty' ->
115     forkNF_Tc (zonkTcTypeToType ty')
116 \end{code}
117
118
119 The main work horse
120 ~~~~~~~~~~~~~~~~~~~
121
122 \begin{code}
123 tc_boxed_type :: RenamedHsType -> TcM s Type
124 tc_boxed_type ty
125   = tc_type_kind ty                                     `thenTc` \ (actual_kind, tc_ty) ->
126     tcAddErrCtxt (typeKindCtxt ty)
127                  (unifyKind boxedTypeKind actual_kind)  `thenTc_`
128     returnTc tc_ty
129
130 tc_type :: RenamedHsType -> TcM s Type
131 tc_type ty
132         -- The type ty must be a *type*, but it can be boxed
133         -- or unboxed.  So we check that is is of form (Type bv)
134         -- using unifyTypeKind
135   = tc_type_kind ty                             `thenTc` \ (actual_kind, tc_ty) ->
136     tcAddErrCtxt (typeKindCtxt ty)
137                  (unifyTypeKind actual_kind)    `thenTc_`
138     returnTc tc_ty
139
140 tc_type_kind :: RenamedHsType -> TcM s (TcKind, Type)
141 tc_type_kind ty@(MonoTyVar name)
142   = tc_app ty []
143     
144 tc_type_kind (MonoListTy ty)
145   = tc_boxed_type ty            `thenTc` \ tau_ty ->
146     returnTc (boxedTypeKind, mkListTy tau_ty)
147
148 tc_type_kind (MonoTupleTy tys True {-boxed-})
149   = mapTc tc_boxed_type tys     `thenTc` \ tau_tys ->
150     returnTc (boxedTypeKind, mkTupleTy (length tys) tau_tys)
151
152 tc_type_kind (MonoTupleTy tys False {-unboxed-})
153   = mapTc tc_type tys                   `thenTc` \ tau_tys ->
154     returnTc (unboxedTypeKind, mkUnboxedTupleTy (length tys) tau_tys)
155
156 tc_type_kind (MonoFunTy ty1 ty2)
157   = tc_type ty1 `thenTc` \ tau_ty1 ->
158     tc_type ty2 `thenTc` \ tau_ty2 ->
159     returnTc (boxedTypeKind, mkFunTy tau_ty1 tau_ty2)
160
161 tc_type_kind (MonoTyApp ty1 ty2)
162   = tc_app ty1 [ty2]
163
164 tc_type_kind (MonoDictTy class_name tys)
165   = tcClassAssertion (class_name, tys)  `thenTc` \ (clas, arg_tys) ->
166     returnTc (boxedTypeKind, mkDictTy clas arg_tys)
167
168 tc_type_kind (MonoUsgTy usg ty)
169   = newUsg usg                          `thenTc` \ usg' ->
170     tc_type_kind ty                     `thenTc` \ (kind, tc_ty) ->
171     returnTc (kind, mkUsgTy usg' tc_ty)
172   where
173     newUsg usg = case usg of
174                    MonoUsOnce        -> returnTc UsOnce
175                    MonoUsMany        -> returnTc UsMany
176                    MonoUsVar uv_name -> tcLookupUVar uv_name `thenTc` \ uv ->
177                                         returnTc (UsVar uv)
178
179 tc_type_kind (MonoUsgForAllTy uv_name ty)
180   = let
181         uv = mkNamedUVar uv_name
182     in
183     tcExtendUVarEnv uv_name uv $
184       tc_type_kind ty                     `thenTc` \ (kind, tc_ty) ->
185       returnTc (kind, mkUsForAllTy uv tc_ty)
186
187 tc_type_kind (HsForAllTy (Just tv_names) context ty)
188   = tcExtendTyVarScope tv_names         $ \ tyvars ->
189     tcContext context                   `thenTc` \ theta ->
190     tc_type_kind ty                     `thenTc` \ (kind, tau) ->
191     tcGetInScopeTyVars                  `thenTc` \ in_scope_vars ->
192     let
193         body_kind | null theta = kind
194                   | otherwise  = boxedTypeKind
195                 -- Context behaves like a function type
196                 -- This matters.  Return-unboxed-tuple analysis can
197                 -- give overloaded functions like
198                 --      f :: forall a. Num a => (# a->a, a->a #)
199                 -- And we want these to get through the type checker
200         check ct@(c,tys) | ambiguous = failWithTc (ambigErr ct tau)
201                          | otherwise = returnTc ()
202           where ct_vars = tyVarsOfTypes tys
203                 forall_tyvars = map varName in_scope_vars
204                 tau_vars = tyVarsOfType tau
205                 ambig ct_var = (varName ct_var `elem` forall_tyvars) &&
206                                not (ct_var `elemUFM` tau_vars)
207                 ambiguous = foldUFM ((||) . ambig) False ct_vars
208     in
209     mapTc check theta                   `thenTc_`
210     returnTc (body_kind, mkSigmaTy tyvars theta tau)
211 \end{code}
212
213 Help functions for type applications
214 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
215
216 \begin{code}
217 tc_app (MonoTyApp ty1 ty2) tys
218   = tc_app ty1 (ty2:tys)
219
220 tc_app ty tys
221   | null tys
222   = tc_fun_type ty []
223
224   | otherwise
225   = tcAddErrCtxt (appKindCtxt pp_app)   $
226     mapAndUnzipTc tc_type_kind tys      `thenTc` \ (arg_kinds, arg_tys) ->
227     tc_fun_type ty arg_tys              `thenTc` \ (fun_kind, result_ty) ->
228
229         -- Check argument compatibility
230     newKindVar                                  `thenNF_Tc` \ result_kind ->
231     unifyKind fun_kind (mkArrowKinds arg_kinds result_kind)
232                                         `thenTc_`
233     returnTc (result_kind, result_ty)
234   where
235     pp_app = ppr ty <+> sep (map pprParendHsType tys)
236
237 -- (tc_fun_type ty arg_tys) returns (kind-of ty, mkAppTys ty arg_tys)
238 -- But not quite; for synonyms it checks the correct arity, and builds a SynTy
239 --      hence the rather strange functionality.
240
241 tc_fun_type (MonoTyVar name) arg_tys
242   = tcLookupTy name                     `thenTc` \ (tycon_kind, maybe_arity, thing) ->
243     case thing of
244         ATyVar tv   -> returnTc (tycon_kind, mkAppTys (mkTyVarTy tv) arg_tys)
245         AClass clas -> failWithTc (classAsTyConErr name)
246         ATyCon tc   -> case maybe_arity of
247                          Nothing ->     -- Data or newtype
248                                         returnTc (tycon_kind, mkTyConApp tc arg_tys)
249
250                          Just arity ->  -- Type synonym
251                                   checkTc (arity <= n_args) err_msg     `thenTc_`
252                                   returnTc (tycon_kind, result_ty)
253                            where
254                                 -- It's OK to have an *over-applied* type synonym
255                                 --      data Tree a b = ...
256                                 --      type Foo a = Tree [a]
257                                 --      f :: Foo a b -> ...
258                               result_ty = mkAppTys (mkSynTy tc (take arity arg_tys))
259                                                    (drop arity arg_tys)
260                               err_msg = arityErr "type synonym" name arity n_args
261                               n_args  = length arg_tys
262
263 tc_fun_type ty arg_tys
264   = tc_type_kind ty             `thenTc` \ (fun_kind, fun_ty) ->
265     returnTc (fun_kind, mkAppTys fun_ty arg_tys)
266 \end{code}
267
268
269 Contexts
270 ~~~~~~~~
271 \begin{code}
272
273 tcContext :: RenamedContext -> TcM s ThetaType
274 tcContext context
275   =     --Someone discovered that @CCallable@ and @CReturnable@
276         -- could be used in contexts such as:
277         --      foo :: CCallable a => a -> PrimIO Int
278         -- Doing this utterly wrecks the whole point of introducing these
279         -- classes so we specifically check that this isn't being done.
280         --
281         -- We *don't* do this check in tcClassAssertion, because that's
282         -- called when checking a HsDictTy, and we don't want to reject
283         --      instance CCallable Int 
284         -- etc. Ugh!
285     mapTc check_naughty context `thenTc_`
286
287     mapTc tcClassAssertion context
288
289  where
290    check_naughty (class_name, _) 
291      = checkTc (not (getUnique class_name `elem` cCallishClassKeys))
292                (naughtyCCallContextErr class_name)
293
294 tcClassAssertion assn@(class_name, tys)
295   = tcAddErrCtxt (appKindCtxt (pprClassAssertion assn)) $
296     mapAndUnzipTc tc_type_kind tys      `thenTc` \ (arg_kinds, arg_tys) ->
297     tcLookupTy class_name               `thenTc` \ (kind, ~(Just arity), thing) ->
298     case thing of
299         ATyVar  _   -> failWithTc (tyVarAsClassErr class_name)
300         ATyCon  _   -> failWithTc (tyConAsClassErr class_name)
301         AClass clas ->
302                         -- Check with kind mis-match
303                 checkTc (arity == n_tys) err                            `thenTc_`
304                 unifyKind kind (mkArrowKinds arg_kinds boxedTypeKind)   `thenTc_`
305                 returnTc (clas, arg_tys)
306             where
307                 n_tys = length tys
308                 err   = arityErr "Class" class_name arity n_tys
309 \end{code}
310
311
312 %************************************************************************
313 %*                                                                      *
314 \subsection{Type variables, with knot tying!}
315 %*                                                                      *
316 %************************************************************************
317
318 \begin{code}
319 tcExtendTopTyVarScope :: TcKind -> [HsTyVar Name]
320                       -> ([TcTyVar] -> TcKind -> TcM s a)
321                       -> TcM s a
322 tcExtendTopTyVarScope kind tyvar_names thing_inside
323   = let
324         (tyvars_w_kinds, result_kind) = zipFunTys tyvar_names kind
325         tyvars                        = map mk_tv tyvars_w_kinds
326     in
327     tcExtendTyVarEnv tyvars (thing_inside tyvars result_kind)   
328   where
329     mk_tv (UserTyVar name,    kind) = mkTyVar name kind
330     mk_tv (IfaceTyVar name _, kind) = mkTyVar name kind
331         -- NB: immutable tyvars, but perhaps with mutable kinds
332
333 tcExtendTyVarScope :: [HsTyVar Name] 
334                    -> ([TcTyVar] -> TcM s a) -> TcM s a
335 tcExtendTyVarScope tv_names thing_inside
336   = mapNF_Tc tcHsTyVar tv_names         `thenNF_Tc` \ tyvars ->
337     tcExtendTyVarEnv tyvars             $
338     thing_inside tyvars
339     
340 tcHsTyVar :: HsTyVar Name -> NF_TcM s TcTyVar
341 tcHsTyVar (UserTyVar name)       = newKindVar           `thenNF_Tc` \ kind ->
342                                    tcNewMutTyVar name kind
343         -- NB: mutable kind => mutable tyvar, so that zonking can bind
344         -- the tyvar to its immutable form
345
346 tcHsTyVar (IfaceTyVar name kind) = returnNF_Tc (mkTyVar name (kindToTcKind kind))
347
348 kcHsTyVar :: HsTyVar name -> NF_TcM s TcKind
349 kcHsTyVar (UserTyVar name)       = newKindVar
350 kcHsTyVar (IfaceTyVar name kind) = returnNF_Tc (kindToTcKind kind)
351 \end{code}
352
353
354 %************************************************************************
355 %*                                                                      *
356 \subsection{Signatures}
357 %*                                                                      *
358 %************************************************************************
359
360 @tcSigs@ checks the signatures for validity, and returns a list of
361 {\em freshly-instantiated} signatures.  That is, the types are already
362 split up, and have fresh type variables installed.  All non-type-signature
363 "RenamedSigs" are ignored.
364
365 The @TcSigInfo@ contains @TcTypes@ because they are unified with
366 the variable's type, and after that checked to see whether they've
367 been instantiated.
368
369 \begin{code}
370 data TcSigInfo
371   = TySigInfo       
372         Name                    -- N, the Name in corresponding binding
373
374         TcId                    -- *Polymorphic* binder for this value...
375                                 -- Has name = N
376
377         [TcTyVar]               -- tyvars
378         TcThetaType             -- theta
379         TcTauType               -- tau
380
381         TcId                    -- *Monomorphic* binder for this value
382                                 -- Does *not* have name = N
383                                 -- Has type tau
384
385         Inst                    -- Empty if theta is null, or 
386                                 -- (method mono_id) otherwise
387
388         SrcLoc                  -- Of the signature
389
390
391 maybeSig :: [TcSigInfo] -> Name -> Maybe (TcSigInfo)
392         -- Search for a particular signature
393 maybeSig [] name = Nothing
394 maybeSig (sig@(TySigInfo sig_name _ _ _ _ _ _ _) : sigs) name
395   | name == sig_name = Just sig
396   | otherwise        = maybeSig sigs name
397 \end{code}
398
399
400 \begin{code}
401 tcTySig :: RenamedSig -> TcM s TcSigInfo
402
403 tcTySig (Sig v ty src_loc)
404  = tcAddSrcLoc src_loc $
405    tcHsType ty                                  `thenTc` \ sigma_tc_ty ->
406    mkTcSig (mkVanillaId v sigma_tc_ty) src_loc  `thenNF_Tc` \ sig -> 
407    returnTc sig
408
409 mkTcSig :: TcId -> SrcLoc -> NF_TcM s TcSigInfo
410 mkTcSig poly_id src_loc
411   =     -- Instantiate this type
412         -- It's important to do this even though in the error-free case
413         -- we could just split the sigma_tc_ty (since the tyvars don't
414         -- unified with anything).  But in the case of an error, when
415         -- the tyvars *do* get unified with something, we want to carry on
416         -- typechecking the rest of the program with the function bound
417         -- to a pristine type, namely sigma_tc_ty
418    let
419         (tyvars, rho) = splitForAllTys (idType poly_id)
420    in
421    mapNF_Tc tcInstSigVar tyvars         `thenNF_Tc` \ tyvars' ->
422         -- Make *signature* type variables
423
424    let
425      tyvar_tys' = mkTyVarTys tyvars'
426      rho' = substTy (mkTopTyVarSubst tyvars tyvar_tys') rho
427         -- mkTopTyVarSubst because the tyvars' are fresh
428      (theta', tau') = splitRhoTy rho'
429         -- This splitRhoTy tries hard to make sure that tau' is a type synonym
430         -- wherever possible, which can improve interface files.
431    in
432    newMethodWithGivenTy SignatureOrigin 
433                 poly_id
434                 tyvar_tys'
435                 theta' tau'                     `thenNF_Tc` \ inst ->
436         -- We make a Method even if it's not overloaded; no harm
437         
438    returnNF_Tc (TySigInfo name poly_id tyvars' theta' tau' (instToIdBndr inst) inst src_loc)
439   where
440     name = idName poly_id
441 \end{code}
442
443
444
445 %************************************************************************
446 %*                                                                      *
447 \subsection{Checking signature type variables}
448 %*                                                                      *
449 %************************************************************************
450
451 @checkSigTyVars@ is used after the type in a type signature has been unified with
452 the actual type found.  It then checks that the type variables of the type signature
453 are
454         (a) Still all type variables
455                 eg matching signature [a] against inferred type [(p,q)]
456                 [then a will be unified to a non-type variable]
457
458         (b) Still all distinct
459                 eg matching signature [(a,b)] against inferred type [(p,p)]
460                 [then a and b will be unified together]
461
462         (c) Not mentioned in the environment
463                 eg the signature for f in this:
464
465                         g x = ... where
466                                         f :: a->[a]
467                                         f y = [x,y]
468
469                 Here, f is forced to be monorphic by the free occurence of x.
470
471         (d) Not (unified with another type variable that is) in scope.
472                 eg f x :: (r->r) = (\y->y) :: forall a. a->r
473             when checking the expression type signature, we find that
474             even though there is nothing in scope whose type mentions r,
475             nevertheless the type signature for the expression isn't right.
476
477             Another example is in a class or instance declaration:
478                 class C a where
479                    op :: forall b. a -> b
480                    op x = x
481             Here, b gets unified with a
482
483 Before doing this, the substitution is applied to the signature type variable.
484
485 We used to have the notion of a "DontBind" type variable, which would
486 only be bound to itself or nothing.  Then points (a) and (b) were 
487 self-checking.  But it gave rise to bogus consequential error messages.
488 For example:
489
490    f = (*)      -- Monomorphic
491
492    g :: Num a => a -> a
493    g x = f x x
494
495 Here, we get a complaint when checking the type signature for g,
496 that g isn't polymorphic enough; but then we get another one when
497 dealing with the (Num x) context arising from f's definition;
498 we try to unify x with Int (to default it), but find that x has already
499 been unified with the DontBind variable "a" from g's signature.
500 This is really a problem with side-effecting unification; we'd like to
501 undo g's effects when its type signature fails, but unification is done
502 by side effect, so we can't (easily).
503
504 So we revert to ordinary type variables for signatures, and try to
505 give a helpful message in checkSigTyVars.
506
507 \begin{code}
508 checkSigTyVars :: [TcTyVar]             -- The original signature type variables
509                -> TcM s [TcTyVar]       -- Zonked signature type variables
510
511 checkSigTyVars [] = returnTc []
512
513 checkSigTyVars sig_tyvars
514   = zonkTcTyVars sig_tyvars             `thenNF_Tc` \ sig_tys ->
515     tcGetGlobalTyVars                   `thenNF_Tc` \ globals ->
516
517     checkTcM (all_ok sig_tys globals)
518              (complain sig_tys globals) `thenTc_`
519
520     returnTc (map (getTyVar "checkSigTyVars") sig_tys)
521
522   where
523     all_ok []       acc = True
524     all_ok (ty:tys) acc = case getTyVar_maybe ty of
525                             Nothing                       -> False      -- Point (a)
526                             Just tv | tv `elemVarSet` acc -> False      -- Point (b) or (c)
527                                     | otherwise           -> all_ok tys (acc `extendVarSet` tv)
528     
529
530     complain sig_tys globals
531       = -- For the in-scope ones, zonk them and construct a map
532         -- from the zonked tyvar to the in-scope one
533         -- If any of the in-scope tyvars zonk to a type, then ignore them;
534         -- that'll be caught later when we back up to their type sig
535         tcGetInScopeTyVars                      `thenNF_Tc` \ in_scope_tvs ->
536         zonkTcTyVars in_scope_tvs               `thenNF_Tc` \ in_scope_tys ->
537         let
538             in_scope_assoc = [ (zonked_tv, in_scope_tv) 
539                              | (z_ty, in_scope_tv) <- in_scope_tys `zip` in_scope_tvs,
540                                Just zonked_tv <- [getTyVar_maybe z_ty]
541                              ]
542             in_scope_env = mkVarEnv in_scope_assoc
543         in
544
545         -- "check" checks each sig tyvar in turn
546         foldlNF_Tc check
547                    (env2, in_scope_env, [])
548                    (tidy_tvs `zip` tidy_tys)    `thenNF_Tc` \ (env3, _, msgs) ->
549
550         failWithTcM (env3, main_msg $$ nest 4 (vcat msgs))
551       where
552         (env1, tidy_tvs) = mapAccumL tidyTyVar emptyTidyEnv sig_tyvars
553         (env2, tidy_tys) = tidyOpenTypes env1 sig_tys
554
555         main_msg = ptext SLIT("Inferred type is less polymorphic than expected")
556
557         check (env, acc, msgs) (sig_tyvar,ty)
558                 -- sig_tyvar is from the signature;
559                 -- ty is what you get if you zonk sig_tyvar and then tidy it
560                 --
561                 -- acc maps a zonked type variable back to a signature type variable
562           = case getTyVar_maybe ty of {
563               Nothing ->                        -- Error (a)!
564                         returnNF_Tc (env, acc, unify_msg sig_tyvar (ppr ty) : msgs) ;
565
566               Just tv ->
567
568             case lookupVarEnv acc tv of {
569                 Just sig_tyvar' ->      -- Error (b) or (d)!
570                         returnNF_Tc (env, acc, unify_msg sig_tyvar (ppr sig_tyvar') : msgs) ;
571
572                 Nothing ->
573
574             if tv `elemVarSet` globals  -- Error (c)! Type variable escapes
575                                         -- The least comprehensible, so put it last
576             then   tcGetValueEnv                        `thenNF_Tc` \ ve ->
577                    find_globals tv env (valueEnvIds ve) `thenNF_Tc` \ (env1, globs) ->
578                    returnNF_Tc (env1, acc, escape_msg sig_tyvar tv globs : msgs)
579
580             else        -- All OK
581             returnNF_Tc (env, extendVarEnv acc tv sig_tyvar, msgs)
582             }}
583
584 -- find_globals looks at the value environment and finds values
585 -- whose types mention the offending type variable.  It has to be 
586 -- careful to zonk the Id's type first, so it has to be in the monad.
587 -- We must be careful to pass it a zonked type variable, too.
588 find_globals tv tidy_env ids
589   | null ids
590   = returnNF_Tc (tidy_env, [])
591
592 find_globals tv tidy_env (id:ids) 
593   | not (isLocallyDefined id) ||
594     isEmptyVarSet (idFreeTyVars id)
595   = find_globals tv tidy_env ids
596
597   | otherwise
598   = zonkTcType (idType id)      `thenNF_Tc` \ id_ty ->
599     if tv `elemVarSet` tyVarsOfType id_ty then
600         let 
601            (tidy_env', id_ty') = tidyOpenType tidy_env id_ty
602         in
603         find_globals tv tidy_env' ids   `thenNF_Tc` \ (tidy_env'', globs) ->
604         returnNF_Tc (tidy_env'', (idName id, id_ty') : globs)
605     else
606         find_globals tv tidy_env ids
607
608 escape_msg sig_tv tv globs
609   = vcat [mk_msg sig_tv <+> ptext SLIT("escapes"),
610           pp_escape,
611           ptext SLIT("The following variables in the environment mention") <+> quotes (ppr tv),
612           nest 4 (vcat_first 10 [ppr name <+> dcolon <+> ppr ty | (name,ty) <- globs])
613     ]
614   where
615     pp_escape | sig_tv /= tv = ptext SLIT("It unifies with") <+>
616                                quotes (ppr tv) <> comma <+>
617                                ptext SLIT("which is mentioned in the environment")
618               | otherwise    = ptext SLIT("It is mentioned in the environment")
619
620     vcat_first :: Int -> [SDoc] -> SDoc
621     vcat_first n []     = empty
622     vcat_first 0 (x:xs) = text "...others omitted..."
623     vcat_first n (x:xs) = x $$ vcat_first (n-1) xs
624
625 unify_msg tv thing = mk_msg tv <+> ptext SLIT("is unified with") <+> quotes thing
626 mk_msg tv          = ptext SLIT("Quantified type variable") <+> quotes (ppr tv)
627 \end{code}
628
629 These two context are used with checkSigTyVars
630     
631 \begin{code}
632 sigCtxt :: (Type -> Message) -> Type
633         -> TidyEnv -> NF_TcM s (TidyEnv, Message)
634 sigCtxt mk_msg sig_ty tidy_env
635   = let
636         (env1, tidy_sig_ty) = tidyOpenType tidy_env sig_ty
637     in
638     returnNF_Tc (env1, mk_msg tidy_sig_ty)
639
640 sigPatCtxt bound_tvs bound_ids tidy_env
641   = returnNF_Tc (env1,
642                  sep [ptext SLIT("When checking a pattern that binds"),
643                       nest 4 (vcat (zipWith ppr_id show_ids tidy_tys))])
644   where
645     show_ids = filter is_interesting bound_ids
646     is_interesting id = any (`elemVarSet` idFreeTyVars id) bound_tvs
647
648     (env1, tidy_tys) = tidyOpenTypes tidy_env (map idType show_ids)
649     ppr_id id ty     = ppr id <+> dcolon <+> ppr ty
650         -- Don't zonk the types so we get the separate, un-unified versions
651 \end{code}
652
653
654 %************************************************************************
655 %*                                                                      *
656 \subsection{Errors and contexts}
657 %*                                                                      *
658 %************************************************************************
659
660 \begin{code}
661 naughtyCCallContextErr clas_name
662   = sep [ptext SLIT("Can't use class") <+> quotes (ppr clas_name), 
663          ptext SLIT("in a context")]
664
665 typeCtxt ty = ptext SLIT("In the type") <+> quotes (ppr ty)
666
667 typeKindCtxt :: RenamedHsType -> Message
668 typeKindCtxt ty = sep [ptext SLIT("When checking that"),
669                        nest 2 (quotes (ppr ty)),
670                        ptext SLIT("is a type")]
671
672 appKindCtxt :: SDoc -> Message
673 appKindCtxt pp = ptext SLIT("When checking kinds in") <+> quotes pp
674
675 classAsTyConErr name
676   = ptext SLIT("Class used as a type constructor:") <+> ppr name
677
678 tyConAsClassErr name
679   = ptext SLIT("Type constructor used as a class:") <+> ppr name
680
681 tyVarAsClassErr name
682   = ptext SLIT("Type variable used as a class:") <+> ppr name
683
684 ambigErr (c, ts) ty
685   = sep [ptext SLIT("Ambiguous constraint") <+> quotes (pprConstraint c ts),
686          nest 4 (ptext SLIT("for the type:") <+> ppr ty),
687          nest 4 (ptext SLIT("Each forall'd type variable mentioned by the constraint must appear after the =>."))]
688 \end{code}