2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcBinds]{TcBinds}
7 module TcBinds ( tcBindsAndThen, tcTopBinds, tcMonoBinds, tcSpecSigs ) where
9 #include "HsVersions.h"
11 import {-# SOURCE #-} TcMatches ( tcGRHSsPat, tcMatchesFun )
12 import {-# SOURCE #-} TcExpr ( tcCheckSigma, tcCheckRho )
14 import CmdLineOpts ( DynFlag(Opt_NoMonomorphismRestriction) )
15 import HsSyn ( HsExpr(..), HsBind(..), LHsBind, LHsBinds, Sig(..),
16 LSig, Match(..), HsBindGroup(..), IPBind(..),
17 collectSigTysFromHsBinds, collectHsBindBinders,
19 import TcHsSyn ( TcId, zonkId, mkHsLet )
22 import Inst ( InstOrigin(..), newDicts, newIPDict, instToId )
23 import TcEnv ( tcExtendLocalValEnv, tcExtendLocalValEnv2, newLocalName )
24 import TcUnify ( Expected(..), newHole, unifyTauTyLists, checkSigTyVarsWrt, sigCtxt )
25 import TcSimplify ( tcSimplifyInfer, tcSimplifyInferCheck, tcSimplifyRestricted,
26 tcSimplifyToDicts, tcSimplifyIPs )
27 import TcHsType ( tcHsSigType, UserTypeCtxt(..), TcSigInfo(..),
28 tcTySig, maybeSig, tcAddScopedTyVars
30 import TcPat ( tcPat, tcSubPat, tcMonoPatBndr )
31 import TcSimplify ( bindInstsOfLocalFuns )
32 import TcMType ( newTyVar, newTyVarTy, zonkTcTyVarToTyVar )
33 import TcType ( TcTyVar, mkTyVarTy, mkForAllTys, mkFunTys, tyVarsOfType,
34 mkPredTy, mkForAllTy, isUnLiftedType )
35 import Kind ( liftedTypeKind, argTypeKind, isUnliftedTypeKind )
37 import CoreFVs ( idFreeTyVars )
38 import Id ( mkLocalId, mkSpecPragmaId, setInlinePragma )
39 import Var ( idType, idName )
40 import Name ( Name, getSrcLoc )
42 import Var ( tyVarKind )
44 import SrcLoc ( Located(..), srcLocSpan, unLoc, noLoc )
46 import Util ( isIn, equalLength )
47 import BasicTypes ( TopLevelFlag(..), RecFlag(..), isNonRec, isRec,
48 isNotTopLevel, isAlwaysActive )
49 import FiniteMap ( listToFM, lookupFM )
54 %************************************************************************
56 \subsection{Type-checking bindings}
58 %************************************************************************
60 @tcBindsAndThen@ typechecks a @HsBinds@. The "and then" part is because
61 it needs to know something about the {\em usage} of the things bound,
62 so that it can create specialisations of them. So @tcBindsAndThen@
63 takes a function which, given an extended environment, E, typechecks
64 the scope of the bindings returning a typechecked thing and (most
65 important) an LIE. It is this LIE which is then used as the basis for
66 specialising the things bound.
68 @tcBindsAndThen@ also takes a "combiner" which glues together the
69 bindings and the "thing" to make a new "thing".
71 The real work is done by @tcBindWithSigsAndThen@.
73 Recursive and non-recursive binds are handled in essentially the same
74 way: because of uniques there are no scoping issues left. The only
75 difference is that non-recursive bindings can bind primitive values.
77 Even for non-recursive binding groups we add typings for each binder
78 to the LVE for the following reason. When each individual binding is
79 checked the type of its LHS is unified with that of its RHS; and
80 type-checking the LHS of course requires that the binder is in scope.
82 At the top-level the LIE is sure to contain nothing but constant
83 dictionaries, which we resolve at the module level.
86 tcTopBinds :: [HsBindGroup Name] -> TcM (LHsBinds TcId, TcLclEnv)
87 -- Note: returning the TcLclEnv is more than we really
88 -- want. The bit we care about is the local bindings
89 -- and the free type variables thereof
91 = tc_binds_and_then TopLevel glue binds $
92 getLclEnv `thenM` \ env ->
93 returnM (emptyBag, env)
95 -- The top level bindings are flattened into a giant
96 -- implicitly-mutually-recursive MonoBinds
97 glue (HsBindGroup binds1 _ _) (binds2, env) = (binds1 `unionBags` binds2, env)
98 -- Can't have a HsIPBinds at top level
102 :: (HsBindGroup TcId -> thing -> thing) -- Combinator
103 -> [HsBindGroup Name]
107 tcBindsAndThen = tc_binds_and_then NotTopLevel
109 tc_binds_and_then top_lvl combiner [] do_next
111 tc_binds_and_then top_lvl combiner (group : groups) do_next
112 = tc_bind_and_then top_lvl combiner group $
113 tc_binds_and_then top_lvl combiner groups do_next
115 tc_bind_and_then top_lvl combiner (HsIPBinds binds) do_next
116 = getLIE do_next `thenM` \ (result, expr_lie) ->
117 mapAndUnzipM (wrapLocSndM tc_ip_bind) binds `thenM` \ (avail_ips, binds') ->
119 -- If the binding binds ?x = E, we must now
120 -- discharge any ?x constraints in expr_lie
121 tcSimplifyIPs avail_ips expr_lie `thenM` \ dict_binds ->
123 returnM (combiner (HsIPBinds binds') $
124 combiner (HsBindGroup dict_binds [] Recursive) result)
126 -- I wonder if we should do these one at at time
129 tc_ip_bind (IPBind ip expr)
130 = newTyVarTy argTypeKind `thenM` \ ty ->
131 newIPDict (IPBindOrigin ip) ip ty `thenM` \ (ip', ip_inst) ->
132 tcCheckRho expr ty `thenM` \ expr' ->
133 returnM (ip_inst, (IPBind ip' expr'))
135 tc_bind_and_then top_lvl combiner (HsBindGroup binds sigs is_rec) do_next
139 = -- BRING ANY SCOPED TYPE VARIABLES INTO SCOPE
140 -- Notice that they scope over
141 -- a) the type signatures in the binding group
142 -- b) the bindings in the group
143 -- c) the scope of the binding group (the "in" part)
144 tcAddScopedTyVars (collectSigTysFromHsBinds (bagToList binds)) $
147 TopLevel -- For the top level don't bother will all this
148 -- bindInstsOfLocalFuns stuff. All the top level
149 -- things are rec'd together anyway, so it's fine to
150 -- leave them to the tcSimplifyTop, and quite a bit faster too
151 -> tcBindWithSigs top_lvl binds sigs is_rec `thenM` \ (poly_binds, poly_ids) ->
152 tc_body poly_ids `thenM` \ (prag_binds, thing) ->
153 returnM (combiner (HsBindGroup
154 (poly_binds `unionBags` prag_binds)
159 NotTopLevel -- For nested bindings we must do the bindInstsOfLocalFuns thing.
160 | not (isRec is_rec) -- Non-recursive group
161 -> -- We want to keep non-recursive things non-recursive
162 -- so that we desugar unlifted bindings correctly
163 tcBindWithSigs top_lvl binds sigs is_rec `thenM` \ (poly_binds, poly_ids) ->
164 getLIE (tc_body poly_ids) `thenM` \ ((prag_binds, thing), lie) ->
166 -- Create specialisations of functions bound here
167 bindInstsOfLocalFuns lie poly_ids `thenM` \ lie_binds ->
170 combiner (HsBindGroup poly_binds [] NonRecursive) $
171 combiner (HsBindGroup prag_binds [] NonRecursive) $
172 combiner (HsBindGroup lie_binds [] Recursive) $
173 -- NB: the binds returned by tcSimplify and
174 -- bindInstsOfLocalFuns aren't guaranteed in
175 -- dependency order (though we could change that);
176 -- hence the Recursive marker.
180 -> -- NB: polymorphic recursion means that a function
181 -- may use an instance of itself, we must look at the LIE arising
182 -- from the function's own right hand side. Hence the getLIE
183 -- encloses the tcBindWithSigs.
186 tcBindWithSigs top_lvl binds sigs is_rec `thenM` \ (poly_binds, poly_ids) ->
187 tc_body poly_ids `thenM` \ (prag_binds, thing) ->
188 returnM (poly_ids, poly_binds `unionBags` prag_binds, thing)
189 ) `thenM` \ ((poly_ids, extra_binds, thing), lie) ->
191 bindInstsOfLocalFuns lie poly_ids `thenM` \ lie_binds ->
193 returnM (combiner (HsBindGroup
194 (extra_binds `unionBags` lie_binds)
198 tc_body poly_ids -- Type check the pragmas and "thing inside"
199 = -- Extend the environment to bind the new polymorphic Ids
200 tcExtendLocalValEnv poly_ids $
202 -- Build bindings and IdInfos corresponding to user pragmas
203 tcSpecSigs sigs `thenM` \ prag_binds ->
205 -- Now do whatever happens next, in the augmented envt
206 do_next `thenM` \ thing ->
208 returnM (prag_binds, thing)
212 %************************************************************************
214 \subsection{tcBindWithSigs}
216 %************************************************************************
218 @tcBindWithSigs@ deals with a single binding group. It does generalisation,
219 so all the clever stuff is in here.
221 * binder_names and mbind must define the same set of Names
223 * The Names in tc_ty_sigs must be a subset of binder_names
225 * The Ids in tc_ty_sigs don't necessarily have to have the same name
226 as the Name in the tc_ty_sig
229 tcBindWithSigs :: TopLevelFlag
233 -> TcM (LHsBinds TcId, [TcId])
235 tcBindWithSigs top_lvl mbind sigs is_rec
236 = -- TYPECHECK THE SIGNATURES
237 recoverM (returnM []) (
238 mappM tcTySig [sig | sig@(L _(Sig name _)) <- sigs]
239 ) `thenM` \ tc_ty_sigs ->
241 -- SET UP THE MAIN RECOVERY; take advantage of any type sigs
243 -- If typechecking the binds fails, then return with each
244 -- signature-less binder given type (forall a.a), to minimise subsequent
246 newTyVar liftedTypeKind `thenM` \ alpha_tv ->
248 forall_a_a = mkForAllTy alpha_tv (mkTyVarTy alpha_tv)
249 binder_names = collectHsBindBinders mbind
250 poly_ids = map mk_dummy binder_names
251 mk_dummy name = case maybeSig tc_ty_sigs name of
252 Just sig -> sig_poly_id sig -- Signature
253 Nothing -> mkLocalId name forall_a_a -- No signature
255 traceTc (text "tcBindsWithSigs: error recovery" <+> ppr binder_names) `thenM_`
256 returnM (emptyBag, poly_ids)
259 -- TYPECHECK THE BINDINGS
260 traceTc (ptext SLIT("--------------------------------------------------------")) `thenM_`
261 traceTc (ptext SLIT("Bindings for") <+> ppr (collectHsBindBinders mbind)) `thenM_`
262 getLIE (tcMonoBinds mbind tc_ty_sigs is_rec) `thenM` \ ((mbind', bndr_names_w_ids), lie_req) ->
264 (binder_names, mono_ids) = unzip (bagToList bndr_names_w_ids)
265 tau_tvs = foldr (unionVarSet . tyVarsOfType . idType) emptyVarSet mono_ids
269 -- (it seems a bit crude to have to do getLIE twice,
270 -- but I can't see a better way just now)
271 addSrcSpan (srcLocSpan (minimum (map getSrcLoc binder_names))) $
272 -- TODO: location wrong
274 addErrCtxt (genCtxt binder_names) $
275 getLIE (generalise binder_names mbind tau_tvs lie_req tc_ty_sigs)
276 `thenM` \ ((tc_tyvars_to_gen, dict_binds, dict_ids), lie_free) ->
279 -- ZONK THE GENERALISED TYPE VARIABLES TO REAL TyVars
280 -- This commits any unbound kind variables to boxed kind, by unification
281 -- It's important that the final quanfified type variables
282 -- are fully zonked, *including boxity*, because they'll be
283 -- included in the forall types of the polymorphic Ids.
284 -- At calls of these Ids we'll instantiate fresh type variables from
285 -- them, and we use their boxity then.
286 mappM zonkTcTyVarToTyVar tc_tyvars_to_gen `thenM` \ real_tyvars_to_gen ->
289 -- It's important that the dict Ids are zonked, including the boxity set
290 -- in the previous step, because they are later used to form the type of
291 -- the polymorphic thing, and forall-types must be zonked so far as
292 -- their bound variables are concerned
293 mappM zonkId dict_ids `thenM` \ zonked_dict_ids ->
294 mappM zonkId mono_ids `thenM` \ zonked_mono_ids ->
296 -- BUILD THE POLYMORPHIC RESULT IDs
298 exports = zipWith mk_export binder_names zonked_mono_ids
299 poly_ids = [poly_id | (_, poly_id, _) <- exports]
300 dict_tys = map idType zonked_dict_ids
302 inlines = mkNameSet [ name
303 | L _ (InlineSig True (L _ name) _) <- sigs]
304 -- Any INLINE sig (regardless of phase control)
305 -- makes the RHS look small
307 inline_phases = listToFM [ (name, phase)
308 | L _ (InlineSig _ (L _ name) phase) <- sigs,
309 not (isAlwaysActive phase)]
310 -- Set the IdInfo field to control the inline phase
311 -- AlwaysActive is the default, so don't bother with them
313 mk_export binder_name zonked_mono_id
315 attachInlinePhase inline_phases poly_id,
319 case maybeSig tc_ty_sigs binder_name of
320 Just sig -> (sig_tvs sig, sig_poly_id sig)
321 Nothing -> (real_tyvars_to_gen, new_poly_id)
323 new_poly_id = mkLocalId binder_name poly_ty
324 poly_ty = mkForAllTys real_tyvars_to_gen
326 $ idType zonked_mono_id
327 -- It's important to build a fully-zonked poly_ty, because
328 -- we'll slurp out its free type variables when extending the
329 -- local environment (tcExtendLocalValEnv); if it's not zonked
330 -- it appears to have free tyvars that aren't actually free
334 traceTc (text "binding:" <+> ppr ((zonked_dict_ids, dict_binds),
335 exports, map idType poly_ids)) `thenM_`
337 -- Check for an unlifted, non-overloaded group
338 -- In that case we must make extra checks
339 if any (isUnLiftedType . idType) zonked_mono_ids && null zonked_dict_ids
340 then -- Some bindings are unlifted
341 checkUnliftedBinds top_lvl is_rec real_tyvars_to_gen mbind `thenM_`
343 extendLIEs lie_req `thenM_`
346 AbsBinds [] [] exports inlines mbind',
347 -- Do not generate even any x=y bindings
351 else -- The normal case
352 extendLIEs lie_free `thenM_`
355 AbsBinds real_tyvars_to_gen
359 (dict_binds `unionBags` mbind'),
363 attachInlinePhase inline_phases bndr
364 = case lookupFM inline_phases (idName bndr) of
365 Just prag -> bndr `setInlinePragma` prag
368 -- Check that non-overloaded unlifted bindings are
371 -- c) non-polymorphic
372 -- d) not a multiple-binding group (more or less implied by (a))
374 checkUnliftedBinds top_lvl is_rec real_tyvars_to_gen mbind
375 = ASSERT( not (any (isUnliftedTypeKind . tyVarKind) real_tyvars_to_gen) )
376 -- The instCantBeGeneralised stuff in tcSimplify should have
377 -- already raised an error if we're trying to generalise an
378 -- unboxed tyvar (NB: unboxed tyvars are always introduced
379 -- along with a class constraint) and it's better done there
380 -- because we have more precise origin information.
381 -- That's why we just use an ASSERT here.
383 checkTc (isNotTopLevel top_lvl)
384 (unliftedBindErr "Top-level" mbind) `thenM_`
385 checkTc (isNonRec is_rec)
386 (unliftedBindErr "Recursive" mbind) `thenM_`
387 checkTc (isSingletonBag mbind)
388 (unliftedBindErr "Multiple" mbind) `thenM_`
389 checkTc (null real_tyvars_to_gen)
390 (unliftedBindErr "Polymorphic" mbind)
394 Polymorphic recursion
395 ~~~~~~~~~~~~~~~~~~~~~
396 The game plan for polymorphic recursion in the code above is
398 * Bind any variable for which we have a type signature
399 to an Id with a polymorphic type. Then when type-checking
400 the RHSs we'll make a full polymorphic call.
402 This fine, but if you aren't a bit careful you end up with a horrendous
403 amount of partial application and (worse) a huge space leak. For example:
405 f :: Eq a => [a] -> [a]
408 If we don't take care, after typechecking we get
410 f = /\a -> \d::Eq a -> let f' = f a d
414 Notice the the stupid construction of (f a d), which is of course
415 identical to the function we're executing. In this case, the
416 polymorphic recursion isn't being used (but that's a very common case).
419 f = /\a -> \d::Eq a -> letrec
420 fm = \ys:[a] -> ...fm...
424 This can lead to a massive space leak, from the following top-level defn
430 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
431 f' is another thunk which evaluates to the same thing... and you end
432 up with a chain of identical values all hung onto by the CAF ff.
436 = let f' = f Int dEqInt in \ys. ...f'...
438 = let f' = let f' = f Int dEqInt in \ys. ...f'...
442 Solution: when typechecking the RHSs we always have in hand the
443 *monomorphic* Ids for each binding. So we just need to make sure that
444 if (Method f a d) shows up in the constraints emerging from (...f...)
445 we just use the monomorphic Id. We achieve this by adding monomorphic Ids
446 to the "givens" when simplifying constraints. That's what the "lies_avail"
450 %************************************************************************
452 \subsection{getTyVarsToGen}
454 %************************************************************************
457 generalise binder_names mbind tau_tvs lie_req sigs =
459 -- check for -fno-monomorphism-restriction
460 doptM Opt_NoMonomorphismRestriction `thenM` \ no_MR ->
461 let is_unrestricted | no_MR = True
462 | otherwise = isUnRestrictedGroup tysig_names mbind
465 if not is_unrestricted then -- RESTRICTED CASE
466 -- Check signature contexts are empty
467 checkTc (all is_mono_sig sigs)
468 (restrictedBindCtxtErr binder_names) `thenM_`
470 -- Now simplify with exactly that set of tyvars
471 -- We have to squash those Methods
472 tcSimplifyRestricted doc tau_tvs lie_req `thenM` \ (qtvs, binds) ->
474 -- Check that signature type variables are OK
475 checkSigsTyVars qtvs sigs `thenM` \ final_qtvs ->
477 returnM (final_qtvs, binds, [])
479 else if null sigs then -- UNRESTRICTED CASE, NO TYPE SIGS
480 tcSimplifyInfer doc tau_tvs lie_req
482 else -- UNRESTRICTED CASE, WITH TYPE SIGS
483 -- CHECKING CASE: Unrestricted group, there are type signatures
484 -- Check signature contexts are identical
485 checkSigsCtxts sigs `thenM` \ (sig_avails, sig_dicts) ->
487 -- Check that the needed dicts can be
488 -- expressed in terms of the signature ones
489 tcSimplifyInferCheck doc tau_tvs sig_avails lie_req `thenM` \ (forall_tvs, dict_binds) ->
491 -- Check that signature type variables are OK
492 checkSigsTyVars forall_tvs sigs `thenM` \ final_qtvs ->
494 returnM (final_qtvs, dict_binds, sig_dicts)
497 tysig_names = map (idName . sig_poly_id) sigs
498 is_mono_sig sig = null (sig_theta sig)
500 doc = ptext SLIT("type signature(s) for") <+> pprBinders binder_names
502 -----------------------
503 -- CHECK THAT ALL THE SIGNATURE CONTEXTS ARE UNIFIABLE
504 -- The type signatures on a mutually-recursive group of definitions
505 -- must all have the same context (or none).
507 -- We unify them because, with polymorphic recursion, their types
508 -- might not otherwise be related. This is a rather subtle issue.
510 checkSigsCtxts sigs@(TySigInfo { sig_poly_id = id1, sig_tvs = sig_tvs, sig_theta = theta1, sig_loc = span}
513 mappM_ check_one other_sigs `thenM_`
515 returnM ([], []) -- Non-overloaded type signatures
517 newDicts SignatureOrigin theta1 `thenM` \ sig_dicts ->
519 -- The "sig_avails" is the stuff available. We get that from
520 -- the context of the type signature, BUT ALSO the lie_avail
521 -- so that polymorphic recursion works right (see comments at end of fn)
522 sig_avails = sig_dicts ++ sig_meths
524 returnM (sig_avails, map instToId sig_dicts)
526 sig1_dict_tys = map mkPredTy theta1
527 sig_meths = concatMap sig_insts sigs
529 check_one (TySigInfo {sig_poly_id = id, sig_theta = theta})
530 = addErrCtxt (sigContextsCtxt id1 id) $
531 checkTc (equalLength theta theta1) sigContextsErr `thenM_`
532 unifyTauTyLists sig1_dict_tys (map mkPredTy theta)
534 checkSigsTyVars :: [TcTyVar] -> [TcSigInfo] -> TcM [TcTyVar]
535 checkSigsTyVars qtvs sigs
536 = mappM check_one sigs `thenM` \ sig_tvs_s ->
538 -- Sigh. Make sure that all the tyvars in the type sigs
539 -- appear in the returned ty var list, which is what we are
540 -- going to generalise over. Reason: we occasionally get
542 -- type T a = () -> ()
545 -- Here, 'a' won't appear in qtvs, so we have to add it
547 sig_tvs = foldl extendVarSetList emptyVarSet sig_tvs_s
548 all_tvs = extendVarSetList sig_tvs qtvs
550 returnM (varSetElems all_tvs)
552 check_one (TySigInfo {sig_poly_id = id, sig_tvs = tvs, sig_theta = theta, sig_tau = tau})
553 = addErrCtxt (ptext SLIT("In the type signature for")
554 <+> quotes (ppr id)) $
555 addErrCtxtM (sigCtxt id tvs theta tau) $
556 checkSigTyVarsWrt (idFreeTyVars id) tvs
559 @getTyVarsToGen@ decides what type variables to generalise over.
561 For a "restricted group" -- see the monomorphism restriction
562 for a definition -- we bind no dictionaries, and
563 remove from tyvars_to_gen any constrained type variables
565 *Don't* simplify dicts at this point, because we aren't going
566 to generalise over these dicts. By the time we do simplify them
567 we may well know more. For example (this actually came up)
569 f x = array ... xs where xs = [1,2,3,4,5]
570 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
571 stuff. If we simplify only at the f-binding (not the xs-binding)
572 we'll know that the literals are all Ints, and we can just produce
575 Find all the type variables involved in overloading, the
576 "constrained_tyvars". These are the ones we *aren't* going to
577 generalise. We must be careful about doing this:
579 (a) If we fail to generalise a tyvar which is not actually
580 constrained, then it will never, ever get bound, and lands
581 up printed out in interface files! Notorious example:
582 instance Eq a => Eq (Foo a b) where ..
583 Here, b is not constrained, even though it looks as if it is.
584 Another, more common, example is when there's a Method inst in
585 the LIE, whose type might very well involve non-overloaded
587 [NOTE: Jan 2001: I don't understand the problem here so I'm doing
588 the simple thing instead]
590 (b) On the other hand, we mustn't generalise tyvars which are constrained,
591 because we are going to pass on out the unmodified LIE, with those
592 tyvars in it. They won't be in scope if we've generalised them.
594 So we are careful, and do a complete simplification just to find the
595 constrained tyvars. We don't use any of the results, except to
596 find which tyvars are constrained.
599 isUnRestrictedGroup :: [Name] -- Signatures given for these
602 isUnRestrictedGroup sigs binds = all (unrestricted . unLoc) (bagToList binds)
604 unrestricted (PatBind other _) = False
605 unrestricted (VarBind v _) = v `is_elem` sigs
606 unrestricted (FunBind v _ matches) = unrestricted_match matches
607 || unLoc v `is_elem` sigs
609 unrestricted_match (L _ (Match [] _ _) : _) = False
610 -- No args => like a pattern binding
611 unrestricted_match other = True
612 -- Some args => a function binding
614 is_elem v vs = isIn "isUnResMono" v vs
618 %************************************************************************
620 \subsection{tcMonoBind}
622 %************************************************************************
624 @tcMonoBinds@ deals with a single @MonoBind@.
625 The signatures have been dealt with already.
628 tcMonoBinds :: LHsBinds Name
629 -> [TcSigInfo] -> RecFlag
630 -> TcM (LHsBinds TcId,
631 Bag (Name, -- Bound names
632 TcId)) -- Corresponding monomorphic bound things
634 tcMonoBinds mbinds tc_ty_sigs is_rec
636 -- 1. Check the patterns, building up an environment binding
637 -- the variables in this group (in the recursive case)
638 -- 2. Extend the environment
640 = mapBagM tc_lbind_pats mbinds `thenM` \ bag_of_pairs ->
644 (returnM (emptyBag, emptyBag), emptyBag)
646 combine (complete_it1, xve1) (complete_it2, xve2)
647 = (complete_it, xve1 `unionBags` xve2)
649 complete_it = complete_it1 `thenM` \ (b1, bs1) ->
650 complete_it2 `thenM` \ (b2, bs2) ->
651 returnM (b1 `consBag` b2, bs1 `unionBags` bs2)
653 tcExtendLocalValEnv2 (bagToList xve) complete_it
655 tc_lbind_pats :: LHsBind Name
656 -> TcM (TcM (LHsBind TcId, Bag (Name,TcId)), -- Completer
658 -- wrapper for tc_bind_pats to deal with the location stuff
659 tc_lbind_pats (L loc bind)
660 = addSrcSpan loc $ do
661 (tc, bag) <- tc_bind_pats bind
662 return (wrap tc, bag)
664 wrap tc = addSrcSpan loc $ do
666 return (L loc bind, stuff)
669 tc_bind_pats :: HsBind Name
670 -> TcM (TcM (HsBind TcId, Bag (Name,TcId)), -- Completer
672 tc_bind_pats (FunBind (L nm_loc name) inf matches)
674 -- a) Type sig supplied
675 -- b) No type sig and recursive
676 -- c) No type sig and non-recursive
678 | Just sig <- maybeSig tc_ty_sigs name
679 = let -- (a) There is a type signature
680 -- Use it for the environment extension, and check
681 -- the RHS has the appropriate type (with outer for-alls stripped off)
682 mono_id = sig_mono_id sig
683 mono_ty = idType mono_id
684 complete_it = tcMatchesFun name matches (Check mono_ty) `thenM` \ matches' ->
685 returnM (FunBind (L nm_loc mono_id) inf matches',
686 unitBag (name, mono_id))
688 returnM (complete_it, if isRec is_rec then unitBag (name, sig_poly_id sig)
692 = -- (b) No type signature, and recursive
693 -- So we must use an ordinary H-M type variable
694 -- which means the variable gets an inferred tau-type
695 newLocalName name `thenM` \ mono_name ->
696 newTyVarTy argTypeKind `thenM` \ mono_ty ->
698 mono_id = mkLocalId mono_name mono_ty
699 complete_it = tcMatchesFun name matches (Check mono_ty) `thenM` \ matches' ->
700 returnM (FunBind (L nm_loc mono_id) inf matches',
701 unitBag (name, mono_id))
703 returnM (complete_it, unitBag (name, mono_id))
705 | otherwise -- (c) No type signature, and non-recursive
706 = let -- So we can use a 'hole' type to infer a higher-rank type
708 = newHole `thenM` \ hole ->
709 tcMatchesFun name matches (Infer hole) `thenM` \ matches' ->
710 readMutVar hole `thenM` \ fun_ty ->
711 newLocalName name `thenM` \ mono_name ->
713 mono_id = mkLocalId mono_name fun_ty
715 returnM (FunBind (L nm_loc mono_id) inf matches',
716 unitBag (name, mono_id))
718 returnM (complete_it, emptyBag)
720 tc_bind_pats bind@(PatBind pat grhss)
721 = -- Now typecheck the pattern
722 -- We do now support binding fresh (not-already-in-scope) scoped
723 -- type variables in the pattern of a pattern binding.
724 -- For example, this is now legal:
726 -- The type variables are brought into scope in tc_binds_and_then,
727 -- so we don't have to do anything here.
728 newHole `thenM` \ hole ->
729 tcPat tc_pat_bndr pat (Infer hole) `thenM` \ (pat', tvs, ids, lie_avail) ->
730 readMutVar hole `thenM` \ pat_ty ->
732 -- Don't know how to deal with pattern-bound existentials yet
733 checkTc (isEmptyBag tvs && null lie_avail)
734 (existentialExplode bind) `thenM_`
737 complete_it = addErrCtxt (patMonoBindsCtxt bind) $
738 tcGRHSsPat grhss (Check pat_ty) `thenM` \ grhss' ->
739 returnM (PatBind pat' grhss', ids)
741 returnM (complete_it, if isRec is_rec then ids else emptyBag)
743 -- tc_pat_bndr is used when dealing with a LHS binder in a pattern.
744 -- If there was a type sig for that Id, we want to make it much
745 -- as if that type signature had been on the binder as a SigPatIn.
746 -- We check for a type signature; if there is one, we use the mono_id
747 -- from the signature. This is how we make sure the tau part of the
748 -- signature actually matches the type of the LHS; then tc_bind_pats
749 -- ensures the LHS and RHS have the same type
751 tc_pat_bndr name pat_ty
752 = case maybeSig tc_ty_sigs name of
753 Nothing -> newLocalName name `thenM` \ bndr_name ->
754 tcMonoPatBndr bndr_name pat_ty
756 Just sig -> addSrcSpan (srcLocSpan (getSrcLoc name)) $
757 -- TODO: location wrong
758 tcSubPat (idType mono_id) pat_ty `thenM` \ co_fn ->
759 returnM (co_fn, mono_id)
761 mono_id = sig_mono_id sig
765 %************************************************************************
767 \subsection{SPECIALIZE pragmas}
769 %************************************************************************
771 @tcSpecSigs@ munches up the specialisation "signatures" that arise through *user*
772 pragmas. It is convenient for them to appear in the @[RenamedSig]@
773 part of a binding because then the same machinery can be used for
774 moving them into place as is done for type signatures.
779 f :: Ord a => [a] -> b -> b
780 {-# SPECIALIZE f :: [Int] -> b -> b #-}
783 For this we generate:
785 f* = /\ b -> let d1 = ...
789 where f* is a SpecPragmaId. The **sole** purpose of SpecPragmaIds is to
790 retain a right-hand-side that the simplifier will otherwise discard as
791 dead code... the simplifier has a flag that tells it not to discard
792 SpecPragmaId bindings.
794 In this case the f* retains a call-instance of the overloaded
795 function, f, (including appropriate dictionaries) so that the
796 specialiser will subsequently discover that there's a call of @f@ at
797 Int, and will create a specialisation for @f@. After that, the
798 binding for @f*@ can be discarded.
800 We used to have a form
801 {-# SPECIALISE f :: <type> = g #-}
802 which promised that g implemented f at <type>, but we do that with
804 {-# SPECIALISE (f::<type) = g #-}
807 tcSpecSigs :: [LSig Name] -> TcM (LHsBinds TcId)
808 tcSpecSigs (L loc (SpecSig (L nm_loc name) poly_ty) : sigs)
809 = -- SPECIALISE f :: forall b. theta => tau = g
811 addErrCtxt (valSpecSigCtxt name poly_ty) $
813 -- Get and instantiate its alleged specialised type
814 tcHsSigType (FunSigCtxt name) poly_ty `thenM` \ sig_ty ->
816 -- Check that f has a more general type, and build a RHS for
817 -- the spec-pragma-id at the same time
818 getLIE (tcCheckSigma (L nm_loc (HsVar name)) sig_ty) `thenM` \ (spec_expr, spec_lie) ->
820 -- Squeeze out any Methods (see comments with tcSimplifyToDicts)
821 tcSimplifyToDicts spec_lie `thenM` \ spec_binds ->
823 -- Just specialise "f" by building a SpecPragmaId binding
824 -- It is the thing that makes sure we don't prematurely
825 -- dead-code-eliminate the binding we are really interested in.
826 newLocalName name `thenM` \ spec_name ->
828 spec_bind = VarBind (mkSpecPragmaId spec_name sig_ty)
829 (mkHsLet spec_binds spec_expr)
832 -- Do the rest and combine
833 tcSpecSigs sigs `thenM` \ binds_rest ->
834 returnM (binds_rest `snocBag` L loc spec_bind)
836 tcSpecSigs (other_sig : sigs) = tcSpecSigs sigs
837 tcSpecSigs [] = returnM emptyBag
840 %************************************************************************
842 \subsection[TcBinds-errors]{Error contexts and messages}
844 %************************************************************************
848 patMonoBindsCtxt bind
849 = hang (ptext SLIT("In a pattern binding:")) 4 (ppr bind)
851 -----------------------------------------------
853 = sep [ptext SLIT("In a SPECIALIZE pragma for a value:"),
854 nest 4 (ppr v <+> dcolon <+> ppr ty)]
856 -----------------------------------------------
857 sigContextsErr = ptext SLIT("Mismatched contexts")
859 sigContextsCtxt s1 s2
860 = vcat [ptext SLIT("When matching the contexts of the signatures for"),
861 nest 2 (vcat [ppr s1 <+> dcolon <+> ppr (idType s1),
862 ppr s2 <+> dcolon <+> ppr (idType s2)]),
863 ptext SLIT("The signature contexts in a mutually recursive group should all be identical")]
865 -----------------------------------------------
866 unliftedBindErr flavour mbind
867 = hang (text flavour <+> ptext SLIT("bindings for unlifted types aren't allowed:"))
870 -----------------------------------------------
871 existentialExplode mbinds
872 = hang (vcat [text "My brain just exploded.",
873 text "I can't handle pattern bindings for existentially-quantified constructors.",
874 text "In the binding group"])
877 -----------------------------------------------
878 restrictedBindCtxtErr binder_names
879 = hang (ptext SLIT("Illegal overloaded type signature(s)"))
880 4 (vcat [ptext SLIT("in a binding group for") <+> pprBinders binder_names,
881 ptext SLIT("that falls under the monomorphism restriction")])
884 = ptext SLIT("When generalising the type(s) for") <+> pprBinders binder_names
886 -- Used in error messages
887 -- Use quotes for a single one; they look a bit "busy" for several
888 pprBinders [bndr] = quotes (ppr bndr)
889 pprBinders bndrs = pprWithCommas ppr bndrs