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, tcHsDeriv,
10 tcHsInstHead, tcHsQuantifiedType,
14 kcHsTyVars, kcHsSigType, kcHsLiftedSigType,
15 kcCheckHsType, kcHsContext, kcHsType,
17 -- Typechecking kinded types
18 tcHsKindedContext, tcHsKindedType, tcHsBangType,
19 tcTyVarBndrs, dsHsType, tcLHsConResTy,
22 -- Pattern type signatures
23 tcHsPatSigType, tcPatSig
26 #include "HsVersions.h"
36 import {- Kind parts of -} Type
55 ----------------------------
57 ----------------------------
59 Generally speaking we now type-check types in three phases
61 1. kcHsType: kind check the HsType
62 *includes* performing any TH type splices;
63 so it returns a translated, and kind-annotated, type
65 2. dsHsType: convert from HsType to Type:
67 expand type synonyms [mkGenTyApps]
68 hoist the foralls [tcHsType]
70 3. checkValidType: check the validity of the resulting type
72 Often these steps are done one after the other (tcHsSigType).
73 But in mutually recursive groups of type and class decls we do
74 1 kind-check the whole group
75 2 build TyCons/Classes in a knot-tied way
76 3 check the validity of types in the now-unknotted TyCons/Classes
78 For example, when we find
79 (forall a m. m a -> m a)
80 we bind a,m to kind varibles and kind-check (m a -> m a). This makes
81 a get kind *, and m get kind *->*. Now we typecheck (m a -> m a) in
82 an environment that binds a and m suitably.
84 The kind checker passed to tcHsTyVars needs to look at enough to
85 establish the kind of the tyvar:
86 * For a group of type and class decls, it's just the group, not
87 the rest of the program
88 * For a tyvar bound in a pattern type signature, its the types
89 mentioned in the other type signatures in that bunch of patterns
90 * For a tyvar bound in a RULE, it's the type signatures on other
91 universally quantified variables in the rule
93 Note that this may occasionally give surprising results. For example:
95 data T a b = MkT (a b)
97 Here we deduce a::*->*, b::*
98 But equally valid would be a::(*->*)-> *, b::*->*
103 Some of the validity check could in principle be done by the kind checker,
106 - During desugaring, we normalise by expanding type synonyms. Only
107 after this step can we check things like type-synonym saturation
108 e.g. type T k = k Int
110 Then (T S) is ok, because T is saturated; (T S) expands to (S Int);
111 and then S is saturated. This is a GHC extension.
113 - Similarly, also a GHC extension, we look through synonyms before complaining
114 about the form of a class or instance declaration
116 - Ambiguity checks involve functional dependencies, and it's easier to wait
117 until knots have been resolved before poking into them
119 Also, in a mutually recursive group of types, we can't look at the TyCon until we've
120 finished building the loop. So to keep things simple, we postpone most validity
121 checking until step (3).
125 During step (1) we might fault in a TyCon defined in another module, and it might
126 (via a loop) refer back to a TyCon defined in this module. So when we tie a big
127 knot around type declarations with ARecThing, so that the fault-in code can get
128 the TyCon being defined.
131 %************************************************************************
133 \subsection{Checking types}
135 %************************************************************************
138 tcHsSigType :: UserTypeCtxt -> LHsType Name -> TcM Type
139 -- Do kind checking, and hoist for-alls to the top
140 -- NB: it's important that the foralls that come from the top-level
141 -- HsForAllTy in hs_ty occur *first* in the returned type.
142 -- See Note [Scoped] with TcSigInfo
143 tcHsSigType ctxt hs_ty
144 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
145 do { kinded_ty <- kcTypeType hs_ty
146 ; ty <- tcHsKindedType kinded_ty
147 ; checkValidType ctxt ty
150 tcHsInstHead :: LHsType Name -> TcM ([TyVar], ThetaType, Type)
151 -- Typecheck an instance head. We can't use
152 -- tcHsSigType, because it's not a valid user type.
154 = do { kinded_ty <- kcHsSigType hs_ty
155 ; poly_ty <- tcHsKindedType kinded_ty
156 ; return (tcSplitSigmaTy poly_ty) }
158 tcHsQuantifiedType :: [LHsTyVarBndr Name] -> LHsType Name -> TcM ([TyVar], Type)
159 -- Behave very like type-checking (HsForAllTy sig_tvs hs_ty),
160 -- except that we want to keep the tvs separate
161 tcHsQuantifiedType tv_names hs_ty
162 = kcHsTyVars tv_names $ \ tv_names' ->
163 do { kc_ty <- kcHsSigType hs_ty
164 ; tcTyVarBndrs tv_names' $ \ tvs ->
165 do { ty <- dsHsType kc_ty
166 ; return (tvs, ty) } }
168 -- Used for the deriving(...) items
169 tcHsDeriv :: HsType Name -> TcM ([TyVar], Class, [Type])
170 tcHsDeriv = tc_hs_deriv []
172 tc_hs_deriv :: [LHsTyVarBndr Name] -> HsType Name
173 -> TcM ([TyVar], Class, [Type])
174 tc_hs_deriv tv_names (HsPredTy (HsClassP cls_name hs_tys))
175 = kcHsTyVars tv_names $ \ tv_names' ->
176 do { cls_kind <- kcClass cls_name
177 ; (tys, _res_kind) <- kcApps cls_kind (ppr cls_name) hs_tys
178 ; tcTyVarBndrs tv_names' $ \ tyvars ->
179 do { arg_tys <- dsHsTypes tys
180 ; cls <- tcLookupClass cls_name
181 ; return (tyvars, cls, arg_tys) }}
183 tc_hs_deriv tv_names1 (HsForAllTy _ tv_names2 (L _ []) (L _ ty))
184 = -- Funny newtype deriving form
186 -- where C has arity 2. Hence can't use regular functions
187 tc_hs_deriv (tv_names1 ++ tv_names2) ty
190 = failWithTc (ptext (sLit "Illegal deriving item") <+> ppr other)
193 These functions are used during knot-tying in
194 type and class declarations, when we have to
195 separate kind-checking, desugaring, and validity checking
198 kcHsSigType, kcHsLiftedSigType :: LHsType Name -> TcM (LHsType Name)
199 -- Used for type signatures
200 kcHsSigType ty = kcTypeType ty
201 kcHsLiftedSigType ty = kcLiftedType ty
203 tcHsKindedType :: LHsType Name -> TcM Type
204 -- Don't do kind checking, nor validity checking.
205 -- This is used in type and class decls, where kinding is
206 -- done in advance, and validity checking is done later
207 -- [Validity checking done later because of knot-tying issues.]
208 tcHsKindedType hs_ty = dsHsType hs_ty
210 tcHsBangType :: LHsType Name -> TcM Type
211 -- Permit a bang, but discard it
212 tcHsBangType (L _ (HsBangTy _ ty)) = tcHsKindedType ty
213 tcHsBangType ty = tcHsKindedType ty
215 tcHsKindedContext :: LHsContext Name -> TcM ThetaType
216 -- Used when we are expecting a ClassContext (i.e. no implicit params)
217 -- Does not do validity checking, like tcHsKindedType
218 tcHsKindedContext hs_theta = addLocM (mapM dsHsLPred) hs_theta
222 %************************************************************************
224 The main kind checker: kcHsType
226 %************************************************************************
228 First a couple of simple wrappers for kcHsType
231 ---------------------------
232 kcLiftedType :: LHsType Name -> TcM (LHsType Name)
233 -- The type ty must be a *lifted* *type*
234 kcLiftedType ty = kcCheckHsType ty liftedTypeKind
236 ---------------------------
237 kcTypeType :: LHsType Name -> TcM (LHsType Name)
238 -- The type ty must be a *type*, but it can be lifted or
239 -- unlifted or an unboxed tuple.
240 kcTypeType ty = kcCheckHsType ty openTypeKind
242 ---------------------------
243 kcCheckHsType :: LHsType Name -> TcKind -> TcM (LHsType Name)
244 -- Check that the type has the specified kind
245 -- Be sure to use checkExpectedKind, rather than simply unifying
246 -- with OpenTypeKind, because it gives better error messages
247 kcCheckHsType (L span ty) exp_kind
249 do { (ty', act_kind) <- add_ctxt ty (kc_hs_type ty)
250 -- Add the context round the inner check only
251 -- because checkExpectedKind already mentions
252 -- 'ty' by name in any error message
254 ; checkExpectedKind (strip ty) act_kind exp_kind
255 ; return (L span ty') }
257 -- Wrap a context around only if we want to show that contexts.
258 add_ctxt (HsPredTy _) thing = thing
259 -- Omit invisble ones and ones user's won't grok (HsPred p).
260 add_ctxt (HsForAllTy _ _ (L _ []) _) thing = thing
261 -- Omit wrapping if the theta-part is empty
262 -- Reason: the recursive call to kcLiftedType, in the ForAllTy
263 -- case of kc_hs_type, will do the wrapping instead
264 -- and we don't want to duplicate
265 add_ctxt other_ty thing = addErrCtxt (typeCtxt other_ty) thing
267 -- We infer the kind of the type, and then complain if it's
268 -- not right. But we don't want to complain about
269 -- (ty) or !(ty) or forall a. ty
270 -- when the real difficulty is with the 'ty' part.
271 strip (HsParTy (L _ ty)) = strip ty
272 strip (HsBangTy _ (L _ ty)) = strip ty
273 strip (HsForAllTy _ _ _ (L _ ty)) = strip ty
277 Here comes the main function
280 kcHsType :: LHsType Name -> TcM (LHsType Name, TcKind)
281 kcHsType ty = wrapLocFstM kc_hs_type ty
282 -- kcHsType *returns* the kind of the type, rather than taking an expected
283 -- kind as argument as tcExpr does.
285 -- (a) the kind of (->) is
286 -- forall bx1 bx2. Type bx1 -> Type bx2 -> Type Boxed
287 -- so we'd need to generate huge numbers of bx variables.
288 -- (b) kinds are so simple that the error messages are fine
290 -- The translated type has explicitly-kinded type-variable binders
292 kc_hs_type :: HsType Name -> TcM (HsType Name, TcKind)
293 kc_hs_type (HsParTy ty) = do
294 (ty', kind) <- kcHsType ty
295 return (HsParTy ty', kind)
297 kc_hs_type (HsTyVar name) = do
299 return (HsTyVar name, kind)
301 kc_hs_type (HsListTy ty) = do
302 ty' <- kcLiftedType ty
303 return (HsListTy ty', liftedTypeKind)
305 kc_hs_type (HsPArrTy ty) = do
306 ty' <- kcLiftedType ty
307 return (HsPArrTy ty', liftedTypeKind)
309 kc_hs_type (HsNumTy n)
310 = return (HsNumTy n, liftedTypeKind)
312 kc_hs_type (HsKindSig ty k) = do
313 ty' <- kcCheckHsType ty k
314 return (HsKindSig ty' k, k)
316 kc_hs_type (HsTupleTy Boxed tys) = do
317 tys' <- mapM kcLiftedType tys
318 return (HsTupleTy Boxed tys', liftedTypeKind)
320 kc_hs_type (HsTupleTy Unboxed tys) = do
321 tys' <- mapM kcTypeType tys
322 return (HsTupleTy Unboxed tys', ubxTupleKind)
324 kc_hs_type (HsFunTy ty1 ty2) = do
325 ty1' <- kcCheckHsType ty1 argTypeKind
326 ty2' <- kcTypeType ty2
327 return (HsFunTy ty1' ty2', liftedTypeKind)
329 kc_hs_type (HsOpTy ty1 op ty2) = do
330 op_kind <- addLocM kcTyVar op
331 ([ty1',ty2'], res_kind) <- kcApps op_kind (ppr op) [ty1,ty2]
332 return (HsOpTy ty1' op ty2', res_kind)
334 kc_hs_type (HsAppTy ty1 ty2) = do
335 (fun_ty', fun_kind) <- kcHsType fun_ty
336 ((arg_ty':arg_tys'), res_kind) <- kcApps fun_kind (ppr fun_ty) arg_tys
337 return (foldl mk_app (HsAppTy fun_ty' arg_ty') arg_tys', res_kind)
339 (fun_ty, arg_tys) = split ty1 [ty2]
340 split (L _ (HsAppTy f a)) as = split f (a:as)
342 mk_app fun arg = HsAppTy (noLoc fun) arg -- Add noLocs for inner nodes of
343 -- the application; they are
346 kc_hs_type (HsPredTy (HsEqualP _ _))
349 kc_hs_type (HsPredTy pred) = do
350 pred' <- kcHsPred pred
351 return (HsPredTy pred', liftedTypeKind)
353 kc_hs_type (HsForAllTy exp tv_names context ty)
354 = kcHsTyVars tv_names $ \ tv_names' ->
355 do { ctxt' <- kcHsContext context
356 ; ty' <- kcLiftedType ty
357 -- The body of a forall is usually a type, but in principle
358 -- there's no reason to prohibit *unlifted* types.
359 -- In fact, GHC can itself construct a function with an
360 -- unboxed tuple inside a for-all (via CPR analyis; see
361 -- typecheck/should_compile/tc170)
363 -- Still, that's only for internal interfaces, which aren't
364 -- kind-checked, so we only allow liftedTypeKind here
366 ; return (HsForAllTy exp tv_names' ctxt' ty', liftedTypeKind) }
368 kc_hs_type (HsBangTy b ty) = do
369 (ty', kind) <- kcHsType ty
370 return (HsBangTy b ty', kind)
372 kc_hs_type ty@(HsSpliceTy _)
373 = failWithTc (ptext (sLit "Unexpected type splice:") <+> ppr ty)
375 -- remove the doc nodes here, no need to worry about the location since
376 -- its the same for a doc node and it's child type node
377 kc_hs_type (HsDocTy ty _)
378 = kc_hs_type (unLoc ty)
380 ---------------------------
381 kcApps :: TcKind -- Function kind
383 -> [LHsType Name] -- Arg types
384 -> TcM ([LHsType Name], TcKind) -- Kind-checked args
385 kcApps fun_kind ppr_fun args = do
386 (arg_kinds, res_kind) <- split_fk fun_kind (length args)
387 args' <- zipWithM kc_arg args arg_kinds
388 return (args', res_kind)
390 split_fk fk 0 = return ([], fk)
391 split_fk fk n = do mb_fk <- unifyFunKind fk
393 Nothing -> failWithTc too_many_args
394 Just (ak,fk') -> do (aks, rk) <- split_fk fk' (n-1)
397 kc_arg arg arg_kind = kcCheckHsType arg arg_kind
399 too_many_args = ptext (sLit "Kind error:") <+> quotes ppr_fun <+>
400 ptext (sLit "is applied to too many type arguments")
402 ---------------------------
403 kcHsContext :: LHsContext Name -> TcM (LHsContext Name)
404 kcHsContext ctxt = wrapLocM (mapM kcHsLPred) ctxt
406 kcHsLPred :: LHsPred Name -> TcM (LHsPred Name)
407 kcHsLPred = wrapLocM kcHsPred
409 kcHsPred :: HsPred Name -> TcM (HsPred Name)
410 kcHsPred pred = do -- Checks that the result is of kind liftedType
411 (pred', kind) <- kc_pred pred
412 checkExpectedKind pred kind liftedTypeKind
415 ---------------------------
416 kc_pred :: HsPred Name -> TcM (HsPred Name, TcKind)
417 -- Does *not* check for a saturated
418 -- application (reason: used from TcDeriv)
419 kc_pred (HsIParam name ty)
420 = do { (ty', kind) <- kcHsType ty
421 ; return (HsIParam name ty', kind)
423 kc_pred (HsClassP cls tys)
424 = do { kind <- kcClass cls
425 ; (tys', res_kind) <- kcApps kind (ppr cls) tys
426 ; return (HsClassP cls tys', res_kind)
428 kc_pred (HsEqualP ty1 ty2)
429 = do { (ty1', kind1) <- kcHsType ty1
430 -- ; checkExpectedKind ty1 kind1 liftedTypeKind
431 ; (ty2', kind2) <- kcHsType ty2
432 -- ; checkExpectedKind ty2 kind2 liftedTypeKind
433 ; checkExpectedKind ty2 kind2 kind1
434 ; return (HsEqualP ty1' ty2', liftedTypeKind)
437 ---------------------------
438 kcTyVar :: Name -> TcM TcKind
439 kcTyVar name = do -- Could be a tyvar or a tycon
440 traceTc (text "lk1" <+> ppr name)
441 thing <- tcLookup name
442 traceTc (text "lk2" <+> ppr name <+> ppr thing)
444 ATyVar _ ty -> return (typeKind ty)
445 AThing kind -> return kind
446 AGlobal (ATyCon tc) -> return (tyConKind tc)
447 _ -> wrongThingErr "type" thing name
449 kcClass :: Name -> TcM TcKind
450 kcClass cls = do -- Must be a class
451 thing <- tcLookup cls
453 AThing kind -> return kind
454 AGlobal (AClass cls) -> return (tyConKind (classTyCon cls))
455 _ -> wrongThingErr "class" thing cls
459 %************************************************************************
463 %************************************************************************
467 * Transforms from HsType to Type
470 It cannot fail, and does no validity checking, except for
471 structural matters, such as
472 (a) spurious ! annotations.
473 (b) a class used as a type
476 dsHsType :: LHsType Name -> TcM Type
477 -- All HsTyVarBndrs in the intput type are kind-annotated
478 dsHsType ty = ds_type (unLoc ty)
480 ds_type :: HsType Name -> TcM Type
481 ds_type ty@(HsTyVar _)
484 ds_type (HsParTy ty) -- Remove the parentheses markers
487 ds_type ty@(HsBangTy _ _) -- No bangs should be here
488 = failWithTc (ptext (sLit "Unexpected strictness annotation:") <+> ppr ty)
490 ds_type (HsKindSig ty _)
491 = dsHsType ty -- Kind checking done already
493 ds_type (HsListTy ty) = do
494 tau_ty <- dsHsType ty
495 checkWiredInTyCon listTyCon
496 return (mkListTy tau_ty)
498 ds_type (HsPArrTy ty) = do
499 tau_ty <- dsHsType ty
500 checkWiredInTyCon parrTyCon
501 return (mkPArrTy tau_ty)
503 ds_type (HsTupleTy boxity tys) = do
504 tau_tys <- dsHsTypes tys
505 checkWiredInTyCon tycon
506 return (mkTyConApp tycon tau_tys)
508 tycon = tupleTyCon boxity (length tys)
510 ds_type (HsFunTy ty1 ty2) = do
511 tau_ty1 <- dsHsType ty1
512 tau_ty2 <- dsHsType ty2
513 return (mkFunTy tau_ty1 tau_ty2)
515 ds_type (HsOpTy ty1 (L span op) ty2) = do
516 tau_ty1 <- dsHsType ty1
517 tau_ty2 <- dsHsType ty2
518 setSrcSpan span (ds_var_app op [tau_ty1,tau_ty2])
522 tc <- tcLookupTyCon genUnitTyConName
523 return (mkTyConApp tc [])
525 ds_type ty@(HsAppTy _ _)
528 ds_type (HsPredTy pred) = do
529 pred' <- dsHsPred pred
530 return (mkPredTy pred')
532 ds_type (HsForAllTy _ tv_names ctxt ty)
533 = tcTyVarBndrs tv_names $ \ tyvars -> do
534 theta <- mapM dsHsLPred (unLoc ctxt)
536 return (mkSigmaTy tyvars theta tau)
538 ds_type (HsSpliceTy {}) = panic "ds_type: HsSpliceTy"
540 ds_type (HsDocTy ty _) -- Remove the doc comment
543 dsHsTypes :: [LHsType Name] -> TcM [Type]
544 dsHsTypes arg_tys = mapM dsHsType arg_tys
547 Help functions for type applications
548 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
551 ds_app :: HsType Name -> [LHsType Name] -> TcM Type
552 ds_app (HsAppTy ty1 ty2) tys
553 = ds_app (unLoc ty1) (ty2:tys)
556 arg_tys <- dsHsTypes tys
558 HsTyVar fun -> ds_var_app fun arg_tys
559 _ -> do fun_ty <- ds_type ty
560 return (mkAppTys fun_ty arg_tys)
562 ds_var_app :: Name -> [Type] -> TcM Type
563 ds_var_app name arg_tys = do
564 thing <- tcLookup name
566 ATyVar _ ty -> return (mkAppTys ty arg_tys)
567 AGlobal (ATyCon tc) -> return (mkTyConApp tc arg_tys)
568 _ -> wrongThingErr "type" thing name
576 dsHsLPred :: LHsPred Name -> TcM PredType
577 dsHsLPred pred = dsHsPred (unLoc pred)
579 dsHsPred :: HsPred Name -> TcM PredType
580 dsHsPred (HsClassP class_name tys)
581 = do { arg_tys <- dsHsTypes tys
582 ; clas <- tcLookupClass class_name
583 ; return (ClassP clas arg_tys)
585 dsHsPred (HsEqualP ty1 ty2)
586 = do { arg_ty1 <- dsHsType ty1
587 ; arg_ty2 <- dsHsType ty2
588 ; return (EqPred arg_ty1 arg_ty2)
590 dsHsPred (HsIParam name ty)
591 = do { arg_ty <- dsHsType ty
592 ; return (IParam name arg_ty)
596 GADT constructor signatures
599 tcLHsConResTy :: LHsType Name -> TcM (TyCon, [TcType])
600 tcLHsConResTy (L span res_ty)
602 case get_args res_ty [] of
603 (HsTyVar tc_name, args)
604 -> do { args' <- mapM dsHsType args
605 ; thing <- tcLookup tc_name
607 AGlobal (ATyCon tc) -> return (tc, args')
608 _ -> failWithTc (badGadtDecl res_ty) }
609 _ -> failWithTc (badGadtDecl res_ty)
611 -- We can't call dsHsType on res_ty, and then do tcSplitTyConApp_maybe
612 -- because that causes a black hole, and for good reason. Building
613 -- the type means expanding type synonyms, and we can't do that
614 -- inside the "knot". So we have to work by steam.
615 get_args (HsAppTy (L _ fun) arg) args = get_args fun (arg:args)
616 get_args (HsParTy (L _ ty)) args = get_args ty args
617 get_args (HsOpTy ty1 (L _ tc) ty2) args = (HsTyVar tc, ty1:ty2:args)
618 get_args ty args = (ty, args)
620 badGadtDecl :: HsType Name -> SDoc
622 = hang (ptext (sLit "Malformed constructor result type:"))
625 typeCtxt :: HsType Name -> SDoc
626 typeCtxt ty = ptext (sLit "In the type") <+> quotes (ppr ty)
629 %************************************************************************
631 Type-variable binders
633 %************************************************************************
637 kcHsTyVars :: [LHsTyVarBndr Name]
638 -> ([LHsTyVarBndr Name] -> TcM r) -- These binders are kind-annotated
639 -- They scope over the thing inside
641 kcHsTyVars tvs thing_inside = do
642 bndrs <- mapM (wrapLocM kcHsTyVar) tvs
643 tcExtendKindEnvTvs bndrs (thing_inside bndrs)
645 kcHsTyVar :: HsTyVarBndr Name -> TcM (HsTyVarBndr Name)
646 -- Return a *kind-annotated* binder, and a tyvar with a mutable kind in it
647 kcHsTyVar (UserTyVar name) = KindedTyVar name <$> newKindVar
648 kcHsTyVar (KindedTyVar name kind) = return (KindedTyVar name kind)
651 tcTyVarBndrs :: [LHsTyVarBndr Name] -- Kind-annotated binders, which need kind-zonking
652 -> ([TyVar] -> TcM r)
654 -- Used when type-checking types/classes/type-decls
655 -- Brings into scope immutable TyVars, not mutable ones that require later zonking
656 tcTyVarBndrs bndrs thing_inside = do
657 tyvars <- mapM (zonk . unLoc) bndrs
658 tcExtendTyVarEnv tyvars (thing_inside tyvars)
660 zonk (KindedTyVar name kind) = do { kind' <- zonkTcKindToKind kind
661 ; return (mkTyVar name kind') }
662 zonk (UserTyVar name) = WARN( True, ptext (sLit "Un-kinded tyvar") <+> ppr name )
663 return (mkTyVar name liftedTypeKind)
665 -----------------------------------
666 tcDataKindSig :: Maybe Kind -> TcM [TyVar]
667 -- GADT decls can have a (perhaps partial) kind signature
668 -- e.g. data T :: * -> * -> * where ...
669 -- This function makes up suitable (kinded) type variables for
670 -- the argument kinds, and checks that the result kind is indeed *.
671 -- We use it also to make up argument type variables for for data instances.
672 tcDataKindSig Nothing = return []
673 tcDataKindSig (Just kind)
674 = do { checkTc (isLiftedTypeKind res_kind) (badKindSig kind)
675 ; span <- getSrcSpanM
676 ; us <- newUniqueSupply
677 ; let uniqs = uniqsFromSupply us
678 ; return [ mk_tv span uniq str kind
679 | ((kind, str), uniq) <- arg_kinds `zip` names `zip` uniqs ] }
681 (arg_kinds, res_kind) = splitKindFunTys kind
682 mk_tv loc uniq str kind = mkTyVar name kind
684 name = mkInternalName uniq occ loc
685 occ = mkOccName tvName str
687 names :: [String] -- a,b,c...aa,ab,ac etc
688 names = [ c:cs | cs <- "" : names, c <- ['a'..'z'] ]
690 badKindSig :: Kind -> SDoc
692 = hang (ptext (sLit "Kind signature on data type declaration has non-* return kind"))
697 %************************************************************************
699 Scoped type variables
701 %************************************************************************
704 tcAddScopedTyVars is used for scoped type variables added by pattern
706 e.g. \ ((x::a), (y::a)) -> x+y
707 They never have explicit kinds (because this is source-code only)
708 They are mutable (because they can get bound to a more specific type).
710 Usually we kind-infer and expand type splices, and then
711 tupecheck/desugar the type. That doesn't work well for scoped type
712 variables, because they scope left-right in patterns. (e.g. in the
713 example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
715 The current not-very-good plan is to
716 * find all the types in the patterns
717 * find their free tyvars
719 * bring the kinded type vars into scope
720 * BUT throw away the kind-checked type
721 (we'll kind-check it again when we type-check the pattern)
723 This is bad because throwing away the kind checked type throws away
724 its splices. But too bad for now. [July 03]
727 We no longer specify that these type variables must be univerally
728 quantified (lots of email on the subject). If you want to put that
730 a) Do a checkSigTyVars after thing_inside
731 b) More insidiously, don't pass in expected_ty, else
732 we unify with it too early and checkSigTyVars barfs
733 Instead you have to pass in a fresh ty var, and unify
734 it with expected_ty afterwards
737 tcHsPatSigType :: UserTypeCtxt
738 -> LHsType Name -- The type signature
739 -> TcM ([TyVar], -- Newly in-scope type variables
740 Type) -- The signature
741 -- Used for type-checking type signatures in
742 -- (a) patterns e.g f (x::Int) = e
743 -- (b) result signatures e.g. g x :: Int = e
744 -- (c) RULE forall bndrs e.g. forall (x::Int). f x = x
746 tcHsPatSigType ctxt hs_ty
747 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
748 do { -- Find the type variables that are mentioned in the type
749 -- but not already in scope. These are the ones that
750 -- should be bound by the pattern signature
751 in_scope <- getInLocalScope
752 ; let span = getLoc hs_ty
753 sig_tvs = [ L span (UserTyVar n)
754 | n <- nameSetToList (extractHsTyVars hs_ty),
757 ; (tyvars, sig_ty) <- tcHsQuantifiedType sig_tvs hs_ty
758 ; checkValidType ctxt sig_ty
759 ; return (tyvars, sig_ty)
762 tcPatSig :: UserTypeCtxt
765 -> TcM (TcType, -- The type to use for "inside" the signature
766 [(Name,TcType)]) -- The new bit of type environment, binding
767 -- the scoped type variables
768 tcPatSig ctxt sig res_ty
769 = do { (sig_tvs, sig_ty) <- tcHsPatSigType ctxt sig
771 ; if null sig_tvs then do {
772 -- The type signature binds no type variables,
773 -- and hence is rigid, so use it to zap the res_ty
774 boxyUnify sig_ty res_ty
775 ; return (sig_ty, [])
778 -- Type signature binds at least one scoped type variable
780 -- A pattern binding cannot bind scoped type variables
781 -- The renamer fails with a name-out-of-scope error
782 -- if a pattern binding tries to bind a type variable,
783 -- So we just have an ASSERT here
784 ; let in_pat_bind = case ctxt of
785 BindPatSigCtxt -> True
787 ; ASSERT( not in_pat_bind || null sig_tvs ) return ()
789 -- Check that pat_ty is rigid
790 ; checkTc (isRigidTy res_ty) (wobblyPatSig sig_tvs)
792 -- Now match the pattern signature against res_ty
793 -- For convenience, and uniform-looking error messages
794 -- we do the matching by allocating meta type variables,
795 -- unifying, and reading out the results.
796 -- This is a strictly local operation.
797 ; box_tvs <- mapM tcInstBoxyTyVar sig_tvs
798 ; boxyUnify (substTyWith sig_tvs (mkTyVarTys box_tvs) sig_ty) res_ty
799 ; sig_tv_tys <- mapM readFilledBox box_tvs
801 -- Check that each is bound to a distinct type variable,
802 -- and one that is not already in scope
803 ; let tv_binds = map tyVarName sig_tvs `zip` sig_tv_tys
804 ; binds_in_scope <- getScopedTyVarBinds
805 ; check binds_in_scope tv_binds
808 ; return (res_ty, tv_binds)
811 check _ [] = return ()
812 check in_scope ((n,ty):rest) = do { check_one in_scope n ty
813 ; check ((n,ty):in_scope) rest }
815 check_one in_scope n ty
816 = do { checkTc (tcIsTyVarTy ty) (scopedNonVar n ty)
817 -- Must bind to a type variable
819 ; checkTc (null dups) (dupInScope n (head dups) ty)
820 -- Must not bind to the same type variable
821 -- as some other in-scope type variable
825 dups = [n' | (n',ty') <- in_scope, tcEqType ty' ty]
829 %************************************************************************
831 Scoped type variables
833 %************************************************************************
836 pprHsSigCtxt :: UserTypeCtxt -> LHsType Name -> SDoc
837 pprHsSigCtxt ctxt hs_ty = vcat [ ptext (sLit "In") <+> pprUserTypeCtxt ctxt <> colon,
838 nest 2 (pp_sig ctxt) ]
840 pp_sig (FunSigCtxt n) = pp_n_colon n
841 pp_sig (ConArgCtxt n) = pp_n_colon n
842 pp_sig (ForSigCtxt n) = pp_n_colon n
843 pp_sig _ = ppr (unLoc hs_ty)
845 pp_n_colon n = ppr n <+> dcolon <+> ppr (unLoc hs_ty)
847 wobblyPatSig :: [Var] -> SDoc
849 = hang (ptext (sLit "A pattern type signature cannot bind scoped type variables")
850 <+> pprQuotedList sig_tvs)
851 2 (ptext (sLit "unless the pattern has a rigid type context"))
853 scopedNonVar :: Name -> Type -> SDoc
855 = vcat [sep [ptext (sLit "The scoped type variable") <+> quotes (ppr n),
856 nest 2 (ptext (sLit "is bound to the type") <+> quotes (ppr ty))],
857 nest 2 (ptext (sLit "You can only bind scoped type variables to type variables"))]
859 dupInScope :: Name -> Name -> Type -> SDoc
861 = hang (ptext (sLit "The scoped type variables") <+> quotes (ppr n) <+> ptext (sLit "and") <+> quotes (ppr n'))
862 2 (vcat [ptext (sLit "are bound to the same type (variable)"),
863 ptext (sLit "Distinct scoped type variables must be distinct")])
865 wrongEqualityErr :: TcM (HsType Name, TcKind)
867 = failWithTc (text "Equality predicate used as a type")