2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcMonoType]{Typechecking user-specified @MonoTypes@}
7 module TcMonoType ( tcHsSigType, tcHsType, tcIfaceType, tcHsTheta, tcHsPred,
11 kcHsTyVar, kcHsTyVars, mkTyClTyVars,
12 kcHsType, kcHsSigType, kcHsSigTypes,
13 kcHsLiftedSigType, kcHsContext,
14 tcAddScopedTyVars, tcHsTyVars, mkImmutTyVars,
16 TcSigInfo(..), tcTySig, mkTcSig, maybeSig
19 #include "HsVersions.h"
21 import HsSyn ( HsType(..), HsTyVarBndr(..),
22 Sig(..), HsPred(..), pprParendHsType, HsTupCon(..), hsTyVarNames )
23 import RnHsSyn ( RenamedHsType, RenamedHsPred, RenamedContext, RenamedSig, extractHsTyVars )
24 import TcHsSyn ( TcId )
27 import TcEnv ( tcExtendTyVarEnv, tcLookup, tcLookupGlobal,
29 TyThing(..), TcTyThing(..), tcExtendKindEnv
31 import TcMType ( newKindVar, zonkKindEnv, tcInstSigType,
32 checkValidType, UserTypeCtxt(..), pprUserTypeCtxt
34 import TcUnify ( unifyKind, unifyOpenTypeKind )
35 import TcType ( Type, Kind, SourceType(..), ThetaType, TyVarDetails(..),
36 TcTyVar, TcKind, TcThetaType, TcTauType,
37 mkTyVarTy, mkTyVarTys, mkFunTy, mkSynTy,
38 hoistForAllTys, zipFunTys,
39 mkSigmaTy, mkPredTy, mkTyConApp, mkAppTys,
40 liftedTypeKind, unliftedTypeKind, mkArrowKind,
41 mkArrowKinds, tcSplitFunTy_maybe
43 import Inst ( Inst, InstOrigin(..), newMethodWithGivenTy, instToId )
45 import Id ( mkLocalId, idName, idType )
46 import Var ( TyVar, mkTyVar, tyVarKind )
47 import ErrUtils ( Message )
48 import TyCon ( TyCon, isSynTyCon, tyConKind )
49 import Class ( classTyCon )
52 import TysWiredIn ( mkListTy, mkTupleTy, genUnitTyCon )
53 import BasicTypes ( Boxity(..) )
54 import SrcLoc ( SrcLoc )
55 import Util ( lengthIs )
61 %************************************************************************
63 \subsection{Checking types}
65 %************************************************************************
67 Generally speaking we now type-check types in three phases
69 1. Kind check the HsType [kcHsType]
70 2. Convert from HsType to Type, and hoist the foralls [tcHsType]
71 3. Check the validity of the resulting type [checkValidType]
73 Often these steps are done one after the othe (tcHsSigType).
74 But in mutually recursive groups of type and class decls we do
75 1 kind-check the whole group
76 2 build TyCons/Classes in a knot-tied wa
77 3 check the validity of types in the now-unknotted TyCons/Classes
80 tcHsSigType :: UserTypeCtxt -> RenamedHsType -> TcM Type
81 -- Do kind checking, and hoist for-alls to the top
82 tcHsSigType ctxt ty = tcAddErrCtxt (checkTypeCtxt ctxt ty) (
83 kcTypeType ty `thenTc_`
86 checkValidType ctxt ty' `thenTc_`
90 = vcat [ptext SLIT("In the type:") <+> ppr ty,
91 ptext SLIT("While checking") <+> pprUserTypeCtxt ctxt ]
93 tcHsType :: RenamedHsType -> TcM Type
94 -- Don't do kind checking, nor validity checking,
95 -- but do hoist for-alls to the top
96 -- This is used in type and class decls, where kinding is
97 -- done in advance, and validity checking is done later
98 -- [Validity checking done later because of knot-tying issues.]
99 tcHsType ty = tc_type ty `thenTc` \ ty' ->
100 returnTc (hoistForAllTys ty')
102 tcHsTheta :: RenamedContext -> TcM ThetaType
103 -- Used when we are expecting a ClassContext (i.e. no implicit params)
104 -- Does not do validity checking, like tcHsType
105 tcHsTheta hs_theta = mapTc tc_pred hs_theta
107 -- In interface files the type is already kinded,
108 -- and we definitely don't want to hoist for-alls.
109 -- Otherwise we'll change
110 -- dmfail :: forall m:(*->*) Monad m => forall a:* => String -> m a
112 -- dmfail :: forall m:(*->*) a:* Monad m => String -> m a
113 -- which definitely isn't right!
114 tcIfaceType ty = tc_type ty
118 %************************************************************************
120 \subsection{Kind checking}
122 %************************************************************************
126 When we come across the binding site for some type variables, we
127 proceed in two stages
129 1. Figure out what kind each tyvar has
131 2. Create suitably-kinded tyvars,
133 and typecheck the body
135 To do step 1, we proceed thus:
137 1a. Bind each type variable to a kind variable
138 1b. Apply the kind checker
139 1c. Zonk the resulting kinds
141 The kind checker is passed to tcHsTyVars as an argument.
143 For example, when we find
144 (forall a m. m a -> m a)
145 we bind a,m to kind varibles and kind-check (m a -> m a). This
146 makes a get kind *, and m get kind *->*. Now we typecheck (m a -> m a)
147 in an environment that binds a and m suitably.
149 The kind checker passed to tcHsTyVars needs to look at enough to
150 establish the kind of the tyvar:
151 * For a group of type and class decls, it's just the group, not
152 the rest of the program
153 * For a tyvar bound in a pattern type signature, its the types
154 mentioned in the other type signatures in that bunch of patterns
155 * For a tyvar bound in a RULE, it's the type signatures on other
156 universally quantified variables in the rule
158 Note that this may occasionally give surprising results. For example:
160 data T a b = MkT (a b)
162 Here we deduce a::*->*, b::*.
163 But equally valid would be
164 a::(*->*)-> *, b::*->*
167 -- tcHsTyVars is used for type variables in type signatures
168 -- e.g. forall a. a->a
169 -- They are immutable, because they scope only over the signature
170 -- They may or may not be explicitly-kinded
171 tcHsTyVars :: [HsTyVarBndr Name]
172 -> TcM a -- The kind checker
173 -> ([TyVar] -> TcM b)
176 tcHsTyVars [] kind_check thing_inside = thing_inside []
177 -- A useful short cut for a common case!
179 tcHsTyVars tv_names kind_check thing_inside
180 = kcHsTyVars tv_names `thenNF_Tc` \ tv_names_w_kinds ->
181 tcExtendKindEnv tv_names_w_kinds kind_check `thenTc_`
182 zonkKindEnv tv_names_w_kinds `thenNF_Tc` \ tvs_w_kinds ->
184 tyvars = mkImmutTyVars tvs_w_kinds
186 tcExtendTyVarEnv tyvars (thing_inside tyvars)
190 tcAddScopedTyVars :: [RenamedHsType] -> TcM a -> TcM a
191 -- tcAddScopedTyVars is used for scoped type variables
192 -- added by pattern type signatures
193 -- e.g. \ (x::a) (y::a) -> x+y
194 -- They never have explicit kinds (because this is source-code only)
195 -- They are mutable (because they can get bound to a more specific type)
197 -- Find the not-already-in-scope signature type variables,
198 -- kind-check them, and bring them into scope
200 -- We no longer specify that these type variables must be univerally
201 -- quantified (lots of email on the subject). If you want to put that
202 -- back in, you need to
203 -- a) Do a checkSigTyVars after thing_inside
204 -- b) More insidiously, don't pass in expected_ty, else
205 -- we unify with it too early and checkSigTyVars barfs
206 -- Instead you have to pass in a fresh ty var, and unify
207 -- it with expected_ty afterwards
208 tcAddScopedTyVars [] thing_inside
209 = thing_inside -- Quick get-out for the empty case
211 tcAddScopedTyVars sig_tys thing_inside
212 = tcGetEnv `thenNF_Tc` \ env ->
214 all_sig_tvs = foldr (unionNameSets . extractHsTyVars) emptyNameSet sig_tys
215 sig_tvs = filter not_in_scope (nameSetToList all_sig_tvs)
216 not_in_scope tv = not (tcInLocalScope env tv)
218 mapNF_Tc newNamedKindVar sig_tvs `thenTc` \ kind_env ->
219 tcExtendKindEnv kind_env (kcHsSigTypes sig_tys) `thenTc_`
220 zonkKindEnv kind_env `thenNF_Tc` \ tvs_w_kinds ->
221 listTc [ tcNewMutTyVar name kind PatSigTv
222 | (name, kind) <- tvs_w_kinds] `thenNF_Tc` \ tyvars ->
223 tcExtendTyVarEnv tyvars thing_inside
228 kcHsTyVar :: HsTyVarBndr name -> NF_TcM (name, TcKind)
229 kcHsTyVars :: [HsTyVarBndr name] -> NF_TcM [(name, TcKind)]
231 kcHsTyVar (UserTyVar name) = newNamedKindVar name
232 kcHsTyVar (IfaceTyVar name kind) = returnNF_Tc (name, kind)
234 kcHsTyVars tvs = mapNF_Tc kcHsTyVar tvs
236 newNamedKindVar name = newKindVar `thenNF_Tc` \ kind ->
237 returnNF_Tc (name, kind)
239 ---------------------------
240 kcLiftedType :: RenamedHsType -> TcM ()
241 -- The type ty must be a *lifted* *type*
243 = kcHsType ty `thenTc` \ kind ->
244 tcAddErrCtxt (typeKindCtxt ty) $
245 unifyKind liftedTypeKind kind
247 ---------------------------
248 kcTypeType :: RenamedHsType -> TcM ()
249 -- The type ty must be a *type*, but it can be lifted or unlifted.
251 = kcHsType ty `thenTc` \ kind ->
252 tcAddErrCtxt (typeKindCtxt ty) $
253 unifyOpenTypeKind kind
255 ---------------------------
256 kcHsSigType, kcHsLiftedSigType :: RenamedHsType -> TcM ()
257 -- Used for type signatures
258 kcHsSigType = kcTypeType
259 kcHsSigTypes tys = mapTc_ kcHsSigType tys
260 kcHsLiftedSigType = kcLiftedType
262 ---------------------------
263 kcHsType :: RenamedHsType -> TcM TcKind
264 kcHsType (HsTyVar name) = kcTyVar name
266 kcHsType (HsListTy ty)
267 = kcLiftedType ty `thenTc` \ tau_ty ->
268 returnTc liftedTypeKind
270 kcHsType (HsTupleTy (HsTupCon _ boxity _) tys)
271 = mapTc kcTypeType tys `thenTc_`
272 returnTc (case boxity of
273 Boxed -> liftedTypeKind
274 Unboxed -> unliftedTypeKind)
276 kcHsType (HsFunTy ty1 ty2)
277 = kcTypeType ty1 `thenTc_`
278 kcTypeType ty2 `thenTc_`
279 returnTc liftedTypeKind
281 kcHsType (HsNumTy _) -- The unit type for generics
282 = returnTc liftedTypeKind
284 kcHsType ty@(HsOpTy ty1 op ty2)
285 = kcTyVar op `thenTc` \ op_kind ->
286 kcHsType ty1 `thenTc` \ ty1_kind ->
287 kcHsType ty2 `thenTc` \ ty2_kind ->
288 tcAddErrCtxt (appKindCtxt (ppr ty)) $
289 kcAppKind op_kind ty1_kind `thenTc` \ op_kind' ->
290 kcAppKind op_kind' ty2_kind
292 kcHsType (HsPredTy pred)
293 = kcHsPred pred `thenTc_`
294 returnTc liftedTypeKind
296 kcHsType ty@(HsAppTy ty1 ty2)
297 = kcHsType ty1 `thenTc` \ tc_kind ->
298 kcHsType ty2 `thenTc` \ arg_kind ->
299 tcAddErrCtxt (appKindCtxt (ppr ty)) $
300 kcAppKind tc_kind arg_kind
302 kcHsType (HsForAllTy (Just tv_names) context ty)
303 = kcHsTyVars tv_names `thenNF_Tc` \ kind_env ->
304 tcExtendKindEnv kind_env $
305 kcHsContext context `thenTc_`
306 kcHsType ty `thenTc_`
307 returnTc liftedTypeKind
309 ---------------------------
310 kcAppKind fun_kind arg_kind
311 = case tcSplitFunTy_maybe fun_kind of
312 Just (arg_kind', res_kind)
313 -> unifyKind arg_kind arg_kind' `thenTc_`
316 Nothing -> newKindVar `thenNF_Tc` \ res_kind ->
317 unifyKind fun_kind (mkArrowKind arg_kind res_kind) `thenTc_`
321 ---------------------------
322 kc_pred :: RenamedHsPred -> TcM TcKind -- Does *not* check for a saturated
323 -- application (reason: used from TcDeriv)
324 kc_pred pred@(HsIParam name ty)
327 kc_pred pred@(HsClassP cls tys)
328 = kcClass cls `thenTc` \ kind ->
329 mapTc kcHsType tys `thenTc` \ arg_kinds ->
330 newKindVar `thenNF_Tc` \ kv ->
331 unifyKind kind (mkArrowKinds arg_kinds kv) `thenTc_`
334 ---------------------------
335 kcHsContext ctxt = mapTc_ kcHsPred ctxt
337 kcHsPred pred -- Checks that the result is of kind liftedType
338 = tcAddErrCtxt (appKindCtxt (ppr pred)) $
339 kc_pred pred `thenTc` \ kind ->
340 unifyKind liftedTypeKind kind `thenTc_`
344 ---------------------------
345 kcTyVar name -- Could be a tyvar or a tycon
346 = tcLookup name `thenTc` \ thing ->
348 AThing kind -> returnTc kind
349 ATyVar tv -> returnTc (tyVarKind tv)
350 AGlobal (ATyCon tc) -> returnTc (tyConKind tc)
351 other -> failWithTc (wrongThingErr "type" thing name)
353 kcClass cls -- Must be a class
354 = tcLookup cls `thenNF_Tc` \ thing ->
356 AThing kind -> returnTc kind
357 AGlobal (AClass cls) -> returnTc (tyConKind (classTyCon cls))
358 other -> failWithTc (wrongThingErr "class" thing cls)
361 %************************************************************************
365 %************************************************************************
367 tc_type, the main work horse
368 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
374 tc_type is used to typecheck the types in the RHS of data
375 constructors. In the case of recursive data types, that means that
376 the type constructors themselves are (partly) black holes. e.g.
378 data T a = MkT a [T a]
380 While typechecking the [T a] on the RHS, T itself is not yet fully
381 defined. That in turn places restrictions on what you can check in
382 tcHsType; if you poke on too much you get a black hole. I keep
383 forgetting this, hence this warning!
385 So tc_type does no validity-checking. Instead that's all done
386 by TcMType.checkValidType
388 --------------------------
389 *** END OF BIG WARNING ***
390 --------------------------
394 tc_type :: RenamedHsType -> TcM Type
396 tc_type ty@(HsTyVar name)
399 tc_type (HsListTy ty)
400 = tc_type ty `thenTc` \ tau_ty ->
401 returnTc (mkListTy tau_ty)
403 tc_type (HsTupleTy (HsTupCon _ boxity arity) tys)
404 = ASSERT( tys `lengthIs` arity )
405 tc_types tys `thenTc` \ tau_tys ->
406 returnTc (mkTupleTy boxity arity tau_tys)
408 tc_type (HsFunTy ty1 ty2)
409 = tc_type ty1 `thenTc` \ tau_ty1 ->
410 tc_type ty2 `thenTc` \ tau_ty2 ->
411 returnTc (mkFunTy tau_ty1 tau_ty2)
415 returnTc (mkTyConApp genUnitTyCon [])
417 tc_type (HsOpTy ty1 op ty2)
418 = tc_type ty1 `thenTc` \ tau_ty1 ->
419 tc_type ty2 `thenTc` \ tau_ty2 ->
420 tc_fun_type op [tau_ty1,tau_ty2]
422 tc_type (HsAppTy ty1 ty2) = tc_app ty1 [ty2]
424 tc_type (HsPredTy pred)
425 = tc_pred pred `thenTc` \ pred' ->
426 returnTc (mkPredTy pred')
428 tc_type full_ty@(HsForAllTy (Just tv_names) ctxt ty)
430 kind_check = kcHsContext ctxt `thenTc_` kcHsType ty
432 tcHsTyVars tv_names kind_check $ \ tyvars ->
433 mapTc tc_pred ctxt `thenTc` \ theta ->
434 tc_type ty `thenTc` \ tau ->
435 returnTc (mkSigmaTy tyvars theta tau)
437 tc_types arg_tys = mapTc tc_type arg_tys
440 Help functions for type applications
441 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
444 tc_app :: RenamedHsType -> [RenamedHsType] -> TcM Type
445 tc_app (HsAppTy ty1 ty2) tys
446 = tc_app ty1 (ty2:tys)
449 = tcAddErrCtxt (appKindCtxt pp_app) $
450 tc_types tys `thenTc` \ arg_tys ->
452 HsTyVar fun -> tc_fun_type fun arg_tys
453 other -> tc_type ty `thenTc` \ fun_ty ->
454 returnNF_Tc (mkAppTys fun_ty arg_tys)
456 pp_app = ppr ty <+> sep (map pprParendHsType tys)
458 -- (tc_fun_type ty arg_tys) returns (mkAppTys ty arg_tys)
459 -- But not quite; for synonyms it checks the correct arity, and builds a SynTy
460 -- hence the rather strange functionality.
462 tc_fun_type name arg_tys
463 = tcLookup name `thenTc` \ thing ->
465 ATyVar tv -> returnTc (mkAppTys (mkTyVarTy tv) arg_tys)
468 | isSynTyCon tc -> returnTc (mkSynTy tc arg_tys)
469 | otherwise -> returnTc (mkTyConApp tc arg_tys)
471 other -> failWithTc (wrongThingErr "type constructor" thing name)
478 tcHsPred pred = kc_pred pred `thenTc_` tc_pred pred
479 -- Is happy with a partial application, e.g. (ST s)
482 tc_pred assn@(HsClassP class_name tys)
483 = tcAddErrCtxt (appKindCtxt (ppr assn)) $
484 tc_types tys `thenTc` \ arg_tys ->
485 tcLookupGlobal class_name `thenTc` \ thing ->
487 AClass clas -> returnTc (ClassP clas arg_tys)
488 other -> failWithTc (wrongThingErr "class" (AGlobal thing) class_name)
490 tc_pred assn@(HsIParam name ty)
491 = tcAddErrCtxt (appKindCtxt (ppr assn)) $
492 tc_type ty `thenTc` \ arg_ty ->
493 returnTc (IParam name arg_ty)
498 %************************************************************************
500 \subsection{Type variables, with knot tying!}
502 %************************************************************************
505 mkImmutTyVars :: [(Name,Kind)] -> [TyVar]
506 mkImmutTyVars pairs = [mkTyVar name kind | (name, kind) <- pairs]
508 mkTyClTyVars :: Kind -- Kind of the tycon or class
509 -> [HsTyVarBndr Name]
511 mkTyClTyVars kind tyvar_names
512 = mkImmutTyVars tyvars_w_kinds
514 (tyvars_w_kinds, _) = zipFunTys (hsTyVarNames tyvar_names) kind
518 %************************************************************************
520 \subsection{Signatures}
522 %************************************************************************
524 @tcSigs@ checks the signatures for validity, and returns a list of
525 {\em freshly-instantiated} signatures. That is, the types are already
526 split up, and have fresh type variables installed. All non-type-signature
527 "RenamedSigs" are ignored.
529 The @TcSigInfo@ contains @TcTypes@ because they are unified with
530 the variable's type, and after that checked to see whether they've
536 Name -- N, the Name in corresponding binding
538 TcId -- *Polymorphic* binder for this value...
545 TcId -- *Monomorphic* binder for this value
546 -- Does *not* have name = N
549 [Inst] -- Empty if theta is null, or
550 -- (method mono_id) otherwise
552 SrcLoc -- Of the signature
554 instance Outputable TcSigInfo where
555 ppr (TySigInfo nm id tyvars theta tau _ inst loc) =
556 ppr nm <+> ptext SLIT("::") <+> ppr tyvars <+> ppr theta <+> ptext SLIT("=>") <+> ppr tau
558 maybeSig :: [TcSigInfo] -> Name -> Maybe (TcSigInfo)
559 -- Search for a particular signature
560 maybeSig [] name = Nothing
561 maybeSig (sig@(TySigInfo sig_name _ _ _ _ _ _ _) : sigs) name
562 | name == sig_name = Just sig
563 | otherwise = maybeSig sigs name
568 tcTySig :: RenamedSig -> TcM TcSigInfo
570 tcTySig (Sig v ty src_loc)
571 = tcAddSrcLoc src_loc $
572 tcHsSigType (FunSigCtxt v) ty `thenTc` \ sigma_tc_ty ->
573 mkTcSig (mkLocalId v sigma_tc_ty) src_loc `thenNF_Tc` \ sig ->
576 mkTcSig :: TcId -> SrcLoc -> NF_TcM TcSigInfo
577 mkTcSig poly_id src_loc
578 = -- Instantiate this type
579 -- It's important to do this even though in the error-free case
580 -- we could just split the sigma_tc_ty (since the tyvars don't
581 -- unified with anything). But in the case of an error, when
582 -- the tyvars *do* get unified with something, we want to carry on
583 -- typechecking the rest of the program with the function bound
584 -- to a pristine type, namely sigma_tc_ty
585 tcInstSigType SigTv (idType poly_id) `thenNF_Tc` \ (tyvars', theta', tau') ->
587 newMethodWithGivenTy SignatureOrigin
590 theta' tau' `thenNF_Tc` \ inst ->
591 -- We make a Method even if it's not overloaded; no harm
593 returnNF_Tc (TySigInfo (idName poly_id) poly_id tyvars' theta' tau'
594 (instToId inst) [inst] src_loc)
599 %************************************************************************
601 \subsection{Errors and contexts}
603 %************************************************************************
606 typeKindCtxt :: RenamedHsType -> Message
607 typeKindCtxt ty = sep [ptext SLIT("When checking that"),
608 nest 2 (quotes (ppr ty)),
609 ptext SLIT("is a type")]
611 appKindCtxt :: SDoc -> Message
612 appKindCtxt pp = ptext SLIT("When checking kinds in") <+> quotes pp
614 wrongThingErr expected thing name
615 = pp_thing thing <+> quotes (ppr name) <+> ptext SLIT("used as a") <+> text expected
617 pp_thing (AGlobal (ATyCon _)) = ptext SLIT("Type constructor")
618 pp_thing (AGlobal (AClass _)) = ptext SLIT("Class")
619 pp_thing (AGlobal (AnId _)) = ptext SLIT("Identifier")
620 pp_thing (ATyVar _) = ptext SLIT("Type variable")
621 pp_thing (ATcId _) = ptext SLIT("Local identifier")
622 pp_thing (AThing _) = ptext SLIT("Utterly bogus")