2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcMonoType]{Typechecking user-specified @MonoTypes@}
7 module TcMonoType ( tcHsType, tcHsSigType, tcHsBoxedSigType,
8 tcContext, tcClassContext, tcHsTyVar,
11 kcHsTyVar, kcHsTyVars, mkTyClTyVars,
12 kcHsType, kcHsSigType, kcHsBoxedSigType, kcHsContext,
15 TcSigInfo(..), tcTySig, mkTcSig, maybeSig,
16 checkSigTyVars, sigCtxt, sigPatCtxt
19 #include "HsVersions.h"
21 import HsSyn ( HsType(..), HsTyVarBndr(..), HsUsageAnn(..),
22 Sig(..), HsPred(..), pprParendHsType, HsTupCon(..), hsTyVarNames )
23 import RnHsSyn ( RenamedHsType, RenamedHsPred, RenamedContext, RenamedSig )
24 import TcHsSyn ( TcId )
27 import TcEnv ( tcExtendTyVarEnv, tcLookupTy, tcGetValueEnv, tcGetInScopeTyVars,
28 tcExtendUVarEnv, tcLookupUVar,
29 tcGetGlobalTyVars, valueEnvIds,
30 TyThing(..), tyThingKind, tcExtendKindEnv
32 import TcType ( TcType, TcKind, TcTyVar, TcThetaType, TcTauType,
33 newKindVar, tcInstSigVar,
34 zonkKindEnv, zonkTcType, zonkTcTyVars, zonkTcTyVar
36 import Inst ( Inst, InstOrigin(..), newMethodWithGivenTy, instToIdBndr,
37 instFunDeps, instFunDepsOfTheta )
38 import FunDeps ( tyVarFunDep, oclose )
39 import TcUnify ( unifyKind, unifyKinds, unifyOpenTypeKind )
40 import Type ( Type, Kind, PredType(..), ThetaType, UsageAnn(..),
41 mkTyVarTy, mkTyVarTys, mkFunTy, mkSynTy, mkUsgTy,
42 mkUsForAllTy, zipFunTys, hoistForAllTys,
43 mkSigmaTy, mkDictTy, mkPredTy, mkTyConApp,
44 mkAppTys, splitForAllTys, splitRhoTy, mkRhoTy,
45 boxedTypeKind, unboxedTypeKind, mkArrowKind,
46 mkArrowKinds, getTyVar_maybe, getTyVar, splitFunTy_maybe,
47 tidyOpenType, tidyOpenTypes, tidyTyVar, tidyTyVars,
48 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, mkForAllTys,
51 import PprType ( pprConstraint, pprType, pprPred )
52 import Subst ( mkTopTyVarSubst, substTy )
53 import Id ( mkVanillaId, idName, idType, idFreeTyVars )
54 import Var ( TyVar, mkTyVar, tyVarKind, mkNamedUVar, varName )
57 import ErrUtils ( Message )
58 import TyCon ( TyCon, isSynTyCon, tyConArity, tyConKind )
59 import Class ( ClassContext, classArity, classTyCon )
60 import Name ( Name, OccName, isLocallyDefined )
61 import TysWiredIn ( mkListTy, mkTupleTy )
62 import UniqFM ( elemUFM, foldUFM )
63 import BasicTypes ( Boxity(..) )
64 import SrcLoc ( SrcLoc )
65 import Util ( mapAccumL, isSingleton, removeDups )
70 %************************************************************************
72 \subsection{Checking types}
74 %************************************************************************
78 kcHsTyVar :: HsTyVarBndr name -> NF_TcM s (name, TcKind)
79 kcHsTyVars :: [HsTyVarBndr name] -> NF_TcM s [(name, TcKind)]
81 kcHsTyVar (UserTyVar name) = newKindVar `thenNF_Tc` \ kind ->
82 returnNF_Tc (name, kind)
83 kcHsTyVar (IfaceTyVar name kind) = returnNF_Tc (name, kind)
85 kcHsTyVars tvs = mapNF_Tc kcHsTyVar tvs
87 ---------------------------
88 kcBoxedType :: RenamedHsType -> TcM s ()
89 -- The type ty must be a *boxed* *type*
91 = kcHsType ty `thenTc` \ kind ->
92 tcAddErrCtxt (typeKindCtxt ty) $
93 unifyKind boxedTypeKind kind
95 ---------------------------
96 kcTypeType :: RenamedHsType -> TcM s ()
97 -- The type ty must be a *type*, but it can be boxed or unboxed.
99 = kcHsType ty `thenTc` \ kind ->
100 tcAddErrCtxt (typeKindCtxt ty) $
101 unifyOpenTypeKind kind
103 ---------------------------
104 kcHsSigType, kcHsBoxedSigType :: RenamedHsType -> TcM s ()
105 -- Used for type signatures
106 kcHsSigType = kcTypeType
107 kcHsBoxedSigType = kcBoxedType
109 ---------------------------
110 kcHsType :: RenamedHsType -> TcM s TcKind
111 kcHsType (HsTyVar name)
112 = tcLookupTy name `thenTc` \ thing ->
114 ATyVar tv -> returnTc (tyVarKind tv)
115 ATyCon tc -> returnTc (tyConKind tc)
116 AThing k -> returnTc k
117 other -> failWithTc (wrongThingErr "type" thing name)
119 kcHsType (HsUsgTy _ ty) = kcHsType ty
120 kcHsType (HsUsgForAllTy _ ty) = kcHsType ty
122 kcHsType (HsListTy ty)
123 = kcBoxedType ty `thenTc` \ tau_ty ->
124 returnTc boxedTypeKind
126 kcHsType (HsTupleTy (HsTupCon _ Boxed) tys)
127 = mapTc kcBoxedType tys `thenTc_`
128 returnTc boxedTypeKind
130 kcHsType (HsTupleTy (HsTupCon _ Unboxed) tys)
131 = mapTc kcTypeType tys `thenTc_`
132 returnTc unboxedTypeKind
134 kcHsType (HsFunTy ty1 ty2)
135 = kcTypeType ty1 `thenTc_`
136 kcTypeType ty2 `thenTc_`
137 returnTc boxedTypeKind
139 kcHsType (HsPredTy pred)
140 = kcHsPred pred `thenTc_`
141 returnTc boxedTypeKind
143 kcHsType ty@(HsAppTy ty1 ty2)
144 = kcHsType ty1 `thenTc` \ tc_kind ->
145 kcHsType ty2 `thenTc` \ arg_kind ->
147 tcAddErrCtxt (appKindCtxt (ppr ty)) $
148 case splitFunTy_maybe tc_kind of
149 Just (arg_kind', res_kind)
150 -> unifyKind arg_kind arg_kind' `thenTc_`
153 Nothing -> newKindVar `thenNF_Tc` \ res_kind ->
154 unifyKind tc_kind (mkArrowKind arg_kind res_kind) `thenTc_`
157 kcHsType (HsForAllTy (Just tv_names) context ty)
158 = kcHsTyVars tv_names `thenNF_Tc` \ kind_env ->
159 tcExtendKindEnv kind_env $
160 kcHsContext context `thenTc_`
161 kcHsType ty `thenTc` \ kind ->
163 -- Context behaves like a function type
164 -- This matters. Return-unboxed-tuple analysis can
165 -- give overloaded functions like
166 -- f :: forall a. Num a => (# a->a, a->a #)
167 -- And we want these to get through the type checker
168 returnTc (if null context then
173 ---------------------------
174 kcHsContext ctxt = mapTc_ kcHsPred ctxt
176 kcHsPred :: RenamedHsPred -> TcM s ()
177 kcHsPred pred@(HsPIParam name ty)
178 = tcAddErrCtxt (appKindCtxt (ppr pred)) $
181 kcHsPred pred@(HsPClass cls tys)
182 = tcAddErrCtxt (appKindCtxt (ppr pred)) $
183 tcLookupTy cls `thenNF_Tc` \ thing ->
185 AClass cls -> returnTc (tyConKind (classTyCon cls))
186 AThing kind -> returnTc kind
187 other -> failWithTc (wrongThingErr "class" thing cls)) `thenTc` \ kind ->
188 mapTc kcHsType tys `thenTc` \ arg_kinds ->
189 unifyKind kind (mkArrowKinds arg_kinds boxedTypeKind)
193 kcTyVarScope :: [HsTyVarBndr Name]
194 -> TcM s a -- The kind checker
196 -- Do a kind check to find out the kinds of the type variables
197 -- Then return the type variables
199 kcTyVarScope [] kind_check = returnTc []
200 -- A useful short cut for a common case!
202 kcTyVarScope tv_names kind_check
203 = kcHsTyVars tv_names `thenNF_Tc` \ tv_names_w_kinds ->
204 tcExtendKindEnv tv_names_w_kinds kind_check `thenTc_`
205 zonkKindEnv tv_names_w_kinds `thenNF_Tc` \ zonked_pairs ->
206 returnTc (map mk_tyvar zonked_pairs)
210 %************************************************************************
212 \subsection{Checking types}
214 %************************************************************************
216 tcHsType and tcHsTypeKind
217 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
219 tcHsSigType and tcHsBoxedSigType are used for type signatures written by the programmer
221 * We hoist any inner for-alls to the top
223 * Notice that we kind-check first, because the type-check assumes
224 that the kinds are already checked.
225 * They are only called when there are no kind vars in the environment
226 so the kind returned is indeed a Kind not a TcKind
229 tcHsSigType :: RenamedHsType -> TcM s TcType
231 = kcTypeType ty `thenTc_`
232 tcHsType ty `thenTc` \ ty' ->
233 returnTc (hoistForAllTys ty')
235 tcHsBoxedSigType :: RenamedHsType -> TcM s Type
237 = kcBoxedType ty `thenTc_`
238 tcHsType ty `thenTc` \ ty' ->
239 returnTc (hoistForAllTys ty')
247 tcHsType :: RenamedHsType -> TcM s Type
248 tcHsType ty@(HsTyVar name)
251 tcHsType (HsListTy ty)
252 = tcHsType ty `thenTc` \ tau_ty ->
253 returnTc (mkListTy tau_ty)
255 tcHsType (HsTupleTy (HsTupCon _ boxity) tys)
256 = mapTc tcHsType tys `thenTc` \ tau_tys ->
257 returnTc (mkTupleTy boxity (length tys) tau_tys)
259 tcHsType (HsFunTy ty1 ty2)
260 = tcHsType ty1 `thenTc` \ tau_ty1 ->
261 tcHsType ty2 `thenTc` \ tau_ty2 ->
262 returnTc (mkFunTy tau_ty1 tau_ty2)
264 tcHsType (HsAppTy ty1 ty2)
267 tcHsType (HsPredTy pred)
268 = tcClassAssertion True pred `thenTc` \ pred' ->
269 returnTc (mkPredTy pred')
271 tcHsType (HsUsgTy usg ty)
272 = newUsg usg `thenTc` \ usg' ->
273 tcHsType ty `thenTc` \ tc_ty ->
274 returnTc (mkUsgTy usg' tc_ty)
276 newUsg usg = case usg of
277 HsUsOnce -> returnTc UsOnce
278 HsUsMany -> returnTc UsMany
279 HsUsVar uv_name -> tcLookupUVar uv_name `thenTc` \ uv ->
282 tcHsType (HsUsgForAllTy uv_name ty)
284 uv = mkNamedUVar uv_name
286 tcExtendUVarEnv uv_name uv $
287 tcHsType ty `thenTc` \ tc_ty ->
288 returnTc (mkUsForAllTy uv tc_ty)
290 tcHsType full_ty@(HsForAllTy (Just tv_names) context ty)
292 kind_check = kcHsContext context `thenTc_` kcHsType ty
294 kcTyVarScope tv_names kind_check `thenTc` \ forall_tyvars ->
295 tcExtendTyVarEnv forall_tyvars $
296 tcContext context `thenTc` \ theta ->
297 tcHsType ty `thenTc` \ tau ->
299 -- Check for ambiguity
300 -- forall V. P => tau
301 -- is ambiguous if P contains generic variables
302 -- (i.e. one of the Vs) that are not mentioned in tau
304 -- However, we need to take account of functional dependencies
305 -- when we speak of 'mentioned in tau'. Example:
306 -- class C a b | a -> b where ...
308 -- forall x y. (C x y) => x
309 -- is not ambiguous because x is mentioned and x determines y
311 -- NOTE: In addition, GHC insists that at least one type variable
312 -- in each constraint is in V. So we disallow a type like
313 -- forall a. Eq b => b -> b
314 -- even in a scope where b is in scope.
315 -- This is the is_free test below.
317 tau_vars = tyVarsOfType tau
318 fds = instFunDepsOfTheta theta
319 tvFundep = tyVarFunDep fds
320 extended_tau_vars = oclose tvFundep tau_vars
321 is_ambig ct_var = (ct_var `elem` forall_tyvars) &&
322 not (ct_var `elemUFM` extended_tau_vars)
323 is_free ct_var = not (ct_var `elem` forall_tyvars)
325 check_pred pred = checkTc (not any_ambig) (ambigErr pred full_ty) `thenTc_`
326 checkTc (not all_free) (freeErr pred full_ty)
328 ct_vars = varSetElems (tyVarsOfPred pred)
329 any_ambig = is_source_polytype && any is_ambig ct_vars
330 all_free = all is_free ct_vars
332 -- Check ambiguity only for source-program types, not
333 -- for types coming from inteface files. The latter can
334 -- legitimately have ambiguous types. Example
335 -- class S a where s :: a -> (Int,Int)
336 -- instance S Char where s _ = (1,1)
337 -- f:: S a => [a] -> Int -> (Int,Int)
338 -- f (_::[a]) x = (a*x,b)
339 -- where (a,b) = s (undefined::a)
340 -- Here the worker for f gets the type
341 -- fw :: forall a. S a => Int -> (# Int, Int #)
343 -- If the list of tv_names is empty, we have a monotype,
344 -- and then we don't need to check for ambiguity either,
345 -- because the test can't fail (see is_ambig).
346 is_source_polytype = case tv_names of
347 (UserTyVar _ : _) -> True
350 mapTc check_pred theta `thenTc_`
351 returnTc (mkSigmaTy forall_tyvars theta tau)
354 Help functions for type applications
355 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
358 tc_app (HsAppTy ty1 ty2) tys
359 = tc_app ty1 (ty2:tys)
362 = tcAddErrCtxt (appKindCtxt pp_app) $
363 mapTc tcHsType tys `thenTc` \ arg_tys ->
364 tc_fun_type ty arg_tys
366 pp_app = ppr ty <+> sep (map pprParendHsType tys)
368 -- (tc_fun_type ty arg_tys) returns (mkAppTys ty arg_tys)
369 -- But not quite; for synonyms it checks the correct arity, and builds a SynTy
370 -- hence the rather strange functionality.
372 tc_fun_type (HsTyVar name) arg_tys
373 = tcLookupTy name `thenTc` \ thing ->
375 ATyVar tv -> returnTc (mkAppTys (mkTyVarTy tv) arg_tys)
377 ATyCon tc | isSynTyCon tc -> checkTc arity_ok err_msg `thenTc_`
378 returnTc (mkAppTys (mkSynTy tc (take arity arg_tys))
379 (drop arity arg_tys))
381 | otherwise -> returnTc (mkTyConApp tc arg_tys)
384 arity_ok = arity <= n_args
385 arity = tyConArity tc
386 -- It's OK to have an *over-applied* type synonym
387 -- data Tree a b = ...
388 -- type Foo a = Tree [a]
389 -- f :: Foo a b -> ...
390 err_msg = arityErr "type synonym" name arity n_args
391 n_args = length arg_tys
393 other -> failWithTc (wrongThingErr "type constructor" thing name)
395 tc_fun_type ty arg_tys
396 = tcHsType ty `thenTc` \ fun_ty ->
397 returnNF_Tc (mkAppTys fun_ty arg_tys)
404 tcClassContext :: RenamedContext -> TcM s ClassContext
405 -- Used when we are expecting a ClassContext (i.e. no implicit params)
406 tcClassContext context
407 = tcContext context `thenTc` \ theta ->
408 returnTc (classesOfPreds theta)
410 tcContext :: RenamedContext -> TcM s ThetaType
411 tcContext context = mapTc (tcClassAssertion False) context
413 tcClassAssertion ccall_ok assn@(HsPClass class_name tys)
414 = tcAddErrCtxt (appKindCtxt (ppr assn)) $
415 mapTc tcHsType tys `thenTc` \ arg_tys ->
416 tcLookupTy class_name `thenTc` \ thing ->
418 AClass clas -> checkTc (arity == n_tys) err `thenTc_`
419 returnTc (Class clas arg_tys)
421 arity = classArity clas
423 err = arityErr "Class" class_name arity n_tys
425 other -> failWithTc (wrongThingErr "class" thing class_name)
427 tcClassAssertion ccall_ok assn@(HsPIParam name ty)
428 = tcAddErrCtxt (appKindCtxt (ppr assn)) $
429 tcHsType ty `thenTc` \ arg_ty ->
430 returnTc (IParam name arg_ty)
434 %************************************************************************
436 \subsection{Type variables, with knot tying!}
438 %************************************************************************
441 mk_tyvar (tv_bndr, kind) = mkTyVar tv_bndr kind
443 mkTyClTyVars :: Kind -- Kind of the tycon or class
444 -> [HsTyVarBndr Name]
446 mkTyClTyVars kind tyvar_names
447 = map mk_tyvar tyvars_w_kinds
449 (tyvars_w_kinds, _) = zipFunTys (hsTyVarNames tyvar_names) kind
451 tcHsTyVar :: HsTyVarBndr Name -> NF_TcM s TcTyVar
452 tcHsTyVar (UserTyVar name) = newKindVar `thenNF_Tc` \ kind ->
453 tcNewMutTyVar name kind
454 -- NB: mutable kind => mutable tyvar, so that zonking can bind
455 -- the tyvar to its immutable form
457 tcHsTyVar (IfaceTyVar name kind) = returnNF_Tc (mkTyVar name kind)
462 %************************************************************************
464 \subsection{Signatures}
466 %************************************************************************
468 @tcSigs@ checks the signatures for validity, and returns a list of
469 {\em freshly-instantiated} signatures. That is, the types are already
470 split up, and have fresh type variables installed. All non-type-signature
471 "RenamedSigs" are ignored.
473 The @TcSigInfo@ contains @TcTypes@ because they are unified with
474 the variable's type, and after that checked to see whether they've
480 Name -- N, the Name in corresponding binding
482 TcId -- *Polymorphic* binder for this value...
489 TcId -- *Monomorphic* binder for this value
490 -- Does *not* have name = N
493 [Inst] -- Empty if theta is null, or
494 -- (method mono_id) otherwise
496 SrcLoc -- Of the signature
498 instance Outputable TcSigInfo where
499 ppr (TySigInfo nm id tyvars theta tau _ inst loc) =
500 ppr nm <+> ptext SLIT("::") <+> ppr tyvars <+> ppr theta <+> ptext SLIT("=>") <+> ppr tau
502 maybeSig :: [TcSigInfo] -> Name -> Maybe (TcSigInfo)
503 -- Search for a particular signature
504 maybeSig [] name = Nothing
505 maybeSig (sig@(TySigInfo sig_name _ _ _ _ _ _ _) : sigs) name
506 | name == sig_name = Just sig
507 | otherwise = maybeSig sigs name
512 tcTySig :: RenamedSig -> TcM s TcSigInfo
514 tcTySig (Sig v ty src_loc)
515 = tcAddSrcLoc src_loc $
516 tcAddErrCtxt (tcsigCtxt v) $
517 tcHsSigType ty `thenTc` \ sigma_tc_ty ->
518 mkTcSig (mkVanillaId v sigma_tc_ty) src_loc `thenNF_Tc` \ sig ->
521 mkTcSig :: TcId -> SrcLoc -> NF_TcM s TcSigInfo
522 mkTcSig poly_id src_loc
523 = -- Instantiate this type
524 -- It's important to do this even though in the error-free case
525 -- we could just split the sigma_tc_ty (since the tyvars don't
526 -- unified with anything). But in the case of an error, when
527 -- the tyvars *do* get unified with something, we want to carry on
528 -- typechecking the rest of the program with the function bound
529 -- to a pristine type, namely sigma_tc_ty
531 (tyvars, rho) = splitForAllTys (idType poly_id)
533 mapNF_Tc tcInstSigVar tyvars `thenNF_Tc` \ tyvars' ->
534 -- Make *signature* type variables
537 tyvar_tys' = mkTyVarTys tyvars'
538 rho' = substTy (mkTopTyVarSubst tyvars tyvar_tys') rho
539 -- mkTopTyVarSubst because the tyvars' are fresh
540 (theta', tau') = splitRhoTy rho'
541 -- This splitRhoTy tries hard to make sure that tau' is a type synonym
542 -- wherever possible, which can improve interface files.
544 newMethodWithGivenTy SignatureOrigin
547 theta' tau' `thenNF_Tc` \ inst ->
548 -- We make a Method even if it's not overloaded; no harm
549 instFunDeps SignatureOrigin theta' `thenNF_Tc` \ fds ->
551 returnNF_Tc (TySigInfo name poly_id tyvars' theta' tau' (instToIdBndr inst) (inst : fds) src_loc)
553 name = idName poly_id
558 %************************************************************************
560 \subsection{Checking signature type variables}
562 %************************************************************************
564 @checkSigTyVars@ is used after the type in a type signature has been unified with
565 the actual type found. It then checks that the type variables of the type signature
567 (a) Still all type variables
568 eg matching signature [a] against inferred type [(p,q)]
569 [then a will be unified to a non-type variable]
571 (b) Still all distinct
572 eg matching signature [(a,b)] against inferred type [(p,p)]
573 [then a and b will be unified together]
575 (c) Not mentioned in the environment
576 eg the signature for f in this:
582 Here, f is forced to be monorphic by the free occurence of x.
584 (d) Not (unified with another type variable that is) in scope.
585 eg f x :: (r->r) = (\y->y) :: forall a. a->r
586 when checking the expression type signature, we find that
587 even though there is nothing in scope whose type mentions r,
588 nevertheless the type signature for the expression isn't right.
590 Another example is in a class or instance declaration:
592 op :: forall b. a -> b
594 Here, b gets unified with a
596 Before doing this, the substitution is applied to the signature type variable.
598 We used to have the notion of a "DontBind" type variable, which would
599 only be bound to itself or nothing. Then points (a) and (b) were
600 self-checking. But it gave rise to bogus consequential error messages.
603 f = (*) -- Monomorphic
608 Here, we get a complaint when checking the type signature for g,
609 that g isn't polymorphic enough; but then we get another one when
610 dealing with the (Num x) context arising from f's definition;
611 we try to unify x with Int (to default it), but find that x has already
612 been unified with the DontBind variable "a" from g's signature.
613 This is really a problem with side-effecting unification; we'd like to
614 undo g's effects when its type signature fails, but unification is done
615 by side effect, so we can't (easily).
617 So we revert to ordinary type variables for signatures, and try to
618 give a helpful message in checkSigTyVars.
621 checkSigTyVars :: [TcTyVar] -- Universally-quantified type variables in the signature
622 -> TcTyVarSet -- Tyvars that are free in the type signature
623 -- These should *already* be in the global-var set, and are
624 -- used here only to improve the error message
625 -> TcM s [TcTyVar] -- Zonked signature type variables
627 checkSigTyVars [] free = returnTc []
629 checkSigTyVars sig_tyvars free_tyvars
630 = zonkTcTyVars sig_tyvars `thenNF_Tc` \ sig_tys ->
631 tcGetGlobalTyVars `thenNF_Tc` \ globals ->
633 checkTcM (all_ok sig_tys globals)
634 (complain sig_tys globals) `thenTc_`
636 returnTc (map (getTyVar "checkSigTyVars") sig_tys)
640 all_ok (ty:tys) acc = case getTyVar_maybe ty of
641 Nothing -> False -- Point (a)
642 Just tv | tv `elemVarSet` acc -> False -- Point (b) or (c)
643 | otherwise -> all_ok tys (acc `extendVarSet` tv)
646 complain sig_tys globals
647 = -- For the in-scope ones, zonk them and construct a map
648 -- from the zonked tyvar to the in-scope one
649 -- If any of the in-scope tyvars zonk to a type, then ignore them;
650 -- that'll be caught later when we back up to their type sig
651 tcGetInScopeTyVars `thenNF_Tc` \ in_scope_tvs ->
652 zonkTcTyVars in_scope_tvs `thenNF_Tc` \ in_scope_tys ->
654 in_scope_assoc = [ (zonked_tv, in_scope_tv)
655 | (z_ty, in_scope_tv) <- in_scope_tys `zip` in_scope_tvs,
656 Just zonked_tv <- [getTyVar_maybe z_ty]
658 in_scope_env = mkVarEnv in_scope_assoc
661 -- "check" checks each sig tyvar in turn
663 (env2, in_scope_env, [])
664 (tidy_tvs `zip` tidy_tys) `thenNF_Tc` \ (env3, _, msgs) ->
666 failWithTcM (env3, main_msg $$ nest 4 (vcat msgs))
668 (env1, tidy_tvs) = mapAccumL tidyTyVar emptyTidyEnv sig_tyvars
669 (env2, tidy_tys) = tidyOpenTypes env1 sig_tys
671 main_msg = ptext SLIT("Inferred type is less polymorphic than expected")
673 check (env, acc, msgs) (sig_tyvar,ty)
674 -- sig_tyvar is from the signature;
675 -- ty is what you get if you zonk sig_tyvar and then tidy it
677 -- acc maps a zonked type variable back to a signature type variable
678 = case getTyVar_maybe ty of {
679 Nothing -> -- Error (a)!
680 returnNF_Tc (env, acc, unify_msg sig_tyvar (ppr ty) : msgs) ;
684 case lookupVarEnv acc tv of {
685 Just sig_tyvar' -> -- Error (b) or (d)!
686 returnNF_Tc (env, acc, unify_msg sig_tyvar (ppr sig_tyvar') : msgs) ;
690 if tv `elemVarSet` globals -- Error (c)! Type variable escapes
691 -- The least comprehensible, so put it last
692 then tcGetValueEnv `thenNF_Tc` \ ve ->
693 find_globals tv env [] (valueEnvIds ve) `thenNF_Tc` \ (env1, globs) ->
694 find_frees tv env1 [] (varSetElems free_tyvars) `thenNF_Tc` \ (env2, frees) ->
695 returnNF_Tc (env2, acc, escape_msg sig_tyvar tv globs frees : msgs)
698 returnNF_Tc (env, extendVarEnv acc tv sig_tyvar, msgs)
701 -- find_globals looks at the value environment and finds values
702 -- whose types mention the offending type variable. It has to be
703 -- careful to zonk the Id's type first, so it has to be in the monad.
704 -- We must be careful to pass it a zonked type variable, too.
705 find_globals tv tidy_env acc []
706 = returnNF_Tc (tidy_env, acc)
708 find_globals tv tidy_env acc (id:ids)
709 | not (isLocallyDefined id) ||
710 isEmptyVarSet (idFreeTyVars id)
711 = find_globals tv tidy_env acc ids
714 = zonkTcType (idType id) `thenNF_Tc` \ id_ty ->
715 if tv `elemVarSet` tyVarsOfType id_ty then
717 (tidy_env', id_ty') = tidyOpenType tidy_env id_ty
718 acc' = (idName id, id_ty') : acc
720 find_globals tv tidy_env' acc' ids
722 find_globals tv tidy_env acc ids
724 find_frees tv tidy_env acc []
725 = returnNF_Tc (tidy_env, acc)
726 find_frees tv tidy_env acc (ftv:ftvs)
727 = zonkTcTyVar ftv `thenNF_Tc` \ ty ->
728 if tv `elemVarSet` tyVarsOfType ty then
730 (tidy_env', ftv') = tidyTyVar tidy_env ftv
732 find_frees tv tidy_env' (ftv':acc) ftvs
734 find_frees tv tidy_env acc ftvs
737 escape_msg sig_tv tv globs frees
738 = mk_msg sig_tv <+> ptext SLIT("escapes") $$
739 if not (null globs) then
740 vcat [pp_it <+> ptext SLIT("is mentioned in the environment"),
741 ptext SLIT("The following variables in the environment mention") <+> quotes (ppr tv),
742 nest 2 (vcat_first 10 [ppr name <+> dcolon <+> ppr ty | (name,ty) <- globs])
744 else if not (null frees) then
745 vcat [ptext SLIT("It is reachable from the type variable(s)") <+> pprQuotedList frees,
746 nest 2 (ptext SLIT("which") <+> is_are <+> ptext SLIT("free in the signature"))
749 empty -- Sigh. It's really hard to give a good error message
750 -- all the time. One bad case is an existential pattern match
752 is_are | isSingleton frees = ptext SLIT("is")
753 | otherwise = ptext SLIT("are")
754 pp_it | sig_tv /= tv = ptext SLIT("It unifies with") <+> quotes (ppr tv) <> comma <+> ptext SLIT("which")
755 | otherwise = ptext SLIT("It")
757 vcat_first :: Int -> [SDoc] -> SDoc
758 vcat_first n [] = empty
759 vcat_first 0 (x:xs) = text "...others omitted..."
760 vcat_first n (x:xs) = x $$ vcat_first (n-1) xs
762 unify_msg tv thing = mk_msg tv <+> ptext SLIT("is unified with") <+> quotes thing
763 mk_msg tv = ptext SLIT("Quantified type variable") <+> quotes (ppr tv)
766 These two context are used with checkSigTyVars
769 sigCtxt :: Message -> [TcTyVar] -> TcThetaType -> TcTauType
770 -> TidyEnv -> NF_TcM s (TidyEnv, Message)
771 sigCtxt when sig_tyvars sig_theta sig_tau tidy_env
772 = zonkTcType sig_tau `thenNF_Tc` \ actual_tau ->
774 (env1, tidy_sig_tyvars) = tidyTyVars tidy_env sig_tyvars
775 (env2, tidy_sig_rho) = tidyOpenType env1 (mkRhoTy sig_theta sig_tau)
776 (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
777 msg = vcat [ptext SLIT("Signature type: ") <+> pprType (mkForAllTys tidy_sig_tyvars tidy_sig_rho),
778 ptext SLIT("Type to generalise:") <+> pprType tidy_actual_tau,
782 returnNF_Tc (env3, msg)
784 sigPatCtxt bound_tvs bound_ids tidy_env
786 sep [ptext SLIT("When checking a pattern that binds"),
787 nest 4 (vcat (zipWith ppr_id show_ids tidy_tys))])
789 show_ids = filter is_interesting bound_ids
790 is_interesting id = any (`elemVarSet` idFreeTyVars id) bound_tvs
792 (env1, tidy_tys) = tidyOpenTypes tidy_env (map idType show_ids)
793 ppr_id id ty = ppr id <+> dcolon <+> ppr ty
794 -- Don't zonk the types so we get the separate, un-unified versions
798 %************************************************************************
800 \subsection{Errors and contexts}
802 %************************************************************************
805 tcsigCtxt v = ptext SLIT("In a type signature for") <+> quotes (ppr v)
807 typeCtxt ty = ptext SLIT("In the type") <+> quotes (ppr ty)
809 typeKindCtxt :: RenamedHsType -> Message
810 typeKindCtxt ty = sep [ptext SLIT("When checking that"),
811 nest 2 (quotes (ppr ty)),
812 ptext SLIT("is a type")]
814 appKindCtxt :: SDoc -> Message
815 appKindCtxt pp = ptext SLIT("When checking kinds in") <+> quotes pp
817 wrongThingErr expected actual name
818 = pp_actual actual <+> quotes (ppr name) <+> ptext SLIT("used as a") <+> text expected
820 pp_actual (ATyCon _) = ptext SLIT("Type constructor")
821 pp_actual (AClass _) = ptext SLIT("Class")
822 pp_actual (ATyVar _) = ptext SLIT("Type variable")
823 pp_actual (AThing _) = ptext SLIT("Utterly bogus")
826 = sep [ptext SLIT("Ambiguous constraint") <+> quotes (pprPred pred),
827 nest 4 (ptext SLIT("for the type:") <+> ppr ty),
828 nest 4 (ptext SLIT("Each forall'd type variable mentioned by the constraint must appear after the =>"))]
831 = sep [ptext SLIT("The constraint") <+> quotes (pprPred pred) <+>
832 ptext SLIT("does not mention any of the universally quantified type variables"),
833 nest 4 (ptext SLIT("in the type") <+> quotes (ppr ty))