ebb97b308195fb3920079c9eb3a8f875d44b5eba
[ghc-hetmet.git] / ghc / compiler / typecheck / TcHsType.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 TcHsType (
8         tcHsSigType, tcHsDeriv,
9         UserTypeCtxt(..), 
10
11                 -- Kind checking
12         kcHsTyVars, kcHsSigType, kcHsLiftedSigType, 
13         kcCheckHsType, kcHsContext, kcHsType, 
14         
15                 -- Typechecking kinded types
16         tcHsKindedContext, tcHsKindedType, tcHsBangType,
17         tcTyVarBndrs, dsHsType, tcLHsConSig, tcDataKindSig,
18
19         tcHsPatSigType, tcAddLetBoundTyVars,
20         
21         TcSigInfo(..), TcSigFun, lookupSig 
22    ) where
23
24 #include "HsVersions.h"
25
26 import HsSyn            ( HsType(..), LHsType, HsTyVarBndr(..), LHsTyVarBndr, HsBang,
27                           LHsContext, HsPred(..), LHsPred, LHsBinds,
28                           getBangStrictness, collectSigTysFromHsBinds )
29 import RnHsSyn          ( extractHsTyVars )
30 import TcRnMonad
31 import TcEnv            ( tcExtendTyVarEnv, tcExtendKindEnv, 
32                           tcLookup, tcLookupClass, tcLookupTyCon,
33                           TyThing(..), getInLocalScope, wrongThingErr
34                         )
35 import TcMType          ( newKindVar, newMetaTyVar, zonkTcKindToKind, 
36                           checkValidType, UserTypeCtxt(..), pprHsSigCtxt
37                         )
38 import TcUnify          ( unifyFunKind, checkExpectedKind )
39 import TcIface          ( checkWiredInTyCon )
40 import TcType           ( Type, PredType(..), ThetaType, 
41                           MetaDetails(Flexi), hoistForAllTys,
42                           TcType, TcTyVar, TcKind, TcThetaType, TcTauType,
43                           mkFunTy, mkSigmaTy, mkPredTy, mkGenTyConApp, 
44                           mkTyConApp, mkAppTys, typeKind )
45 import Kind             ( Kind, isLiftedTypeKind, liftedTypeKind, ubxTupleKind, 
46                           openTypeKind, argTypeKind, splitKindFunTys )
47 import Id               ( idName )
48 import Var              ( TyVar, mkTyVar )
49 import TyCon            ( TyCon, tyConKind )
50 import Class            ( Class, classTyCon )
51 import Name             ( Name, mkInternalName )
52 import OccName          ( mkOccName, tvName )
53 import NameSet
54 import PrelNames        ( genUnitTyConName )
55 import TysWiredIn       ( mkListTy, listTyCon, mkPArrTy, parrTyCon, tupleTyCon )
56 import Bag              ( bagToList )
57 import BasicTypes       ( Boxity(..) )
58 import SrcLoc           ( Located(..), unLoc, noLoc, srcSpanStart )
59 import UniqSupply       ( uniqsFromSupply )
60 import Outputable
61 \end{code}
62
63
64         ----------------------------
65                 General notes
66         ----------------------------
67
68 Generally speaking we now type-check types in three phases
69
70   1.  kcHsType: kind check the HsType
71         *includes* performing any TH type splices;
72         so it returns a translated, and kind-annotated, type
73
74   2.  dsHsType: convert from HsType to Type:
75         perform zonking
76         expand type synonyms [mkGenTyApps]
77         hoist the foralls [tcHsType]
78
79   3.  checkValidType: check the validity of the resulting type
80
81 Often these steps are done one after the other (tcHsSigType).
82 But in mutually recursive groups of type and class decls we do
83         1 kind-check the whole group
84         2 build TyCons/Classes in a knot-tied way
85         3 check the validity of types in the now-unknotted TyCons/Classes
86
87 For example, when we find
88         (forall a m. m a -> m a)
89 we bind a,m to kind varibles and kind-check (m a -> m a).  This makes
90 a get kind *, and m get kind *->*.  Now we typecheck (m a -> m a) in
91 an environment that binds a and m suitably.
92
93 The kind checker passed to tcHsTyVars needs to look at enough to
94 establish the kind of the tyvar:
95   * For a group of type and class decls, it's just the group, not
96         the rest of the program
97   * For a tyvar bound in a pattern type signature, its the types
98         mentioned in the other type signatures in that bunch of patterns
99   * For a tyvar bound in a RULE, it's the type signatures on other
100         universally quantified variables in the rule
101
102 Note that this may occasionally give surprising results.  For example:
103
104         data T a b = MkT (a b)
105
106 Here we deduce                  a::*->*,       b::*
107 But equally valid would be      a::(*->*)-> *, b::*->*
108
109
110 Validity checking
111 ~~~~~~~~~~~~~~~~~
112 Some of the validity check could in principle be done by the kind checker, 
113 but not all:
114
115 - During desugaring, we normalise by expanding type synonyms.  Only
116   after this step can we check things like type-synonym saturation
117   e.g.  type T k = k Int
118         type S a = a
119   Then (T S) is ok, because T is saturated; (T S) expands to (S Int);
120   and then S is saturated.  This is a GHC extension.
121
122 - Similarly, also a GHC extension, we look through synonyms before complaining
123   about the form of a class or instance declaration
124
125 - Ambiguity checks involve functional dependencies, and it's easier to wait
126   until knots have been resolved before poking into them
127
128 Also, in a mutually recursive group of types, we can't look at the TyCon until we've
129 finished building the loop.  So to keep things simple, we postpone most validity
130 checking until step (3).
131
132 Knot tying
133 ~~~~~~~~~~
134 During step (1) we might fault in a TyCon defined in another module, and it might
135 (via a loop) refer back to a TyCon defined in this module. So when we tie a big
136 knot around type declarations with ARecThing, so that the fault-in code can get
137 the TyCon being defined.
138
139
140 %************************************************************************
141 %*                                                                      *
142 \subsection{Checking types}
143 %*                                                                      *
144 %************************************************************************
145
146 \begin{code}
147 tcHsSigType :: UserTypeCtxt -> LHsType Name -> TcM Type
148   -- Do kind checking, and hoist for-alls to the top
149   -- NB: it's important that the foralls that come from the top-level
150   --     HsForAllTy in hs_ty occur *first* in the returned type.
151   --     See Note [Scoped] with TcSigInfo
152 tcHsSigType ctxt hs_ty 
153   = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
154     do  { kinded_ty <- kcTypeType hs_ty
155         ; ty <- tcHsKindedType kinded_ty
156         ; checkValidType ctxt ty        
157         ; returnM ty }
158
159 -- Used for the deriving(...) items
160 tcHsDeriv :: LHsType Name -> TcM ([TyVar], Class, [Type])
161 tcHsDeriv = addLocM (tc_hs_deriv [])
162
163 tc_hs_deriv tv_names (HsPredTy (HsClassP cls_name hs_tys))
164   = kcHsTyVars tv_names                 $ \ tv_names' ->
165     do  { cls_kind <- kcClass cls_name
166         ; (tys, res_kind) <- kcApps cls_kind (ppr cls_name) hs_tys
167         ; tcTyVarBndrs tv_names'        $ \ tyvars ->
168     do  { arg_tys <- dsHsTypes tys
169         ; cls <- tcLookupClass cls_name
170         ; return (tyvars, cls, arg_tys) }}
171
172 tc_hs_deriv tv_names1 (HsForAllTy _ tv_names2 (L _ []) (L _ ty))
173   =     -- Funny newtype deriving form
174         --      forall a. C [a]
175         -- where C has arity 2.  Hence can't use regular functions
176     tc_hs_deriv (tv_names1 ++ tv_names2) ty
177
178 tc_hs_deriv _ other
179   = failWithTc (ptext SLIT("Illegal deriving item") <+> ppr other)
180 \end{code}
181
182         These functions are used during knot-tying in
183         type and class declarations, when we have to
184         separate kind-checking, desugaring, and validity checking
185
186 \begin{code}
187 kcHsSigType, kcHsLiftedSigType :: LHsType Name -> TcM (LHsType Name)
188         -- Used for type signatures
189 kcHsSigType ty       = kcTypeType ty
190 kcHsLiftedSigType ty = kcLiftedType ty
191
192 tcHsKindedType :: LHsType Name -> TcM Type
193   -- Don't do kind checking, nor validity checking, 
194   --    but do hoist for-alls to the top
195   -- This is used in type and class decls, where kinding is
196   -- done in advance, and validity checking is done later
197   -- [Validity checking done later because of knot-tying issues.]
198 tcHsKindedType hs_ty 
199   = do  { ty <- dsHsType hs_ty
200         ; return (hoistForAllTys ty) }
201
202 tcHsBangType :: LHsType Name -> TcM Type
203 -- Permit a bang, but discard it
204 tcHsBangType (L span (HsBangTy b ty)) = tcHsKindedType ty
205 tcHsBangType ty                       = tcHsKindedType ty
206
207 tcHsKindedContext :: LHsContext Name -> TcM ThetaType
208 -- Used when we are expecting a ClassContext (i.e. no implicit params)
209 -- Does not do validity checking, like tcHsKindedType
210 tcHsKindedContext hs_theta = addLocM (mappM dsHsLPred) hs_theta
211 \end{code}
212
213
214 %************************************************************************
215 %*                                                                      *
216                 The main kind checker: kcHsType
217 %*                                                                      *
218 %************************************************************************
219         
220         First a couple of simple wrappers for kcHsType
221
222 \begin{code}
223 ---------------------------
224 kcLiftedType :: LHsType Name -> TcM (LHsType Name)
225 -- The type ty must be a *lifted* *type*
226 kcLiftedType ty = kcCheckHsType ty liftedTypeKind
227     
228 ---------------------------
229 kcTypeType :: LHsType Name -> TcM (LHsType Name)
230 -- The type ty must be a *type*, but it can be lifted or 
231 -- unlifted or an unboxed tuple.
232 kcTypeType ty = kcCheckHsType ty openTypeKind
233
234 ---------------------------
235 kcCheckHsType :: LHsType Name -> TcKind -> TcM (LHsType Name)
236 -- Check that the type has the specified kind
237 -- Be sure to use checkExpectedKind, rather than simply unifying 
238 -- with OpenTypeKind, because it gives better error messages
239 kcCheckHsType (L span ty) exp_kind 
240   = setSrcSpan span                             $
241     do  { (ty', act_kind) <- addErrCtxt (typeCtxt ty) $
242                              kc_hs_type ty
243                 -- Add the context round the inner check only
244                 -- because checkExpectedKind already mentions
245                 -- 'ty' by name in any error message
246         ; checkExpectedKind ty act_kind exp_kind
247         ; return (L span ty') }
248 \end{code}
249
250         Here comes the main function
251
252 \begin{code}
253 kcHsType :: LHsType Name -> TcM (LHsType Name, TcKind)
254 kcHsType ty = wrapLocFstM kc_hs_type ty
255 -- kcHsType *returns* the kind of the type, rather than taking an expected
256 -- kind as argument as tcExpr does.  
257 -- Reasons: 
258 --      (a) the kind of (->) is
259 --              forall bx1 bx2. Type bx1 -> Type bx2 -> Type Boxed
260 --          so we'd need to generate huge numbers of bx variables.
261 --      (b) kinds are so simple that the error messages are fine
262 --
263 -- The translated type has explicitly-kinded type-variable binders
264
265 kc_hs_type (HsParTy ty)
266  = kcHsType ty          `thenM` \ (ty', kind) ->
267    returnM (HsParTy ty', kind)
268
269 kc_hs_type (HsTyVar name)
270   = kcTyVar name        `thenM` \ kind ->
271     returnM (HsTyVar name, kind)
272
273 kc_hs_type (HsListTy ty) 
274   = kcLiftedType ty                     `thenM` \ ty' ->
275     returnM (HsListTy ty', liftedTypeKind)
276
277 kc_hs_type (HsPArrTy ty)
278   = kcLiftedType ty                     `thenM` \ ty' ->
279     returnM (HsPArrTy ty', liftedTypeKind)
280
281 kc_hs_type (HsNumTy n)
282    = returnM (HsNumTy n, liftedTypeKind)
283
284 kc_hs_type (HsKindSig ty k) 
285   = kcCheckHsType ty k  `thenM` \ ty' ->
286     returnM (HsKindSig ty' k, k)
287
288 kc_hs_type (HsTupleTy Boxed tys)
289   = mappM kcLiftedType tys      `thenM` \ tys' ->
290     returnM (HsTupleTy Boxed tys', liftedTypeKind)
291
292 kc_hs_type (HsTupleTy Unboxed tys)
293   = mappM kcTypeType tys        `thenM` \ tys' ->
294     returnM (HsTupleTy Unboxed tys', ubxTupleKind)
295
296 kc_hs_type (HsFunTy ty1 ty2)
297   = kcCheckHsType ty1 argTypeKind       `thenM` \ ty1' ->
298     kcTypeType ty2                      `thenM` \ ty2' ->
299     returnM (HsFunTy ty1' ty2', liftedTypeKind)
300
301 kc_hs_type ty@(HsOpTy ty1 op ty2)
302   = addLocM kcTyVar op                  `thenM` \ op_kind ->
303     kcApps op_kind (ppr op) [ty1,ty2]   `thenM` \ ([ty1',ty2'], res_kind) ->
304     returnM (HsOpTy ty1' op ty2', res_kind)
305
306 kc_hs_type ty@(HsAppTy ty1 ty2)
307   = kcHsType fun_ty                       `thenM` \ (fun_ty', fun_kind) ->
308     kcApps fun_kind (ppr fun_ty) arg_tys  `thenM` \ ((arg_ty':arg_tys'), res_kind) ->
309     returnM (foldl mk_app (HsAppTy fun_ty' arg_ty') arg_tys', res_kind)
310   where
311     (fun_ty, arg_tys) = split ty1 [ty2]
312     split (L _ (HsAppTy f a)) as = split f (a:as)
313     split f                   as = (f,as)
314     mk_app fun arg = HsAppTy (noLoc fun) arg    -- Add noLocs for inner nodes of
315                                                 -- the application; they are never used
316     
317 kc_hs_type (HsPredTy pred)
318   = kcHsPred pred               `thenM` \ pred' ->
319     returnM (HsPredTy pred', liftedTypeKind)
320
321 kc_hs_type (HsForAllTy exp tv_names context ty)
322   = kcHsTyVars tv_names         $ \ tv_names' ->
323     kcHsContext context         `thenM` \ ctxt' ->
324     kcLiftedType ty             `thenM` \ ty' ->
325         -- The body of a forall is usually a type, but in principle
326         -- there's no reason to prohibit *unlifted* types.
327         -- In fact, GHC can itself construct a function with an
328         -- unboxed tuple inside a for-all (via CPR analyis; see 
329         -- typecheck/should_compile/tc170)
330         --
331         -- Still, that's only for internal interfaces, which aren't
332         -- kind-checked, so we only allow liftedTypeKind here
333     returnM (HsForAllTy exp tv_names' ctxt' ty', liftedTypeKind)
334
335 kc_hs_type (HsBangTy b ty)
336   = do { (ty', kind) <- kcHsType ty
337        ; return (HsBangTy b ty', kind) }
338
339 kc_hs_type ty@(HsSpliceTy _)
340   = failWithTc (ptext SLIT("Unexpected type splice:") <+> ppr ty)
341
342
343 ---------------------------
344 kcApps :: TcKind                        -- Function kind
345        -> SDoc                          -- Function 
346        -> [LHsType Name]                -- Arg types
347        -> TcM ([LHsType Name], TcKind)  -- Kind-checked args
348 kcApps fun_kind ppr_fun args
349   = split_fk fun_kind (length args)     `thenM` \ (arg_kinds, res_kind) ->
350     zipWithM kc_arg args arg_kinds      `thenM` \ args' ->
351     returnM (args', res_kind)
352   where
353     split_fk fk 0 = returnM ([], fk)
354     split_fk fk n = unifyFunKind fk     `thenM` \ mb_fk ->
355                     case mb_fk of 
356                         Nothing       -> failWithTc too_many_args 
357                         Just (ak,fk') -> split_fk fk' (n-1)     `thenM` \ (aks, rk) ->
358                                          returnM (ak:aks, rk)
359
360     kc_arg arg arg_kind = kcCheckHsType arg arg_kind
361
362     too_many_args = ptext SLIT("Kind error:") <+> quotes ppr_fun <+>
363                     ptext SLIT("is applied to too many type arguments")
364
365 ---------------------------
366 kcHsContext :: LHsContext Name -> TcM (LHsContext Name)
367 kcHsContext ctxt = wrapLocM (mappM kcHsLPred) ctxt
368
369 kcHsLPred :: LHsPred Name -> TcM (LHsPred Name)
370 kcHsLPred = wrapLocM kcHsPred
371
372 kcHsPred :: HsPred Name -> TcM (HsPred Name)
373 kcHsPred pred   -- Checks that the result is of kind liftedType
374   = kc_pred pred                                `thenM` \ (pred', kind) ->
375     checkExpectedKind pred kind liftedTypeKind  `thenM_` 
376     returnM pred'
377     
378 ---------------------------
379 kc_pred :: HsPred Name -> TcM (HsPred Name, TcKind)     
380         -- Does *not* check for a saturated
381         -- application (reason: used from TcDeriv)
382 kc_pred pred@(HsIParam name ty)
383   = kcHsType ty         `thenM` \ (ty', kind) ->
384     returnM (HsIParam name ty', kind)
385
386 kc_pred pred@(HsClassP cls tys)
387   = kcClass cls                 `thenM` \ kind ->
388     kcApps kind (ppr cls) tys   `thenM` \ (tys', res_kind) ->
389     returnM (HsClassP cls tys', res_kind)
390
391 ---------------------------
392 kcTyVar :: Name -> TcM TcKind
393 kcTyVar name    -- Could be a tyvar or a tycon
394   = traceTc (text "lk1" <+> ppr name)   `thenM_`
395     tcLookup name       `thenM` \ thing ->
396     traceTc (text "lk2" <+> ppr name <+> ppr thing)     `thenM_`
397     case thing of 
398         ATyVar _ ty             -> returnM (typeKind ty)
399         AThing kind             -> returnM kind
400         AGlobal (ATyCon tc)     -> returnM (tyConKind tc) 
401         other                   -> wrongThingErr "type" thing name
402
403 kcClass :: Name -> TcM TcKind
404 kcClass cls     -- Must be a class
405   = tcLookup cls                                `thenM` \ thing -> 
406     case thing of
407         AThing kind             -> returnM kind
408         AGlobal (AClass cls)    -> returnM (tyConKind (classTyCon cls))
409         other                   -> wrongThingErr "class" thing cls
410 \end{code}
411
412
413 %************************************************************************
414 %*                                                                      *
415                 Desugaring
416 %*                                                                      *
417 %************************************************************************
418
419 The type desugarer
420
421         * Transforms from HsType to Type
422         * Zonks any kinds
423
424 It cannot fail, and does no validity checking, except for 
425 structural matters, such as
426         (a) spurious ! annotations.
427         (b) a class used as a type
428
429 \begin{code}
430 dsHsType :: LHsType Name -> TcM Type
431 -- All HsTyVarBndrs in the intput type are kind-annotated
432 dsHsType ty = ds_type (unLoc ty)
433
434 ds_type ty@(HsTyVar name)
435   = ds_app ty []
436
437 ds_type (HsParTy ty)            -- Remove the parentheses markers
438   = dsHsType ty
439
440 ds_type ty@(HsBangTy _ _)       -- No bangs should be here
441   = failWithTc (ptext SLIT("Unexpected strictness annotation:") <+> ppr ty)
442
443 ds_type (HsKindSig ty k)
444   = dsHsType ty -- Kind checking done already
445
446 ds_type (HsListTy ty)
447   = dsHsType ty                 `thenM` \ tau_ty ->
448     checkWiredInTyCon listTyCon `thenM_`
449     returnM (mkListTy tau_ty)
450
451 ds_type (HsPArrTy ty)
452   = dsHsType ty                 `thenM` \ tau_ty ->
453     checkWiredInTyCon parrTyCon `thenM_`
454     returnM (mkPArrTy tau_ty)
455
456 ds_type (HsTupleTy boxity tys)
457   = dsHsTypes tys               `thenM` \ tau_tys ->
458     checkWiredInTyCon tycon     `thenM_`
459     returnM (mkTyConApp tycon tau_tys)
460   where
461     tycon = tupleTyCon boxity (length tys)
462
463 ds_type (HsFunTy ty1 ty2)
464   = dsHsType ty1                        `thenM` \ tau_ty1 ->
465     dsHsType ty2                        `thenM` \ tau_ty2 ->
466     returnM (mkFunTy tau_ty1 tau_ty2)
467
468 ds_type (HsOpTy ty1 (L span op) ty2)
469   = dsHsType ty1                `thenM` \ tau_ty1 ->
470     dsHsType ty2                `thenM` \ tau_ty2 ->
471     setSrcSpan span (ds_var_app op [tau_ty1,tau_ty2])
472
473 ds_type (HsNumTy n)
474   = ASSERT(n==1)
475     tcLookupTyCon genUnitTyConName      `thenM` \ tc ->
476     returnM (mkTyConApp tc [])
477
478 ds_type ty@(HsAppTy _ _)
479   = ds_app ty []
480
481 ds_type (HsPredTy pred)
482   = dsHsPred pred       `thenM` \ pred' ->
483     returnM (mkPredTy pred')
484
485 ds_type full_ty@(HsForAllTy exp tv_names ctxt ty)
486   = tcTyVarBndrs tv_names               $ \ tyvars ->
487     mappM dsHsLPred (unLoc ctxt)        `thenM` \ theta ->
488     dsHsType ty                         `thenM` \ tau ->
489     returnM (mkSigmaTy tyvars theta tau)
490
491 dsHsTypes arg_tys = mappM dsHsType arg_tys
492 \end{code}
493
494 Help functions for type applications
495 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
496
497 \begin{code}
498 ds_app :: HsType Name -> [LHsType Name] -> TcM Type
499 ds_app (HsAppTy ty1 ty2) tys
500   = ds_app (unLoc ty1) (ty2:tys)
501
502 ds_app ty tys
503   = dsHsTypes tys                       `thenM` \ arg_tys ->
504     case ty of
505         HsTyVar fun -> ds_var_app fun arg_tys
506         other       -> ds_type ty               `thenM` \ fun_ty ->
507                        returnM (mkAppTys fun_ty arg_tys)
508
509 ds_var_app :: Name -> [Type] -> TcM Type
510 ds_var_app name arg_tys 
511  = tcLookup name                        `thenM` \ thing ->
512     case thing of
513         ATyVar _ ty         -> returnM (mkAppTys ty arg_tys)
514         AGlobal (ATyCon tc) -> returnM (mkGenTyConApp tc arg_tys)
515         other               -> wrongThingErr "type" thing name
516 \end{code}
517
518
519 Contexts
520 ~~~~~~~~
521
522 \begin{code}
523 dsHsLPred :: LHsPred Name -> TcM PredType
524 dsHsLPred pred = dsHsPred (unLoc pred)
525
526 dsHsPred pred@(HsClassP class_name tys)
527   = dsHsTypes tys                       `thenM` \ arg_tys ->
528     tcLookupClass class_name            `thenM` \ clas ->
529     returnM (ClassP clas arg_tys)
530
531 dsHsPred (HsIParam name ty)
532   = dsHsType ty                                 `thenM` \ arg_ty ->
533     returnM (IParam name arg_ty)
534 \end{code}
535
536 GADT constructor signatures
537
538 \begin{code}
539 tcLHsConSig :: LHsType Name 
540             -> TcM ([TcTyVar], TcThetaType, 
541                     [HsBang], [TcType],
542                     TyCon, [TcType])
543 -- Take apart the type signature for a data constructor
544 -- The difference is that there can be bangs at the top of
545 -- the argument types, and kind-checking is the right place to check
546 tcLHsConSig sig@(L span (HsForAllTy exp tv_names ctxt ty))
547   = setSrcSpan span             $
548     addErrCtxt (gadtSigCtxt sig) $
549     tcTyVarBndrs tv_names       $ \ tyvars ->
550     do  { theta <- mappM dsHsLPred (unLoc ctxt)
551         ; (bangs, arg_tys, tc, res_tys) <- tc_con_sig_tau ty
552         ; return (tyvars, theta, bangs, arg_tys, tc, res_tys) }
553 tcLHsConSig ty 
554   = do  { (bangs, arg_tys, tc, res_tys) <- tc_con_sig_tau ty
555         ; return ([], [], bangs, arg_tys, tc, res_tys) }
556
557 --------
558 tc_con_sig_tau (L _ (HsFunTy arg ty))
559   = do  { (bangs, arg_tys, tc, res_tys) <- tc_con_sig_tau ty
560         ; arg_ty <- tcHsBangType arg
561         ; return (getBangStrictness arg : bangs, 
562                   arg_ty : arg_tys, tc, res_tys) }
563
564 tc_con_sig_tau ty
565   = do  { (tc, res_tys) <- tc_con_res ty []
566         ; return ([], [], tc, res_tys) }
567
568 --------
569 tc_con_res (L _ (HsAppTy fun res_ty)) res_tys
570   = do  { res_ty' <- dsHsType res_ty
571         ; tc_con_res fun (res_ty' : res_tys) }
572
573 tc_con_res ty@(L _ (HsTyVar name)) res_tys
574   = do  { thing <- tcLookup name
575         ; case thing of
576             AGlobal (ATyCon tc) -> return (tc, res_tys)
577             other -> failWithTc (badGadtDecl ty)
578         }
579
580 tc_con_res ty _ = failWithTc (badGadtDecl ty)
581
582 gadtSigCtxt ty
583   = hang (ptext SLIT("In the signature of a data constructor:"))
584        2 (ppr ty)
585 badGadtDecl ty
586   = hang (ptext SLIT("Malformed constructor signature:"))
587        2 (ppr ty)
588
589 typeCtxt ty = ptext SLIT("In the type") <+> quotes (ppr ty)
590 \end{code}
591
592 %************************************************************************
593 %*                                                                      *
594                 Type-variable binders
595 %*                                                                      *
596 %************************************************************************
597
598
599 \begin{code}
600 kcHsTyVars :: [LHsTyVarBndr Name] 
601            -> ([LHsTyVarBndr Name] -> TcM r)    -- These binders are kind-annotated
602                                                 -- They scope over the thing inside
603            -> TcM r
604 kcHsTyVars tvs thing_inside 
605   = mappM (wrapLocM kcHsTyVar) tvs      `thenM` \ bndrs ->
606     tcExtendKindEnv [(n,k) | L _ (KindedTyVar n k) <- bndrs]
607                     (thing_inside bndrs)
608
609 kcHsTyVar :: HsTyVarBndr Name -> TcM (HsTyVarBndr Name)
610         -- Return a *kind-annotated* binder, and a tyvar with a mutable kind in it      
611 kcHsTyVar (UserTyVar name)        = newKindVar  `thenM` \ kind ->
612                                     returnM (KindedTyVar name kind)
613 kcHsTyVar (KindedTyVar name kind) = returnM (KindedTyVar name kind)
614
615 ------------------
616 tcTyVarBndrs :: [LHsTyVarBndr Name]     -- Kind-annotated binders, which need kind-zonking
617              -> ([TyVar] -> TcM r)
618              -> TcM r
619 -- Used when type-checking types/classes/type-decls
620 -- Brings into scope immutable TyVars, not mutable ones that require later zonking
621 tcTyVarBndrs bndrs thing_inside
622   = mapM (zonk . unLoc) bndrs   `thenM` \ tyvars ->
623     tcExtendTyVarEnv tyvars (thing_inside tyvars)
624   where
625     zonk (KindedTyVar name kind) = zonkTcKindToKind kind        `thenM` \ kind' ->
626                                    returnM (mkTyVar name kind')
627     zonk (UserTyVar name) = pprTrace "Un-kinded tyvar" (ppr name) $
628                             returnM (mkTyVar name liftedTypeKind)
629
630 -----------------------------------
631 tcDataKindSig :: Maybe Kind -> TcM [TyVar]
632 -- GADT decls can have a (perhpas partial) kind signature
633 --      e.g.  data T :: * -> * -> * where ...
634 -- This function makes up suitable (kinded) type variables for 
635 -- the argument kinds, and checks that the result kind is indeed *
636 tcDataKindSig Nothing = return []
637 tcDataKindSig (Just kind)
638   = do  { checkTc (isLiftedTypeKind res_kind) (badKindSig kind)
639         ; span <- getSrcSpanM
640         ; us   <- newUniqueSupply 
641         ; let loc   = srcSpanStart span
642               uniqs = uniqsFromSupply us
643         ; return [ mk_tv loc uniq str kind 
644                  | ((kind, str), uniq) <- arg_kinds `zip` names `zip` uniqs ] }
645   where
646     (arg_kinds, res_kind) = splitKindFunTys kind
647     mk_tv loc uniq str kind = mkTyVar name kind
648         where
649            name = mkInternalName uniq occ loc
650            occ  = mkOccName tvName str
651
652     names :: [String]   -- a,b,c...aa,ab,ac etc
653     names = [ c:cs | cs <- "" : names, c <- ['a'..'z'] ] 
654
655 badKindSig :: Kind -> SDoc
656 badKindSig kind 
657  = hang (ptext SLIT("Kind signature on data type declaration has non-* return kind"))
658         2 (ppr kind)
659 \end{code}
660
661
662 %************************************************************************
663 %*                                                                      *
664                 Scoped type variables
665 %*                                                                      *
666 %************************************************************************
667
668
669 tcAddScopedTyVars is used for scoped type variables added by pattern
670 type signatures
671         e.g.  \ ((x::a), (y::a)) -> x+y
672 They never have explicit kinds (because this is source-code only)
673 They are mutable (because they can get bound to a more specific type).
674
675 Usually we kind-infer and expand type splices, and then
676 tupecheck/desugar the type.  That doesn't work well for scoped type
677 variables, because they scope left-right in patterns.  (e.g. in the
678 example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
679
680 The current not-very-good plan is to
681   * find all the types in the patterns
682   * find their free tyvars
683   * do kind inference
684   * bring the kinded type vars into scope
685   * BUT throw away the kind-checked type
686         (we'll kind-check it again when we type-check the pattern)
687
688 This is bad because throwing away the kind checked type throws away
689 its splices.  But too bad for now.  [July 03]
690
691 Historical note:
692     We no longer specify that these type variables must be univerally 
693     quantified (lots of email on the subject).  If you want to put that 
694     back in, you need to
695         a) Do a checkSigTyVars after thing_inside
696         b) More insidiously, don't pass in expected_ty, else
697            we unify with it too early and checkSigTyVars barfs
698            Instead you have to pass in a fresh ty var, and unify
699            it with expected_ty afterwards
700
701 \begin{code}
702 tcPatSigBndrs :: LHsType Name
703               -> TcM ([TcTyVar],        -- Brought into scope
704                       LHsType Name)     -- Kinded, but not yet desugared
705
706 tcPatSigBndrs hs_ty
707   = do  { in_scope <- getInLocalScope
708         ; span <- getSrcSpanM
709         ; let sig_tvs = [ L span (UserTyVar n) 
710                         | n <- nameSetToList (extractHsTyVars hs_ty),
711                           not (in_scope n) ]
712                 -- The tyvars we want are the free type variables of 
713                 -- the type that are not already in scope
714
715         -- Behave like kcHsType on a ForAll type
716         -- i.e. make kinded tyvars with mutable kinds, 
717         --      and kind-check the enclosed types
718         ; (kinded_tvs, kinded_ty) <- kcHsTyVars sig_tvs $ \ kinded_tvs -> do
719                                     { kinded_ty <- kcTypeType hs_ty
720                                     ; return (kinded_tvs, kinded_ty) }
721
722         -- Zonk the mutable kinds and bring the tyvars into scope
723         -- Just like the call to tcTyVarBndrs in ds_type (HsForAllTy case), 
724         -- except that it brings *meta* tyvars into scope, not regular ones
725         --
726         --      [Out of date, but perhaps should be resurrected]
727         -- Furthermore, the tyvars are PatSigTvs, which means that we get better
728         -- error messages when type variables escape:
729         --      Inferred type is less polymorphic than expected
730         --      Quantified type variable `t' escapes
731         --      It is mentioned in the environment:
732         --      t is bound by the pattern type signature at tcfail103.hs:6
733         ; tyvars <- mapM (zonk . unLoc) kinded_tvs
734         ; return (tyvars, kinded_ty) }
735   where
736     zonk (KindedTyVar name kind) = zonkTcKindToKind kind        `thenM` \ kind' ->
737                                    newMetaTyVar name kind' Flexi
738         -- Scoped type variables are bound to a *type*, hence Flexi
739     zonk (UserTyVar name) = pprTrace "Un-kinded tyvar" (ppr name) $
740                             returnM (mkTyVar name liftedTypeKind)
741
742 tcHsPatSigType :: UserTypeCtxt
743                -> LHsType Name          -- The type signature
744                -> TcM ([TcTyVar],       -- Newly in-scope type variables
745                         TcType)         -- The signature
746
747 tcHsPatSigType ctxt hs_ty 
748   = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
749     do  { (tyvars, kinded_ty) <- tcPatSigBndrs hs_ty
750
751          -- Complete processing of the type, and check its validity
752         ; tcExtendTyVarEnv tyvars $ do
753                 { sig_ty <- tcHsKindedType kinded_ty    
754                 ; checkValidType ctxt sig_ty 
755                 ; return (tyvars, sig_ty) }
756         }
757
758 tcAddLetBoundTyVars :: LHsBinds Name -> TcM a -> TcM a
759 -- Turgid funciton, used for type variables bound by the patterns of a let binding
760
761 tcAddLetBoundTyVars binds thing_inside
762   = go (collectSigTysFromHsBinds (bagToList binds)) thing_inside
763   where
764     go [] thing_inside = thing_inside
765     go (hs_ty:hs_tys) thing_inside
766         = do { (tyvars, _kinded_ty) <- tcPatSigBndrs hs_ty
767              ; tcExtendTyVarEnv tyvars (go hs_tys thing_inside) }
768 \end{code}
769
770
771 %************************************************************************
772 %*                                                                      *
773 \subsection{Signatures}
774 %*                                                                      *
775 %************************************************************************
776
777 @tcSigs@ checks the signatures for validity, and returns a list of
778 {\em freshly-instantiated} signatures.  That is, the types are already
779 split up, and have fresh type variables installed.  All non-type-signature
780 "RenamedSigs" are ignored.
781
782 The @TcSigInfo@ contains @TcTypes@ because they are unified with
783 the variable's type, and after that checked to see whether they've
784 been instantiated.
785
786 \begin{code}
787 data TcSigInfo
788   = TcSigInfo {
789         sig_id     :: TcId,             --  *Polymorphic* binder for this value...
790
791         sig_scoped :: [Name],           -- Names for any scoped type variables
792                                         -- Invariant: correspond 1-1 with an initial
793                                         -- segment of sig_tvs (see Note [Scoped])
794
795         sig_tvs    :: [TcTyVar],        -- Instantiated type variables
796                                         -- See Note [Instantiate sig]
797
798         sig_theta  :: TcThetaType,      -- Instantiated theta
799         sig_tau    :: TcTauType,        -- Instantiated tau
800         sig_loc    :: InstLoc           -- The location of the signature
801     }
802
803 --      Note [Scoped]
804 -- There may be more instantiated type variables than scoped 
805 -- ones.  For example:
806 --      type T a = forall b. b -> (a,b)
807 --      f :: forall c. T c
808 -- Here, the signature for f will have one scoped type variable, c,
809 -- but two instantiated type variables, c' and b'.  
810 --
811 -- We assume that the scoped ones are at the *front* of sig_tvs,
812 -- and remember the names from the original HsForAllTy in sig_scoped
813
814 --      Note [Instantiate sig]
815 -- It's vital to instantiate a type signature with fresh variable.
816 -- For example:
817 --      type S = forall a. a->a
818 --      f,g :: S
819 --      f = ...
820 --      g = ...
821 -- Here, we must use distinct type variables when checking f,g's right hand sides.
822 -- (Instantiation is only necessary because of type synonyms.  Otherwise,
823 -- it's all cool; each signature has distinct type variables from the renamer.)
824
825 type TcSigFun = Name -> Maybe TcSigInfo
826
827 instance Outputable TcSigInfo where
828     ppr (TcSigInfo { sig_id = id, sig_tvs = tyvars, sig_theta = theta, sig_tau = tau})
829         = ppr id <+> ptext SLIT("::") <+> ppr tyvars <+> ppr theta <+> ptext SLIT("=>") <+> ppr tau
830
831 lookupSig :: [TcSigInfo] -> TcSigFun    -- Search for a particular signature
832 lookupSig [] name = Nothing
833 lookupSig (sig : sigs) name
834   | name == idName (sig_id sig) = Just sig
835   | otherwise                   = lookupSig sigs name
836 \end{code}
837