2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[TcBinds]{TcBinds}
7 #include "HsVersions.h"
9 module TcBinds ( tcBindsAndThen, tcPragmaSigs, checkSigTyVars ) where
13 import HsSyn ( HsBinds(..), Bind(..), Sig(..), MonoBinds(..),
14 Match, HsType, InPat(..), OutPat(..), HsExpr(..),
15 GRHSsAndBinds, ArithSeqInfo, HsLit, Fake, Stmt, DoOrListComp, Fixity,
17 import RnHsSyn ( SYN_IE(RenamedHsBinds), SYN_IE(RenamedBind), RenamedSig(..),
18 SYN_IE(RenamedMonoBinds)
20 import TcHsSyn ( SYN_IE(TcHsBinds), SYN_IE(TcBind), SYN_IE(TcMonoBinds),
21 TcIdOcc(..), SYN_IE(TcIdBndr), SYN_IE(TcExpr),
26 import Inst ( Inst, SYN_IE(LIE), emptyLIE, plusLIE, InstOrigin(..),
27 newDicts, tyVarsOfInst, instToId
29 import TcEnv ( tcExtendLocalValEnv, tcLookupLocalValueOK, newMonoIds,
30 tcGetGlobalTyVars, tcExtendGlobalTyVars
32 import SpecEnv ( SpecEnv )
33 IMPORT_DELOOPER(TcLoop) ( tcGRHSsAndBinds )
34 import TcMatches ( tcMatchesFun )
35 import TcSimplify ( tcSimplify, tcSimplifyAndCheck )
36 import TcMonoType ( tcHsType )
37 import TcPat ( tcPat )
38 import TcSimplify ( bindInstsOfLocalFuns )
39 import TcType ( SYN_IE(TcType), SYN_IE(TcThetaType), SYN_IE(TcTauType),
40 SYN_IE(TcTyVarSet), SYN_IE(TcTyVar),
41 newTyVarTy, zonkTcType, zonkTcTyVar, zonkTcTyVars,
42 newTcTyVar, tcInstSigType, newTyVarTys
44 import Unify ( unifyTauTy )
46 import Kind ( isUnboxedTypeKind, mkTypeKind, isTypeKind, mkBoxedTypeKind )
47 import Id ( GenId, idType, mkUserLocal, mkUserId )
48 import IdInfo ( noIdInfo )
49 import Maybes ( assocMaybe, catMaybes )
50 import Name ( pprNonSym, getOccName, getSrcLoc, Name )
51 import PragmaInfo ( PragmaInfo(..) )
53 import Type ( mkTyVarTy, mkTyVarTys, isTyVarTy, tyVarsOfTypes, eqSimpleTheta,
54 mkSigmaTy, splitSigmaTy, mkForAllTys, mkFunTys, getTyVar,
55 splitRhoTy, mkForAllTy, splitForAllTy )
56 import TyVar ( GenTyVar, SYN_IE(TyVar), tyVarKind, minusTyVarSet, emptyTyVarSet,
57 elementOfTyVarSet, unionTyVarSets, tyVarSetToList )
58 import Bag ( bagToList, foldrBag, isEmptyBag )
59 import Util ( isIn, zipEqual, zipWithEqual, zipWith3Equal, hasNoDups, assoc,
61 import PprType ( GenClass, GenType, GenTyVar )
62 import Unique ( Unique )
63 import Outputable ( interppSP, interpp'SP )
67 %************************************************************************
69 \subsection{Type-checking bindings}
71 %************************************************************************
73 @tcBindsAndThen@ typechecks a @HsBinds@. The "and then" part is because
74 it needs to know something about the {\em usage} of the things bound,
75 so that it can create specialisations of them. So @tcBindsAndThen@
76 takes a function which, given an extended environment, E, typechecks
77 the scope of the bindings returning a typechecked thing and (most
78 important) an LIE. It is this LIE which is then used as the basis for
79 specialising the things bound.
81 @tcBindsAndThen@ also takes a "combiner" which glues together the
82 bindings and the "thing" to make a new "thing".
84 The real work is done by @tcBindWithSigsAndThen@.
86 Recursive and non-recursive binds are handled in essentially the same
87 way: because of uniques there are no scoping issues left. The only
88 difference is that non-recursive bindings can bind primitive values.
90 Even for non-recursive binding groups we add typings for each binder
91 to the LVE for the following reason. When each individual binding is
92 checked the type of its LHS is unified with that of its RHS; and
93 type-checking the LHS of course requires that the binder is in scope.
95 At the top-level the LIE is sure to contain nothing but constant
96 dictionaries, which we resolve at the module level.
100 :: (TcHsBinds s -> thing -> thing) -- Combinator
102 -> TcM s (thing, LIE s, thing_ty)
103 -> TcM s (thing, LIE s, thing_ty)
105 tcBindsAndThen combiner EmptyBinds do_next
106 = do_next `thenTc` \ (thing, lie, thing_ty) ->
107 returnTc (combiner EmptyBinds thing, lie, thing_ty)
109 tcBindsAndThen combiner (SingleBind bind) do_next
110 = tcBindWithSigsAndThen combiner bind [] do_next
112 tcBindsAndThen combiner (BindWith bind sigs) do_next
113 = tcBindWithSigsAndThen combiner bind sigs do_next
115 tcBindsAndThen combiner (ThenBinds binds1 binds2) do_next
116 = tcBindsAndThen combiner binds1 (tcBindsAndThen combiner binds2 do_next)
119 An aside. The original version of @tcBindsAndThen@ which lacks a
120 combiner function, appears below. Though it is perfectly well
121 behaved, it cannot be typed by Haskell, because the recursive call is
122 at a different type to the definition itself. There aren't too many
123 examples of this, which is why I thought it worth preserving! [SLPJ]
128 -> TcM s (thing, LIE s, thing_ty))
129 -> TcM s ((TcHsBinds s, thing), LIE s, thing_ty)
131 tcBindsAndThen EmptyBinds do_next
132 = do_next `thenTc` \ (thing, lie, thing_ty) ->
133 returnTc ((EmptyBinds, thing), lie, thing_ty)
135 tcBindsAndThen (SingleBind bind) do_next
136 = tcBindAndThen bind [] do_next
138 tcBindsAndThen (BindWith bind sigs) do_next
139 = tcBindAndThen bind sigs do_next
141 tcBindsAndThen (ThenBinds binds1 binds2) do_next
142 = tcBindsAndThen binds1 (tcBindsAndThen binds2 do_next)
143 `thenTc` \ ((binds1', (binds2', thing')), lie1, thing_ty) ->
145 returnTc ((binds1' `ThenBinds` binds2', thing'), lie1, thing_ty)
149 %************************************************************************
151 \subsection{tcBindWithSigsAndThen}
153 %************************************************************************
155 @tcBindAndThen@ deals with one binding group and the thing it scopes over.
158 tcBindWithSigsAndThen
159 :: (TcHsBinds s -> thing -> thing) -- Combinator
160 -> RenamedBind -- The Bind to typecheck
161 -> [RenamedSig] -- ...and its signatures
162 -> TcM s (thing, LIE s, thing_ty) -- Thing to type check in
164 -> TcM s (thing, LIE s, thing_ty) -- Results, incl the
166 tcBindWithSigsAndThen combiner bind sigs do_next
169 -- If typechecking the binds fails, then return with each
170 -- binder given type (forall a.a), to minimise subsequent
172 newTcTyVar mkBoxedTypeKind `thenNF_Tc` \ alpha_tv ->
174 forall_a_a = mkForAllTy alpha_tv (mkTyVarTy alpha_tv)
175 poly_ids = [ mkUserId name forall_a_a NoPragmaInfo
176 | name <- binder_names]
178 -- Extend the environment to bind the new polymorphic Ids
179 -- and do the thing inside
180 tcExtendLocalValEnv binder_names poly_ids $
184 fixTc (\ ~(prag_info_fn, _) ->
185 -- This is the usual prag_info fix; the PragmaInfo field of an Id
186 -- is not inspected till ages later in the compiler, so there
187 -- should be no black-hole problems here.
188 tcBindWithSigs binder_names bind
189 sigs prag_info_fn `thenTc` \ (poly_binds, poly_lie, poly_ids) ->
191 -- Extend the environment to bind the new polymorphic Ids
192 tcExtendLocalValEnv binder_names poly_ids $
194 -- Build bindings and IdInfos corresponding to user pragmas
195 tcPragmaSigs sigs `thenTc` \ (prag_info_fn, prag_binds, prag_lie) ->
197 -- Now do whatever happens next, in the augmented envt
198 do_next `thenTc` \ (thing, thing_lie, thing_ty) ->
200 -- Create specialisations of functions bound here
201 bindInstsOfLocalFuns (prag_lie `plusLIE` thing_lie)
202 poly_ids `thenTc` \ (lie2, inst_mbinds) ->
206 final_lie = lie2 `plusLIE` poly_lie
207 final_binds = poly_binds `ThenBinds`
208 SingleBind (NonRecBind inst_mbinds) `ThenBinds`
211 returnTc (prag_info_fn, (combiner final_binds thing, final_lie, thing_ty))
212 ) `thenTc` \ (_, result) ->
215 binder_names = map fst (bagToList (collectBinders bind))
219 %************************************************************************
221 \subsection{tcBindWithSigs}
223 %************************************************************************
225 @tcBindWithSigs@ deals with a single binding group. It does generalisation,
226 so all the clever stuff is in here.
229 tcBindWithSigs binder_names bind sigs prag_info_fn
230 = -- Create a new identifier for each binder, with each being given
231 -- a fresh unique, and a type-variable type.
232 tcGetUniques no_of_binders `thenNF_Tc` \ uniqs ->
233 newTyVarTys no_of_binders kind `thenNF_Tc` \ tys ->
235 mono_ids = zipWith3Equal "tcBindAndSigs" mk_id binder_names uniqs tys
236 mk_id name uniq ty = mkUserLocal (getOccName name) uniq ty (getSrcLoc name)
239 -- TYPECHECK THE SIGNATURES
240 mapTc tcTySig ty_sigs `thenTc` \ tc_ty_sigs ->
242 -- TYPECHECK THE BINDINGS
243 tcMonoBinds mbind binder_names mono_ids tc_ty_sigs `thenTc` \ (mbind', lie) ->
245 -- CHECK THAT THE SIGNATURES MATCH
246 -- (must do this before getTyVarsToGen)
247 checkSigMatch (binder_names `zip` mono_ids) tc_ty_sigs `thenTc` \ sig_theta ->
249 -- COMPUTE VARIABLES OVER WHICH TO QUANTIFY, namely tyvars_to_gen
250 -- The tyvars_not_to_gen are free in the environment, and hence
251 -- candidates for generalisation, but sometimes the monomorphism
252 -- restriction means we can't generalise them nevertheless
253 mapNF_Tc (zonkTcType . idType) mono_ids `thenNF_Tc` \ mono_id_types ->
254 getTyVarsToGen is_unrestricted mono_id_types lie `thenTc` \ (tyvars_not_to_gen, tyvars_to_gen) ->
256 tyvars_to_gen_list = tyVarSetToList tyvars_to_gen -- Commit to a particular order
260 tcExtendGlobalTyVars tyvars_not_to_gen (
261 if null tc_ty_sigs then
262 -- No signatures, so just simplify the lie
263 tcSimplify tyvars_to_gen lie `thenTc` \ (lie_free, dict_binds, lie_bound) ->
264 returnTc (lie_free, dict_binds, map instToId (bagToList lie_bound))
267 newDicts SignatureOrigin sig_theta `thenNF_Tc` \ (dicts_sig, dict_ids) ->
268 -- It's important that sig_theta is zonked, because
269 -- dict_id is later used to form the type of the polymorphic thing,
270 -- and forall-types must be zonked so far as their bound variables
273 -- Check that the needed dicts can be expressed in
274 -- terms of the signature ones
275 tcAddErrCtxt (sigsCtxt tysig_names) $
276 tcSimplifyAndCheck tyvars_to_gen dicts_sig lie `thenTc` \ (lie_free, dict_binds) ->
277 returnTc (lie_free, dict_binds, dict_ids)
279 ) `thenTc` \ (lie_free, dict_binds, dicts_bound) ->
281 -- DEAL WITH TYPE VARIABLE KINDS
282 defaultUncommittedTyVars tyvars_to_gen_list `thenTc_`
284 -- BUILD THE POLYMORPHIC RESULT IDs
286 dict_tys = map tcIdType dicts_bound
287 poly_tys = map (mkForAllTys tyvars_to_gen_list . mkFunTys dict_tys) mono_id_types
288 poly_ids = zipWithEqual "genspecetc" mk_poly binder_names poly_tys
289 mk_poly name ty = mkUserId name ty (prag_info_fn name)
292 -- MAKE EXTRA BINDS FOR THE TYPE-SIG POLYMORPHIC VARIABLES
293 -- These are only needed to scope over the right-hand sides of the group,
294 -- and hence aren't needed at all for non-recursive definitions.
296 -- Alas, the polymorphic variables from the type signature can't coincide
297 -- with the poly_ids because the order of their type variables may not be
298 -- the same. These bindings just swizzle the type variables.
300 poly_binds | is_rec_bind = map mk_poly_bind tc_ty_sigs
303 mk_poly_bind (TySigInfo name rhs_poly_id rhs_tyvars _ _ _)
304 = (TcId rhs_poly_id, TyLam rhs_tyvars $
305 TyApp (HsVar (TcId main_poly_id)) $
306 mkTyVarTys tyvars_to_gen_list)
308 main_poly_id = head (filter ((== name) . getName) poly_ids)
312 AbsBinds tyvars_to_gen_list
314 (zipEqual "genBinds" (map TcId mono_ids) (map TcId poly_ids))
315 (poly_binds ++ dict_binds)
321 no_of_binders = length binder_names
323 is_rec_bind = case bind of
324 NonRecBind _ -> False
331 ty_sigs = [sig | sig@(Sig name _ _) <- sigs]
332 tysig_names = [name | (Sig name _ _) <- ty_sigs]
333 is_unrestricted = isUnRestrictedGroup tysig_names mbind
335 kind | is_rec_bind = mkBoxedTypeKind -- Recursive, so no unboxed types
336 | otherwise = mkTypeKind -- Non-recursive, so we permit unboxed types
338 wrap_it mbind | is_rec_bind = RecBind mbind
339 | otherwise = NonRecBind mbind
343 @getImplicitStuffToGen@ decides what type variables generalise over.
345 For a "restricted group" -- see the monomorphism restriction
346 for a definition -- we bind no dictionaries, and
347 remove from tyvars_to_gen any constrained type variables
349 *Don't* simplify dicts at this point, because we aren't going
350 to generalise over these dicts. By the time we do simplify them
351 we may well know more. For example (this actually came up)
353 f x = array ... xs where xs = [1,2,3,4,5]
354 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
355 stuff. If we simplify only at the f-binding (not the xs-binding)
356 we'll know that the literals are all Ints, and we can just produce
359 Find all the type variables involved in overloading, the
360 "constrained_tyvars". These are the ones we *aren't* going to
361 generalise. We must be careful about doing this:
363 (a) If we fail to generalise a tyvar which is not actually
364 constrained, then it will never, ever get bound, and lands
365 up printed out in interface files! Notorious example:
366 instance Eq a => Eq (Foo a b) where ..
367 Here, b is not constrained, even though it looks as if it is.
368 Another, more common, example is when there's a Method inst in
369 the LIE, whose type might very well involve non-overloaded
372 (b) On the other hand, we mustn't generalise tyvars which are constrained,
373 because we are going to pass on out the unmodified LIE, with those
374 tyvars in it. They won't be in scope if we've generalised them.
376 So we are careful, and do a complete simplification just to find the
377 constrained tyvars. We don't use any of the results, except to
378 find which tyvars are constrained.
381 getTyVarsToGen is_unrestricted mono_id_types lie
382 = tcGetGlobalTyVars `thenNF_Tc` \ free_tyvars ->
384 mentioned_tyvars = tyVarsOfTypes mono_id_types
385 tyvars_to_gen = mentioned_tyvars `minusTyVarSet` free_tyvars
389 returnTc (emptyTyVarSet, tyvars_to_gen)
391 tcSimplify tyvars_to_gen lie `thenTc` \ (_, _, constrained_dicts) ->
393 -- ASSERT: dicts_sig is already zonked!
394 constrained_tyvars = foldrBag (unionTyVarSets . tyVarsOfInst) emptyTyVarSet constrained_dicts
395 reduced_tyvars_to_gen = tyvars_to_gen `minusTyVarSet` constrained_tyvars
397 returnTc (constrained_tyvars, reduced_tyvars_to_gen)
402 isUnRestrictedGroup :: [Name] -- Signatures given for these
406 is_elem v vs = isIn "isUnResMono" v vs
408 isUnRestrictedGroup sigs (PatMonoBind (VarPatIn v) _ _) = v `is_elem` sigs
409 isUnRestrictedGroup sigs (PatMonoBind other _ _) = False
410 isUnRestrictedGroup sigs (VarMonoBind v _) = v `is_elem` sigs
411 isUnRestrictedGroup sigs (FunMonoBind _ _ _ _) = True
412 isUnRestrictedGroup sigs (AndMonoBinds mb1 mb2) = isUnRestrictedGroup sigs mb1 &&
413 isUnRestrictedGroup sigs mb2
414 isUnRestrictedGroup sigs EmptyMonoBinds = True
417 @defaultUncommittedTyVars@ checks for generalisation over unboxed
418 types, and defaults any TypeKind TyVars to BoxedTypeKind.
421 defaultUncommittedTyVars tyvars
422 = ASSERT( null unboxed_kind_tyvars ) -- The instCantBeGeneralised stuff in tcSimplify
423 -- should have dealt with unboxed type variables;
424 -- and it's better done there because we have more
425 -- precise origin information.
426 -- That's why we call this *after* simplifying.
427 -- (NB: unboxed tyvars are always introduced along
428 -- with a class constraint.)
430 mapTc box_it unresolved_kind_tyvars
432 unboxed_kind_tyvars = filter (isUnboxedTypeKind . tyVarKind) tyvars
433 unresolved_kind_tyvars = filter (isTypeKind . tyVarKind) tyvars
435 box_it tyvar = newTyVarTy mkBoxedTypeKind `thenNF_Tc` \ boxed_ty ->
436 unifyTauTy boxed_ty (mkTyVarTy tyvar)
440 %************************************************************************
442 \subsection{tcMonoBind}
444 %************************************************************************
446 @tcMonoBinds@ deals with a single @MonoBind@.
447 The signatures have been dealt with already.
450 tcMonoBinds :: RenamedMonoBinds
451 -> [Name] -> [TcIdBndr s]
453 -> TcM s (TcMonoBinds s, LIE s)
455 tcMonoBinds mbind binder_names mono_ids tc_ty_sigs
456 = tcExtendLocalValEnv binder_names mono_ids (
460 sig_names = [name | (TySigInfo name _ _ _ _ _) <- tc_ty_sigs]
461 sig_ids = [id | (TySigInfo _ id _ _ _ _) <- tc_ty_sigs]
463 tc_mono_binds EmptyMonoBinds = returnTc (EmptyMonoBinds, emptyLIE)
465 tc_mono_binds (AndMonoBinds mb1 mb2)
466 = tc_mono_binds mb1 `thenTc` \ (mb1a, lie1) ->
467 tc_mono_binds mb2 `thenTc` \ (mb2a, lie2) ->
468 returnTc (AndMonoBinds mb1a mb2a, lie1 `plusLIE` lie2)
470 tc_mono_binds (FunMonoBind name inf matches locn)
472 tcLookupLocalValueOK "tc_mono_binds" name `thenNF_Tc` \ id ->
474 -- Before checking the RHS, extend the envt with
475 -- bindings for the *polymorphic* Ids from any type signatures
476 tcExtendLocalValEnv sig_names sig_ids $
477 tcMatchesFun name (idType id) matches `thenTc` \ (matches', lie) ->
479 returnTc (FunMonoBind (TcId id) inf matches' locn, lie)
481 tc_mono_binds bind@(PatMonoBind pat grhss_and_binds locn)
483 tcPat pat `thenTc` \ (pat2, lie_pat, pat_ty) ->
484 tcExtendLocalValEnv sig_names sig_ids $
485 tcGRHSsAndBinds grhss_and_binds `thenTc` \ (grhss_and_binds2, lie, grhss_ty) ->
486 tcAddErrCtxt (patMonoBindsCtxt bind) $
487 unifyTauTy pat_ty grhss_ty `thenTc_`
488 returnTc (PatMonoBind pat2 grhss_and_binds2 locn,
492 %************************************************************************
494 \subsection{Signatures}
496 %************************************************************************
498 @tcSigs@ checks the signatures for validity, and returns a list of
499 {\em freshly-instantiated} signatures. That is, the types are already
500 split up, and have fresh type variables installed. All non-type-signature
501 "RenamedSigs" are ignored.
503 The @TcSigInfo@ contains @TcTypes@ because they are unified with
504 the variable's type, and after that checked to see whether they've
510 (TcIdBndr s) -- *Polymorphic* binder for this value...
511 [TcTyVar s] (TcThetaType s) (TcTauType s)
517 tcTySig :: RenamedSig -> TcM s (TcSigInfo s)
519 tcTySig (Sig v ty src_loc)
520 = tcAddSrcLoc src_loc $
521 tcHsType ty `thenTc` \ sigma_ty ->
522 tcGetUnique `thenNF_Tc` \ uniq ->
523 tcInstSigType sigma_ty `thenNF_Tc` \ sigma_ty' ->
525 poly_id = mkUserLocal (getOccName v) uniq sigma_ty' src_loc
526 (tyvars', theta', tau') = splitSigmaTy sigma_ty'
528 returnTc (TySigInfo v poly_id tyvars' theta' tau' src_loc)
531 @checkSigMatch@ does the next step in checking signature matching.
532 The tau-type part has already been unified. What we do here is to
533 check that this unification has not over-constrained the (polymorphic)
534 type variables of the original signature type.
536 The error message here is somewhat unsatisfactory, but it'll do for
540 checkSigMatch binder_names_w_mono_isd []
541 = returnTc (error "checkSigMatch")
543 checkSigMatch binder_names_w_mono_ids tc_ty_sigs
546 -- CHECK THAT THE SIGNATURE TYVARS AND TAU_TYPES ARE OK
547 -- Doesn't affect substitution
548 mapTc check_one_sig tc_ty_sigs `thenTc_`
550 -- CHECK THAT ALL THE SIGNATURE CONTEXTS ARE IDENTICAL
551 -- The type signatures on a mutually-recursive group of definitions
552 -- must all have the same context (or none).
553 -- We have to zonk them first to make their type variables line up
554 mapNF_Tc get_zonked_theta tc_ty_sigs `thenNF_Tc` \ (theta:thetas) ->
555 checkTc (all (eqSimpleTheta theta) thetas)
556 (sigContextsErr tc_ty_sigs) `thenTc_`
560 check_one_sig (TySigInfo name id sig_tyvars _ sig_tau src_loc)
561 = tcAddSrcLoc src_loc $
562 tcAddErrCtxt (sigCtxt id) $
563 unifyTauTy sig_tau mono_id_ty `thenTc_`
564 checkSigTyVars sig_tyvars sig_tau
566 mono_id_ty = idType (assoc "checkSigMatch" binder_names_w_mono_ids name)
568 get_zonked_theta (TySigInfo _ _ _ theta _ _)
569 = mapNF_Tc (\ (c,t) -> zonkTcType t `thenNF_Tc` \ t' -> returnNF_Tc (c,t')) theta
573 @checkSigTyVars@ is used after the type in a type signature has been unified with
574 the actual type found. It then checks that the type variables of the type signature
576 (a) still all type variables
577 eg matching signature [a] against inferred type [(p,q)]
578 [then a will be unified to a non-type variable]
580 (b) still all distinct
581 eg matching signature [(a,b)] against inferred type [(p,p)]
582 [then a and b will be unified together]
584 BUT ACTUALLY THESE FIRST TWO ARE FORCED BY USING DontBind TYVARS
586 (c) not mentioned in the environment
587 eg the signature for f in this:
593 Here, f is forced to be monorphic by the free occurence of x.
595 Before doing this, the substitution is applied to the signature type variable.
598 checkSigTyVars :: [TcTyVar s] -- The original signature type variables
599 -> TcType s -- signature type (for err msg)
602 checkSigTyVars sig_tyvars sig_tau
603 = tcGetGlobalTyVars `thenNF_Tc` \ globals ->
605 mono_tyvars = filter (`elementOfTyVarSet` globals) sig_tyvars
608 -- Until the final Bind-handling stuff is in, several type signatures in the same
609 -- bindings group can cause the signature type variable from the different
610 -- signatures to be unified. So we still need to zonk and check point (b).
611 -- Remove when activating the new binding code
612 mapNF_Tc zonkTcTyVar sig_tyvars `thenNF_Tc` \ sig_tys ->
613 checkTcM (hasNoDups (map (getTyVar "checkSigTyVars") sig_tys))
614 (zonkTcType sig_tau `thenNF_Tc` \ sig_tau' ->
615 failTc (badMatchErr sig_tau sig_tau')
620 -- We want to report errors in terms of the original signature tyvars,
621 -- ie sig_tyvars, NOT sig_tyvars'. sig_tys and sig_tyvars' correspond
622 -- 1-1 with sig_tyvars, so we can just map back.
623 checkTc (null mono_tyvars)
624 (notAsPolyAsSigErr sig_tau mono_tyvars)
628 %************************************************************************
630 \subsection{SPECIALIZE pragmas}
632 %************************************************************************
635 @tcPragmaSigs@ munches up the "signatures" that arise through *user*
636 pragmas. It is convenient for them to appear in the @[RenamedSig]@
637 part of a binding because then the same machinery can be used for
638 moving them into place as is done for type signatures.
641 tcPragmaSigs :: [RenamedSig] -- The pragma signatures
642 -> TcM s (Name -> PragmaInfo, -- Maps name to the appropriate PragmaInfo
646 tcPragmaSigs sigs = returnTc ( \name -> NoPragmaInfo, EmptyBinds, emptyLIE )
650 = mapAndUnzip3Tc tcPragmaSig sigs `thenTc` \ (names_w_id_infos, binds, lies) ->
652 name_to_info name = foldr ($) noIdInfo
653 [info_fn | (n,info_fn) <- names_w_id_infos, n==name]
655 returnTc (name_to_info,
656 foldr ThenBinds EmptyBinds binds,
657 foldr plusLIE emptyLIE lies)
660 Here are the easy cases for tcPragmaSigs
663 tcPragmaSig (DeforestSig name loc)
664 = returnTc ((name, addDeforestInfo DoDeforest),EmptyBinds,emptyLIE)
665 tcPragmaSig (InlineSig name loc)
666 = returnTc ((name, addUnfoldInfo (iWantToBeINLINEd UnfoldAlways)), EmptyBinds, emptyLIE)
667 tcPragmaSig (MagicUnfoldingSig name string loc)
668 = returnTc ((name, addUnfoldInfo (mkMagicUnfolding string)), EmptyBinds, emptyLIE)
671 The interesting case is for SPECIALISE pragmas. There are two forms.
672 Here's the first form:
674 f :: Ord a => [a] -> b -> b
675 {-# SPECIALIZE f :: [Int] -> b -> b #-}
678 For this we generate:
680 f* = /\ b -> let d1 = ...
684 where f* is a SpecPragmaId. The **sole** purpose of SpecPragmaIds is to
685 retain a right-hand-side that the simplifier will otherwise discard as
686 dead code... the simplifier has a flag that tells it not to discard
687 SpecPragmaId bindings.
689 In this case the f* retains a call-instance of the overloaded
690 function, f, (including appropriate dictionaries) so that the
691 specialiser will subsequently discover that there's a call of @f@ at
692 Int, and will create a specialisation for @f@. After that, the
693 binding for @f*@ can be discarded.
695 The second form is this:
697 f :: Ord a => [a] -> b -> b
698 {-# SPECIALIZE f :: [Int] -> b -> b = g #-}
701 Here @g@ is specified as a function that implements the specialised
702 version of @f@. Suppose that g has type (a->b->b); that is, g's type
703 is more general than that required. For this we generate
705 f@Int = /\b -> g Int b
709 Here @f@@Int@ is a SpecId, the specialised version of @f@. It inherits
710 f's export status etc. @f*@ is a SpecPragmaId, as before, which just serves
711 to prevent @f@@Int@ from being discarded prematurely. After specialisation,
712 if @f@@Int@ is going to be used at all it will be used explicitly, so the simplifier can
713 discard the f* binding.
715 Actually, there is really only point in giving a SPECIALISE pragma on exported things,
716 and the simplifer won't discard SpecIds for exporte things anyway, so maybe this is
720 tcPragmaSig (SpecSig name poly_ty maybe_spec_name src_loc)
721 = tcAddSrcLoc src_loc $
722 tcAddErrCtxt (valSpecSigCtxt name spec_ty) $
724 -- Get and instantiate its alleged specialised type
725 tcHsType poly_ty `thenTc` \ sig_sigma ->
726 tcInstSigType sig_sigma `thenNF_Tc` \ sig_ty ->
728 (sig_tyvars, sig_theta, sig_tau) = splitSigmaTy sig_ty
729 origin = ValSpecOrigin name
732 -- Check that the SPECIALIZE pragma had an empty context
733 checkTc (null sig_theta)
734 (panic "SPECIALIZE non-empty context (ToDo: msg)") `thenTc_`
736 -- Get and instantiate the type of the id mentioned
737 tcLookupLocalValueOK "tcPragmaSig" name `thenNF_Tc` \ main_id ->
738 tcInstSigType [] (idType main_id) `thenNF_Tc` \ main_ty ->
740 (main_tyvars, main_rho) = splitForAllTy main_ty
741 (main_theta,main_tau) = splitRhoTy main_rho
742 main_arg_tys = mkTyVarTys main_tyvars
745 -- Check that the specialised type is indeed an instance of
746 -- the type of the main function.
747 unifyTauTy sig_tau main_tau `thenTc_`
748 checkSigTyVars sig_tyvars sig_tau `thenTc_`
750 -- Check that the type variables of the polymorphic function are
751 -- either left polymorphic, or instantiate to ground type.
752 -- Also check that the overloaded type variables are instantiated to
753 -- ground type; or equivalently that all dictionaries have ground type
754 mapTc zonkTcType main_arg_tys `thenNF_Tc` \ main_arg_tys' ->
755 zonkTcThetaType main_theta `thenNF_Tc` \ main_theta' ->
756 tcAddErrCtxt (specGroundnessCtxt main_arg_tys')
757 (checkTc (all isGroundOrTyVarTy main_arg_tys')) `thenTc_`
758 tcAddErrCtxt (specContextGroundnessCtxt main_theta')
759 (checkTc (and [isGroundTy ty | (_,ty) <- theta'])) `thenTc_`
761 -- Build the SpecPragmaId; it is the thing that makes sure we
762 -- don't prematurely dead-code-eliminate the binding we are really interested in.
763 newSpecPragmaId name sig_ty `thenNF_Tc` \ spec_pragma_id ->
765 -- Build a suitable binding; depending on whether we were given
766 -- a value (Maybe Name) to be used as the specialisation.
768 Nothing -> -- No implementation function specified
770 -- Make a Method inst for the occurrence of the overloaded function
771 newMethodWithGivenTy (OccurrenceOf name)
772 (TcId main_id) main_arg_tys main_rho `thenNF_Tc` \ (lie, meth_id) ->
775 pseudo_bind = VarMonoBind spec_pragma_id pseudo_rhs
776 pseudo_rhs = mkHsTyLam sig_tyvars (HsVar (TcId meth_id))
778 returnTc (pseudo_bind, lie, \ info -> info)
780 Just spec_name -> -- Use spec_name as the specialisation value ...
782 -- Type check a simple occurrence of the specialised Id
783 tcId spec_name `thenTc` \ (spec_body, spec_lie, spec_tau) ->
785 -- Check that it has the correct type, and doesn't constrain the
786 -- signature variables at all
787 unifyTauTy sig_tau spec_tau `thenTc_`
788 checkSigTyVars sig_tyvars sig_tau `thenTc_`
790 -- Make a local SpecId to bind to applied spec_id
791 newSpecId main_id main_arg_tys sig_ty `thenNF_Tc` \ local_spec_id ->
794 spec_rhs = mkHsTyLam sig_tyvars spec_body
795 spec_binds = VarMonoBind local_spec_id spec_rhs
797 VarMonoBind spec_pragma_id (HsVar (TcId local_spec_id))
798 spec_info = SpecInfo spec_tys (length main_theta) local_spec_id
800 returnTc ((name, addSpecInfo spec_info), spec_binds, spec_lie)
805 %************************************************************************
807 \subsection[TcBinds-errors]{Error contexts and messages}
809 %************************************************************************
813 patMonoBindsCtxt bind sty
814 = ppHang (ppPStr SLIT("In a pattern binding:")) 4 (ppr sty bind)
816 -----------------------------------------------
817 valSpecSigCtxt v ty sty
818 = ppHang (ppPStr SLIT("In a SPECIALIZE pragma for a value:"))
819 4 (ppSep [ppBeside (pprNonSym sty v) (ppPStr SLIT(" ::")),
824 -----------------------------------------------
825 notAsPolyAsSigErr sig_tau mono_tyvars sty
826 = ppHang (ppPStr SLIT("A type signature is more polymorphic than the inferred type"))
827 4 (ppAboves [ppStr "Some type variables in the inferred type can't be forall'd, namely:",
828 interpp'SP sty mono_tyvars,
829 ppPStr SLIT("Possible cause: the RHS mentions something subject to the monomorphism restriction")
832 -----------------------------------------------
833 badMatchErr sig_ty inferred_ty sty
834 = ppHang (ppPStr SLIT("Type signature doesn't match inferred type"))
835 4 (ppAboves [ppHang (ppPStr SLIT("Signature:")) 4 (ppr sty sig_ty),
836 ppHang (ppPStr SLIT("Inferred :")) 4 (ppr sty inferred_ty)
839 -----------------------------------------------
841 = ppSep [ppPStr SLIT("When checking signature for"), ppr sty id]
843 = ppSep [ppPStr SLIT("When checking signature(s) for:"), interpp'SP sty ids]
845 -----------------------------------------------
846 sigContextsErr ty_sigs sty
847 = ppHang (ppPStr SLIT("A group of type signatures have mismatched contexts"))
848 4 (ppAboves (map ppr_tc_ty_sig ty_sigs))
850 ppr_tc_ty_sig (TySigInfo val _ tyvars theta tau_ty _)
851 = ppHang (ppBeside (ppr sty val) (ppPStr SLIT(" :: ")))
854 else ppBesides [ppChar '(',
855 ppIntersperse (ppStr ", ") (map (ppr_inst sty) theta),
857 ppr_inst sty (clas, ty) = ppCat [ppr sty clas, ppr sty ty]
859 -----------------------------------------------
861 = panic "specGroundnessCtxt"
863 --------------------------------------------
864 specContextGroundnessCtxt -- err_ctxt dicts sty
865 = panic "specContextGroundnessCtxt"
868 ppSep [ppBesides [ppPStr SLIT("In the SPECIALIZE pragma for `"), ppr sty name, ppChar '\''],
869 ppBesides [ppPStr SLIT(" specialised to the type `"), ppr sty spec_ty, ppChar '\''],
871 ppPStr SLIT("... not all overloaded type variables were instantiated"),
872 ppPStr SLIT("to ground types:")])
873 4 (ppAboves [ppCat [ppr sty c, ppr sty t]
874 | (c,t) <- map getDictClassAndType dicts])
876 (name, spec_ty, locn, pp_spec_id)
878 ValSpecSigCtxt n ty loc -> (n, ty, loc, \ x -> ppNil)
879 ValSpecSpecIdCtxt n ty spec loc ->
881 \ sty -> ppBesides [ppPStr SLIT("... type of explicit id `"), ppr sty spec, ppChar '\''])