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