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