2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 \section[TcMonoType]{Typechecking user-specified @MonoTypes@}
9 tcHsSigType, tcHsSigTypeNC, tcHsDeriv,
10 tcHsInstHead, tcHsQuantifiedType,
14 kcHsTyVars, kcHsSigType, kcHsLiftedSigType,
15 kcLHsType, kcCheckLHsType, kcHsContext,
17 -- Typechecking kinded types
18 tcHsKindedContext, tcHsKindedType, tcHsBangType,
19 tcTyVarBndrs, dsHsType, tcLHsConResTy,
20 tcDataKindSig, ExpKind(..), EkCtxt(..),
22 -- Pattern type signatures
23 tcHsPatSigType, tcPatSig
26 #include "HsVersions.h"
28 #ifdef GHCI /* Only if bootstrapped */
29 import {-# SOURCE #-} TcSplice( kcSpliceType )
40 import {- Kind parts of -} Type
60 ----------------------------
62 ----------------------------
64 Generally speaking we now type-check types in three phases
66 1. kcHsType: kind check the HsType
67 *includes* performing any TH type splices;
68 so it returns a translated, and kind-annotated, type
70 2. dsHsType: convert from HsType to Type:
72 expand type synonyms [mkGenTyApps]
73 hoist the foralls [tcHsType]
75 3. checkValidType: check the validity of the resulting type
77 Often these steps are done one after the other (tcHsSigType).
78 But in mutually recursive groups of type and class decls we do
79 1 kind-check the whole group
80 2 build TyCons/Classes in a knot-tied way
81 3 check the validity of types in the now-unknotted TyCons/Classes
83 For example, when we find
84 (forall a m. m a -> m a)
85 we bind a,m to kind varibles and kind-check (m a -> m a). This makes
86 a get kind *, and m get kind *->*. Now we typecheck (m a -> m a) in
87 an environment that binds a and m suitably.
89 The kind checker passed to tcHsTyVars needs to look at enough to
90 establish the kind of the tyvar:
91 * For a group of type and class decls, it's just the group, not
92 the rest of the program
93 * For a tyvar bound in a pattern type signature, its the types
94 mentioned in the other type signatures in that bunch of patterns
95 * For a tyvar bound in a RULE, it's the type signatures on other
96 universally quantified variables in the rule
98 Note that this may occasionally give surprising results. For example:
100 data T a b = MkT (a b)
102 Here we deduce a::*->*, b::*
103 But equally valid would be a::(*->*)-> *, b::*->*
108 Some of the validity check could in principle be done by the kind checker,
111 - During desugaring, we normalise by expanding type synonyms. Only
112 after this step can we check things like type-synonym saturation
113 e.g. type T k = k Int
115 Then (T S) is ok, because T is saturated; (T S) expands to (S Int);
116 and then S is saturated. This is a GHC extension.
118 - Similarly, also a GHC extension, we look through synonyms before complaining
119 about the form of a class or instance declaration
121 - Ambiguity checks involve functional dependencies, and it's easier to wait
122 until knots have been resolved before poking into them
124 Also, in a mutually recursive group of types, we can't look at the TyCon until we've
125 finished building the loop. So to keep things simple, we postpone most validity
126 checking until step (3).
130 During step (1) we might fault in a TyCon defined in another module, and it might
131 (via a loop) refer back to a TyCon defined in this module. So when we tie a big
132 knot around type declarations with ARecThing, so that the fault-in code can get
133 the TyCon being defined.
136 %************************************************************************
138 \subsection{Checking types}
140 %************************************************************************
143 tcHsSigType, tcHsSigTypeNC :: UserTypeCtxt -> LHsType Name -> TcM Type
144 -- Do kind checking, and hoist for-alls to the top
145 -- NB: it's important that the foralls that come from the top-level
146 -- HsForAllTy in hs_ty occur *first* in the returned type.
147 -- See Note [Scoped] with TcSigInfo
148 tcHsSigType ctxt hs_ty
149 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
150 tcHsSigTypeNC ctxt hs_ty
152 tcHsSigTypeNC ctxt hs_ty
153 = do { (kinded_ty, _kind) <- kc_lhs_type hs_ty
154 -- The kind is checked by checkValidType, and isn't necessarily
155 -- of kind * in a Template Haskell quote eg [t| Maybe |]
156 ; ty <- tcHsKindedType kinded_ty
157 ; checkValidType ctxt ty
160 tcHsInstHead :: LHsType Name -> TcM ([TyVar], ThetaType, Type)
161 -- Typecheck an instance head. We can't use
162 -- tcHsSigType, because it's not a valid user type.
164 = do { kinded_ty <- kcHsSigType hs_ty
165 ; poly_ty <- tcHsKindedType kinded_ty
166 ; return (tcSplitSigmaTy poly_ty) }
168 tcHsQuantifiedType :: [LHsTyVarBndr Name] -> LHsType Name -> TcM ([TyVar], Type)
169 -- Behave very like type-checking (HsForAllTy sig_tvs hs_ty),
170 -- except that we want to keep the tvs separate
171 tcHsQuantifiedType tv_names hs_ty
172 = kcHsTyVars tv_names $ \ tv_names' ->
173 do { kc_ty <- kcHsSigType hs_ty
174 ; tcTyVarBndrs tv_names' $ \ tvs ->
175 do { ty <- dsHsType kc_ty
176 ; return (tvs, ty) } }
178 -- Used for the deriving(...) items
179 tcHsDeriv :: HsType Name -> TcM ([TyVar], Class, [Type])
180 tcHsDeriv = tc_hs_deriv []
182 tc_hs_deriv :: [LHsTyVarBndr Name] -> HsType Name
183 -> TcM ([TyVar], Class, [Type])
184 tc_hs_deriv tv_names (HsPredTy (HsClassP cls_name hs_tys))
185 = kcHsTyVars tv_names $ \ tv_names' ->
186 do { cls_kind <- kcClass cls_name
187 ; (tys, _res_kind) <- kcApps cls_name cls_kind hs_tys
188 ; tcTyVarBndrs tv_names' $ \ tyvars ->
189 do { arg_tys <- dsHsTypes tys
190 ; cls <- tcLookupClass cls_name
191 ; return (tyvars, cls, arg_tys) }}
193 tc_hs_deriv tv_names1 (HsForAllTy _ tv_names2 (L _ []) (L _ ty))
194 = -- Funny newtype deriving form
196 -- where C has arity 2. Hence can't use regular functions
197 tc_hs_deriv (tv_names1 ++ tv_names2) ty
200 = failWithTc (ptext (sLit "Illegal deriving item") <+> ppr other)
203 These functions are used during knot-tying in
204 type and class declarations, when we have to
205 separate kind-checking, desugaring, and validity checking
208 kcHsSigType, kcHsLiftedSigType :: LHsType Name -> TcM (LHsType Name)
209 -- Used for type signatures
210 kcHsSigType ty = addKcTypeCtxt ty $ kcTypeType ty
211 kcHsLiftedSigType ty = addKcTypeCtxt ty $ kcLiftedType ty
213 tcHsKindedType :: LHsType Name -> TcM Type
214 -- Don't do kind checking, nor validity checking.
215 -- This is used in type and class decls, where kinding is
216 -- done in advance, and validity checking is done later
217 -- [Validity checking done later because of knot-tying issues.]
218 tcHsKindedType hs_ty = dsHsType hs_ty
220 tcHsBangType :: LHsType Name -> TcM Type
221 -- Permit a bang, but discard it
222 tcHsBangType (L _ (HsBangTy _ ty)) = tcHsKindedType ty
223 tcHsBangType ty = tcHsKindedType ty
225 tcHsKindedContext :: LHsContext Name -> TcM ThetaType
226 -- Used when we are expecting a ClassContext (i.e. no implicit params)
227 -- Does not do validity checking, like tcHsKindedType
228 tcHsKindedContext hs_theta = addLocM (mapM dsHsLPred) hs_theta
232 %************************************************************************
234 The main kind checker: kcHsType
236 %************************************************************************
238 First a couple of simple wrappers for kcHsType
241 ---------------------------
242 kcLiftedType :: LHsType Name -> TcM (LHsType Name)
243 -- The type ty must be a *lifted* *type*
244 kcLiftedType ty = kc_check_lhs_type ty ekLifted
246 ---------------------------
247 kcTypeType :: LHsType Name -> TcM (LHsType Name)
248 -- The type ty must be a *type*, but it can be lifted or
249 -- unlifted or an unboxed tuple.
250 kcTypeType ty = kc_check_lhs_type ty ekOpen
252 ---------------------------
253 kcCheckLHsType :: LHsType Name -> ExpKind -> TcM (LHsType Name)
254 kcCheckLHsType ty kind = addKcTypeCtxt ty $ kc_check_lhs_type ty kind
257 kc_check_lhs_type :: LHsType Name -> ExpKind -> TcM (LHsType Name)
258 -- Check that the type has the specified kind
259 -- Be sure to use checkExpectedKind, rather than simply unifying
260 -- with OpenTypeKind, because it gives better error messages
261 kc_check_lhs_type (L span ty) exp_kind
263 do { ty' <- kc_check_hs_type ty exp_kind
264 ; return (L span ty') }
266 kc_check_lhs_types :: [(LHsType Name, ExpKind)] -> TcM [LHsType Name]
267 kc_check_lhs_types tys_w_kinds
268 = mapM kc_arg tys_w_kinds
270 kc_arg (arg, arg_kind) = kc_check_lhs_type arg arg_kind
273 ---------------------------
274 kc_check_hs_type :: HsType Name -> ExpKind -> TcM (HsType Name)
276 -- First some special cases for better error messages
277 -- when we know the expected kind
278 kc_check_hs_type (HsParTy ty) exp_kind
279 = do { ty' <- kc_check_lhs_type ty exp_kind; return (HsParTy ty') }
281 kc_check_hs_type ty@(HsAppTy ty1 ty2) exp_kind
282 = do { let (fun_ty, arg_tys) = splitHsAppTys ty1 ty2
283 ; (fun_ty', fun_kind) <- kc_lhs_type fun_ty
284 ; arg_tys' <- kcCheckApps fun_ty fun_kind arg_tys ty exp_kind
285 ; return (mkHsAppTys fun_ty' arg_tys') }
287 kc_check_hs_type ty@(HsPredTy (HsClassP cls tys)) exp_kind
288 = do { cls_kind <- kcClass cls
289 ; tys' <- kcCheckApps cls cls_kind tys ty exp_kind
290 ; return (HsPredTy (HsClassP cls tys')) }
292 -- This is the general case: infer the kind and compare
293 kc_check_hs_type ty exp_kind
294 = do { (ty', act_kind) <- kc_hs_type ty
295 -- Add the context round the inner check only
296 -- because checkExpectedKind already mentions
297 -- 'ty' by name in any error message
299 ; checkExpectedKind (strip ty) act_kind exp_kind
302 -- We infer the kind of the type, and then complain if it's
303 -- not right. But we don't want to complain about
304 -- (ty) or !(ty) or forall a. ty
305 -- when the real difficulty is with the 'ty' part.
306 strip (HsParTy (L _ ty)) = strip ty
307 strip (HsBangTy _ (L _ ty)) = strip ty
308 strip (HsForAllTy _ _ _ (L _ ty)) = strip ty
313 Here comes the main function
316 kcLHsType :: LHsType Name -> TcM (LHsType Name, TcKind)
317 -- Called from outside: set the context
318 kcLHsType ty = addKcTypeCtxt ty (kc_lhs_type ty)
320 kc_lhs_type :: LHsType Name -> TcM (LHsType Name, TcKind)
321 kc_lhs_type (L span ty)
323 do { (ty', kind) <- kc_hs_type ty
324 ; return (L span ty', kind) }
326 -- kc_hs_type *returns* the kind of the type, rather than taking an expected
327 -- kind as argument as tcExpr does.
329 -- (a) the kind of (->) is
330 -- forall bx1 bx2. Type bx1 -> Type bx2 -> Type Boxed
331 -- so we'd need to generate huge numbers of bx variables.
332 -- (b) kinds are so simple that the error messages are fine
334 -- The translated type has explicitly-kinded type-variable binders
336 kc_hs_type :: HsType Name -> TcM (HsType Name, TcKind)
337 kc_hs_type (HsParTy ty) = do
338 (ty', kind) <- kc_lhs_type ty
339 return (HsParTy ty', kind)
341 kc_hs_type (HsTyVar name) = do
343 return (HsTyVar name, kind)
345 kc_hs_type (HsListTy ty) = do
346 ty' <- kcLiftedType ty
347 return (HsListTy ty', liftedTypeKind)
349 kc_hs_type (HsPArrTy ty) = do
350 ty' <- kcLiftedType ty
351 return (HsPArrTy ty', liftedTypeKind)
353 kc_hs_type (HsNumTy n)
354 = return (HsNumTy n, liftedTypeKind)
356 kc_hs_type (HsKindSig ty k) = do
357 ty' <- kc_check_lhs_type ty (EK k EkKindSig)
358 return (HsKindSig ty' k, k)
360 kc_hs_type (HsTupleTy Boxed tys) = do
361 tys' <- mapM kcLiftedType tys
362 return (HsTupleTy Boxed tys', liftedTypeKind)
364 kc_hs_type (HsTupleTy Unboxed tys) = do
365 tys' <- mapM kcTypeType tys
366 return (HsTupleTy Unboxed tys', ubxTupleKind)
368 kc_hs_type (HsFunTy ty1 ty2) = do
369 ty1' <- kc_check_lhs_type ty1 (EK argTypeKind EkUnk)
370 ty2' <- kcTypeType ty2
371 return (HsFunTy ty1' ty2', liftedTypeKind)
373 kc_hs_type (HsOpTy ty1 op ty2) = do
374 op_kind <- addLocM kcTyVar op
375 ([ty1',ty2'], res_kind) <- kcApps op op_kind [ty1,ty2]
376 return (HsOpTy ty1' op ty2', res_kind)
378 kc_hs_type (HsAppTy ty1 ty2) = do
379 (fun_ty', fun_kind) <- kc_lhs_type fun_ty
380 (arg_tys', res_kind) <- kcApps fun_ty fun_kind arg_tys
381 return (mkHsAppTys fun_ty' arg_tys', res_kind)
383 (fun_ty, arg_tys) = splitHsAppTys ty1 ty2
385 kc_hs_type (HsPredTy (HsEqualP _ _))
388 kc_hs_type (HsPredTy pred) = do
389 pred' <- kcHsPred pred
390 return (HsPredTy pred', liftedTypeKind)
392 kc_hs_type (HsForAllTy exp tv_names context ty)
393 = kcHsTyVars tv_names $ \ tv_names' ->
394 do { ctxt' <- kcHsContext context
395 ; ty' <- kcLiftedType ty
396 -- The body of a forall is usually a type, but in principle
397 -- there's no reason to prohibit *unlifted* types.
398 -- In fact, GHC can itself construct a function with an
399 -- unboxed tuple inside a for-all (via CPR analyis; see
400 -- typecheck/should_compile/tc170)
402 -- Still, that's only for internal interfaces, which aren't
403 -- kind-checked, so we only allow liftedTypeKind here
405 ; return (HsForAllTy exp tv_names' ctxt' ty', liftedTypeKind) }
407 kc_hs_type (HsBangTy b ty) = do
408 (ty', kind) <- kc_lhs_type ty
409 return (HsBangTy b ty', kind)
411 #ifdef GHCI /* Only if bootstrapped */
412 kc_hs_type (HsSpliceTy sp) = kcSpliceType sp
414 kc_hs_type ty@(HsSpliceTy _) = failWithTc (ptext (sLit "Unexpected type splice:") <+> ppr ty)
417 -- remove the doc nodes here, no need to worry about the location since
418 -- its the same for a doc node and it's child type node
419 kc_hs_type (HsDocTy ty _)
420 = kc_hs_type (unLoc ty)
422 ---------------------------
423 kcApps :: Outputable a
425 -> TcKind -- Function kind
426 -> [LHsType Name] -- Arg types
427 -> TcM ([LHsType Name], TcKind) -- Kind-checked args
428 kcApps the_fun fun_kind args
429 = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
430 ; args' <- kc_check_lhs_types args_w_kinds
431 ; return (args', res_kind) }
433 kcCheckApps :: Outputable a => a -> TcKind -> [LHsType Name]
434 -> HsType Name -- The type being checked (for err messages only)
435 -> ExpKind -- Expected kind
436 -> TcM [LHsType Name]
437 kcCheckApps the_fun fun_kind args ty exp_kind
438 = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
439 ; checkExpectedKind ty res_kind exp_kind
440 -- Check the result kind *before* checking argument kinds
441 -- This improves error message; Trac #2994
442 ; kc_check_lhs_types args_w_kinds }
444 splitHsAppTys :: LHsType Name -> LHsType Name -> (LHsType Name, [LHsType Name])
445 splitHsAppTys fun_ty arg_ty = split fun_ty [arg_ty]
447 split (L _ (HsAppTy f a)) as = split f (a:as)
450 mkHsAppTys :: LHsType Name -> [LHsType Name] -> HsType Name
451 mkHsAppTys fun_ty [] = pprPanic "mkHsAppTys" (ppr fun_ty)
452 mkHsAppTys fun_ty (arg_ty:arg_tys)
453 = foldl mk_app (HsAppTy fun_ty arg_ty) arg_tys
455 mk_app fun arg = HsAppTy (noLoc fun) arg -- Add noLocs for inner nodes of
456 -- the application; they are
459 ---------------------------
460 splitFunKind :: SDoc -> Int -> TcKind -> [b] -> TcM ([(b,ExpKind)], TcKind)
461 splitFunKind _ _ fk [] = return ([], fk)
462 splitFunKind the_fun arg_no fk (arg:args)
463 = do { mb_fk <- unifyFunKind fk
465 Nothing -> failWithTc too_many_args
466 Just (ak,fk') -> do { (aks, rk) <- splitFunKind the_fun (arg_no+1) fk' args
467 ; return ((arg, EK ak (EkArg the_fun arg_no)):aks, rk) } }
469 too_many_args = quotes the_fun <+>
470 ptext (sLit "is applied to too many type arguments")
472 ---------------------------
473 kcHsContext :: LHsContext Name -> TcM (LHsContext Name)
474 kcHsContext ctxt = wrapLocM (mapM kcHsLPred) ctxt
476 kcHsLPred :: LHsPred Name -> TcM (LHsPred Name)
477 kcHsLPred = wrapLocM kcHsPred
479 kcHsPred :: HsPred Name -> TcM (HsPred Name)
480 kcHsPred pred = do -- Checks that the result is of kind liftedType
481 (pred', kind) <- kc_pred pred
482 checkExpectedKind pred kind ekLifted
485 ---------------------------
486 kc_pred :: HsPred Name -> TcM (HsPred Name, TcKind)
487 -- Does *not* check for a saturated
488 -- application (reason: used from TcDeriv)
489 kc_pred (HsIParam name ty)
490 = do { (ty', kind) <- kc_lhs_type ty
491 ; return (HsIParam name ty', kind)
493 kc_pred (HsClassP cls tys)
494 = do { kind <- kcClass cls
495 ; (tys', res_kind) <- kcApps cls kind tys
496 ; return (HsClassP cls tys', res_kind)
498 kc_pred (HsEqualP ty1 ty2)
499 = do { (ty1', kind1) <- kc_lhs_type ty1
500 -- ; checkExpectedKind ty1 kind1 liftedTypeKind
501 ; (ty2', kind2) <- kc_lhs_type ty2
502 -- ; checkExpectedKind ty2 kind2 liftedTypeKind
503 ; checkExpectedKind ty2 kind2 (EK kind1 EkEqPred)
504 ; return (HsEqualP ty1' ty2', liftedTypeKind)
507 ---------------------------
508 kcTyVar :: Name -> TcM TcKind
509 kcTyVar name = do -- Could be a tyvar or a tycon
510 traceTc (text "lk1" <+> ppr name)
511 thing <- tcLookup name
512 traceTc (text "lk2" <+> ppr name <+> ppr thing)
514 ATyVar _ ty -> return (typeKind ty)
515 AThing kind -> return kind
516 AGlobal (ATyCon tc) -> return (tyConKind tc)
517 _ -> wrongThingErr "type" thing name
519 kcClass :: Name -> TcM TcKind
520 kcClass cls = do -- Must be a class
521 thing <- tcLookup cls
523 AThing kind -> return kind
524 AGlobal (AClass cls) -> return (tyConKind (classTyCon cls))
525 _ -> wrongThingErr "class" thing cls
529 %************************************************************************
533 %************************************************************************
537 * Transforms from HsType to Type
540 It cannot fail, and does no validity checking, except for
541 structural matters, such as
542 (a) spurious ! annotations.
543 (b) a class used as a type
546 dsHsType :: LHsType Name -> TcM Type
547 -- All HsTyVarBndrs in the intput type are kind-annotated
548 dsHsType ty = ds_type (unLoc ty)
550 ds_type :: HsType Name -> TcM Type
551 ds_type ty@(HsTyVar _)
554 ds_type (HsParTy ty) -- Remove the parentheses markers
557 ds_type ty@(HsBangTy _ _) -- No bangs should be here
558 = failWithTc (ptext (sLit "Unexpected strictness annotation:") <+> ppr ty)
560 ds_type (HsKindSig ty _)
561 = dsHsType ty -- Kind checking done already
563 ds_type (HsListTy ty) = do
564 tau_ty <- dsHsType ty
565 checkWiredInTyCon listTyCon
566 return (mkListTy tau_ty)
568 ds_type (HsPArrTy ty) = do
569 tau_ty <- dsHsType ty
570 checkWiredInTyCon parrTyCon
571 return (mkPArrTy tau_ty)
573 ds_type (HsTupleTy boxity tys) = do
574 tau_tys <- dsHsTypes tys
575 checkWiredInTyCon tycon
576 return (mkTyConApp tycon tau_tys)
578 tycon = tupleTyCon boxity (length tys)
580 ds_type (HsFunTy ty1 ty2) = do
581 tau_ty1 <- dsHsType ty1
582 tau_ty2 <- dsHsType ty2
583 return (mkFunTy tau_ty1 tau_ty2)
585 ds_type (HsOpTy ty1 (L span op) ty2) = do
586 tau_ty1 <- dsHsType ty1
587 tau_ty2 <- dsHsType ty2
588 setSrcSpan span (ds_var_app op [tau_ty1,tau_ty2])
592 tc <- tcLookupTyCon genUnitTyConName
593 return (mkTyConApp tc [])
595 ds_type ty@(HsAppTy _ _)
598 ds_type (HsPredTy pred) = do
599 pred' <- dsHsPred pred
600 return (mkPredTy pred')
602 ds_type (HsForAllTy _ tv_names ctxt ty)
603 = tcTyVarBndrs tv_names $ \ tyvars -> do
604 theta <- mapM dsHsLPred (unLoc ctxt)
606 return (mkSigmaTy tyvars theta tau)
608 ds_type (HsSpliceTy {}) = panic "ds_type: HsSpliceTy"
610 ds_type (HsDocTy ty _) -- Remove the doc comment
613 dsHsTypes :: [LHsType Name] -> TcM [Type]
614 dsHsTypes arg_tys = mapM dsHsType arg_tys
617 Help functions for type applications
618 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
621 ds_app :: HsType Name -> [LHsType Name] -> TcM Type
622 ds_app (HsAppTy ty1 ty2) tys
623 = ds_app (unLoc ty1) (ty2:tys)
626 arg_tys <- dsHsTypes tys
628 HsTyVar fun -> ds_var_app fun arg_tys
629 _ -> do fun_ty <- ds_type ty
630 return (mkAppTys fun_ty arg_tys)
632 ds_var_app :: Name -> [Type] -> TcM Type
633 ds_var_app name arg_tys = do
634 thing <- tcLookup name
636 ATyVar _ ty -> return (mkAppTys ty arg_tys)
637 AGlobal (ATyCon tc) -> return (mkTyConApp tc arg_tys)
638 _ -> wrongThingErr "type" thing name
646 dsHsLPred :: LHsPred Name -> TcM PredType
647 dsHsLPred pred = dsHsPred (unLoc pred)
649 dsHsPred :: HsPred Name -> TcM PredType
650 dsHsPred (HsClassP class_name tys)
651 = do { arg_tys <- dsHsTypes tys
652 ; clas <- tcLookupClass class_name
653 ; return (ClassP clas arg_tys)
655 dsHsPred (HsEqualP ty1 ty2)
656 = do { arg_ty1 <- dsHsType ty1
657 ; arg_ty2 <- dsHsType ty2
658 ; return (EqPred arg_ty1 arg_ty2)
660 dsHsPred (HsIParam name ty)
661 = do { arg_ty <- dsHsType ty
662 ; return (IParam name arg_ty)
666 GADT constructor signatures
669 tcLHsConResTy :: LHsType Name -> TcM (TyCon, [TcType])
670 tcLHsConResTy (L span res_ty)
672 case get_args res_ty [] of
673 (HsTyVar tc_name, args)
674 -> do { args' <- mapM dsHsType args
675 ; thing <- tcLookup tc_name
677 AGlobal (ATyCon tc) -> return (tc, args')
678 _ -> failWithTc (badGadtDecl res_ty) }
679 _ -> failWithTc (badGadtDecl res_ty)
681 -- We can't call dsHsType on res_ty, and then do tcSplitTyConApp_maybe
682 -- because that causes a black hole, and for good reason. Building
683 -- the type means expanding type synonyms, and we can't do that
684 -- inside the "knot". So we have to work by steam.
685 get_args (HsAppTy (L _ fun) arg) args = get_args fun (arg:args)
686 get_args (HsParTy (L _ ty)) args = get_args ty args
687 get_args (HsOpTy ty1 (L _ tc) ty2) args = (HsTyVar tc, ty1:ty2:args)
688 get_args ty args = (ty, args)
690 badGadtDecl :: HsType Name -> SDoc
692 = hang (ptext (sLit "Malformed constructor result type:"))
695 addKcTypeCtxt :: LHsType Name -> TcM a -> TcM a
696 -- Wrap a context around only if we want to show that contexts.
697 addKcTypeCtxt (L _ (HsPredTy _)) thing = thing
698 -- Omit invisble ones and ones user's won't grok (HsPred p).
699 addKcTypeCtxt (L _ other_ty) thing = addErrCtxt (typeCtxt other_ty) thing
701 typeCtxt :: HsType Name -> SDoc
702 typeCtxt ty = ptext (sLit "In the type") <+> quotes (ppr ty)
705 %************************************************************************
707 Type-variable binders
709 %************************************************************************
713 kcHsTyVars :: [LHsTyVarBndr Name]
714 -> ([LHsTyVarBndr Name] -> TcM r) -- These binders are kind-annotated
715 -- They scope over the thing inside
717 kcHsTyVars tvs thing_inside = do
718 bndrs <- mapM (wrapLocM kcHsTyVar) tvs
719 tcExtendKindEnvTvs bndrs (thing_inside bndrs)
721 kcHsTyVar :: HsTyVarBndr Name -> TcM (HsTyVarBndr Name)
722 -- Return a *kind-annotated* binder, and a tyvar with a mutable kind in it
723 kcHsTyVar (UserTyVar name) = KindedTyVar name <$> newKindVar
724 kcHsTyVar (KindedTyVar name kind) = return (KindedTyVar name kind)
727 tcTyVarBndrs :: [LHsTyVarBndr Name] -- Kind-annotated binders, which need kind-zonking
728 -> ([TyVar] -> TcM r)
730 -- Used when type-checking types/classes/type-decls
731 -- Brings into scope immutable TyVars, not mutable ones that require later zonking
732 tcTyVarBndrs bndrs thing_inside = do
733 tyvars <- mapM (zonk . unLoc) bndrs
734 tcExtendTyVarEnv tyvars (thing_inside tyvars)
736 zonk (KindedTyVar name kind) = do { kind' <- zonkTcKindToKind kind
737 ; return (mkTyVar name kind') }
738 zonk (UserTyVar name) = WARN( True, ptext (sLit "Un-kinded tyvar") <+> ppr name )
739 return (mkTyVar name liftedTypeKind)
741 -----------------------------------
742 tcDataKindSig :: Maybe Kind -> TcM [TyVar]
743 -- GADT decls can have a (perhaps partial) kind signature
744 -- e.g. data T :: * -> * -> * where ...
745 -- This function makes up suitable (kinded) type variables for
746 -- the argument kinds, and checks that the result kind is indeed *.
747 -- We use it also to make up argument type variables for for data instances.
748 tcDataKindSig Nothing = return []
749 tcDataKindSig (Just kind)
750 = do { checkTc (isLiftedTypeKind res_kind) (badKindSig kind)
751 ; span <- getSrcSpanM
752 ; us <- newUniqueSupply
753 ; let uniqs = uniqsFromSupply us
754 ; return [ mk_tv span uniq str kind
755 | ((kind, str), uniq) <- arg_kinds `zip` dnames `zip` uniqs ] }
757 (arg_kinds, res_kind) = splitKindFunTys kind
758 mk_tv loc uniq str kind = mkTyVar name kind
760 name = mkInternalName uniq occ loc
761 occ = mkOccName tvName str
763 dnames = map ('$' :) names -- Note [Avoid name clashes for associated data types]
766 names = [ c:cs | cs <- "" : names, c <- ['a'..'z'] ]
768 badKindSig :: Kind -> SDoc
770 = hang (ptext (sLit "Kind signature on data type declaration has non-* return kind"))
774 Note [Avoid name clashes for associated data types]
775 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
776 Consider class C a b where
778 When typechecking the decl for D, we'll invent an extra type variable for D,
779 to fill out its kind. We *don't* want this type variable to be 'a', because
780 in an .hi file we'd get
783 which makes it look as if there are *two* type indices. But there aren't!
784 So we use $a instead, which cannot clash with a user-written type variable.
785 Remember that type variable binders in interface files are just FastStrings,
788 (The tidying phase can't help here because we don't tidy TyCons. Another
789 alternative would be to record the number of indexing parameters in the
793 %************************************************************************
795 Scoped type variables
797 %************************************************************************
800 tcAddScopedTyVars is used for scoped type variables added by pattern
802 e.g. \ ((x::a), (y::a)) -> x+y
803 They never have explicit kinds (because this is source-code only)
804 They are mutable (because they can get bound to a more specific type).
806 Usually we kind-infer and expand type splices, and then
807 tupecheck/desugar the type. That doesn't work well for scoped type
808 variables, because they scope left-right in patterns. (e.g. in the
809 example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
811 The current not-very-good plan is to
812 * find all the types in the patterns
813 * find their free tyvars
815 * bring the kinded type vars into scope
816 * BUT throw away the kind-checked type
817 (we'll kind-check it again when we type-check the pattern)
819 This is bad because throwing away the kind checked type throws away
820 its splices. But too bad for now. [July 03]
823 We no longer specify that these type variables must be univerally
824 quantified (lots of email on the subject). If you want to put that
826 a) Do a checkSigTyVars after thing_inside
827 b) More insidiously, don't pass in expected_ty, else
828 we unify with it too early and checkSigTyVars barfs
829 Instead you have to pass in a fresh ty var, and unify
830 it with expected_ty afterwards
833 tcHsPatSigType :: UserTypeCtxt
834 -> LHsType Name -- The type signature
835 -> TcM ([TyVar], -- Newly in-scope type variables
836 Type) -- The signature
837 -- Used for type-checking type signatures in
838 -- (a) patterns e.g f (x::Int) = e
839 -- (b) result signatures e.g. g x :: Int = e
840 -- (c) RULE forall bndrs e.g. forall (x::Int). f x = x
842 tcHsPatSigType ctxt hs_ty
843 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
844 do { -- Find the type variables that are mentioned in the type
845 -- but not already in scope. These are the ones that
846 -- should be bound by the pattern signature
847 in_scope <- getInLocalScope
848 ; let span = getLoc hs_ty
849 sig_tvs = [ L span (UserTyVar n)
850 | n <- nameSetToList (extractHsTyVars hs_ty),
853 ; (tyvars, sig_ty) <- tcHsQuantifiedType sig_tvs hs_ty
854 ; checkValidType ctxt sig_ty
855 ; return (tyvars, sig_ty)
858 tcPatSig :: UserTypeCtxt
861 -> TcM (TcType, -- The type to use for "inside" the signature
862 [(Name, TcType)], -- The new bit of type environment, binding
863 -- the scoped type variables
864 CoercionI) -- Coercion due to unification with actual ty
865 tcPatSig ctxt sig res_ty
866 = do { (sig_tvs, sig_ty) <- tcHsPatSigType ctxt sig
868 ; if null sig_tvs then do {
869 -- The type signature binds no type variables,
870 -- and hence is rigid, so use it to zap the res_ty
871 coi <- boxyUnify sig_ty res_ty
872 ; return (sig_ty, [], coi)
875 -- Type signature binds at least one scoped type variable
877 -- A pattern binding cannot bind scoped type variables
878 -- The renamer fails with a name-out-of-scope error
879 -- if a pattern binding tries to bind a type variable,
880 -- So we just have an ASSERT here
881 ; let in_pat_bind = case ctxt of
882 BindPatSigCtxt -> True
884 ; ASSERT( not in_pat_bind || null sig_tvs ) return ()
886 -- Check that pat_ty is rigid
887 ; checkTc (isRigidTy res_ty) (wobblyPatSig sig_tvs)
889 -- Now match the pattern signature against res_ty
890 -- For convenience, and uniform-looking error messages
891 -- we do the matching by allocating meta type variables,
892 -- unifying, and reading out the results.
893 -- This is a strictly local operation.
894 ; box_tvs <- mapM tcInstBoxyTyVar sig_tvs
895 ; coi <- boxyUnify (substTyWith sig_tvs (mkTyVarTys box_tvs) sig_ty)
897 ; sig_tv_tys <- mapM readFilledBox box_tvs
899 -- Check that each is bound to a distinct type variable,
900 -- and one that is not already in scope
901 ; let tv_binds = map tyVarName sig_tvs `zip` sig_tv_tys
902 ; binds_in_scope <- getScopedTyVarBinds
903 ; check binds_in_scope tv_binds
906 ; return (res_ty, tv_binds, coi)
909 check _ [] = return ()
910 check in_scope ((n,ty):rest) = do { check_one in_scope n ty
911 ; check ((n,ty):in_scope) rest }
913 check_one in_scope n ty
914 = do { checkTc (tcIsTyVarTy ty) (scopedNonVar n ty)
915 -- Must bind to a type variable
917 ; checkTc (null dups) (dupInScope n (head dups) ty)
918 -- Must not bind to the same type variable
919 -- as some other in-scope type variable
923 dups = [n' | (n',ty') <- in_scope, tcEqType ty' ty]
927 %************************************************************************
931 %************************************************************************
933 We would like to get a decent error message from
934 (a) Under-applied type constructors
936 (b) Over-applied type constructors
940 -- The ExpKind datatype means "expected kind" and contains
941 -- some info about just why that kind is expected, to improve
942 -- the error message on a mis-match
943 data ExpKind = EK TcKind EkCtxt
944 data EkCtxt = EkUnk -- Unknown context
945 | EkEqPred -- Second argument of an equality predicate
946 | EkKindSig -- Kind signature
947 | EkArg SDoc Int -- Function, arg posn, expected kind
950 ekLifted, ekOpen :: ExpKind
951 ekLifted = EK liftedTypeKind EkUnk
952 ekOpen = EK openTypeKind EkUnk
954 checkExpectedKind :: Outputable a => a -> TcKind -> ExpKind -> TcM ()
955 -- A fancy wrapper for 'unifyKind', which tries
956 -- to give decent error messages.
957 -- (checkExpectedKind ty act_kind exp_kind)
958 -- checks that the actual kind act_kind is compatible
959 -- with the expected kind exp_kind
960 -- The first argument, ty, is used only in the error message generation
961 checkExpectedKind ty act_kind (EK exp_kind ek_ctxt)
962 | act_kind `isSubKind` exp_kind -- Short cut for a very common case
965 (_errs, mb_r) <- tryTc (unifyKind exp_kind act_kind)
967 Just _ -> return () -- Unification succeeded
970 -- So there's definitely an error
971 -- Now to find out what sort
972 exp_kind <- zonkTcKind exp_kind
973 act_kind <- zonkTcKind act_kind
975 env0 <- tcInitTidyEnv
976 let (exp_as, _) = splitKindFunTys exp_kind
977 (act_as, _) = splitKindFunTys act_kind
978 n_exp_as = length exp_as
979 n_act_as = length act_as
981 (env1, tidy_exp_kind) = tidyKind env0 exp_kind
982 (env2, tidy_act_kind) = tidyKind env1 act_kind
984 err | n_exp_as < n_act_as -- E.g. [Maybe]
985 = quotes (ppr ty) <+> ptext (sLit "is not applied to enough type arguments")
987 -- Now n_exp_as >= n_act_as. In the next two cases,
988 -- n_exp_as == 0, and hence so is n_act_as
989 | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
990 = ptext (sLit "Expecting a lifted type, but") <+> quotes (ppr ty)
991 <+> ptext (sLit "is unlifted")
993 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
994 = ptext (sLit "Expecting an unlifted type, but") <+> quotes (ppr ty)
995 <+> ptext (sLit "is lifted")
997 | otherwise -- E.g. Monad [Int]
998 = ptext (sLit "Kind mis-match")
1000 more_info = sep [ expected_herald ek_ctxt <+> ptext (sLit "kind")
1001 <+> quotes (pprKind tidy_exp_kind) <> comma,
1002 ptext (sLit "but") <+> quotes (ppr ty) <+>
1003 ptext (sLit "has kind") <+> quotes (pprKind tidy_act_kind)]
1005 expected_herald EkUnk = ptext (sLit "Expected")
1006 expected_herald EkKindSig = ptext (sLit "An enclosing kind signature specified")
1007 expected_herald EkEqPred = ptext (sLit "The left argument of the equality predicate had")
1008 expected_herald (EkArg fun arg_no)
1009 = ptext (sLit "The") <+> speakNth arg_no <+> ptext (sLit "argument of")
1010 <+> quotes fun <+> ptext (sLit ("should have"))
1012 failWithTcM (env2, err $$ more_info)
1015 %************************************************************************
1017 Scoped type variables
1019 %************************************************************************
1022 pprHsSigCtxt :: UserTypeCtxt -> LHsType Name -> SDoc
1023 pprHsSigCtxt ctxt hs_ty = vcat [ ptext (sLit "In") <+> pprUserTypeCtxt ctxt <> colon,
1024 nest 2 (pp_sig ctxt) ]
1026 pp_sig (FunSigCtxt n) = pp_n_colon n
1027 pp_sig (ConArgCtxt n) = pp_n_colon n
1028 pp_sig (ForSigCtxt n) = pp_n_colon n
1029 pp_sig _ = ppr (unLoc hs_ty)
1031 pp_n_colon n = ppr n <+> dcolon <+> ppr (unLoc hs_ty)
1033 wobblyPatSig :: [Var] -> SDoc
1034 wobblyPatSig sig_tvs
1035 = hang (ptext (sLit "A pattern type signature cannot bind scoped type variables")
1036 <+> pprQuotedList sig_tvs)
1037 2 (ptext (sLit "unless the pattern has a rigid type context"))
1039 scopedNonVar :: Name -> Type -> SDoc
1041 = vcat [sep [ptext (sLit "The scoped type variable") <+> quotes (ppr n),
1042 nest 2 (ptext (sLit "is bound to the type") <+> quotes (ppr ty))],
1043 nest 2 (ptext (sLit "You can only bind scoped type variables to type variables"))]
1045 dupInScope :: Name -> Name -> Type -> SDoc
1047 = hang (ptext (sLit "The scoped type variables") <+> quotes (ppr n) <+> ptext (sLit "and") <+> quotes (ppr n'))
1048 2 (vcat [ptext (sLit "are bound to the same type (variable)"),
1049 ptext (sLit "Distinct scoped type variables must be distinct")])
1051 wrongEqualityErr :: TcM (HsType Name, TcKind)
1053 = failWithTc (text "Equality predicate used as a type")