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