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