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