2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcBinds]{TcBinds}
7 module TcBinds ( tcBindsAndThen, tcTopBinds,
8 tcSpecSigs, tcBindWithSigs ) where
10 #include "HsVersions.h"
12 import {-# SOURCE #-} TcMatches ( tcGRHSs, tcMatchesFun )
13 import {-# SOURCE #-} TcExpr ( tcExpr )
15 import CmdLineOpts ( DynFlag(Opt_NoMonomorphismRestriction) )
16 import HsSyn ( HsExpr(..), HsBinds(..), MonoBinds(..), Sig(..),
17 Match(..), HsMatchContext(..),
18 collectMonoBinders, andMonoBinds,
19 collectSigTysFromMonoBinds
21 import RnHsSyn ( RenamedHsBinds, RenamedSig, RenamedMonoBinds )
22 import TcHsSyn ( TcMonoBinds, TcId, zonkId, mkHsLet )
25 import Inst ( LIE, emptyLIE, mkLIE, plusLIE, InstOrigin(..),
28 import TcEnv ( tcExtendLocalValEnv, newLocalName )
29 import TcUnify ( unifyTauTyLists, checkSigTyVars, sigCtxt )
30 import TcSimplify ( tcSimplifyInfer, tcSimplifyInferCheck, tcSimplifyRestricted, tcSimplifyToDicts )
31 import TcMonoType ( tcHsSigType, UserTypeCtxt(..),
32 TcSigInfo(..), tcTySig, maybeSig, tcAddScopedTyVars
34 import TcPat ( tcPat, tcSubPat, tcMonoPatBndr )
35 import TcSimplify ( bindInstsOfLocalFuns )
36 import TcMType ( newTyVar, newTyVarTy, newHoleTyVarTy,
39 import TcType ( mkTyVarTy, mkForAllTys, mkFunTys, tyVarsOfType,
40 mkPredTy, mkForAllTy, isUnLiftedType,
41 unliftedTypeKind, liftedTypeKind, openTypeKind, eqKind
44 import CoreFVs ( idFreeTyVars )
45 import Id ( mkLocalId, mkSpecPragmaId, setInlinePragma )
46 import Var ( idType, idName )
47 import Name ( Name, getSrcLoc )
49 import Var ( tyVarKind )
52 import Util ( isIn, equalLength )
53 import BasicTypes ( TopLevelFlag(..), RecFlag(..), isNonRec, isNotTopLevel,
55 import FiniteMap ( listToFM, lookupFM )
60 %************************************************************************
62 \subsection{Type-checking bindings}
64 %************************************************************************
66 @tcBindsAndThen@ typechecks a @HsBinds@. The "and then" part is because
67 it needs to know something about the {\em usage} of the things bound,
68 so that it can create specialisations of them. So @tcBindsAndThen@
69 takes a function which, given an extended environment, E, typechecks
70 the scope of the bindings returning a typechecked thing and (most
71 important) an LIE. It is this LIE which is then used as the basis for
72 specialising the things bound.
74 @tcBindsAndThen@ also takes a "combiner" which glues together the
75 bindings and the "thing" to make a new "thing".
77 The real work is done by @tcBindWithSigsAndThen@.
79 Recursive and non-recursive binds are handled in essentially the same
80 way: because of uniques there are no scoping issues left. The only
81 difference is that non-recursive bindings can bind primitive values.
83 Even for non-recursive binding groups we add typings for each binder
84 to the LVE for the following reason. When each individual binding is
85 checked the type of its LHS is unified with that of its RHS; and
86 type-checking the LHS of course requires that the binder is in scope.
88 At the top-level the LIE is sure to contain nothing but constant
89 dictionaries, which we resolve at the module level.
92 tcTopBinds :: RenamedHsBinds -> TcM ((TcMonoBinds, TcEnv), LIE)
94 = tc_binds_and_then TopLevel glue binds $
95 tcGetEnv `thenNF_Tc` \ env ->
96 returnTc ((EmptyMonoBinds, env), emptyLIE)
98 glue is_rec binds1 (binds2, thing) = (binds1 `AndMonoBinds` binds2, thing)
102 :: (RecFlag -> TcMonoBinds -> thing -> thing) -- Combinator
107 tcBindsAndThen = tc_binds_and_then NotTopLevel
109 tc_binds_and_then top_lvl combiner EmptyBinds do_next
111 tc_binds_and_then top_lvl combiner (MonoBind EmptyMonoBinds sigs is_rec) do_next
114 tc_binds_and_then top_lvl combiner (ThenBinds b1 b2) do_next
115 = tc_binds_and_then top_lvl combiner b1 $
116 tc_binds_and_then top_lvl combiner b2 $
119 tc_binds_and_then top_lvl combiner (MonoBind bind sigs is_rec) do_next
120 = -- BRING ANY SCOPED TYPE VARIABLES INTO SCOPE
121 -- Notice that they scope over
122 -- a) the type signatures in the binding group
123 -- b) the bindings in the group
124 -- c) the scope of the binding group (the "in" part)
125 tcAddScopedTyVars (collectSigTysFromMonoBinds bind) $
127 -- TYPECHECK THE SIGNATURES
128 mapTc tcTySig [sig | sig@(Sig name _ _) <- sigs] `thenTc` \ tc_ty_sigs ->
130 tcBindWithSigs top_lvl bind tc_ty_sigs
131 sigs is_rec `thenTc` \ (poly_binds, poly_lie, poly_ids) ->
133 -- Extend the environment to bind the new polymorphic Ids
134 tcExtendLocalValEnv [(idName poly_id, poly_id) | poly_id <- poly_ids] $
136 -- Build bindings and IdInfos corresponding to user pragmas
137 tcSpecSigs sigs `thenTc` \ (prag_binds, prag_lie) ->
139 -- Now do whatever happens next, in the augmented envt
140 do_next `thenTc` \ (thing, thing_lie) ->
142 -- Create specialisations of functions bound here
143 -- We want to keep non-recursive things non-recursive
144 -- so that we desugar unlifted bindings correctly
145 case (top_lvl, is_rec) of
147 -- For the top level don't bother will all this bindInstsOfLocalFuns stuff
148 -- All the top level things are rec'd together anyway, so it's fine to
149 -- leave them to the tcSimplifyTop, and quite a bit faster too
151 -> returnTc (combiner Recursive (poly_binds `andMonoBinds` prag_binds) thing,
152 thing_lie `plusLIE` prag_lie `plusLIE` poly_lie)
154 (NotTopLevel, NonRecursive)
155 -> bindInstsOfLocalFuns
156 (thing_lie `plusLIE` prag_lie)
157 poly_ids `thenTc` \ (thing_lie', lie_binds) ->
160 combiner NonRecursive poly_binds $
161 combiner NonRecursive prag_binds $
162 combiner Recursive lie_binds $
163 -- NB: the binds returned by tcSimplify and bindInstsOfLocalFuns
164 -- aren't guaranteed in dependency order (though we could change
165 -- that); hence the Recursive marker.
168 thing_lie' `plusLIE` poly_lie
171 (NotTopLevel, Recursive)
172 -> bindInstsOfLocalFuns
173 (thing_lie `plusLIE` poly_lie `plusLIE` prag_lie)
174 poly_ids `thenTc` \ (final_lie, lie_binds) ->
178 poly_binds `andMonoBinds`
179 lie_binds `andMonoBinds`
186 %************************************************************************
188 \subsection{tcBindWithSigs}
190 %************************************************************************
192 @tcBindWithSigs@ deals with a single binding group. It does generalisation,
193 so all the clever stuff is in here.
195 * binder_names and mbind must define the same set of Names
197 * The Names in tc_ty_sigs must be a subset of binder_names
199 * The Ids in tc_ty_sigs don't necessarily have to have the same name
200 as the Name in the tc_ty_sig
207 -> [RenamedSig] -- Used solely to get INLINE, NOINLINE sigs
209 -> TcM (TcMonoBinds, LIE, [TcId])
211 tcBindWithSigs top_lvl mbind tc_ty_sigs inline_sigs is_rec
213 -- If typechecking the binds fails, then return with each
214 -- signature-less binder given type (forall a.a), to minimise subsequent
216 newTyVar liftedTypeKind `thenNF_Tc` \ alpha_tv ->
218 forall_a_a = mkForAllTy alpha_tv (mkTyVarTy alpha_tv)
219 binder_names = collectMonoBinders mbind
220 poly_ids = map mk_dummy binder_names
221 mk_dummy name = case maybeSig tc_ty_sigs name of
222 Just (TySigInfo _ poly_id _ _ _ _ _ _) -> poly_id -- Signature
223 Nothing -> mkLocalId name forall_a_a -- No signature
225 returnTc (EmptyMonoBinds, emptyLIE, poly_ids)
228 -- TYPECHECK THE BINDINGS
229 tcMonoBinds mbind tc_ty_sigs is_rec `thenTc` \ (mbind', lie_req, binder_names, mono_ids) ->
231 tau_tvs = foldr (unionVarSet . tyVarsOfType . idType) emptyVarSet mono_ids
235 tcAddSrcLoc (minimum (map getSrcLoc binder_names)) $
236 tcAddErrCtxt (genCtxt binder_names) $
237 generalise binder_names mbind tau_tvs lie_req tc_ty_sigs
238 `thenTc` \ (tc_tyvars_to_gen, lie_free, dict_binds, dict_ids) ->
241 -- ZONK THE GENERALISED TYPE VARIABLES TO REAL TyVars
242 -- This commits any unbound kind variables to boxed kind, by unification
243 -- It's important that the final quanfified type variables
244 -- are fully zonked, *including boxity*, because they'll be
245 -- included in the forall types of the polymorphic Ids.
246 -- At calls of these Ids we'll instantiate fresh type variables from
247 -- them, and we use their boxity then.
248 mapNF_Tc zonkTcTyVarToTyVar tc_tyvars_to_gen `thenNF_Tc` \ real_tyvars_to_gen ->
251 -- It's important that the dict Ids are zonked, including the boxity set
252 -- in the previous step, because they are later used to form the type of
253 -- the polymorphic thing, and forall-types must be zonked so far as
254 -- their bound variables are concerned
255 mapNF_Tc zonkId dict_ids `thenNF_Tc` \ zonked_dict_ids ->
256 mapNF_Tc zonkId mono_ids `thenNF_Tc` \ zonked_mono_ids ->
258 -- BUILD THE POLYMORPHIC RESULT IDs
260 exports = zipWith mk_export binder_names zonked_mono_ids
261 poly_ids = [poly_id | (_, poly_id, _) <- exports]
262 dict_tys = map idType zonked_dict_ids
264 inlines = mkNameSet [name | InlineSig True name _ loc <- inline_sigs]
265 no_inlines = listToFM [(name, phase) | InlineSig _ name phase _ <- inline_sigs,
266 not (isAlwaysActive phase)]
267 -- AlwaysActive is the default, so don't bother with them
269 mk_export binder_name zonked_mono_id
271 attachNoInlinePrag no_inlines poly_id,
275 case maybeSig tc_ty_sigs binder_name of
276 Just (TySigInfo _ sig_poly_id sig_tyvars _ _ _ _ _) ->
277 (sig_tyvars, sig_poly_id)
278 Nothing -> (real_tyvars_to_gen, new_poly_id)
280 new_poly_id = mkLocalId binder_name poly_ty
281 poly_ty = mkForAllTys real_tyvars_to_gen
283 $ idType zonked_mono_id
284 -- It's important to build a fully-zonked poly_ty, because
285 -- we'll slurp out its free type variables when extending the
286 -- local environment (tcExtendLocalValEnv); if it's not zonked
287 -- it appears to have free tyvars that aren't actually free
291 traceTc (text "binding:" <+> ppr ((zonked_dict_ids, dict_binds),
292 exports, map idType poly_ids)) `thenTc_`
294 -- Check for an unlifted, non-overloaded group
295 -- In that case we must make extra checks
296 if any (isUnLiftedType . idType) zonked_mono_ids && null zonked_dict_ids
297 then -- Some bindings are unlifted
298 checkUnliftedBinds top_lvl is_rec real_tyvars_to_gen mbind `thenTc_`
301 AbsBinds [] [] exports inlines mbind',
302 lie_req, -- Do not generate even any x=y bindings
306 else -- The normal case
308 AbsBinds real_tyvars_to_gen
312 (dict_binds `andMonoBinds` mbind'),
316 attachNoInlinePrag no_inlines bndr
317 = case lookupFM no_inlines (idName bndr) of
318 Just prag -> bndr `setInlinePragma` prag
321 -- Check that non-overloaded unlifted bindings are
324 -- c) non-polymorphic
325 -- d) not a multiple-binding group (more or less implied by (a))
327 checkUnliftedBinds top_lvl is_rec real_tyvars_to_gen mbind
328 = ASSERT( not (any ((eqKind unliftedTypeKind) . tyVarKind) real_tyvars_to_gen) )
329 -- The instCantBeGeneralised stuff in tcSimplify should have
330 -- already raised an error if we're trying to generalise an
331 -- unboxed tyvar (NB: unboxed tyvars are always introduced
332 -- along with a class constraint) and it's better done there
333 -- because we have more precise origin information.
334 -- That's why we just use an ASSERT here.
336 checkTc (isNotTopLevel top_lvl)
337 (unliftedBindErr "Top-level" mbind) `thenTc_`
338 checkTc (isNonRec is_rec)
339 (unliftedBindErr "Recursive" mbind) `thenTc_`
340 checkTc (single_bind mbind)
341 (unliftedBindErr "Multiple" mbind) `thenTc_`
342 checkTc (null real_tyvars_to_gen)
343 (unliftedBindErr "Polymorphic" mbind)
346 single_bind (PatMonoBind _ _ _) = True
347 single_bind (FunMonoBind _ _ _ _) = True
348 single_bind other = False
352 Polymorphic recursion
353 ~~~~~~~~~~~~~~~~~~~~~
354 The game plan for polymorphic recursion in the code above is
356 * Bind any variable for which we have a type signature
357 to an Id with a polymorphic type. Then when type-checking
358 the RHSs we'll make a full polymorphic call.
360 This fine, but if you aren't a bit careful you end up with a horrendous
361 amount of partial application and (worse) a huge space leak. For example:
363 f :: Eq a => [a] -> [a]
366 If we don't take care, after typechecking we get
368 f = /\a -> \d::Eq a -> let f' = f a d
372 Notice the the stupid construction of (f a d), which is of course
373 identical to the function we're executing. In this case, the
374 polymorphic recursion isn't being used (but that's a very common case).
377 f = /\a -> \d::Eq a -> letrec
378 fm = \ys:[a] -> ...fm...
382 This can lead to a massive space leak, from the following top-level defn
388 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
389 f' is another thunk which evaluates to the same thing... and you end
390 up with a chain of identical values all hung onto by the CAF ff.
394 = let f' = f Int dEqInt in \ys. ...f'...
396 = let f' = let f' = f Int dEqInt in \ys. ...f'...
400 Solution: when typechecking the RHSs we always have in hand the
401 *monomorphic* Ids for each binding. So we just need to make sure that
402 if (Method f a d) shows up in the constraints emerging from (...f...)
403 we just use the monomorphic Id. We achieve this by adding monomorphic Ids
404 to the "givens" when simplifying constraints. That's what the "lies_avail"
408 %************************************************************************
410 \subsection{getTyVarsToGen}
412 %************************************************************************
415 generalise binder_names mbind tau_tvs lie_req sigs =
417 -- check for -fno-monomorphism-restriction
418 doptsTc Opt_NoMonomorphismRestriction `thenTc` \ no_MR ->
419 let is_unrestricted | no_MR = True
420 | otherwise = isUnRestrictedGroup tysig_names mbind
423 if not is_unrestricted then -- RESTRICTED CASE
424 -- Check signature contexts are empty
425 checkTc (all is_mono_sig sigs)
426 (restrictedBindCtxtErr binder_names) `thenTc_`
428 -- Now simplify with exactly that set of tyvars
429 -- We have to squash those Methods
430 tcSimplifyRestricted doc tau_tvs lie_req `thenTc` \ (qtvs, lie_free, binds) ->
432 -- Check that signature type variables are OK
433 checkSigsTyVars sigs `thenTc_`
435 returnTc (qtvs, lie_free, binds, [])
437 else if null sigs then -- UNRESTRICTED CASE, NO TYPE SIGS
438 tcSimplifyInfer doc tau_tvs lie_req
440 else -- UNRESTRICTED CASE, WITH TYPE SIGS
441 -- CHECKING CASE: Unrestricted group, there are type signatures
442 -- Check signature contexts are empty
443 checkSigsCtxts sigs `thenTc` \ (sig_avails, sig_dicts) ->
445 -- Check that the needed dicts can be
446 -- expressed in terms of the signature ones
447 tcSimplifyInferCheck doc tau_tvs sig_avails lie_req `thenTc` \ (forall_tvs, lie_free, dict_binds) ->
449 -- Check that signature type variables are OK
450 checkSigsTyVars sigs `thenTc_`
452 returnTc (forall_tvs, lie_free, dict_binds, sig_dicts)
455 tysig_names = [name | (TySigInfo name _ _ _ _ _ _ _) <- sigs]
456 is_mono_sig (TySigInfo _ _ _ theta _ _ _ _) = null theta
458 doc = ptext SLIT("type signature(s) for") <+> pprBinders binder_names
460 -----------------------
461 -- CHECK THAT ALL THE SIGNATURE CONTEXTS ARE UNIFIABLE
462 -- The type signatures on a mutually-recursive group of definitions
463 -- must all have the same context (or none).
465 -- We unify them because, with polymorphic recursion, their types
466 -- might not otherwise be related. This is a rather subtle issue.
468 checkSigsCtxts sigs@(TySigInfo _ id1 sig_tvs theta1 _ _ _ src_loc : other_sigs)
469 = tcAddSrcLoc src_loc $
470 mapTc_ check_one other_sigs `thenTc_`
472 returnTc ([], []) -- Non-overloaded type signatures
474 newDicts SignatureOrigin theta1 `thenNF_Tc` \ sig_dicts ->
476 -- The "sig_avails" is the stuff available. We get that from
477 -- the context of the type signature, BUT ALSO the lie_avail
478 -- so that polymorphic recursion works right (see comments at end of fn)
479 sig_avails = sig_dicts ++ sig_meths
481 returnTc (sig_avails, map instToId sig_dicts)
483 sig1_dict_tys = map mkPredTy theta1
484 sig_meths = concat [insts | TySigInfo _ _ _ _ _ _ insts _ <- sigs]
486 check_one sig@(TySigInfo _ id _ theta _ _ _ src_loc)
487 = tcAddErrCtxt (sigContextsCtxt id1 id) $
488 checkTc (equalLength theta theta1) sigContextsErr `thenTc_`
489 unifyTauTyLists sig1_dict_tys (map mkPredTy theta)
491 checkSigsTyVars sigs = mapTc_ check_one sigs
493 check_one (TySigInfo _ id sig_tyvars sig_theta sig_tau _ _ src_loc)
494 = tcAddSrcLoc src_loc $
495 tcAddErrCtxt (ptext SLIT("When checking the type signature for")
496 <+> quotes (ppr id)) $
497 tcAddErrCtxtM (sigCtxt sig_tyvars sig_theta sig_tau) $
498 checkSigTyVars sig_tyvars (idFreeTyVars id)
501 @getTyVarsToGen@ decides what type variables to generalise over.
503 For a "restricted group" -- see the monomorphism restriction
504 for a definition -- we bind no dictionaries, and
505 remove from tyvars_to_gen any constrained type variables
507 *Don't* simplify dicts at this point, because we aren't going
508 to generalise over these dicts. By the time we do simplify them
509 we may well know more. For example (this actually came up)
511 f x = array ... xs where xs = [1,2,3,4,5]
512 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
513 stuff. If we simplify only at the f-binding (not the xs-binding)
514 we'll know that the literals are all Ints, and we can just produce
517 Find all the type variables involved in overloading, the
518 "constrained_tyvars". These are the ones we *aren't* going to
519 generalise. We must be careful about doing this:
521 (a) If we fail to generalise a tyvar which is not actually
522 constrained, then it will never, ever get bound, and lands
523 up printed out in interface files! Notorious example:
524 instance Eq a => Eq (Foo a b) where ..
525 Here, b is not constrained, even though it looks as if it is.
526 Another, more common, example is when there's a Method inst in
527 the LIE, whose type might very well involve non-overloaded
529 [NOTE: Jan 2001: I don't understand the problem here so I'm doing
530 the simple thing instead]
532 (b) On the other hand, we mustn't generalise tyvars which are constrained,
533 because we are going to pass on out the unmodified LIE, with those
534 tyvars in it. They won't be in scope if we've generalised them.
536 So we are careful, and do a complete simplification just to find the
537 constrained tyvars. We don't use any of the results, except to
538 find which tyvars are constrained.
541 isUnRestrictedGroup :: [Name] -- Signatures given for these
545 is_elem v vs = isIn "isUnResMono" v vs
547 isUnRestrictedGroup sigs (PatMonoBind other _ _) = False
548 isUnRestrictedGroup sigs (VarMonoBind v _) = v `is_elem` sigs
549 isUnRestrictedGroup sigs (FunMonoBind v _ matches _) = isUnRestrictedMatch matches ||
551 isUnRestrictedGroup sigs (AndMonoBinds mb1 mb2) = isUnRestrictedGroup sigs mb1 &&
552 isUnRestrictedGroup sigs mb2
553 isUnRestrictedGroup sigs EmptyMonoBinds = True
555 isUnRestrictedMatch (Match [] _ _ : _) = False -- No args => like a pattern binding
556 isUnRestrictedMatch other = True -- Some args => a function binding
560 %************************************************************************
562 \subsection{tcMonoBind}
564 %************************************************************************
566 @tcMonoBinds@ deals with a single @MonoBind@.
567 The signatures have been dealt with already.
570 tcMonoBinds :: RenamedMonoBinds
575 [Name], -- Bound names
576 [TcId]) -- Corresponding monomorphic bound things
578 tcMonoBinds mbinds tc_ty_sigs is_rec
579 = tc_mb_pats mbinds `thenTc` \ (complete_it, lie_req_pat, tvs, ids, lie_avail) ->
581 id_list = bagToList ids
582 (names, mono_ids) = unzip id_list
584 -- This last defn is the key one:
585 -- extend the val envt with bindings for the
586 -- things bound in this group, overriding the monomorphic
587 -- ids with the polymorphic ones from the pattern
588 extra_val_env = case is_rec of
589 Recursive -> map mk_bind id_list
592 -- Don't know how to deal with pattern-bound existentials yet
593 checkTc (isEmptyBag tvs && isEmptyBag lie_avail)
594 (existentialExplode mbinds) `thenTc_`
596 -- *Before* checking the RHSs, but *after* checking *all* the patterns,
597 -- extend the envt with bindings for all the bound ids;
598 -- and *then* override with the polymorphic Ids from the signatures
599 -- That is the whole point of the "complete_it" stuff.
601 -- There's a further wrinkle: we have to delay extending the environment
602 -- until after we've dealt with any pattern-bound signature type variables
603 -- Consider f (x::a) = ...f...
604 -- We're going to check that a isn't unified with anything in the envt,
605 -- so f itself had better not be! So we pass the envt binding f into
606 -- complete_it, which extends the actual envt in TcMatches.tcMatch, after
607 -- dealing with the signature tyvars
609 complete_it extra_val_env `thenTc` \ (mbinds', lie_req_rhss) ->
611 returnTc (mbinds', lie_req_pat `plusLIE` lie_req_rhss, names, mono_ids)
614 mk_bind (name, mono_id) = case maybeSig tc_ty_sigs name of
615 Nothing -> (name, mono_id)
616 Just (TySigInfo name poly_id _ _ _ _ _ _) -> (name, poly_id)
618 tc_mb_pats EmptyMonoBinds
619 = returnTc (\ xve -> returnTc (EmptyMonoBinds, emptyLIE), emptyLIE, emptyBag, emptyBag, emptyLIE)
621 tc_mb_pats (AndMonoBinds mb1 mb2)
622 = tc_mb_pats mb1 `thenTc` \ (complete_it1, lie_req1, tvs1, ids1, lie_avail1) ->
623 tc_mb_pats mb2 `thenTc` \ (complete_it2, lie_req2, tvs2, ids2, lie_avail2) ->
625 complete_it xve = complete_it1 xve `thenTc` \ (mb1', lie1) ->
626 complete_it2 xve `thenTc` \ (mb2', lie2) ->
627 returnTc (AndMonoBinds mb1' mb2', lie1 `plusLIE` lie2)
629 returnTc (complete_it,
630 lie_req1 `plusLIE` lie_req2,
631 tvs1 `unionBags` tvs2,
632 ids1 `unionBags` ids2,
633 lie_avail1 `plusLIE` lie_avail2)
635 tc_mb_pats (FunMonoBind name inf matches locn)
636 = (case maybeSig tc_ty_sigs name of
637 Just (TySigInfo _ _ _ _ _ mono_id _ _)
638 -> returnNF_Tc mono_id
639 Nothing -> newLocalName name `thenNF_Tc` \ bndr_name ->
640 newTyVarTy openTypeKind `thenNF_Tc` \ bndr_ty ->
641 -- NB: not a 'hole' tyvar; since there is no type
642 -- signature, we revert to ordinary H-M typechecking
643 -- which means the variable gets an inferred tau-type
644 returnNF_Tc (mkLocalId bndr_name bndr_ty)
645 ) `thenNF_Tc` \ bndr_id ->
647 bndr_ty = idType bndr_id
648 complete_it xve = tcAddSrcLoc locn $
649 tcMatchesFun xve name bndr_ty matches `thenTc` \ (matches', lie) ->
650 returnTc (FunMonoBind bndr_id inf matches' locn, lie)
652 returnTc (complete_it, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
654 tc_mb_pats bind@(PatMonoBind pat grhss locn)
656 newHoleTyVarTy `thenNF_Tc` \ pat_ty ->
658 -- Now typecheck the pattern
659 -- We do now support binding fresh (not-already-in-scope) scoped
660 -- type variables in the pattern of a pattern binding.
661 -- For example, this is now legal:
663 -- The type variables are brought into scope in tc_binds_and_then,
664 -- so we don't have to do anything here.
666 tcPat tc_pat_bndr pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
668 complete_it xve = tcAddSrcLoc locn $
669 tcAddErrCtxt (patMonoBindsCtxt bind) $
670 tcExtendLocalValEnv xve $
671 tcGRHSs PatBindRhs grhss pat_ty `thenTc` \ (grhss', lie) ->
672 returnTc (PatMonoBind pat' grhss' locn, lie)
674 returnTc (complete_it, lie_req, tvs, ids, lie_avail)
676 -- tc_pat_bndr is used when dealing with a LHS binder in a pattern.
677 -- If there was a type sig for that Id, we want to make it much
678 -- as if that type signature had been on the binder as a SigPatIn.
679 -- We check for a type signature; if there is one, we use the mono_id
680 -- from the signature. This is how we make sure the tau part of the
681 -- signature actually matches the type of the LHS; then tc_mb_pats
682 -- ensures the LHS and RHS have the same type
684 tc_pat_bndr name pat_ty
685 = case maybeSig tc_ty_sigs name of
687 -> newLocalName name `thenNF_Tc` \ bndr_name ->
688 tcMonoPatBndr bndr_name pat_ty
690 Just (TySigInfo _ _ _ _ _ mono_id _ _)
691 -> tcAddSrcLoc (getSrcLoc name) $
692 tcSubPat pat_ty (idType mono_id) `thenTc` \ (co_fn, lie) ->
693 returnTc (co_fn, lie, mono_id)
697 %************************************************************************
699 \subsection{SPECIALIZE pragmas}
701 %************************************************************************
703 @tcSpecSigs@ munches up the specialisation "signatures" that arise through *user*
704 pragmas. It is convenient for them to appear in the @[RenamedSig]@
705 part of a binding because then the same machinery can be used for
706 moving them into place as is done for type signatures.
711 f :: Ord a => [a] -> b -> b
712 {-# SPECIALIZE f :: [Int] -> b -> b #-}
715 For this we generate:
717 f* = /\ b -> let d1 = ...
721 where f* is a SpecPragmaId. The **sole** purpose of SpecPragmaIds is to
722 retain a right-hand-side that the simplifier will otherwise discard as
723 dead code... the simplifier has a flag that tells it not to discard
724 SpecPragmaId bindings.
726 In this case the f* retains a call-instance of the overloaded
727 function, f, (including appropriate dictionaries) so that the
728 specialiser will subsequently discover that there's a call of @f@ at
729 Int, and will create a specialisation for @f@. After that, the
730 binding for @f*@ can be discarded.
732 We used to have a form
733 {-# SPECIALISE f :: <type> = g #-}
734 which promised that g implemented f at <type>, but we do that with
736 {-# SPECIALISE (f::<type) = g #-}
739 tcSpecSigs :: [RenamedSig] -> TcM (TcMonoBinds, LIE)
740 tcSpecSigs (SpecSig name poly_ty src_loc : sigs)
741 = -- SPECIALISE f :: forall b. theta => tau = g
742 tcAddSrcLoc src_loc $
743 tcAddErrCtxt (valSpecSigCtxt name poly_ty) $
745 -- Get and instantiate its alleged specialised type
746 tcHsSigType (FunSigCtxt name) poly_ty `thenTc` \ sig_ty ->
748 -- Check that f has a more general type, and build a RHS for
749 -- the spec-pragma-id at the same time
750 tcExpr (HsVar name) sig_ty `thenTc` \ (spec_expr, spec_lie) ->
752 -- Squeeze out any Methods (see comments with tcSimplifyToDicts)
753 tcSimplifyToDicts spec_lie `thenTc` \ (spec_dicts, spec_binds) ->
755 -- Just specialise "f" by building a SpecPragmaId binding
756 -- It is the thing that makes sure we don't prematurely
757 -- dead-code-eliminate the binding we are really interested in.
758 newLocalName name `thenNF_Tc` \ spec_name ->
760 spec_bind = VarMonoBind (mkSpecPragmaId spec_name sig_ty)
761 (mkHsLet spec_binds spec_expr)
764 -- Do the rest and combine
765 tcSpecSigs sigs `thenTc` \ (binds_rest, lie_rest) ->
766 returnTc (binds_rest `andMonoBinds` spec_bind,
767 lie_rest `plusLIE` mkLIE spec_dicts)
769 tcSpecSigs (other_sig : sigs) = tcSpecSigs sigs
770 tcSpecSigs [] = returnTc (EmptyMonoBinds, emptyLIE)
774 %************************************************************************
776 \subsection[TcBinds-errors]{Error contexts and messages}
778 %************************************************************************
782 patMonoBindsCtxt bind
783 = hang (ptext SLIT("In a pattern binding:")) 4 (ppr bind)
785 -----------------------------------------------
787 = sep [ptext SLIT("In a SPECIALIZE pragma for a value:"),
788 nest 4 (ppr v <+> dcolon <+> ppr ty)]
790 -----------------------------------------------
791 sigContextsErr = ptext SLIT("Mismatched contexts")
793 sigContextsCtxt s1 s2
794 = vcat [ptext SLIT("When matching the contexts of the signatures for"),
795 nest 2 (vcat [ppr s1 <+> dcolon <+> ppr (idType s1),
796 ppr s2 <+> dcolon <+> ppr (idType s2)]),
797 ptext SLIT("The signature contexts in a mutually recursive group should all be identical")]
799 -----------------------------------------------
800 unliftedBindErr flavour mbind
801 = hang (text flavour <+> ptext SLIT("bindings for unlifted types aren't allowed:"))
804 -----------------------------------------------
805 existentialExplode mbinds
806 = hang (vcat [text "My brain just exploded.",
807 text "I can't handle pattern bindings for existentially-quantified constructors.",
808 text "In the binding group"])
811 -----------------------------------------------
812 restrictedBindCtxtErr binder_names
813 = hang (ptext SLIT("Illegal overloaded type signature(s)"))
814 4 (vcat [ptext SLIT("in a binding group for") <+> pprBinders binder_names,
815 ptext SLIT("that falls under the monomorphism restriction")])
818 = ptext SLIT("When generalising the type(s) for") <+> pprBinders binder_names
820 -- Used in error messages
821 -- Use quotes for a single one; they look a bit "busy" for several
822 pprBinders [bndr] = quotes (ppr bndr)
823 pprBinders bndrs = pprWithCommas ppr bndrs