2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcMonoType]{Typechecking user-specified @MonoTypes@}
8 tcHsSigType, tcHsDeriv,
12 kcHsTyVars, kcHsSigType, kcHsLiftedSigType,
13 kcCheckHsType, kcHsContext, kcHsType,
15 -- Typechecking kinded types
16 tcHsKindedContext, tcHsKindedType, tcHsBangType,
17 tcTyVarBndrs, dsHsType, tcLHsConSig, tcDataKindSig,
19 tcHsPatSigType, tcAddLetBoundTyVars,
21 TcSigInfo(..), mkTcSig,
25 #include "HsVersions.h"
27 import HsSyn ( HsType(..), LHsType, HsTyVarBndr(..), LHsTyVarBndr, HsBang,
28 LHsContext, HsPred(..), LHsPred, LHsBinds,
29 getBangStrictness, collectSigTysFromHsBinds )
30 import RnHsSyn ( extractHsTyVars )
32 import TcEnv ( tcExtendTyVarEnv, tcExtendKindEnv,
33 tcLookup, tcLookupClass, tcLookupTyCon,
34 TyThing(..), getInLocalScope, wrongThingErr
36 import TcMType ( newKindVar, tcSkolType, newMetaTyVar,
38 checkValidType, UserTypeCtxt(..), pprHsSigCtxt
40 import TcUnify ( unifyFunKind, checkExpectedKind )
41 import TcType ( Type, PredType(..), ThetaType,
42 SkolemInfo(SigSkol), MetaDetails(Flexi),
43 TcType, TcTyVar, TcKind, TcThetaType, TcTauType,
45 mkForAllTys, mkFunTys, tcEqType, isPredTy,
46 mkSigmaTy, mkPredTy, mkGenTyConApp, mkTyConApp, mkAppTys,
47 tcSplitFunTy_maybe, tcSplitForAllTys )
48 import Kind ( Kind, isLiftedTypeKind, liftedTypeKind, ubxTupleKind,
49 openTypeKind, argTypeKind, splitKindFunTys )
50 import Id ( idName, idType )
51 import Var ( TyVar, mkTyVar, tyVarKind )
52 import TyCon ( TyCon, tyConKind )
53 import Class ( Class, classTyCon )
54 import Name ( Name, mkInternalName )
55 import OccName ( mkOccName, tvName )
57 import PrelNames ( genUnitTyConName )
58 import Type ( deShadowTy )
59 import TysWiredIn ( mkListTy, mkPArrTy, mkTupleTy )
60 import Bag ( bagToList )
61 import BasicTypes ( Boxity(..) )
62 import SrcLoc ( Located(..), unLoc, noLoc, srcSpanStart )
63 import UniqSupply ( uniqsFromSupply )
69 ----------------------------
71 ----------------------------
73 Generally speaking we now type-check types in three phases
75 1. kcHsType: kind check the HsType
76 *includes* performing any TH type splices;
77 so it returns a translated, and kind-annotated, type
79 2. dsHsType: convert from HsType to Type:
81 expand type synonyms [mkGenTyApps]
82 hoist the foralls [tcHsType]
84 3. checkValidType: check the validity of the resulting type
86 Often these steps are done one after the other (tcHsSigType).
87 But in mutually recursive groups of type and class decls we do
88 1 kind-check the whole group
89 2 build TyCons/Classes in a knot-tied way
90 3 check the validity of types in the now-unknotted TyCons/Classes
92 For example, when we find
93 (forall a m. m a -> m a)
94 we bind a,m to kind varibles and kind-check (m a -> m a). This makes
95 a get kind *, and m get kind *->*. Now we typecheck (m a -> m a) in
96 an environment that binds a and m suitably.
98 The kind checker passed to tcHsTyVars needs to look at enough to
99 establish the kind of the tyvar:
100 * For a group of type and class decls, it's just the group, not
101 the rest of the program
102 * For a tyvar bound in a pattern type signature, its the types
103 mentioned in the other type signatures in that bunch of patterns
104 * For a tyvar bound in a RULE, it's the type signatures on other
105 universally quantified variables in the rule
107 Note that this may occasionally give surprising results. For example:
109 data T a b = MkT (a b)
111 Here we deduce a::*->*, b::*
112 But equally valid would be a::(*->*)-> *, b::*->*
117 Some of the validity check could in principle be done by the kind checker,
120 - During desugaring, we normalise by expanding type synonyms. Only
121 after this step can we check things like type-synonym saturation
122 e.g. type T k = k Int
124 Then (T S) is ok, because T is saturated; (T S) expands to (S Int);
125 and then S is saturated. This is a GHC extension.
127 - Similarly, also a GHC extension, we look through synonyms before complaining
128 about the form of a class or instance declaration
130 - Ambiguity checks involve functional dependencies, and it's easier to wait
131 until knots have been resolved before poking into them
133 Also, in a mutually recursive group of types, we can't look at the TyCon until we've
134 finished building the loop. So to keep things simple, we postpone most validity
135 checking until step (3).
139 During step (1) we might fault in a TyCon defined in another module, and it might
140 (via a loop) refer back to a TyCon defined in this module. So when we tie a big
141 knot around type declarations with ARecThing, so that the fault-in code can get
142 the TyCon being defined.
145 %************************************************************************
147 \subsection{Checking types}
149 %************************************************************************
152 tcHsSigType :: UserTypeCtxt -> LHsType Name -> TcM Type
153 -- Do kind checking, and hoist for-alls to the top
154 tcHsSigType ctxt hs_ty
155 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
156 do { kinded_ty <- kcTypeType hs_ty
157 ; ty <- tcHsKindedType kinded_ty
158 ; checkValidType ctxt ty
160 -- Used for the deriving(...) items
161 tcHsDeriv :: LHsType Name -> TcM ([TyVar], Class, [Type])
162 tcHsDeriv = addLocM (tc_hs_deriv [])
164 tc_hs_deriv tv_names (HsPredTy (HsClassP cls_name hs_tys))
165 = kcHsTyVars tv_names $ \ tv_names' ->
166 do { cls_kind <- kcClass cls_name
167 ; (tys, res_kind) <- kcApps cls_kind (ppr cls_name) hs_tys
168 ; tcTyVarBndrs tv_names' $ \ tyvars ->
169 do { arg_tys <- dsHsTypes tys
170 ; cls <- tcLookupClass cls_name
171 ; return (tyvars, cls, arg_tys) }}
173 tc_hs_deriv tv_names1 (HsForAllTy _ tv_names2 (L _ []) (L _ ty))
174 = -- Funny newtype deriving form
176 -- where C has arity 2. Hence can't use regular functions
177 tc_hs_deriv (tv_names1 ++ tv_names2) ty
180 = failWithTc (ptext SLIT("Illegal deriving item") <+> ppr other)
183 These functions are used during knot-tying in
184 type and class declarations, when we have to
185 separate kind-checking, desugaring, and validity checking
188 kcHsSigType, kcHsLiftedSigType :: LHsType Name -> TcM (LHsType Name)
189 -- Used for type signatures
190 kcHsSigType ty = kcTypeType ty
191 kcHsLiftedSigType ty = kcLiftedType ty
193 tcHsKindedType :: LHsType Name -> TcM Type
194 -- Don't do kind checking, nor validity checking,
195 -- but do hoist for-alls to the top
196 -- This is used in type and class decls, where kinding is
197 -- done in advance, and validity checking is done later
198 -- [Validity checking done later because of knot-tying issues.]
200 = do { ty <- dsHsType hs_ty
201 ; return (hoistForAllTys ty) }
203 tcHsBangType :: LHsType Name -> TcM Type
204 -- Permit a bang, but discard it
205 tcHsBangType (L span (HsBangTy b ty)) = tcHsKindedType ty
206 tcHsBangType ty = tcHsKindedType ty
208 tcHsKindedContext :: LHsContext Name -> TcM ThetaType
209 -- Used when we are expecting a ClassContext (i.e. no implicit params)
210 -- Does not do validity checking, like tcHsKindedType
211 tcHsKindedContext hs_theta = addLocM (mappM dsHsLPred) hs_theta
215 %************************************************************************
217 The main kind checker: kcHsType
219 %************************************************************************
221 First a couple of simple wrappers for kcHsType
224 ---------------------------
225 kcLiftedType :: LHsType Name -> TcM (LHsType Name)
226 -- The type ty must be a *lifted* *type*
227 kcLiftedType ty = kcCheckHsType ty liftedTypeKind
229 ---------------------------
230 kcTypeType :: LHsType Name -> TcM (LHsType Name)
231 -- The type ty must be a *type*, but it can be lifted or
232 -- unlifted or an unboxed tuple.
233 kcTypeType ty = kcCheckHsType ty openTypeKind
235 ---------------------------
236 kcCheckHsType :: LHsType Name -> TcKind -> TcM (LHsType Name)
237 -- Check that the type has the specified kind
238 -- Be sure to use checkExpectedKind, rather than simply unifying
239 -- with OpenTypeKind, because it gives better error messages
240 kcCheckHsType (L span ty) exp_kind
242 kc_hs_type ty `thenM` \ (ty', act_kind) ->
243 checkExpectedKind ty act_kind exp_kind `thenM_`
247 Here comes the main function
250 kcHsType :: LHsType Name -> TcM (LHsType Name, TcKind)
251 kcHsType ty = wrapLocFstM kc_hs_type ty
252 -- kcHsType *returns* the kind of the type, rather than taking an expected
253 -- kind as argument as tcExpr does.
255 -- (a) the kind of (->) is
256 -- forall bx1 bx2. Type bx1 -> Type bx2 -> Type Boxed
257 -- so we'd need to generate huge numbers of bx variables.
258 -- (b) kinds are so simple that the error messages are fine
260 -- The translated type has explicitly-kinded type-variable binders
262 kc_hs_type (HsParTy ty)
263 = kcHsType ty `thenM` \ (ty', kind) ->
264 returnM (HsParTy ty', kind)
266 kc_hs_type (HsTyVar name)
267 = kcTyVar name `thenM` \ kind ->
268 returnM (HsTyVar name, kind)
270 kc_hs_type (HsListTy ty)
271 = kcLiftedType ty `thenM` \ ty' ->
272 returnM (HsListTy ty', liftedTypeKind)
274 kc_hs_type (HsPArrTy ty)
275 = kcLiftedType ty `thenM` \ ty' ->
276 returnM (HsPArrTy ty', liftedTypeKind)
278 kc_hs_type (HsNumTy n)
279 = returnM (HsNumTy n, liftedTypeKind)
281 kc_hs_type (HsKindSig ty k)
282 = kcCheckHsType ty k `thenM` \ ty' ->
283 returnM (HsKindSig ty' k, k)
285 kc_hs_type (HsTupleTy Boxed tys)
286 = mappM kcLiftedType tys `thenM` \ tys' ->
287 returnM (HsTupleTy Boxed tys', liftedTypeKind)
289 kc_hs_type (HsTupleTy Unboxed tys)
290 = mappM kcTypeType tys `thenM` \ tys' ->
291 returnM (HsTupleTy Unboxed tys', ubxTupleKind)
293 kc_hs_type (HsFunTy ty1 ty2)
294 = kcCheckHsType ty1 argTypeKind `thenM` \ ty1' ->
295 kcTypeType ty2 `thenM` \ ty2' ->
296 returnM (HsFunTy ty1' ty2', liftedTypeKind)
298 kc_hs_type ty@(HsOpTy ty1 op ty2)
299 = addLocM kcTyVar op `thenM` \ op_kind ->
300 kcApps op_kind (ppr op) [ty1,ty2] `thenM` \ ([ty1',ty2'], res_kind) ->
301 returnM (HsOpTy ty1' op ty2', res_kind)
303 kc_hs_type ty@(HsAppTy ty1 ty2)
304 = kcHsType fun_ty `thenM` \ (fun_ty', fun_kind) ->
305 kcApps fun_kind (ppr fun_ty) arg_tys `thenM` \ ((arg_ty':arg_tys'), res_kind) ->
306 returnM (foldl mk_app (HsAppTy fun_ty' arg_ty') arg_tys', res_kind)
308 (fun_ty, arg_tys) = split ty1 [ty2]
309 split (L _ (HsAppTy f a)) as = split f (a:as)
311 mk_app fun arg = HsAppTy (noLoc fun) arg -- Add noLocs for inner nodes of
312 -- the application; they are never used
314 kc_hs_type (HsPredTy pred)
315 = kcHsPred pred `thenM` \ pred' ->
316 returnM (HsPredTy pred', liftedTypeKind)
318 kc_hs_type (HsForAllTy exp tv_names context ty)
319 = kcHsTyVars tv_names $ \ tv_names' ->
320 kcHsContext context `thenM` \ ctxt' ->
321 kcLiftedType ty `thenM` \ ty' ->
322 -- The body of a forall is usually a type, but in principle
323 -- there's no reason to prohibit *unlifted* types.
324 -- In fact, GHC can itself construct a function with an
325 -- unboxed tuple inside a for-all (via CPR analyis; see
326 -- typecheck/should_compile/tc170)
328 -- Still, that's only for internal interfaces, which aren't
329 -- kind-checked, so we only allow liftedTypeKind here
330 returnM (HsForAllTy exp tv_names' ctxt' ty', liftedTypeKind)
332 kc_hs_type (HsBangTy b ty)
333 = do { (ty', kind) <- kcHsType ty
334 ; return (HsBangTy b ty', kind) }
336 kc_hs_type ty@(HsSpliceTy _)
337 = failWithTc (ptext SLIT("Unexpected type splice:") <+> ppr ty)
340 ---------------------------
341 kcApps :: TcKind -- Function kind
343 -> [LHsType Name] -- Arg types
344 -> TcM ([LHsType Name], TcKind) -- Kind-checked args
345 kcApps fun_kind ppr_fun args
346 = split_fk fun_kind (length args) `thenM` \ (arg_kinds, res_kind) ->
347 zipWithM kc_arg args arg_kinds `thenM` \ args' ->
348 returnM (args', res_kind)
350 split_fk fk 0 = returnM ([], fk)
351 split_fk fk n = unifyFunKind fk `thenM` \ mb_fk ->
353 Nothing -> failWithTc too_many_args
354 Just (ak,fk') -> split_fk fk' (n-1) `thenM` \ (aks, rk) ->
357 kc_arg arg arg_kind = kcCheckHsType arg arg_kind
359 too_many_args = ptext SLIT("Kind error:") <+> quotes ppr_fun <+>
360 ptext SLIT("is applied to too many type arguments")
362 ---------------------------
363 kcHsContext :: LHsContext Name -> TcM (LHsContext Name)
364 kcHsContext ctxt = wrapLocM (mappM kcHsLPred) ctxt
366 kcHsLPred :: LHsPred Name -> TcM (LHsPred Name)
367 kcHsLPred = wrapLocM kcHsPred
369 kcHsPred :: HsPred Name -> TcM (HsPred Name)
370 kcHsPred pred -- Checks that the result is of kind liftedType
371 = kc_pred pred `thenM` \ (pred', kind) ->
372 checkExpectedKind pred kind liftedTypeKind `thenM_`
375 ---------------------------
376 kc_pred :: HsPred Name -> TcM (HsPred Name, TcKind)
377 -- Does *not* check for a saturated
378 -- application (reason: used from TcDeriv)
379 kc_pred pred@(HsIParam name ty)
380 = kcHsType ty `thenM` \ (ty', kind) ->
381 returnM (HsIParam name ty', kind)
383 kc_pred pred@(HsClassP cls tys)
384 = kcClass cls `thenM` \ kind ->
385 kcApps kind (ppr cls) tys `thenM` \ (tys', res_kind) ->
386 returnM (HsClassP cls tys', res_kind)
388 ---------------------------
389 kcTyVar :: Name -> TcM TcKind
390 kcTyVar name -- Could be a tyvar or a tycon
391 = traceTc (text "lk1" <+> ppr name) `thenM_`
392 tcLookup name `thenM` \ thing ->
393 traceTc (text "lk2" <+> ppr name <+> ppr thing) `thenM_`
395 ATyVar tv _ -> returnM (tyVarKind tv)
396 AThing kind -> returnM kind
397 AGlobal (ATyCon tc) -> returnM (tyConKind tc)
398 other -> wrongThingErr "type" thing name
400 kcClass :: Name -> TcM TcKind
401 kcClass cls -- Must be a class
402 = tcLookup cls `thenM` \ thing ->
404 AThing kind -> returnM kind
405 AGlobal (AClass cls) -> returnM (tyConKind (classTyCon cls))
406 other -> wrongThingErr "class" thing cls
410 %************************************************************************
414 %************************************************************************
418 * Transforms from HsType to Type
421 It cannot fail, and does no validity checking, except for
422 structural matters, such as spurious ! annotations.
425 dsHsType :: LHsType Name -> TcM Type
426 -- All HsTyVarBndrs in the intput type are kind-annotated
427 dsHsType ty = ds_type (unLoc ty)
429 ds_type ty@(HsTyVar name)
432 ds_type (HsParTy ty) -- Remove the parentheses markers
435 ds_type ty@(HsBangTy _ _) -- No bangs should be here
436 = failWithTc (ptext SLIT("Unexpected strictness annotation:") <+> ppr ty)
438 ds_type (HsKindSig ty k)
439 = dsHsType ty -- Kind checking done already
441 ds_type (HsListTy ty)
442 = dsHsType ty `thenM` \ tau_ty ->
443 returnM (mkListTy tau_ty)
445 ds_type (HsPArrTy ty)
446 = dsHsType ty `thenM` \ tau_ty ->
447 returnM (mkPArrTy tau_ty)
449 ds_type (HsTupleTy boxity tys)
450 = dsHsTypes tys `thenM` \ tau_tys ->
451 returnM (mkTupleTy boxity (length tys) tau_tys)
453 ds_type (HsFunTy ty1 ty2)
454 = dsHsType ty1 `thenM` \ tau_ty1 ->
455 dsHsType ty2 `thenM` \ tau_ty2 ->
456 returnM (mkFunTy tau_ty1 tau_ty2)
458 ds_type (HsOpTy ty1 (L span op) ty2)
459 = dsHsType ty1 `thenM` \ tau_ty1 ->
460 dsHsType ty2 `thenM` \ tau_ty2 ->
461 setSrcSpan span (ds_var_app op [tau_ty1,tau_ty2])
465 tcLookupTyCon genUnitTyConName `thenM` \ tc ->
466 returnM (mkTyConApp tc [])
468 ds_type ty@(HsAppTy _ _)
471 ds_type (HsPredTy pred)
472 = dsHsPred pred `thenM` \ pred' ->
473 returnM (mkPredTy pred')
475 ds_type full_ty@(HsForAllTy exp tv_names ctxt ty)
476 = tcTyVarBndrs tv_names $ \ tyvars ->
477 mappM dsHsLPred (unLoc ctxt) `thenM` \ theta ->
478 dsHsType ty `thenM` \ tau ->
479 returnM (mkSigmaTy tyvars theta tau)
481 dsHsTypes arg_tys = mappM dsHsType arg_tys
484 Help functions for type applications
485 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
488 ds_app :: HsType Name -> [LHsType Name] -> TcM Type
489 ds_app (HsAppTy ty1 ty2) tys
490 = ds_app (unLoc ty1) (ty2:tys)
493 = dsHsTypes tys `thenM` \ arg_tys ->
495 HsTyVar fun -> ds_var_app fun arg_tys
496 other -> ds_type ty `thenM` \ fun_ty ->
497 returnM (mkAppTys fun_ty arg_tys)
499 ds_var_app :: Name -> [Type] -> TcM Type
500 ds_var_app name arg_tys
501 = tcLookup name `thenM` \ thing ->
503 ATyVar _ ty -> returnM (mkAppTys ty arg_tys)
504 AGlobal (ATyCon tc) -> returnM (mkGenTyConApp tc arg_tys)
505 -- AThing _ -> tcLookupTyCon name `thenM` \ tc ->
506 -- returnM (mkGenTyConApp tc arg_tys)
507 other -> pprPanic "ds_app_type" (ppr name <+> ppr arg_tys)
515 dsHsLPred :: LHsPred Name -> TcM PredType
516 dsHsLPred pred = dsHsPred (unLoc pred)
518 dsHsPred pred@(HsClassP class_name tys)
519 = dsHsTypes tys `thenM` \ arg_tys ->
520 tcLookupClass class_name `thenM` \ clas ->
521 returnM (ClassP clas arg_tys)
523 dsHsPred (HsIParam name ty)
524 = dsHsType ty `thenM` \ arg_ty ->
525 returnM (IParam name arg_ty)
528 GADT constructor signatures
531 tcLHsConSig :: LHsType Name
532 -> TcM ([TcTyVar], TcThetaType,
535 -- Take apart the type signature for a data constructor
536 -- The difference is that there can be bangs at the top of
537 -- the argument types, and kind-checking is the right place to check
538 tcLHsConSig sig@(L span (HsForAllTy exp tv_names ctxt ty))
540 addErrCtxt (gadtSigCtxt sig) $
541 tcTyVarBndrs tv_names $ \ tyvars ->
542 do { theta <- mappM dsHsLPred (unLoc ctxt)
543 ; (bangs, arg_tys, tc, res_tys) <- tc_con_sig_tau ty
544 ; return (tyvars, theta, bangs, arg_tys, tc, res_tys) }
546 = do { (bangs, arg_tys, tc, res_tys) <- tc_con_sig_tau ty
547 ; return ([], [], bangs, arg_tys, tc, res_tys) }
550 tc_con_sig_tau (L _ (HsFunTy arg ty))
551 = do { (bangs, arg_tys, tc, res_tys) <- tc_con_sig_tau ty
552 ; arg_ty <- tcHsBangType arg
553 ; return (getBangStrictness arg : bangs,
554 arg_ty : arg_tys, tc, res_tys) }
557 = do { (tc, res_tys) <- tc_con_res ty []
558 ; return ([], [], tc, res_tys) }
561 tc_con_res (L _ (HsAppTy fun res_ty)) res_tys
562 = do { res_ty' <- dsHsType res_ty
563 ; tc_con_res fun (res_ty' : res_tys) }
565 tc_con_res ty@(L _ (HsTyVar name)) res_tys
566 = do { thing <- tcLookup name
568 AGlobal (ATyCon tc) -> return (tc, res_tys)
569 other -> failWithTc (badGadtDecl ty)
572 tc_con_res ty _ = failWithTc (badGadtDecl ty)
575 = hang (ptext SLIT("In the signature of a data constructor:"))
578 = hang (ptext SLIT("Malformed constructor signature:"))
582 %************************************************************************
584 Type-variable binders
586 %************************************************************************
590 kcHsTyVars :: [LHsTyVarBndr Name]
591 -> ([LHsTyVarBndr Name] -> TcM r) -- These binders are kind-annotated
592 -- They scope over the thing inside
594 kcHsTyVars tvs thing_inside
595 = mappM (wrapLocM kcHsTyVar) tvs `thenM` \ bndrs ->
596 tcExtendKindEnv [(n,k) | L _ (KindedTyVar n k) <- bndrs]
599 kcHsTyVar :: HsTyVarBndr Name -> TcM (HsTyVarBndr Name)
600 -- Return a *kind-annotated* binder, and a tyvar with a mutable kind in it
601 kcHsTyVar (UserTyVar name) = newKindVar `thenM` \ kind ->
602 returnM (KindedTyVar name kind)
603 kcHsTyVar (KindedTyVar name kind) = returnM (KindedTyVar name kind)
606 tcTyVarBndrs :: [LHsTyVarBndr Name] -- Kind-annotated binders, which need kind-zonking
607 -> ([TyVar] -> TcM r)
609 -- Used when type-checking types/classes/type-decls
610 -- Brings into scope immutable TyVars, not mutable ones that require later zonking
611 tcTyVarBndrs bndrs thing_inside
612 = mapM (zonk . unLoc) bndrs `thenM` \ tyvars ->
613 tcExtendTyVarEnv tyvars (thing_inside tyvars)
615 zonk (KindedTyVar name kind) = zonkTcKindToKind kind `thenM` \ kind' ->
616 returnM (mkTyVar name kind')
617 zonk (UserTyVar name) = pprTrace "Un-kinded tyvar" (ppr name) $
618 returnM (mkTyVar name liftedTypeKind)
620 -----------------------------------
621 tcDataKindSig :: Maybe Kind -> TcM [TyVar]
622 -- GADT decls can have a (perhpas partial) kind signature
623 -- e.g. data T :: * -> * -> * where ...
624 -- This function makes up suitable (kinded) type variables for
625 -- the argument kinds, and checks that the result kind is indeed *
626 tcDataKindSig Nothing = return []
627 tcDataKindSig (Just kind)
628 = do { checkTc (isLiftedTypeKind res_kind) (badKindSig kind)
629 ; span <- getSrcSpanM
630 ; us <- newUniqueSupply
631 ; let loc = srcSpanStart span
632 uniqs = uniqsFromSupply us
633 ; return [ mk_tv loc uniq str kind
634 | ((kind, str), uniq) <- arg_kinds `zip` names `zip` uniqs ] }
636 (arg_kinds, res_kind) = splitKindFunTys kind
637 mk_tv loc uniq str kind = mkTyVar name kind
639 name = mkInternalName uniq occ loc
640 occ = mkOccName tvName str
642 names :: [String] -- a,b,c...aa,ab,ac etc
643 names = [ c:cs | cs <- "" : names, c <- ['a'..'z'] ]
645 badKindSig :: Kind -> SDoc
647 = hang (ptext SLIT("Kind signature on data type declaration has non-* return kind"))
652 %************************************************************************
654 Scoped type variables
656 %************************************************************************
659 tcAddScopedTyVars is used for scoped type variables added by pattern
661 e.g. \ ((x::a), (y::a)) -> x+y
662 They never have explicit kinds (because this is source-code only)
663 They are mutable (because they can get bound to a more specific type).
665 Usually we kind-infer and expand type splices, and then
666 tupecheck/desugar the type. That doesn't work well for scoped type
667 variables, because they scope left-right in patterns. (e.g. in the
668 example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
670 The current not-very-good plan is to
671 * find all the types in the patterns
672 * find their free tyvars
674 * bring the kinded type vars into scope
675 * BUT throw away the kind-checked type
676 (we'll kind-check it again when we type-check the pattern)
678 This is bad because throwing away the kind checked type throws away
679 its splices. But too bad for now. [July 03]
682 We no longer specify that these type variables must be univerally
683 quantified (lots of email on the subject). If you want to put that
685 a) Do a checkSigTyVars after thing_inside
686 b) More insidiously, don't pass in expected_ty, else
687 we unify with it too early and checkSigTyVars barfs
688 Instead you have to pass in a fresh ty var, and unify
689 it with expected_ty afterwards
692 tcPatSigBndrs :: LHsType Name
693 -> TcM ([TcTyVar], -- Brought into scope
694 LHsType Name) -- Kinded, but not yet desugared
697 = do { in_scope <- getInLocalScope
698 ; span <- getSrcSpanM
699 ; let sig_tvs = [ L span (UserTyVar n)
700 | n <- nameSetToList (extractHsTyVars hs_ty),
702 -- The tyvars we want are the free type variables of
703 -- the type that are not already in scope
705 -- Behave like kcHsType on a ForAll type
706 -- i.e. make kinded tyvars with mutable kinds,
707 -- and kind-check the enclosed types
708 ; (kinded_tvs, kinded_ty) <- kcHsTyVars sig_tvs $ \ kinded_tvs -> do
709 { kinded_ty <- kcTypeType hs_ty
710 ; return (kinded_tvs, kinded_ty) }
712 -- Zonk the mutable kinds and bring the tyvars into scope
713 -- Just like the call to tcTyVarBndrs in ds_type (HsForAllTy case),
714 -- except that it brings *meta* tyvars into scope, not regular ones
716 -- [Out of date, but perhaps should be resurrected]
717 -- Furthermore, the tyvars are PatSigTvs, which means that we get better
718 -- error messages when type variables escape:
719 -- Inferred type is less polymorphic than expected
720 -- Quantified type variable `t' escapes
721 -- It is mentioned in the environment:
722 -- t is bound by the pattern type signature at tcfail103.hs:6
723 ; tyvars <- mapM (zonk . unLoc) kinded_tvs
724 ; return (tyvars, kinded_ty) }
726 zonk (KindedTyVar name kind) = zonkTcKindToKind kind `thenM` \ kind' ->
727 newMetaTyVar name kind' Flexi
728 -- Scoped type variables are bound to a *type*, hence Flexi
729 zonk (UserTyVar name) = pprTrace "Un-kinded tyvar" (ppr name) $
730 returnM (mkTyVar name liftedTypeKind)
732 tcHsPatSigType :: UserTypeCtxt
733 -> LHsType Name -- The type signature
734 -> TcM ([TcTyVar], -- Newly in-scope type variables
735 TcType) -- The signature
737 tcHsPatSigType ctxt hs_ty
738 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
739 do { (tyvars, kinded_ty) <- tcPatSigBndrs hs_ty
741 -- Complete processing of the type, and check its validity
742 ; tcExtendTyVarEnv tyvars $ do
743 { sig_ty <- tcHsKindedType kinded_ty
744 ; checkValidType ctxt sig_ty
745 ; return (tyvars, sig_ty) }
748 tcAddLetBoundTyVars :: LHsBinds Name -> TcM a -> TcM a
749 -- Turgid funciton, used for type variables bound by the patterns of a let binding
751 tcAddLetBoundTyVars binds thing_inside
752 = go (collectSigTysFromHsBinds (bagToList binds)) thing_inside
754 go [] thing_inside = thing_inside
755 go (hs_ty:hs_tys) thing_inside
756 = do { (tyvars, _kinded_ty) <- tcPatSigBndrs hs_ty
757 ; tcExtendTyVarEnv tyvars (go hs_tys thing_inside) }
761 %************************************************************************
763 \subsection{Signatures}
765 %************************************************************************
767 @tcSigs@ checks the signatures for validity, and returns a list of
768 {\em freshly-instantiated} signatures. That is, the types are already
769 split up, and have fresh type variables installed. All non-type-signature
770 "RenamedSigs" are ignored.
772 The @TcSigInfo@ contains @TcTypes@ because they are unified with
773 the variable's type, and after that checked to see whether they've
779 sig_id :: TcId, -- *Polymorphic* binder for this value...
780 sig_tvs :: [TcTyVar], -- tyvars
781 sig_theta :: TcThetaType, -- theta
782 sig_tau :: TcTauType, -- tau
783 sig_loc :: InstLoc -- The location of the signature
786 type TcSigFun = Name -> Maybe TcSigInfo
788 instance Outputable TcSigInfo where
789 ppr (TcSigInfo { sig_id = id, sig_tvs = tyvars, sig_theta = theta, sig_tau = tau})
790 = ppr id <+> ptext SLIT("::") <+> ppr tyvars <+> ppr theta <+> ptext SLIT("=>") <+> ppr tau
792 lookupSig :: [TcSigInfo] -> TcSigFun -- Search for a particular signature
793 lookupSig [] name = Nothing
794 lookupSig (sig : sigs) name
795 | name == idName (sig_id sig) = Just sig
796 | otherwise = lookupSig sigs name
798 mkTcSig :: TcId -> TcM TcSigInfo
800 = -- Instantiate this type
801 -- It's important to do this even though in the error-free case
802 -- we could just split the sigma_tc_ty (since the tyvars don't
803 -- unified with anything). But in the case of an error, when
804 -- the tyvars *do* get unified with something, we want to carry on
805 -- typechecking the rest of the program with the function bound
806 -- to a pristine type, namely sigma_tc_ty
807 do { let rigid_info = SigSkol (idName poly_id)
808 ; (tyvars', theta', tau') <- tcSkolType rigid_info (idType poly_id)
809 ; loc <- getInstLoc (SigOrigin rigid_info)
810 ; return (TcSigInfo { sig_id = poly_id, sig_tvs = tyvars',
811 sig_theta = theta', sig_tau = tau', sig_loc = loc }) }
815 %************************************************************************
817 \subsection{Errors and contexts}
819 %************************************************************************
823 hoistForAllTys :: Type -> Type
824 -- Used for user-written type signatures only
825 -- Move all the foralls and constraints to the top
826 -- e.g. T -> forall a. a ==> forall a. T -> a
827 -- T -> (?x::Int) -> Int ==> (?x::Int) -> T -> Int
829 -- Also: eliminate duplicate constraints. These can show up
830 -- when hoisting constraints, notably implicit parameters.
832 -- We want to 'look through' type synonyms when doing this
833 -- so it's better done on the Type than the HsType
837 no_shadow_ty = deShadowTy ty
838 -- Running over ty with an empty substitution gives it the
839 -- no-shadowing property. This is important. For example:
840 -- type Foo r = forall a. a -> r
841 -- foo :: Foo (Foo ())
842 -- Here the hoisting should give
843 -- foo :: forall a a1. a -> a1 -> ()
845 -- What about type vars that are lexically in scope in the envt?
846 -- We simply rely on them having a different unique to any
847 -- binder in 'ty'. Otherwise we'd have to slurp the in-scope-tyvars
848 -- out of the envt, which is boring and (I think) not necessary.
850 case hoist no_shadow_ty of
851 (tvs, theta, body) -> mkForAllTys tvs (mkFunTys (nubBy tcEqType theta) body)
852 -- The 'nubBy' eliminates duplicate constraints,
853 -- notably implicit parameters
856 | (tvs1, body_ty) <- tcSplitForAllTys ty,
858 = case hoist body_ty of
859 (tvs2,theta,tau) -> (tvs1 ++ tvs2, theta, tau)
861 | Just (arg, res) <- tcSplitFunTy_maybe ty
863 arg' = hoistForAllTys arg -- Don't forget to apply hoist recursively
864 in -- to the argument type
865 if (isPredTy arg') then
867 (tvs,theta,tau) -> (tvs, arg':theta, tau)
870 (tvs,theta,tau) -> (tvs, theta, mkFunTy arg' tau)
872 | otherwise = ([], [], ty)