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 -- remove the doc nodes here, no need to worry about the location since
422 -- its the same for a doc node and it's child type node
423 kc_hs_type (HsDocTy ty _)
424 = kc_hs_type (unLoc ty)
426 ---------------------------
427 kcApps :: Outputable a
429 -> TcKind -- Function kind
430 -> [LHsType Name] -- Arg types
431 -> TcM ([LHsType Name], TcKind) -- Kind-checked args
432 kcApps the_fun fun_kind args
433 = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
434 ; args' <- kc_check_lhs_types args_w_kinds
435 ; return (args', res_kind) }
437 kcCheckApps :: Outputable a => a -> TcKind -> [LHsType Name]
438 -> HsType Name -- The type being checked (for err messages only)
439 -> ExpKind -- Expected kind
440 -> TcM [LHsType Name]
441 kcCheckApps the_fun fun_kind args ty exp_kind
442 = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
443 ; checkExpectedKind ty res_kind exp_kind
444 -- Check the result kind *before* checking argument kinds
445 -- This improves error message; Trac #2994
446 ; kc_check_lhs_types args_w_kinds }
448 splitHsAppTys :: LHsType Name -> LHsType Name -> (LHsType Name, [LHsType Name])
449 splitHsAppTys fun_ty arg_ty = split fun_ty [arg_ty]
451 split (L _ (HsAppTy f a)) as = split f (a:as)
454 mkHsAppTys :: LHsType Name -> [LHsType Name] -> HsType Name
455 mkHsAppTys fun_ty [] = pprPanic "mkHsAppTys" (ppr fun_ty)
456 mkHsAppTys fun_ty (arg_ty:arg_tys)
457 = foldl mk_app (HsAppTy fun_ty arg_ty) arg_tys
459 mk_app fun arg = HsAppTy (noLoc fun) arg -- Add noLocs for inner nodes of
460 -- the application; they are
463 ---------------------------
464 splitFunKind :: SDoc -> Int -> TcKind -> [b] -> TcM ([(b,ExpKind)], TcKind)
465 splitFunKind _ _ fk [] = return ([], fk)
466 splitFunKind the_fun arg_no fk (arg:args)
467 = do { mb_fk <- unifyFunKind fk
469 Nothing -> failWithTc too_many_args
470 Just (ak,fk') -> do { (aks, rk) <- splitFunKind the_fun (arg_no+1) fk' args
471 ; return ((arg, EK ak (EkArg the_fun arg_no)):aks, rk) } }
473 too_many_args = quotes the_fun <+>
474 ptext (sLit "is applied to too many type arguments")
476 ---------------------------
477 kcHsContext :: LHsContext Name -> TcM (LHsContext Name)
478 kcHsContext ctxt = wrapLocM (mapM kcHsLPred) ctxt
480 kcHsLPred :: LHsPred Name -> TcM (LHsPred Name)
481 kcHsLPred = wrapLocM kcHsPred
483 kcHsPred :: HsPred Name -> TcM (HsPred Name)
484 kcHsPred pred = do -- Checks that the result is of kind liftedType
485 (pred', kind) <- kc_pred pred
486 checkExpectedKind pred kind ekLifted
489 ---------------------------
490 kc_pred :: HsPred Name -> TcM (HsPred Name, TcKind)
491 -- Does *not* check for a saturated
492 -- application (reason: used from TcDeriv)
493 kc_pred (HsIParam name ty)
494 = do { (ty', kind) <- kc_lhs_type ty
495 ; return (HsIParam name ty', kind)
497 kc_pred (HsClassP cls tys)
498 = do { kind <- kcClass cls
499 ; (tys', res_kind) <- kcApps cls kind tys
500 ; return (HsClassP cls tys', res_kind)
502 kc_pred (HsEqualP ty1 ty2)
503 = do { (ty1', kind1) <- kc_lhs_type ty1
504 -- ; checkExpectedKind ty1 kind1 liftedTypeKind
505 ; (ty2', kind2) <- kc_lhs_type ty2
506 -- ; checkExpectedKind ty2 kind2 liftedTypeKind
507 ; checkExpectedKind ty2 kind2 (EK kind1 EkEqPred)
508 ; return (HsEqualP ty1' ty2', liftedTypeKind)
511 ---------------------------
512 kcTyVar :: Name -> TcM TcKind
513 kcTyVar name = do -- Could be a tyvar or a tycon
514 traceTc (text "lk1" <+> ppr name)
515 thing <- tcLookup name
516 traceTc (text "lk2" <+> ppr name <+> ppr thing)
518 ATyVar _ ty -> return (typeKind ty)
519 AThing kind -> return kind
520 AGlobal (ATyCon tc) -> return (tyConKind tc)
521 _ -> wrongThingErr "type" thing name
523 kcClass :: Name -> TcM TcKind
524 kcClass cls = do -- Must be a class
525 thing <- tcLookup cls
527 AThing kind -> return kind
528 AGlobal (AClass cls) -> return (tyConKind (classTyCon cls))
529 _ -> wrongThingErr "class" thing cls
533 %************************************************************************
537 %************************************************************************
541 * Transforms from HsType to Type
544 It cannot fail, and does no validity checking, except for
545 structural matters, such as
546 (a) spurious ! annotations.
547 (b) a class used as a type
550 dsHsType :: LHsType Name -> TcM Type
551 -- All HsTyVarBndrs in the intput type are kind-annotated
552 dsHsType ty = ds_type (unLoc ty)
554 ds_type :: HsType Name -> TcM Type
555 ds_type ty@(HsTyVar _)
558 ds_type (HsParTy ty) -- Remove the parentheses markers
561 ds_type ty@(HsBangTy {}) -- No bangs should be here
562 = failWithTc (ptext (sLit "Unexpected strictness annotation:") <+> ppr ty)
564 ds_type ty@(HsRecTy {}) -- No bangs should be here
565 = failWithTc (ptext (sLit "Unexpected record type:") <+> ppr ty)
567 ds_type (HsKindSig ty _)
568 = dsHsType ty -- Kind checking done already
570 ds_type (HsListTy ty) = do
571 tau_ty <- dsHsType ty
572 checkWiredInTyCon listTyCon
573 return (mkListTy tau_ty)
575 ds_type (HsPArrTy ty) = do
576 tau_ty <- dsHsType ty
577 checkWiredInTyCon parrTyCon
578 return (mkPArrTy tau_ty)
580 ds_type (HsTupleTy boxity tys) = do
581 tau_tys <- dsHsTypes tys
582 checkWiredInTyCon tycon
583 return (mkTyConApp tycon tau_tys)
585 tycon = tupleTyCon boxity (length tys)
587 ds_type (HsFunTy ty1 ty2) = do
588 tau_ty1 <- dsHsType ty1
589 tau_ty2 <- dsHsType ty2
590 return (mkFunTy tau_ty1 tau_ty2)
592 ds_type (HsOpTy ty1 (L span op) ty2) = do
593 tau_ty1 <- dsHsType ty1
594 tau_ty2 <- dsHsType ty2
595 setSrcSpan span (ds_var_app op [tau_ty1,tau_ty2])
599 tc <- tcLookupTyCon genUnitTyConName
600 return (mkTyConApp tc [])
602 ds_type ty@(HsAppTy _ _)
605 ds_type (HsPredTy pred) = do
606 pred' <- dsHsPred pred
607 return (mkPredTy pred')
609 ds_type (HsForAllTy _ tv_names ctxt ty)
610 = tcTyVarBndrs tv_names $ \ tyvars -> do
611 theta <- mapM dsHsLPred (unLoc ctxt)
613 return (mkSigmaTy tyvars theta tau)
615 ds_type (HsSpliceTy {}) = panic "ds_type: HsSpliceTy"
617 ds_type (HsDocTy ty _) -- Remove the doc comment
620 dsHsTypes :: [LHsType Name] -> TcM [Type]
621 dsHsTypes arg_tys = mapM dsHsType arg_tys
624 Help functions for type applications
625 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
628 ds_app :: HsType Name -> [LHsType Name] -> TcM Type
629 ds_app (HsAppTy ty1 ty2) tys
630 = ds_app (unLoc ty1) (ty2:tys)
633 arg_tys <- dsHsTypes tys
635 HsTyVar fun -> ds_var_app fun arg_tys
636 _ -> do fun_ty <- ds_type ty
637 return (mkAppTys fun_ty arg_tys)
639 ds_var_app :: Name -> [Type] -> TcM Type
640 ds_var_app name arg_tys = do
641 thing <- tcLookup name
643 ATyVar _ ty -> return (mkAppTys ty arg_tys)
644 AGlobal (ATyCon tc) -> return (mkTyConApp tc arg_tys)
645 _ -> wrongThingErr "type" thing name
653 dsHsLPred :: LHsPred Name -> TcM PredType
654 dsHsLPred pred = dsHsPred (unLoc pred)
656 dsHsPred :: HsPred Name -> TcM PredType
657 dsHsPred (HsClassP class_name tys)
658 = do { arg_tys <- dsHsTypes tys
659 ; clas <- tcLookupClass class_name
660 ; return (ClassP clas arg_tys)
662 dsHsPred (HsEqualP ty1 ty2)
663 = do { arg_ty1 <- dsHsType ty1
664 ; arg_ty2 <- dsHsType ty2
665 ; return (EqPred arg_ty1 arg_ty2)
667 dsHsPred (HsIParam name ty)
668 = do { arg_ty <- dsHsType ty
669 ; return (IParam name arg_ty)
673 GADT constructor signatures
676 tcLHsConResTy :: LHsType Name -> TcM (TyCon, [TcType])
677 tcLHsConResTy (L span res_ty)
679 case get_args res_ty [] of
680 (HsTyVar tc_name, args)
681 -> do { args' <- mapM dsHsType args
682 ; thing <- tcLookup tc_name
684 AGlobal (ATyCon tc) -> return (tc, args')
685 _ -> failWithTc (badGadtDecl res_ty) }
686 _ -> failWithTc (badGadtDecl res_ty)
688 -- We can't call dsHsType on res_ty, and then do tcSplitTyConApp_maybe
689 -- because that causes a black hole, and for good reason. Building
690 -- the type means expanding type synonyms, and we can't do that
691 -- inside the "knot". So we have to work by steam.
692 get_args (HsAppTy (L _ fun) arg) args = get_args fun (arg:args)
693 get_args (HsParTy (L _ ty)) args = get_args ty args
694 get_args (HsOpTy ty1 (L _ tc) ty2) args = (HsTyVar tc, ty1:ty2:args)
695 get_args ty args = (ty, args)
697 badGadtDecl :: HsType Name -> SDoc
699 = hang (ptext (sLit "Malformed constructor result type:"))
702 addKcTypeCtxt :: LHsType Name -> TcM a -> TcM a
703 -- Wrap a context around only if we want to show that contexts.
704 addKcTypeCtxt (L _ (HsPredTy _)) thing = thing
705 -- Omit invisble ones and ones user's won't grok (HsPred p).
706 addKcTypeCtxt (L _ other_ty) thing = addErrCtxt (typeCtxt other_ty) thing
708 typeCtxt :: HsType Name -> SDoc
709 typeCtxt ty = ptext (sLit "In the type") <+> quotes (ppr ty)
712 %************************************************************************
714 Type-variable binders
716 %************************************************************************
720 kcHsTyVars :: [LHsTyVarBndr Name]
721 -> ([LHsTyVarBndr Name] -> TcM r) -- These binders are kind-annotated
722 -- They scope over the thing inside
724 kcHsTyVars tvs thing_inside = do
725 bndrs <- mapM (wrapLocM kcHsTyVar) tvs
726 tcExtendKindEnvTvs bndrs (thing_inside bndrs)
728 kcHsTyVar :: HsTyVarBndr Name -> TcM (HsTyVarBndr Name)
729 -- Return a *kind-annotated* binder, and a tyvar with a mutable kind in it
730 kcHsTyVar (UserTyVar name) = KindedTyVar name <$> newKindVar
731 kcHsTyVar (KindedTyVar name kind) = return (KindedTyVar name kind)
734 tcTyVarBndrs :: [LHsTyVarBndr Name] -- Kind-annotated binders, which need kind-zonking
735 -> ([TyVar] -> TcM r)
737 -- Used when type-checking types/classes/type-decls
738 -- Brings into scope immutable TyVars, not mutable ones that require later zonking
739 tcTyVarBndrs bndrs thing_inside = do
740 tyvars <- mapM (zonk . unLoc) bndrs
741 tcExtendTyVarEnv tyvars (thing_inside tyvars)
743 zonk (KindedTyVar name kind) = do { kind' <- zonkTcKindToKind kind
744 ; return (mkTyVar name kind') }
745 zonk (UserTyVar name) = WARN( True, ptext (sLit "Un-kinded tyvar") <+> ppr name )
746 return (mkTyVar name liftedTypeKind)
748 -----------------------------------
749 tcDataKindSig :: Maybe Kind -> TcM [TyVar]
750 -- GADT decls can have a (perhaps partial) kind signature
751 -- e.g. data T :: * -> * -> * where ...
752 -- This function makes up suitable (kinded) type variables for
753 -- the argument kinds, and checks that the result kind is indeed *.
754 -- We use it also to make up argument type variables for for data instances.
755 tcDataKindSig Nothing = return []
756 tcDataKindSig (Just kind)
757 = do { checkTc (isLiftedTypeKind res_kind) (badKindSig kind)
758 ; span <- getSrcSpanM
759 ; us <- newUniqueSupply
760 ; let uniqs = uniqsFromSupply us
761 ; return [ mk_tv span uniq str kind
762 | ((kind, str), uniq) <- arg_kinds `zip` dnames `zip` uniqs ] }
764 (arg_kinds, res_kind) = splitKindFunTys kind
765 mk_tv loc uniq str kind = mkTyVar name kind
767 name = mkInternalName uniq occ loc
768 occ = mkOccName tvName str
770 dnames = map ('$' :) names -- Note [Avoid name clashes for associated data types]
773 names = [ c:cs | cs <- "" : names, c <- ['a'..'z'] ]
775 badKindSig :: Kind -> SDoc
777 = hang (ptext (sLit "Kind signature on data type declaration has non-* return kind"))
781 Note [Avoid name clashes for associated data types]
782 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
783 Consider class C a b where
785 When typechecking the decl for D, we'll invent an extra type variable for D,
786 to fill out its kind. We *don't* want this type variable to be 'a', because
787 in an .hi file we'd get
790 which makes it look as if there are *two* type indices. But there aren't!
791 So we use $a instead, which cannot clash with a user-written type variable.
792 Remember that type variable binders in interface files are just FastStrings,
795 (The tidying phase can't help here because we don't tidy TyCons. Another
796 alternative would be to record the number of indexing parameters in the
800 %************************************************************************
802 Scoped type variables
804 %************************************************************************
807 tcAddScopedTyVars is used for scoped type variables added by pattern
809 e.g. \ ((x::a), (y::a)) -> x+y
810 They never have explicit kinds (because this is source-code only)
811 They are mutable (because they can get bound to a more specific type).
813 Usually we kind-infer and expand type splices, and then
814 tupecheck/desugar the type. That doesn't work well for scoped type
815 variables, because they scope left-right in patterns. (e.g. in the
816 example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
818 The current not-very-good plan is to
819 * find all the types in the patterns
820 * find their free tyvars
822 * bring the kinded type vars into scope
823 * BUT throw away the kind-checked type
824 (we'll kind-check it again when we type-check the pattern)
826 This is bad because throwing away the kind checked type throws away
827 its splices. But too bad for now. [July 03]
830 We no longer specify that these type variables must be univerally
831 quantified (lots of email on the subject). If you want to put that
833 a) Do a checkSigTyVars after thing_inside
834 b) More insidiously, don't pass in expected_ty, else
835 we unify with it too early and checkSigTyVars barfs
836 Instead you have to pass in a fresh ty var, and unify
837 it with expected_ty afterwards
840 tcHsPatSigType :: UserTypeCtxt
841 -> LHsType Name -- The type signature
842 -> TcM ([TyVar], -- Newly in-scope type variables
843 Type) -- The signature
844 -- Used for type-checking type signatures in
845 -- (a) patterns e.g f (x::Int) = e
846 -- (b) result signatures e.g. g x :: Int = e
847 -- (c) RULE forall bndrs e.g. forall (x::Int). f x = x
849 tcHsPatSigType ctxt hs_ty
850 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
851 do { -- Find the type variables that are mentioned in the type
852 -- but not already in scope. These are the ones that
853 -- should be bound by the pattern signature
854 in_scope <- getInLocalScope
855 ; let span = getLoc hs_ty
856 sig_tvs = [ L span (UserTyVar n)
857 | n <- nameSetToList (extractHsTyVars hs_ty),
860 ; (tyvars, sig_ty) <- tcHsQuantifiedType sig_tvs hs_ty
861 ; checkValidType ctxt sig_ty
862 ; return (tyvars, sig_ty)
865 tcPatSig :: UserTypeCtxt
868 -> TcM (TcType, -- The type to use for "inside" the signature
869 [(Name, TcType)], -- The new bit of type environment, binding
870 -- the scoped type variables
871 CoercionI) -- Coercion due to unification with actual ty
872 tcPatSig ctxt sig res_ty
873 = do { (sig_tvs, sig_ty) <- tcHsPatSigType ctxt sig
875 ; if null sig_tvs then do {
876 -- The type signature binds no type variables,
877 -- and hence is rigid, so use it to zap the res_ty
878 coi <- boxyUnify sig_ty res_ty
879 ; return (sig_ty, [], coi)
882 -- Type signature binds at least one scoped type variable
884 -- A pattern binding cannot bind scoped type variables
885 -- The renamer fails with a name-out-of-scope error
886 -- if a pattern binding tries to bind a type variable,
887 -- So we just have an ASSERT here
888 ; let in_pat_bind = case ctxt of
889 BindPatSigCtxt -> True
891 ; ASSERT( not in_pat_bind || null sig_tvs ) return ()
893 -- Check that pat_ty is rigid
894 ; checkTc (isRigidTy res_ty) (wobblyPatSig sig_tvs)
896 -- Check that all newly-in-scope tyvars are in fact
897 -- constrained by the pattern. This catches tiresome
901 -- f (x :: T a) = ...
902 -- Here 'a' doesn't get a binding. Sigh
903 ; let bad_tvs = filterOut (`elemVarSet` exactTyVarsOfType sig_ty) sig_tvs
904 ; checkTc (null bad_tvs) (badPatSigTvs sig_ty bad_tvs)
906 -- Now match the pattern signature against res_ty
907 -- For convenience, and uniform-looking error messages
908 -- we do the matching by allocating meta type variables,
909 -- unifying, and reading out the results.
910 -- This is a strictly local operation.
911 ; box_tvs <- mapM tcInstBoxyTyVar sig_tvs
912 ; coi <- boxyUnify (substTyWith sig_tvs (mkTyVarTys box_tvs) sig_ty)
914 ; sig_tv_tys <- mapM readFilledBox box_tvs
916 -- Check that each is bound to a distinct type variable,
917 -- and one that is not already in scope
918 ; let tv_binds = map tyVarName sig_tvs `zip` sig_tv_tys
919 ; binds_in_scope <- getScopedTyVarBinds
920 ; check binds_in_scope tv_binds
923 ; return (res_ty, tv_binds, coi)
926 check _ [] = return ()
927 check in_scope ((n,ty):rest) = do { check_one in_scope n ty
928 ; check ((n,ty):in_scope) rest }
930 check_one in_scope n ty
931 = do { checkTc (tcIsTyVarTy ty) (scopedNonVar n ty)
932 -- Must bind to a type variable
934 ; checkTc (null dups) (dupInScope n (head dups) ty)
935 -- Must not bind to the same type variable
936 -- as some other in-scope type variable
940 dups = [n' | (n',ty') <- in_scope, tcEqType ty' ty]
944 %************************************************************************
948 %************************************************************************
950 We would like to get a decent error message from
951 (a) Under-applied type constructors
953 (b) Over-applied type constructors
957 -- The ExpKind datatype means "expected kind" and contains
958 -- some info about just why that kind is expected, to improve
959 -- the error message on a mis-match
960 data ExpKind = EK TcKind EkCtxt
961 data EkCtxt = EkUnk -- Unknown context
962 | EkEqPred -- Second argument of an equality predicate
963 | EkKindSig -- Kind signature
964 | EkArg SDoc Int -- Function, arg posn, expected kind
967 ekLifted, ekOpen :: ExpKind
968 ekLifted = EK liftedTypeKind EkUnk
969 ekOpen = EK openTypeKind EkUnk
971 checkExpectedKind :: Outputable a => a -> TcKind -> ExpKind -> TcM ()
972 -- A fancy wrapper for 'unifyKind', which tries
973 -- to give decent error messages.
974 -- (checkExpectedKind ty act_kind exp_kind)
975 -- checks that the actual kind act_kind is compatible
976 -- with the expected kind exp_kind
977 -- The first argument, ty, is used only in the error message generation
978 checkExpectedKind ty act_kind (EK exp_kind ek_ctxt)
979 | act_kind `isSubKind` exp_kind -- Short cut for a very common case
982 (_errs, mb_r) <- tryTc (unifyKind exp_kind act_kind)
984 Just _ -> return () -- Unification succeeded
987 -- So there's definitely an error
988 -- Now to find out what sort
989 exp_kind <- zonkTcKind exp_kind
990 act_kind <- zonkTcKind act_kind
992 env0 <- tcInitTidyEnv
993 let (exp_as, _) = splitKindFunTys exp_kind
994 (act_as, _) = splitKindFunTys act_kind
995 n_exp_as = length exp_as
996 n_act_as = length act_as
998 (env1, tidy_exp_kind) = tidyKind env0 exp_kind
999 (env2, tidy_act_kind) = tidyKind env1 act_kind
1001 err | n_exp_as < n_act_as -- E.g. [Maybe]
1002 = quotes (ppr ty) <+> ptext (sLit "is not applied to enough type arguments")
1004 -- Now n_exp_as >= n_act_as. In the next two cases,
1005 -- n_exp_as == 0, and hence so is n_act_as
1006 | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
1007 = ptext (sLit "Expecting a lifted type, but") <+> quotes (ppr ty)
1008 <+> ptext (sLit "is unlifted")
1010 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1011 = ptext (sLit "Expecting an unlifted type, but") <+> quotes (ppr ty)
1012 <+> ptext (sLit "is lifted")
1014 | otherwise -- E.g. Monad [Int]
1015 = ptext (sLit "Kind mis-match")
1017 more_info = sep [ expected_herald ek_ctxt <+> ptext (sLit "kind")
1018 <+> quotes (pprKind tidy_exp_kind) <> comma,
1019 ptext (sLit "but") <+> quotes (ppr ty) <+>
1020 ptext (sLit "has kind") <+> quotes (pprKind tidy_act_kind)]
1022 expected_herald EkUnk = ptext (sLit "Expected")
1023 expected_herald EkKindSig = ptext (sLit "An enclosing kind signature specified")
1024 expected_herald EkEqPred = ptext (sLit "The left argument of the equality predicate had")
1025 expected_herald (EkArg fun arg_no)
1026 = ptext (sLit "The") <+> speakNth arg_no <+> ptext (sLit "argument of")
1027 <+> quotes fun <+> ptext (sLit ("should have"))
1029 failWithTcM (env2, err $$ more_info)
1032 %************************************************************************
1034 Scoped type variables
1036 %************************************************************************
1039 pprHsSigCtxt :: UserTypeCtxt -> LHsType Name -> SDoc
1040 pprHsSigCtxt ctxt hs_ty = vcat [ ptext (sLit "In") <+> pprUserTypeCtxt ctxt <> colon,
1041 nest 2 (pp_sig ctxt) ]
1043 pp_sig (FunSigCtxt n) = pp_n_colon n
1044 pp_sig (ConArgCtxt n) = pp_n_colon n
1045 pp_sig (ForSigCtxt n) = pp_n_colon n
1046 pp_sig _ = ppr (unLoc hs_ty)
1048 pp_n_colon n = ppr n <+> dcolon <+> ppr (unLoc hs_ty)
1050 wobblyPatSig :: [Var] -> SDoc
1051 wobblyPatSig sig_tvs
1052 = hang (ptext (sLit "A pattern type signature cannot bind scoped type variables")
1053 <+> pprQuotedList sig_tvs)
1054 2 (ptext (sLit "unless the pattern has a rigid type context"))
1056 badPatSigTvs :: TcType -> [TyVar] -> SDoc
1057 badPatSigTvs sig_ty bad_tvs
1058 = vcat [ fsep [ptext (sLit "The type variable") <> plural bad_tvs,
1059 quotes (pprWithCommas ppr bad_tvs),
1060 ptext (sLit "should be bound by the pattern signature") <+> quotes (ppr sig_ty),
1061 ptext (sLit "but are actually discarded by a type synonym") ]
1062 , ptext (sLit "To fix this, expand the type synonym")
1063 , ptext (sLit "[Note: I hope to lift this restriction in due course]") ]
1065 scopedNonVar :: Name -> Type -> SDoc
1067 = vcat [sep [ptext (sLit "The scoped type variable") <+> quotes (ppr n),
1068 nest 2 (ptext (sLit "is bound to the type") <+> quotes (ppr ty))],
1069 nest 2 (ptext (sLit "You can only bind scoped type variables to type variables"))]
1071 dupInScope :: Name -> Name -> Type -> SDoc
1073 = hang (ptext (sLit "The scoped type variables") <+> quotes (ppr n) <+> ptext (sLit "and") <+> quotes (ppr n'))
1074 2 (vcat [ptext (sLit "are bound to the same type (variable)"),
1075 ptext (sLit "Distinct scoped type variables must be distinct")])
1077 wrongEqualityErr :: TcM (HsType Name, TcKind)
1079 = failWithTc (text "Equality predicate used as a type")