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