[project @ 2002-09-09 13:48:01 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, tcHsPred,
8                     UserTypeCtxt(..),
9
10                         -- Kind checking
11                     kcHsTyVar, kcHsTyVars, mkTyClTyVars,
12                     kcHsType, kcHsSigType, kcHsSigTypes, 
13                     kcHsLiftedSigType, kcHsContext,
14                     tcAddScopedTyVars, tcHsTyVars, mkImmutTyVars,
15
16                     TcSigInfo(..), tcTySig, mkTcSig, maybeSig, tcSigPolyId, tcSigMonoId
17                   ) where
18
19 #include "HsVersions.h"
20
21 import HsSyn            ( HsType(..), HsTyVarBndr(..), HsTyOp(..),
22                           Sig(..), HsPred(..), pprParendHsType, HsTupCon(..), hsTyVarNames )
23 import RnHsSyn          ( RenamedHsType, RenamedHsPred, RenamedContext, RenamedSig, extractHsTyVars )
24 import TcHsSyn          ( TcId )
25
26 import TcMonad
27 import TcEnv            ( tcExtendTyVarEnv, tcLookup, tcLookupGlobal,
28                           tcInLocalScope,
29                           TyThing(..), TcTyThing(..), tcExtendKindEnv
30                         )
31 import TcMType          ( newKindVar, zonkKindEnv, tcInstType,
32                           checkValidType, UserTypeCtxt(..), pprUserTypeCtxt
33                         )
34 import TcUnify          ( unifyKind, unifyOpenTypeKind )
35 import TcType           ( Type, Kind, SourceType(..), ThetaType, TyVarDetails(..),
36                           TcTyVar, TcKind, TcThetaType, TcTauType,
37                           mkTyVarTy, mkTyVarTys, mkFunTy, 
38                           zipFunTys, mkForAllTys, mkFunTys, tcEqType, isPredTy,
39                           mkSigmaTy, mkPredTy, mkGenTyConApp, mkTyConApp, mkAppTys, 
40                           liftedTypeKind, unliftedTypeKind, mkArrowKind,
41                           mkArrowKinds, tcSplitFunTy_maybe, tcSplitForAllTys
42                         )
43 import Inst             ( Inst, InstOrigin(..), newMethodWithGivenTy, instToId )
44
45 import Id               ( mkLocalId, idName, idType )
46 import Var              ( TyVar, mkTyVar, tyVarKind )
47 import ErrUtils         ( Message )
48 import TyCon            ( TyCon, tyConKind )
49 import Class            ( classTyCon )
50 import Name             ( Name )
51 import NameSet
52 import Subst            ( deShadowTy )
53 import TysWiredIn       ( mkListTy, mkPArrTy, mkTupleTy, genUnitTyCon )
54 import BasicTypes       ( Boxity(..) )
55 import SrcLoc           ( SrcLoc )
56 import Util             ( lengthIs )
57 import Outputable
58 import List             ( nubBy )
59 \end{code}
60
61
62 %************************************************************************
63 %*                                                                      *
64 \subsection{Checking types}
65 %*                                                                      *
66 %************************************************************************
67
68 Generally speaking we now type-check types in three phases
69
70         1.  Kind check the HsType [kcHsType]
71         2.  Convert from HsType to Type, and hoist the foralls [tcHsType]
72         3.  Check the validity of the resulting type [checkValidType]
73
74 Often these steps are done one after the othe (tcHsSigType).
75 But in mutually recursive groups of type and class decls we do
76         1 kind-check the whole group
77         2 build TyCons/Classes in a knot-tied wa
78         3 check the validity of types in the now-unknotted TyCons/Classes
79
80 \begin{code}
81 tcHsSigType :: UserTypeCtxt -> RenamedHsType -> TcM Type
82   -- Do kind checking, and hoist for-alls to the top
83 tcHsSigType ctxt ty = tcAddErrCtxt (checkTypeCtxt ctxt ty) (
84                         kcTypeType ty           `thenTc_`
85                         tcHsType ty
86                       )                         `thenTc` \ ty' ->
87                       checkValidType ctxt ty'   `thenTc_`
88                       returnTc ty'
89
90 checkTypeCtxt ctxt ty
91   = vcat [ptext SLIT("In the type:") <+> ppr ty,
92           ptext SLIT("While checking") <+> pprUserTypeCtxt ctxt ]
93
94 tcHsType    :: RenamedHsType -> TcM Type
95   -- Don't do kind checking, nor validity checking, 
96   --    but do hoist for-alls to the top
97   -- This is used in type and class decls, where kinding is
98   -- done in advance, and validity checking is done later
99   -- [Validity checking done later because of knot-tying issues.]
100 tcHsType ty = tc_type ty  `thenTc` \ ty' ->  
101               returnTc (hoistForAllTys ty')
102
103 tcHsTheta :: RenamedContext -> TcM ThetaType
104 -- Used when we are expecting a ClassContext (i.e. no implicit params)
105 -- Does not do validity checking, like tcHsType
106 tcHsTheta hs_theta = mapTc tc_pred hs_theta
107
108 -- In interface files the type is already kinded,
109 -- and we definitely don't want to hoist for-alls.
110 -- Otherwise we'll change
111 --      dmfail :: forall m:(*->*) Monad m => forall a:* => String -> m a
112 -- into 
113 --      dmfail :: forall m:(*->*) a:* Monad m => String -> m a
114 -- which definitely isn't right!
115 tcIfaceType ty = tc_type ty
116 \end{code}
117
118
119 %************************************************************************
120 %*                                                                      *
121 \subsection{Kind checking}
122 %*                                                                      *
123 %************************************************************************
124
125 Kind checking
126 ~~~~~~~~~~~~~
127 When we come across the binding site for some type variables, we
128 proceed in two stages
129
130 1. Figure out what kind each tyvar has
131
132 2. Create suitably-kinded tyvars, 
133    extend the envt, 
134    and typecheck the body
135
136 To do step 1, we proceed thus:
137
138 1a. Bind each type variable to a kind variable
139 1b. Apply the kind checker
140 1c. Zonk the resulting kinds
141
142 The kind checker is passed to tcHsTyVars as an argument.  
143
144 For example, when we find
145         (forall a m. m a -> m a)
146 we bind a,m to kind varibles and kind-check (m a -> m a).  This
147 makes a get kind *, and m get kind *->*.  Now we typecheck (m a -> m a)
148 in an environment that binds a and m suitably.
149
150 The kind checker passed to tcHsTyVars needs to look at enough to
151 establish the kind of the tyvar:
152   * For a group of type and class decls, it's just the group, not
153         the rest of the program
154   * For a tyvar bound in a pattern type signature, its the types
155         mentioned in the other type signatures in that bunch of patterns
156   * For a tyvar bound in a RULE, it's the type signatures on other
157         universally quantified variables in the rule
158
159 Note that this may occasionally give surprising results.  For example:
160
161         data T a b = MkT (a b)
162
163 Here we deduce                  a::*->*, b::*.
164 But equally valid would be
165                                 a::(*->*)-> *, b::*->*
166
167 \begin{code}
168 -- tcHsTyVars is used for type variables in type signatures
169 --      e.g. forall a. a->a
170 -- They are immutable, because they scope only over the signature
171 -- They may or may not be explicitly-kinded
172 tcHsTyVars :: [HsTyVarBndr Name] 
173            -> TcM a                             -- The kind checker
174            -> ([TyVar] -> TcM b)
175            -> TcM b
176
177 tcHsTyVars [] kind_check thing_inside = thing_inside []
178         -- A useful short cut for a common case!
179   
180 tcHsTyVars tv_names kind_check thing_inside
181   = kcHsTyVars tv_names                                 `thenNF_Tc` \ tv_names_w_kinds ->
182     tcExtendKindEnv tv_names_w_kinds kind_check         `thenTc_`
183     zonkKindEnv tv_names_w_kinds                        `thenNF_Tc` \ tvs_w_kinds ->
184     let
185         tyvars = mkImmutTyVars tvs_w_kinds
186     in
187     tcExtendTyVarEnv tyvars (thing_inside tyvars)
188
189
190
191 tcAddScopedTyVars :: [RenamedHsType] -> TcM a -> TcM a
192 -- tcAddScopedTyVars is used for scoped type variables
193 -- added by pattern type signatures
194 --      e.g.  \ (x::a) (y::a) -> x+y
195 -- They never have explicit kinds (because this is source-code only)
196 -- They are mutable (because they can get bound to a more specific type)
197
198 -- Find the not-already-in-scope signature type variables,
199 -- kind-check them, and bring them into scope
200 --
201 -- We no longer specify that these type variables must be univerally 
202 -- quantified (lots of email on the subject).  If you want to put that 
203 -- back in, you need to
204 --      a) Do a checkSigTyVars after thing_inside
205 --      b) More insidiously, don't pass in expected_ty, else
206 --         we unify with it too early and checkSigTyVars barfs
207 --         Instead you have to pass in a fresh ty var, and unify
208 --         it with expected_ty afterwards
209 tcAddScopedTyVars [] thing_inside
210   = thing_inside        -- Quick get-out for the empty case
211
212 tcAddScopedTyVars sig_tys thing_inside
213   = tcGetEnv                                    `thenNF_Tc` \ env ->
214     let
215         all_sig_tvs     = foldr (unionNameSets . extractHsTyVars) emptyNameSet sig_tys
216         sig_tvs         = filter not_in_scope (nameSetToList all_sig_tvs)
217         not_in_scope tv = not (tcInLocalScope env tv)
218     in        
219     mapNF_Tc newNamedKindVar sig_tvs                    `thenTc` \ kind_env ->
220     tcExtendKindEnv kind_env (kcHsSigTypes sig_tys)     `thenTc_`
221     zonkKindEnv kind_env                                `thenNF_Tc` \ tvs_w_kinds ->
222     listTc [ tcNewMutTyVar name kind PatSigTv
223            | (name, kind) <- tvs_w_kinds]               `thenNF_Tc` \ tyvars ->
224     tcExtendTyVarEnv tyvars thing_inside
225 \end{code}
226     
227
228 \begin{code}
229 kcHsTyVar  :: HsTyVarBndr name   -> NF_TcM (name, TcKind)
230 kcHsTyVars :: [HsTyVarBndr name] -> NF_TcM [(name, TcKind)]
231
232 kcHsTyVar (UserTyVar name)       = newNamedKindVar name
233 kcHsTyVar (IfaceTyVar name kind) = returnNF_Tc (name, kind)
234
235 kcHsTyVars tvs = mapNF_Tc kcHsTyVar tvs
236
237 newNamedKindVar name = newKindVar       `thenNF_Tc` \ kind ->
238                        returnNF_Tc (name, kind)
239
240 ---------------------------
241 kcLiftedType :: RenamedHsType -> TcM ()
242         -- The type ty must be a *lifted* *type*
243 kcLiftedType ty
244   = kcHsType ty                         `thenTc` \ kind ->
245     tcAddErrCtxt (typeKindCtxt ty)      $
246     unifyKind liftedTypeKind kind
247     
248 ---------------------------
249 kcTypeType :: RenamedHsType -> TcM ()
250         -- The type ty must be a *type*, but it can be lifted or unlifted.
251 kcTypeType ty
252   = kcHsType ty                         `thenTc` \ kind ->
253     tcAddErrCtxt (typeKindCtxt ty)      $
254     unifyOpenTypeKind kind
255
256 ---------------------------
257 kcHsSigType, kcHsLiftedSigType :: RenamedHsType -> TcM ()
258         -- Used for type signatures
259 kcHsSigType       = kcTypeType
260 kcHsSigTypes tys  = mapTc_ kcHsSigType tys
261 kcHsLiftedSigType = kcLiftedType
262
263 ---------------------------
264 kcHsType :: RenamedHsType -> TcM TcKind
265 kcHsType (HsTyVar name)       = kcTyVar name
266
267 kcHsType (HsKindSig ty k)
268   = kcHsType ty                 `thenTc` \ k' ->
269     unifyKind k k'              `thenTc_`
270     returnTc k
271
272 kcHsType (HsListTy ty)
273   = kcLiftedType ty             `thenTc` \ tau_ty ->
274     returnTc liftedTypeKind
275
276 kcHsType (HsPArrTy ty)
277   = kcLiftedType ty             `thenTc` \ tau_ty ->
278     returnTc liftedTypeKind
279
280 kcHsType (HsTupleTy (HsTupCon _ boxity _) tys)
281   = mapTc kcTypeType tys        `thenTc_`
282     returnTc (case boxity of
283                   Boxed   -> liftedTypeKind
284                   Unboxed -> unliftedTypeKind)
285
286 kcHsType (HsFunTy ty1 ty2)
287   = kcTypeType ty1      `thenTc_`
288     kcTypeType ty2      `thenTc_`
289     returnTc liftedTypeKind
290
291 kcHsType (HsOpTy ty1 HsArrow ty2)
292   = kcTypeType ty1      `thenTc_`
293     kcTypeType ty2      `thenTc_`
294     returnTc liftedTypeKind
295
296 kcHsType ty@(HsOpTy ty1 (HsTyOp op) ty2)
297   = kcTyVar op                          `thenTc` \ op_kind ->
298     kcHsType ty1                        `thenTc` \ ty1_kind ->
299     kcHsType ty2                        `thenTc` \ ty2_kind ->
300     tcAddErrCtxt (appKindCtxt (ppr ty)) $
301     kcAppKind op_kind  ty1_kind         `thenTc` \ op_kind' ->
302     kcAppKind op_kind' ty2_kind
303
304 kcHsType (HsParTy ty)           -- Skip parentheses markers
305   = kcHsType ty
306    
307 kcHsType (HsNumTy _)            -- The unit type for generics
308   = returnTc liftedTypeKind
309
310 kcHsType (HsPredTy pred)
311   = kcHsPred pred               `thenTc_`
312     returnTc liftedTypeKind
313
314 kcHsType ty@(HsAppTy ty1 ty2)
315   = kcHsType ty1                        `thenTc` \ tc_kind ->
316     kcHsType ty2                        `thenTc` \ arg_kind ->
317     tcAddErrCtxt (appKindCtxt (ppr ty)) $
318     kcAppKind tc_kind arg_kind
319
320 kcHsType (HsForAllTy (Just tv_names) context ty)
321   = kcHsTyVars tv_names         `thenNF_Tc` \ kind_env ->
322     tcExtendKindEnv kind_env    $
323     kcHsContext context         `thenTc_`
324     kcLiftedType ty             `thenTc_`
325         -- The body of a forall must be of kind *
326         -- In principle, I suppose, we could allow unlifted types,
327         -- but it seems simpler to stick to lifted types for now.
328     returnTc liftedTypeKind
329
330 ---------------------------
331 kcAppKind fun_kind arg_kind
332   = case tcSplitFunTy_maybe fun_kind of 
333         Just (arg_kind', res_kind)
334                 -> unifyKind arg_kind arg_kind' `thenTc_`
335                    returnTc res_kind
336
337         Nothing -> newKindVar                                           `thenNF_Tc` \ res_kind ->
338                    unifyKind fun_kind (mkArrowKind arg_kind res_kind)   `thenTc_`
339                    returnTc res_kind
340
341
342 ---------------------------
343 kc_pred :: RenamedHsPred -> TcM TcKind  -- Does *not* check for a saturated
344                                         -- application (reason: used from TcDeriv)
345 kc_pred pred@(HsIParam name ty)
346   = kcHsType ty
347
348 kc_pred pred@(HsClassP cls tys)
349   = kcClass cls                         `thenTc` \ kind ->
350     mapTc kcHsType tys                  `thenTc` \ arg_kinds ->
351     newKindVar                          `thenNF_Tc` \ kv -> 
352     unifyKind kind (mkArrowKinds arg_kinds kv)  `thenTc_` 
353     returnTc kv
354
355 ---------------------------
356 kcHsContext ctxt = mapTc_ kcHsPred ctxt
357
358 kcHsPred pred           -- Checks that the result is of kind liftedType
359   = tcAddErrCtxt (appKindCtxt (ppr pred))       $
360     kc_pred pred                                `thenTc` \ kind ->
361     unifyKind liftedTypeKind kind               `thenTc_`
362     returnTc ()
363     
364
365  ---------------------------
366 kcTyVar name    -- Could be a tyvar or a tycon
367   = tcLookup name       `thenTc` \ thing ->
368     case thing of 
369         AThing kind         -> returnTc kind
370         ATyVar tv           -> returnTc (tyVarKind tv)
371         AGlobal (ATyCon tc) -> returnTc (tyConKind tc) 
372         other               -> failWithTc (wrongThingErr "type" thing name)
373
374 kcClass cls     -- Must be a class
375   = tcLookup cls                                `thenNF_Tc` \ thing -> 
376     case thing of
377         AThing kind           -> returnTc kind
378         AGlobal (AClass cls)  -> returnTc (tyConKind (classTyCon cls))
379         other                 -> failWithTc (wrongThingErr "class" thing cls)
380 \end{code}
381
382 %************************************************************************
383 %*                                                                      *
384 \subsection{tc_type}
385 %*                                                                      *
386 %************************************************************************
387
388 tc_type, the main work horse
389 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
390
391         -------------------
392         *** BIG WARNING ***
393         -------------------
394
395 tc_type is used to typecheck the types in the RHS of data
396 constructors.  In the case of recursive data types, that means that
397 the type constructors themselves are (partly) black holes.  e.g.
398
399         data T a = MkT a [T a]
400
401 While typechecking the [T a] on the RHS, T itself is not yet fully
402 defined.  That in turn places restrictions on what you can check in
403 tcHsType; if you poke on too much you get a black hole.  I keep
404 forgetting this, hence this warning!
405
406 So tc_type does no validity-checking.  Instead that's all done
407 by TcMType.checkValidType
408
409         --------------------------
410         *** END OF BIG WARNING ***
411         --------------------------
412
413
414 \begin{code}
415 tc_type :: RenamedHsType -> TcM Type
416
417 tc_type ty@(HsTyVar name)
418   = tc_app ty []
419
420 tc_type (HsKindSig ty k)
421   = tc_type ty  -- Kind checking done already
422
423 tc_type (HsListTy ty)
424   = tc_type ty  `thenTc` \ tau_ty ->
425     returnTc (mkListTy tau_ty)
426
427 tc_type (HsPArrTy ty)
428   = tc_type ty  `thenTc` \ tau_ty ->
429     returnTc (mkPArrTy tau_ty)
430
431 tc_type (HsTupleTy (HsTupCon _ boxity arity) tys)
432   = ASSERT( tys `lengthIs` arity )
433     tc_types tys        `thenTc` \ tau_tys ->
434     returnTc (mkTupleTy boxity arity tau_tys)
435
436 tc_type (HsFunTy ty1 ty2)
437   = tc_type ty1                 `thenTc` \ tau_ty1 ->
438     tc_type ty2                 `thenTc` \ tau_ty2 ->
439     returnTc (mkFunTy tau_ty1 tau_ty2)
440
441 tc_type (HsOpTy ty1 HsArrow ty2)
442   = tc_type ty1 `thenTc` \ tau_ty1 ->
443     tc_type ty2 `thenTc` \ tau_ty2 ->
444     returnTc (mkFunTy tau_ty1 tau_ty2)
445
446 tc_type (HsOpTy ty1 (HsTyOp op) ty2)
447   = tc_type ty1 `thenTc` \ tau_ty1 ->
448     tc_type ty2 `thenTc` \ tau_ty2 ->
449     tc_fun_type op [tau_ty1,tau_ty2]
450
451 tc_type (HsParTy ty)            -- Remove the parentheses markers
452   = tc_type ty
453
454 tc_type (HsNumTy n)
455   = ASSERT(n== 1)
456     returnTc (mkTyConApp genUnitTyCon [])
457
458 tc_type (HsAppTy ty1 ty2) = tc_app ty1 [ty2]
459
460 tc_type (HsPredTy pred)
461   = tc_pred pred        `thenTc` \ pred' ->
462     returnTc (mkPredTy pred')
463
464 tc_type full_ty@(HsForAllTy (Just tv_names) ctxt ty)
465   = let
466         kind_check = kcHsContext ctxt `thenTc_` kcHsType ty
467     in
468     tcHsTyVars tv_names kind_check      $ \ tyvars ->
469     mapTc tc_pred ctxt                  `thenTc` \ theta ->
470     tc_type ty                          `thenTc` \ tau ->
471     returnTc (mkSigmaTy tyvars theta tau)
472
473 tc_types arg_tys = mapTc tc_type arg_tys
474 \end{code}
475
476 Help functions for type applications
477 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
478
479 \begin{code}
480 tc_app :: RenamedHsType -> [RenamedHsType] -> TcM Type
481 tc_app (HsAppTy ty1 ty2) tys
482   = tc_app ty1 (ty2:tys)
483
484 tc_app ty tys
485   = tcAddErrCtxt (appKindCtxt pp_app)   $
486     tc_types tys                        `thenTc` \ arg_tys ->
487     case ty of
488         HsTyVar fun -> tc_fun_type fun arg_tys
489         other       -> tc_type ty               `thenTc` \ fun_ty ->
490                        returnNF_Tc (mkAppTys fun_ty arg_tys)
491   where
492     pp_app = ppr ty <+> sep (map pprParendHsType tys)
493
494 -- (tc_fun_type ty arg_tys) returns (mkAppTys ty arg_tys)
495 -- But not quite; for synonyms it checks the correct arity, and builds a SynTy
496 --      hence the rather strange functionality.
497
498 tc_fun_type name arg_tys
499   = tcLookup name                       `thenTc` \ thing ->
500     case thing of
501         ATyVar tv -> returnTc (mkAppTys (mkTyVarTy tv) arg_tys)
502
503         AGlobal (ATyCon tc) -> returnTc (mkGenTyConApp tc arg_tys)
504
505         other -> failWithTc (wrongThingErr "type constructor" thing name)
506 \end{code}
507
508
509 Contexts
510 ~~~~~~~~
511 \begin{code}
512 tcHsPred pred = kc_pred pred `thenTc_`  tc_pred pred
513         -- Is happy with a partial application, e.g. (ST s)
514         -- Used from TcDeriv
515
516 tc_pred assn@(HsClassP class_name tys)
517   = tcAddErrCtxt (appKindCtxt (ppr assn))       $
518     tc_types tys                        `thenTc` \ arg_tys ->
519     tcLookupGlobal class_name                   `thenTc` \ thing ->
520     case thing of
521         AClass clas -> returnTc (ClassP clas arg_tys)
522         other       -> failWithTc (wrongThingErr "class" (AGlobal thing) class_name)
523
524 tc_pred assn@(HsIParam name ty)
525   = tcAddErrCtxt (appKindCtxt (ppr assn))       $
526     tc_type ty                                  `thenTc` \ arg_ty ->
527     returnTc (IParam name arg_ty)
528 \end{code}
529
530
531
532 %************************************************************************
533 %*                                                                      *
534 \subsection{Type variables, with knot tying!}
535 %*                                                                      *
536 %************************************************************************
537
538 \begin{code}
539 mkImmutTyVars :: [(Name,Kind)] -> [TyVar]
540 mkImmutTyVars pairs = [mkTyVar name kind | (name, kind) <- pairs]
541
542 mkTyClTyVars :: Kind                    -- Kind of the tycon or class
543              -> [HsTyVarBndr Name]
544              -> [TyVar]
545 mkTyClTyVars kind tyvar_names
546   = mkImmutTyVars tyvars_w_kinds
547   where
548     (tyvars_w_kinds, _) = zipFunTys (hsTyVarNames tyvar_names) kind
549 \end{code}
550
551
552 %************************************************************************
553 %*                                                                      *
554 \subsection{Signatures}
555 %*                                                                      *
556 %************************************************************************
557
558 @tcSigs@ checks the signatures for validity, and returns a list of
559 {\em freshly-instantiated} signatures.  That is, the types are already
560 split up, and have fresh type variables installed.  All non-type-signature
561 "RenamedSigs" are ignored.
562
563 The @TcSigInfo@ contains @TcTypes@ because they are unified with
564 the variable's type, and after that checked to see whether they've
565 been instantiated.
566
567 \begin{code}
568 data TcSigInfo
569   = TySigInfo       
570         TcId                    -- *Polymorphic* binder for this value...
571                                 -- Has name = N
572
573         [TcTyVar]               -- tyvars
574         TcThetaType             -- theta
575         TcTauType               -- tau
576
577         TcId                    -- *Monomorphic* binder for this value
578                                 -- Does *not* have name = N
579                                 -- Has type tau
580
581         [Inst]                  -- Empty if theta is null, or
582                                 -- (method mono_id) otherwise
583
584         SrcLoc                  -- Of the signature
585
586 instance Outputable TcSigInfo where
587     ppr (TySigInfo id tyvars theta tau _ inst loc) =
588         ppr id <+> ptext SLIT("::") <+> ppr tyvars <+> ppr theta <+> ptext SLIT("=>") <+> ppr tau
589
590 tcSigPolyId :: TcSigInfo -> TcId
591 tcSigPolyId (TySigInfo id _ _ _ _ _ _) = id
592
593 tcSigMonoId :: TcSigInfo -> TcId
594 tcSigMonoId (TySigInfo _ _ _ _ id _ _) = id
595
596 maybeSig :: [TcSigInfo] -> Name -> Maybe (TcSigInfo)
597         -- Search for a particular signature
598 maybeSig [] name = Nothing
599 maybeSig (sig@(TySigInfo sig_id _ _ _ _ _ _) : sigs) name
600   | name == idName sig_id = Just sig
601   | otherwise             = maybeSig sigs name
602 \end{code}
603
604
605 \begin{code}
606 tcTySig :: RenamedSig -> TcM TcSigInfo
607
608 tcTySig (Sig v ty src_loc)
609  = tcAddSrcLoc src_loc                          $ 
610    tcHsSigType (FunSigCtxt v) ty                `thenTc` \ sigma_tc_ty ->
611    mkTcSig (mkLocalId v sigma_tc_ty) src_loc    `thenNF_Tc` \ sig -> 
612    returnTc sig
613
614 mkTcSig :: TcId -> SrcLoc -> NF_TcM TcSigInfo
615 mkTcSig poly_id src_loc
616   =     -- Instantiate this type
617         -- It's important to do this even though in the error-free case
618         -- we could just split the sigma_tc_ty (since the tyvars don't
619         -- unified with anything).  But in the case of an error, when
620         -- the tyvars *do* get unified with something, we want to carry on
621         -- typechecking the rest of the program with the function bound
622         -- to a pristine type, namely sigma_tc_ty
623    tcInstType SigTv (idType poly_id)            `thenNF_Tc` \ (tyvars', theta', tau') ->
624
625    newMethodWithGivenTy SignatureOrigin 
626                         poly_id
627                         (mkTyVarTys tyvars')
628                         theta' tau'             `thenNF_Tc` \ inst ->
629         -- We make a Method even if it's not overloaded; no harm
630         
631    returnNF_Tc (TySigInfo poly_id tyvars' theta' tau' 
632                           (instToId inst) [inst] src_loc)
633 \end{code}
634
635
636 %************************************************************************
637 %*                                                                      *
638 \subsection{Errors and contexts}
639 %*                                                                      *
640 %************************************************************************
641
642
643 \begin{code}
644 hoistForAllTys :: Type -> Type
645 -- Used for user-written type signatures only
646 -- Move all the foralls and constraints to the top
647 -- e.g.  T -> forall a. a        ==>   forall a. T -> a
648 --       T -> (?x::Int) -> Int   ==>   (?x::Int) -> T -> Int
649 --
650 -- Also: eliminate duplicate constraints.  These can show up
651 -- when hoisting constraints, notably implicit parameters.
652 --
653 -- We want to 'look through' type synonyms when doing this
654 -- so it's better done on the Type than the HsType
655
656 hoistForAllTys ty
657   = let
658         no_shadow_ty = deShadowTy ty
659         -- Running over ty with an empty substitution gives it the
660         -- no-shadowing property.  This is important.  For example:
661         --      type Foo r = forall a. a -> r
662         --      foo :: Foo (Foo ())
663         -- Here the hoisting should give
664         --      foo :: forall a a1. a -> a1 -> ()
665         --
666         -- What about type vars that are lexically in scope in the envt?
667         -- We simply rely on them having a different unique to any
668         -- binder in 'ty'.  Otherwise we'd have to slurp the in-scope-tyvars
669         -- out of the envt, which is boring and (I think) not necessary.
670     in
671     case hoist no_shadow_ty of 
672         (tvs, theta, body) -> mkForAllTys tvs (mkFunTys (nubBy tcEqType theta) body)
673                 -- The 'nubBy' eliminates duplicate constraints,
674                 -- notably implicit parameters
675   where
676     hoist ty
677         | (tvs1, body_ty) <- tcSplitForAllTys ty,
678           not (null tvs1)
679         = case hoist body_ty of
680                 (tvs2,theta,tau) -> (tvs1 ++ tvs2, theta, tau)
681
682         | Just (arg, res) <- tcSplitFunTy_maybe ty
683         = let
684               arg' = hoistForAllTys arg -- Don't forget to apply hoist recursively
685           in                            -- to the argument type
686           if (isPredTy arg') then
687             case hoist res of
688                 (tvs,theta,tau) -> (tvs, arg':theta, tau)
689           else
690              case hoist res of
691                 (tvs,theta,tau) -> (tvs, theta, mkFunTy arg' tau)
692
693         | otherwise = ([], [], ty)
694 \end{code}
695
696
697 %************************************************************************
698 %*                                                                      *
699 \subsection{Errors and contexts}
700 %*                                                                      *
701 %************************************************************************
702
703 \begin{code}
704 typeKindCtxt :: RenamedHsType -> Message
705 typeKindCtxt ty = sep [ptext SLIT("When checking that"),
706                        nest 2 (quotes (ppr ty)),
707                        ptext SLIT("is a type")]
708
709 appKindCtxt :: SDoc -> Message
710 appKindCtxt pp = ptext SLIT("When checking kinds in") <+> quotes pp
711
712 wrongThingErr expected thing name
713   = pp_thing thing <+> quotes (ppr name) <+> ptext SLIT("used as a") <+> text expected
714   where
715     pp_thing (AGlobal (ATyCon _)) = ptext SLIT("Type constructor")
716     pp_thing (AGlobal (AClass _)) = ptext SLIT("Class")
717     pp_thing (AGlobal (AnId   _)) = ptext SLIT("Identifier")
718     pp_thing (ATyVar _)           = ptext SLIT("Type variable")
719     pp_thing (ATcId _)            = ptext SLIT("Local identifier")
720     pp_thing (AThing _)           = ptext SLIT("Utterly bogus")
721 \end{code}