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, kcHsLPred, dsHsLPred,
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 TysPrim ( ecKind )
41 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, tcHsSigTypeNC :: 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 tcHsSigTypeNC ctxt hs_ty
150 tcHsSigTypeNC ctxt hs_ty
151 = do { (kinded_ty, _kind) <- kc_lhs_type hs_ty
152 -- The kind is checked by checkValidType, and isn't necessarily
153 -- of kind * in a Template Haskell quote eg [t| Maybe |]
154 ; ty <- tcHsKindedType kinded_ty
155 ; checkValidType ctxt ty
158 tcHsInstHead :: LHsType Name -> TcM ([TyVar], ThetaType, Class, [Type])
159 -- Typecheck an instance head. We can't use
160 -- tcHsSigType, because it's not a valid user type.
161 tcHsInstHead (L loc hs_ty)
162 = setSrcSpan loc $ -- No need for an "In the type..." context
163 -- because that comes from the caller
164 do { kinded_ty <- kc_inst_head hs_ty
165 ; ds_inst_head kinded_ty }
167 kc_inst_head ty@(HsPredTy pred@(HsClassP {}))
168 = do { (pred', kind) <- kc_pred pred
169 ; checkExpectedKind ty kind ekLifted
170 ; return (HsPredTy pred') }
171 kc_inst_head (HsForAllTy exp tv_names context (L loc ty))
172 = kcHsTyVars tv_names $ \ tv_names' ->
173 do { ctxt' <- kcHsContext context
174 ; ty' <- kc_inst_head ty
175 ; return (HsForAllTy exp tv_names' ctxt' (L loc ty')) }
176 kc_inst_head _ = failWithTc (ptext (sLit "Malformed instance type"))
178 ds_inst_head (HsPredTy (HsClassP cls_name tys))
179 = do { clas <- tcLookupClass cls_name
180 ; arg_tys <- dsHsTypes tys
181 ; return ([], [], clas, arg_tys) }
182 ds_inst_head (HsForAllTy _ tvs ctxt (L _ tau))
183 = tcTyVarBndrs tvs $ \ tvs' ->
184 do { ctxt' <- mapM dsHsLPred (unLoc ctxt)
185 ; (tvs_r, ctxt_r, cls, tys) <- ds_inst_head tau
186 ; return (tvs' ++ tvs_r, ctxt' ++ ctxt_r , cls, tys) }
187 ds_inst_head _ = panic "ds_inst_head"
189 tcHsQuantifiedType :: [LHsTyVarBndr Name] -> LHsType Name -> TcM ([TyVar], Type)
190 -- Behave very like type-checking (HsForAllTy sig_tvs hs_ty),
191 -- except that we want to keep the tvs separate
192 tcHsQuantifiedType tv_names hs_ty
193 = kcHsTyVars tv_names $ \ tv_names' ->
194 do { kc_ty <- kcHsSigType hs_ty
195 ; tcTyVarBndrs tv_names' $ \ tvs ->
196 do { ty <- dsHsType kc_ty
197 ; return (tvs, ty) } }
199 -- Used for the deriving(...) items
200 tcHsDeriv :: HsType Name -> TcM ([TyVar], Class, [Type])
201 tcHsDeriv = tc_hs_deriv []
203 tc_hs_deriv :: [LHsTyVarBndr Name] -> HsType Name
204 -> TcM ([TyVar], Class, [Type])
205 tc_hs_deriv tv_names (HsPredTy (HsClassP cls_name hs_tys))
206 = kcHsTyVars tv_names $ \ tv_names' ->
207 do { cls_kind <- kcClass cls_name
208 ; (tys, _res_kind) <- kcApps cls_name cls_kind hs_tys
209 ; tcTyVarBndrs tv_names' $ \ tyvars ->
210 do { arg_tys <- dsHsTypes tys
211 ; cls <- tcLookupClass cls_name
212 ; return (tyvars, cls, arg_tys) }}
214 tc_hs_deriv tv_names1 (HsForAllTy _ tv_names2 (L _ []) (L _ ty))
215 = -- Funny newtype deriving form
217 -- where C has arity 2. Hence can't use regular functions
218 tc_hs_deriv (tv_names1 ++ tv_names2) ty
221 = failWithTc (ptext (sLit "Illegal deriving item") <+> ppr other)
224 These functions are used during knot-tying in
225 type and class declarations, when we have to
226 separate kind-checking, desugaring, and validity checking
229 kcHsSigType, kcHsLiftedSigType :: LHsType Name -> TcM (LHsType Name)
230 -- Used for type signatures
231 kcHsSigType ty = addKcTypeCtxt ty $ kcTypeType ty
232 kcHsLiftedSigType ty = addKcTypeCtxt ty $ kcLiftedType ty
234 tcHsKindedType :: LHsType Name -> TcM Type
235 -- Don't do kind checking, nor validity checking.
236 -- This is used in type and class decls, where kinding is
237 -- done in advance, and validity checking is done later
238 -- [Validity checking done later because of knot-tying issues.]
239 tcHsKindedType hs_ty = dsHsType hs_ty
241 tcHsBangType :: LHsType Name -> TcM Type
242 -- Permit a bang, but discard it
243 tcHsBangType (L _ (HsBangTy _ ty)) = tcHsKindedType ty
244 tcHsBangType ty = tcHsKindedType ty
246 tcHsKindedContext :: LHsContext Name -> TcM ThetaType
247 -- Used when we are expecting a ClassContext (i.e. no implicit params)
248 -- Does not do validity checking, like tcHsKindedType
249 tcHsKindedContext hs_theta = addLocM (mapM dsHsLPred) hs_theta
253 %************************************************************************
255 The main kind checker: kcHsType
257 %************************************************************************
259 First a couple of simple wrappers for kcHsType
262 ---------------------------
263 kcLiftedType :: LHsType Name -> TcM (LHsType Name)
264 -- The type ty must be a *lifted* *type*
265 kcLiftedType ty = kc_check_lhs_type ty ekLifted
267 ---------------------------
268 kcTypeType :: LHsType Name -> TcM (LHsType Name)
269 -- The type ty must be a *type*, but it can be lifted or
270 -- unlifted or an unboxed tuple.
271 kcTypeType ty = kc_check_lhs_type ty ekOpen
273 ---------------------------
274 kcCheckLHsType :: LHsType Name -> ExpKind -> TcM (LHsType Name)
275 kcCheckLHsType ty kind = addKcTypeCtxt ty $ kc_check_lhs_type ty kind
278 kc_check_lhs_type :: LHsType Name -> ExpKind -> TcM (LHsType Name)
279 -- Check that the type has the specified kind
280 -- Be sure to use checkExpectedKind, rather than simply unifying
281 -- with OpenTypeKind, because it gives better error messages
282 kc_check_lhs_type (L span ty) exp_kind
284 do { ty' <- kc_check_hs_type ty exp_kind
285 ; return (L span ty') }
287 kc_check_lhs_types :: [(LHsType Name, ExpKind)] -> TcM [LHsType Name]
288 kc_check_lhs_types tys_w_kinds
289 = mapM kc_arg tys_w_kinds
291 kc_arg (arg, arg_kind) = kc_check_lhs_type arg arg_kind
294 ---------------------------
295 kc_check_hs_type :: HsType Name -> ExpKind -> TcM (HsType Name)
297 -- First some special cases for better error messages
298 -- when we know the expected kind
299 kc_check_hs_type (HsParTy ty) exp_kind
300 = do { ty' <- kc_check_lhs_type ty exp_kind; return (HsParTy ty') }
302 kc_check_hs_type ty@(HsAppTy ty1 ty2) exp_kind
303 = do { let (fun_ty, arg_tys) = splitHsAppTys ty1 [ty2]
304 ; (fun_ty', fun_kind) <- kc_lhs_type fun_ty
305 ; arg_tys' <- kcCheckApps fun_ty fun_kind arg_tys ty exp_kind
306 ; return (mkHsAppTys fun_ty' arg_tys') }
308 -- This is the general case: infer the kind and compare
309 kc_check_hs_type ty exp_kind
310 = do { (ty', act_kind) <- kc_hs_type ty
311 -- Add the context round the inner check only
312 -- because checkExpectedKind already mentions
313 -- 'ty' by name in any error message
315 ; checkExpectedKind (strip ty) act_kind exp_kind
318 -- We infer the kind of the type, and then complain if it's
319 -- not right. But we don't want to complain about
320 -- (ty) or !(ty) or forall a. ty
321 -- when the real difficulty is with the 'ty' part.
322 strip (HsParTy (L _ ty)) = strip ty
323 strip (HsBangTy _ (L _ ty)) = strip ty
324 strip (HsForAllTy _ _ _ (L _ ty)) = strip ty
328 Here comes the main function
331 kcLHsType :: LHsType Name -> TcM (LHsType Name, TcKind)
332 -- Called from outside: set the context
333 kcLHsType ty = addKcTypeCtxt ty (kc_lhs_type ty)
335 kc_lhs_type :: LHsType Name -> TcM (LHsType Name, TcKind)
336 kc_lhs_type (L span ty)
338 do { (ty', kind) <- kc_hs_type ty
339 ; return (L span ty', kind) }
341 -- kc_hs_type *returns* the kind of the type, rather than taking an expected
342 -- kind as argument as tcExpr does.
344 -- (a) the kind of (->) is
345 -- forall bx1 bx2. Type bx1 -> Type bx2 -> Type Boxed
346 -- so we'd need to generate huge numbers of bx variables.
347 -- (b) kinds are so simple that the error messages are fine
349 -- The translated type has explicitly-kinded type-variable binders
351 kc_hs_type :: HsType Name -> TcM (HsType Name, TcKind)
352 kc_hs_type (HsParTy ty) = do
353 (ty', kind) <- kc_lhs_type ty
354 return (HsParTy ty', kind)
356 kc_hs_type (HsTyVar name) = do
358 return (HsTyVar name, kind)
360 kc_hs_type (HsListTy ty) = do
361 ty' <- kcLiftedType ty
362 return (HsListTy ty', liftedTypeKind)
364 kc_hs_type (HsPArrTy ty) = do
365 ty' <- kcLiftedType ty
366 return (HsPArrTy ty', liftedTypeKind)
368 kc_hs_type (HsModalBoxType ecn ty) = do
369 kc_check_hs_type (HsTyVar ecn) (EK ecKind EkUnk)
370 ty' <- kcLiftedType ty
371 return (HsModalBoxType ecn ty', liftedTypeKind)
373 kc_hs_type (HsKappaTy ty1 ty2) = do
374 ty1' <- kc_check_lhs_type ty1 (EK argTypeKind EkUnk)
375 ty2' <- kcTypeType ty2
376 return (HsKappaTy ty1' ty2', liftedTypeKind)
378 kc_hs_type (HsKindSig ty k) = do
379 ty' <- kc_check_lhs_type ty (EK k EkKindSig)
380 return (HsKindSig ty' k, k)
382 kc_hs_type (HsTupleTy Boxed tys) = do
383 tys' <- mapM kcLiftedType tys
384 return (HsTupleTy Boxed tys', liftedTypeKind)
386 kc_hs_type (HsTupleTy Unboxed tys) = do
387 tys' <- mapM kcTypeType tys
388 return (HsTupleTy Unboxed tys', ubxTupleKind)
390 kc_hs_type (HsFunTy ty1 ty2) = do
391 ty1' <- kc_check_lhs_type ty1 (EK argTypeKind EkUnk)
392 ty2' <- kcTypeType ty2
393 return (HsFunTy ty1' ty2', liftedTypeKind)
395 kc_hs_type (HsOpTy ty1 op ty2) = do
396 op_kind <- addLocM kcTyVar op
397 ([ty1',ty2'], res_kind) <- kcApps op op_kind [ty1,ty2]
398 return (HsOpTy ty1' op ty2', res_kind)
400 kc_hs_type (HsAppTy ty1 ty2) = do
401 let (fun_ty, arg_tys) = splitHsAppTys ty1 [ty2]
402 (fun_ty', fun_kind) <- kc_lhs_type fun_ty
403 (arg_tys', res_kind) <- kcApps fun_ty fun_kind arg_tys
404 return (mkHsAppTys fun_ty' arg_tys', res_kind)
406 kc_hs_type (HsPredTy pred)
409 kc_hs_type (HsCoreTy ty)
410 = return (HsCoreTy ty, typeKind ty)
412 kc_hs_type (HsForAllTy exp tv_names context ty)
413 = kcHsTyVars tv_names $ \ tv_names' ->
414 do { ctxt' <- kcHsContext context
415 ; ty' <- kcLiftedType ty
416 -- The body of a forall is usually a type, but in principle
417 -- there's no reason to prohibit *unlifted* types.
418 -- In fact, GHC can itself construct a function with an
419 -- unboxed tuple inside a for-all (via CPR analyis; see
420 -- typecheck/should_compile/tc170)
422 -- Still, that's only for internal interfaces, which aren't
423 -- kind-checked, so we only allow liftedTypeKind here
425 ; return (HsForAllTy exp tv_names' ctxt' ty', liftedTypeKind) }
427 kc_hs_type (HsBangTy b ty)
428 = do { (ty', kind) <- kc_lhs_type ty
429 ; return (HsBangTy b ty', kind) }
431 kc_hs_type ty@(HsRecTy _)
432 = failWithTc (ptext (sLit "Unexpected record type") <+> ppr ty)
433 -- Record types (which only show up temporarily in constructor signatures)
434 -- should have been removed by now
436 #ifdef GHCI /* Only if bootstrapped */
437 kc_hs_type (HsSpliceTy sp fvs _) = kcSpliceType sp fvs
439 kc_hs_type ty@(HsSpliceTy {}) = failWithTc (ptext (sLit "Unexpected type splice:") <+> ppr ty)
442 kc_hs_type (HsQuasiQuoteTy {}) = panic "kc_hs_type" -- Eliminated by renamer
444 -- remove the doc nodes here, no need to worry about the location since
445 -- its the same for a doc node and it's child type node
446 kc_hs_type (HsDocTy ty _)
447 = kc_hs_type (unLoc ty)
449 ---------------------------
450 kcApps :: Outputable a
452 -> TcKind -- Function kind
453 -> [LHsType Name] -- Arg types
454 -> TcM ([LHsType Name], TcKind) -- Kind-checked args
455 kcApps the_fun fun_kind args
456 = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
457 ; args' <- kc_check_lhs_types args_w_kinds
458 ; return (args', res_kind) }
460 kcCheckApps :: Outputable a => a -> TcKind -> [LHsType Name]
461 -> HsType Name -- The type being checked (for err messages only)
462 -> ExpKind -- Expected kind
463 -> TcM [LHsType Name]
464 kcCheckApps the_fun fun_kind args ty exp_kind
465 = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
466 ; checkExpectedKind ty res_kind exp_kind
467 -- Check the result kind *before* checking argument kinds
468 -- This improves error message; Trac #2994
469 ; kc_check_lhs_types args_w_kinds }
472 ---------------------------
473 splitFunKind :: SDoc -> Int -> TcKind -> [b] -> TcM ([(b,ExpKind)], TcKind)
474 splitFunKind _ _ fk [] = return ([], fk)
475 splitFunKind the_fun arg_no fk (arg:args)
476 = do { mb_fk <- matchExpectedFunKind fk
478 Nothing -> failWithTc too_many_args
479 Just (ak,fk') -> do { (aks, rk) <- splitFunKind the_fun (arg_no+1) fk' args
480 ; return ((arg, EK ak (EkArg the_fun arg_no)):aks, rk) } }
482 too_many_args = quotes the_fun <+>
483 ptext (sLit "is applied to too many type arguments")
485 ---------------------------
486 kcHsContext :: LHsContext Name -> TcM (LHsContext Name)
487 kcHsContext ctxt = wrapLocM (mapM kcHsLPred) ctxt
489 kcHsLPred :: LHsPred Name -> TcM (LHsPred Name)
490 kcHsLPred = wrapLocM kcHsPred
492 kcHsPred :: HsPred Name -> TcM (HsPred Name)
493 kcHsPred pred = do -- Checks that the result is a type kind
494 (pred', kind) <- kc_pred pred
495 checkExpectedKind pred kind ekOpen
498 ---------------------------
499 kc_pred :: HsPred Name -> TcM (HsPred Name, TcKind)
500 -- Does *not* check for a saturated
501 -- application (reason: used from TcDeriv)
502 kc_pred (HsIParam name ty)
503 = do { (ty', kind) <- kc_lhs_type ty
504 ; return (HsIParam name ty', kind) }
505 kc_pred (HsClassP cls tys)
506 = do { kind <- kcClass cls
507 ; (tys', res_kind) <- kcApps cls kind tys
508 ; return (HsClassP cls tys', res_kind) }
509 kc_pred (HsEqualP ty1 ty2)
510 = do { (ty1', kind1) <- kc_lhs_type ty1
511 ; (ty2', kind2) <- kc_lhs_type ty2
512 ; checkExpectedKind ty2 kind2 (EK kind1 EkEqPred)
513 ; return (HsEqualP ty1' ty2', unliftedTypeKind) }
515 ---------------------------
516 kcTyVar :: Name -> TcM TcKind
517 kcTyVar name = do -- Could be a tyvar or a tycon
518 traceTc "lk1" (ppr name)
519 thing <- tcLookup name
520 traceTc "lk2" (ppr name <+> ppr thing)
522 ATyVar _ ty -> return (typeKind ty)
523 AThing kind -> return kind
524 AGlobal (ATyCon tc) -> return (tyConKind tc)
525 _ -> wrongThingErr "type" thing name
527 kcClass :: Name -> TcM TcKind
528 kcClass cls = do -- Must be a class
529 thing <- tcLookup cls
531 AThing kind -> return kind
532 AGlobal (AClass cls) -> return (tyConKind (classTyCon cls))
533 _ -> wrongThingErr "class" thing cls
537 %************************************************************************
541 %************************************************************************
545 * Transforms from HsType to Type
548 It cannot fail, and does no validity checking, except for
549 structural matters, such as
550 (a) spurious ! annotations.
551 (b) a class used as a type
554 dsHsType :: LHsType Name -> TcM Type
555 -- All HsTyVarBndrs in the intput type are kind-annotated
556 dsHsType ty = ds_type (unLoc ty)
558 ds_type :: HsType Name -> TcM Type
559 ds_type ty@(HsTyVar _)
562 ds_type (HsParTy ty) -- Remove the parentheses markers
565 ds_type ty@(HsBangTy {}) -- No bangs should be here
566 = failWithTc (ptext (sLit "Unexpected strictness annotation:") <+> ppr ty)
568 ds_type ty@(HsRecTy {}) -- No bangs should be here
569 = failWithTc (ptext (sLit "Unexpected record type:") <+> ppr ty)
571 ds_type (HsKindSig ty _)
572 = dsHsType ty -- Kind checking done already
574 ds_type (HsListTy ty) = do
575 tau_ty <- dsHsType ty
576 checkWiredInTyCon listTyCon
577 return (mkListTy tau_ty)
579 ds_type (HsPArrTy ty) = do
580 tau_ty <- dsHsType ty
581 checkWiredInTyCon parrTyCon
582 return (mkPArrTy tau_ty)
584 ds_type (HsModalBoxType ecn ty) = do
585 tau_ty <- dsHsType ty
586 checkWiredInTyCon hetMetCodeTypeTyCon
587 return (mkHetMetCodeTypeTy (mkTyVar ecn ecKind) tau_ty)
589 ds_type (HsKappaTy ty1 ty2) = do
590 tau_ty1 <- dsHsType ty1
591 tau_ty2 <- dsHsType ty2
592 return (mkHetMetKappaTy tau_ty1 tau_ty2)
594 ds_type (HsTupleTy boxity tys) = do
595 tau_tys <- dsHsTypes tys
596 checkWiredInTyCon tycon
597 return (mkTyConApp tycon tau_tys)
599 tycon = tupleTyCon boxity (length tys)
601 ds_type (HsFunTy ty1 ty2) = do
602 tau_ty1 <- dsHsType ty1
603 tau_ty2 <- dsHsType ty2
604 return (mkFunTy tau_ty1 tau_ty2)
606 ds_type (HsOpTy ty1 (L span op) ty2) = do
607 tau_ty1 <- dsHsType ty1
608 tau_ty2 <- dsHsType ty2
609 setSrcSpan span (ds_var_app op [tau_ty1,tau_ty2])
611 ds_type ty@(HsAppTy _ _)
614 ds_type (HsPredTy pred) = do
615 pred' <- dsHsPred pred
616 return (mkPredTy pred')
618 ds_type (HsForAllTy _ tv_names ctxt ty)
619 = tcTyVarBndrs tv_names $ \ tyvars -> do
620 theta <- mapM dsHsLPred (unLoc ctxt)
622 return (mkSigmaTy tyvars theta tau)
624 ds_type (HsDocTy ty _) -- Remove the doc comment
627 ds_type (HsSpliceTy _ _ kind)
628 = do { kind' <- zonkTcKindToKind kind
629 ; newFlexiTyVarTy kind' }
631 ds_type (HsQuasiQuoteTy {}) = panic "ds_type" -- Eliminated by renamer
632 ds_type (HsCoreTy ty) = return ty
634 dsHsTypes :: [LHsType Name] -> TcM [Type]
635 dsHsTypes arg_tys = mapM dsHsType arg_tys
638 Help functions for type applications
639 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
642 ds_app :: HsType Name -> [LHsType Name] -> TcM Type
643 ds_app (HsAppTy ty1 ty2) tys
644 = ds_app (unLoc ty1) (ty2:tys)
647 arg_tys <- dsHsTypes tys
649 HsTyVar fun -> ds_var_app fun arg_tys
650 _ -> do fun_ty <- ds_type ty
651 return (mkAppTys fun_ty arg_tys)
653 ds_var_app :: Name -> [Type] -> TcM Type
654 ds_var_app name arg_tys = do
655 thing <- tcLookup name
657 ATyVar _ ty -> return (mkAppTys ty arg_tys)
658 AGlobal (ATyCon tc) -> return (mkTyConApp tc arg_tys)
659 _ -> wrongThingErr "type" thing name
667 dsHsLPred :: LHsPred Name -> TcM PredType
668 dsHsLPred pred = dsHsPred (unLoc pred)
670 dsHsPred :: HsPred Name -> TcM PredType
671 dsHsPred (HsClassP class_name tys)
672 = do { arg_tys <- dsHsTypes tys
673 ; clas <- tcLookupClass class_name
674 ; return (ClassP clas arg_tys)
676 dsHsPred (HsEqualP ty1 ty2)
677 = do { arg_ty1 <- dsHsType ty1
678 ; arg_ty2 <- dsHsType ty2
679 ; return (EqPred arg_ty1 arg_ty2)
681 dsHsPred (HsIParam name ty)
682 = do { arg_ty <- dsHsType ty
683 ; return (IParam name arg_ty)
688 addKcTypeCtxt :: LHsType Name -> TcM a -> TcM a
689 -- Wrap a context around only if we want to show that contexts.
690 addKcTypeCtxt (L _ (HsPredTy _)) thing = thing
691 -- Omit invisble ones and ones user's won't grok (HsPred p).
692 addKcTypeCtxt (L _ other_ty) thing = addErrCtxt (typeCtxt other_ty) thing
694 typeCtxt :: HsType Name -> SDoc
695 typeCtxt ty = ptext (sLit "In the type") <+> quotes (ppr ty)
698 %************************************************************************
700 Type-variable binders
702 %************************************************************************
706 kcHsTyVars :: [LHsTyVarBndr Name]
707 -> ([LHsTyVarBndr Name] -> TcM r) -- These binders are kind-annotated
708 -- They scope over the thing inside
710 kcHsTyVars tvs thing_inside
711 = do { kinded_tvs <- mapM (wrapLocM kcHsTyVar) tvs
712 ; tcExtendKindEnvTvs kinded_tvs thing_inside }
714 kcHsTyVar :: HsTyVarBndr Name -> TcM (HsTyVarBndr Name)
715 -- Return a *kind-annotated* binder, and a tyvar with a mutable kind in it
716 kcHsTyVar (UserTyVar name _) = UserTyVar name <$> newKindVar
717 kcHsTyVar tv@(KindedTyVar {}) = return tv
720 tcTyVarBndrs :: [LHsTyVarBndr Name] -- Kind-annotated binders, which need kind-zonking
721 -> ([TyVar] -> TcM r)
723 -- Used when type-checking types/classes/type-decls
724 -- Brings into scope immutable TyVars, not mutable ones that require later zonking
725 tcTyVarBndrs bndrs thing_inside = do
726 tyvars <- mapM (zonk . unLoc) bndrs
727 tcExtendTyVarEnv tyvars (thing_inside tyvars)
729 zonk (UserTyVar name kind) = do { kind' <- zonkTcKindToKind kind
730 ; return (mkTyVar name kind') }
731 zonk (KindedTyVar name kind) = return (mkTyVar name kind)
733 -----------------------------------
734 tcDataKindSig :: Maybe Kind -> TcM [TyVar]
735 -- GADT decls can have a (perhaps partial) kind signature
736 -- e.g. data T :: * -> * -> * where ...
737 -- This function makes up suitable (kinded) type variables for
738 -- the argument kinds, and checks that the result kind is indeed *.
739 -- We use it also to make up argument type variables for for data instances.
740 tcDataKindSig Nothing = return []
741 tcDataKindSig (Just kind)
742 = do { checkTc (isLiftedTypeKind res_kind) (badKindSig kind)
743 ; span <- getSrcSpanM
744 ; us <- newUniqueSupply
745 ; let uniqs = uniqsFromSupply us
746 ; return [ mk_tv span uniq str kind
747 | ((kind, str), uniq) <- arg_kinds `zip` dnames `zip` uniqs ] }
749 (arg_kinds, res_kind) = splitKindFunTys kind
750 mk_tv loc uniq str kind = mkTyVar name kind
752 name = mkInternalName uniq occ loc
753 occ = mkOccName tvName str
755 dnames = map ('$' :) names -- Note [Avoid name clashes for associated data types]
758 names = [ c:cs | cs <- "" : names, c <- ['a'..'z'] ]
760 badKindSig :: Kind -> SDoc
762 = hang (ptext (sLit "Kind signature on data type declaration has non-* return kind"))
766 Note [Avoid name clashes for associated data types]
767 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
768 Consider class C a b where
770 When typechecking the decl for D, we'll invent an extra type variable for D,
771 to fill out its kind. We *don't* want this type variable to be 'a', because
772 in an .hi file we'd get
775 which makes it look as if there are *two* type indices. But there aren't!
776 So we use $a instead, which cannot clash with a user-written type variable.
777 Remember that type variable binders in interface files are just FastStrings,
780 (The tidying phase can't help here because we don't tidy TyCons. Another
781 alternative would be to record the number of indexing parameters in the
785 %************************************************************************
787 Scoped type variables
789 %************************************************************************
792 tcAddScopedTyVars is used for scoped type variables added by pattern
794 e.g. \ ((x::a), (y::a)) -> x+y
795 They never have explicit kinds (because this is source-code only)
796 They are mutable (because they can get bound to a more specific type).
798 Usually we kind-infer and expand type splices, and then
799 tupecheck/desugar the type. That doesn't work well for scoped type
800 variables, because they scope left-right in patterns. (e.g. in the
801 example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
803 The current not-very-good plan is to
804 * find all the types in the patterns
805 * find their free tyvars
807 * bring the kinded type vars into scope
808 * BUT throw away the kind-checked type
809 (we'll kind-check it again when we type-check the pattern)
811 This is bad because throwing away the kind checked type throws away
812 its splices. But too bad for now. [July 03]
815 We no longer specify that these type variables must be univerally
816 quantified (lots of email on the subject). If you want to put that
818 a) Do a checkSigTyVars after thing_inside
819 b) More insidiously, don't pass in expected_ty, else
820 we unify with it too early and checkSigTyVars barfs
821 Instead you have to pass in a fresh ty var, and unify
822 it with expected_ty afterwards
825 tcHsPatSigType :: UserTypeCtxt
826 -> LHsType Name -- The type signature
827 -> TcM ([TyVar], -- Newly in-scope type variables
828 Type) -- The signature
829 -- Used for type-checking type signatures in
830 -- (a) patterns e.g f (x::Int) = e
831 -- (b) result signatures e.g. g x :: Int = e
832 -- (c) RULE forall bndrs e.g. forall (x::Int). f x = x
834 tcHsPatSigType ctxt hs_ty
835 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
836 do { -- Find the type variables that are mentioned in the type
837 -- but not already in scope. These are the ones that
838 -- should be bound by the pattern signature
839 in_scope <- getInLocalScope
840 ; let span = getLoc hs_ty
841 sig_tvs = userHsTyVarBndrs $ map (L span) $
843 nameSetToList (extractHsTyVars hs_ty)
845 ; (tyvars, sig_ty) <- tcHsQuantifiedType sig_tvs hs_ty
846 ; checkValidType ctxt sig_ty
847 ; return (tyvars, sig_ty)
850 tcPatSig :: UserTypeCtxt
853 -> TcM (TcType, -- The type to use for "inside" the signature
854 [(Name, TcType)], -- The new bit of type environment, binding
855 -- the scoped type variables
856 HsWrapper) -- Coercion due to unification with actual ty
857 -- Of shape: res_ty ~ sig_ty
858 tcPatSig ctxt sig res_ty
859 = do { (sig_tvs, sig_ty) <- tcHsPatSigType ctxt sig
860 -- sig_tvs are the type variables free in 'sig',
861 -- and not already in scope. These are the ones
862 -- that should be brought into scope
864 ; if null sig_tvs then do {
865 -- The type signature binds no type variables,
866 -- and hence is rigid, so use it to zap the res_ty
867 wrap <- tcSubType PatSigOrigin ctxt res_ty sig_ty
868 ; return (sig_ty, [], wrap)
870 -- Type signature binds at least one scoped type variable
872 -- A pattern binding cannot bind scoped type variables
873 -- The renamer fails with a name-out-of-scope error
874 -- if a pattern binding tries to bind a type variable,
875 -- So we just have an ASSERT here
876 ; let in_pat_bind = case ctxt of
877 BindPatSigCtxt -> True
879 ; ASSERT( not in_pat_bind || null sig_tvs ) return ()
881 -- Check that all newly-in-scope tyvars are in fact
882 -- constrained by the pattern. This catches tiresome
886 -- f (x :: T a) = ...
887 -- Here 'a' doesn't get a binding. Sigh
888 ; let bad_tvs = filterOut (`elemVarSet` exactTyVarsOfType sig_ty) sig_tvs
889 ; checkTc (null bad_tvs) (badPatSigTvs sig_ty bad_tvs)
891 -- Now do a subsumption check of the pattern signature against res_ty
892 ; sig_tvs' <- tcInstSigTyVars sig_tvs
893 ; let sig_ty' = substTyWith sig_tvs sig_tv_tys' sig_ty
894 sig_tv_tys' = mkTyVarTys sig_tvs'
895 ; wrap <- tcSubType PatSigOrigin ctxt res_ty sig_ty'
897 -- Check that each is bound to a distinct type variable,
898 -- and one that is not already in scope
899 ; binds_in_scope <- getScopedTyVarBinds
900 ; let tv_binds = map tyVarName sig_tvs `zip` sig_tv_tys'
901 ; check binds_in_scope tv_binds
904 ; return (sig_ty', tv_binds, wrap)
907 check _ [] = return ()
908 check in_scope ((n,ty):rest) = do { check_one in_scope n ty
909 ; check ((n,ty):in_scope) rest }
911 check_one in_scope n ty
912 = checkTc (null dups) (dupInScope n (head dups) ty)
913 -- Must not bind to the same type variable
914 -- as some other in-scope type variable
916 dups = [n' | (n',ty') <- in_scope, eqType ty' ty]
920 %************************************************************************
924 %************************************************************************
926 We would like to get a decent error message from
927 (a) Under-applied type constructors
929 (b) Over-applied type constructors
933 -- The ExpKind datatype means "expected kind" and contains
934 -- some info about just why that kind is expected, to improve
935 -- the error message on a mis-match
936 data ExpKind = EK TcKind EkCtxt
937 data EkCtxt = EkUnk -- Unknown context
938 | EkEqPred -- Second argument of an equality predicate
939 | EkKindSig -- Kind signature
940 | EkArg SDoc Int -- Function, arg posn, expected kind
943 ekLifted, ekOpen :: ExpKind
944 ekLifted = EK liftedTypeKind EkUnk
945 ekOpen = EK openTypeKind EkUnk
947 checkExpectedKind :: Outputable a => a -> TcKind -> ExpKind -> TcM ()
948 -- A fancy wrapper for 'unifyKind', which tries
949 -- to give decent error messages.
950 -- (checkExpectedKind ty act_kind exp_kind)
951 -- checks that the actual kind act_kind is compatible
952 -- with the expected kind exp_kind
953 -- The first argument, ty, is used only in the error message generation
954 checkExpectedKind ty act_kind (EK exp_kind ek_ctxt)
955 | act_kind `isSubKind` exp_kind -- Short cut for a very common case
958 (_errs, mb_r) <- tryTc (unifyKind exp_kind act_kind)
960 Just _ -> return () -- Unification succeeded
963 -- So there's definitely an error
964 -- Now to find out what sort
965 exp_kind <- zonkTcKind exp_kind
966 act_kind <- zonkTcKind act_kind
968 env0 <- tcInitTidyEnv
969 let (exp_as, _) = splitKindFunTys exp_kind
970 (act_as, _) = splitKindFunTys act_kind
971 n_exp_as = length exp_as
972 n_act_as = length act_as
974 (env1, tidy_exp_kind) = tidyKind env0 exp_kind
975 (env2, tidy_act_kind) = tidyKind env1 act_kind
977 err | n_exp_as < n_act_as -- E.g. [Maybe]
978 = quotes (ppr ty) <+> ptext (sLit "is not applied to enough type arguments")
980 -- Now n_exp_as >= n_act_as. In the next two cases,
981 -- n_exp_as == 0, and hence so is n_act_as
982 | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
983 = ptext (sLit "Expecting a lifted type, but") <+> quotes (ppr ty)
984 <+> ptext (sLit "is unlifted")
986 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
987 = ptext (sLit "Expecting an unlifted type, but") <+> quotes (ppr ty)
988 <+> ptext (sLit "is lifted")
990 | otherwise -- E.g. Monad [Int]
991 = ptext (sLit "Kind mis-match")
993 more_info = sep [ expected_herald ek_ctxt <+> ptext (sLit "kind")
994 <+> quotes (pprKind tidy_exp_kind) <> comma,
995 ptext (sLit "but") <+> quotes (ppr ty) <+>
996 ptext (sLit "has kind") <+> quotes (pprKind tidy_act_kind)]
998 expected_herald EkUnk = ptext (sLit "Expected")
999 expected_herald EkKindSig = ptext (sLit "An enclosing kind signature specified")
1000 expected_herald EkEqPred = ptext (sLit "The left argument of the equality predicate had")
1001 expected_herald (EkArg fun arg_no)
1002 = ptext (sLit "The") <+> speakNth arg_no <+> ptext (sLit "argument of")
1003 <+> quotes fun <+> ptext (sLit ("should have"))
1005 failWithTcM (env2, err $$ more_info)
1008 %************************************************************************
1010 Scoped type variables
1012 %************************************************************************
1015 pprHsSigCtxt :: UserTypeCtxt -> LHsType Name -> SDoc
1016 pprHsSigCtxt ctxt hs_ty = sep [ ptext (sLit "In") <+> pprUserTypeCtxt ctxt <> colon,
1017 nest 2 (pp_sig ctxt) ]
1019 pp_sig (FunSigCtxt n) = pp_n_colon n
1020 pp_sig (ConArgCtxt n) = pp_n_colon n
1021 pp_sig (ForSigCtxt n) = pp_n_colon n
1022 pp_sig _ = ppr (unLoc hs_ty)
1024 pp_n_colon n = ppr n <+> dcolon <+> ppr (unLoc hs_ty)
1026 badPatSigTvs :: TcType -> [TyVar] -> SDoc
1027 badPatSigTvs sig_ty bad_tvs
1028 = vcat [ fsep [ptext (sLit "The type variable") <> plural bad_tvs,
1029 quotes (pprWithCommas ppr bad_tvs),
1030 ptext (sLit "should be bound by the pattern signature") <+> quotes (ppr sig_ty),
1031 ptext (sLit "but are actually discarded by a type synonym") ]
1032 , ptext (sLit "To fix this, expand the type synonym")
1033 , ptext (sLit "[Note: I hope to lift this restriction in due course]") ]
1035 dupInScope :: Name -> Name -> Type -> SDoc
1037 = hang (ptext (sLit "The scoped type variables") <+> quotes (ppr n) <+> ptext (sLit "and") <+> quotes (ppr n'))
1038 2 (vcat [ptext (sLit "are bound to the same type (variable)"),
1039 ptext (sLit "Distinct scoped type variables must be distinct")])
1041 wrongPredErr :: HsPred Name -> TcM (HsType Name, TcKind)
1042 wrongPredErr pred = failWithTc (text "Predicate used as a type:" <+> ppr pred)