669c61ca37f3630a7125553783c2c9b7e831e7d9
[ghc-hetmet.git] / compiler / typecheck / TcHsType.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5 \section[TcMonoType]{Typechecking user-specified @MonoTypes@}
6
7 \begin{code}
8 module TcHsType (
9         tcHsSigType, tcHsSigTypeNC, tcHsDeriv, 
10         tcHsInstHead, tcHsQuantifiedType,
11         UserTypeCtxt(..), 
12
13                 -- Kind checking
14         kcHsTyVars, kcHsSigType, kcHsLiftedSigType, 
15         kcLHsType, kcCheckLHsType, kcHsContext, 
16         
17                 -- Typechecking kinded types
18         tcHsKindedContext, tcHsKindedType, tcHsBangType,
19         tcTyVarBndrs, dsHsType, kcHsLPred, dsHsLPred,
20         tcDataKindSig, ExpKind(..), EkCtxt(..),
21
22                 -- Pattern type signatures
23         tcHsPatSigType, tcPatSig
24    ) where
25
26 #include "HsVersions.h"
27
28 #ifdef GHCI     /* Only if bootstrapped */
29 import {-# SOURCE #-}   TcSplice( kcSpliceType )
30 #endif
31
32 import HsSyn
33 import RnHsSyn
34 import TcRnMonad
35 import TcEnv
36 import TcMType
37 import TcUnify
38 import TcIface
39 import TcType
40 import TypeRep ( ecKind )
41 import {- Kind parts of -} Type
42 import Var
43 import VarSet
44 import TyCon
45 import Class
46 import Name
47 import NameSet
48 import PrelNames
49 import TysWiredIn
50 import BasicTypes
51 import SrcLoc
52 import Util
53 import UniqSupply
54 import Outputable
55 import FastString
56 \end{code}
57
58
59         ----------------------------
60                 General notes
61         ----------------------------
62
63 Generally speaking we now type-check types in three phases
64
65   1.  kcHsType: kind check the HsType
66         *includes* performing any TH type splices;
67         so it returns a translated, and kind-annotated, type
68
69   2.  dsHsType: convert from HsType to Type:
70         perform zonking
71         expand type synonyms [mkGenTyApps]
72         hoist the foralls [tcHsType]
73
74   3.  checkValidType: check the validity of the resulting type
75
76 Often these steps are done one after the other (tcHsSigType).
77 But in mutually recursive groups of type and class decls we do
78         1 kind-check the whole group
79         2 build TyCons/Classes in a knot-tied way
80         3 check the validity of types in the now-unknotted TyCons/Classes
81
82 For example, when we find
83         (forall a m. m a -> m a)
84 we bind a,m to kind varibles and kind-check (m a -> m a).  This makes
85 a get kind *, and m get kind *->*.  Now we typecheck (m a -> m a) in
86 an environment that binds a and m suitably.
87
88 The kind checker passed to tcHsTyVars needs to look at enough to
89 establish the kind of the tyvar:
90   * For a group of type and class decls, it's just the group, not
91         the rest of the program
92   * For a tyvar bound in a pattern type signature, its the types
93         mentioned in the other type signatures in that bunch of patterns
94   * For a tyvar bound in a RULE, it's the type signatures on other
95         universally quantified variables in the rule
96
97 Note that this may occasionally give surprising results.  For example:
98
99         data T a b = MkT (a b)
100
101 Here we deduce                  a::*->*,       b::*
102 But equally valid would be      a::(*->*)-> *, b::*->*
103
104
105 Validity checking
106 ~~~~~~~~~~~~~~~~~
107 Some of the validity check could in principle be done by the kind checker, 
108 but not all:
109
110 - During desugaring, we normalise by expanding type synonyms.  Only
111   after this step can we check things like type-synonym saturation
112   e.g.  type T k = k Int
113         type S a = a
114   Then (T S) is ok, because T is saturated; (T S) expands to (S Int);
115   and then S is saturated.  This is a GHC extension.
116
117 - Similarly, also a GHC extension, we look through synonyms before complaining
118   about the form of a class or instance declaration
119
120 - Ambiguity checks involve functional dependencies, and it's easier to wait
121   until knots have been resolved before poking into them
122
123 Also, in a mutually recursive group of types, we can't look at the TyCon until we've
124 finished building the loop.  So to keep things simple, we postpone most validity
125 checking until step (3).
126
127 Knot tying
128 ~~~~~~~~~~
129 During step (1) we might fault in a TyCon defined in another module, and it might
130 (via a loop) refer back to a TyCon defined in this module. So when we tie a big
131 knot around type declarations with ARecThing, so that the fault-in code can get
132 the TyCon being defined.
133
134
135 %************************************************************************
136 %*                                                                      *
137 \subsection{Checking types}
138 %*                                                                      *
139 %************************************************************************
140
141 \begin{code}
142 tcHsSigType, tcHsSigTypeNC :: UserTypeCtxt -> LHsType Name -> TcM Type
143   -- Do kind checking, and hoist for-alls to the top
144   -- NB: it's important that the foralls that come from the top-level
145   --     HsForAllTy in hs_ty occur *first* in the returned type.
146   --     See Note [Scoped] with TcSigInfo
147 tcHsSigType ctxt hs_ty 
148   = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
149     tcHsSigTypeNC ctxt hs_ty
150
151 tcHsSigTypeNC ctxt hs_ty
152   = do  { (kinded_ty, _kind) <- kc_lhs_type hs_ty
153           -- The kind is checked by checkValidType, and isn't necessarily
154           -- of kind * in a Template Haskell quote eg [t| Maybe |]
155         ; ty <- tcHsKindedType kinded_ty
156         ; checkValidType ctxt ty        
157         ; return ty }
158
159 tcHsInstHead :: LHsType Name -> TcM ([TyVar], ThetaType, Class, [Type])
160 -- Typecheck an instance head.  We can't use 
161 -- tcHsSigType, because it's not a valid user type.
162 tcHsInstHead (L loc hs_ty)
163   = setSrcSpan loc   $  -- No need for an "In the type..." context
164                         -- because that comes from the caller
165     do { kinded_ty <- kc_inst_head hs_ty
166        ; ds_inst_head kinded_ty }
167   where
168     kc_inst_head ty@(HsPredTy pred@(HsClassP {}))
169       = do { (pred', kind) <- kc_pred pred
170            ; checkExpectedKind ty kind ekLifted
171            ; return (HsPredTy pred') }
172     kc_inst_head (HsForAllTy exp tv_names context (L loc ty))
173       = kcHsTyVars tv_names         $ \ tv_names' ->
174         do { ctxt' <- kcHsContext context
175            ; ty'   <- kc_inst_head ty
176            ; return (HsForAllTy exp tv_names' ctxt' (L loc ty')) }
177     kc_inst_head _ = failWithTc (ptext (sLit "Malformed instance type"))
178
179     ds_inst_head (HsPredTy (HsClassP cls_name tys))
180       = do { clas <- tcLookupClass cls_name
181            ; arg_tys <- dsHsTypes tys
182            ; return ([], [], clas, arg_tys) }
183     ds_inst_head (HsForAllTy _ tvs ctxt (L _ tau))
184       = tcTyVarBndrs tvs  $ \ tvs' ->
185         do { ctxt' <- mapM dsHsLPred (unLoc ctxt)
186            ; (tvs_r, ctxt_r, cls, tys) <- ds_inst_head tau
187            ; return (tvs' ++ tvs_r, ctxt' ++ ctxt_r , cls, tys) }
188     ds_inst_head _ = panic "ds_inst_head"
189
190 tcHsQuantifiedType :: [LHsTyVarBndr Name] -> LHsType Name -> TcM ([TyVar], Type)
191 -- Behave very like type-checking (HsForAllTy sig_tvs hs_ty),
192 -- except that we want to keep the tvs separate
193 tcHsQuantifiedType tv_names hs_ty
194   = kcHsTyVars tv_names $ \ tv_names' ->
195     do  { kc_ty <- kcHsSigType hs_ty
196         ; tcTyVarBndrs tv_names' $ \ tvs ->
197     do  { ty <- dsHsType kc_ty
198         ; return (tvs, ty) } }
199
200 -- Used for the deriving(...) items
201 tcHsDeriv :: HsType Name -> TcM ([TyVar], Class, [Type])
202 tcHsDeriv = tc_hs_deriv []
203
204 tc_hs_deriv :: [LHsTyVarBndr Name] -> HsType Name
205             -> TcM ([TyVar], Class, [Type])
206 tc_hs_deriv tv_names (HsPredTy (HsClassP cls_name hs_tys))
207   = kcHsTyVars tv_names                 $ \ tv_names' ->
208     do  { cls_kind <- kcClass cls_name
209         ; (tys, _res_kind) <- kcApps cls_name cls_kind hs_tys
210         ; tcTyVarBndrs tv_names'        $ \ tyvars ->
211     do  { arg_tys <- dsHsTypes tys
212         ; cls <- tcLookupClass cls_name
213         ; return (tyvars, cls, arg_tys) }}
214
215 tc_hs_deriv tv_names1 (HsForAllTy _ tv_names2 (L _ []) (L _ ty))
216   =     -- Funny newtype deriving form
217         --      forall a. C [a]
218         -- where C has arity 2.  Hence can't use regular functions
219     tc_hs_deriv (tv_names1 ++ tv_names2) ty
220
221 tc_hs_deriv _ other
222   = failWithTc (ptext (sLit "Illegal deriving item") <+> ppr other)
223 \end{code}
224
225         These functions are used during knot-tying in
226         type and class declarations, when we have to
227         separate kind-checking, desugaring, and validity checking
228
229 \begin{code}
230 kcHsSigType, kcHsLiftedSigType :: LHsType Name -> TcM (LHsType Name)
231         -- Used for type signatures
232 kcHsSigType ty       = addKcTypeCtxt ty $ kcTypeType ty
233 kcHsLiftedSigType ty = addKcTypeCtxt ty $ kcLiftedType ty
234
235 tcHsKindedType :: LHsType Name -> TcM Type
236   -- Don't do kind checking, nor validity checking.
237   -- This is used in type and class decls, where kinding is
238   -- done in advance, and validity checking is done later
239   -- [Validity checking done later because of knot-tying issues.]
240 tcHsKindedType hs_ty = dsHsType hs_ty
241
242 tcHsBangType :: LHsType Name -> TcM Type
243 -- Permit a bang, but discard it
244 tcHsBangType (L _ (HsBangTy _ ty)) = tcHsKindedType ty
245 tcHsBangType ty                    = tcHsKindedType ty
246
247 tcHsKindedContext :: LHsContext Name -> TcM ThetaType
248 -- Used when we are expecting a ClassContext (i.e. no implicit params)
249 -- Does not do validity checking, like tcHsKindedType
250 tcHsKindedContext hs_theta = addLocM (mapM dsHsLPred) hs_theta
251 \end{code}
252
253
254 %************************************************************************
255 %*                                                                      *
256                 The main kind checker: kcHsType
257 %*                                                                      *
258 %************************************************************************
259         
260         First a couple of simple wrappers for kcHsType
261
262 \begin{code}
263 ---------------------------
264 kcLiftedType :: LHsType Name -> TcM (LHsType Name)
265 -- The type ty must be a *lifted* *type*
266 kcLiftedType ty = kc_check_lhs_type ty ekLifted
267     
268 ---------------------------
269 kcTypeType :: LHsType Name -> TcM (LHsType Name)
270 -- The type ty must be a *type*, but it can be lifted or 
271 -- unlifted or an unboxed tuple.
272 kcTypeType ty = kc_check_lhs_type ty ekOpen
273
274 ---------------------------
275 kcCheckLHsType :: LHsType Name -> ExpKind -> TcM (LHsType Name)
276 kcCheckLHsType ty kind = addKcTypeCtxt ty $ kc_check_lhs_type ty kind
277
278
279 kc_check_lhs_type :: LHsType Name -> ExpKind -> TcM (LHsType Name)
280 -- Check that the type has the specified kind
281 -- Be sure to use checkExpectedKind, rather than simply unifying 
282 -- with OpenTypeKind, because it gives better error messages
283 kc_check_lhs_type (L span ty) exp_kind 
284   = setSrcSpan span $
285     do { ty' <- kc_check_hs_type ty exp_kind
286        ; return (L span ty') }
287
288 kc_check_lhs_types :: [(LHsType Name, ExpKind)] -> TcM [LHsType Name]
289 kc_check_lhs_types tys_w_kinds
290   = mapM kc_arg tys_w_kinds
291   where
292     kc_arg (arg, arg_kind) = kc_check_lhs_type arg arg_kind
293
294
295 ---------------------------
296 kc_check_hs_type :: HsType Name -> ExpKind -> TcM (HsType Name)
297
298 -- First some special cases for better error messages 
299 -- when we know the expected kind
300 kc_check_hs_type (HsParTy ty) exp_kind
301   = do { ty' <- kc_check_lhs_type ty exp_kind; return (HsParTy ty') }
302
303 kc_check_hs_type ty@(HsAppTy ty1 ty2) exp_kind
304   = do { let (fun_ty, arg_tys) = splitHsAppTys ty1 ty2
305        ; (fun_ty', fun_kind) <- kc_lhs_type fun_ty
306        ; arg_tys' <- kcCheckApps fun_ty fun_kind arg_tys ty exp_kind
307        ; return (mkHsAppTys fun_ty' arg_tys') }
308
309 -- This is the general case: infer the kind and compare
310 kc_check_hs_type ty exp_kind
311   = do  { (ty', act_kind) <- kc_hs_type ty
312                 -- Add the context round the inner check only
313                 -- because checkExpectedKind already mentions
314                 -- 'ty' by name in any error message
315
316         ; checkExpectedKind (strip ty) act_kind exp_kind
317         ; return ty' }
318   where
319         -- We infer the kind of the type, and then complain if it's
320         -- not right.  But we don't want to complain about
321         --      (ty) or !(ty) or forall a. ty
322         -- when the real difficulty is with the 'ty' part.
323     strip (HsParTy (L _ ty))          = strip ty
324     strip (HsBangTy _ (L _ ty))       = strip ty
325     strip (HsForAllTy _ _ _ (L _ ty)) = strip ty
326     strip ty                          = ty
327 \end{code}
328
329         Here comes the main function
330
331 \begin{code}
332 kcLHsType :: LHsType Name -> TcM (LHsType Name, TcKind)
333 -- Called from outside: set the context
334 kcLHsType ty = addKcTypeCtxt ty (kc_lhs_type ty)
335
336 kc_lhs_type :: LHsType Name -> TcM (LHsType Name, TcKind)
337 kc_lhs_type (L span ty)
338   = setSrcSpan span $
339     do { (ty', kind) <- kc_hs_type ty
340        ; return (L span ty', kind) }
341
342 -- kc_hs_type *returns* the kind of the type, rather than taking an expected
343 -- kind as argument as tcExpr does.  
344 -- Reasons: 
345 --      (a) the kind of (->) is
346 --              forall bx1 bx2. Type bx1 -> Type bx2 -> Type Boxed
347 --          so we'd need to generate huge numbers of bx variables.
348 --      (b) kinds are so simple that the error messages are fine
349 --
350 -- The translated type has explicitly-kinded type-variable binders
351
352 kc_hs_type :: HsType Name -> TcM (HsType Name, TcKind)
353 kc_hs_type (HsParTy ty) = do
354    (ty', kind) <- kc_lhs_type ty
355    return (HsParTy ty', kind)
356
357 kc_hs_type (HsTyVar name) = do
358     kind <- kcTyVar name
359     return (HsTyVar name, kind)
360
361 kc_hs_type (HsListTy ty) = do
362     ty' <- kcLiftedType ty
363     return (HsListTy ty', liftedTypeKind)
364
365 kc_hs_type (HsPArrTy ty) = do
366     ty' <- kcLiftedType ty
367     return (HsPArrTy ty', liftedTypeKind)
368
369 kc_hs_type (HsModalBoxType ecn ty) = do
370     kc_check_hs_type (HsTyVar ecn) (EK ecKind EkUnk)
371     ty' <- kcLiftedType ty
372     return (HsModalBoxType ecn ty', liftedTypeKind)
373
374 kc_hs_type (HsNumTy n)
375    = return (HsNumTy n, liftedTypeKind)
376
377 kc_hs_type (HsKindSig ty k) = do
378     ty' <- kc_check_lhs_type ty (EK k EkKindSig)
379     return (HsKindSig ty' k, k)
380
381 kc_hs_type (HsTupleTy Boxed tys) = do
382     tys' <- mapM kcLiftedType tys
383     return (HsTupleTy Boxed tys', liftedTypeKind)
384
385 kc_hs_type (HsTupleTy Unboxed tys) = do
386     tys' <- mapM kcTypeType tys
387     return (HsTupleTy Unboxed tys', ubxTupleKind)
388
389 kc_hs_type (HsFunTy ty1 ty2) = do
390     ty1' <- kc_check_lhs_type ty1 (EK argTypeKind EkUnk)
391     ty2' <- kcTypeType ty2
392     return (HsFunTy ty1' ty2', liftedTypeKind)
393
394 kc_hs_type (HsOpTy ty1 op ty2) = do
395     op_kind <- addLocM kcTyVar op
396     ([ty1',ty2'], res_kind) <- kcApps op op_kind [ty1,ty2]
397     return (HsOpTy ty1' op ty2', res_kind)
398
399 kc_hs_type (HsAppTy ty1 ty2) = do
400     (fun_ty', fun_kind) <- kc_lhs_type fun_ty
401     (arg_tys', res_kind) <- kcApps fun_ty fun_kind arg_tys
402     return (mkHsAppTys fun_ty' arg_tys', res_kind)
403   where
404     (fun_ty, arg_tys) = splitHsAppTys ty1 ty2
405
406 kc_hs_type (HsPredTy pred)
407   = wrongPredErr pred
408
409 kc_hs_type (HsCoreTy ty)
410   = return (HsCoreTy ty, typeKind ty)
411
412 kc_hs_type (HsForAllTy exp tv_names context ty)
413   = kcHsTyVars tv_names         $ \ tv_names' ->
414     do  { ctxt' <- kcHsContext context
415         ; ty'   <- kcLiftedType ty
416              -- The body of a forall is usually a type, but in principle
417              -- there's no reason to prohibit *unlifted* types.
418              -- In fact, GHC can itself construct a function with an
419              -- unboxed tuple inside a for-all (via CPR analyis; see 
420              -- typecheck/should_compile/tc170)
421              --
422              -- Still, that's only for internal interfaces, which aren't
423              -- kind-checked, so we only allow liftedTypeKind here
424
425         ; return (HsForAllTy exp tv_names' ctxt' ty', liftedTypeKind) }
426
427 kc_hs_type (HsBangTy b ty)
428   = do { (ty', kind) <- kc_lhs_type ty
429        ; return (HsBangTy b ty', kind) }
430
431 kc_hs_type ty@(HsRecTy _)
432   = failWithTc (ptext (sLit "Unexpected record type") <+> ppr ty)
433       -- Record types (which only show up temporarily in constructor signatures) 
434       -- should have been removed by now
435
436 #ifdef GHCI     /* Only if bootstrapped */
437 kc_hs_type (HsSpliceTy sp fvs _) = kcSpliceType sp fvs
438 #else
439 kc_hs_type ty@(HsSpliceTy {}) = failWithTc (ptext (sLit "Unexpected type splice:") <+> ppr ty)
440 #endif
441
442 kc_hs_type (HsQuasiQuoteTy {}) = panic "kc_hs_type"     -- Eliminated by renamer
443
444 -- remove the doc nodes here, no need to worry about the location since
445 -- its the same for a doc node and it's child type node
446 kc_hs_type (HsDocTy ty _)
447   = kc_hs_type (unLoc ty) 
448
449 ---------------------------
450 kcApps :: Outputable a
451        => a 
452        -> TcKind                        -- Function kind
453        -> [LHsType Name]                -- Arg types
454        -> TcM ([LHsType Name], TcKind)  -- Kind-checked args
455 kcApps the_fun fun_kind args
456   = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
457        ; args' <- kc_check_lhs_types args_w_kinds
458        ; return (args', res_kind) }
459
460 kcCheckApps :: Outputable a => a -> TcKind -> [LHsType Name]
461             -> HsType Name     -- The type being checked (for err messages only)
462             -> ExpKind         -- Expected kind
463             -> TcM [LHsType Name]
464 kcCheckApps the_fun fun_kind args ty exp_kind
465   = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
466        ; checkExpectedKind ty res_kind exp_kind
467              -- Check the result kind *before* checking argument kinds
468              -- This improves error message; Trac #2994
469        ; kc_check_lhs_types args_w_kinds }
470
471 splitHsAppTys :: LHsType Name -> LHsType Name -> (LHsType Name, [LHsType Name])
472 splitHsAppTys fun_ty arg_ty = split fun_ty [arg_ty]
473   where
474     split (L _ (HsAppTy f a)) as = split f (a:as)
475     split f                   as = (f,as)
476
477 mkHsAppTys :: LHsType Name -> [LHsType Name] -> HsType Name
478 mkHsAppTys fun_ty [] = pprPanic "mkHsAppTys" (ppr fun_ty)
479 mkHsAppTys fun_ty (arg_ty:arg_tys)
480   = foldl mk_app (HsAppTy fun_ty arg_ty) arg_tys
481   where
482     mk_app fun arg = HsAppTy (noLoc fun) arg    -- Add noLocs for inner nodes of
483                                                 -- the application; they are
484                                                 -- never used 
485
486 ---------------------------
487 splitFunKind :: SDoc -> Int -> TcKind -> [b] -> TcM ([(b,ExpKind)], TcKind)
488 splitFunKind _       _      fk [] = return ([], fk)
489 splitFunKind the_fun arg_no fk (arg:args)
490   = do { mb_fk <- matchExpectedFunKind fk
491        ; case mb_fk of
492             Nothing       -> failWithTc too_many_args 
493             Just (ak,fk') -> do { (aks, rk) <- splitFunKind the_fun (arg_no+1) fk' args
494                                 ; return ((arg, EK ak (EkArg the_fun arg_no)):aks, rk) } }
495   where
496     too_many_args = quotes the_fun <+>
497                     ptext (sLit "is applied to too many type arguments")
498
499 ---------------------------
500 kcHsContext :: LHsContext Name -> TcM (LHsContext Name)
501 kcHsContext ctxt = wrapLocM (mapM kcHsLPred) ctxt
502
503 kcHsLPred :: LHsPred Name -> TcM (LHsPred Name)
504 kcHsLPred = wrapLocM kcHsPred
505
506 kcHsPred :: HsPred Name -> TcM (HsPred Name)
507 kcHsPred pred = do      -- Checks that the result is a type kind
508     (pred', kind) <- kc_pred pred
509     checkExpectedKind pred kind ekOpen
510     return pred'
511     
512 ---------------------------
513 kc_pred :: HsPred Name -> TcM (HsPred Name, TcKind)     
514         -- Does *not* check for a saturated
515         -- application (reason: used from TcDeriv)
516 kc_pred (HsIParam name ty)
517   = do { (ty', kind) <- kc_lhs_type ty
518        ; return (HsIParam name ty', kind) }
519 kc_pred (HsClassP cls tys)
520   = do { kind <- kcClass cls
521        ; (tys', res_kind) <- kcApps cls kind tys
522        ; return (HsClassP cls tys', res_kind) }
523 kc_pred (HsEqualP ty1 ty2)
524   = do { (ty1', kind1) <- kc_lhs_type ty1
525        ; (ty2', kind2) <- kc_lhs_type ty2
526        ; checkExpectedKind ty2 kind2 (EK kind1 EkEqPred)
527        ; return (HsEqualP ty1' ty2', unliftedTypeKind) }
528
529 ---------------------------
530 kcTyVar :: Name -> TcM TcKind
531 kcTyVar name = do       -- Could be a tyvar or a tycon
532     traceTc "lk1" (ppr name)
533     thing <- tcLookup name
534     traceTc "lk2" (ppr name <+> ppr thing)
535     case thing of 
536         ATyVar _ ty             -> return (typeKind ty)
537         AThing kind             -> return kind
538         AGlobal (ATyCon tc)     -> return (tyConKind tc)
539         _                       -> wrongThingErr "type" thing name
540
541 kcClass :: Name -> TcM TcKind
542 kcClass cls = do        -- Must be a class
543     thing <- tcLookup cls
544     case thing of
545         AThing kind             -> return kind
546         AGlobal (AClass cls)    -> return (tyConKind (classTyCon cls))
547         _                       -> wrongThingErr "class" thing cls
548 \end{code}
549
550
551 %************************************************************************
552 %*                                                                      *
553                 Desugaring
554 %*                                                                      *
555 %************************************************************************
556
557 The type desugarer
558
559         * Transforms from HsType to Type
560         * Zonks any kinds
561
562 It cannot fail, and does no validity checking, except for 
563 structural matters, such as
564         (a) spurious ! annotations.
565         (b) a class used as a type
566
567 \begin{code}
568 dsHsType :: LHsType Name -> TcM Type
569 -- All HsTyVarBndrs in the intput type are kind-annotated
570 dsHsType ty = ds_type (unLoc ty)
571
572 ds_type :: HsType Name -> TcM Type
573 ds_type ty@(HsTyVar _)
574   = ds_app ty []
575
576 ds_type (HsParTy ty)            -- Remove the parentheses markers
577   = dsHsType ty
578
579 ds_type ty@(HsBangTy {})    -- No bangs should be here
580   = failWithTc (ptext (sLit "Unexpected strictness annotation:") <+> ppr ty)
581
582 ds_type ty@(HsRecTy {})     -- No bangs should be here
583   = failWithTc (ptext (sLit "Unexpected record type:") <+> ppr ty)
584
585 ds_type (HsKindSig ty _)
586   = dsHsType ty -- Kind checking done already
587
588 ds_type (HsListTy ty) = do
589     tau_ty <- dsHsType ty
590     checkWiredInTyCon listTyCon
591     return (mkListTy tau_ty)
592
593 ds_type (HsPArrTy ty) = do
594     tau_ty <- dsHsType ty
595     checkWiredInTyCon parrTyCon
596     return (mkPArrTy tau_ty)
597
598 ds_type (HsModalBoxType ecn ty) = do
599     tau_ty <- dsHsType ty
600     checkWiredInTyCon hetMetCodeTypeTyCon
601     return (mkHetMetCodeTypeTy (mkTyVar ecn ecKind) tau_ty)
602
603 ds_type (HsTupleTy boxity tys) = do
604     tau_tys <- dsHsTypes tys
605     checkWiredInTyCon tycon
606     return (mkTyConApp tycon tau_tys)
607   where
608     tycon = tupleTyCon boxity (length tys)
609
610 ds_type (HsFunTy ty1 ty2) = do
611     tau_ty1 <- dsHsType ty1
612     tau_ty2 <- dsHsType ty2
613     return (mkFunTy tau_ty1 tau_ty2)
614
615 ds_type (HsOpTy ty1 (L span op) ty2) = do
616     tau_ty1 <- dsHsType ty1
617     tau_ty2 <- dsHsType ty2
618     setSrcSpan span (ds_var_app op [tau_ty1,tau_ty2])
619
620 ds_type (HsNumTy n)
621   = ASSERT(n==1) do
622     tc <- tcLookupTyCon genUnitTyConName
623     return (mkTyConApp tc [])
624
625 ds_type ty@(HsAppTy _ _)
626   = ds_app ty []
627
628 ds_type (HsPredTy pred) = do
629     pred' <- dsHsPred pred
630     return (mkPredTy pred')
631
632 ds_type (HsForAllTy _ tv_names ctxt ty)
633   = tcTyVarBndrs tv_names               $ \ tyvars -> do
634     theta <- mapM dsHsLPred (unLoc ctxt)
635     tau <- dsHsType ty
636     return (mkSigmaTy tyvars theta tau)
637
638 ds_type (HsDocTy ty _)  -- Remove the doc comment
639   = dsHsType ty
640
641 ds_type (HsSpliceTy _ _ kind) 
642   = do { kind' <- zonkTcKindToKind kind
643        ; newFlexiTyVarTy kind' }
644
645 ds_type (HsQuasiQuoteTy {}) = panic "ds_type"   -- Eliminated by renamer
646 ds_type (HsCoreTy ty)       = return ty
647
648 dsHsTypes :: [LHsType Name] -> TcM [Type]
649 dsHsTypes arg_tys = mapM dsHsType arg_tys
650 \end{code}
651
652 Help functions for type applications
653 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
654
655 \begin{code}
656 ds_app :: HsType Name -> [LHsType Name] -> TcM Type
657 ds_app (HsAppTy ty1 ty2) tys
658   = ds_app (unLoc ty1) (ty2:tys)
659
660 ds_app ty tys = do
661     arg_tys <- dsHsTypes tys
662     case ty of
663         HsTyVar fun -> ds_var_app fun arg_tys
664         _           -> do fun_ty <- ds_type ty
665                           return (mkAppTys fun_ty arg_tys)
666
667 ds_var_app :: Name -> [Type] -> TcM Type
668 ds_var_app name arg_tys = do
669     thing <- tcLookup name
670     case thing of
671         ATyVar _ ty         -> return (mkAppTys ty arg_tys)
672         AGlobal (ATyCon tc) -> return (mkTyConApp tc arg_tys)
673         _                   -> wrongThingErr "type" thing name
674 \end{code}
675
676
677 Contexts
678 ~~~~~~~~
679
680 \begin{code}
681 dsHsLPred :: LHsPred Name -> TcM PredType
682 dsHsLPred pred = dsHsPred (unLoc pred)
683
684 dsHsPred :: HsPred Name -> TcM PredType
685 dsHsPred (HsClassP class_name tys)
686   = do { arg_tys <- dsHsTypes tys
687        ; clas <- tcLookupClass class_name
688        ; return (ClassP clas arg_tys)
689        }
690 dsHsPred (HsEqualP ty1 ty2)
691   = do { arg_ty1 <- dsHsType ty1
692        ; arg_ty2 <- dsHsType ty2
693        ; return (EqPred arg_ty1 arg_ty2)
694        }
695 dsHsPred (HsIParam name ty)
696   = do { arg_ty <- dsHsType ty
697        ; return (IParam name arg_ty)
698        }
699 \end{code}
700
701 \begin{code}
702 addKcTypeCtxt :: LHsType Name -> TcM a -> TcM a
703         -- Wrap a context around only if we want to show that contexts.  
704 addKcTypeCtxt (L _ (HsPredTy _)) thing = thing
705         -- Omit invisble ones and ones user's won't grok (HsPred p).
706 addKcTypeCtxt (L _ other_ty) thing = addErrCtxt (typeCtxt other_ty) thing
707
708 typeCtxt :: HsType Name -> SDoc
709 typeCtxt ty = ptext (sLit "In the type") <+> quotes (ppr ty)
710 \end{code}
711
712 %************************************************************************
713 %*                                                                      *
714                 Type-variable binders
715 %*                                                                      *
716 %************************************************************************
717
718
719 \begin{code}
720 kcHsTyVars :: [LHsTyVarBndr Name] 
721            -> ([LHsTyVarBndr Name] -> TcM r)    -- These binders are kind-annotated
722                                                 -- They scope over the thing inside
723            -> TcM r
724 kcHsTyVars tvs thing_inside
725   = do { kinded_tvs <- mapM (wrapLocM kcHsTyVar) tvs
726        ; tcExtendKindEnvTvs kinded_tvs thing_inside }
727
728 kcHsTyVar :: HsTyVarBndr Name -> TcM (HsTyVarBndr Name)
729         -- Return a *kind-annotated* binder, and a tyvar with a mutable kind in it      
730 kcHsTyVar (UserTyVar name _)  = UserTyVar name <$> newKindVar
731 kcHsTyVar tv@(KindedTyVar {}) = return tv
732
733 ------------------
734 tcTyVarBndrs :: [LHsTyVarBndr Name]     -- Kind-annotated binders, which need kind-zonking
735              -> ([TyVar] -> TcM r)
736              -> TcM r
737 -- Used when type-checking types/classes/type-decls
738 -- Brings into scope immutable TyVars, not mutable ones that require later zonking
739 tcTyVarBndrs bndrs thing_inside = do
740     tyvars <- mapM (zonk . unLoc) bndrs
741     tcExtendTyVarEnv tyvars (thing_inside tyvars)
742   where
743     zonk (UserTyVar name kind) = do { kind' <- zonkTcKindToKind kind
744                                     ; return (mkTyVar name kind') }
745     zonk (KindedTyVar name kind) = return (mkTyVar name kind)
746
747 -----------------------------------
748 tcDataKindSig :: Maybe Kind -> TcM [TyVar]
749 -- GADT decls can have a (perhaps partial) kind signature
750 --      e.g.  data T :: * -> * -> * where ...
751 -- This function makes up suitable (kinded) type variables for 
752 -- the argument kinds, and checks that the result kind is indeed *.
753 -- We use it also to make up argument type variables for for data instances.
754 tcDataKindSig Nothing = return []
755 tcDataKindSig (Just kind)
756   = do  { checkTc (isLiftedTypeKind res_kind) (badKindSig kind)
757         ; span <- getSrcSpanM
758         ; us   <- newUniqueSupply 
759         ; let uniqs = uniqsFromSupply us
760         ; return [ mk_tv span uniq str kind 
761                  | ((kind, str), uniq) <- arg_kinds `zip` dnames `zip` uniqs ] }
762   where
763     (arg_kinds, res_kind) = splitKindFunTys kind
764     mk_tv loc uniq str kind = mkTyVar name kind
765         where
766            name = mkInternalName uniq occ loc
767            occ  = mkOccName tvName str
768           
769     dnames = map ('$' :) names  -- Note [Avoid name clashes for associated data types]
770
771     names :: [String]
772     names = [ c:cs | cs <- "" : names, c <- ['a'..'z'] ] 
773
774 badKindSig :: Kind -> SDoc
775 badKindSig kind 
776  = hang (ptext (sLit "Kind signature on data type declaration has non-* return kind"))
777         2 (ppr kind)
778 \end{code}
779
780 Note [Avoid name clashes for associated data types]
781 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
782 Consider    class C a b where
783                data D b :: * -> *
784 When typechecking the decl for D, we'll invent an extra type variable for D,
785 to fill out its kind.  We *don't* want this type variable to be 'a', because
786 in an .hi file we'd get
787             class C a b where
788                data D b a 
789 which makes it look as if there are *two* type indices.  But there aren't!
790 So we use $a instead, which cannot clash with a user-written type variable.
791 Remember that type variable binders in interface files are just FastStrings,
792 not proper Names.
793
794 (The tidying phase can't help here because we don't tidy TyCons.  Another
795 alternative would be to record the number of indexing parameters in the 
796 interface file.)
797
798
799 %************************************************************************
800 %*                                                                      *
801                 Scoped type variables
802 %*                                                                      *
803 %************************************************************************
804
805
806 tcAddScopedTyVars is used for scoped type variables added by pattern
807 type signatures
808         e.g.  \ ((x::a), (y::a)) -> x+y
809 They never have explicit kinds (because this is source-code only)
810 They are mutable (because they can get bound to a more specific type).
811
812 Usually we kind-infer and expand type splices, and then
813 tupecheck/desugar the type.  That doesn't work well for scoped type
814 variables, because they scope left-right in patterns.  (e.g. in the
815 example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
816
817 The current not-very-good plan is to
818   * find all the types in the patterns
819   * find their free tyvars
820   * do kind inference
821   * bring the kinded type vars into scope
822   * BUT throw away the kind-checked type
823         (we'll kind-check it again when we type-check the pattern)
824
825 This is bad because throwing away the kind checked type throws away
826 its splices.  But too bad for now.  [July 03]
827
828 Historical note:
829     We no longer specify that these type variables must be univerally 
830     quantified (lots of email on the subject).  If you want to put that 
831     back in, you need to
832         a) Do a checkSigTyVars after thing_inside
833         b) More insidiously, don't pass in expected_ty, else
834            we unify with it too early and checkSigTyVars barfs
835            Instead you have to pass in a fresh ty var, and unify
836            it with expected_ty afterwards
837
838 \begin{code}
839 tcHsPatSigType :: UserTypeCtxt
840                -> LHsType Name          -- The type signature
841                -> TcM ([TyVar],         -- Newly in-scope type variables
842                         Type)           -- The signature
843 -- Used for type-checking type signatures in
844 -- (a) patterns           e.g  f (x::Int) = e
845 -- (b) result signatures  e.g. g x :: Int = e
846 -- (c) RULE forall bndrs  e.g. forall (x::Int). f x = x
847
848 tcHsPatSigType ctxt hs_ty 
849   = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
850     do  {       -- Find the type variables that are mentioned in the type
851                 -- but not already in scope.  These are the ones that
852                 -- should be bound by the pattern signature
853           in_scope <- getInLocalScope
854         ; let span = getLoc hs_ty
855               sig_tvs = userHsTyVarBndrs $ map (L span) $ 
856                         filterOut in_scope $
857                         nameSetToList (extractHsTyVars hs_ty)
858
859         ; (tyvars, sig_ty) <- tcHsQuantifiedType sig_tvs hs_ty
860         ; checkValidType ctxt sig_ty 
861         ; return (tyvars, sig_ty)
862       }
863
864 tcPatSig :: UserTypeCtxt
865          -> LHsType Name
866          -> TcSigmaType
867          -> TcM (TcType,           -- The type to use for "inside" the signature
868                  [(Name, TcType)], -- The new bit of type environment, binding
869                                    -- the scoped type variables
870                  HsWrapper)        -- Coercion due to unification with actual ty
871                                    -- Of shape:  res_ty ~ sig_ty
872 tcPatSig ctxt sig res_ty
873   = do  { (sig_tvs, sig_ty) <- tcHsPatSigType ctxt sig
874         -- sig_tvs are the type variables free in 'sig', 
875         -- and not already in scope. These are the ones
876         -- that should be brought into scope
877
878         ; if null sig_tvs then do {
879                 -- The type signature binds no type variables, 
880                 -- and hence is rigid, so use it to zap the res_ty
881                   wrap <- tcSubType PatSigOrigin ctxt res_ty sig_ty
882                 ; return (sig_ty, [], wrap)
883
884         } else do {
885                 -- Type signature binds at least one scoped type variable
886         
887                 -- A pattern binding cannot bind scoped type variables
888                 -- The renamer fails with a name-out-of-scope error 
889                 -- if a pattern binding tries to bind a type variable,
890                 -- So we just have an ASSERT here
891         ; let in_pat_bind = case ctxt of
892                                 BindPatSigCtxt -> True
893                                 _              -> False
894         ; ASSERT( not in_pat_bind || null sig_tvs ) return ()
895
896                 -- Check that all newly-in-scope tyvars are in fact
897                 -- constrained by the pattern.  This catches tiresome
898                 -- cases like   
899                 --      type T a = Int
900                 --      f :: Int -> Int
901                 --      f (x :: T a) = ...
902                 -- Here 'a' doesn't get a binding.  Sigh
903         ; let bad_tvs = filterOut (`elemVarSet` exactTyVarsOfType sig_ty) sig_tvs
904         ; checkTc (null bad_tvs) (badPatSigTvs sig_ty bad_tvs)
905
906         -- Now do a subsumption check of the pattern signature against res_ty
907         ; sig_tvs' <- tcInstSigTyVars sig_tvs
908         ; let sig_ty' = substTyWith sig_tvs sig_tv_tys' sig_ty
909               sig_tv_tys' = mkTyVarTys sig_tvs'
910         ; wrap <- tcSubType PatSigOrigin ctxt res_ty sig_ty'
911
912         -- Check that each is bound to a distinct type variable,
913         -- and one that is not already in scope
914         ; binds_in_scope <- getScopedTyVarBinds
915         ; let tv_binds = map tyVarName sig_tvs `zip` sig_tv_tys'
916         ; check binds_in_scope tv_binds
917         
918         -- Phew!
919         ; return (sig_ty', tv_binds, wrap)
920         } }
921   where
922     check _ [] = return ()
923     check in_scope ((n,ty):rest) = do { check_one in_scope n ty
924                                       ; check ((n,ty):in_scope) rest }
925
926     check_one in_scope n ty
927         = checkTc (null dups) (dupInScope n (head dups) ty)
928                 -- Must not bind to the same type variable
929                 -- as some other in-scope type variable
930         where
931           dups = [n' | (n',ty') <- in_scope, tcEqType ty' ty]
932 \end{code}
933
934
935 %************************************************************************
936 %*                                                                      *
937         Checking kinds
938 %*                                                                      *
939 %************************************************************************
940
941 We would like to get a decent error message from
942   (a) Under-applied type constructors
943              f :: (Maybe, Maybe)
944   (b) Over-applied type constructors
945              f :: Int x -> Int x
946
947 \begin{code}
948 -- The ExpKind datatype means "expected kind" and contains 
949 -- some info about just why that kind is expected, to improve
950 -- the error message on a mis-match
951 data ExpKind = EK TcKind EkCtxt
952 data EkCtxt  = EkUnk            -- Unknown context
953              | EkEqPred         -- Second argument of an equality predicate
954              | EkKindSig        -- Kind signature
955              | EkArg SDoc Int   -- Function, arg posn, expected kind
956
957
958 ekLifted, ekOpen :: ExpKind
959 ekLifted = EK liftedTypeKind EkUnk
960 ekOpen   = EK openTypeKind   EkUnk
961
962 checkExpectedKind :: Outputable a => a -> TcKind -> ExpKind -> TcM ()
963 -- A fancy wrapper for 'unifyKind', which tries
964 -- to give decent error messages.
965 --      (checkExpectedKind ty act_kind exp_kind)
966 -- checks that the actual kind act_kind is compatible
967 --      with the expected kind exp_kind
968 -- The first argument, ty, is used only in the error message generation
969 checkExpectedKind ty act_kind (EK exp_kind ek_ctxt)
970   | act_kind `isSubKind` exp_kind -- Short cut for a very common case
971   = return ()
972   | otherwise = do
973     (_errs, mb_r) <- tryTc (unifyKind exp_kind act_kind)
974     case mb_r of
975         Just _  -> return ()  -- Unification succeeded
976         Nothing -> do
977
978         -- So there's definitely an error
979         -- Now to find out what sort
980            exp_kind <- zonkTcKind exp_kind
981            act_kind <- zonkTcKind act_kind
982
983            env0 <- tcInitTidyEnv
984            let (exp_as, _) = splitKindFunTys exp_kind
985                (act_as, _) = splitKindFunTys act_kind
986                n_exp_as = length exp_as
987                n_act_as = length act_as
988
989                (env1, tidy_exp_kind) = tidyKind env0 exp_kind
990                (env2, tidy_act_kind) = tidyKind env1 act_kind
991
992                err | n_exp_as < n_act_as     -- E.g. [Maybe]
993                    = quotes (ppr ty) <+> ptext (sLit "is not applied to enough type arguments")
994
995                      -- Now n_exp_as >= n_act_as. In the next two cases,
996                      -- n_exp_as == 0, and hence so is n_act_as
997                    | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
998                    = ptext (sLit "Expecting a lifted type, but") <+> quotes (ppr ty)
999                        <+> ptext (sLit "is unlifted")
1000
1001                    | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1002                    = ptext (sLit "Expecting an unlifted type, but") <+> quotes (ppr ty)
1003                        <+> ptext (sLit "is lifted")
1004
1005                    | otherwise               -- E.g. Monad [Int]
1006                    = ptext (sLit "Kind mis-match")
1007
1008                more_info = sep [ expected_herald ek_ctxt <+> ptext (sLit "kind") 
1009                                     <+> quotes (pprKind tidy_exp_kind) <> comma,
1010                                  ptext (sLit "but") <+> quotes (ppr ty) <+>
1011                                      ptext (sLit "has kind") <+> quotes (pprKind tidy_act_kind)]
1012
1013                expected_herald EkUnk     = ptext (sLit "Expected")
1014                expected_herald EkKindSig = ptext (sLit "An enclosing kind signature specified")
1015                expected_herald EkEqPred  = ptext (sLit "The left argument of the equality predicate had")
1016                expected_herald (EkArg fun arg_no)
1017                  = ptext (sLit "The") <+> speakNth arg_no <+> ptext (sLit "argument of")
1018                    <+> quotes fun <+> ptext (sLit ("should have"))
1019
1020            failWithTcM (env2, err $$ more_info)
1021 \end{code}
1022
1023 %************************************************************************
1024 %*                                                                      *
1025                 Scoped type variables
1026 %*                                                                      *
1027 %************************************************************************
1028
1029 \begin{code}
1030 pprHsSigCtxt :: UserTypeCtxt -> LHsType Name -> SDoc
1031 pprHsSigCtxt ctxt hs_ty = sep [ ptext (sLit "In") <+> pprUserTypeCtxt ctxt <> colon, 
1032                                  nest 2 (pp_sig ctxt) ]
1033   where
1034     pp_sig (FunSigCtxt n)  = pp_n_colon n
1035     pp_sig (ConArgCtxt n)  = pp_n_colon n
1036     pp_sig (ForSigCtxt n)  = pp_n_colon n
1037     pp_sig _               = ppr (unLoc hs_ty)
1038
1039     pp_n_colon n = ppr n <+> dcolon <+> ppr (unLoc hs_ty)
1040
1041 badPatSigTvs :: TcType -> [TyVar] -> SDoc
1042 badPatSigTvs sig_ty bad_tvs
1043   = vcat [ fsep [ptext (sLit "The type variable") <> plural bad_tvs, 
1044                  quotes (pprWithCommas ppr bad_tvs), 
1045                  ptext (sLit "should be bound by the pattern signature") <+> quotes (ppr sig_ty),
1046                  ptext (sLit "but are actually discarded by a type synonym") ]
1047          , ptext (sLit "To fix this, expand the type synonym") 
1048          , ptext (sLit "[Note: I hope to lift this restriction in due course]") ]
1049
1050 dupInScope :: Name -> Name -> Type -> SDoc
1051 dupInScope n n' _
1052   = hang (ptext (sLit "The scoped type variables") <+> quotes (ppr n) <+> ptext (sLit "and") <+> quotes (ppr n'))
1053        2 (vcat [ptext (sLit "are bound to the same type (variable)"),
1054                 ptext (sLit "Distinct scoped type variables must be distinct")])
1055
1056 wrongPredErr :: HsPred Name -> TcM (HsType Name, TcKind)
1057 wrongPredErr pred = failWithTc (text "Predicate used as a type:" <+> ppr pred)
1058 \end{code}
1059