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, 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"
36 import {- Kind parts of -} Type
56 ----------------------------
58 ----------------------------
60 Generally speaking we now type-check types in three phases
62 1. kcHsType: kind check the HsType
63 *includes* performing any TH type splices;
64 so it returns a translated, and kind-annotated, type
66 2. dsHsType: convert from HsType to Type:
68 expand type synonyms [mkGenTyApps]
69 hoist the foralls [tcHsType]
71 3. checkValidType: check the validity of the resulting type
73 Often these steps are done one after the other (tcHsSigType).
74 But in mutually recursive groups of type and class decls we do
75 1 kind-check the whole group
76 2 build TyCons/Classes in a knot-tied way
77 3 check the validity of types in the now-unknotted TyCons/Classes
79 For example, when we find
80 (forall a m. m a -> m a)
81 we bind a,m to kind varibles and kind-check (m a -> m a). This makes
82 a get kind *, and m get kind *->*. Now we typecheck (m a -> m a) in
83 an environment that binds a and m suitably.
85 The kind checker passed to tcHsTyVars needs to look at enough to
86 establish the kind of the tyvar:
87 * For a group of type and class decls, it's just the group, not
88 the rest of the program
89 * For a tyvar bound in a pattern type signature, its the types
90 mentioned in the other type signatures in that bunch of patterns
91 * For a tyvar bound in a RULE, it's the type signatures on other
92 universally quantified variables in the rule
94 Note that this may occasionally give surprising results. For example:
96 data T a b = MkT (a b)
98 Here we deduce a::*->*, b::*
99 But equally valid would be a::(*->*)-> *, b::*->*
104 Some of the validity check could in principle be done by the kind checker,
107 - During desugaring, we normalise by expanding type synonyms. Only
108 after this step can we check things like type-synonym saturation
109 e.g. type T k = k Int
111 Then (T S) is ok, because T is saturated; (T S) expands to (S Int);
112 and then S is saturated. This is a GHC extension.
114 - Similarly, also a GHC extension, we look through synonyms before complaining
115 about the form of a class or instance declaration
117 - Ambiguity checks involve functional dependencies, and it's easier to wait
118 until knots have been resolved before poking into them
120 Also, in a mutually recursive group of types, we can't look at the TyCon until we've
121 finished building the loop. So to keep things simple, we postpone most validity
122 checking until step (3).
126 During step (1) we might fault in a TyCon defined in another module, and it might
127 (via a loop) refer back to a TyCon defined in this module. So when we tie a big
128 knot around type declarations with ARecThing, so that the fault-in code can get
129 the TyCon being defined.
132 %************************************************************************
134 \subsection{Checking types}
136 %************************************************************************
139 tcHsSigType :: UserTypeCtxt -> LHsType Name -> TcM Type
140 -- Do kind checking, and hoist for-alls to the top
141 -- NB: it's important that the foralls that come from the top-level
142 -- HsForAllTy in hs_ty occur *first* in the returned type.
143 -- See Note [Scoped] with TcSigInfo
144 tcHsSigType ctxt hs_ty
145 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
146 do { kinded_ty <- kcTypeType hs_ty
147 ; ty <- tcHsKindedType kinded_ty
148 ; checkValidType ctxt ty
151 tcHsInstHead :: LHsType Name -> TcM ([TyVar], ThetaType, Type)
152 -- Typecheck an instance head. We can't use
153 -- tcHsSigType, because it's not a valid user type.
155 = do { kinded_ty <- kcHsSigType hs_ty
156 ; poly_ty <- tcHsKindedType kinded_ty
157 ; return (tcSplitSigmaTy poly_ty) }
159 tcHsQuantifiedType :: [LHsTyVarBndr Name] -> LHsType Name -> TcM ([TyVar], Type)
160 -- Behave very like type-checking (HsForAllTy sig_tvs hs_ty),
161 -- except that we want to keep the tvs separate
162 tcHsQuantifiedType tv_names hs_ty
163 = kcHsTyVars tv_names $ \ tv_names' ->
164 do { kc_ty <- kcHsSigType hs_ty
165 ; tcTyVarBndrs tv_names' $ \ tvs ->
166 do { ty <- dsHsType kc_ty
167 ; return (tvs, ty) } }
169 -- Used for the deriving(...) items
170 tcHsDeriv :: HsType Name -> TcM ([TyVar], Class, [Type])
171 tcHsDeriv = tc_hs_deriv []
173 tc_hs_deriv :: [LHsTyVarBndr Name] -> HsType Name
174 -> TcM ([TyVar], Class, [Type])
175 tc_hs_deriv tv_names (HsPredTy (HsClassP cls_name hs_tys))
176 = kcHsTyVars tv_names $ \ tv_names' ->
177 do { cls_kind <- kcClass cls_name
178 ; (tys, _res_kind) <- kcApps cls_name cls_kind hs_tys
179 ; tcTyVarBndrs tv_names' $ \ tyvars ->
180 do { arg_tys <- dsHsTypes tys
181 ; cls <- tcLookupClass cls_name
182 ; return (tyvars, cls, arg_tys) }}
184 tc_hs_deriv tv_names1 (HsForAllTy _ tv_names2 (L _ []) (L _ ty))
185 = -- Funny newtype deriving form
187 -- where C has arity 2. Hence can't use regular functions
188 tc_hs_deriv (tv_names1 ++ tv_names2) ty
191 = failWithTc (ptext (sLit "Illegal deriving item") <+> ppr other)
194 These functions are used during knot-tying in
195 type and class declarations, when we have to
196 separate kind-checking, desugaring, and validity checking
199 kcHsSigType, kcHsLiftedSigType :: LHsType Name -> TcM (LHsType Name)
200 -- Used for type signatures
201 kcHsSigType ty = addKcTypeCtxt ty $ kcTypeType ty
202 kcHsLiftedSigType ty = addKcTypeCtxt ty $ kcLiftedType ty
204 tcHsKindedType :: LHsType Name -> TcM Type
205 -- Don't do kind checking, nor validity checking.
206 -- This is used in type and class decls, where kinding is
207 -- done in advance, and validity checking is done later
208 -- [Validity checking done later because of knot-tying issues.]
209 tcHsKindedType hs_ty = dsHsType hs_ty
211 tcHsBangType :: LHsType Name -> TcM Type
212 -- Permit a bang, but discard it
213 tcHsBangType (L _ (HsBangTy _ ty)) = tcHsKindedType ty
214 tcHsBangType ty = tcHsKindedType ty
216 tcHsKindedContext :: LHsContext Name -> TcM ThetaType
217 -- Used when we are expecting a ClassContext (i.e. no implicit params)
218 -- Does not do validity checking, like tcHsKindedType
219 tcHsKindedContext hs_theta = addLocM (mapM dsHsLPred) hs_theta
223 %************************************************************************
225 The main kind checker: kcHsType
227 %************************************************************************
229 First a couple of simple wrappers for kcHsType
232 ---------------------------
233 kcLiftedType :: LHsType Name -> TcM (LHsType Name)
234 -- The type ty must be a *lifted* *type*
235 kcLiftedType ty = kc_check_lhs_type ty ekLifted
237 ---------------------------
238 kcTypeType :: LHsType Name -> TcM (LHsType Name)
239 -- The type ty must be a *type*, but it can be lifted or
240 -- unlifted or an unboxed tuple.
241 kcTypeType ty = kc_check_lhs_type ty ekOpen
243 ---------------------------
244 kcCheckLHsType :: LHsType Name -> ExpKind -> TcM (LHsType Name)
245 kcCheckLHsType ty kind = addKcTypeCtxt ty $ kc_check_lhs_type ty kind
248 kc_check_lhs_type :: LHsType Name -> ExpKind -> TcM (LHsType Name)
249 -- Check that the type has the specified kind
250 -- Be sure to use checkExpectedKind, rather than simply unifying
251 -- with OpenTypeKind, because it gives better error messages
252 kc_check_lhs_type (L span ty) exp_kind
254 do { ty' <- kc_check_hs_type ty exp_kind
255 ; return (L span ty') }
257 kc_check_lhs_types :: [(LHsType Name, ExpKind)] -> TcM [LHsType Name]
258 kc_check_lhs_types tys_w_kinds
259 = mapM kc_arg tys_w_kinds
261 kc_arg (arg, arg_kind) = kc_check_lhs_type arg arg_kind
264 ---------------------------
265 kc_check_hs_type :: HsType Name -> ExpKind -> TcM (HsType Name)
267 -- First some special cases for better error messages
268 -- when we know the expected kind
269 kc_check_hs_type (HsParTy ty) exp_kind
270 = do { ty' <- kc_check_lhs_type ty exp_kind; return (HsParTy ty') }
272 kc_check_hs_type ty@(HsAppTy ty1 ty2) exp_kind
273 = do { let (fun_ty, arg_tys) = splitHsAppTys ty1 ty2
274 ; (fun_ty', fun_kind) <- kc_lhs_type fun_ty
275 ; arg_tys' <- kcCheckApps fun_ty fun_kind arg_tys ty exp_kind
276 ; return (mkHsAppTys fun_ty' arg_tys') }
278 kc_check_hs_type ty@(HsPredTy (HsClassP cls tys)) exp_kind
279 = do { cls_kind <- kcClass cls
280 ; tys' <- kcCheckApps cls cls_kind tys ty exp_kind
281 ; return (HsPredTy (HsClassP cls tys')) }
283 -- This is the general case: infer the kind and compare
284 kc_check_hs_type ty exp_kind
285 = do { (ty', act_kind) <- kc_hs_type ty
286 -- Add the context round the inner check only
287 -- because checkExpectedKind already mentions
288 -- 'ty' by name in any error message
290 ; checkExpectedKind (strip ty) act_kind exp_kind
293 -- We infer the kind of the type, and then complain if it's
294 -- not right. But we don't want to complain about
295 -- (ty) or !(ty) or forall a. ty
296 -- when the real difficulty is with the 'ty' part.
297 strip (HsParTy (L _ ty)) = strip ty
298 strip (HsBangTy _ (L _ ty)) = strip ty
299 strip (HsForAllTy _ _ _ (L _ ty)) = strip ty
304 Here comes the main function
307 kcLHsType :: LHsType Name -> TcM (LHsType Name, TcKind)
308 -- Called from outside: set the context
309 kcLHsType ty = addKcTypeCtxt ty (kc_lhs_type ty)
311 kc_lhs_type :: LHsType Name -> TcM (LHsType Name, TcKind)
312 kc_lhs_type (L span ty)
314 do { (ty', kind) <- kc_hs_type ty
315 ; return (L span ty', kind) }
317 -- kc_hs_type *returns* the kind of the type, rather than taking an expected
318 -- kind as argument as tcExpr does.
320 -- (a) the kind of (->) is
321 -- forall bx1 bx2. Type bx1 -> Type bx2 -> Type Boxed
322 -- so we'd need to generate huge numbers of bx variables.
323 -- (b) kinds are so simple that the error messages are fine
325 -- The translated type has explicitly-kinded type-variable binders
327 kc_hs_type :: HsType Name -> TcM (HsType Name, TcKind)
328 kc_hs_type (HsParTy ty) = do
329 (ty', kind) <- kc_lhs_type ty
330 return (HsParTy ty', kind)
332 kc_hs_type (HsTyVar name) = do
334 return (HsTyVar name, kind)
336 kc_hs_type (HsListTy ty) = do
337 ty' <- kcLiftedType ty
338 return (HsListTy ty', liftedTypeKind)
340 kc_hs_type (HsPArrTy ty) = do
341 ty' <- kcLiftedType ty
342 return (HsPArrTy ty', liftedTypeKind)
344 kc_hs_type (HsNumTy n)
345 = return (HsNumTy n, liftedTypeKind)
347 kc_hs_type (HsKindSig ty k) = do
348 ty' <- kc_check_lhs_type ty (EK k EkKindSig)
349 return (HsKindSig ty' k, k)
351 kc_hs_type (HsTupleTy Boxed tys) = do
352 tys' <- mapM kcLiftedType tys
353 return (HsTupleTy Boxed tys', liftedTypeKind)
355 kc_hs_type (HsTupleTy Unboxed tys) = do
356 tys' <- mapM kcTypeType tys
357 return (HsTupleTy Unboxed tys', ubxTupleKind)
359 kc_hs_type (HsFunTy ty1 ty2) = do
360 ty1' <- kc_check_lhs_type ty1 (EK argTypeKind EkUnk)
361 ty2' <- kcTypeType ty2
362 return (HsFunTy ty1' ty2', liftedTypeKind)
364 kc_hs_type (HsOpTy ty1 op ty2) = do
365 op_kind <- addLocM kcTyVar op
366 ([ty1',ty2'], res_kind) <- kcApps op op_kind [ty1,ty2]
367 return (HsOpTy ty1' op ty2', res_kind)
369 kc_hs_type (HsAppTy ty1 ty2) = do
370 (fun_ty', fun_kind) <- kc_lhs_type fun_ty
371 (arg_tys', res_kind) <- kcApps fun_ty fun_kind arg_tys
372 return (mkHsAppTys fun_ty' arg_tys', res_kind)
374 (fun_ty, arg_tys) = splitHsAppTys ty1 ty2
376 kc_hs_type (HsPredTy (HsEqualP _ _))
379 kc_hs_type (HsPredTy pred) = do
380 pred' <- kcHsPred pred
381 return (HsPredTy pred', liftedTypeKind)
383 kc_hs_type (HsForAllTy exp tv_names context ty)
384 = kcHsTyVars tv_names $ \ tv_names' ->
385 do { ctxt' <- kcHsContext context
386 ; ty' <- kcLiftedType ty
387 -- The body of a forall is usually a type, but in principle
388 -- there's no reason to prohibit *unlifted* types.
389 -- In fact, GHC can itself construct a function with an
390 -- unboxed tuple inside a for-all (via CPR analyis; see
391 -- typecheck/should_compile/tc170)
393 -- Still, that's only for internal interfaces, which aren't
394 -- kind-checked, so we only allow liftedTypeKind here
396 ; return (HsForAllTy exp tv_names' ctxt' ty', liftedTypeKind) }
398 kc_hs_type (HsBangTy b ty) = do
399 (ty', kind) <- kc_lhs_type ty
400 return (HsBangTy b ty', kind)
402 kc_hs_type ty@(HsSpliceTy _)
403 = failWithTc (ptext (sLit "Unexpected type splice:") <+> ppr ty)
405 -- remove the doc nodes here, no need to worry about the location since
406 -- its the same for a doc node and it's child type node
407 kc_hs_type (HsDocTy ty _)
408 = kc_hs_type (unLoc ty)
410 ---------------------------
411 kcApps :: Outputable a
413 -> TcKind -- Function kind
414 -> [LHsType Name] -- Arg types
415 -> TcM ([LHsType Name], TcKind) -- Kind-checked args
416 kcApps the_fun fun_kind args
417 = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
418 ; args' <- kc_check_lhs_types args_w_kinds
419 ; return (args', res_kind) }
421 kcCheckApps :: Outputable a => a -> TcKind -> [LHsType Name]
422 -> HsType Name -- The type being checked (for err messages only)
423 -> ExpKind -- Expected kind
424 -> TcM [LHsType Name]
425 kcCheckApps the_fun fun_kind args ty exp_kind
426 = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
427 ; checkExpectedKind ty res_kind exp_kind
428 -- Check the result kind *before* checking argument kinds
429 -- This improves error message; Trac #2994
430 ; kc_check_lhs_types args_w_kinds }
432 splitHsAppTys :: LHsType Name -> LHsType Name -> (LHsType Name, [LHsType Name])
433 splitHsAppTys fun_ty arg_ty = split fun_ty [arg_ty]
435 split (L _ (HsAppTy f a)) as = split f (a:as)
438 mkHsAppTys :: LHsType Name -> [LHsType Name] -> HsType Name
439 mkHsAppTys fun_ty [] = pprPanic "mkHsAppTys" (ppr fun_ty)
440 mkHsAppTys fun_ty (arg_ty:arg_tys)
441 = foldl mk_app (HsAppTy fun_ty arg_ty) arg_tys
443 mk_app fun arg = HsAppTy (noLoc fun) arg -- Add noLocs for inner nodes of
444 -- the application; they are
447 ---------------------------
448 splitFunKind :: SDoc -> Int -> TcKind -> [b] -> TcM ([(b,ExpKind)], TcKind)
449 splitFunKind _ _ fk [] = return ([], fk)
450 splitFunKind the_fun arg_no fk (arg:args)
451 = do { mb_fk <- unifyFunKind fk
453 Nothing -> failWithTc too_many_args
454 Just (ak,fk') -> do { (aks, rk) <- splitFunKind the_fun (arg_no+1) fk' args
455 ; return ((arg, EK ak (EkArg the_fun arg_no)):aks, rk) } }
457 too_many_args = quotes the_fun <+>
458 ptext (sLit "is applied to too many type arguments")
460 ---------------------------
461 kcHsContext :: LHsContext Name -> TcM (LHsContext Name)
462 kcHsContext ctxt = wrapLocM (mapM kcHsLPred) ctxt
464 kcHsLPred :: LHsPred Name -> TcM (LHsPred Name)
465 kcHsLPred = wrapLocM kcHsPred
467 kcHsPred :: HsPred Name -> TcM (HsPred Name)
468 kcHsPred pred = do -- Checks that the result is of kind liftedType
469 (pred', kind) <- kc_pred pred
470 checkExpectedKind pred kind ekLifted
473 ---------------------------
474 kc_pred :: HsPred Name -> TcM (HsPred Name, TcKind)
475 -- Does *not* check for a saturated
476 -- application (reason: used from TcDeriv)
477 kc_pred (HsIParam name ty)
478 = do { (ty', kind) <- kc_lhs_type ty
479 ; return (HsIParam name ty', kind)
481 kc_pred (HsClassP cls tys)
482 = do { kind <- kcClass cls
483 ; (tys', res_kind) <- kcApps cls kind tys
484 ; return (HsClassP cls tys', res_kind)
486 kc_pred (HsEqualP ty1 ty2)
487 = do { (ty1', kind1) <- kc_lhs_type ty1
488 -- ; checkExpectedKind ty1 kind1 liftedTypeKind
489 ; (ty2', kind2) <- kc_lhs_type ty2
490 -- ; checkExpectedKind ty2 kind2 liftedTypeKind
491 ; checkExpectedKind ty2 kind2 (EK kind1 EkEqPred)
492 ; return (HsEqualP ty1' ty2', liftedTypeKind)
495 ---------------------------
496 kcTyVar :: Name -> TcM TcKind
497 kcTyVar name = do -- Could be a tyvar or a tycon
498 traceTc (text "lk1" <+> ppr name)
499 thing <- tcLookup name
500 traceTc (text "lk2" <+> ppr name <+> ppr thing)
502 ATyVar _ ty -> return (typeKind ty)
503 AThing kind -> return kind
504 AGlobal (ATyCon tc) -> return (tyConKind tc)
505 _ -> wrongThingErr "type" thing name
507 kcClass :: Name -> TcM TcKind
508 kcClass cls = do -- Must be a class
509 thing <- tcLookup cls
511 AThing kind -> return kind
512 AGlobal (AClass cls) -> return (tyConKind (classTyCon cls))
513 _ -> wrongThingErr "class" thing cls
517 %************************************************************************
521 %************************************************************************
525 * Transforms from HsType to Type
528 It cannot fail, and does no validity checking, except for
529 structural matters, such as
530 (a) spurious ! annotations.
531 (b) a class used as a type
534 dsHsType :: LHsType Name -> TcM Type
535 -- All HsTyVarBndrs in the intput type are kind-annotated
536 dsHsType ty = ds_type (unLoc ty)
538 ds_type :: HsType Name -> TcM Type
539 ds_type ty@(HsTyVar _)
542 ds_type (HsParTy ty) -- Remove the parentheses markers
545 ds_type ty@(HsBangTy _ _) -- No bangs should be here
546 = failWithTc (ptext (sLit "Unexpected strictness annotation:") <+> ppr ty)
548 ds_type (HsKindSig ty _)
549 = dsHsType ty -- Kind checking done already
551 ds_type (HsListTy ty) = do
552 tau_ty <- dsHsType ty
553 checkWiredInTyCon listTyCon
554 return (mkListTy tau_ty)
556 ds_type (HsPArrTy ty) = do
557 tau_ty <- dsHsType ty
558 checkWiredInTyCon parrTyCon
559 return (mkPArrTy tau_ty)
561 ds_type (HsTupleTy boxity tys) = do
562 tau_tys <- dsHsTypes tys
563 checkWiredInTyCon tycon
564 return (mkTyConApp tycon tau_tys)
566 tycon = tupleTyCon boxity (length tys)
568 ds_type (HsFunTy ty1 ty2) = do
569 tau_ty1 <- dsHsType ty1
570 tau_ty2 <- dsHsType ty2
571 return (mkFunTy tau_ty1 tau_ty2)
573 ds_type (HsOpTy ty1 (L span op) ty2) = do
574 tau_ty1 <- dsHsType ty1
575 tau_ty2 <- dsHsType ty2
576 setSrcSpan span (ds_var_app op [tau_ty1,tau_ty2])
580 tc <- tcLookupTyCon genUnitTyConName
581 return (mkTyConApp tc [])
583 ds_type ty@(HsAppTy _ _)
586 ds_type (HsPredTy pred) = do
587 pred' <- dsHsPred pred
588 return (mkPredTy pred')
590 ds_type (HsForAllTy _ tv_names ctxt ty)
591 = tcTyVarBndrs tv_names $ \ tyvars -> do
592 theta <- mapM dsHsLPred (unLoc ctxt)
594 return (mkSigmaTy tyvars theta tau)
596 ds_type (HsSpliceTy {}) = panic "ds_type: HsSpliceTy"
598 ds_type (HsDocTy ty _) -- Remove the doc comment
601 dsHsTypes :: [LHsType Name] -> TcM [Type]
602 dsHsTypes arg_tys = mapM dsHsType arg_tys
605 Help functions for type applications
606 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
609 ds_app :: HsType Name -> [LHsType Name] -> TcM Type
610 ds_app (HsAppTy ty1 ty2) tys
611 = ds_app (unLoc ty1) (ty2:tys)
614 arg_tys <- dsHsTypes tys
616 HsTyVar fun -> ds_var_app fun arg_tys
617 _ -> do fun_ty <- ds_type ty
618 return (mkAppTys fun_ty arg_tys)
620 ds_var_app :: Name -> [Type] -> TcM Type
621 ds_var_app name arg_tys = do
622 thing <- tcLookup name
624 ATyVar _ ty -> return (mkAppTys ty arg_tys)
625 AGlobal (ATyCon tc) -> return (mkTyConApp tc arg_tys)
626 _ -> wrongThingErr "type" thing name
634 dsHsLPred :: LHsPred Name -> TcM PredType
635 dsHsLPred pred = dsHsPred (unLoc pred)
637 dsHsPred :: HsPred Name -> TcM PredType
638 dsHsPred (HsClassP class_name tys)
639 = do { arg_tys <- dsHsTypes tys
640 ; clas <- tcLookupClass class_name
641 ; return (ClassP clas arg_tys)
643 dsHsPred (HsEqualP ty1 ty2)
644 = do { arg_ty1 <- dsHsType ty1
645 ; arg_ty2 <- dsHsType ty2
646 ; return (EqPred arg_ty1 arg_ty2)
648 dsHsPred (HsIParam name ty)
649 = do { arg_ty <- dsHsType ty
650 ; return (IParam name arg_ty)
654 GADT constructor signatures
657 tcLHsConResTy :: LHsType Name -> TcM (TyCon, [TcType])
658 tcLHsConResTy (L span res_ty)
660 case get_args res_ty [] of
661 (HsTyVar tc_name, args)
662 -> do { args' <- mapM dsHsType args
663 ; thing <- tcLookup tc_name
665 AGlobal (ATyCon tc) -> return (tc, args')
666 _ -> failWithTc (badGadtDecl res_ty) }
667 _ -> failWithTc (badGadtDecl res_ty)
669 -- We can't call dsHsType on res_ty, and then do tcSplitTyConApp_maybe
670 -- because that causes a black hole, and for good reason. Building
671 -- the type means expanding type synonyms, and we can't do that
672 -- inside the "knot". So we have to work by steam.
673 get_args (HsAppTy (L _ fun) arg) args = get_args fun (arg:args)
674 get_args (HsParTy (L _ ty)) args = get_args ty args
675 get_args (HsOpTy ty1 (L _ tc) ty2) args = (HsTyVar tc, ty1:ty2:args)
676 get_args ty args = (ty, args)
678 badGadtDecl :: HsType Name -> SDoc
680 = hang (ptext (sLit "Malformed constructor result type:"))
683 addKcTypeCtxt :: LHsType Name -> TcM a -> TcM a
684 -- Wrap a context around only if we want to show that contexts.
685 addKcTypeCtxt (L _ (HsPredTy _)) thing = thing
686 -- Omit invisble ones and ones user's won't grok (HsPred p).
687 addKcTypeCtxt (L _ other_ty) thing = addErrCtxt (typeCtxt other_ty) thing
689 typeCtxt :: HsType Name -> SDoc
690 typeCtxt ty = ptext (sLit "In the type") <+> quotes (ppr ty)
693 %************************************************************************
695 Type-variable binders
697 %************************************************************************
701 kcHsTyVars :: [LHsTyVarBndr Name]
702 -> ([LHsTyVarBndr Name] -> TcM r) -- These binders are kind-annotated
703 -- They scope over the thing inside
705 kcHsTyVars tvs thing_inside = do
706 bndrs <- mapM (wrapLocM kcHsTyVar) tvs
707 tcExtendKindEnvTvs bndrs (thing_inside bndrs)
709 kcHsTyVar :: HsTyVarBndr Name -> TcM (HsTyVarBndr Name)
710 -- Return a *kind-annotated* binder, and a tyvar with a mutable kind in it
711 kcHsTyVar (UserTyVar name) = KindedTyVar name <$> newKindVar
712 kcHsTyVar (KindedTyVar name kind) = return (KindedTyVar name kind)
715 tcTyVarBndrs :: [LHsTyVarBndr Name] -- Kind-annotated binders, which need kind-zonking
716 -> ([TyVar] -> TcM r)
718 -- Used when type-checking types/classes/type-decls
719 -- Brings into scope immutable TyVars, not mutable ones that require later zonking
720 tcTyVarBndrs bndrs thing_inside = do
721 tyvars <- mapM (zonk . unLoc) bndrs
722 tcExtendTyVarEnv tyvars (thing_inside tyvars)
724 zonk (KindedTyVar name kind) = do { kind' <- zonkTcKindToKind kind
725 ; return (mkTyVar name kind') }
726 zonk (UserTyVar name) = WARN( True, ptext (sLit "Un-kinded tyvar") <+> ppr name )
727 return (mkTyVar name liftedTypeKind)
729 -----------------------------------
730 tcDataKindSig :: Maybe Kind -> TcM [TyVar]
731 -- GADT decls can have a (perhaps partial) kind signature
732 -- e.g. data T :: * -> * -> * where ...
733 -- This function makes up suitable (kinded) type variables for
734 -- the argument kinds, and checks that the result kind is indeed *.
735 -- We use it also to make up argument type variables for for data instances.
736 tcDataKindSig Nothing = return []
737 tcDataKindSig (Just kind)
738 = do { checkTc (isLiftedTypeKind res_kind) (badKindSig kind)
739 ; span <- getSrcSpanM
740 ; us <- newUniqueSupply
741 ; let uniqs = uniqsFromSupply us
742 ; return [ mk_tv span uniq str kind
743 | ((kind, str), uniq) <- arg_kinds `zip` dnames `zip` uniqs ] }
745 (arg_kinds, res_kind) = splitKindFunTys kind
746 mk_tv loc uniq str kind = mkTyVar name kind
748 name = mkInternalName uniq occ loc
749 occ = mkOccName tvName str
751 dnames = map ('$' :) names -- Note [Avoid name clashes for associated data types]
754 names = [ c:cs | cs <- "" : names, c <- ['a'..'z'] ]
756 badKindSig :: Kind -> SDoc
758 = hang (ptext (sLit "Kind signature on data type declaration has non-* return kind"))
762 Note [Avoid name clashes for associated data types]
763 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
764 Consider class C a b where
766 When typechecking the decl for D, we'll invent an extra type variable for D,
767 to fill out its kind. We *don't* want this type variable to be 'a', because
768 in an .hi file we'd get
771 which makes it look as if there are *two* type indices. But there aren't!
772 So we use $a instead, which cannot clash with a user-written type variable.
773 Remember that type variable binders in interface files are just FastStrings,
776 (The tidying phase can't help here because we don't tidy TyCons. Another
777 alternative would be to record the number of indexing parameters in the
781 %************************************************************************
783 Scoped type variables
785 %************************************************************************
788 tcAddScopedTyVars is used for scoped type variables added by pattern
790 e.g. \ ((x::a), (y::a)) -> x+y
791 They never have explicit kinds (because this is source-code only)
792 They are mutable (because they can get bound to a more specific type).
794 Usually we kind-infer and expand type splices, and then
795 tupecheck/desugar the type. That doesn't work well for scoped type
796 variables, because they scope left-right in patterns. (e.g. in the
797 example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
799 The current not-very-good plan is to
800 * find all the types in the patterns
801 * find their free tyvars
803 * bring the kinded type vars into scope
804 * BUT throw away the kind-checked type
805 (we'll kind-check it again when we type-check the pattern)
807 This is bad because throwing away the kind checked type throws away
808 its splices. But too bad for now. [July 03]
811 We no longer specify that these type variables must be univerally
812 quantified (lots of email on the subject). If you want to put that
814 a) Do a checkSigTyVars after thing_inside
815 b) More insidiously, don't pass in expected_ty, else
816 we unify with it too early and checkSigTyVars barfs
817 Instead you have to pass in a fresh ty var, and unify
818 it with expected_ty afterwards
821 tcHsPatSigType :: UserTypeCtxt
822 -> LHsType Name -- The type signature
823 -> TcM ([TyVar], -- Newly in-scope type variables
824 Type) -- The signature
825 -- Used for type-checking type signatures in
826 -- (a) patterns e.g f (x::Int) = e
827 -- (b) result signatures e.g. g x :: Int = e
828 -- (c) RULE forall bndrs e.g. forall (x::Int). f x = x
830 tcHsPatSigType ctxt hs_ty
831 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
832 do { -- Find the type variables that are mentioned in the type
833 -- but not already in scope. These are the ones that
834 -- should be bound by the pattern signature
835 in_scope <- getInLocalScope
836 ; let span = getLoc hs_ty
837 sig_tvs = [ L span (UserTyVar n)
838 | n <- nameSetToList (extractHsTyVars hs_ty),
841 ; (tyvars, sig_ty) <- tcHsQuantifiedType sig_tvs hs_ty
842 ; checkValidType ctxt sig_ty
843 ; return (tyvars, sig_ty)
846 tcPatSig :: UserTypeCtxt
849 -> TcM (TcType, -- The type to use for "inside" the signature
850 [(Name, TcType)], -- The new bit of type environment, binding
851 -- the scoped type variables
852 CoercionI) -- Coercion due to unification with actual ty
853 tcPatSig ctxt sig res_ty
854 = do { (sig_tvs, sig_ty) <- tcHsPatSigType ctxt sig
856 ; if null sig_tvs then do {
857 -- The type signature binds no type variables,
858 -- and hence is rigid, so use it to zap the res_ty
859 coi <- boxyUnify sig_ty res_ty
860 ; return (sig_ty, [], coi)
863 -- Type signature binds at least one scoped type variable
865 -- A pattern binding cannot bind scoped type variables
866 -- The renamer fails with a name-out-of-scope error
867 -- if a pattern binding tries to bind a type variable,
868 -- So we just have an ASSERT here
869 ; let in_pat_bind = case ctxt of
870 BindPatSigCtxt -> True
872 ; ASSERT( not in_pat_bind || null sig_tvs ) return ()
874 -- Check that pat_ty is rigid
875 ; checkTc (isRigidTy res_ty) (wobblyPatSig sig_tvs)
877 -- Now match the pattern signature against res_ty
878 -- For convenience, and uniform-looking error messages
879 -- we do the matching by allocating meta type variables,
880 -- unifying, and reading out the results.
881 -- This is a strictly local operation.
882 ; box_tvs <- mapM tcInstBoxyTyVar sig_tvs
883 ; coi <- boxyUnify (substTyWith sig_tvs (mkTyVarTys box_tvs) sig_ty)
885 ; sig_tv_tys <- mapM readFilledBox box_tvs
887 -- Check that each is bound to a distinct type variable,
888 -- and one that is not already in scope
889 ; let tv_binds = map tyVarName sig_tvs `zip` sig_tv_tys
890 ; binds_in_scope <- getScopedTyVarBinds
891 ; check binds_in_scope tv_binds
894 ; return (res_ty, tv_binds, coi)
897 check _ [] = return ()
898 check in_scope ((n,ty):rest) = do { check_one in_scope n ty
899 ; check ((n,ty):in_scope) rest }
901 check_one in_scope n ty
902 = do { checkTc (tcIsTyVarTy ty) (scopedNonVar n ty)
903 -- Must bind to a type variable
905 ; checkTc (null dups) (dupInScope n (head dups) ty)
906 -- Must not bind to the same type variable
907 -- as some other in-scope type variable
911 dups = [n' | (n',ty') <- in_scope, tcEqType ty' ty]
915 %************************************************************************
919 %************************************************************************
921 We would like to get a decent error message from
922 (a) Under-applied type constructors
924 (b) Over-applied type constructors
928 -- The ExpKind datatype means "expected kind" and contains
929 -- some info about just why that kind is expected, to improve
930 -- the error message on a mis-match
931 data ExpKind = EK TcKind EkCtxt
932 data EkCtxt = EkUnk -- Unknown context
933 | EkEqPred -- Second argument of an equality predicate
934 | EkKindSig -- Kind signature
935 | EkArg SDoc Int -- Function, arg posn, expected kind
938 ekLifted, ekOpen :: ExpKind
939 ekLifted = EK liftedTypeKind EkUnk
940 ekOpen = EK openTypeKind EkUnk
942 checkExpectedKind :: Outputable a => a -> TcKind -> ExpKind -> TcM ()
943 -- A fancy wrapper for 'unifyKind', which tries
944 -- to give decent error messages.
945 -- (checkExpectedKind ty act_kind exp_kind)
946 -- checks that the actual kind act_kind is compatible
947 -- with the expected kind exp_kind
948 -- The first argument, ty, is used only in the error message generation
949 checkExpectedKind ty act_kind (EK exp_kind ek_ctxt)
950 | act_kind `isSubKind` exp_kind -- Short cut for a very common case
953 (_errs, mb_r) <- tryTc (unifyKind exp_kind act_kind)
955 Just _ -> return () -- Unification succeeded
958 -- So there's definitely an error
959 -- Now to find out what sort
960 exp_kind <- zonkTcKind exp_kind
961 act_kind <- zonkTcKind act_kind
963 env0 <- tcInitTidyEnv
964 let (exp_as, _) = splitKindFunTys exp_kind
965 (act_as, _) = splitKindFunTys act_kind
966 n_exp_as = length exp_as
967 n_act_as = length act_as
969 (env1, tidy_exp_kind) = tidyKind env0 exp_kind
970 (env2, tidy_act_kind) = tidyKind env1 act_kind
972 err | n_exp_as < n_act_as -- E.g. [Maybe]
973 = quotes (ppr ty) <+> ptext (sLit "is not applied to enough type arguments")
975 -- Now n_exp_as >= n_act_as. In the next two cases,
976 -- n_exp_as == 0, and hence so is n_act_as
977 | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
978 = ptext (sLit "Expecting a lifted type, but") <+> quotes (ppr ty)
979 <+> ptext (sLit "is unlifted")
981 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
982 = ptext (sLit "Expecting an unlifted type, but") <+> quotes (ppr ty)
983 <+> ptext (sLit "is lifted")
985 | otherwise -- E.g. Monad [Int]
986 = ptext (sLit "Kind mis-match")
988 more_info = sep [ expected_herald ek_ctxt <+> ptext (sLit "kind")
989 <+> quotes (pprKind tidy_exp_kind) <> comma,
990 ptext (sLit "but") <+> quotes (ppr ty) <+>
991 ptext (sLit "has kind") <+> quotes (pprKind tidy_act_kind)]
993 expected_herald EkUnk = ptext (sLit "Expected")
994 expected_herald EkKindSig = ptext (sLit "An enclosing kind signature specified")
995 expected_herald EkEqPred = ptext (sLit "The left argument of the equality predicate had")
996 expected_herald (EkArg fun arg_no)
997 = ptext (sLit "The") <+> speakNth arg_no <+> ptext (sLit "argument of")
998 <+> quotes fun <+> ptext (sLit ("should have"))
1000 failWithTcM (env2, err $$ more_info)
1003 %************************************************************************
1005 Scoped type variables
1007 %************************************************************************
1010 pprHsSigCtxt :: UserTypeCtxt -> LHsType Name -> SDoc
1011 pprHsSigCtxt ctxt hs_ty = vcat [ ptext (sLit "In") <+> pprUserTypeCtxt ctxt <> colon,
1012 nest 2 (pp_sig ctxt) ]
1014 pp_sig (FunSigCtxt n) = pp_n_colon n
1015 pp_sig (ConArgCtxt n) = pp_n_colon n
1016 pp_sig (ForSigCtxt n) = pp_n_colon n
1017 pp_sig _ = ppr (unLoc hs_ty)
1019 pp_n_colon n = ppr n <+> dcolon <+> ppr (unLoc hs_ty)
1021 wobblyPatSig :: [Var] -> SDoc
1022 wobblyPatSig sig_tvs
1023 = hang (ptext (sLit "A pattern type signature cannot bind scoped type variables")
1024 <+> pprQuotedList sig_tvs)
1025 2 (ptext (sLit "unless the pattern has a rigid type context"))
1027 scopedNonVar :: Name -> Type -> SDoc
1029 = vcat [sep [ptext (sLit "The scoped type variable") <+> quotes (ppr n),
1030 nest 2 (ptext (sLit "is bound to the type") <+> quotes (ppr ty))],
1031 nest 2 (ptext (sLit "You can only bind scoped type variables to type variables"))]
1033 dupInScope :: Name -> Name -> Type -> SDoc
1035 = hang (ptext (sLit "The scoped type variables") <+> quotes (ppr n) <+> ptext (sLit "and") <+> quotes (ppr n'))
1036 2 (vcat [ptext (sLit "are bound to the same type (variable)"),
1037 ptext (sLit "Distinct scoped type variables must be distinct")])
1039 wrongEqualityErr :: TcM (HsType Name, TcKind)
1041 = failWithTc (text "Equality predicate used as a type")