2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 \section[TcMonoType]{Typechecking user-specified @MonoTypes@}
8 {-# LANGUAGE RelaxedPolyRec #-}
11 tcHsSigType, tcHsDeriv,
12 tcHsInstHead, tcHsQuantifiedType,
16 kcHsTyVars, kcHsSigType, kcHsLiftedSigType,
17 kcLHsType, kcCheckLHsType, kcHsContext,
19 -- Typechecking kinded types
20 tcHsKindedContext, tcHsKindedType, tcHsBangType,
21 tcTyVarBndrs, dsHsType, tcLHsConResTy,
24 -- Pattern type signatures
25 tcHsPatSigType, tcPatSig
28 #include "HsVersions.h"
38 import {- Kind parts of -} Type
58 ----------------------------
60 ----------------------------
62 Generally speaking we now type-check types in three phases
64 1. kcHsType: kind check the HsType
65 *includes* performing any TH type splices;
66 so it returns a translated, and kind-annotated, type
68 2. dsHsType: convert from HsType to Type:
70 expand type synonyms [mkGenTyApps]
71 hoist the foralls [tcHsType]
73 3. checkValidType: check the validity of the resulting type
75 Often these steps are done one after the other (tcHsSigType).
76 But in mutually recursive groups of type and class decls we do
77 1 kind-check the whole group
78 2 build TyCons/Classes in a knot-tied way
79 3 check the validity of types in the now-unknotted TyCons/Classes
81 For example, when we find
82 (forall a m. m a -> m a)
83 we bind a,m to kind varibles and kind-check (m a -> m a). This makes
84 a get kind *, and m get kind *->*. Now we typecheck (m a -> m a) in
85 an environment that binds a and m suitably.
87 The kind checker passed to tcHsTyVars needs to look at enough to
88 establish the kind of the tyvar:
89 * For a group of type and class decls, it's just the group, not
90 the rest of the program
91 * For a tyvar bound in a pattern type signature, its the types
92 mentioned in the other type signatures in that bunch of patterns
93 * For a tyvar bound in a RULE, it's the type signatures on other
94 universally quantified variables in the rule
96 Note that this may occasionally give surprising results. For example:
98 data T a b = MkT (a b)
100 Here we deduce a::*->*, b::*
101 But equally valid would be a::(*->*)-> *, b::*->*
106 Some of the validity check could in principle be done by the kind checker,
109 - During desugaring, we normalise by expanding type synonyms. Only
110 after this step can we check things like type-synonym saturation
111 e.g. type T k = k Int
113 Then (T S) is ok, because T is saturated; (T S) expands to (S Int);
114 and then S is saturated. This is a GHC extension.
116 - Similarly, also a GHC extension, we look through synonyms before complaining
117 about the form of a class or instance declaration
119 - Ambiguity checks involve functional dependencies, and it's easier to wait
120 until knots have been resolved before poking into them
122 Also, in a mutually recursive group of types, we can't look at the TyCon until we've
123 finished building the loop. So to keep things simple, we postpone most validity
124 checking until step (3).
128 During step (1) we might fault in a TyCon defined in another module, and it might
129 (via a loop) refer back to a TyCon defined in this module. So when we tie a big
130 knot around type declarations with ARecThing, so that the fault-in code can get
131 the TyCon being defined.
134 %************************************************************************
136 \subsection{Checking types}
138 %************************************************************************
141 tcHsSigType :: UserTypeCtxt -> LHsType Name -> TcM Type
142 -- Do kind checking, and hoist for-alls to the top
143 -- NB: it's important that the foralls that come from the top-level
144 -- HsForAllTy in hs_ty occur *first* in the returned type.
145 -- See Note [Scoped] with TcSigInfo
146 tcHsSigType ctxt hs_ty
147 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
148 do { kinded_ty <- kcTypeType hs_ty
149 ; ty <- tcHsKindedType kinded_ty
150 ; checkValidType ctxt ty
153 tcHsInstHead :: LHsType Name -> TcM ([TyVar], ThetaType, Type)
154 -- Typecheck an instance head. We can't use
155 -- tcHsSigType, because it's not a valid user type.
157 = do { kinded_ty <- kcHsSigType hs_ty
158 ; poly_ty <- tcHsKindedType kinded_ty
159 ; return (tcSplitSigmaTy poly_ty) }
161 tcHsQuantifiedType :: [LHsTyVarBndr Name] -> LHsType Name -> TcM ([TyVar], Type)
162 -- Behave very like type-checking (HsForAllTy sig_tvs hs_ty),
163 -- except that we want to keep the tvs separate
164 tcHsQuantifiedType tv_names hs_ty
165 = kcHsTyVars tv_names $ \ tv_names' ->
166 do { kc_ty <- kcHsSigType hs_ty
167 ; tcTyVarBndrs tv_names' $ \ tvs ->
168 do { ty <- dsHsType kc_ty
169 ; return (tvs, ty) } }
171 -- Used for the deriving(...) items
172 tcHsDeriv :: HsType Name -> TcM ([TyVar], Class, [Type])
173 tcHsDeriv = tc_hs_deriv []
175 tc_hs_deriv :: [LHsTyVarBndr Name] -> HsType Name
176 -> TcM ([TyVar], Class, [Type])
177 tc_hs_deriv tv_names (HsPredTy (HsClassP cls_name hs_tys))
178 = kcHsTyVars tv_names $ \ tv_names' ->
179 do { cls_kind <- kcClass cls_name
180 ; (tys, _res_kind) <- kcApps cls_name cls_kind hs_tys
181 ; tcTyVarBndrs tv_names' $ \ tyvars ->
182 do { arg_tys <- dsHsTypes tys
183 ; cls <- tcLookupClass cls_name
184 ; return (tyvars, cls, arg_tys) }}
186 tc_hs_deriv tv_names1 (HsForAllTy _ tv_names2 (L _ []) (L _ ty))
187 = -- Funny newtype deriving form
189 -- where C has arity 2. Hence can't use regular functions
190 tc_hs_deriv (tv_names1 ++ tv_names2) ty
193 = failWithTc (ptext (sLit "Illegal deriving item") <+> ppr other)
196 These functions are used during knot-tying in
197 type and class declarations, when we have to
198 separate kind-checking, desugaring, and validity checking
201 kcHsSigType, kcHsLiftedSigType :: LHsType Name -> TcM (LHsType Name)
202 -- Used for type signatures
203 kcHsSigType ty = addKcTypeCtxt ty $ kcTypeType ty
204 kcHsLiftedSigType ty = addKcTypeCtxt ty $ kcLiftedType ty
206 tcHsKindedType :: LHsType Name -> TcM Type
207 -- Don't do kind checking, nor validity checking.
208 -- This is used in type and class decls, where kinding is
209 -- done in advance, and validity checking is done later
210 -- [Validity checking done later because of knot-tying issues.]
211 tcHsKindedType hs_ty = dsHsType hs_ty
213 tcHsBangType :: LHsType Name -> TcM Type
214 -- Permit a bang, but discard it
215 tcHsBangType (L _ (HsBangTy _ ty)) = tcHsKindedType ty
216 tcHsBangType ty = tcHsKindedType ty
218 tcHsKindedContext :: LHsContext Name -> TcM ThetaType
219 -- Used when we are expecting a ClassContext (i.e. no implicit params)
220 -- Does not do validity checking, like tcHsKindedType
221 tcHsKindedContext hs_theta = addLocM (mapM dsHsLPred) hs_theta
225 %************************************************************************
227 The main kind checker: kcHsType
229 %************************************************************************
231 First a couple of simple wrappers for kcHsType
234 ---------------------------
235 kcLiftedType :: LHsType Name -> TcM (LHsType Name)
236 -- The type ty must be a *lifted* *type*
237 kcLiftedType ty = kc_check_lhs_type ty liftedTypeKind
239 ---------------------------
240 kcTypeType :: LHsType Name -> TcM (LHsType Name)
241 -- The type ty must be a *type*, but it can be lifted or
242 -- unlifted or an unboxed tuple.
243 kcTypeType ty = kc_check_lhs_type ty openTypeKind
245 ---------------------------
246 kcCheckLHsType :: LHsType Name -> TcKind -> TcM (LHsType Name)
247 kcCheckLHsType ty kind = addKcTypeCtxt ty $ kc_check_lhs_type ty kind
250 kc_check_lhs_type :: LHsType Name -> TcKind -> TcM (LHsType Name)
251 -- Check that the type has the specified kind
252 -- Be sure to use checkExpectedKind, rather than simply unifying
253 -- with OpenTypeKind, because it gives better error messages
254 kc_check_lhs_type (L span ty) exp_kind
256 do { ty' <- kc_check_hs_type ty exp_kind
257 ; return (L span ty') }
259 kc_check_lhs_types :: [(LHsType Name,TcKind)] -> TcM [LHsType Name]
260 kc_check_lhs_types tys_w_kinds
261 = mapM kc_arg tys_w_kinds
263 kc_arg (arg, arg_kind) = kc_check_lhs_type arg arg_kind
266 ---------------------------
267 kc_check_hs_type :: HsType Name -> TcKind -> TcM (HsType Name)
269 -- First some special cases for better error messages
270 -- when we know the expected kind
271 kc_check_hs_type (HsParTy ty) exp_kind
272 = do { ty' <- kc_check_lhs_type ty exp_kind; return (HsParTy ty') }
274 kc_check_hs_type ty@(HsAppTy ty1 ty2) exp_kind
275 = do { let (fun_ty, arg_tys) = splitHsAppTys ty1 ty2
276 ; (fun_ty', fun_kind) <- kc_lhs_type fun_ty
277 ; arg_tys' <- kcCheckApps fun_ty fun_kind arg_tys ty exp_kind
278 ; return (mkHsAppTys fun_ty' arg_tys') }
280 kc_check_hs_type ty@(HsPredTy (HsClassP cls tys)) exp_kind
281 = do { cls_kind <- kcClass cls
282 ; tys' <- kcCheckApps cls cls_kind tys ty exp_kind
283 ; return (HsPredTy (HsClassP cls tys')) }
285 -- This is the general case: infer the kind and compare
286 kc_check_hs_type ty exp_kind
287 = do { (ty', act_kind) <- kc_hs_type ty
288 -- Add the context round the inner check only
289 -- because checkExpectedKind already mentions
290 -- 'ty' by name in any error message
292 ; checkExpectedKind (strip ty) act_kind exp_kind
295 -- We infer the kind of the type, and then complain if it's
296 -- not right. But we don't want to complain about
297 -- (ty) or !(ty) or forall a. ty
298 -- when the real difficulty is with the 'ty' part.
299 strip (HsParTy (L _ ty)) = strip ty
300 strip (HsBangTy _ (L _ ty)) = strip ty
301 strip (HsForAllTy _ _ _ (L _ ty)) = strip ty
306 Here comes the main function
309 kcLHsType :: LHsType Name -> TcM (LHsType Name, TcKind)
310 -- Called from outside: set the context
311 kcLHsType ty = addKcTypeCtxt ty (kc_lhs_type ty)
313 kc_lhs_type :: LHsType Name -> TcM (LHsType Name, TcKind)
314 kc_lhs_type (L span ty)
316 do { (ty', kind) <- kc_hs_type ty
317 ; return (L span ty', kind) }
319 -- kc_hs_type *returns* the kind of the type, rather than taking an expected
320 -- kind as argument as tcExpr does.
322 -- (a) the kind of (->) is
323 -- forall bx1 bx2. Type bx1 -> Type bx2 -> Type Boxed
324 -- so we'd need to generate huge numbers of bx variables.
325 -- (b) kinds are so simple that the error messages are fine
327 -- The translated type has explicitly-kinded type-variable binders
329 kc_hs_type :: HsType Name -> TcM (HsType Name, TcKind)
330 kc_hs_type (HsParTy ty) = do
331 (ty', kind) <- kc_lhs_type ty
332 return (HsParTy ty', kind)
334 kc_hs_type (HsTyVar name) = do
336 return (HsTyVar name, kind)
338 kc_hs_type (HsListTy ty) = do
339 ty' <- kcLiftedType ty
340 return (HsListTy ty', liftedTypeKind)
342 kc_hs_type (HsPArrTy ty) = do
343 ty' <- kcLiftedType ty
344 return (HsPArrTy ty', liftedTypeKind)
346 kc_hs_type (HsNumTy n)
347 = return (HsNumTy n, liftedTypeKind)
349 kc_hs_type (HsKindSig ty k) = do
350 ty' <- kc_check_lhs_type ty k
351 return (HsKindSig ty' k, k)
353 kc_hs_type (HsTupleTy Boxed tys) = do
354 tys' <- mapM kcLiftedType tys
355 return (HsTupleTy Boxed tys', liftedTypeKind)
357 kc_hs_type (HsTupleTy Unboxed tys) = do
358 tys' <- mapM kcTypeType tys
359 return (HsTupleTy Unboxed tys', ubxTupleKind)
361 kc_hs_type (HsFunTy ty1 ty2) = do
362 ty1' <- kc_check_lhs_type ty1 argTypeKind
363 ty2' <- kcTypeType ty2
364 return (HsFunTy ty1' ty2', liftedTypeKind)
366 kc_hs_type (HsOpTy ty1 op ty2) = do
367 op_kind <- addLocM kcTyVar op
368 ([ty1',ty2'], res_kind) <- kcApps op op_kind [ty1,ty2]
369 return (HsOpTy ty1' op ty2', res_kind)
371 kc_hs_type (HsAppTy ty1 ty2) = do
372 (fun_ty', fun_kind) <- kc_lhs_type fun_ty
373 (arg_tys', res_kind) <- kcApps fun_ty fun_kind arg_tys
374 return (mkHsAppTys fun_ty' arg_tys', res_kind)
376 (fun_ty, arg_tys) = splitHsAppTys ty1 ty2
378 kc_hs_type (HsPredTy (HsEqualP _ _))
381 kc_hs_type (HsPredTy pred) = do
382 pred' <- kcHsPred pred
383 return (HsPredTy pred', liftedTypeKind)
385 kc_hs_type (HsForAllTy exp tv_names context ty)
386 = kcHsTyVars tv_names $ \ tv_names' ->
387 do { ctxt' <- kcHsContext context
388 ; ty' <- kcLiftedType ty
389 -- The body of a forall is usually a type, but in principle
390 -- there's no reason to prohibit *unlifted* types.
391 -- In fact, GHC can itself construct a function with an
392 -- unboxed tuple inside a for-all (via CPR analyis; see
393 -- typecheck/should_compile/tc170)
395 -- Still, that's only for internal interfaces, which aren't
396 -- kind-checked, so we only allow liftedTypeKind here
398 ; return (HsForAllTy exp tv_names' ctxt' ty', liftedTypeKind) }
400 kc_hs_type (HsBangTy b ty) = do
401 (ty', kind) <- kc_lhs_type ty
402 return (HsBangTy b ty', kind)
404 kc_hs_type ty@(HsSpliceTy _)
405 = failWithTc (ptext (sLit "Unexpected type splice:") <+> ppr ty)
407 -- remove the doc nodes here, no need to worry about the location since
408 -- its the same for a doc node and it's child type node
409 kc_hs_type (HsDocTy ty _)
410 = kc_hs_type (unLoc ty)
412 ---------------------------
413 kcApps :: Outputable a
415 -> TcKind -- Function kind
416 -> [LHsType Name] -- Arg types
417 -> TcM ([LHsType Name], TcKind) -- Kind-checked args
418 kcApps the_fun fun_kind args
419 = do { (args_w_kinds, res_kind) <- splitFunKind the_fun fun_kind args
420 ; args' <- kc_check_lhs_types args_w_kinds
421 ; return (args', res_kind) }
423 kcCheckApps :: Outputable a => a -> TcKind -> [LHsType Name]
424 -> HsType Name -- The type being checked (for err messages only)
425 -> TcKind -- Expected kind
426 -> TcM [LHsType Name]
427 kcCheckApps the_fun fun_kind args ty exp_kind
428 = do { (args_w_kinds, res_kind) <- splitFunKind the_fun fun_kind args
429 ; checkExpectedKind ty res_kind exp_kind
430 -- Check the result kind *before* checking argument kinds
431 -- This improves error message; Trac #2994
432 ; kc_check_lhs_types args_w_kinds }
434 splitHsAppTys :: LHsType Name -> LHsType Name -> (LHsType Name, [LHsType Name])
435 splitHsAppTys fun_ty arg_ty = split fun_ty [arg_ty]
437 split (L _ (HsAppTy f a)) as = split f (a:as)
440 mkHsAppTys :: LHsType Name -> [LHsType Name] -> HsType Name
441 mkHsAppTys fun_ty [] = pprPanic "mkHsAppTys" (ppr fun_ty)
442 mkHsAppTys fun_ty (arg_ty:arg_tys)
443 = foldl mk_app (HsAppTy fun_ty arg_ty) arg_tys
445 mk_app fun arg = HsAppTy (noLoc fun) arg -- Add noLocs for inner nodes of
446 -- the application; they are
449 ---------------------------
450 splitFunKind :: Outputable a => a -> TcKind -> [b] -> TcM ([(b,TcKind)], TcKind)
451 splitFunKind _ fk [] = return ([], fk)
452 splitFunKind the_fun fk (arg:args)
453 = do { mb_fk <- unifyFunKind fk
455 Nothing -> failWithTc too_many_args
456 Just (ak,fk') -> do { (aks, rk) <- splitFunKind the_fun fk' args
457 ; return ((arg,ak):aks, rk) } }
459 too_many_args = quotes (ppr the_fun) <+>
460 ptext (sLit "is applied to too many type arguments")
462 ---------------------------
463 kcHsContext :: LHsContext Name -> TcM (LHsContext Name)
464 kcHsContext ctxt = wrapLocM (mapM kcHsLPred) ctxt
466 kcHsLPred :: LHsPred Name -> TcM (LHsPred Name)
467 kcHsLPred = wrapLocM kcHsPred
469 kcHsPred :: HsPred Name -> TcM (HsPred Name)
470 kcHsPred pred = do -- Checks that the result is of kind liftedType
471 (pred', kind) <- kc_pred pred
472 checkExpectedKind pred kind liftedTypeKind
475 ---------------------------
476 kc_pred :: HsPred Name -> TcM (HsPred Name, TcKind)
477 -- Does *not* check for a saturated
478 -- application (reason: used from TcDeriv)
479 kc_pred (HsIParam name ty)
480 = do { (ty', kind) <- kc_lhs_type ty
481 ; return (HsIParam name ty', kind)
483 kc_pred (HsClassP cls tys)
484 = do { kind <- kcClass cls
485 ; (tys', res_kind) <- kcApps cls kind tys
486 ; return (HsClassP cls tys', res_kind)
488 kc_pred (HsEqualP ty1 ty2)
489 = do { (ty1', kind1) <- kc_lhs_type ty1
490 -- ; checkExpectedKind ty1 kind1 liftedTypeKind
491 ; (ty2', kind2) <- kc_lhs_type ty2
492 -- ; checkExpectedKind ty2 kind2 liftedTypeKind
493 ; checkExpectedKind ty2 kind2 kind1
494 ; return (HsEqualP ty1' ty2', liftedTypeKind)
497 ---------------------------
498 kcTyVar :: Name -> TcM TcKind
499 kcTyVar name = do -- Could be a tyvar or a tycon
500 traceTc (text "lk1" <+> ppr name)
501 thing <- tcLookup name
502 traceTc (text "lk2" <+> ppr name <+> ppr thing)
504 ATyVar _ ty -> return (typeKind ty)
505 AThing kind -> return kind
506 AGlobal (ATyCon tc) -> return (tyConKind tc)
507 _ -> wrongThingErr "type" thing name
509 kcClass :: Name -> TcM TcKind
510 kcClass cls = do -- Must be a class
511 thing <- tcLookup cls
513 AThing kind -> return kind
514 AGlobal (AClass cls) -> return (tyConKind (classTyCon cls))
515 _ -> wrongThingErr "class" thing cls
519 %************************************************************************
523 %************************************************************************
527 * Transforms from HsType to Type
530 It cannot fail, and does no validity checking, except for
531 structural matters, such as
532 (a) spurious ! annotations.
533 (b) a class used as a type
536 dsHsType :: LHsType Name -> TcM Type
537 -- All HsTyVarBndrs in the intput type are kind-annotated
538 dsHsType ty = ds_type (unLoc ty)
540 ds_type :: HsType Name -> TcM Type
541 ds_type ty@(HsTyVar _)
544 ds_type (HsParTy ty) -- Remove the parentheses markers
547 ds_type ty@(HsBangTy _ _) -- No bangs should be here
548 = failWithTc (ptext (sLit "Unexpected strictness annotation:") <+> ppr ty)
550 ds_type (HsKindSig ty _)
551 = dsHsType ty -- Kind checking done already
553 ds_type (HsListTy ty) = do
554 tau_ty <- dsHsType ty
555 checkWiredInTyCon listTyCon
556 return (mkListTy tau_ty)
558 ds_type (HsPArrTy ty) = do
559 tau_ty <- dsHsType ty
560 checkWiredInTyCon parrTyCon
561 return (mkPArrTy tau_ty)
563 ds_type (HsTupleTy boxity tys) = do
564 tau_tys <- dsHsTypes tys
565 checkWiredInTyCon tycon
566 return (mkTyConApp tycon tau_tys)
568 tycon = tupleTyCon boxity (length tys)
570 ds_type (HsFunTy ty1 ty2) = do
571 tau_ty1 <- dsHsType ty1
572 tau_ty2 <- dsHsType ty2
573 return (mkFunTy tau_ty1 tau_ty2)
575 ds_type (HsOpTy ty1 (L span op) ty2) = do
576 tau_ty1 <- dsHsType ty1
577 tau_ty2 <- dsHsType ty2
578 setSrcSpan span (ds_var_app op [tau_ty1,tau_ty2])
582 tc <- tcLookupTyCon genUnitTyConName
583 return (mkTyConApp tc [])
585 ds_type ty@(HsAppTy _ _)
588 ds_type (HsPredTy pred) = do
589 pred' <- dsHsPred pred
590 return (mkPredTy pred')
592 ds_type (HsForAllTy _ tv_names ctxt ty)
593 = tcTyVarBndrs tv_names $ \ tyvars -> do
594 theta <- mapM dsHsLPred (unLoc ctxt)
596 return (mkSigmaTy tyvars theta tau)
598 ds_type (HsSpliceTy {}) = panic "ds_type: HsSpliceTy"
600 ds_type (HsDocTy ty _) -- Remove the doc comment
603 dsHsTypes :: [LHsType Name] -> TcM [Type]
604 dsHsTypes arg_tys = mapM dsHsType arg_tys
607 Help functions for type applications
608 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
611 ds_app :: HsType Name -> [LHsType Name] -> TcM Type
612 ds_app (HsAppTy ty1 ty2) tys
613 = ds_app (unLoc ty1) (ty2:tys)
616 arg_tys <- dsHsTypes tys
618 HsTyVar fun -> ds_var_app fun arg_tys
619 _ -> do fun_ty <- ds_type ty
620 return (mkAppTys fun_ty arg_tys)
622 ds_var_app :: Name -> [Type] -> TcM Type
623 ds_var_app name arg_tys = do
624 thing <- tcLookup name
626 ATyVar _ ty -> return (mkAppTys ty arg_tys)
627 AGlobal (ATyCon tc) -> return (mkTyConApp tc arg_tys)
628 _ -> wrongThingErr "type" thing name
636 dsHsLPred :: LHsPred Name -> TcM PredType
637 dsHsLPred pred = dsHsPred (unLoc pred)
639 dsHsPred :: HsPred Name -> TcM PredType
640 dsHsPred (HsClassP class_name tys)
641 = do { arg_tys <- dsHsTypes tys
642 ; clas <- tcLookupClass class_name
643 ; return (ClassP clas arg_tys)
645 dsHsPred (HsEqualP ty1 ty2)
646 = do { arg_ty1 <- dsHsType ty1
647 ; arg_ty2 <- dsHsType ty2
648 ; return (EqPred arg_ty1 arg_ty2)
650 dsHsPred (HsIParam name ty)
651 = do { arg_ty <- dsHsType ty
652 ; return (IParam name arg_ty)
656 GADT constructor signatures
659 tcLHsConResTy :: LHsType Name -> TcM (TyCon, [TcType])
660 tcLHsConResTy (L span res_ty)
662 case get_args res_ty [] of
663 (HsTyVar tc_name, args)
664 -> do { args' <- mapM dsHsType args
665 ; thing <- tcLookup tc_name
667 AGlobal (ATyCon tc) -> return (tc, args')
668 _ -> failWithTc (badGadtDecl res_ty) }
669 _ -> failWithTc (badGadtDecl res_ty)
671 -- We can't call dsHsType on res_ty, and then do tcSplitTyConApp_maybe
672 -- because that causes a black hole, and for good reason. Building
673 -- the type means expanding type synonyms, and we can't do that
674 -- inside the "knot". So we have to work by steam.
675 get_args (HsAppTy (L _ fun) arg) args = get_args fun (arg:args)
676 get_args (HsParTy (L _ ty)) args = get_args ty args
677 get_args (HsOpTy ty1 (L _ tc) ty2) args = (HsTyVar tc, ty1:ty2:args)
678 get_args ty args = (ty, args)
680 badGadtDecl :: HsType Name -> SDoc
682 = hang (ptext (sLit "Malformed constructor result type:"))
685 addKcTypeCtxt :: LHsType Name -> TcM a -> TcM a
686 -- Wrap a context around only if we want to show that contexts.
687 addKcTypeCtxt (L _ (HsPredTy _)) thing = thing
688 -- Omit invisble ones and ones user's won't grok (HsPred p).
689 addKcTypeCtxt (L _ other_ty) thing = addErrCtxt (typeCtxt other_ty) thing
691 typeCtxt :: HsType Name -> SDoc
692 typeCtxt ty = ptext (sLit "In the type") <+> quotes (ppr ty)
695 %************************************************************************
697 Type-variable binders
699 %************************************************************************
703 kcHsTyVars :: [LHsTyVarBndr Name]
704 -> ([LHsTyVarBndr Name] -> TcM r) -- These binders are kind-annotated
705 -- They scope over the thing inside
707 kcHsTyVars tvs thing_inside = do
708 bndrs <- mapM (wrapLocM kcHsTyVar) tvs
709 tcExtendKindEnvTvs bndrs (thing_inside bndrs)
711 kcHsTyVar :: HsTyVarBndr Name -> TcM (HsTyVarBndr Name)
712 -- Return a *kind-annotated* binder, and a tyvar with a mutable kind in it
713 kcHsTyVar (UserTyVar name) = KindedTyVar name <$> newKindVar
714 kcHsTyVar (KindedTyVar name kind) = return (KindedTyVar name kind)
717 tcTyVarBndrs :: [LHsTyVarBndr Name] -- Kind-annotated binders, which need kind-zonking
718 -> ([TyVar] -> TcM r)
720 -- Used when type-checking types/classes/type-decls
721 -- Brings into scope immutable TyVars, not mutable ones that require later zonking
722 tcTyVarBndrs bndrs thing_inside = do
723 tyvars <- mapM (zonk . unLoc) bndrs
724 tcExtendTyVarEnv tyvars (thing_inside tyvars)
726 zonk (KindedTyVar name kind) = do { kind' <- zonkTcKindToKind kind
727 ; return (mkTyVar name kind') }
728 zonk (UserTyVar name) = WARN( True, ptext (sLit "Un-kinded tyvar") <+> ppr name )
729 return (mkTyVar name liftedTypeKind)
731 -----------------------------------
732 tcDataKindSig :: Maybe Kind -> TcM [TyVar]
733 -- GADT decls can have a (perhaps partial) kind signature
734 -- e.g. data T :: * -> * -> * where ...
735 -- This function makes up suitable (kinded) type variables for
736 -- the argument kinds, and checks that the result kind is indeed *.
737 -- We use it also to make up argument type variables for for data instances.
738 tcDataKindSig Nothing = return []
739 tcDataKindSig (Just kind)
740 = do { checkTc (isLiftedTypeKind res_kind) (badKindSig kind)
741 ; span <- getSrcSpanM
742 ; us <- newUniqueSupply
743 ; let uniqs = uniqsFromSupply us
744 ; return [ mk_tv span uniq str kind
745 | ((kind, str), uniq) <- arg_kinds `zip` dnames `zip` uniqs ] }
747 (arg_kinds, res_kind) = splitKindFunTys kind
748 mk_tv loc uniq str kind = mkTyVar name kind
750 name = mkInternalName uniq occ loc
751 occ = mkOccName tvName str
753 dnames = map ('$' :) names -- Note [Avoid name clashes for associated data types]
756 names = [ c:cs | cs <- "" : names, c <- ['a'..'z'] ]
758 badKindSig :: Kind -> SDoc
760 = hang (ptext (sLit "Kind signature on data type declaration has non-* return kind"))
764 Note [Avoid name clashes for associated data types]
765 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
766 Consider class C a b where
768 When typechecking the decl for D, we'll invent an extra type variable for D,
769 to fill out its kind. We *don't* want this type variable to be 'a', because
770 in an .hi file we'd get
773 which makes it look as if there are *two* type indices. But there aren't!
774 So we use $a instead, which cannot clash with a user-written type variable.
775 Remember that type variable binders in interface files are just FastStrings,
778 (The tidying phase can't help here because we don't tidy TyCons. Another
779 alternative would be to record the number of indexing parameters in the
783 %************************************************************************
785 Scoped type variables
787 %************************************************************************
790 tcAddScopedTyVars is used for scoped type variables added by pattern
792 e.g. \ ((x::a), (y::a)) -> x+y
793 They never have explicit kinds (because this is source-code only)
794 They are mutable (because they can get bound to a more specific type).
796 Usually we kind-infer and expand type splices, and then
797 tupecheck/desugar the type. That doesn't work well for scoped type
798 variables, because they scope left-right in patterns. (e.g. in the
799 example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
801 The current not-very-good plan is to
802 * find all the types in the patterns
803 * find their free tyvars
805 * bring the kinded type vars into scope
806 * BUT throw away the kind-checked type
807 (we'll kind-check it again when we type-check the pattern)
809 This is bad because throwing away the kind checked type throws away
810 its splices. But too bad for now. [July 03]
813 We no longer specify that these type variables must be univerally
814 quantified (lots of email on the subject). If you want to put that
816 a) Do a checkSigTyVars after thing_inside
817 b) More insidiously, don't pass in expected_ty, else
818 we unify with it too early and checkSigTyVars barfs
819 Instead you have to pass in a fresh ty var, and unify
820 it with expected_ty afterwards
823 tcHsPatSigType :: UserTypeCtxt
824 -> LHsType Name -- The type signature
825 -> TcM ([TyVar], -- Newly in-scope type variables
826 Type) -- The signature
827 -- Used for type-checking type signatures in
828 -- (a) patterns e.g f (x::Int) = e
829 -- (b) result signatures e.g. g x :: Int = e
830 -- (c) RULE forall bndrs e.g. forall (x::Int). f x = x
832 tcHsPatSigType ctxt hs_ty
833 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
834 do { -- Find the type variables that are mentioned in the type
835 -- but not already in scope. These are the ones that
836 -- should be bound by the pattern signature
837 in_scope <- getInLocalScope
838 ; let span = getLoc hs_ty
839 sig_tvs = [ L span (UserTyVar n)
840 | n <- nameSetToList (extractHsTyVars hs_ty),
843 ; (tyvars, sig_ty) <- tcHsQuantifiedType sig_tvs hs_ty
844 ; checkValidType ctxt sig_ty
845 ; return (tyvars, sig_ty)
848 tcPatSig :: UserTypeCtxt
851 -> TcM (TcType, -- The type to use for "inside" the signature
852 [(Name, TcType)], -- The new bit of type environment, binding
853 -- the scoped type variables
854 CoercionI) -- Coercion due to unification with actual ty
855 tcPatSig ctxt sig res_ty
856 = do { (sig_tvs, sig_ty) <- tcHsPatSigType ctxt sig
858 ; if null sig_tvs then do {
859 -- The type signature binds no type variables,
860 -- and hence is rigid, so use it to zap the res_ty
861 coi <- boxyUnify sig_ty res_ty
862 ; return (sig_ty, [], coi)
865 -- Type signature binds at least one scoped type variable
867 -- A pattern binding cannot bind scoped type variables
868 -- The renamer fails with a name-out-of-scope error
869 -- if a pattern binding tries to bind a type variable,
870 -- So we just have an ASSERT here
871 ; let in_pat_bind = case ctxt of
872 BindPatSigCtxt -> True
874 ; ASSERT( not in_pat_bind || null sig_tvs ) return ()
876 -- Check that pat_ty is rigid
877 ; checkTc (isRigidTy res_ty) (wobblyPatSig sig_tvs)
879 -- Now match the pattern signature against res_ty
880 -- For convenience, and uniform-looking error messages
881 -- we do the matching by allocating meta type variables,
882 -- unifying, and reading out the results.
883 -- This is a strictly local operation.
884 ; box_tvs <- mapM tcInstBoxyTyVar sig_tvs
885 ; coi <- boxyUnify (substTyWith sig_tvs (mkTyVarTys box_tvs) sig_ty)
887 ; sig_tv_tys <- mapM readFilledBox box_tvs
889 -- Check that each is bound to a distinct type variable,
890 -- and one that is not already in scope
891 ; let tv_binds = map tyVarName sig_tvs `zip` sig_tv_tys
892 ; binds_in_scope <- getScopedTyVarBinds
893 ; check binds_in_scope tv_binds
896 ; return (res_ty, tv_binds, coi)
899 check _ [] = return ()
900 check in_scope ((n,ty):rest) = do { check_one in_scope n ty
901 ; check ((n,ty):in_scope) rest }
903 check_one in_scope n ty
904 = do { checkTc (tcIsTyVarTy ty) (scopedNonVar n ty)
905 -- Must bind to a type variable
907 ; checkTc (null dups) (dupInScope n (head dups) ty)
908 -- Must not bind to the same type variable
909 -- as some other in-scope type variable
913 dups = [n' | (n',ty') <- in_scope, tcEqType ty' ty]
917 %************************************************************************
919 Scoped type variables
921 %************************************************************************
924 pprHsSigCtxt :: UserTypeCtxt -> LHsType Name -> SDoc
925 pprHsSigCtxt ctxt hs_ty = vcat [ ptext (sLit "In") <+> pprUserTypeCtxt ctxt <> colon,
926 nest 2 (pp_sig ctxt) ]
928 pp_sig (FunSigCtxt n) = pp_n_colon n
929 pp_sig (ConArgCtxt n) = pp_n_colon n
930 pp_sig (ForSigCtxt n) = pp_n_colon n
931 pp_sig _ = ppr (unLoc hs_ty)
933 pp_n_colon n = ppr n <+> dcolon <+> ppr (unLoc hs_ty)
935 wobblyPatSig :: [Var] -> SDoc
937 = hang (ptext (sLit "A pattern type signature cannot bind scoped type variables")
938 <+> pprQuotedList sig_tvs)
939 2 (ptext (sLit "unless the pattern has a rigid type context"))
941 scopedNonVar :: Name -> Type -> SDoc
943 = vcat [sep [ptext (sLit "The scoped type variable") <+> quotes (ppr n),
944 nest 2 (ptext (sLit "is bound to the type") <+> quotes (ppr ty))],
945 nest 2 (ptext (sLit "You can only bind scoped type variables to type variables"))]
947 dupInScope :: Name -> Name -> Type -> SDoc
949 = hang (ptext (sLit "The scoped type variables") <+> quotes (ppr n) <+> ptext (sLit "and") <+> quotes (ppr n'))
950 2 (vcat [ptext (sLit "are bound to the same type (variable)"),
951 ptext (sLit "Distinct scoped type variables must be distinct")])
953 wrongEqualityErr :: TcM (HsType Name, TcKind)
955 = failWithTc (text "Equality predicate used as a type")