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, getLoc )
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 (getLoc (head (bagToList mbind))) $
272 -- TODO: location a bit awkward, but the mbinds have been
273 -- dependency analysed and may no longer be adjacent
275 addErrCtxt (genCtxt binder_names) $
276 getLIE (generalise binder_names mbind tau_tvs lie_req tc_ty_sigs)
277 `thenM` \ ((tc_tyvars_to_gen, dict_binds, dict_ids), lie_free) ->
280 -- ZONK THE GENERALISED TYPE VARIABLES TO REAL TyVars
281 -- This commits any unbound kind variables to boxed kind, by unification
282 -- It's important that the final quanfified type variables
283 -- are fully zonked, *including boxity*, because they'll be
284 -- included in the forall types of the polymorphic Ids.
285 -- At calls of these Ids we'll instantiate fresh type variables from
286 -- them, and we use their boxity then.
287 mappM zonkTcTyVarToTyVar tc_tyvars_to_gen `thenM` \ real_tyvars_to_gen ->
290 -- It's important that the dict Ids are zonked, including the boxity set
291 -- in the previous step, because they are later used to form the type of
292 -- the polymorphic thing, and forall-types must be zonked so far as
293 -- their bound variables are concerned
294 mappM zonkId dict_ids `thenM` \ zonked_dict_ids ->
295 mappM zonkId mono_ids `thenM` \ zonked_mono_ids ->
297 -- BUILD THE POLYMORPHIC RESULT IDs
299 exports = zipWith mk_export binder_names zonked_mono_ids
300 poly_ids = [poly_id | (_, poly_id, _) <- exports]
301 dict_tys = map idType zonked_dict_ids
303 inlines = mkNameSet [ name
304 | L _ (InlineSig True (L _ name) _) <- sigs]
305 -- Any INLINE sig (regardless of phase control)
306 -- makes the RHS look small
308 inline_phases = listToFM [ (name, phase)
309 | L _ (InlineSig _ (L _ name) phase) <- sigs,
310 not (isAlwaysActive phase)]
311 -- Set the IdInfo field to control the inline phase
312 -- AlwaysActive is the default, so don't bother with them
314 mk_export binder_name zonked_mono_id
316 attachInlinePhase inline_phases poly_id,
320 case maybeSig tc_ty_sigs binder_name of
321 Just sig -> (sig_tvs sig, sig_poly_id sig)
322 Nothing -> (real_tyvars_to_gen, new_poly_id)
324 new_poly_id = mkLocalId binder_name poly_ty
325 poly_ty = mkForAllTys real_tyvars_to_gen
327 $ idType zonked_mono_id
328 -- It's important to build a fully-zonked poly_ty, because
329 -- we'll slurp out its free type variables when extending the
330 -- local environment (tcExtendLocalValEnv); if it's not zonked
331 -- it appears to have free tyvars that aren't actually free
335 traceTc (text "binding:" <+> ppr ((zonked_dict_ids, dict_binds),
336 exports, map idType poly_ids)) `thenM_`
338 -- Check for an unlifted, non-overloaded group
339 -- In that case we must make extra checks
340 if any (isUnLiftedType . idType) zonked_mono_ids && null zonked_dict_ids
341 then -- Some bindings are unlifted
342 checkUnliftedBinds top_lvl is_rec real_tyvars_to_gen mbind `thenM_`
344 extendLIEs lie_req `thenM_`
347 AbsBinds [] [] exports inlines mbind',
348 -- Do not generate even any x=y bindings
352 else -- The normal case
353 extendLIEs lie_free `thenM_`
356 AbsBinds real_tyvars_to_gen
360 (dict_binds `unionBags` mbind'),
364 attachInlinePhase inline_phases bndr
365 = case lookupFM inline_phases (idName bndr) of
366 Just prag -> bndr `setInlinePragma` prag
369 -- Check that non-overloaded unlifted bindings are
372 -- c) non-polymorphic
373 -- d) not a multiple-binding group (more or less implied by (a))
375 checkUnliftedBinds top_lvl is_rec real_tyvars_to_gen mbind
376 = ASSERT( not (any (isUnliftedTypeKind . tyVarKind) real_tyvars_to_gen) )
377 -- The instCantBeGeneralised stuff in tcSimplify should have
378 -- already raised an error if we're trying to generalise an
379 -- unboxed tyvar (NB: unboxed tyvars are always introduced
380 -- along with a class constraint) and it's better done there
381 -- because we have more precise origin information.
382 -- That's why we just use an ASSERT here.
384 checkTc (isNotTopLevel top_lvl)
385 (unliftedBindErr "Top-level" mbind) `thenM_`
386 checkTc (isNonRec is_rec)
387 (unliftedBindErr "Recursive" mbind) `thenM_`
388 checkTc (isSingletonBag mbind)
389 (unliftedBindErr "Multiple" mbind) `thenM_`
390 checkTc (null real_tyvars_to_gen)
391 (unliftedBindErr "Polymorphic" mbind)
395 Polymorphic recursion
396 ~~~~~~~~~~~~~~~~~~~~~
397 The game plan for polymorphic recursion in the code above is
399 * Bind any variable for which we have a type signature
400 to an Id with a polymorphic type. Then when type-checking
401 the RHSs we'll make a full polymorphic call.
403 This fine, but if you aren't a bit careful you end up with a horrendous
404 amount of partial application and (worse) a huge space leak. For example:
406 f :: Eq a => [a] -> [a]
409 If we don't take care, after typechecking we get
411 f = /\a -> \d::Eq a -> let f' = f a d
415 Notice the the stupid construction of (f a d), which is of course
416 identical to the function we're executing. In this case, the
417 polymorphic recursion isn't being used (but that's a very common case).
420 f = /\a -> \d::Eq a -> letrec
421 fm = \ys:[a] -> ...fm...
425 This can lead to a massive space leak, from the following top-level defn
431 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
432 f' is another thunk which evaluates to the same thing... and you end
433 up with a chain of identical values all hung onto by the CAF ff.
437 = let f' = f Int dEqInt in \ys. ...f'...
439 = let f' = let f' = f Int dEqInt in \ys. ...f'...
443 Solution: when typechecking the RHSs we always have in hand the
444 *monomorphic* Ids for each binding. So we just need to make sure that
445 if (Method f a d) shows up in the constraints emerging from (...f...)
446 we just use the monomorphic Id. We achieve this by adding monomorphic Ids
447 to the "givens" when simplifying constraints. That's what the "lies_avail"
451 %************************************************************************
453 \subsection{getTyVarsToGen}
455 %************************************************************************
458 generalise binder_names mbind tau_tvs lie_req sigs =
460 -- check for -fno-monomorphism-restriction
461 doptM Opt_NoMonomorphismRestriction `thenM` \ no_MR ->
462 let is_unrestricted | no_MR = True
463 | otherwise = isUnRestrictedGroup tysig_names mbind
466 if not is_unrestricted then -- RESTRICTED CASE
467 -- Check signature contexts are empty
468 checkTc (all is_mono_sig sigs)
469 (restrictedBindCtxtErr binder_names) `thenM_`
471 -- Now simplify with exactly that set of tyvars
472 -- We have to squash those Methods
473 tcSimplifyRestricted doc tau_tvs lie_req `thenM` \ (qtvs, binds) ->
475 -- Check that signature type variables are OK
476 checkSigsTyVars qtvs sigs `thenM` \ final_qtvs ->
478 returnM (final_qtvs, binds, [])
480 else if null sigs then -- UNRESTRICTED CASE, NO TYPE SIGS
481 tcSimplifyInfer doc tau_tvs lie_req
483 else -- UNRESTRICTED CASE, WITH TYPE SIGS
484 -- CHECKING CASE: Unrestricted group, there are type signatures
485 -- Check signature contexts are identical
486 checkSigsCtxts sigs `thenM` \ (sig_avails, sig_dicts) ->
488 -- Check that the needed dicts can be
489 -- expressed in terms of the signature ones
490 tcSimplifyInferCheck doc tau_tvs sig_avails lie_req `thenM` \ (forall_tvs, dict_binds) ->
492 -- Check that signature type variables are OK
493 checkSigsTyVars forall_tvs sigs `thenM` \ final_qtvs ->
495 returnM (final_qtvs, dict_binds, sig_dicts)
498 tysig_names = map (idName . sig_poly_id) sigs
499 is_mono_sig sig = null (sig_theta sig)
501 doc = ptext SLIT("type signature(s) for") <+> pprBinders binder_names
503 -----------------------
504 -- CHECK THAT ALL THE SIGNATURE CONTEXTS ARE UNIFIABLE
505 -- The type signatures on a mutually-recursive group of definitions
506 -- must all have the same context (or none).
508 -- We unify them because, with polymorphic recursion, their types
509 -- might not otherwise be related. This is a rather subtle issue.
511 checkSigsCtxts sigs@(TySigInfo { sig_poly_id = id1, sig_tvs = sig_tvs, sig_theta = theta1, sig_loc = span}
514 mappM_ check_one other_sigs `thenM_`
516 returnM ([], []) -- Non-overloaded type signatures
518 newDicts SignatureOrigin theta1 `thenM` \ sig_dicts ->
520 -- The "sig_avails" is the stuff available. We get that from
521 -- the context of the type signature, BUT ALSO the lie_avail
522 -- so that polymorphic recursion works right (see comments at end of fn)
523 sig_avails = sig_dicts ++ sig_meths
525 returnM (sig_avails, map instToId sig_dicts)
527 sig1_dict_tys = map mkPredTy theta1
528 sig_meths = concatMap sig_insts sigs
530 check_one (TySigInfo {sig_poly_id = id, sig_theta = theta})
531 = addErrCtxt (sigContextsCtxt id1 id) $
532 checkTc (equalLength theta theta1) sigContextsErr `thenM_`
533 unifyTauTyLists sig1_dict_tys (map mkPredTy theta)
535 checkSigsTyVars :: [TcTyVar] -> [TcSigInfo] -> TcM [TcTyVar]
536 checkSigsTyVars qtvs sigs
537 = mappM check_one sigs `thenM` \ sig_tvs_s ->
539 -- Sigh. Make sure that all the tyvars in the type sigs
540 -- appear in the returned ty var list, which is what we are
541 -- going to generalise over. Reason: we occasionally get
543 -- type T a = () -> ()
546 -- Here, 'a' won't appear in qtvs, so we have to add it
548 sig_tvs = foldl extendVarSetList emptyVarSet sig_tvs_s
549 all_tvs = extendVarSetList sig_tvs qtvs
551 returnM (varSetElems all_tvs)
553 check_one (TySigInfo {sig_poly_id = id, sig_tvs = tvs, sig_theta = theta, sig_tau = tau})
554 = addErrCtxt (ptext SLIT("In the type signature for")
555 <+> quotes (ppr id)) $
556 addErrCtxtM (sigCtxt id tvs theta tau) $
557 checkSigTyVarsWrt (idFreeTyVars id) tvs
560 @getTyVarsToGen@ decides what type variables to generalise over.
562 For a "restricted group" -- see the monomorphism restriction
563 for a definition -- we bind no dictionaries, and
564 remove from tyvars_to_gen any constrained type variables
566 *Don't* simplify dicts at this point, because we aren't going
567 to generalise over these dicts. By the time we do simplify them
568 we may well know more. For example (this actually came up)
570 f x = array ... xs where xs = [1,2,3,4,5]
571 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
572 stuff. If we simplify only at the f-binding (not the xs-binding)
573 we'll know that the literals are all Ints, and we can just produce
576 Find all the type variables involved in overloading, the
577 "constrained_tyvars". These are the ones we *aren't* going to
578 generalise. We must be careful about doing this:
580 (a) If we fail to generalise a tyvar which is not actually
581 constrained, then it will never, ever get bound, and lands
582 up printed out in interface files! Notorious example:
583 instance Eq a => Eq (Foo a b) where ..
584 Here, b is not constrained, even though it looks as if it is.
585 Another, more common, example is when there's a Method inst in
586 the LIE, whose type might very well involve non-overloaded
588 [NOTE: Jan 2001: I don't understand the problem here so I'm doing
589 the simple thing instead]
591 (b) On the other hand, we mustn't generalise tyvars which are constrained,
592 because we are going to pass on out the unmodified LIE, with those
593 tyvars in it. They won't be in scope if we've generalised them.
595 So we are careful, and do a complete simplification just to find the
596 constrained tyvars. We don't use any of the results, except to
597 find which tyvars are constrained.
600 isUnRestrictedGroup :: [Name] -- Signatures given for these
603 isUnRestrictedGroup sigs binds = all (unrestricted . unLoc) (bagToList binds)
605 unrestricted (PatBind other _) = False
606 unrestricted (VarBind v _) = v `is_elem` sigs
607 unrestricted (FunBind v _ matches) = unrestricted_match matches
608 || unLoc v `is_elem` sigs
610 unrestricted_match (L _ (Match [] _ _) : _) = False
611 -- No args => like a pattern binding
612 unrestricted_match other = True
613 -- Some args => a function binding
615 is_elem v vs = isIn "isUnResMono" v vs
619 %************************************************************************
621 \subsection{tcMonoBind}
623 %************************************************************************
625 @tcMonoBinds@ deals with a single @MonoBind@.
626 The signatures have been dealt with already.
629 tcMonoBinds :: LHsBinds Name
630 -> [TcSigInfo] -> RecFlag
631 -> TcM (LHsBinds TcId,
632 Bag (Name, -- Bound names
633 TcId)) -- Corresponding monomorphic bound things
635 tcMonoBinds mbinds tc_ty_sigs is_rec
637 -- 1. Check the patterns, building up an environment binding
638 -- the variables in this group (in the recursive case)
639 -- 2. Extend the environment
641 = mapBagM tc_lbind_pats mbinds `thenM` \ bag_of_pairs ->
645 (returnM (emptyBag, emptyBag), emptyBag)
647 combine (complete_it1, xve1) (complete_it2, xve2)
648 = (complete_it, xve1 `unionBags` xve2)
650 complete_it = complete_it1 `thenM` \ (b1, bs1) ->
651 complete_it2 `thenM` \ (b2, bs2) ->
652 returnM (b1 `consBag` b2, bs1 `unionBags` bs2)
654 tcExtendLocalValEnv2 (bagToList xve) complete_it
656 tc_lbind_pats :: LHsBind Name
657 -> TcM (TcM (LHsBind TcId, Bag (Name,TcId)), -- Completer
659 -- wrapper for tc_bind_pats to deal with the location stuff
660 tc_lbind_pats (L loc bind)
661 = addSrcSpan loc $ do
662 (tc, bag) <- tc_bind_pats bind
663 return (wrap tc, bag)
665 wrap tc = addSrcSpan loc $ do
667 return (L loc bind, stuff)
670 tc_bind_pats :: HsBind Name
671 -> TcM (TcM (HsBind TcId, Bag (Name,TcId)), -- Completer
673 tc_bind_pats (FunBind (L nm_loc name) inf matches)
675 -- a) Type sig supplied
676 -- b) No type sig and recursive
677 -- c) No type sig and non-recursive
679 | Just sig <- maybeSig tc_ty_sigs name
680 = let -- (a) There is a type signature
681 -- Use it for the environment extension, and check
682 -- the RHS has the appropriate type (with outer for-alls stripped off)
683 mono_id = sig_mono_id sig
684 mono_ty = idType mono_id
685 complete_it = tcMatchesFun name matches (Check mono_ty) `thenM` \ matches' ->
686 returnM (FunBind (L nm_loc mono_id) inf matches',
687 unitBag (name, mono_id))
689 returnM (complete_it, if isRec is_rec then unitBag (name, sig_poly_id sig)
693 = -- (b) No type signature, and recursive
694 -- So we must use an ordinary H-M type variable
695 -- which means the variable gets an inferred tau-type
696 newLocalName name `thenM` \ mono_name ->
697 newTyVarTy argTypeKind `thenM` \ mono_ty ->
699 mono_id = mkLocalId mono_name mono_ty
700 complete_it = tcMatchesFun name matches (Check mono_ty) `thenM` \ matches' ->
701 returnM (FunBind (L nm_loc mono_id) inf matches',
702 unitBag (name, mono_id))
704 returnM (complete_it, unitBag (name, mono_id))
706 | otherwise -- (c) No type signature, and non-recursive
707 = let -- So we can use a 'hole' type to infer a higher-rank type
709 = newHole `thenM` \ hole ->
710 tcMatchesFun name matches (Infer hole) `thenM` \ matches' ->
711 readMutVar hole `thenM` \ fun_ty ->
712 newLocalName name `thenM` \ mono_name ->
714 mono_id = mkLocalId mono_name fun_ty
716 returnM (FunBind (L nm_loc mono_id) inf matches',
717 unitBag (name, mono_id))
719 returnM (complete_it, emptyBag)
721 tc_bind_pats bind@(PatBind pat grhss)
722 = -- Now typecheck the pattern
723 -- We do now support binding fresh (not-already-in-scope) scoped
724 -- type variables in the pattern of a pattern binding.
725 -- For example, this is now legal:
727 -- The type variables are brought into scope in tc_binds_and_then,
728 -- so we don't have to do anything here.
729 newHole `thenM` \ hole ->
730 tcPat tc_pat_bndr pat (Infer hole) `thenM` \ (pat', tvs, ids, lie_avail) ->
731 readMutVar hole `thenM` \ pat_ty ->
733 -- Don't know how to deal with pattern-bound existentials yet
734 checkTc (isEmptyBag tvs && null lie_avail)
735 (existentialExplode bind) `thenM_`
738 complete_it = addErrCtxt (patMonoBindsCtxt bind) $
739 tcGRHSsPat grhss (Check pat_ty) `thenM` \ grhss' ->
740 returnM (PatBind pat' grhss', ids)
742 returnM (complete_it, if isRec is_rec then ids else emptyBag)
744 -- tc_pat_bndr is used when dealing with a LHS binder in a pattern.
745 -- If there was a type sig for that Id, we want to make it much
746 -- as if that type signature had been on the binder as a SigPatIn.
747 -- We check for a type signature; if there is one, we use the mono_id
748 -- from the signature. This is how we make sure the tau part of the
749 -- signature actually matches the type of the LHS; then tc_bind_pats
750 -- ensures the LHS and RHS have the same type
752 tc_pat_bndr name pat_ty
753 = case maybeSig tc_ty_sigs name of
754 Nothing -> newLocalName name `thenM` \ bndr_name ->
755 tcMonoPatBndr bndr_name pat_ty
757 Just sig -> addSrcSpan (srcLocSpan (getSrcLoc name)) $
758 -- TODO: location wrong
759 tcSubPat (idType mono_id) pat_ty `thenM` \ co_fn ->
760 returnM (co_fn, mono_id)
762 mono_id = sig_mono_id sig
766 %************************************************************************
768 \subsection{SPECIALIZE pragmas}
770 %************************************************************************
772 @tcSpecSigs@ munches up the specialisation "signatures" that arise through *user*
773 pragmas. It is convenient for them to appear in the @[RenamedSig]@
774 part of a binding because then the same machinery can be used for
775 moving them into place as is done for type signatures.
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 We used to have a form
802 {-# SPECIALISE f :: <type> = g #-}
803 which promised that g implemented f at <type>, but we do that with
805 {-# SPECIALISE (f::<type) = g #-}
808 tcSpecSigs :: [LSig Name] -> TcM (LHsBinds TcId)
809 tcSpecSigs (L loc (SpecSig (L nm_loc name) poly_ty) : sigs)
810 = -- SPECIALISE f :: forall b. theta => tau = g
812 addErrCtxt (valSpecSigCtxt name poly_ty) $
814 -- Get and instantiate its alleged specialised type
815 tcHsSigType (FunSigCtxt name) poly_ty `thenM` \ sig_ty ->
817 -- Check that f has a more general type, and build a RHS for
818 -- the spec-pragma-id at the same time
819 getLIE (tcCheckSigma (L nm_loc (HsVar name)) sig_ty) `thenM` \ (spec_expr, spec_lie) ->
821 -- Squeeze out any Methods (see comments with tcSimplifyToDicts)
822 tcSimplifyToDicts spec_lie `thenM` \ spec_binds ->
824 -- Just specialise "f" by building a SpecPragmaId binding
825 -- It is the thing that makes sure we don't prematurely
826 -- dead-code-eliminate the binding we are really interested in.
827 newLocalName name `thenM` \ spec_name ->
829 spec_bind = VarBind (mkSpecPragmaId spec_name sig_ty)
830 (mkHsLet spec_binds spec_expr)
833 -- Do the rest and combine
834 tcSpecSigs sigs `thenM` \ binds_rest ->
835 returnM (binds_rest `snocBag` L loc spec_bind)
837 tcSpecSigs (other_sig : sigs) = tcSpecSigs sigs
838 tcSpecSigs [] = returnM emptyBag
841 %************************************************************************
843 \subsection[TcBinds-errors]{Error contexts and messages}
845 %************************************************************************
849 patMonoBindsCtxt bind
850 = hang (ptext SLIT("In a pattern binding:")) 4 (ppr bind)
852 -----------------------------------------------
854 = sep [ptext SLIT("In a SPECIALIZE pragma for a value:"),
855 nest 4 (ppr v <+> dcolon <+> ppr ty)]
857 -----------------------------------------------
858 sigContextsErr = ptext SLIT("Mismatched contexts")
860 sigContextsCtxt s1 s2
861 = vcat [ptext SLIT("When matching the contexts of the signatures for"),
862 nest 2 (vcat [ppr s1 <+> dcolon <+> ppr (idType s1),
863 ppr s2 <+> dcolon <+> ppr (idType s2)]),
864 ptext SLIT("The signature contexts in a mutually recursive group should all be identical")]
866 -----------------------------------------------
867 unliftedBindErr flavour mbind
868 = hang (text flavour <+> ptext SLIT("bindings for unlifted types aren't allowed:"))
871 -----------------------------------------------
872 existentialExplode mbinds
873 = hang (vcat [text "My brain just exploded.",
874 text "I can't handle pattern bindings for existentially-quantified constructors.",
875 text "In the binding group"])
878 -----------------------------------------------
879 restrictedBindCtxtErr binder_names
880 = hang (ptext SLIT("Illegal overloaded type signature(s)"))
881 4 (vcat [ptext SLIT("in a binding group for") <+> pprBinders binder_names,
882 ptext SLIT("that falls under the monomorphism restriction")])
885 = ptext SLIT("When generalising the type(s) for") <+> pprBinders binder_names
887 -- Used in error messages
888 -- Use quotes for a single one; they look a bit "busy" for several
889 pprBinders [bndr] = quotes (ppr bndr)
890 pprBinders bndrs = pprWithCommas ppr bndrs