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