Monadify typecheck/TcHsType: use do, return and standard monad functions
[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 {-# OPTIONS -w #-}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
13 -- for details
14
15 module TcHsType (
16         tcHsSigType, tcHsDeriv, 
17         tcHsInstHead, tcHsQuantifiedType,
18         UserTypeCtxt(..), 
19
20                 -- Kind checking
21         kcHsTyVars, kcHsSigType, kcHsLiftedSigType, 
22         kcCheckHsType, kcHsContext, kcHsType, 
23         
24                 -- Typechecking kinded types
25         tcHsKindedContext, tcHsKindedType, tcHsBangType,
26         tcTyVarBndrs, dsHsType, tcLHsConResTy,
27         tcDataKindSig,
28
29                 -- Pattern type signatures
30         tcHsPatSigType, tcPatSig
31    ) where
32
33 #include "HsVersions.h"
34
35 import HsSyn
36 import RnHsSyn
37 import TcRnMonad
38 import TcEnv
39 import TcMType
40 import TcUnify
41 import TcIface
42 import TcType
43 import {- Kind parts of -} Type
44 import Var
45 import TyCon
46 import Class
47 import Name
48 import OccName
49 import NameSet
50 import PrelNames
51 import TysWiredIn
52 import BasicTypes
53 import SrcLoc
54 import UniqSupply
55 import Outputable
56
57 import Control.Monad
58 \end{code}
59
60
61         ----------------------------
62                 General notes
63         ----------------------------
64
65 Generally speaking we now type-check types in three phases
66
67   1.  kcHsType: kind check the HsType
68         *includes* performing any TH type splices;
69         so it returns a translated, and kind-annotated, type
70
71   2.  dsHsType: convert from HsType to Type:
72         perform zonking
73         expand type synonyms [mkGenTyApps]
74         hoist the foralls [tcHsType]
75
76   3.  checkValidType: check the validity of the resulting type
77
78 Often these steps are done one after the other (tcHsSigType).
79 But in mutually recursive groups of type and class decls we do
80         1 kind-check the whole group
81         2 build TyCons/Classes in a knot-tied way
82         3 check the validity of types in the now-unknotted TyCons/Classes
83
84 For example, when we find
85         (forall a m. m a -> m a)
86 we bind a,m to kind varibles and kind-check (m a -> m a).  This makes
87 a get kind *, and m get kind *->*.  Now we typecheck (m a -> m a) in
88 an environment that binds a and m suitably.
89
90 The kind checker passed to tcHsTyVars needs to look at enough to
91 establish the kind of the tyvar:
92   * For a group of type and class decls, it's just the group, not
93         the rest of the program
94   * For a tyvar bound in a pattern type signature, its the types
95         mentioned in the other type signatures in that bunch of patterns
96   * For a tyvar bound in a RULE, it's the type signatures on other
97         universally quantified variables in the rule
98
99 Note that this may occasionally give surprising results.  For example:
100
101         data T a b = MkT (a b)
102
103 Here we deduce                  a::*->*,       b::*
104 But equally valid would be      a::(*->*)-> *, b::*->*
105
106
107 Validity checking
108 ~~~~~~~~~~~~~~~~~
109 Some of the validity check could in principle be done by the kind checker, 
110 but not all:
111
112 - During desugaring, we normalise by expanding type synonyms.  Only
113   after this step can we check things like type-synonym saturation
114   e.g.  type T k = k Int
115         type S a = a
116   Then (T S) is ok, because T is saturated; (T S) expands to (S Int);
117   and then S is saturated.  This is a GHC extension.
118
119 - Similarly, also a GHC extension, we look through synonyms before complaining
120   about the form of a class or instance declaration
121
122 - Ambiguity checks involve functional dependencies, and it's easier to wait
123   until knots have been resolved before poking into them
124
125 Also, in a mutually recursive group of types, we can't look at the TyCon until we've
126 finished building the loop.  So to keep things simple, we postpone most validity
127 checking until step (3).
128
129 Knot tying
130 ~~~~~~~~~~
131 During step (1) we might fault in a TyCon defined in another module, and it might
132 (via a loop) refer back to a TyCon defined in this module. So when we tie a big
133 knot around type declarations with ARecThing, so that the fault-in code can get
134 the TyCon being defined.
135
136
137 %************************************************************************
138 %*                                                                      *
139 \subsection{Checking types}
140 %*                                                                      *
141 %************************************************************************
142
143 \begin{code}
144 tcHsSigType :: UserTypeCtxt -> LHsType Name -> TcM Type
145   -- Do kind checking, and hoist for-alls to the top
146   -- NB: it's important that the foralls that come from the top-level
147   --     HsForAllTy in hs_ty occur *first* in the returned type.
148   --     See Note [Scoped] with TcSigInfo
149 tcHsSigType ctxt hs_ty 
150   = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
151     do  { kinded_ty <- kcTypeType hs_ty
152         ; ty <- tcHsKindedType kinded_ty
153         ; checkValidType ctxt ty        
154         ; return ty }
155
156 tcHsInstHead :: LHsType Name -> TcM ([TyVar], ThetaType, Type)
157 -- Typecheck an instance head.  We can't use 
158 -- tcHsSigType, because it's not a valid user type.
159 tcHsInstHead hs_ty
160   = do  { kinded_ty <- kcHsSigType hs_ty
161         ; poly_ty   <- tcHsKindedType kinded_ty
162         ; return (tcSplitSigmaTy poly_ty) }
163
164 tcHsQuantifiedType :: [LHsTyVarBndr Name] -> LHsType Name -> TcM ([TyVar], Type)
165 -- Behave very like type-checking (HsForAllTy sig_tvs hs_ty),
166 -- except that we want to keep the tvs separate
167 tcHsQuantifiedType tv_names hs_ty
168   = kcHsTyVars tv_names $ \ tv_names' ->
169     do  { kc_ty <- kcHsSigType hs_ty
170         ; tcTyVarBndrs tv_names' $ \ tvs ->
171     do  { ty <- dsHsType kc_ty
172         ; return (tvs, ty) } }
173
174 -- Used for the deriving(...) items
175 tcHsDeriv :: LHsType Name -> TcM ([TyVar], Class, [Type])
176 tcHsDeriv = addLocM (tc_hs_deriv [])
177
178 tc_hs_deriv tv_names (HsPredTy (HsClassP cls_name hs_tys))
179   = kcHsTyVars tv_names                 $ \ tv_names' ->
180     do  { cls_kind <- kcClass cls_name
181         ; (tys, res_kind) <- kcApps cls_kind (ppr cls_name) hs_tys
182         ; tcTyVarBndrs tv_names'        $ \ tyvars ->
183     do  { arg_tys <- dsHsTypes tys
184         ; cls <- tcLookupClass cls_name
185         ; return (tyvars, cls, arg_tys) }}
186
187 tc_hs_deriv tv_names1 (HsForAllTy _ tv_names2 (L _ []) (L _ ty))
188   =     -- Funny newtype deriving form
189         --      forall a. C [a]
190         -- where C has arity 2.  Hence can't use regular functions
191     tc_hs_deriv (tv_names1 ++ tv_names2) ty
192
193 tc_hs_deriv _ other
194   = failWithTc (ptext SLIT("Illegal deriving item") <+> ppr other)
195 \end{code}
196
197         These functions are used during knot-tying in
198         type and class declarations, when we have to
199         separate kind-checking, desugaring, and validity checking
200
201 \begin{code}
202 kcHsSigType, kcHsLiftedSigType :: LHsType Name -> TcM (LHsType Name)
203         -- Used for type signatures
204 kcHsSigType ty       = kcTypeType ty
205 kcHsLiftedSigType ty = kcLiftedType ty
206
207 tcHsKindedType :: LHsType Name -> TcM Type
208   -- Don't do kind checking, nor validity checking.
209   -- This is used in type and class decls, where kinding is
210   -- done in advance, and validity checking is done later
211   -- [Validity checking done later because of knot-tying issues.]
212 tcHsKindedType hs_ty = dsHsType hs_ty
213
214 tcHsBangType :: LHsType Name -> TcM Type
215 -- Permit a bang, but discard it
216 tcHsBangType (L span (HsBangTy b ty)) = tcHsKindedType ty
217 tcHsBangType ty                       = tcHsKindedType ty
218
219 tcHsKindedContext :: LHsContext Name -> TcM ThetaType
220 -- Used when we are expecting a ClassContext (i.e. no implicit params)
221 -- Does not do validity checking, like tcHsKindedType
222 tcHsKindedContext hs_theta = addLocM (mapM dsHsLPred) hs_theta
223 \end{code}
224
225
226 %************************************************************************
227 %*                                                                      *
228                 The main kind checker: kcHsType
229 %*                                                                      *
230 %************************************************************************
231         
232         First a couple of simple wrappers for kcHsType
233
234 \begin{code}
235 ---------------------------
236 kcLiftedType :: LHsType Name -> TcM (LHsType Name)
237 -- The type ty must be a *lifted* *type*
238 kcLiftedType ty = kcCheckHsType ty liftedTypeKind
239     
240 ---------------------------
241 kcTypeType :: LHsType Name -> TcM (LHsType Name)
242 -- The type ty must be a *type*, but it can be lifted or 
243 -- unlifted or an unboxed tuple.
244 kcTypeType ty = kcCheckHsType ty openTypeKind
245
246 ---------------------------
247 kcCheckHsType :: LHsType Name -> TcKind -> TcM (LHsType Name)
248 -- Check that the type has the specified kind
249 -- Be sure to use checkExpectedKind, rather than simply unifying 
250 -- with OpenTypeKind, because it gives better error messages
251 kcCheckHsType (L span ty) exp_kind 
252   = setSrcSpan span                             $
253     do  { (ty', act_kind) <- add_ctxt ty (kc_hs_type ty)
254                 -- Add the context round the inner check only
255                 -- because checkExpectedKind already mentions
256                 -- 'ty' by name in any error message
257
258         ; checkExpectedKind (strip ty) act_kind exp_kind
259         ; return (L span ty') }
260   where
261         -- Wrap a context around only if we want to show that contexts.  
262     add_ctxt (HsPredTy p)                thing = thing
263         -- Omit invisble ones and ones user's won't grok (HsPred p).
264     add_ctxt (HsForAllTy _ _ (L _ []) _) thing = thing
265         -- Omit wrapping if the theta-part is empty
266         -- Reason: the recursive call to kcLiftedType, in the ForAllTy
267         --         case of kc_hs_type, will do the wrapping instead
268         --         and we don't want to duplicate
269     add_ctxt other_ty thing = addErrCtxt (typeCtxt other_ty) thing
270
271         -- We infer the kind of the type, and then complain if it's
272         -- not right.  But we don't want to complain about
273         --      (ty) or !(ty) or forall a. ty
274         -- when the real difficulty is with the 'ty' part.
275     strip (HsParTy (L _ ty))          = strip ty
276     strip (HsBangTy _ (L _ ty))       = strip ty
277     strip (HsForAllTy _ _ _ (L _ ty)) = strip ty
278     strip ty                          = ty
279 \end{code}
280
281         Here comes the main function
282
283 \begin{code}
284 kcHsType :: LHsType Name -> TcM (LHsType Name, TcKind)
285 kcHsType ty = wrapLocFstM kc_hs_type ty
286 -- kcHsType *returns* the kind of the type, rather than taking an expected
287 -- kind as argument as tcExpr does.  
288 -- Reasons: 
289 --      (a) the kind of (->) is
290 --              forall bx1 bx2. Type bx1 -> Type bx2 -> Type Boxed
291 --          so we'd need to generate huge numbers of bx variables.
292 --      (b) kinds are so simple that the error messages are fine
293 --
294 -- The translated type has explicitly-kinded type-variable binders
295
296 kc_hs_type (HsParTy ty) = do
297    (ty', kind) <- kcHsType ty
298    return (HsParTy ty', kind)
299
300 kc_hs_type (HsTyVar name) = do
301     kind <- kcTyVar name
302     return (HsTyVar name, kind)
303
304 kc_hs_type (HsListTy ty) = do
305     ty' <- kcLiftedType ty
306     return (HsListTy ty', liftedTypeKind)
307
308 kc_hs_type (HsPArrTy ty) = do
309     ty' <- kcLiftedType ty
310     return (HsPArrTy ty', liftedTypeKind)
311
312 kc_hs_type (HsNumTy n)
313    = return (HsNumTy n, liftedTypeKind)
314
315 kc_hs_type (HsKindSig ty k) = do
316     ty' <- kcCheckHsType ty k
317     return (HsKindSig ty' k, k)
318
319 kc_hs_type (HsTupleTy Boxed tys) = do
320     tys' <- mapM kcLiftedType tys
321     return (HsTupleTy Boxed tys', liftedTypeKind)
322
323 kc_hs_type (HsTupleTy Unboxed tys) = do
324     tys' <- mapM kcTypeType tys
325     return (HsTupleTy Unboxed tys', ubxTupleKind)
326
327 kc_hs_type (HsFunTy ty1 ty2) = do
328     ty1' <- kcCheckHsType ty1 argTypeKind
329     ty2' <- kcTypeType ty2
330     return (HsFunTy ty1' ty2', liftedTypeKind)
331
332 kc_hs_type ty@(HsOpTy ty1 op ty2) = do
333     op_kind <- addLocM kcTyVar op
334     ([ty1',ty2'], res_kind) <- kcApps op_kind (ppr op) [ty1,ty2]
335     return (HsOpTy ty1' op ty2', res_kind)
336
337 kc_hs_type ty@(HsAppTy ty1 ty2) = do
338     (fun_ty', fun_kind) <- kcHsType fun_ty
339     ((arg_ty':arg_tys'), res_kind) <- kcApps fun_kind (ppr fun_ty) arg_tys
340     return (foldl mk_app (HsAppTy fun_ty' arg_ty') arg_tys', res_kind)
341   where
342     (fun_ty, arg_tys) = split ty1 [ty2]
343     split (L _ (HsAppTy f a)) as = split f (a:as)
344     split f                   as = (f,as)
345     mk_app fun arg = HsAppTy (noLoc fun) arg    -- Add noLocs for inner nodes of
346                                                 -- the application; they are
347                                                 -- never used 
348
349 kc_hs_type ty@(HsPredTy (HsEqualP _ _))
350   = wrongEqualityErr
351
352 kc_hs_type (HsPredTy pred) = do
353     pred' <- kcHsPred pred
354     return (HsPredTy pred', liftedTypeKind)
355
356 kc_hs_type (HsForAllTy exp tv_names context ty)
357   = kcHsTyVars tv_names         $ \ tv_names' ->
358     do  { ctxt' <- kcHsContext context
359         ; ty'   <- kcLiftedType ty
360              -- The body of a forall is usually a type, but in principle
361              -- there's no reason to prohibit *unlifted* types.
362              -- In fact, GHC can itself construct a function with an
363              -- unboxed tuple inside a for-all (via CPR analyis; see 
364              -- typecheck/should_compile/tc170)
365              --
366              -- Still, that's only for internal interfaces, which aren't
367              -- kind-checked, so we only allow liftedTypeKind here
368
369         ; return (HsForAllTy exp tv_names' ctxt' ty', liftedTypeKind) }
370
371 kc_hs_type (HsBangTy b ty) = do
372     (ty', kind) <- kcHsType ty
373     return (HsBangTy b ty', kind)
374
375 kc_hs_type ty@(HsSpliceTy _)
376   = failWithTc (ptext SLIT("Unexpected type splice:") <+> ppr ty)
377
378 -- remove the doc nodes here, no need to worry about the location since
379 -- its the same for a doc node and it's child type node
380 kc_hs_type (HsDocTy ty _)
381   = kc_hs_type (unLoc ty) 
382
383 ---------------------------
384 kcApps :: TcKind                        -- Function kind
385        -> SDoc                          -- Function 
386        -> [LHsType Name]                -- Arg types
387        -> TcM ([LHsType Name], TcKind)  -- Kind-checked args
388 kcApps fun_kind ppr_fun args = do
389     (arg_kinds, res_kind) <- split_fk fun_kind (length args)
390     args' <- zipWithM kc_arg args arg_kinds
391     return (args', res_kind)
392   where
393     split_fk fk 0 = return ([], fk)
394     split_fk fk n = do mb_fk <- unifyFunKind fk
395                        case mb_fk of
396                           Nothing       -> failWithTc too_many_args 
397                           Just (ak,fk') -> do (aks, rk) <- split_fk fk' (n-1)
398                                               return (ak:aks, rk)
399
400     kc_arg arg arg_kind = kcCheckHsType arg arg_kind
401
402     too_many_args = ptext SLIT("Kind error:") <+> quotes ppr_fun <+>
403                     ptext SLIT("is applied to too many type arguments")
404
405 ---------------------------
406 kcHsContext :: LHsContext Name -> TcM (LHsContext Name)
407 kcHsContext ctxt = wrapLocM (mapM kcHsLPred) ctxt
408
409 kcHsLPred :: LHsPred Name -> TcM (LHsPred Name)
410 kcHsLPred = wrapLocM kcHsPred
411
412 kcHsPred :: HsPred Name -> TcM (HsPred Name)
413 kcHsPred pred = do      -- Checks that the result is of kind liftedType
414     (pred', kind) <- kc_pred pred
415     checkExpectedKind pred kind liftedTypeKind
416     return pred'
417     
418 ---------------------------
419 kc_pred :: HsPred Name -> TcM (HsPred Name, TcKind)     
420         -- Does *not* check for a saturated
421         -- application (reason: used from TcDeriv)
422 kc_pred pred@(HsIParam name ty)
423   = do { (ty', kind) <- kcHsType ty
424        ; return (HsIParam name ty', kind)
425        }
426 kc_pred pred@(HsClassP cls tys)
427   = do { kind <- kcClass cls
428        ; (tys', res_kind) <- kcApps kind (ppr cls) tys
429        ; return (HsClassP cls tys', res_kind)
430        }
431 kc_pred pred@(HsEqualP ty1 ty2)
432   = do { (ty1', kind1) <- kcHsType ty1
433 --       ; checkExpectedKind ty1 kind1 liftedTypeKind
434        ; (ty2', kind2) <- kcHsType ty2
435 --       ; checkExpectedKind ty2 kind2 liftedTypeKind
436        ; checkExpectedKind ty2 kind2 kind1
437        ; return (HsEqualP ty1' ty2', liftedTypeKind)
438        }
439
440 ---------------------------
441 kcTyVar :: Name -> TcM TcKind
442 kcTyVar name = do       -- Could be a tyvar or a tycon
443     traceTc (text "lk1" <+> ppr name)
444     thing <- tcLookup name
445     traceTc (text "lk2" <+> ppr name <+> ppr thing)
446     case thing of 
447         ATyVar _ ty             -> return (typeKind ty)
448         AThing kind             -> return kind
449         AGlobal (ATyCon tc)     -> return (tyConKind tc)
450         other                   -> wrongThingErr "type" thing name
451
452 kcClass :: Name -> TcM TcKind
453 kcClass cls = do        -- Must be a class
454     thing <- tcLookup cls
455     case thing of
456         AThing kind             -> return kind
457         AGlobal (AClass cls)    -> return (tyConKind (classTyCon cls))
458         other                   -> wrongThingErr "class" thing cls
459 \end{code}
460
461
462 %************************************************************************
463 %*                                                                      *
464                 Desugaring
465 %*                                                                      *
466 %************************************************************************
467
468 The type desugarer
469
470         * Transforms from HsType to Type
471         * Zonks any kinds
472
473 It cannot fail, and does no validity checking, except for 
474 structural matters, such as
475         (a) spurious ! annotations.
476         (b) a class used as a type
477
478 \begin{code}
479 dsHsType :: LHsType Name -> TcM Type
480 -- All HsTyVarBndrs in the intput type are kind-annotated
481 dsHsType ty = ds_type (unLoc ty)
482
483 ds_type ty@(HsTyVar name)
484   = ds_app ty []
485
486 ds_type (HsParTy ty)            -- Remove the parentheses markers
487   = dsHsType ty
488
489 ds_type ty@(HsBangTy _ _)       -- No bangs should be here
490   = failWithTc (ptext SLIT("Unexpected strictness annotation:") <+> ppr ty)
491
492 ds_type (HsKindSig ty k)
493   = dsHsType ty -- Kind checking done already
494
495 ds_type (HsListTy ty) = do
496     tau_ty <- dsHsType ty
497     checkWiredInTyCon listTyCon
498     return (mkListTy tau_ty)
499
500 ds_type (HsPArrTy ty) = do
501     tau_ty <- dsHsType ty
502     checkWiredInTyCon parrTyCon
503     return (mkPArrTy tau_ty)
504
505 ds_type (HsTupleTy boxity tys) = do
506     tau_tys <- dsHsTypes tys
507     checkWiredInTyCon tycon
508     return (mkTyConApp tycon tau_tys)
509   where
510     tycon = tupleTyCon boxity (length tys)
511
512 ds_type (HsFunTy ty1 ty2) = do
513     tau_ty1 <- dsHsType ty1
514     tau_ty2 <- dsHsType ty2
515     return (mkFunTy tau_ty1 tau_ty2)
516
517 ds_type (HsOpTy ty1 (L span op) ty2) = do
518     tau_ty1 <- dsHsType ty1
519     tau_ty2 <- dsHsType ty2
520     setSrcSpan span (ds_var_app op [tau_ty1,tau_ty2])
521
522 ds_type (HsNumTy n)
523   = ASSERT(n==1) do
524     tc <- tcLookupTyCon genUnitTyConName
525     return (mkTyConApp tc [])
526
527 ds_type ty@(HsAppTy _ _)
528   = ds_app ty []
529
530 ds_type (HsPredTy pred) = do
531     pred' <- dsHsPred pred
532     return (mkPredTy pred')
533
534 ds_type full_ty@(HsForAllTy exp tv_names ctxt ty)
535   = tcTyVarBndrs tv_names               $ \ tyvars -> do
536     theta <- mapM dsHsLPred (unLoc ctxt)
537     tau <- dsHsType ty
538     return (mkSigmaTy tyvars theta tau)
539
540 ds_type (HsSpliceTy {}) = panic "ds_type: HsSpliceTy"
541
542 ds_type (HsDocTy ty _)  -- Remove the doc comment
543   = dsHsType ty
544
545 dsHsTypes arg_tys = mapM dsHsType arg_tys
546 \end{code}
547
548 Help functions for type applications
549 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
550
551 \begin{code}
552 ds_app :: HsType Name -> [LHsType Name] -> TcM Type
553 ds_app (HsAppTy ty1 ty2) tys
554   = ds_app (unLoc ty1) (ty2:tys)
555
556 ds_app ty tys = do
557     arg_tys <- dsHsTypes tys
558     case ty of
559         HsTyVar fun -> ds_var_app fun arg_tys
560         other       -> do fun_ty <- ds_type ty
561                           return (mkAppTys fun_ty arg_tys)
562
563 ds_var_app :: Name -> [Type] -> TcM Type
564 ds_var_app name arg_tys = do
565     thing <- tcLookup name
566     case thing of
567         ATyVar _ ty         -> return (mkAppTys ty arg_tys)
568         AGlobal (ATyCon tc) -> return (mkTyConApp tc arg_tys)
569         other               -> wrongThingErr "type" thing name
570 \end{code}
571
572
573 Contexts
574 ~~~~~~~~
575
576 \begin{code}
577 dsHsLPred :: LHsPred Name -> TcM PredType
578 dsHsLPred pred = dsHsPred (unLoc pred)
579
580 dsHsPred pred@(HsClassP class_name tys)
581   = do { arg_tys <- dsHsTypes tys
582        ; clas <- tcLookupClass class_name
583        ; return (ClassP clas arg_tys)
584        }
585 dsHsPred pred@(HsEqualP ty1 ty2)
586   = do { arg_ty1 <- dsHsType ty1
587        ; arg_ty2 <- dsHsType ty2
588        ; return (EqPred arg_ty1 arg_ty2)
589        }
590 dsHsPred (HsIParam name ty)
591   = do { arg_ty <- dsHsType ty
592        ; return (IParam name arg_ty)
593        }
594 \end{code}
595
596 GADT constructor signatures
597
598 \begin{code}
599 tcLHsConResTy :: LHsType Name -> TcM (TyCon, [TcType])
600 tcLHsConResTy res_ty
601   = addErrCtxt (gadtResCtxt res_ty) $
602     case get_largs res_ty [] of
603            (HsTyVar tc_name, args) 
604               -> do { args' <- mapM dsHsType args
605                     ; thing <- tcLookup tc_name
606                     ; case thing of
607                         AGlobal (ATyCon tc) -> return (tc, args')
608                         other -> failWithTc (badGadtDecl res_ty) }
609            other -> failWithTc (badGadtDecl res_ty)
610   where
611         -- We can't call dsHsType on res_ty, and then do tcSplitTyConApp_maybe
612         -- because that causes a black hole, and for good reason.  Building
613         -- the type means expanding type synonyms, and we can't do that
614         -- inside the "knot".  So we have to work by steam.
615     get_largs (L _ ty) args = get_args ty args
616     get_args (HsAppTy fun arg)            args = get_largs fun (arg:args)
617     get_args (HsParTy ty)                 args = get_largs ty  args
618     get_args (HsOpTy ty1 (L span tc) ty2) args = (HsTyVar tc, ty1:ty2:args)
619     get_args ty                           args = (ty, args)
620
621 gadtResCtxt ty
622   = hang (ptext SLIT("In the result type of a data constructor:"))
623        2 (ppr ty)
624 badGadtDecl ty
625   = hang (ptext SLIT("Malformed constructor result type:"))
626        2 (ppr ty)
627
628 typeCtxt ty = ptext SLIT("In the type") <+> quotes (ppr ty)
629 \end{code}
630
631 %************************************************************************
632 %*                                                                      *
633                 Type-variable binders
634 %*                                                                      *
635 %************************************************************************
636
637
638 \begin{code}
639 kcHsTyVars :: [LHsTyVarBndr Name] 
640            -> ([LHsTyVarBndr Name] -> TcM r)    -- These binders are kind-annotated
641                                                 -- They scope over the thing inside
642            -> TcM r
643 kcHsTyVars tvs thing_inside  = do
644     bndrs <- mapM (wrapLocM kcHsTyVar) tvs
645     tcExtendKindEnvTvs bndrs (thing_inside bndrs)
646
647 kcHsTyVar :: HsTyVarBndr Name -> TcM (HsTyVarBndr Name)
648         -- Return a *kind-annotated* binder, and a tyvar with a mutable kind in it      
649 kcHsTyVar (UserTyVar name)        = KindedTyVar name <$> newKindVar
650 kcHsTyVar (KindedTyVar name kind) = return (KindedTyVar name kind)
651
652 ------------------
653 tcTyVarBndrs :: [LHsTyVarBndr Name]     -- Kind-annotated binders, which need kind-zonking
654              -> ([TyVar] -> TcM r)
655              -> TcM r
656 -- Used when type-checking types/classes/type-decls
657 -- Brings into scope immutable TyVars, not mutable ones that require later zonking
658 tcTyVarBndrs bndrs thing_inside = do
659     tyvars <- mapM (zonk . unLoc) bndrs
660     tcExtendTyVarEnv tyvars (thing_inside tyvars)
661   where
662     zonk (KindedTyVar name kind) = do { kind' <- zonkTcKindToKind kind
663                                       ; return (mkTyVar name kind') }
664     zonk (UserTyVar name) = WARN( True, ptext SLIT("Un-kinded tyvar") <+> ppr name )
665                             return (mkTyVar name liftedTypeKind)
666
667 -----------------------------------
668 tcDataKindSig :: Maybe Kind -> TcM [TyVar]
669 -- GADT decls can have a (perhaps partial) kind signature
670 --      e.g.  data T :: * -> * -> * where ...
671 -- This function makes up suitable (kinded) type variables for 
672 -- the argument kinds, and checks that the result kind is indeed *.
673 -- We use it also to make up argument type variables for for data instances.
674 tcDataKindSig Nothing = return []
675 tcDataKindSig (Just kind)
676   = do  { checkTc (isLiftedTypeKind res_kind) (badKindSig kind)
677         ; span <- getSrcSpanM
678         ; us   <- newUniqueSupply 
679         ; let uniqs = uniqsFromSupply us
680         ; return [ mk_tv span uniq str kind 
681                  | ((kind, str), uniq) <- arg_kinds `zip` names `zip` uniqs ] }
682   where
683     (arg_kinds, res_kind) = splitKindFunTys kind
684     mk_tv loc uniq str kind = mkTyVar name kind
685         where
686            name = mkInternalName uniq occ loc
687            occ  = mkOccName tvName str
688
689     names :: [String]   -- a,b,c...aa,ab,ac etc
690     names = [ c:cs | cs <- "" : names, c <- ['a'..'z'] ] 
691
692 badKindSig :: Kind -> SDoc
693 badKindSig kind 
694  = hang (ptext SLIT("Kind signature on data type declaration has non-* return kind"))
695         2 (ppr kind)
696 \end{code}
697
698
699 %************************************************************************
700 %*                                                                      *
701                 Scoped type variables
702 %*                                                                      *
703 %************************************************************************
704
705
706 tcAddScopedTyVars is used for scoped type variables added by pattern
707 type signatures
708         e.g.  \ ((x::a), (y::a)) -> x+y
709 They never have explicit kinds (because this is source-code only)
710 They are mutable (because they can get bound to a more specific type).
711
712 Usually we kind-infer and expand type splices, and then
713 tupecheck/desugar the type.  That doesn't work well for scoped type
714 variables, because they scope left-right in patterns.  (e.g. in the
715 example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
716
717 The current not-very-good plan is to
718   * find all the types in the patterns
719   * find their free tyvars
720   * do kind inference
721   * bring the kinded type vars into scope
722   * BUT throw away the kind-checked type
723         (we'll kind-check it again when we type-check the pattern)
724
725 This is bad because throwing away the kind checked type throws away
726 its splices.  But too bad for now.  [July 03]
727
728 Historical note:
729     We no longer specify that these type variables must be univerally 
730     quantified (lots of email on the subject).  If you want to put that 
731     back in, you need to
732         a) Do a checkSigTyVars after thing_inside
733         b) More insidiously, don't pass in expected_ty, else
734            we unify with it too early and checkSigTyVars barfs
735            Instead you have to pass in a fresh ty var, and unify
736            it with expected_ty afterwards
737
738 \begin{code}
739 tcHsPatSigType :: UserTypeCtxt
740                -> LHsType Name          -- The type signature
741                -> TcM ([TyVar],         -- Newly in-scope type variables
742                         Type)           -- The signature
743 -- Used for type-checking type signatures in
744 -- (a) patterns           e.g  f (x::Int) = e
745 -- (b) result signatures  e.g. g x :: Int = e
746 -- (c) RULE forall bndrs  e.g. forall (x::Int). f x = x
747
748 tcHsPatSigType ctxt hs_ty 
749   = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
750     do  {       -- Find the type variables that are mentioned in the type
751                 -- but not already in scope.  These are the ones that
752                 -- should be bound by the pattern signature
753           in_scope <- getInLocalScope
754         ; let span = getLoc hs_ty
755               sig_tvs = [ L span (UserTyVar n) 
756                         | n <- nameSetToList (extractHsTyVars hs_ty),
757                           not (in_scope n) ]
758
759         ; (tyvars, sig_ty) <- tcHsQuantifiedType sig_tvs hs_ty
760         ; checkValidType ctxt sig_ty 
761         ; return (tyvars, sig_ty)
762       }
763
764 tcPatSig :: UserTypeCtxt
765          -> LHsType Name
766          -> BoxySigmaType
767          -> TcM (TcType,           -- The type to use for "inside" the signature
768                  [(Name,TcType)])  -- The new bit of type environment, binding
769                                    -- the scoped type variables
770 tcPatSig ctxt sig res_ty
771   = do  { (sig_tvs, sig_ty) <- tcHsPatSigType ctxt sig
772
773         ; if null sig_tvs then do {
774                 -- The type signature binds no type variables, 
775                 -- and hence is rigid, so use it to zap the res_ty
776                   boxyUnify sig_ty res_ty
777                 ; return (sig_ty, [])
778
779         } else do {
780                 -- Type signature binds at least one scoped type variable
781         
782                 -- A pattern binding cannot bind scoped type variables
783                 -- The renamer fails with a name-out-of-scope error 
784                 -- if a pattern binding tries to bind a type variable,
785                 -- So we just have an ASSERT here
786         ; let in_pat_bind = case ctxt of
787                                 BindPatSigCtxt -> True
788                                 other          -> False
789         ; ASSERT( not in_pat_bind || null sig_tvs ) return ()
790
791                 -- Check that pat_ty is rigid
792         ; checkTc (isRigidTy res_ty) (wobblyPatSig sig_tvs)
793
794                 -- Now match the pattern signature against res_ty
795                 -- For convenience, and uniform-looking error messages
796                 -- we do the matching by allocating meta type variables, 
797                 -- unifying, and reading out the results.
798                 -- This is a strictly local operation.
799         ; box_tvs <- mapM tcInstBoxyTyVar sig_tvs
800         ; boxyUnify (substTyWith sig_tvs (mkTyVarTys box_tvs) sig_ty) res_ty
801         ; sig_tv_tys <- mapM readFilledBox box_tvs
802
803                 -- Check that each is bound to a distinct type variable,
804                 -- and one that is not already in scope
805         ; let tv_binds = map tyVarName sig_tvs `zip` sig_tv_tys
806         ; binds_in_scope <- getScopedTyVarBinds
807         ; check binds_in_scope tv_binds
808         
809                 -- Phew!
810         ; return (res_ty, tv_binds)
811         } }
812   where
813     check in_scope []            = return ()
814     check in_scope ((n,ty):rest) = do { check_one in_scope n ty
815                                       ; check ((n,ty):in_scope) rest }
816
817     check_one in_scope n ty
818         = do { checkTc (tcIsTyVarTy ty) (scopedNonVar n ty)
819                 -- Must bind to a type variable
820
821              ; checkTc (null dups) (dupInScope n (head dups) ty)
822                 -- Must not bind to the same type variable
823                 -- as some other in-scope type variable
824
825              ; return () }
826         where
827           dups = [n' | (n',ty') <- in_scope, tcEqType ty' ty]
828 \end{code}
829
830
831 %************************************************************************
832 %*                                                                      *
833                 Scoped type variables
834 %*                                                                      *
835 %************************************************************************
836
837 \begin{code}
838 pprHsSigCtxt :: UserTypeCtxt -> LHsType Name -> SDoc
839 pprHsSigCtxt ctxt hs_ty = vcat [ ptext SLIT("In") <+> pprUserTypeCtxt ctxt <> colon, 
840                                  nest 2 (pp_sig ctxt) ]
841   where
842     pp_sig (FunSigCtxt n)  = pp_n_colon n
843     pp_sig (ConArgCtxt n)  = pp_n_colon n
844     pp_sig (ForSigCtxt n)  = pp_n_colon n
845     pp_sig other           = ppr (unLoc hs_ty)
846
847     pp_n_colon n = ppr n <+> dcolon <+> ppr (unLoc hs_ty)
848
849
850 wobblyPatSig sig_tvs
851   = hang (ptext SLIT("A pattern type signature cannot bind scoped type variables") 
852                 <+> pprQuotedList sig_tvs)
853        2 (ptext SLIT("unless the pattern has a rigid type context"))
854                 
855 scopedNonVar n ty
856   = vcat [sep [ptext SLIT("The scoped type variable") <+> quotes (ppr n),
857                nest 2 (ptext SLIT("is bound to the type") <+> quotes (ppr ty))],
858           nest 2 (ptext SLIT("You can only bind scoped type variables to type variables"))]
859
860 dupInScope n n' ty
861   = hang (ptext SLIT("The scoped type variables") <+> quotes (ppr n) <+> ptext SLIT("and") <+> quotes (ppr n'))
862        2 (vcat [ptext SLIT("are bound to the same type (variable)"),
863                 ptext SLIT("Distinct scoped type variables must be distinct")])
864
865 wrongEqualityErr
866   = failWithTc (text "Equality predicate used as a type")
867 \end{code}
868