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