[project @ 2001-10-17 10:35:34 by simonpj]
[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 ( tcHsSigType, tcHsType, tcIfaceType, tcHsTheta, 
8                     UserTypeCtxt(..),
9
10                         -- Kind checking
11                     kcHsTyVar, kcHsTyVars, mkTyClTyVars,
12                     kcHsType, kcHsSigType, kcHsSigTypes, 
13                     kcHsLiftedSigType, kcHsContext,
14                     tcScopedTyVars, tcHsTyVars, mkImmutTyVars,
15
16                     TcSigInfo(..), tcTySig, mkTcSig, maybeSig,
17                     checkSigTyVars, sigCtxt, sigPatCtxt
18                   ) where
19
20 #include "HsVersions.h"
21
22 import HsSyn            ( HsType(..), HsTyVarBndr(..),
23                           Sig(..), HsPred(..), pprParendHsType, HsTupCon(..), hsTyVarNames )
24 import RnHsSyn          ( RenamedHsType, RenamedHsPred, RenamedContext, RenamedSig )
25 import TcHsSyn          ( TcId )
26
27 import TcMonad
28 import TcEnv            ( tcExtendTyVarEnv, tcLookup, tcLookupGlobal,
29                           tcGetGlobalTyVars, tcEnvTcIds, tcEnvTyVars,
30                           TyThing(..), TcTyThing(..), tcExtendKindEnv
31                         )
32 import TcMType          ( newKindVar, tcInstSigVars, 
33                           zonkKindEnv, zonkTcType, zonkTcTyVars, zonkTcTyVar,
34                           unifyKind, unifyOpenTypeKind,
35                           checkValidType, UserTypeCtxt(..), pprUserTypeCtxt
36                         )
37 import TcType           ( Type, Kind, SourceType(..), ThetaType,
38                           mkTyVarTy, mkTyVarTys, mkFunTy, mkSynTy,
39                           tcSplitForAllTys, tcSplitRhoTy,
40                           hoistForAllTys, allDistinctTyVars,
41                           zipFunTys, 
42                           mkSigmaTy, mkPredTy, mkTyConApp,
43                           mkAppTys, mkRhoTy,
44                           liftedTypeKind, unliftedTypeKind, mkArrowKind,
45                           mkArrowKinds, tcGetTyVar_maybe, tcGetTyVar, tcSplitFunTy_maybe,
46                           tidyOpenType, tidyOpenTypes, tidyOpenTyVar, tidyOpenTyVars,
47                           tyVarsOfType, mkForAllTys
48                         )
49 import Inst             ( Inst, InstOrigin(..), newMethodWithGivenTy, instToId )
50 import PprType          ( pprType )
51 import Subst            ( mkTopTyVarSubst, substTy )
52 import CoreFVs          ( idFreeTyVars )
53 import Id               ( mkLocalId, idName, idType )
54 import Var              ( Id, Var, TyVar, mkTyVar, tyVarKind )
55 import VarEnv
56 import VarSet
57 import ErrUtils         ( Message )
58 import TyCon            ( TyCon, isSynTyCon, tyConArity, tyConKind )
59 import Class            ( classTyCon )
60 import Name             ( Name )
61 import TysWiredIn       ( mkListTy, mkTupleTy, genUnitTyCon )
62 import BasicTypes       ( Boxity(..) )
63 import SrcLoc           ( SrcLoc )
64 import Util             ( isSingleton )
65 import Outputable
66
67 \end{code}
68
69
70 %************************************************************************
71 %*                                                                      *
72 \subsection{Checking types}
73 %*                                                                      *
74 %************************************************************************
75
76 Generally speaking we now type-check types in three phases
77
78         1.  Kind check the HsType [kcHsType]
79         2.  Convert from HsType to Type, and hoist the foralls [tcHsType]
80         3.  Check the validity of the resulting type [checkValidType]
81
82 Often these steps are done one after the othe (tcHsSigType).
83 But in mutually recursive groups of type and class decls we do
84         1 kind-check the whole group
85         2 build TyCons/Classes in a knot-tied wa
86         3 check the validity of types in the now-unknotted TyCons/Classes
87
88 \begin{code}
89 tcHsSigType :: UserTypeCtxt -> RenamedHsType -> TcM Type
90   -- Do kind checking, and hoist for-alls to the top
91 tcHsSigType ctxt ty = tcAddErrCtxt (checkTypeCtxt ctxt ty) (
92                         kcTypeType ty           `thenTc_`
93                         tcHsType ty
94                       )                         `thenTc` \ ty' ->
95                       checkValidType ctxt ty'   `thenTc_`
96                       returnTc ty'
97
98 checkTypeCtxt ctxt ty
99   = vcat [ptext SLIT("In the type:") <+> ppr ty,
100           ptext SLIT("While checking") <+> pprUserTypeCtxt ctxt ]
101
102 tcHsType    :: RenamedHsType -> TcM Type
103   -- Don't do kind checking, nor validity checking, 
104   --    but do hoist for-alls to the top
105   -- This is used in type and class decls, where kinding is
106   -- done in advance, and validity checking is done later
107   -- [Validity checking done later because of knot-tying issues.]
108 tcHsType ty = tc_type ty  `thenTc` \ ty' ->  
109               returnTc (hoistForAllTys ty')
110
111 tcHsTheta :: RenamedContext -> TcM ThetaType
112 -- Used when we are expecting a ClassContext (i.e. no implicit params)
113 -- Does not do validity checking, like tcHsType
114 tcHsTheta hs_theta = mapTc tc_pred hs_theta
115
116 -- In interface files the type is already kinded,
117 -- and we definitely don't want to hoist for-alls.
118 -- Otherwise we'll change
119 --      dmfail :: forall m:(*->*) Monad m => forall a:* => String -> m a
120 -- into 
121 --      dmfail :: forall m:(*->*) a:* Monad m => String -> m a
122 -- which definitely isn't right!
123 tcIfaceType ty = tc_type ty
124 \end{code}
125
126
127 %************************************************************************
128 %*                                                                      *
129 \subsection{Kind checking}
130 %*                                                                      *
131 %************************************************************************
132
133 Kind checking
134 ~~~~~~~~~~~~~
135 When we come across the binding site for some type variables, we
136 proceed in two stages
137
138 1. Figure out what kind each tyvar has
139
140 2. Create suitably-kinded tyvars, 
141    extend the envt, 
142    and typecheck the body
143
144 To do step 1, we proceed thus:
145
146 1a. Bind each type variable to a kind variable
147 1b. Apply the kind checker
148 1c. Zonk the resulting kinds
149
150 The kind checker is passed to tcHsTyVars as an argument.  
151
152 For example, when we find
153         (forall a m. m a -> m a)
154 we bind a,m to kind varibles and kind-check (m a -> m a).  This
155 makes a get kind *, and m get kind *->*.  Now we typecheck (m a -> m a)
156 in an environment that binds a and m suitably.
157
158 The kind checker passed to tcHsTyVars needs to look at enough to
159 establish the kind of the tyvar:
160   * For a group of type and class decls, it's just the group, not
161         the rest of the program
162   * For a tyvar bound in a pattern type signature, its the types
163         mentioned in the other type signatures in that bunch of patterns
164   * For a tyvar bound in a RULE, it's the type signatures on other
165         universally quantified variables in the rule
166
167 Note that this may occasionally give surprising results.  For example:
168
169         data T a b = MkT (a b)
170
171 Here we deduce                  a::*->*, b::*.
172 But equally valid would be
173                                 a::(*->*)-> *, b::*->*
174
175 \begin{code}
176 -- tcHsTyVars is used for type variables in type signatures
177 --      e.g. forall a. a->a
178 -- They are immutable, because they scope only over the signature
179 -- They may or may not be explicitly-kinded
180 tcHsTyVars :: [HsTyVarBndr Name] 
181            -> TcM a                             -- The kind checker
182            -> ([TyVar] -> TcM b)
183            -> TcM b
184
185 tcHsTyVars [] kind_check thing_inside = thing_inside []
186         -- A useful short cut for a common case!
187   
188 tcHsTyVars tv_names kind_check thing_inside
189   = kcHsTyVars tv_names                                 `thenNF_Tc` \ tv_names_w_kinds ->
190     tcExtendKindEnv tv_names_w_kinds kind_check         `thenTc_`
191     zonkKindEnv tv_names_w_kinds                        `thenNF_Tc` \ tvs_w_kinds ->
192     let
193         tyvars = mkImmutTyVars tvs_w_kinds
194     in
195     tcExtendTyVarEnv tyvars (thing_inside tyvars)
196
197 -- tcScopedTyVars is used for scoped type variables
198 --      e.g.  \ (x::a) (y::a) -> x+y
199 -- They never have explicit kinds (because this is source-code only)
200 -- They are mutable (because they can get bound to a more specific type)
201 tcScopedTyVars :: [Name] 
202                -> TcM a                         -- The kind checker
203                -> TcM b
204                -> TcM b
205 tcScopedTyVars [] kind_check thing_inside = thing_inside
206
207 tcScopedTyVars tv_names kind_check thing_inside
208   = mapNF_Tc newNamedKindVar tv_names           `thenTc` \ kind_env ->
209     tcExtendKindEnv kind_env kind_check         `thenTc_`
210     zonkKindEnv kind_env                        `thenNF_Tc` \ tvs_w_kinds ->
211     listTc [tcNewMutTyVar name kind | (name, kind) <- tvs_w_kinds]      `thenNF_Tc` \ tyvars ->
212     tcExtendTyVarEnv tyvars thing_inside
213 \end{code}
214     
215
216 \begin{code}
217 kcHsTyVar  :: HsTyVarBndr name   -> NF_TcM (name, TcKind)
218 kcHsTyVars :: [HsTyVarBndr name] -> NF_TcM [(name, TcKind)]
219
220 kcHsTyVar (UserTyVar name)       = newNamedKindVar name
221 kcHsTyVar (IfaceTyVar name kind) = returnNF_Tc (name, kind)
222
223 kcHsTyVars tvs = mapNF_Tc kcHsTyVar tvs
224
225 newNamedKindVar name = newKindVar       `thenNF_Tc` \ kind ->
226                        returnNF_Tc (name, kind)
227
228 ---------------------------
229 kcLiftedType :: RenamedHsType -> TcM ()
230         -- The type ty must be a *lifted* *type*
231 kcLiftedType ty
232   = kcHsType ty                         `thenTc` \ kind ->
233     tcAddErrCtxt (typeKindCtxt ty)      $
234     unifyKind liftedTypeKind kind
235     
236 ---------------------------
237 kcTypeType :: RenamedHsType -> TcM ()
238         -- The type ty must be a *type*, but it can be lifted or unlifted.
239 kcTypeType ty
240   = kcHsType ty                         `thenTc` \ kind ->
241     tcAddErrCtxt (typeKindCtxt ty)      $
242     unifyOpenTypeKind kind
243
244 ---------------------------
245 kcHsSigType, kcHsLiftedSigType :: RenamedHsType -> TcM ()
246         -- Used for type signatures
247 kcHsSigType       = kcTypeType
248 kcHsSigTypes tys  = mapTc_ kcHsSigType tys
249 kcHsLiftedSigType = kcLiftedType
250
251 ---------------------------
252 kcHsType :: RenamedHsType -> TcM TcKind
253 kcHsType (HsTyVar name)       = kcTyVar name
254
255 kcHsType (HsListTy ty)
256   = kcLiftedType ty             `thenTc` \ tau_ty ->
257     returnTc liftedTypeKind
258
259 kcHsType (HsTupleTy (HsTupCon _ boxity _) tys)
260   = mapTc kcTypeType tys        `thenTc_`
261     returnTc (case boxity of
262                   Boxed   -> liftedTypeKind
263                   Unboxed -> unliftedTypeKind)
264
265 kcHsType (HsFunTy ty1 ty2)
266   = kcTypeType ty1      `thenTc_`
267     kcTypeType ty2      `thenTc_`
268     returnTc liftedTypeKind
269
270 kcHsType (HsNumTy _)            -- The unit type for generics
271   = returnTc liftedTypeKind
272
273 kcHsType ty@(HsOpTy ty1 op ty2)
274   = kcTyVar op                          `thenTc` \ op_kind ->
275     kcHsType ty1                        `thenTc` \ ty1_kind ->
276     kcHsType ty2                        `thenTc` \ ty2_kind ->
277     tcAddErrCtxt (appKindCtxt (ppr ty)) $
278     kcAppKind op_kind  ty1_kind         `thenTc` \ op_kind' ->
279     kcAppKind op_kind' ty2_kind
280    
281 kcHsType (HsPredTy pred)
282   = kcHsPred pred               `thenTc_`
283     returnTc liftedTypeKind
284
285 kcHsType ty@(HsAppTy ty1 ty2)
286   = kcHsType ty1                        `thenTc` \ tc_kind ->
287     kcHsType ty2                        `thenTc` \ arg_kind ->
288     tcAddErrCtxt (appKindCtxt (ppr ty)) $
289     kcAppKind tc_kind arg_kind
290
291 kcHsType (HsForAllTy (Just tv_names) context ty)
292   = kcHsTyVars tv_names         `thenNF_Tc` \ kind_env ->
293     tcExtendKindEnv kind_env    $
294     kcHsContext context         `thenTc_`
295     kcHsType ty                 `thenTc_`
296     returnTc liftedTypeKind
297
298 ---------------------------
299 kcAppKind fun_kind arg_kind
300   = case tcSplitFunTy_maybe fun_kind of 
301         Just (arg_kind', res_kind)
302                 -> unifyKind arg_kind arg_kind' `thenTc_`
303                    returnTc res_kind
304
305         Nothing -> newKindVar                                           `thenNF_Tc` \ res_kind ->
306                    unifyKind fun_kind (mkArrowKind arg_kind res_kind)   `thenTc_`
307                    returnTc res_kind
308
309
310 ---------------------------
311 kcHsContext ctxt = mapTc_ kcHsPred ctxt
312
313 kcHsPred :: RenamedHsPred -> TcM ()
314 kcHsPred pred@(HsIParam name ty)
315   = tcAddErrCtxt (appKindCtxt (ppr pred))       $
316     kcLiftedType ty
317
318 kcHsPred pred@(HsClassP cls tys)
319   = tcAddErrCtxt (appKindCtxt (ppr pred))       $
320     kcClass cls                                 `thenTc` \ kind ->
321     mapTc kcHsType tys                          `thenTc` \ arg_kinds ->
322     unifyKind kind (mkArrowKinds arg_kinds liftedTypeKind)
323
324  ---------------------------
325 kcTyVar name    -- Could be a tyvar or a tycon
326   = tcLookup name       `thenTc` \ thing ->
327     case thing of 
328         AThing kind         -> returnTc kind
329         ATyVar tv           -> returnTc (tyVarKind tv)
330         AGlobal (ATyCon tc) -> returnTc (tyConKind tc) 
331         other               -> failWithTc (wrongThingErr "type" thing name)
332
333 kcClass cls     -- Must be a class
334   = tcLookup cls                                `thenNF_Tc` \ thing -> 
335     case thing of
336         AThing kind           -> returnTc kind
337         AGlobal (AClass cls)  -> returnTc (tyConKind (classTyCon cls))
338         other                 -> failWithTc (wrongThingErr "class" thing cls)
339 \end{code}
340
341 %************************************************************************
342 %*                                                                      *
343 \subsection{tc_type}
344 %*                                                                      *
345 %************************************************************************
346
347 tc_type, the main work horse
348 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
349
350         -------------------
351         *** BIG WARNING ***
352         -------------------
353
354 tc_type is used to typecheck the types in the RHS of data
355 constructors.  In the case of recursive data types, that means that
356 the type constructors themselves are (partly) black holes.  e.g.
357
358         data T a = MkT a [T a]
359
360 While typechecking the [T a] on the RHS, T itself is not yet fully
361 defined.  That in turn places restrictions on what you can check in
362 tcHsType; if you poke on too much you get a black hole.  I keep
363 forgetting this, hence this warning!
364
365 So tc_type does no validity-checking.  Instead that's all done
366 by TcMType.checkValidType
367
368         --------------------------
369         *** END OF BIG WARNING ***
370         --------------------------
371
372
373 \begin{code}
374 tc_type :: RenamedHsType -> TcM Type
375
376 tc_type ty@(HsTyVar name)
377   = tc_app ty []
378
379 tc_type (HsListTy ty)
380   = tc_type ty  `thenTc` \ tau_ty ->
381     returnTc (mkListTy tau_ty)
382
383 tc_type (HsTupleTy (HsTupCon _ boxity arity) tys)
384   = ASSERT( arity == length tys )
385     tc_types tys        `thenTc` \ tau_tys ->
386     returnTc (mkTupleTy boxity arity tau_tys)
387
388 tc_type (HsFunTy ty1 ty2)
389   = tc_type ty1                 `thenTc` \ tau_ty1 ->
390     tc_type ty2                 `thenTc` \ tau_ty2 ->
391     returnTc (mkFunTy tau_ty1 tau_ty2)
392
393 tc_type (HsNumTy n)
394   = ASSERT(n== 1)
395     returnTc (mkTyConApp genUnitTyCon [])
396
397 tc_type (HsOpTy ty1 op ty2)
398   = tc_type ty1 `thenTc` \ tau_ty1 ->
399     tc_type ty2 `thenTc` \ tau_ty2 ->
400     tc_fun_type op [tau_ty1,tau_ty2]
401
402 tc_type (HsAppTy ty1 ty2) = tc_app ty1 [ty2]
403
404 tc_type (HsPredTy pred)
405   = tc_pred pred        `thenTc` \ pred' ->
406     returnTc (mkPredTy pred')
407
408 tc_type full_ty@(HsForAllTy (Just tv_names) ctxt ty)
409   = let
410         kind_check = kcHsContext ctxt `thenTc_` kcHsType ty
411     in
412     tcHsTyVars tv_names kind_check      $ \ tyvars ->
413     mapTc tc_pred ctxt                  `thenTc` \ theta ->
414     tc_type ty                          `thenTc` \ tau ->
415     returnTc (mkSigmaTy tyvars theta tau)
416
417 tc_types arg_tys = mapTc tc_type arg_tys
418 \end{code}
419
420 Help functions for type applications
421 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
422
423 \begin{code}
424 tc_app :: RenamedHsType -> [RenamedHsType] -> TcM Type
425 tc_app (HsAppTy ty1 ty2) tys
426   = tc_app ty1 (ty2:tys)
427
428 tc_app ty tys
429   = tcAddErrCtxt (appKindCtxt pp_app)   $
430     tc_types tys                        `thenTc` \ arg_tys ->
431     case ty of
432         HsTyVar fun -> tc_fun_type fun arg_tys
433         other       -> tc_type ty               `thenTc` \ fun_ty ->
434                        returnNF_Tc (mkAppTys fun_ty arg_tys)
435   where
436     pp_app = ppr ty <+> sep (map pprParendHsType tys)
437
438 -- (tc_fun_type ty arg_tys) returns (mkAppTys ty arg_tys)
439 -- But not quite; for synonyms it checks the correct arity, and builds a SynTy
440 --      hence the rather strange functionality.
441
442 tc_fun_type name arg_tys
443   = tcLookup name                       `thenTc` \ thing ->
444     case thing of
445         ATyVar tv -> returnTc (mkAppTys (mkTyVarTy tv) arg_tys)
446
447         AGlobal (ATyCon tc)
448                 | isSynTyCon tc ->  returnTc (mkSynTy tc arg_tys)
449                 | otherwise     ->  returnTc (mkTyConApp tc arg_tys)
450
451         other -> failWithTc (wrongThingErr "type constructor" thing name)
452 \end{code}
453
454
455 Contexts
456 ~~~~~~~~
457 \begin{code}
458 tc_pred assn@(HsClassP class_name tys)
459   = tcAddErrCtxt (appKindCtxt (ppr assn))       $
460     tc_types tys                        `thenTc` \ arg_tys ->
461     tcLookupGlobal class_name                   `thenTc` \ thing ->
462     case thing of
463         AClass clas -> returnTc (ClassP clas arg_tys)
464         other       -> failWithTc (wrongThingErr "class" (AGlobal thing) class_name)
465
466 tc_pred assn@(HsIParam name ty)
467   = tcAddErrCtxt (appKindCtxt (ppr assn))       $
468     tc_type ty                                  `thenTc` \ arg_ty ->
469     returnTc (IParam name arg_ty)
470 \end{code}
471
472
473
474 %************************************************************************
475 %*                                                                      *
476 \subsection{Type variables, with knot tying!}
477 %*                                                                      *
478 %************************************************************************
479
480 \begin{code}
481 mkImmutTyVars :: [(Name,Kind)] -> [TyVar]
482 mkImmutTyVars pairs = [mkTyVar name kind | (name, kind) <- pairs]
483
484 mkTyClTyVars :: Kind                    -- Kind of the tycon or class
485              -> [HsTyVarBndr Name]
486              -> [TyVar]
487 mkTyClTyVars kind tyvar_names
488   = mkImmutTyVars tyvars_w_kinds
489   where
490     (tyvars_w_kinds, _) = zipFunTys (hsTyVarNames tyvar_names) kind
491 \end{code}
492
493
494 %************************************************************************
495 %*                                                                      *
496 \subsection{Signatures}
497 %*                                                                      *
498 %************************************************************************
499
500 @tcSigs@ checks the signatures for validity, and returns a list of
501 {\em freshly-instantiated} signatures.  That is, the types are already
502 split up, and have fresh type variables installed.  All non-type-signature
503 "RenamedSigs" are ignored.
504
505 The @TcSigInfo@ contains @TcTypes@ because they are unified with
506 the variable's type, and after that checked to see whether they've
507 been instantiated.
508
509 \begin{code}
510 data TcSigInfo
511   = TySigInfo       
512         Name                    -- N, the Name in corresponding binding
513
514         TcId                    -- *Polymorphic* binder for this value...
515                                 -- Has name = N
516
517         [TcTyVar]               -- tyvars
518         TcThetaType             -- theta
519         TcTauType               -- tau
520
521         TcId                    -- *Monomorphic* binder for this value
522                                 -- Does *not* have name = N
523                                 -- Has type tau
524
525         [Inst]                  -- Empty if theta is null, or
526                                 -- (method mono_id) otherwise
527
528         SrcLoc                  -- Of the signature
529
530 instance Outputable TcSigInfo where
531     ppr (TySigInfo nm id tyvars theta tau _ inst loc) =
532         ppr nm <+> ptext SLIT("::") <+> ppr tyvars <+> ppr theta <+> ptext SLIT("=>") <+> ppr tau
533
534 maybeSig :: [TcSigInfo] -> Name -> Maybe (TcSigInfo)
535         -- Search for a particular signature
536 maybeSig [] name = Nothing
537 maybeSig (sig@(TySigInfo sig_name _ _ _ _ _ _ _) : sigs) name
538   | name == sig_name = Just sig
539   | otherwise        = maybeSig sigs name
540 \end{code}
541
542
543 \begin{code}
544 tcTySig :: RenamedSig -> TcM TcSigInfo
545
546 tcTySig (Sig v ty src_loc)
547  = tcAddSrcLoc src_loc                          $ 
548    tcHsSigType (FunSigCtxt v) ty                `thenTc` \ sigma_tc_ty ->
549    mkTcSig (mkLocalId v sigma_tc_ty) src_loc    `thenNF_Tc` \ sig -> 
550    returnTc sig
551
552 mkTcSig :: TcId -> SrcLoc -> NF_TcM TcSigInfo
553 mkTcSig poly_id src_loc
554   =     -- Instantiate this type
555         -- It's important to do this even though in the error-free case
556         -- we could just split the sigma_tc_ty (since the tyvars don't
557         -- unified with anything).  But in the case of an error, when
558         -- the tyvars *do* get unified with something, we want to carry on
559         -- typechecking the rest of the program with the function bound
560         -- to a pristine type, namely sigma_tc_ty
561    let
562         (tyvars, rho) = tcSplitForAllTys (idType poly_id)
563    in
564    tcInstSigVars tyvars                 `thenNF_Tc` \ tyvars' ->
565         -- Make *signature* type variables
566
567    let
568      tyvar_tys' = mkTyVarTys tyvars'
569      rho' = substTy (mkTopTyVarSubst tyvars tyvar_tys') rho
570         -- mkTopTyVarSubst because the tyvars' are fresh
571
572      (theta', tau') = tcSplitRhoTy rho'
573         -- This splitRhoTy tries hard to make sure that tau' is a type synonym
574         -- wherever possible, which can improve interface files.
575    in
576    newMethodWithGivenTy SignatureOrigin 
577                 poly_id
578                 tyvar_tys'
579                 theta' tau'                     `thenNF_Tc` \ inst ->
580         -- We make a Method even if it's not overloaded; no harm
581         
582    returnNF_Tc (TySigInfo name poly_id tyvars' theta' tau' (instToId inst) [inst] src_loc)
583   where
584     name = idName poly_id
585 \end{code}
586
587
588
589 %************************************************************************
590 %*                                                                      *
591 \subsection{Checking signature type variables}
592 %*                                                                      *
593 %************************************************************************
594
595 @checkSigTyVars@ is used after the type in a type signature has been unified with
596 the actual type found.  It then checks that the type variables of the type signature
597 are
598         (a) Still all type variables
599                 eg matching signature [a] against inferred type [(p,q)]
600                 [then a will be unified to a non-type variable]
601
602         (b) Still all distinct
603                 eg matching signature [(a,b)] against inferred type [(p,p)]
604                 [then a and b will be unified together]
605
606         (c) Not mentioned in the environment
607                 eg the signature for f in this:
608
609                         g x = ... where
610                                         f :: a->[a]
611                                         f y = [x,y]
612
613                 Here, f is forced to be monorphic by the free occurence of x.
614
615         (d) Not (unified with another type variable that is) in scope.
616                 eg f x :: (r->r) = (\y->y) :: forall a. a->r
617             when checking the expression type signature, we find that
618             even though there is nothing in scope whose type mentions r,
619             nevertheless the type signature for the expression isn't right.
620
621             Another example is in a class or instance declaration:
622                 class C a where
623                    op :: forall b. a -> b
624                    op x = x
625             Here, b gets unified with a
626
627 Before doing this, the substitution is applied to the signature type variable.
628
629 We used to have the notion of a "DontBind" type variable, which would
630 only be bound to itself or nothing.  Then points (a) and (b) were 
631 self-checking.  But it gave rise to bogus consequential error messages.
632 For example:
633
634    f = (*)      -- Monomorphic
635
636    g :: Num a => a -> a
637    g x = f x x
638
639 Here, we get a complaint when checking the type signature for g,
640 that g isn't polymorphic enough; but then we get another one when
641 dealing with the (Num x) context arising from f's definition;
642 we try to unify x with Int (to default it), but find that x has already
643 been unified with the DontBind variable "a" from g's signature.
644 This is really a problem with side-effecting unification; we'd like to
645 undo g's effects when its type signature fails, but unification is done
646 by side effect, so we can't (easily).
647
648 So we revert to ordinary type variables for signatures, and try to
649 give a helpful message in checkSigTyVars.
650
651 \begin{code}
652 checkSigTyVars :: [TcTyVar]             -- Universally-quantified type variables in the signature
653                -> TcTyVarSet            -- Tyvars that are free in the type signature
654                                         --      Not necessarily zonked
655                                         --      These should *already* be in the free-in-env set, 
656                                         --      and are used here only to improve the error message
657                -> TcM [TcTyVar]         -- Zonked signature type variables
658
659 checkSigTyVars [] free = returnTc []
660 checkSigTyVars sig_tyvars free_tyvars
661   = zonkTcTyVars sig_tyvars             `thenNF_Tc` \ sig_tys ->
662     tcGetGlobalTyVars                   `thenNF_Tc` \ globals ->
663
664     checkTcM (allDistinctTyVars sig_tys globals)
665              (complain sig_tys globals) `thenTc_`
666
667     returnTc (map (tcGetTyVar "checkSigTyVars") sig_tys)
668
669   where
670     complain sig_tys globals
671       = -- For the in-scope ones, zonk them and construct a map
672         -- from the zonked tyvar to the in-scope one
673         -- If any of the in-scope tyvars zonk to a type, then ignore them;
674         -- that'll be caught later when we back up to their type sig
675         tcGetEnv                                `thenNF_Tc` \ env ->
676         let
677            in_scope_tvs = tcEnvTyVars env
678         in
679         zonkTcTyVars in_scope_tvs               `thenNF_Tc` \ in_scope_tys ->
680         let
681             in_scope_assoc = [ (zonked_tv, in_scope_tv) 
682                              | (z_ty, in_scope_tv) <- in_scope_tys `zip` in_scope_tvs,
683                                Just zonked_tv <- [tcGetTyVar_maybe z_ty]
684                              ]
685             in_scope_env = mkVarEnv in_scope_assoc
686         in
687
688         -- "check" checks each sig tyvar in turn
689         foldlNF_Tc check
690                    (env2, in_scope_env, [])
691                    (tidy_tvs `zip` tidy_tys)    `thenNF_Tc` \ (env3, _, msgs) ->
692
693         failWithTcM (env3, main_msg $$ nest 4 (vcat msgs))
694       where
695         (env1, tidy_tvs) = tidyOpenTyVars emptyTidyEnv sig_tyvars
696         (env2, tidy_tys) = tidyOpenTypes  env1         sig_tys
697
698         main_msg = ptext SLIT("Inferred type is less polymorphic than expected")
699
700         check (tidy_env, acc, msgs) (sig_tyvar,ty)
701                 -- sig_tyvar is from the signature;
702                 -- ty is what you get if you zonk sig_tyvar and then tidy it
703                 --
704                 -- acc maps a zonked type variable back to a signature type variable
705           = case tcGetTyVar_maybe ty of {
706               Nothing ->                        -- Error (a)!
707                         returnNF_Tc (tidy_env, acc, unify_msg sig_tyvar (quotes (ppr ty)) : msgs) ;
708
709               Just tv ->
710
711             case lookupVarEnv acc tv of {
712                 Just sig_tyvar' ->      -- Error (b) or (d)!
713                         returnNF_Tc (tidy_env, acc, unify_msg sig_tyvar thing : msgs)
714                     where
715                         thing = ptext SLIT("another quantified type variable") <+> quotes (ppr sig_tyvar')
716
717               ; Nothing ->
718
719             if tv `elemVarSet` globals  -- Error (c)! Type variable escapes
720                                         -- The least comprehensible, so put it last
721                         -- Game plan: 
722                         --    a) get the local TcIds from the environment,
723                         --       and pass them to find_globals (they might have tv free)
724                         --    b) similarly, find any free_tyvars that mention tv
725             then   tcGetEnv                                                     `thenNF_Tc` \ ve ->
726                    find_globals tv tidy_env  [] (tcEnvTcIds ve)                 `thenNF_Tc` \ (tidy_env1, globs) ->
727                    find_frees   tv tidy_env1 [] (varSetElems free_tyvars)       `thenNF_Tc` \ (tidy_env2, frees) ->
728                    returnNF_Tc (tidy_env2, acc, escape_msg sig_tyvar tv globs frees : msgs)
729
730             else        -- All OK
731             returnNF_Tc (tidy_env, extendVarEnv acc tv sig_tyvar, msgs)
732             }}
733
734 -- find_globals looks at the value environment and finds values
735 -- whose types mention the offending type variable.  It has to be 
736 -- careful to zonk the Id's type first, so it has to be in the monad.
737 -- We must be careful to pass it a zonked type variable, too.
738
739 find_globals :: Var 
740              -> TidyEnv 
741              -> [(Name,Type)] 
742              -> [Id] 
743              -> NF_TcM (TidyEnv,[(Name,Type)])
744
745 find_globals tv tidy_env acc []
746   = returnNF_Tc (tidy_env, acc)
747
748 find_globals tv tidy_env acc (id:ids) 
749   | isEmptyVarSet (idFreeTyVars id)
750   = find_globals tv tidy_env acc ids
751
752   | otherwise
753   = zonkTcType (idType id)      `thenNF_Tc` \ id_ty ->
754     if tv `elemVarSet` tyVarsOfType id_ty then
755         let 
756            (tidy_env', id_ty') = tidyOpenType tidy_env id_ty
757            acc'                = (idName id, id_ty') : acc
758         in
759         find_globals tv tidy_env' acc' ids
760     else
761         find_globals tv tidy_env  acc  ids
762
763 find_frees tv tidy_env acc []
764   = returnNF_Tc (tidy_env, acc)
765 find_frees tv tidy_env acc (ftv:ftvs)
766   = zonkTcTyVar ftv     `thenNF_Tc` \ ty ->
767     if tv `elemVarSet` tyVarsOfType ty then
768         let
769             (tidy_env', ftv') = tidyOpenTyVar tidy_env ftv
770         in
771         find_frees tv tidy_env' (ftv':acc) ftvs
772     else
773         find_frees tv tidy_env  acc        ftvs
774
775
776 escape_msg sig_tv tv globs frees
777   = mk_msg sig_tv <+> ptext SLIT("escapes") $$
778     if not (null globs) then
779         vcat [pp_it <+> ptext SLIT("is mentioned in the environment"),
780               ptext SLIT("The following variables in the environment mention") <+> quotes (ppr tv),
781               nest 2 (vcat_first 10 [ppr name <+> dcolon <+> ppr ty | (name,ty) <- globs])
782         ]
783      else if not (null frees) then
784         vcat [ptext SLIT("It is reachable from the type variable(s)") <+> pprQuotedList frees,
785               nest 2 (ptext SLIT("which") <+> is_are <+> ptext SLIT("free in the signature"))
786         ]
787      else
788         empty   -- Sigh.  It's really hard to give a good error message
789                 -- all the time.   One bad case is an existential pattern match
790   where
791     is_are | isSingleton frees = ptext SLIT("is")
792            | otherwise         = ptext SLIT("are")
793     pp_it | sig_tv /= tv = ptext SLIT("It unifies with") <+> quotes (ppr tv) <> comma <+> ptext SLIT("which")
794           | otherwise    = ptext SLIT("It")
795
796     vcat_first :: Int -> [SDoc] -> SDoc
797     vcat_first n []     = empty
798     vcat_first 0 (x:xs) = text "...others omitted..."
799     vcat_first n (x:xs) = x $$ vcat_first (n-1) xs
800
801 unify_msg tv thing = mk_msg tv <+> ptext SLIT("is unified with") <+> thing
802 mk_msg tv          = ptext SLIT("Quantified type variable") <+> quotes (ppr tv)
803 \end{code}
804
805 These two context are used with checkSigTyVars
806     
807 \begin{code}
808 sigCtxt :: Message -> [TcTyVar] -> TcThetaType -> TcTauType
809         -> TidyEnv -> NF_TcM (TidyEnv, Message)
810 sigCtxt when sig_tyvars sig_theta sig_tau tidy_env
811   = zonkTcType sig_tau          `thenNF_Tc` \ actual_tau ->
812     let
813         (env1, tidy_sig_tyvars)  = tidyOpenTyVars tidy_env sig_tyvars
814         (env2, tidy_sig_rho)     = tidyOpenType env1 (mkRhoTy sig_theta sig_tau)
815         (env3, tidy_actual_tau)  = tidyOpenType env2 actual_tau
816         msg = vcat [ptext SLIT("Signature type:    ") <+> pprType (mkForAllTys tidy_sig_tyvars tidy_sig_rho),
817                     ptext SLIT("Type to generalise:") <+> pprType tidy_actual_tau,
818                     when
819                    ]
820     in
821     returnNF_Tc (env3, msg)
822
823 sigPatCtxt bound_tvs bound_ids tidy_env
824   = returnNF_Tc (env1,
825                  sep [ptext SLIT("When checking a pattern that binds"),
826                       nest 4 (vcat (zipWith ppr_id show_ids tidy_tys))])
827   where
828     show_ids = filter is_interesting bound_ids
829     is_interesting id = any (`elemVarSet` idFreeTyVars id) bound_tvs
830
831     (env1, tidy_tys) = tidyOpenTypes tidy_env (map idType show_ids)
832     ppr_id id ty     = ppr id <+> dcolon <+> ppr ty
833         -- Don't zonk the types so we get the separate, un-unified versions
834 \end{code}
835
836
837 %************************************************************************
838 %*                                                                      *
839 \subsection{Errors and contexts}
840 %*                                                                      *
841 %************************************************************************
842
843 \begin{code}
844 typeKindCtxt :: RenamedHsType -> Message
845 typeKindCtxt ty = sep [ptext SLIT("When checking that"),
846                        nest 2 (quotes (ppr ty)),
847                        ptext SLIT("is a type")]
848
849 appKindCtxt :: SDoc -> Message
850 appKindCtxt pp = ptext SLIT("When checking kinds in") <+> quotes pp
851
852 wrongThingErr expected thing name
853   = pp_thing thing <+> quotes (ppr name) <+> ptext SLIT("used as a") <+> text expected
854   where
855     pp_thing (AGlobal (ATyCon _)) = ptext SLIT("Type constructor")
856     pp_thing (AGlobal (AClass _)) = ptext SLIT("Class")
857     pp_thing (AGlobal (AnId   _)) = ptext SLIT("Identifier")
858     pp_thing (ATyVar _)           = ptext SLIT("Type variable")
859     pp_thing (ATcId _)            = ptext SLIT("Local identifier")
860     pp_thing (AThing _)           = ptext SLIT("Utterly bogus")
861 \end{code}