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