[project @ 2004-04-02 16:46:57 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, tcTyVarBndrs, dsHsType, 
17
18         tcAddScopedTyVars, 
19         
20         TcSigInfo(..), tcTySig, mkTcSig, maybeSig 
21    ) where
22
23 #include "HsVersions.h"
24
25 import HsSyn            ( HsType(..), LHsType, HsTyVarBndr(..), LHsTyVarBndr, 
26                           LHsContext, Sig(..), LSig, HsPred(..), LHsPred )
27 import RnHsSyn          ( extractHsTyVars )
28 import TcHsSyn          ( TcId )
29
30 import TcRnMonad
31 import TcEnv            ( tcExtendTyVarEnv, tcExtendKindEnv,
32                           tcLookup, tcLookupClass, tcLookupTyCon,
33                           TyThing(..), TcTyThing(..), 
34                           getInLocalScope, wrongThingErr
35                         )
36 import TcMType          ( newKindVar, tcInstType, newMutTyVar, 
37                           zonkTcKindToKind, 
38                           checkValidType, UserTypeCtxt(..), pprHsSigCtxt
39                         )
40 import TcUnify          ( unifyFunKind, checkExpectedKind )
41 import TcType           ( Type, PredType(..), ThetaType, TyVarDetails(..),
42                           TcTyVar, TcKind, TcThetaType, TcTauType,
43                           mkTyVarTy, mkTyVarTys, mkFunTy, 
44                           mkForAllTys, mkFunTys, tcEqType, isPredTy,
45                           mkSigmaTy, mkPredTy, mkGenTyConApp, mkTyConApp, mkAppTys, 
46                           tcSplitFunTy_maybe, tcSplitForAllTys )
47 import Kind             ( liftedTypeKind, ubxTupleKind, openTypeKind, argTypeKind )
48 import Inst             ( Inst, InstOrigin(..), newMethod, instToId )
49
50 import Id               ( mkLocalId, idName, idType )
51 import Var              ( TyVar, mkTyVar, tyVarKind )
52 import TyCon            ( TyCon, tyConKind )
53 import Class            ( Class, classTyCon )
54 import Name             ( Name )
55 import NameSet
56 import PrelNames        ( genUnitTyConName )
57 import Subst            ( deShadowTy )
58 import TysWiredIn       ( mkListTy, mkPArrTy, mkTupleTy )
59 import BasicTypes       ( Boxity(..) )
60 import SrcLoc           ( SrcSpan, Located(..), unLoc, noLoc )
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 tcHsSigType ctxt hs_ty 
152   = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
153     do  { kinded_ty <- kcTypeType hs_ty
154         ; ty <- tcHsKindedType kinded_ty
155         ; checkValidType ctxt ty        
156         ; returnM ty }
157
158 -- Used for the deriving(...) items
159 tcHsDeriv :: LHsType Name -> TcM ([TyVar], Class, [Type])
160 tcHsDeriv = addLocM (tc_hs_deriv [])
161
162 tc_hs_deriv tv_names (HsPredTy (L _ (HsClassP cls_name hs_tys)))
163   = kcHsTyVars tv_names                 $ \ tv_names' ->
164     do  { cls_kind <- kcClass cls_name
165         ; (tys, res_kind) <- kcApps cls_kind (ppr cls_name) hs_tys
166         ; tcTyVarBndrs tv_names'        $ \ tyvars ->
167     do  { arg_tys <- dsHsTypes tys
168         ; cls <- tcLookupClass cls_name
169         ; return (tyvars, cls, arg_tys) }}
170
171 tc_hs_deriv tv_names1 (HsForAllTy _ tv_names2 (L _ []) (L _ ty))
172   =     -- Funny newtype deriving form
173         --      forall a. C [a]
174         -- where C has arity 2.  Hence can't use regular functions
175     tc_hs_deriv (tv_names1 ++ tv_names2) ty
176
177 tc_hs_deriv _ other
178   = failWithTc (ptext SLIT("Illegal deriving item") <+> ppr other)
179 \end{code}
180
181         These functions are used during knot-tying in
182         type and class declarations, when we have to
183         separate kind-checking, desugaring, and validity checking
184
185 \begin{code}
186 kcHsSigType, kcHsLiftedSigType :: LHsType Name -> TcM (LHsType Name)
187         -- Used for type signatures
188 kcHsSigType ty       = kcTypeType ty
189 kcHsLiftedSigType ty = kcLiftedType ty
190
191 tcHsKindedType :: LHsType Name -> TcM Type
192   -- Don't do kind checking, nor validity checking, 
193   --    but do hoist for-alls to the top
194   -- This is used in type and class decls, where kinding is
195   -- done in advance, and validity checking is done later
196   -- [Validity checking done later because of knot-tying issues.]
197 tcHsKindedType hs_ty 
198   = do  { ty <- dsHsType hs_ty
199         ; return (hoistForAllTys ty) }
200
201 tcHsKindedContext :: LHsContext Name -> TcM ThetaType
202 -- Used when we are expecting a ClassContext (i.e. no implicit params)
203 -- Does not do validity checking, like tcHsKindedType
204 tcHsKindedContext hs_theta = addLocM (mappM dsHsPred) hs_theta
205 \end{code}
206
207
208 %************************************************************************
209 %*                                                                      *
210                 The main kind checker: kcHsType
211 %*                                                                      *
212 %************************************************************************
213         
214         First a couple of simple wrappers for kcHsType
215
216 \begin{code}
217 ---------------------------
218 kcLiftedType :: LHsType Name -> TcM (LHsType Name)
219 -- The type ty must be a *lifted* *type*
220 kcLiftedType ty = kcCheckHsType ty liftedTypeKind
221     
222 ---------------------------
223 kcTypeType :: LHsType Name -> TcM (LHsType Name)
224 -- The type ty must be a *type*, but it can be lifted or 
225 -- unlifted or an unboxed tuple.
226 kcTypeType ty = kcCheckHsType ty openTypeKind
227
228 ---------------------------
229 kcCheckHsType :: LHsType Name -> TcKind -> TcM (LHsType Name)
230 -- Check that the type has the specified kind
231 -- Be sure to use checkExpectedKind, rather than simply unifying 
232 -- with OpenTypeKind, because it gives better error messages
233 kcCheckHsType (L span ty) exp_kind 
234   = addSrcSpan span                             $
235     kc_hs_type ty                               `thenM` \ (ty', act_kind) ->
236     checkExpectedKind ty act_kind exp_kind      `thenM_`
237     returnM (L span ty')
238 \end{code}
239
240         Here comes the main function
241
242 \begin{code}
243 kcHsType :: LHsType Name -> TcM (LHsType Name, TcKind)
244 kcHsType ty = wrapLocFstM kc_hs_type ty
245 -- kcHsType *returns* the kind of the type, rather than taking an expected
246 -- kind as argument as tcExpr does.  
247 -- Reasons: 
248 --      (a) the kind of (->) is
249 --              forall bx1 bx2. Type bx1 -> Type bx2 -> Type Boxed
250 --          so we'd need to generate huge numbers of bx variables.
251 --      (b) kinds are so simple that the error messages are fine
252 --
253 -- The translated type has explicitly-kinded type-variable binders
254
255 kc_hs_type (HsParTy ty)
256  = kcHsType ty          `thenM` \ (ty', kind) ->
257    returnM (HsParTy ty', kind)
258
259 -- kcHsType (HsSpliceTy s)
260 --   = kcSpliceType s)
261
262 kc_hs_type (HsTyVar name)
263   = kcTyVar name        `thenM` \ kind ->
264     returnM (HsTyVar name, kind)
265
266 kc_hs_type (HsListTy ty) 
267   = kcLiftedType ty                     `thenM` \ ty' ->
268     returnM (HsListTy ty', liftedTypeKind)
269
270 kc_hs_type (HsPArrTy ty)
271   = kcLiftedType ty                     `thenM` \ ty' ->
272     returnM (HsPArrTy ty', liftedTypeKind)
273
274 kc_hs_type (HsNumTy n)
275    = returnM (HsNumTy n, liftedTypeKind)
276
277 kc_hs_type (HsKindSig ty k) 
278   = kcCheckHsType ty k  `thenM` \ ty' ->
279     returnM (HsKindSig ty' k, k)
280
281 kc_hs_type (HsTupleTy Boxed tys)
282   = mappM kcLiftedType tys      `thenM` \ tys' ->
283     returnM (HsTupleTy Boxed tys', liftedTypeKind)
284
285 kc_hs_type (HsTupleTy Unboxed tys)
286   = mappM kcTypeType tys        `thenM` \ tys' ->
287     returnM (HsTupleTy Unboxed tys', ubxTupleKind)
288
289 kc_hs_type (HsFunTy ty1 ty2)
290   = kcCheckHsType ty1 argTypeKind       `thenM` \ ty1' ->
291     kcTypeType ty2                      `thenM` \ ty2' ->
292     returnM (HsFunTy ty1' ty2', liftedTypeKind)
293
294 kc_hs_type ty@(HsOpTy ty1 op ty2)
295   = addLocM kcTyVar op                  `thenM` \ op_kind ->
296     kcApps op_kind (ppr op) [ty1,ty2]   `thenM` \ ([ty1',ty2'], res_kind) ->
297     returnM (HsOpTy ty1' op ty2', res_kind)
298
299 kc_hs_type ty@(HsAppTy ty1 ty2)
300   = kcHsType fun_ty                       `thenM` \ (fun_ty', fun_kind) ->
301     kcApps fun_kind (ppr fun_ty) arg_tys  `thenM` \ ((arg_ty':arg_tys'), res_kind) ->
302     returnM (foldl mk_app (HsAppTy fun_ty' arg_ty') arg_tys', res_kind)
303   where
304     (fun_ty, arg_tys) = split ty1 [ty2]
305     split (L _ (HsAppTy f a)) as = split f (a:as)
306     split f                   as = (f,as)
307     mk_app fun arg = HsAppTy (noLoc fun) arg    -- Add noLocs for inner nodes of
308                                                 -- the application; they are never used
309     
310 kc_hs_type (HsPredTy pred)
311   = kcHsPred pred               `thenM` \ pred' ->
312     returnM (HsPredTy pred', liftedTypeKind)
313
314 kc_hs_type (HsForAllTy exp tv_names context ty)
315   = kcHsTyVars tv_names         $ \ tv_names' ->
316     kcHsContext context         `thenM` \ ctxt' ->
317     kcHsType ty                 `thenM` \ (ty', kind) ->
318         -- The body of a forall is usually a type, but in principle
319         -- there's no reason to prohibit *unlifted* types.
320         -- In fact, GHC can itself construct a function with an
321         -- unboxed tuple inside a for-all (via CPR analyis; see 
322         -- typecheck/should_compile/tc170)
323         --
324         -- Furthermore, in newtype deriving we allow
325         --      deriving( forall a. C [a] )
326         -- where C :: *->*->*, so it's awkward to prohibit higher-kinded
327         -- bodies.  In any case, if there is a higher-kinded body
328         -- and we propagate that up, the caller will find any bugs.
329     returnM (HsForAllTy exp tv_names' ctxt' ty', kind)
330
331 ---------------------------
332 kcApps :: TcKind                        -- Function kind
333        -> SDoc                          -- Function 
334        -> [LHsType Name]                -- Arg types
335        -> TcM ([LHsType Name], TcKind)  -- Kind-checked args
336 kcApps fun_kind ppr_fun args
337   = split_fk fun_kind (length args)     `thenM` \ (arg_kinds, res_kind) ->
338     zipWithM kc_arg args arg_kinds      `thenM` \ args' ->
339     returnM (args', res_kind)
340   where
341     split_fk fk 0 = returnM ([], fk)
342     split_fk fk n = unifyFunKind fk     `thenM` \ mb_fk ->
343                     case mb_fk of 
344                         Nothing       -> failWithTc too_many_args 
345                         Just (ak,fk') -> split_fk fk' (n-1)     `thenM` \ (aks, rk) ->
346                                          returnM (ak:aks, rk)
347
348     kc_arg arg arg_kind = kcCheckHsType arg arg_kind
349
350     too_many_args = ptext SLIT("Kind error:") <+> quotes ppr_fun <+>
351                     ptext SLIT("is applied to too many type arguments")
352
353 ---------------------------
354 kcHsContext :: LHsContext Name -> TcM (LHsContext Name)
355 kcHsContext ctxt = wrapLocM (mappM kcHsPred) ctxt
356
357 kcHsPred (L span pred)          -- Checks that the result is of kind liftedType
358   = addSrcSpan span $
359     kc_pred pred                                `thenM` \ (pred', kind) ->
360     checkExpectedKind pred kind liftedTypeKind  `thenM_` 
361     returnM (L span pred')
362     
363 ---------------------------
364 kc_pred :: HsPred Name -> TcM (HsPred Name, TcKind)     
365         -- Does *not* check for a saturated
366         -- application (reason: used from TcDeriv)
367 kc_pred pred@(HsIParam name ty)
368   = kcHsType ty         `thenM` \ (ty', kind) ->
369     returnM (HsIParam name ty', kind)
370
371 kc_pred pred@(HsClassP cls tys)
372   = kcClass cls                 `thenM` \ kind ->
373     kcApps kind (ppr cls) tys   `thenM` \ (tys', res_kind) ->
374     returnM (HsClassP cls tys', res_kind)
375
376 ---------------------------
377 kcTyVar :: Name -> TcM TcKind
378 kcTyVar name    -- Could be a tyvar or a tycon
379   = traceTc (text "lk1" <+> ppr name)   `thenM_`
380     tcLookup name       `thenM` \ thing ->
381     traceTc (text "lk2" <+> ppr name <+> ppr thing)     `thenM_`
382     case thing of 
383         ATyVar tv               -> returnM (tyVarKind tv)
384         AThing kind             -> returnM kind
385         AGlobal (ATyCon tc)     -> returnM (tyConKind tc) 
386         other                   -> wrongThingErr "type" thing name
387
388 kcClass :: Name -> TcM TcKind
389 kcClass cls     -- Must be a class
390   = tcLookup cls                                `thenM` \ thing -> 
391     case thing of
392         AThing kind             -> returnM kind
393         AGlobal (AClass cls)    -> returnM (tyConKind (classTyCon cls))
394         other                   -> wrongThingErr "class" thing cls
395 \end{code}
396
397
398 %************************************************************************
399 %*                                                                      *
400                 Desugaring
401 %*                                                                      *
402 %************************************************************************
403
404 The type desugarer
405
406         * Transforms from HsType to Type
407         * Zonks any kinds
408
409 It cannot fail, and does no validity checking
410
411 \begin{code}
412 dsHsType :: LHsType Name -> TcM Type
413 -- All HsTyVarBndrs in the intput type are kind-annotated
414 dsHsType ty = ds_type (unLoc ty)
415
416 ds_type ty@(HsTyVar name)
417   = ds_app ty []
418
419 ds_type (HsParTy ty)            -- Remove the parentheses markers
420   = dsHsType ty
421
422 ds_type (HsKindSig ty k)
423   = dsHsType ty -- Kind checking done already
424
425 ds_type (HsListTy ty)
426   = dsHsType ty                         `thenM` \ tau_ty ->
427     returnM (mkListTy tau_ty)
428
429 ds_type (HsPArrTy ty)
430   = dsHsType ty                         `thenM` \ tau_ty ->
431     returnM (mkPArrTy tau_ty)
432
433 ds_type (HsTupleTy boxity tys)
434   = dsHsTypes tys                       `thenM` \ tau_tys ->
435     returnM (mkTupleTy boxity (length tys) tau_tys)
436
437 ds_type (HsFunTy ty1 ty2)
438   = dsHsType ty1                        `thenM` \ tau_ty1 ->
439     dsHsType ty2                        `thenM` \ tau_ty2 ->
440     returnM (mkFunTy tau_ty1 tau_ty2)
441
442 ds_type (HsOpTy ty1 (L span op) ty2)
443   = dsHsType ty1                `thenM` \ tau_ty1 ->
444     dsHsType ty2                `thenM` \ tau_ty2 ->
445     addSrcSpan span (ds_var_app op [tau_ty1,tau_ty2])
446
447 ds_type (HsNumTy n)
448   = ASSERT(n==1)
449     tcLookupTyCon genUnitTyConName      `thenM` \ tc ->
450     returnM (mkTyConApp tc [])
451
452 ds_type ty@(HsAppTy _ _)
453   = ds_app ty []
454
455 ds_type (HsPredTy pred)
456   = dsHsPred pred       `thenM` \ pred' ->
457     returnM (mkPredTy pred')
458
459 ds_type full_ty@(HsForAllTy exp tv_names ctxt ty)
460   = tcTyVarBndrs tv_names               $ \ tyvars ->
461     mappM dsHsPred (unLoc ctxt)         `thenM` \ theta ->
462     dsHsType ty                         `thenM` \ tau ->
463     returnM (mkSigmaTy tyvars theta tau)
464
465 dsHsTypes arg_tys = mappM dsHsType arg_tys
466 \end{code}
467
468 Help functions for type applications
469 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
470
471 \begin{code}
472 ds_app :: HsType Name -> [LHsType Name] -> TcM Type
473 ds_app (HsAppTy ty1 ty2) tys
474   = ds_app (unLoc ty1) (ty2:tys)
475
476 ds_app ty tys
477   = dsHsTypes tys                       `thenM` \ arg_tys ->
478     case ty of
479         HsTyVar fun -> ds_var_app fun arg_tys
480         other       -> ds_type ty               `thenM` \ fun_ty ->
481                        returnM (mkAppTys fun_ty arg_tys)
482
483 ds_var_app :: Name -> [Type] -> TcM Type
484 ds_var_app name arg_tys 
485  = tcLookup name                        `thenM` \ thing ->
486     case thing of
487         ATyVar tv            -> returnM (mkAppTys (mkTyVarTy tv) arg_tys)
488         AGlobal (ATyCon tc)  -> returnM (mkGenTyConApp tc arg_tys)
489         AThing _             -> tcLookupTyCon name      `thenM` \ tc ->
490                                 returnM (mkGenTyConApp tc arg_tys)
491         other -> pprPanic "ds_app_type" (ppr name <+> ppr arg_tys)
492 \end{code}
493
494
495 Contexts
496 ~~~~~~~~
497 \begin{code}
498 dsHsPred :: LHsPred Name -> TcM PredType
499 dsHsPred pred = ds_pred (unLoc pred)
500
501 ds_pred pred@(HsClassP class_name tys)
502   = dsHsTypes tys                       `thenM` \ arg_tys ->
503     tcLookupClass class_name            `thenM` \ clas ->
504     returnM (ClassP clas arg_tys)
505
506 ds_pred (HsIParam name ty)
507   = dsHsType ty                                 `thenM` \ arg_ty ->
508     returnM (IParam name arg_ty)
509 \end{code}
510
511
512 %************************************************************************
513 %*                                                                      *
514                 Type-variable binders
515 %*                                                                      *
516 %************************************************************************
517
518
519 \begin{code}
520 kcHsTyVars :: [LHsTyVarBndr Name] 
521            -> ([LHsTyVarBndr Name] -> TcM r)    -- These binders are kind-annotated
522                                                 -- They scope over the thing inside
523            -> TcM r
524 kcHsTyVars tvs thing_inside 
525   = mappM (wrapLocM kcHsTyVar) tvs      `thenM` \ bndrs ->
526     tcExtendKindEnv [(n,k) | L _ (KindedTyVar n k) <- bndrs]
527                     (thing_inside bndrs)
528
529 kcHsTyVar :: HsTyVarBndr Name -> TcM (HsTyVarBndr Name)
530         -- Return a *kind-annotated* binder, and a tyvar with a mutable kind in it      
531 kcHsTyVar (UserTyVar name)        = newKindVar  `thenM` \ kind ->
532                                     returnM (KindedTyVar name kind)
533 kcHsTyVar (KindedTyVar name kind) = returnM (KindedTyVar name kind)
534
535 ------------------
536 tcTyVarBndrs :: [LHsTyVarBndr Name]     -- Kind-annotated binders, which need kind-zonking
537              -> ([TyVar] -> TcM r)
538              -> TcM r
539 -- Used when type-checking types/classes/type-decls
540 -- Brings into scope immutable TyVars, not mutable ones that require later zonking
541 tcTyVarBndrs bndrs thing_inside
542   = mapM (zonk . unLoc) bndrs   `thenM` \ tyvars ->
543     tcExtendTyVarEnv tyvars (thing_inside tyvars)
544   where
545     zonk (KindedTyVar name kind) = zonkTcKindToKind kind        `thenM` \ kind' ->
546                                    returnM (mkTyVar name kind')
547     zonk (UserTyVar name) = pprTrace "BAD: Un-kinded tyvar" (ppr name) $
548                             returnM (mkTyVar name liftedTypeKind)
549 \end{code}
550
551
552 %************************************************************************
553 %*                                                                      *
554                 Scoped type variables
555 %*                                                                      *
556 %************************************************************************
557
558
559 tcAddScopedTyVars is used for scoped type variables added by pattern
560 type signatures
561         e.g.  \ ((x::a), (y::a)) -> x+y
562 They never have explicit kinds (because this is source-code only)
563 They are mutable (because they can get bound to a more specific type).
564
565 Usually we kind-infer and expand type splices, and then
566 tupecheck/desugar the type.  That doesn't work well for scoped type
567 variables, because they scope left-right in patterns.  (e.g. in the
568 example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
569
570 The current not-very-good plan is to
571   * find all the types in the patterns
572   * find their free tyvars
573   * do kind inference
574   * bring the kinded type vars into scope
575   * BUT throw away the kind-checked type
576         (we'll kind-check it again when we type-check the pattern)
577
578 This is bad because throwing away the kind checked type throws away
579 its splices.  But too bad for now.  [July 03]
580
581 Historical note:
582     We no longer specify that these type variables must be univerally 
583     quantified (lots of email on the subject).  If you want to put that 
584     back in, you need to
585         a) Do a checkSigTyVars after thing_inside
586         b) More insidiously, don't pass in expected_ty, else
587            we unify with it too early and checkSigTyVars barfs
588            Instead you have to pass in a fresh ty var, and unify
589            it with expected_ty afterwards
590
591 \begin{code}
592 tcAddScopedTyVars :: [LHsType Name] -> TcM a -> TcM a
593 tcAddScopedTyVars [] thing_inside
594   = thing_inside        -- Quick get-out for the empty case
595
596 tcAddScopedTyVars sig_tys thing_inside
597   = getInLocalScope                     `thenM` \ in_scope ->
598     getSrcSpanM                         `thenM` \ span ->
599     let
600         sig_tvs = [ L span (UserTyVar n) 
601                   | ty <- sig_tys,
602                     n <- nameSetToList (extractHsTyVars ty),
603                     not (in_scope n) ]
604         -- The tyvars we want are the free type variables of 
605         -- the type that are not already in scope
606     in        
607         -- Behave like kcHsType on a ForAll type
608         -- i.e. make kinded tyvars with mutable kinds, 
609         --      and kind-check the enclosed types
610     kcHsTyVars sig_tvs (\ kinded_tvs -> do
611                             { mappM kcTypeType sig_tys
612                             ; return kinded_tvs })      `thenM` \ kinded_tvs ->
613
614         -- Zonk the mutable kinds and bring the tyvars into scope
615         -- Rather like tcTyVarBndrs, except that it brings *mutable* 
616         -- tyvars into scope, not immutable ones
617         --
618         -- Furthermore, the tyvars are PatSigTvs, which means that we get better
619         -- error messages when type variables escape:
620         --      Inferred type is less polymorphic than expected
621         --      Quantified type variable `t' escapes
622         --      It is mentioned in the environment:
623         --      t is bound by the pattern type signature at tcfail103.hs:6
624     mapM (zonk . unLoc) kinded_tvs      `thenM` \ tyvars ->
625     tcExtendTyVarEnv tyvars thing_inside
626
627   where
628     zonk (KindedTyVar name kind) = zonkTcKindToKind kind        `thenM` \ kind' ->
629                                    newMutTyVar name kind' PatSigTv
630     zonk (UserTyVar name) = pprTrace "BAD: Un-kinded tyvar" (ppr name) $
631                             returnM (mkTyVar name liftedTypeKind)
632 \end{code}
633
634
635 %************************************************************************
636 %*                                                                      *
637 \subsection{Signatures}
638 %*                                                                      *
639 %************************************************************************
640
641 @tcSigs@ checks the signatures for validity, and returns a list of
642 {\em freshly-instantiated} signatures.  That is, the types are already
643 split up, and have fresh type variables installed.  All non-type-signature
644 "RenamedSigs" are ignored.
645
646 The @TcSigInfo@ contains @TcTypes@ because they are unified with
647 the variable's type, and after that checked to see whether they've
648 been instantiated.
649
650 \begin{code}
651 data TcSigInfo
652   = TySigInfo {
653         sig_poly_id :: TcId,    -- *Polymorphic* binder for this value...
654                                 -- Has name = N
655
656         sig_tvs   :: [TcTyVar],         -- tyvars
657         sig_theta :: TcThetaType,       -- theta
658         sig_tau   :: TcTauType,         -- tau
659
660         sig_mono_id :: TcId,    -- *Monomorphic* binder for this value
661                                 -- Does *not* have name = N
662                                 -- Has type tau
663
664         sig_insts :: [Inst],    -- Empty if theta is null, or
665                                 -- (method mono_id) otherwise
666
667         sig_loc :: SrcSpan      -- The location of the signature
668     }
669
670
671 instance Outputable TcSigInfo where
672     ppr (TySigInfo id tyvars theta tau _ inst _) =
673         ppr id <+> ptext SLIT("::") <+> ppr tyvars <+> ppr theta <+> ptext SLIT("=>") <+> ppr tau
674
675 maybeSig :: [TcSigInfo] -> Name -> Maybe (TcSigInfo)
676         -- Search for a particular signature
677 maybeSig [] name = Nothing
678 maybeSig (sig@(TySigInfo sig_id _ _ _ _ _ _) : sigs) name
679   | name == idName sig_id = Just sig
680   | otherwise             = maybeSig sigs name
681 \end{code}
682
683
684 \begin{code}
685 tcTySig :: LSig Name -> TcM TcSigInfo
686
687 tcTySig (L span (Sig (L _ v) ty))
688  = addSrcSpan span                      $
689    tcHsSigType (FunSigCtxt v) ty        `thenM` \ sigma_tc_ty ->
690    mkTcSig (mkLocalId v sigma_tc_ty)    `thenM` \ sig -> 
691    returnM sig
692
693 mkTcSig :: TcId -> TcM TcSigInfo
694 mkTcSig poly_id
695   =     -- Instantiate this type
696         -- It's important to do this even though in the error-free case
697         -- we could just split the sigma_tc_ty (since the tyvars don't
698         -- unified with anything).  But in the case of an error, when
699         -- the tyvars *do* get unified with something, we want to carry on
700         -- typechecking the rest of the program with the function bound
701         -- to a pristine type, namely sigma_tc_ty
702    tcInstType SigTv (idType poly_id)            `thenM` \ (tyvars', theta', tau') ->
703
704    getInstLoc SignatureOrigin                   `thenM` \ inst_loc ->
705    newMethod inst_loc poly_id
706              (mkTyVarTys tyvars')
707              theta' tau'                        `thenM` \ inst ->
708         -- We make a Method even if it's not overloaded; no harm
709         -- But do not extend the LIE!  We're just making an Id.
710         
711    getSrcSpanM                                  `thenM` \ src_loc ->
712    returnM (TySigInfo { sig_poly_id = poly_id, sig_tvs = tyvars', 
713                         sig_theta = theta', sig_tau = tau', 
714                         sig_mono_id = instToId inst,
715                         sig_insts = [inst], sig_loc = src_loc })
716 \end{code}
717
718
719 %************************************************************************
720 %*                                                                      *
721 \subsection{Errors and contexts}
722 %*                                                                      *
723 %************************************************************************
724
725
726 \begin{code}
727 hoistForAllTys :: Type -> Type
728 -- Used for user-written type signatures only
729 -- Move all the foralls and constraints to the top
730 -- e.g.  T -> forall a. a        ==>   forall a. T -> a
731 --       T -> (?x::Int) -> Int   ==>   (?x::Int) -> T -> Int
732 --
733 -- Also: eliminate duplicate constraints.  These can show up
734 -- when hoisting constraints, notably implicit parameters.
735 --
736 -- We want to 'look through' type synonyms when doing this
737 -- so it's better done on the Type than the HsType
738
739 hoistForAllTys ty
740   = let
741         no_shadow_ty = deShadowTy ty
742         -- Running over ty with an empty substitution gives it the
743         -- no-shadowing property.  This is important.  For example:
744         --      type Foo r = forall a. a -> r
745         --      foo :: Foo (Foo ())
746         -- Here the hoisting should give
747         --      foo :: forall a a1. a -> a1 -> ()
748         --
749         -- What about type vars that are lexically in scope in the envt?
750         -- We simply rely on them having a different unique to any
751         -- binder in 'ty'.  Otherwise we'd have to slurp the in-scope-tyvars
752         -- out of the envt, which is boring and (I think) not necessary.
753     in
754     case hoist no_shadow_ty of 
755         (tvs, theta, body) -> mkForAllTys tvs (mkFunTys (nubBy tcEqType theta) body)
756                 -- The 'nubBy' eliminates duplicate constraints,
757                 -- notably implicit parameters
758   where
759     hoist ty
760         | (tvs1, body_ty) <- tcSplitForAllTys ty,
761           not (null tvs1)
762         = case hoist body_ty of
763                 (tvs2,theta,tau) -> (tvs1 ++ tvs2, theta, tau)
764
765         | Just (arg, res) <- tcSplitFunTy_maybe ty
766         = let
767               arg' = hoistForAllTys arg -- Don't forget to apply hoist recursively
768           in                            -- to the argument type
769           if (isPredTy arg') then
770             case hoist res of
771                 (tvs,theta,tau) -> (tvs, arg':theta, tau)
772           else
773              case hoist res of
774                 (tvs,theta,tau) -> (tvs, theta, mkFunTy arg' tau)
775
776         | otherwise = ([], [], ty)
777 \end{code}
778