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