2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[TcBinds]{TcBinds}
7 #include "HsVersions.h"
9 module TcBinds ( tcBindsAndThen, tcPragmaSigs, checkSigTyVars, tcBindWithSigs, TcSigInfo(..) ) where
12 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ <= 201
13 IMPORT_DELOOPER(TcLoop) ( tcGRHSsAndBinds )
15 import {-# SOURCE #-} TcGRHSs ( tcGRHSsAndBinds )
18 import HsSyn ( HsBinds(..), Sig(..), MonoBinds(..),
19 Match, HsType, InPat(..), OutPat(..), HsExpr(..),
20 SYN_IE(RecFlag), nonRecursive,
21 GRHSsAndBinds, ArithSeqInfo, HsLit, Fake, Stmt, DoOrListComp, Fixity,
23 import RnHsSyn ( SYN_IE(RenamedHsBinds), RenamedSig(..),
24 SYN_IE(RenamedMonoBinds)
26 import TcHsSyn ( SYN_IE(TcHsBinds), SYN_IE(TcMonoBinds),
32 import Inst ( Inst, SYN_IE(LIE), emptyLIE, plusLIE, plusLIEs, InstOrigin(..),
33 newDicts, tyVarsOfInst, instToId, newMethodWithGivenTy
35 import TcEnv ( tcExtendLocalValEnv, tcLookupLocalValueOK, newLocalId,
36 tcGetGlobalTyVars, tcExtendGlobalTyVars
38 import SpecEnv ( SpecEnv )
39 import TcMatches ( tcMatchesFun )
40 import TcSimplify ( tcSimplify, tcSimplifyAndCheck )
41 import TcMonoType ( tcHsType )
42 import TcPat ( tcPat )
43 import TcSimplify ( bindInstsOfLocalFuns )
44 import TcType ( TcIdOcc(..), SYN_IE(TcIdBndr),
45 SYN_IE(TcType), SYN_IE(TcThetaType), SYN_IE(TcTauType),
46 SYN_IE(TcTyVarSet), SYN_IE(TcTyVar),
47 newTyVarTy, zonkTcType, zonkTcTheta, zonkSigTyVar,
48 newTcTyVar, tcInstSigType, newTyVarTys
50 import Unify ( unifyTauTy, unifyTauTyLists )
52 import Kind ( isUnboxedTypeKind, mkTypeKind, isTypeKind, mkBoxedTypeKind )
53 import Id ( GenId, idType, mkUserId )
54 import IdInfo ( noIdInfo )
55 import Maybes ( maybeToBool, assocMaybe, catMaybes )
56 import Name ( getOccName, getSrcLoc, Name )
57 import PragmaInfo ( PragmaInfo(..) )
59 import Type ( mkTyVarTy, mkTyVarTys, isTyVarTy, tyVarsOfTypes, eqSimpleTheta,
60 mkSigmaTy, splitSigmaTy, mkForAllTys, mkFunTys, getTyVar, mkDictTy,
61 splitRhoTy, mkForAllTy, splitForAllTy )
62 import TyVar ( GenTyVar, SYN_IE(TyVar), tyVarKind, mkTyVarSet, minusTyVarSet, emptyTyVarSet,
63 elementOfTyVarSet, unionTyVarSets, tyVarSetToList )
64 import Bag ( bagToList, foldrBag, isEmptyBag )
65 import Util ( isIn, zipEqual, zipWithEqual, zipWith3Equal, hasNoDups, assoc,
66 assertPanic, panic, pprTrace )
67 import PprType ( GenClass, GenType, GenTyVar )
68 import Unique ( Unique )
69 import SrcLoc ( SrcLoc )
71 import Outputable --( interppSP, interpp'SP )
77 %************************************************************************
79 \subsection{Type-checking bindings}
81 %************************************************************************
83 @tcBindsAndThen@ typechecks a @HsBinds@. The "and then" part is because
84 it needs to know something about the {\em usage} of the things bound,
85 so that it can create specialisations of them. So @tcBindsAndThen@
86 takes a function which, given an extended environment, E, typechecks
87 the scope of the bindings returning a typechecked thing and (most
88 important) an LIE. It is this LIE which is then used as the basis for
89 specialising the things bound.
91 @tcBindsAndThen@ also takes a "combiner" which glues together the
92 bindings and the "thing" to make a new "thing".
94 The real work is done by @tcBindWithSigsAndThen@.
96 Recursive and non-recursive binds are handled in essentially the same
97 way: because of uniques there are no scoping issues left. The only
98 difference is that non-recursive bindings can bind primitive values.
100 Even for non-recursive binding groups we add typings for each binder
101 to the LVE for the following reason. When each individual binding is
102 checked the type of its LHS is unified with that of its RHS; and
103 type-checking the LHS of course requires that the binder is in scope.
105 At the top-level the LIE is sure to contain nothing but constant
106 dictionaries, which we resolve at the module level.
110 :: (RecFlag -> TcMonoBinds s -> thing -> thing) -- Combinator
112 -> TcM s (thing, LIE s)
113 -> TcM s (thing, LIE s)
115 tcBindsAndThen combiner EmptyBinds do_next
116 = do_next `thenTc` \ (thing, lie) ->
117 returnTc (combiner nonRecursive EmptyMonoBinds thing, lie)
119 tcBindsAndThen combiner (ThenBinds binds1 binds2) do_next
120 = tcBindsAndThen combiner binds1 (tcBindsAndThen combiner binds2 do_next)
122 tcBindsAndThen combiner (MonoBind bind sigs is_rec) do_next
123 = fixTc (\ ~(prag_info_fn, _) ->
124 -- This is the usual prag_info fix; the PragmaInfo field of an Id
125 -- is not inspected till ages later in the compiler, so there
126 -- should be no black-hole problems here.
128 -- TYPECHECK THE SIGNATURES
129 mapTc (tcTySig prag_info_fn) ty_sigs `thenTc` \ tc_ty_sigs ->
131 tcBindWithSigs binder_names bind
132 tc_ty_sigs is_rec prag_info_fn `thenTc` \ (poly_binds, poly_lie, poly_ids) ->
134 -- Extend the environment to bind the new polymorphic Ids
135 tcExtendLocalValEnv binder_names poly_ids $
137 -- Build bindings and IdInfos corresponding to user pragmas
138 tcPragmaSigs sigs `thenTc` \ (prag_info_fn, prag_binds, prag_lie) ->
140 -- Now do whatever happens next, in the augmented envt
141 do_next `thenTc` \ (thing, thing_lie) ->
143 -- Create specialisations of functions bound here
144 bindInstsOfLocalFuns (prag_lie `plusLIE` thing_lie)
145 poly_ids `thenTc` \ (lie2, inst_mbinds) ->
149 final_lie = lie2 `plusLIE` poly_lie
150 final_thing = combiner is_rec poly_binds $
151 combiner nonRecursive inst_mbinds $
152 combiner nonRecursive prag_binds
155 returnTc (prag_info_fn, (final_thing, final_lie))
156 ) `thenTc` \ (_, result) ->
159 binder_names = map fst (bagToList (collectMonoBinders bind))
160 ty_sigs = [sig | sig@(Sig name _ _) <- sigs]
163 An aside. The original version of @tcBindsAndThen@ which lacks a
164 combiner function, appears below. Though it is perfectly well
165 behaved, it cannot be typed by Haskell, because the recursive call is
166 at a different type to the definition itself. There aren't too many
167 examples of this, which is why I thought it worth preserving! [SLPJ]
172 -> TcM s (thing, LIE s, thing_ty))
173 -> TcM s ((TcHsBinds s, thing), LIE s, thing_ty)
175 tcBindsAndThen EmptyBinds do_next
176 = do_next `thenTc` \ (thing, lie, thing_ty) ->
177 returnTc ((EmptyBinds, thing), lie, thing_ty)
179 tcBindsAndThen (ThenBinds binds1 binds2) do_next
180 = tcBindsAndThen binds1 (tcBindsAndThen binds2 do_next)
181 `thenTc` \ ((binds1', (binds2', thing')), lie1, thing_ty) ->
183 returnTc ((binds1' `ThenBinds` binds2', thing'), lie1, thing_ty)
185 tcBindsAndThen (MonoBind bind sigs is_rec) do_next
186 = tcBindAndThen bind sigs do_next
190 %************************************************************************
192 \subsection{tcBindWithSigs}
194 %************************************************************************
196 @tcBindWithSigs@ deals with a single binding group. It does generalisation,
197 so all the clever stuff is in here.
199 * binder_names and mbind must define the same set of Names
201 * The Names in tc_ty_sigs must be a subset of binder_names
203 * The Ids in tc_ty_sigs don't necessarily have to have the same name
204 as the Name in the tc_ty_sig
212 -> (Name -> PragmaInfo)
213 -> TcM s (TcMonoBinds s, LIE s, [TcIdBndr s])
215 tcBindWithSigs binder_names mbind tc_ty_sigs is_rec prag_info_fn
217 -- If typechecking the binds fails, then return with each
218 -- signature-less binder given type (forall a.a), to minimise subsequent
220 newTcTyVar mkBoxedTypeKind `thenNF_Tc` \ alpha_tv ->
222 forall_a_a = mkForAllTy alpha_tv (mkTyVarTy alpha_tv)
223 poly_ids = map mk_dummy binder_names
224 mk_dummy name = case maybeSig tc_ty_sigs name of
225 Just (TySigInfo _ poly_id _ _ _ _) -> poly_id -- Signature
226 Nothing -> mkUserId name forall_a_a NoPragmaInfo -- No signature
228 returnTc (EmptyMonoBinds, emptyLIE, poly_ids)
231 -- Create a new identifier for each binder, with each being given
232 -- a fresh unique, and a type-variable type.
233 -- For "mono_lies" see comments about polymorphic recursion at the
234 -- end of the function.
235 mapAndUnzipNF_Tc mk_mono_id binder_names `thenNF_Tc` \ (mono_lies, mono_ids) ->
237 mono_lie = plusLIEs mono_lies
238 mono_id_tys = map idType mono_ids
241 -- TYPECHECK THE BINDINGS
242 tcMonoBinds mbind binder_names mono_ids tc_ty_sigs `thenTc` \ (mbind', lie) ->
244 -- CHECK THAT THE SIGNATURES MATCH
245 -- (must do this before getTyVarsToGen)
246 checkSigMatch tc_ty_sigs `thenTc` \ sig_theta ->
248 -- COMPUTE VARIABLES OVER WHICH TO QUANTIFY, namely tyvars_to_gen
249 -- The tyvars_not_to_gen are free in the environment, and hence
250 -- candidates for generalisation, but sometimes the monomorphism
251 -- restriction means we can't generalise them nevertheless
252 getTyVarsToGen is_unrestricted mono_id_tys lie `thenTc` \ (tyvars_not_to_gen, tyvars_to_gen) ->
254 -- DEAL WITH TYPE VARIABLE KINDS
255 mapTc defaultUncommittedTyVar
256 (tyVarSetToList tyvars_to_gen) `thenTc` \ real_tyvars_to_gen_list ->
258 real_tyvars_to_gen = mkTyVarSet real_tyvars_to_gen_list
259 -- It's important that the final list
260 -- (real_tyvars_to_gen and real_tyvars_to_gen_list) is fully
261 -- zonked, *including boxity*, because they'll be included in the forall types of
262 -- the polymorphic Ids, and instances of these Ids will be generated from them.
264 -- Also NB that tcSimplify takes zonked tyvars as its arg, hence we pass
265 -- real_tyvars_to_gen
267 -- **** This step can do unification => keep other zonking after this ****
271 tcExtendGlobalTyVars tyvars_not_to_gen (
272 if null tc_ty_sigs then
273 -- No signatures, so just simplify the lie
274 -- NB: no signatures => no polymorphic recursion, so no
275 -- need to use mono_lies (which will be empty anyway)
276 tcSimplify real_tyvars_to_gen lie `thenTc` \ (lie_free, dict_binds, lie_bound) ->
277 returnTc (lie_free, dict_binds, map instToId (bagToList lie_bound))
280 zonkTcTheta sig_theta `thenNF_Tc` \ sig_theta' ->
281 newDicts SignatureOrigin sig_theta' `thenNF_Tc` \ (dicts_sig, dict_ids) ->
282 -- It's important that sig_theta is zonked, because
283 -- dict_id is later used to form the type of the polymorphic thing,
284 -- and forall-types must be zonked so far as their bound variables
288 -- The "givens" is the stuff available. We get that from
289 -- the context of the type signature, BUT ALSO the mono_lie
290 -- so that polymorphic recursion works right (see comments at end of fn)
291 givens = dicts_sig `plusLIE` mono_lie
294 -- Check that the needed dicts can be expressed in
295 -- terms of the signature ones
296 tcAddErrCtxt (sigsCtxt tysig_names) $
297 tcSimplifyAndCheck real_tyvars_to_gen givens lie `thenTc` \ (lie_free, dict_binds) ->
298 returnTc (lie_free, dict_binds, dict_ids)
300 ) `thenTc` \ (lie_free, dict_binds, dicts_bound) ->
302 ASSERT( not (any (isUnboxedTypeKind . tyVarKind) real_tyvars_to_gen_list) )
303 -- The instCantBeGeneralised stuff in tcSimplify should have
304 -- already raised an error if we're trying to generalise an unboxed tyvar
305 -- (NB: unboxed tyvars are always introduced along with a class constraint)
306 -- and it's better done there because we have more precise origin information.
307 -- That's why we just use an ASSERT here.
309 -- BUILD THE POLYMORPHIC RESULT IDs
310 mapNF_Tc zonkTcType mono_id_tys `thenNF_Tc` \ zonked_mono_id_types ->
312 exports = zipWith3 mk_export binder_names mono_ids zonked_mono_id_types
313 dict_tys = map tcIdType dicts_bound
315 mk_export binder_name mono_id zonked_mono_id_ty
316 | maybeToBool maybe_sig = (sig_tyvars, TcId sig_poly_id, TcId mono_id)
317 | otherwise = (real_tyvars_to_gen_list, TcId poly_id, TcId mono_id)
319 maybe_sig = maybeSig tc_ty_sigs binder_name
320 Just (TySigInfo _ sig_poly_id sig_tyvars _ _ _) = maybe_sig
321 poly_id = mkUserId binder_name poly_ty (prag_info_fn binder_name)
322 poly_ty = mkForAllTys real_tyvars_to_gen_list $ mkFunTys dict_tys $ zonked_mono_id_ty
323 -- It's important to build a fully-zonked poly_ty, because
324 -- we'll slurp out its free type variables when extending the
325 -- local environment (tcExtendLocalValEnv); if it's not zonked
326 -- it appears to have free tyvars that aren't actually free at all.
331 AbsBinds real_tyvars_to_gen_list
334 (dict_binds `AndMonoBinds` mbind'),
336 [poly_id | (_, TcId poly_id, _) <- exports]
339 no_of_binders = length binder_names
341 mk_mono_id binder_name
342 | theres_a_signature -- There's a signature; and it's overloaded,
343 && not (null sig_theta) -- so make a Method
344 = tcAddSrcLoc sig_loc $
345 newMethodWithGivenTy SignatureOrigin
346 (TcId poly_id) (mkTyVarTys sig_tyvars)
347 sig_theta sig_tau `thenNF_Tc` \ (mono_lie, TcId mono_id) ->
348 -- A bit turgid to have to strip the TcId
349 returnNF_Tc (mono_lie, mono_id)
351 | otherwise -- No signature or not overloaded;
352 = tcAddSrcLoc (getSrcLoc binder_name) $
353 (if theres_a_signature then
354 returnNF_Tc sig_tau -- Non-overloaded signature; use its type
356 newTyVarTy kind -- No signature; use a new type variable
357 ) `thenNF_Tc` \ mono_id_ty ->
359 newLocalId (getOccName binder_name) mono_id_ty `thenNF_Tc` \ mono_id ->
360 returnNF_Tc (emptyLIE, mono_id)
362 maybe_sig = maybeSig tc_ty_sigs binder_name
363 theres_a_signature = maybeToBool maybe_sig
364 Just (TySigInfo name poly_id sig_tyvars sig_theta sig_tau sig_loc) = maybe_sig
366 tysig_names = [name | (TySigInfo name _ _ _ _ _) <- tc_ty_sigs]
367 is_unrestricted = isUnRestrictedGroup tysig_names mbind
369 kind | is_rec = mkBoxedTypeKind -- Recursive, so no unboxed types
370 | otherwise = mkTypeKind -- Non-recursive, so we permit unboxed types
373 Polymorphic recursion
374 ~~~~~~~~~~~~~~~~~~~~~
375 The game plan for polymorphic recursion in the code above is
377 * Bind any variable for which we have a type signature
378 to an Id with a polymorphic type. Then when type-checking
379 the RHSs we'll make a full polymorphic call.
381 This fine, but if you aren't a bit careful you end up with a horrendous
382 amount of partial application and (worse) a huge space leak. For example:
384 f :: Eq a => [a] -> [a]
387 If we don't take care, after typechecking we get
389 f = /\a -> \d::Eq a -> let f' = f a d
393 Notice the the stupid construction of (f a d), which is of course
394 identical to the function we're executing. In this case, the
395 polymorphic recursion ins't being used (but that's a very common case).
397 This can lead to a massive space leak, from the following top-level defn:
402 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
403 f' is another thunk which evaluates to the same thing... and you end
404 up with a chain of identical values all hung onto by the CAF ff.
406 Solution: when typechecking the RHSs we always have in hand the
407 *monomorphic* Ids for each binding. So we just need to make sure that
408 if (Method f a d) shows up in the constraints emerging from (...f...)
409 we just use the monomorphic Id. We achieve this by adding monomorphic Ids
410 to the "givens" when simplifying constraints. Thats' what the "mono_lies"
414 %************************************************************************
416 \subsection{getTyVarsToGen}
418 %************************************************************************
420 @getTyVarsToGen@ decides what type variables generalise over.
422 For a "restricted group" -- see the monomorphism restriction
423 for a definition -- we bind no dictionaries, and
424 remove from tyvars_to_gen any constrained type variables
426 *Don't* simplify dicts at this point, because we aren't going
427 to generalise over these dicts. By the time we do simplify them
428 we may well know more. For example (this actually came up)
430 f x = array ... xs where xs = [1,2,3,4,5]
431 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
432 stuff. If we simplify only at the f-binding (not the xs-binding)
433 we'll know that the literals are all Ints, and we can just produce
436 Find all the type variables involved in overloading, the
437 "constrained_tyvars". These are the ones we *aren't* going to
438 generalise. We must be careful about doing this:
440 (a) If we fail to generalise a tyvar which is not actually
441 constrained, then it will never, ever get bound, and lands
442 up printed out in interface files! Notorious example:
443 instance Eq a => Eq (Foo a b) where ..
444 Here, b is not constrained, even though it looks as if it is.
445 Another, more common, example is when there's a Method inst in
446 the LIE, whose type might very well involve non-overloaded
449 (b) On the other hand, we mustn't generalise tyvars which are constrained,
450 because we are going to pass on out the unmodified LIE, with those
451 tyvars in it. They won't be in scope if we've generalised them.
453 So we are careful, and do a complete simplification just to find the
454 constrained tyvars. We don't use any of the results, except to
455 find which tyvars are constrained.
458 getTyVarsToGen is_unrestricted mono_id_tys lie
459 = tcGetGlobalTyVars `thenNF_Tc` \ free_tyvars ->
460 mapNF_Tc zonkTcType mono_id_tys `thenNF_Tc` \ zonked_mono_id_tys ->
462 tyvars_to_gen = tyVarsOfTypes zonked_mono_id_tys `minusTyVarSet` free_tyvars
466 returnTc (emptyTyVarSet, tyvars_to_gen)
468 tcSimplify tyvars_to_gen lie `thenTc` \ (_, _, constrained_dicts) ->
470 -- ASSERT: dicts_sig is already zonked!
471 constrained_tyvars = foldrBag (unionTyVarSets . tyVarsOfInst) emptyTyVarSet constrained_dicts
472 reduced_tyvars_to_gen = tyvars_to_gen `minusTyVarSet` constrained_tyvars
474 returnTc (constrained_tyvars, reduced_tyvars_to_gen)
479 isUnRestrictedGroup :: [Name] -- Signatures given for these
483 is_elem v vs = isIn "isUnResMono" v vs
485 isUnRestrictedGroup sigs (PatMonoBind (VarPatIn v) _ _) = v `is_elem` sigs
486 isUnRestrictedGroup sigs (PatMonoBind other _ _) = False
487 isUnRestrictedGroup sigs (VarMonoBind v _) = v `is_elem` sigs
488 isUnRestrictedGroup sigs (FunMonoBind _ _ _ _) = True
489 isUnRestrictedGroup sigs (AndMonoBinds mb1 mb2) = isUnRestrictedGroup sigs mb1 &&
490 isUnRestrictedGroup sigs mb2
491 isUnRestrictedGroup sigs EmptyMonoBinds = True
494 @defaultUncommittedTyVar@ checks for generalisation over unboxed
495 types, and defaults any TypeKind TyVars to BoxedTypeKind.
498 defaultUncommittedTyVar tyvar
499 | isTypeKind (tyVarKind tyvar)
500 = newTcTyVar mkBoxedTypeKind `thenNF_Tc` \ boxed_tyvar ->
501 unifyTauTy (mkTyVarTy boxed_tyvar) (mkTyVarTy tyvar) `thenTc_`
509 %************************************************************************
511 \subsection{tcMonoBind}
513 %************************************************************************
515 @tcMonoBinds@ deals with a single @MonoBind@.
516 The signatures have been dealt with already.
519 tcMonoBinds :: RenamedMonoBinds
520 -> [Name] -> [TcIdBndr s]
522 -> TcM s (TcMonoBinds s, LIE s)
524 tcMonoBinds mbind binder_names mono_ids tc_ty_sigs
525 = tcExtendLocalValEnv binder_names mono_ids (
529 sig_names = [name | (TySigInfo name _ _ _ _ _) <- tc_ty_sigs]
530 sig_ids = [id | (TySigInfo _ id _ _ _ _) <- tc_ty_sigs]
532 tc_mono_binds EmptyMonoBinds = returnTc (EmptyMonoBinds, emptyLIE)
534 tc_mono_binds (AndMonoBinds mb1 mb2)
535 = tc_mono_binds mb1 `thenTc` \ (mb1a, lie1) ->
536 tc_mono_binds mb2 `thenTc` \ (mb2a, lie2) ->
537 returnTc (AndMonoBinds mb1a mb2a, lie1 `plusLIE` lie2)
539 tc_mono_binds (FunMonoBind name inf matches locn)
541 tcLookupLocalValueOK "tc_mono_binds" name `thenNF_Tc` \ id ->
543 -- Before checking the RHS, extend the envt with
544 -- bindings for the *polymorphic* Ids from any type signatures
545 tcExtendLocalValEnv sig_names sig_ids $
546 tcMatchesFun name (idType id) matches `thenTc` \ (matches', lie) ->
548 returnTc (FunMonoBind (TcId id) inf matches' locn, lie)
550 tc_mono_binds bind@(PatMonoBind pat grhss_and_binds locn)
552 tcAddErrCtxt (patMonoBindsCtxt bind) $
553 tcPat pat `thenTc` \ (pat2, lie_pat, pat_ty) ->
555 -- Before checking the RHS, but after the pattern, extend the envt with
556 -- bindings for the *polymorphic* Ids from any type signatures
557 tcExtendLocalValEnv sig_names sig_ids $
558 tcGRHSsAndBinds pat_ty grhss_and_binds `thenTc` \ (grhss_and_binds2, lie) ->
559 returnTc (PatMonoBind pat2 grhss_and_binds2 locn,
563 %************************************************************************
565 \subsection{Signatures}
567 %************************************************************************
569 @tcSigs@ checks the signatures for validity, and returns a list of
570 {\em freshly-instantiated} signatures. That is, the types are already
571 split up, and have fresh type variables installed. All non-type-signature
572 "RenamedSigs" are ignored.
574 The @TcSigInfo@ contains @TcTypes@ because they are unified with
575 the variable's type, and after that checked to see whether they've
581 Name -- N, the Name in corresponding binding
582 (TcIdBndr s) -- *Polymorphic* binder for this value...
583 -- Usually has name = N, but doesn't have to.
590 maybeSig :: [TcSigInfo s] -> Name -> Maybe (TcSigInfo s)
591 -- Search for a particular signature
592 maybeSig [] name = Nothing
593 maybeSig (sig@(TySigInfo sig_name _ _ _ _ _) : sigs) name
594 | name == sig_name = Just sig
595 | otherwise = maybeSig sigs name
600 tcTySig :: (Name -> PragmaInfo)
602 -> TcM s (TcSigInfo s)
604 tcTySig prag_info_fn (Sig v ty src_loc)
605 = tcAddSrcLoc src_loc $
606 tcHsType ty `thenTc` \ sigma_ty ->
607 tcInstSigType sigma_ty `thenNF_Tc` \ sigma_ty' ->
609 poly_id = mkUserId v sigma_ty' (prag_info_fn v)
610 (tyvars', theta', tau') = splitSigmaTy sigma_ty'
611 -- This splitSigmaTy tries hard to make sure that tau' is a type synonym
612 -- wherever possible, which can improve interface files.
614 returnTc (TySigInfo v poly_id tyvars' theta' tau' src_loc)
617 @checkSigMatch@ does the next step in checking signature matching.
618 The tau-type part has already been unified. What we do here is to
619 check that this unification has not over-constrained the (polymorphic)
620 type variables of the original signature type.
622 The error message here is somewhat unsatisfactory, but it'll do for
627 = returnTc (error "checkSigMatch")
629 checkSigMatch tc_ty_sigs@( sig1@(TySigInfo _ id1 _ theta1 _ _) : all_sigs_but_first )
630 = -- CHECK THAT THE SIGNATURE TYVARS AND TAU_TYPES ARE OK
631 -- Doesn't affect substitution
632 mapTc check_one_sig tc_ty_sigs `thenTc_`
634 -- CHECK THAT ALL THE SIGNATURE CONTEXTS ARE UNIFIABLE
635 -- The type signatures on a mutually-recursive group of definitions
636 -- must all have the same context (or none).
638 -- We unify them because, with polymorphic recursion, their types
639 -- might not otherwise be related. This is a rather subtle issue.
641 mapTc check_one_cxt all_sigs_but_first `thenTc_`
645 sig1_dict_tys = mk_dict_tys theta1
646 n_sig1_dict_tys = length sig1_dict_tys
648 check_one_cxt sig@(TySigInfo _ id _ theta _ src_loc)
649 = tcAddSrcLoc src_loc $
650 tcAddErrCtxt (sigContextsCtxt id1 id) $
651 checkTc (length this_sig_dict_tys == n_sig1_dict_tys)
652 sigContextsErr `thenTc_`
653 unifyTauTyLists sig1_dict_tys this_sig_dict_tys
655 this_sig_dict_tys = mk_dict_tys theta
657 check_one_sig (TySigInfo name id sig_tyvars _ sig_tau src_loc)
658 = tcAddSrcLoc src_loc $
659 tcAddErrCtxt (sigCtxt id) $
660 checkSigTyVars sig_tyvars sig_tau
662 mk_dict_tys theta = [mkDictTy c t | (c,t) <- theta]
666 @checkSigTyVars@ is used after the type in a type signature has been unified with
667 the actual type found. It then checks that the type variables of the type signature
669 (a) still all type variables
670 eg matching signature [a] against inferred type [(p,q)]
671 [then a will be unified to a non-type variable]
673 (b) still all distinct
674 eg matching signature [(a,b)] against inferred type [(p,p)]
675 [then a and b will be unified together]
677 BUT ACTUALLY THESE FIRST TWO ARE FORCED BY USING DontBind TYVARS
679 (c) not mentioned in the environment
680 eg the signature for f in this:
686 Here, f is forced to be monorphic by the free occurence of x.
688 Before doing this, the substitution is applied to the signature type variable.
691 checkSigTyVars :: [TcTyVar s] -- The original signature type variables
692 -> TcType s -- signature type (for err msg)
695 checkSigTyVars sig_tyvars sig_tau
696 = -- Several type signatures in the same bindings group can
697 -- cause the signature type variable from the different
698 -- signatures to be unified. So we need to zonk them.
699 mapNF_Tc zonkSigTyVar sig_tyvars `thenNF_Tc` \ sig_tyvars' ->
701 -- Point (a) is forced by the fact that they are signature type
702 -- variables, so the unifer won't bind them to a type.
705 checkTcM (hasNoDups sig_tyvars')
706 (zonkTcType sig_tau `thenNF_Tc` \ sig_tau' ->
707 failTc (badMatchErr sig_tau sig_tau')
711 -- We want to report errors in terms of the original signature tyvars,
712 -- ie sig_tyvars, NOT sig_tyvars'. sig_tyvars' correspond
713 -- 1-1 with sig_tyvars, so we can just map back.
714 tcGetGlobalTyVars `thenNF_Tc` \ globals ->
716 -- mono_tyvars = [sig_tv | (sig_tv, sig_tv') <- sig_tyvars `zip` sig_tyvars',
717 -- sig_tv' `elementOfTyVarSet` globals
719 mono_tyvars' = [sig_tv' | sig_tv' <- sig_tyvars',
720 sig_tv' `elementOfTyVarSet` globals]
722 checkTcM (null mono_tyvars')
723 (zonkTcType sig_tau `thenNF_Tc` \ sig_tau' ->
724 failTc (notAsPolyAsSigErr sig_tau' mono_tyvars'))
728 %************************************************************************
730 \subsection{SPECIALIZE pragmas}
732 %************************************************************************
735 @tcPragmaSigs@ munches up the "signatures" that arise through *user*
736 pragmas. It is convenient for them to appear in the @[RenamedSig]@
737 part of a binding because then the same machinery can be used for
738 moving them into place as is done for type signatures.
741 tcPragmaSigs :: [RenamedSig] -- The pragma signatures
742 -> TcM s (Name -> PragmaInfo, -- Maps name to the appropriate PragmaInfo
746 -- For now we just deal with INLINE pragmas
747 tcPragmaSigs sigs = returnTc (prag_fn, EmptyMonoBinds, emptyLIE )
749 prag_fn name | any has_inline sigs = IWantToBeINLINEd
750 | otherwise = NoPragmaInfo
752 has_inline (InlineSig n _) = (n == name)
753 has_inline other = False
758 = mapAndUnzip3Tc tcPragmaSig sigs `thenTc` \ (names_w_id_infos, binds, lies) ->
760 name_to_info name = foldr ($) noIdInfo
761 [info_fn | (n,info_fn) <- names_w_id_infos, n==name]
763 returnTc (name_to_info,
764 foldr ThenBinds EmptyBinds binds,
765 foldr plusLIE emptyLIE lies)
768 Here are the easy cases for tcPragmaSigs
771 tcPragmaSig (InlineSig name loc)
772 = returnTc ((name, addUnfoldInfo (iWantToBeINLINEd UnfoldAlways)), EmptyBinds, emptyLIE)
773 tcPragmaSig (MagicUnfoldingSig name string loc)
774 = returnTc ((name, addUnfoldInfo (mkMagicUnfolding string)), EmptyBinds, emptyLIE)
777 The interesting case is for SPECIALISE pragmas. There are two forms.
778 Here's the first form:
780 f :: Ord a => [a] -> b -> b
781 {-# SPECIALIZE f :: [Int] -> b -> b #-}
784 For this we generate:
786 f* = /\ b -> let d1 = ...
790 where f* is a SpecPragmaId. The **sole** purpose of SpecPragmaIds is to
791 retain a right-hand-side that the simplifier will otherwise discard as
792 dead code... the simplifier has a flag that tells it not to discard
793 SpecPragmaId bindings.
795 In this case the f* retains a call-instance of the overloaded
796 function, f, (including appropriate dictionaries) so that the
797 specialiser will subsequently discover that there's a call of @f@ at
798 Int, and will create a specialisation for @f@. After that, the
799 binding for @f*@ can be discarded.
801 The second form is this:
803 f :: Ord a => [a] -> b -> b
804 {-# SPECIALIZE f :: [Int] -> b -> b = g #-}
807 Here @g@ is specified as a function that implements the specialised
808 version of @f@. Suppose that g has type (a->b->b); that is, g's type
809 is more general than that required. For this we generate
811 f@Int = /\b -> g Int b
815 Here @f@@Int@ is a SpecId, the specialised version of @f@. It inherits
816 f's export status etc. @f*@ is a SpecPragmaId, as before, which just serves
817 to prevent @f@@Int@ from being discarded prematurely. After specialisation,
818 if @f@@Int@ is going to be used at all it will be used explicitly, so the simplifier can
819 discard the f* binding.
821 Actually, there is really only point in giving a SPECIALISE pragma on exported things,
822 and the simplifer won't discard SpecIds for exporte things anyway, so maybe this is
826 tcPragmaSig (SpecSig name poly_ty maybe_spec_name src_loc)
827 = tcAddSrcLoc src_loc $
828 tcAddErrCtxt (valSpecSigCtxt name spec_ty) $
830 -- Get and instantiate its alleged specialised type
831 tcHsType poly_ty `thenTc` \ sig_sigma ->
832 tcInstSigType sig_sigma `thenNF_Tc` \ sig_ty ->
834 (sig_tyvars, sig_theta, sig_tau) = splitSigmaTy sig_ty
835 origin = ValSpecOrigin name
838 -- Check that the SPECIALIZE pragma had an empty context
839 checkTc (null sig_theta)
840 (panic "SPECIALIZE non-empty context (ToDo: msg)") `thenTc_`
842 -- Get and instantiate the type of the id mentioned
843 tcLookupLocalValueOK "tcPragmaSig" name `thenNF_Tc` \ main_id ->
844 tcInstSigType [] (idType main_id) `thenNF_Tc` \ main_ty ->
846 (main_tyvars, main_rho) = splitForAllTy main_ty
847 (main_theta,main_tau) = splitRhoTy main_rho
848 main_arg_tys = mkTyVarTys main_tyvars
851 -- Check that the specialised type is indeed an instance of
852 -- the type of the main function.
853 unifyTauTy sig_tau main_tau `thenTc_`
854 checkSigTyVars sig_tyvars sig_tau `thenTc_`
856 -- Check that the type variables of the polymorphic function are
857 -- either left polymorphic, or instantiate to ground type.
858 -- Also check that the overloaded type variables are instantiated to
859 -- ground type; or equivalently that all dictionaries have ground type
860 mapTc zonkTcType main_arg_tys `thenNF_Tc` \ main_arg_tys' ->
861 zonkTcThetaType main_theta `thenNF_Tc` \ main_theta' ->
862 tcAddErrCtxt (specGroundnessCtxt main_arg_tys')
863 (checkTc (all isGroundOrTyVarTy main_arg_tys')) `thenTc_`
864 tcAddErrCtxt (specContextGroundnessCtxt main_theta')
865 (checkTc (and [isGroundTy ty | (_,ty) <- theta'])) `thenTc_`
867 -- Build the SpecPragmaId; it is the thing that makes sure we
868 -- don't prematurely dead-code-eliminate the binding we are really interested in.
869 newSpecPragmaId name sig_ty `thenNF_Tc` \ spec_pragma_id ->
871 -- Build a suitable binding; depending on whether we were given
872 -- a value (Maybe Name) to be used as the specialisation.
874 Nothing -> -- No implementation function specified
876 -- Make a Method inst for the occurrence of the overloaded function
877 newMethodWithGivenTy (OccurrenceOf name)
878 (TcId main_id) main_arg_tys main_rho `thenNF_Tc` \ (lie, meth_id) ->
881 pseudo_bind = VarMonoBind spec_pragma_id pseudo_rhs
882 pseudo_rhs = mkHsTyLam sig_tyvars (HsVar (TcId meth_id))
884 returnTc (pseudo_bind, lie, \ info -> info)
886 Just spec_name -> -- Use spec_name as the specialisation value ...
888 -- Type check a simple occurrence of the specialised Id
889 tcId spec_name `thenTc` \ (spec_body, spec_lie, spec_tau) ->
891 -- Check that it has the correct type, and doesn't constrain the
892 -- signature variables at all
893 unifyTauTy sig_tau spec_tau `thenTc_`
894 checkSigTyVars sig_tyvars sig_tau `thenTc_`
896 -- Make a local SpecId to bind to applied spec_id
897 newSpecId main_id main_arg_tys sig_ty `thenNF_Tc` \ local_spec_id ->
900 spec_rhs = mkHsTyLam sig_tyvars spec_body
901 spec_binds = VarMonoBind local_spec_id spec_rhs
903 VarMonoBind spec_pragma_id (HsVar (TcId local_spec_id))
904 spec_info = SpecInfo spec_tys (length main_theta) local_spec_id
906 returnTc ((name, addSpecInfo spec_info), spec_binds, spec_lie)
911 %************************************************************************
913 \subsection[TcBinds-errors]{Error contexts and messages}
915 %************************************************************************
919 patMonoBindsCtxt bind sty
920 = hang (ptext SLIT("In a pattern binding:")) 4 (ppr sty bind)
922 -----------------------------------------------
923 valSpecSigCtxt v ty sty
924 = hang (ptext SLIT("In a SPECIALIZE pragma for a value:"))
925 4 (sep [(<>) (ppr sty v) (ptext SLIT(" ::")),
930 -----------------------------------------------
931 notAsPolyAsSigErr sig_tau mono_tyvars sty
932 = hang (ptext SLIT("A type signature is more polymorphic than the inferred type"))
933 4 (vcat [text "Can't for-all the type variable(s)" <+> interpp'SP sty mono_tyvars,
934 text "in the inferred type" <+> ppr sty sig_tau
937 -----------------------------------------------
938 badMatchErr sig_ty inferred_ty sty
939 = hang (ptext SLIT("Type signature doesn't match inferred type"))
940 4 (vcat [hang (ptext SLIT("Signature:")) 4 (ppr sty sig_ty),
941 hang (ptext SLIT("Inferred :")) 4 (ppr sty inferred_ty)
944 -----------------------------------------------
946 = sep [ptext SLIT("When checking signature for"), ppr sty id]
948 = sep [ptext SLIT("When checking signature(s) for:"), interpp'SP sty ids]
950 -----------------------------------------------
952 = ptext SLIT("Mismatched contexts")
953 sigContextsCtxt s1 s2 sty
954 = hang (hsep [ptext SLIT("When matching the contexts of the signatures for"),
955 ppr sty s1, ptext SLIT("and"), ppr sty s2])
956 4 (ptext SLIT("(the signature contexts in a mutually recursive group should all be identical)"))
958 -----------------------------------------------
960 = panic "specGroundnessCtxt"
962 --------------------------------------------
963 specContextGroundnessCtxt -- err_ctxt dicts sty
964 = panic "specContextGroundnessCtxt"
967 sep [hsep [ptext SLIT("In the SPECIALIZE pragma for"), ppr sty name],
968 hcat [ptext SLIT(" specialised to the type"), ppr sty spec_ty],
970 ptext SLIT("... not all overloaded type variables were instantiated"),
971 ptext SLIT("to ground types:")])
972 4 (vcat [hsep [ppr sty c, ppr sty t]
973 | (c,t) <- map getDictClassAndType dicts])
975 (name, spec_ty, locn, pp_spec_id)
977 ValSpecSigCtxt n ty loc -> (n, ty, loc, \ x -> empty)
978 ValSpecSpecIdCtxt n ty spec loc ->
980 \ sty -> hsep [ptext SLIT("... type of explicit id"), ppr sty spec])