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