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 ( tcGRHSs, tcMatchesFun )
12 import {-# SOURCE #-} TcExpr ( tcExpr, tcMonoExpr )
14 import CmdLineOpts ( DynFlag(Opt_NoMonomorphismRestriction) )
15 import HsSyn ( HsExpr(..), HsBinds(..), MonoBinds(..), Sig(..),
16 Match(..), HsMatchContext(..), mkMonoBind,
17 collectMonoBinders, andMonoBinds,
18 collectSigTysFromMonoBinds
20 import RnHsSyn ( RenamedHsBinds, RenamedSig, RenamedMonoBinds )
21 import TcHsSyn ( TcHsBinds, TcMonoBinds, TcId, zonkId, mkHsLet )
24 import Inst ( InstOrigin(..), newDicts, newIPDict, instToId )
25 import TcEnv ( tcExtendLocalValEnv, tcExtendLocalValEnv2, newLocalName )
26 import TcUnify ( unifyTauTyLists, checkSigTyVarsWrt, sigCtxt )
27 import TcSimplify ( tcSimplifyInfer, tcSimplifyInferCheck, tcSimplifyRestricted,
28 tcSimplifyToDicts, tcSimplifyIPs )
29 import TcMonoType ( tcHsSigType, UserTypeCtxt(..), TcSigInfo(..),
30 tcTySig, maybeSig, tcSigPolyId, tcSigMonoId, tcAddScopedTyVars
32 import TcPat ( tcPat, tcSubPat, tcMonoPatBndr )
33 import TcSimplify ( bindInstsOfLocalFuns )
34 import TcMType ( newTyVar, newTyVarTy, newHoleTyVarTy,
35 zonkTcTyVarToTyVar, readHoleResult
37 import TcType ( TcTyVar, mkTyVarTy, mkForAllTys, mkFunTys, tyVarsOfType,
38 mkPredTy, mkForAllTy, isUnLiftedType,
39 unliftedTypeKind, liftedTypeKind, openTypeKind, eqKind
42 import CoreFVs ( idFreeTyVars )
43 import Id ( mkLocalId, mkSpecPragmaId, setInlinePragma )
44 import Var ( idType, idName )
45 import Name ( Name, getSrcLoc )
47 import Var ( tyVarKind )
50 import Util ( isIn, equalLength )
51 import BasicTypes ( TopLevelFlag(..), RecFlag(..), isNonRec, isRec,
52 isNotTopLevel, isAlwaysActive )
53 import FiniteMap ( listToFM, lookupFM )
58 %************************************************************************
60 \subsection{Type-checking bindings}
62 %************************************************************************
64 @tcBindsAndThen@ typechecks a @HsBinds@. The "and then" part is because
65 it needs to know something about the {\em usage} of the things bound,
66 so that it can create specialisations of them. So @tcBindsAndThen@
67 takes a function which, given an extended environment, E, typechecks
68 the scope of the bindings returning a typechecked thing and (most
69 important) an LIE. It is this LIE which is then used as the basis for
70 specialising the things bound.
72 @tcBindsAndThen@ also takes a "combiner" which glues together the
73 bindings and the "thing" to make a new "thing".
75 The real work is done by @tcBindWithSigsAndThen@.
77 Recursive and non-recursive binds are handled in essentially the same
78 way: because of uniques there are no scoping issues left. The only
79 difference is that non-recursive bindings can bind primitive values.
81 Even for non-recursive binding groups we add typings for each binder
82 to the LVE for the following reason. When each individual binding is
83 checked the type of its LHS is unified with that of its RHS; and
84 type-checking the LHS of course requires that the binder is in scope.
86 At the top-level the LIE is sure to contain nothing but constant
87 dictionaries, which we resolve at the module level.
90 tcTopBinds :: RenamedHsBinds -> TcM (TcMonoBinds, TcLclEnv)
91 -- Note: returning the TcLclEnv is more than we really
92 -- want. The bit we care about is the local bindings
93 -- and the free type variables thereof
95 = tc_binds_and_then TopLevel glue binds $
96 getLclEnv `thenM` \ env ->
97 returnM (EmptyMonoBinds, env)
99 -- The top level bindings are flattened into a giant
100 -- implicitly-mutually-recursive MonoBinds
101 glue binds1 (binds2, env) = (flatten binds1 `AndMonoBinds` binds2, env)
102 flatten EmptyBinds = EmptyMonoBinds
103 flatten (b1 `ThenBinds` b2) = flatten b1 `AndMonoBinds` flatten b2
104 flatten (MonoBind b _ _) = b
105 -- Can't have a IPBinds at top level
109 :: (TcHsBinds -> thing -> thing) -- Combinator
114 tcBindsAndThen = tc_binds_and_then NotTopLevel
116 tc_binds_and_then top_lvl combiner EmptyBinds do_next
118 tc_binds_and_then top_lvl combiner (MonoBind EmptyMonoBinds sigs is_rec) do_next
121 tc_binds_and_then top_lvl combiner (ThenBinds b1 b2) do_next
122 = tc_binds_and_then top_lvl combiner b1 $
123 tc_binds_and_then top_lvl combiner b2 $
126 tc_binds_and_then top_lvl combiner (IPBinds binds is_with) do_next
127 = getLIE do_next `thenM` \ (result, expr_lie) ->
128 mapAndUnzipM tc_ip_bind binds `thenM` \ (avail_ips, binds') ->
130 -- If the binding binds ?x = E, we must now
131 -- discharge any ?x constraints in expr_lie
132 tcSimplifyIPs avail_ips expr_lie `thenM` \ dict_binds ->
134 returnM (combiner (IPBinds binds' is_with) $
135 combiner (mkMonoBind Recursive dict_binds) result)
137 -- I wonder if we should do these one at at time
140 tc_ip_bind (ip, expr)
141 = newTyVarTy openTypeKind `thenM` \ ty ->
142 getSrcLocM `thenM` \ loc ->
143 newIPDict (IPBind ip) ip ty `thenM` \ (ip', ip_inst) ->
144 tcMonoExpr expr ty `thenM` \ expr' ->
145 returnM (ip_inst, (ip', expr'))
147 tc_binds_and_then top_lvl combiner (MonoBind bind sigs is_rec) do_next
148 = -- BRING ANY SCOPED TYPE VARIABLES INTO SCOPE
149 -- Notice that they scope over
150 -- a) the type signatures in the binding group
151 -- b) the bindings in the group
152 -- c) the scope of the binding group (the "in" part)
153 tcAddScopedTyVars (collectSigTysFromMonoBinds bind) $
155 tcBindWithSigs top_lvl bind sigs is_rec `thenM` \ (poly_binds, poly_ids) ->
158 TopLevel -- For the top level don't bother will all this
159 -- bindInstsOfLocalFuns stuff. All the top level
160 -- things are rec'd together anyway, so it's fine to
161 -- leave them to the tcSimplifyTop, and quite a bit faster too
163 -- Subtle (and ugly) point: furthermore at top level we
164 -- return the TcLclEnv, which contains the LIE var; we
165 -- don't want to return the wrong one!
166 -> tc_body poly_ids `thenM` \ (prag_binds, thing) ->
167 returnM (combiner (mkMonoBind Recursive (poly_binds `andMonoBinds` prag_binds))
170 NotTopLevel -- For nested bindings we must do teh bindInstsOfLocalFuns thing
171 -> getLIE (tc_body poly_ids) `thenM` \ ((prag_binds, thing), lie) ->
173 -- Create specialisations of functions bound here
174 bindInstsOfLocalFuns lie poly_ids `thenM` \ lie_binds ->
176 -- We want to keep non-recursive things non-recursive
177 -- so that we desugar unlifted bindings correctly
180 combiner (mkMonoBind Recursive (
181 poly_binds `andMonoBinds`
182 lie_binds `andMonoBinds`
187 combiner (mkMonoBind NonRecursive poly_binds) $
188 combiner (mkMonoBind NonRecursive prag_binds) $
189 combiner (mkMonoBind Recursive lie_binds) $
190 -- NB: the binds returned by tcSimplify and bindInstsOfLocalFuns
191 -- aren't guaranteed in dependency order (though we could change
192 -- that); hence the Recursive marker.
195 tc_body poly_ids -- Type check the pragmas and "thing inside"
196 = -- Extend the environment to bind the new polymorphic Ids
197 tcExtendLocalValEnv poly_ids $
199 -- Build bindings and IdInfos corresponding to user pragmas
200 tcSpecSigs sigs `thenM` \ prag_binds ->
202 -- Now do whatever happens next, in the augmented envt
203 do_next `thenM` \ thing ->
205 returnM (prag_binds, thing)
209 %************************************************************************
211 \subsection{tcBindWithSigs}
213 %************************************************************************
215 @tcBindWithSigs@ deals with a single binding group. It does generalisation,
216 so all the clever stuff is in here.
218 * binder_names and mbind must define the same set of Names
220 * The Names in tc_ty_sigs must be a subset of binder_names
222 * The Ids in tc_ty_sigs don't necessarily have to have the same name
223 as the Name in the tc_ty_sig
229 -> [RenamedSig] -- Used solely to get INLINE, NOINLINE sigs
231 -> TcM (TcMonoBinds, [TcId])
233 tcBindWithSigs top_lvl mbind sigs is_rec
234 = -- TYPECHECK THE SIGNATURES
235 recoverM (returnM []) (
236 mappM tcTySig [sig | sig@(Sig name _ _) <- sigs]
237 ) `thenM` \ tc_ty_sigs ->
239 -- SET UP THE MAIN RECOVERY; take advantage of any type sigs
241 -- If typechecking the binds fails, then return with each
242 -- signature-less binder given type (forall a.a), to minimise subsequent
244 newTyVar liftedTypeKind `thenM` \ alpha_tv ->
246 forall_a_a = mkForAllTy alpha_tv (mkTyVarTy alpha_tv)
247 binder_names = collectMonoBinders mbind
248 poly_ids = map mk_dummy binder_names
249 mk_dummy name = case maybeSig tc_ty_sigs name of
250 Just sig -> tcSigPolyId sig -- Signature
251 Nothing -> mkLocalId name forall_a_a -- No signature
253 traceTc (text "tcBindsWithSigs: error recovery" <+> ppr binder_names) `thenM_`
254 returnM (EmptyMonoBinds, poly_ids)
257 -- TYPECHECK THE BINDINGS
258 getLIE (tcMonoBinds mbind tc_ty_sigs is_rec) `thenM` \ ((mbind', bndr_names_w_ids), lie_req) ->
260 (binder_names, mono_ids) = unzip (bagToList bndr_names_w_ids)
261 tau_tvs = foldr (unionVarSet . tyVarsOfType . idType) emptyVarSet mono_ids
265 -- (it seems a bit crude to have to do getLIE twice,
266 -- but I can't see a better way just now)
267 addSrcLoc (minimum (map getSrcLoc binder_names)) $
268 addErrCtxt (genCtxt binder_names) $
269 getLIE (generalise binder_names mbind tau_tvs lie_req tc_ty_sigs)
270 `thenM` \ ((tc_tyvars_to_gen, dict_binds, dict_ids), lie_free) ->
273 -- ZONK THE GENERALISED TYPE VARIABLES TO REAL TyVars
274 -- This commits any unbound kind variables to boxed kind, by unification
275 -- It's important that the final quanfified type variables
276 -- are fully zonked, *including boxity*, because they'll be
277 -- included in the forall types of the polymorphic Ids.
278 -- At calls of these Ids we'll instantiate fresh type variables from
279 -- them, and we use their boxity then.
280 mappM zonkTcTyVarToTyVar tc_tyvars_to_gen `thenM` \ real_tyvars_to_gen ->
283 -- It's important that the dict Ids are zonked, including the boxity set
284 -- in the previous step, because they are later used to form the type of
285 -- the polymorphic thing, and forall-types must be zonked so far as
286 -- their bound variables are concerned
287 mappM zonkId dict_ids `thenM` \ zonked_dict_ids ->
288 mappM zonkId mono_ids `thenM` \ zonked_mono_ids ->
290 -- BUILD THE POLYMORPHIC RESULT IDs
292 exports = zipWith mk_export binder_names zonked_mono_ids
293 poly_ids = [poly_id | (_, poly_id, _) <- exports]
294 dict_tys = map idType zonked_dict_ids
296 inlines = mkNameSet [name | InlineSig True name _ loc <- sigs]
297 -- Any INLINE sig (regardless of phase control)
298 -- makes the RHS look small
299 inline_phases = listToFM [(name, phase) | InlineSig _ name phase _ <- sigs,
300 not (isAlwaysActive phase)]
301 -- Set the IdInfo field to control the inline phase
302 -- AlwaysActive is the default, so don't bother with them
304 mk_export binder_name zonked_mono_id
306 attachInlinePhase inline_phases poly_id,
310 case maybeSig tc_ty_sigs binder_name of
311 Just (TySigInfo sig_poly_id sig_tyvars _ _ _ _ _) ->
312 (sig_tyvars, sig_poly_id)
313 Nothing -> (real_tyvars_to_gen, new_poly_id)
315 new_poly_id = mkLocalId binder_name poly_ty
316 poly_ty = mkForAllTys real_tyvars_to_gen
318 $ idType zonked_mono_id
319 -- It's important to build a fully-zonked poly_ty, because
320 -- we'll slurp out its free type variables when extending the
321 -- local environment (tcExtendLocalValEnv); if it's not zonked
322 -- it appears to have free tyvars that aren't actually free
326 traceTc (text "binding:" <+> ppr ((zonked_dict_ids, dict_binds),
327 exports, map idType poly_ids)) `thenM_`
329 -- Check for an unlifted, non-overloaded group
330 -- In that case we must make extra checks
331 if any (isUnLiftedType . idType) zonked_mono_ids && null zonked_dict_ids
332 then -- Some bindings are unlifted
333 checkUnliftedBinds top_lvl is_rec real_tyvars_to_gen mbind `thenM_`
335 extendLIEs lie_req `thenM_`
337 AbsBinds [] [] exports inlines mbind',
338 -- Do not generate even any x=y bindings
342 else -- The normal case
343 extendLIEs lie_free `thenM_`
345 AbsBinds real_tyvars_to_gen
349 (dict_binds `andMonoBinds` mbind'),
353 attachInlinePhase inline_phases bndr
354 = case lookupFM inline_phases (idName bndr) of
355 Just prag -> bndr `setInlinePragma` prag
358 -- Check that non-overloaded unlifted bindings are
361 -- c) non-polymorphic
362 -- d) not a multiple-binding group (more or less implied by (a))
364 checkUnliftedBinds top_lvl is_rec real_tyvars_to_gen mbind
365 = ASSERT( not (any ((eqKind unliftedTypeKind) . tyVarKind) real_tyvars_to_gen) )
366 -- The instCantBeGeneralised stuff in tcSimplify should have
367 -- already raised an error if we're trying to generalise an
368 -- unboxed tyvar (NB: unboxed tyvars are always introduced
369 -- along with a class constraint) and it's better done there
370 -- because we have more precise origin information.
371 -- That's why we just use an ASSERT here.
373 checkTc (isNotTopLevel top_lvl)
374 (unliftedBindErr "Top-level" mbind) `thenM_`
375 checkTc (isNonRec is_rec)
376 (unliftedBindErr "Recursive" mbind) `thenM_`
377 checkTc (single_bind mbind)
378 (unliftedBindErr "Multiple" mbind) `thenM_`
379 checkTc (null real_tyvars_to_gen)
380 (unliftedBindErr "Polymorphic" mbind)
383 single_bind (PatMonoBind _ _ _) = True
384 single_bind (FunMonoBind _ _ _ _) = True
385 single_bind other = False
389 Polymorphic recursion
390 ~~~~~~~~~~~~~~~~~~~~~
391 The game plan for polymorphic recursion in the code above is
393 * Bind any variable for which we have a type signature
394 to an Id with a polymorphic type. Then when type-checking
395 the RHSs we'll make a full polymorphic call.
397 This fine, but if you aren't a bit careful you end up with a horrendous
398 amount of partial application and (worse) a huge space leak. For example:
400 f :: Eq a => [a] -> [a]
403 If we don't take care, after typechecking we get
405 f = /\a -> \d::Eq a -> let f' = f a d
409 Notice the the stupid construction of (f a d), which is of course
410 identical to the function we're executing. In this case, the
411 polymorphic recursion isn't being used (but that's a very common case).
414 f = /\a -> \d::Eq a -> letrec
415 fm = \ys:[a] -> ...fm...
419 This can lead to a massive space leak, from the following top-level defn
425 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
426 f' is another thunk which evaluates to the same thing... and you end
427 up with a chain of identical values all hung onto by the CAF ff.
431 = let f' = f Int dEqInt in \ys. ...f'...
433 = let f' = let f' = f Int dEqInt in \ys. ...f'...
437 Solution: when typechecking the RHSs we always have in hand the
438 *monomorphic* Ids for each binding. So we just need to make sure that
439 if (Method f a d) shows up in the constraints emerging from (...f...)
440 we just use the monomorphic Id. We achieve this by adding monomorphic Ids
441 to the "givens" when simplifying constraints. That's what the "lies_avail"
445 %************************************************************************
447 \subsection{getTyVarsToGen}
449 %************************************************************************
452 generalise binder_names mbind tau_tvs lie_req sigs =
454 -- check for -fno-monomorphism-restriction
455 doptM Opt_NoMonomorphismRestriction `thenM` \ no_MR ->
456 let is_unrestricted | no_MR = True
457 | otherwise = isUnRestrictedGroup tysig_names mbind
460 if not is_unrestricted then -- RESTRICTED CASE
461 -- Check signature contexts are empty
462 checkTc (all is_mono_sig sigs)
463 (restrictedBindCtxtErr binder_names) `thenM_`
465 -- Now simplify with exactly that set of tyvars
466 -- We have to squash those Methods
467 tcSimplifyRestricted doc tau_tvs lie_req `thenM` \ (qtvs, binds) ->
469 -- Check that signature type variables are OK
470 checkSigsTyVars qtvs sigs `thenM` \ final_qtvs ->
472 returnM (final_qtvs, binds, [])
474 else if null sigs then -- UNRESTRICTED CASE, NO TYPE SIGS
475 tcSimplifyInfer doc tau_tvs lie_req
477 else -- UNRESTRICTED CASE, WITH TYPE SIGS
478 -- CHECKING CASE: Unrestricted group, there are type signatures
479 -- Check signature contexts are identical
480 checkSigsCtxts sigs `thenM` \ (sig_avails, sig_dicts) ->
482 -- Check that the needed dicts can be
483 -- expressed in terms of the signature ones
484 tcSimplifyInferCheck doc tau_tvs sig_avails lie_req `thenM` \ (forall_tvs, dict_binds) ->
486 -- Check that signature type variables are OK
487 checkSigsTyVars forall_tvs sigs `thenM` \ final_qtvs ->
489 returnM (final_qtvs, dict_binds, sig_dicts)
492 tysig_names = map (idName . tcSigPolyId) sigs
493 is_mono_sig (TySigInfo _ _ theta _ _ _ _) = null theta
495 doc = ptext SLIT("type signature(s) for") <+> pprBinders binder_names
497 -----------------------
498 -- CHECK THAT ALL THE SIGNATURE CONTEXTS ARE UNIFIABLE
499 -- The type signatures on a mutually-recursive group of definitions
500 -- must all have the same context (or none).
502 -- We unify them because, with polymorphic recursion, their types
503 -- might not otherwise be related. This is a rather subtle issue.
505 checkSigsCtxts sigs@(TySigInfo id1 sig_tvs theta1 _ _ _ src_loc : other_sigs)
506 = addSrcLoc src_loc $
507 mappM_ check_one other_sigs `thenM_`
509 returnM ([], []) -- Non-overloaded type signatures
511 newDicts SignatureOrigin theta1 `thenM` \ sig_dicts ->
513 -- The "sig_avails" is the stuff available. We get that from
514 -- the context of the type signature, BUT ALSO the lie_avail
515 -- so that polymorphic recursion works right (see comments at end of fn)
516 sig_avails = sig_dicts ++ sig_meths
518 returnM (sig_avails, map instToId sig_dicts)
520 sig1_dict_tys = map mkPredTy theta1
521 sig_meths = concat [insts | TySigInfo _ _ _ _ _ insts _ <- sigs]
523 check_one sig@(TySigInfo id _ theta _ _ _ _)
524 = addErrCtxt (sigContextsCtxt id1 id) $
525 checkTc (equalLength theta theta1) sigContextsErr `thenM_`
526 unifyTauTyLists sig1_dict_tys (map mkPredTy theta)
528 checkSigsTyVars :: [TcTyVar] -> [TcSigInfo] -> TcM [TcTyVar]
529 checkSigsTyVars qtvs sigs
530 = mappM check_one sigs `thenM` \ sig_tvs_s ->
532 -- Sigh. Make sure that all the tyvars in the type sigs
533 -- appear in the returned ty var list, which is what we are
534 -- going to generalise over. Reason: we occasionally get
536 -- type T a = () -> ()
539 -- Here, 'a' won't appear in qtvs, so we have to add it
541 sig_tvs = foldr (unionVarSet . mkVarSet) emptyVarSet sig_tvs_s
542 all_tvs = mkVarSet qtvs `unionVarSet` sig_tvs
544 returnM (varSetElems all_tvs)
546 check_one (TySigInfo id sig_tyvars sig_theta sig_tau _ _ src_loc)
547 = addSrcLoc src_loc $
548 addErrCtxt (ptext SLIT("When checking the type signature for")
549 <+> quotes (ppr id)) $
550 addErrCtxtM (sigCtxt id sig_tyvars sig_theta sig_tau) $
551 checkSigTyVarsWrt (idFreeTyVars id) sig_tyvars
554 @getTyVarsToGen@ decides what type variables to generalise over.
556 For a "restricted group" -- see the monomorphism restriction
557 for a definition -- we bind no dictionaries, and
558 remove from tyvars_to_gen any constrained type variables
560 *Don't* simplify dicts at this point, because we aren't going
561 to generalise over these dicts. By the time we do simplify them
562 we may well know more. For example (this actually came up)
564 f x = array ... xs where xs = [1,2,3,4,5]
565 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
566 stuff. If we simplify only at the f-binding (not the xs-binding)
567 we'll know that the literals are all Ints, and we can just produce
570 Find all the type variables involved in overloading, the
571 "constrained_tyvars". These are the ones we *aren't* going to
572 generalise. We must be careful about doing this:
574 (a) If we fail to generalise a tyvar which is not actually
575 constrained, then it will never, ever get bound, and lands
576 up printed out in interface files! Notorious example:
577 instance Eq a => Eq (Foo a b) where ..
578 Here, b is not constrained, even though it looks as if it is.
579 Another, more common, example is when there's a Method inst in
580 the LIE, whose type might very well involve non-overloaded
582 [NOTE: Jan 2001: I don't understand the problem here so I'm doing
583 the simple thing instead]
585 (b) On the other hand, we mustn't generalise tyvars which are constrained,
586 because we are going to pass on out the unmodified LIE, with those
587 tyvars in it. They won't be in scope if we've generalised them.
589 So we are careful, and do a complete simplification just to find the
590 constrained tyvars. We don't use any of the results, except to
591 find which tyvars are constrained.
594 isUnRestrictedGroup :: [Name] -- Signatures given for these
598 is_elem v vs = isIn "isUnResMono" v vs
600 isUnRestrictedGroup sigs (PatMonoBind other _ _) = False
601 isUnRestrictedGroup sigs (VarMonoBind v _) = v `is_elem` sigs
602 isUnRestrictedGroup sigs (FunMonoBind v _ matches _) = isUnRestrictedMatch matches ||
604 isUnRestrictedGroup sigs (AndMonoBinds mb1 mb2) = isUnRestrictedGroup sigs mb1 &&
605 isUnRestrictedGroup sigs mb2
606 isUnRestrictedGroup sigs EmptyMonoBinds = True
608 isUnRestrictedMatch (Match [] _ _ : _) = False -- No args => like a pattern binding
609 isUnRestrictedMatch other = True -- Some args => a function binding
613 %************************************************************************
615 \subsection{tcMonoBind}
617 %************************************************************************
619 @tcMonoBinds@ deals with a single @MonoBind@.
620 The signatures have been dealt with already.
623 tcMonoBinds :: RenamedMonoBinds
624 -> [TcSigInfo] -> RecFlag
626 Bag (Name, -- Bound names
627 TcId)) -- Corresponding monomorphic bound things
629 tcMonoBinds mbinds tc_ty_sigs is_rec
631 -- 1. Check the patterns, building up an environment binding
632 -- the variables in this group (in the recursive case)
633 -- 2. Extend the environment
635 = tc_mb_pats mbinds `thenM` \ (complete_it, xve) ->
636 tcExtendLocalValEnv2 (bagToList xve) complete_it
638 tc_mb_pats EmptyMonoBinds
639 = returnM (returnM (EmptyMonoBinds, emptyBag), emptyBag)
641 tc_mb_pats (AndMonoBinds mb1 mb2)
642 = tc_mb_pats mb1 `thenM` \ (complete_it1, xve1) ->
643 tc_mb_pats mb2 `thenM` \ (complete_it2, xve2) ->
645 complete_it = complete_it1 `thenM` \ (mb1', bs1) ->
646 complete_it2 `thenM` \ (mb2', bs2) ->
647 returnM (AndMonoBinds mb1' mb2', bs1 `unionBags` bs2)
649 returnM (complete_it, xve1 `unionBags` xve2)
651 tc_mb_pats (FunMonoBind name inf matches locn)
653 -- a) Type sig supplied
654 -- b) No type sig and recursive
655 -- c) No type sig and non-recursive
657 | Just sig <- maybeSig tc_ty_sigs name
658 = let -- (a) There is a type signature
659 -- Use it for the environment extension, and check
660 -- the RHS has the appropriate type (with outer for-alls stripped off)
661 mono_id = tcSigMonoId sig
662 mono_ty = idType mono_id
663 complete_it = addSrcLoc locn $
664 tcMatchesFun name mono_ty matches `thenM` \ matches' ->
665 returnM (FunMonoBind mono_id inf matches' locn,
666 unitBag (name, mono_id))
668 returnM (complete_it, if isRec is_rec then unitBag (name,tcSigPolyId sig)
672 = -- (b) No type signature, and recursive
673 -- So we must use an ordinary H-M type variable
674 -- which means the variable gets an inferred tau-type
675 newLocalName name `thenM` \ mono_name ->
676 newTyVarTy openTypeKind `thenM` \ mono_ty ->
678 mono_id = mkLocalId mono_name mono_ty
679 complete_it = addSrcLoc locn $
680 tcMatchesFun name mono_ty matches `thenM` \ matches' ->
681 returnM (FunMonoBind mono_id inf matches' locn,
682 unitBag (name, mono_id))
684 returnM (complete_it, unitBag (name, mono_id))
686 | otherwise -- (c) No type signature, and non-recursive
687 = let -- So we can use a 'hole' type to infer a higher-rank type
690 newHoleTyVarTy `thenM` \ fun_ty ->
691 tcMatchesFun name fun_ty matches `thenM` \ matches' ->
692 readHoleResult fun_ty `thenM` \ fun_ty' ->
693 newLocalName name `thenM` \ mono_name ->
695 mono_id = mkLocalId mono_name fun_ty'
697 returnM (FunMonoBind mono_id inf matches' locn,
698 unitBag (name, mono_id))
700 returnM (complete_it, emptyBag)
702 tc_mb_pats bind@(PatMonoBind pat grhss locn)
705 -- Now typecheck the pattern
706 -- We do now support binding fresh (not-already-in-scope) scoped
707 -- type variables in the pattern of a pattern binding.
708 -- For example, this is now legal:
710 -- The type variables are brought into scope in tc_binds_and_then,
711 -- so we don't have to do anything here.
713 newHoleTyVarTy `thenM` \ pat_ty ->
714 tcPat tc_pat_bndr pat pat_ty `thenM` \ (pat', tvs, ids, lie_avail) ->
715 readHoleResult pat_ty `thenM` \ pat_ty' ->
717 -- Don't know how to deal with pattern-bound existentials yet
718 checkTc (isEmptyBag tvs && null lie_avail)
719 (existentialExplode bind) `thenM_`
722 complete_it = addSrcLoc locn $
723 addErrCtxt (patMonoBindsCtxt bind) $
724 tcGRHSs PatBindRhs grhss pat_ty' `thenM` \ grhss' ->
725 returnM (PatMonoBind pat' grhss' locn, ids)
727 returnM (complete_it, if isRec is_rec then ids else emptyBag)
729 -- tc_pat_bndr is used when dealing with a LHS binder in a pattern.
730 -- If there was a type sig for that Id, we want to make it much
731 -- as if that type signature had been on the binder as a SigPatIn.
732 -- We check for a type signature; if there is one, we use the mono_id
733 -- from the signature. This is how we make sure the tau part of the
734 -- signature actually matches the type of the LHS; then tc_mb_pats
735 -- ensures the LHS and RHS have the same type
737 tc_pat_bndr name pat_ty
738 = case maybeSig tc_ty_sigs name of
739 Nothing -> newLocalName name `thenM` \ bndr_name ->
740 tcMonoPatBndr bndr_name pat_ty
742 Just sig -> addSrcLoc (getSrcLoc name) $
743 tcSubPat (idType mono_id) pat_ty `thenM` \ co_fn ->
744 returnM (co_fn, mono_id)
746 mono_id = tcSigMonoId sig
750 %************************************************************************
752 \subsection{SPECIALIZE pragmas}
754 %************************************************************************
756 @tcSpecSigs@ munches up the specialisation "signatures" that arise through *user*
757 pragmas. It is convenient for them to appear in the @[RenamedSig]@
758 part of a binding because then the same machinery can be used for
759 moving them into place as is done for type signatures.
764 f :: Ord a => [a] -> b -> b
765 {-# SPECIALIZE f :: [Int] -> b -> b #-}
768 For this we generate:
770 f* = /\ b -> let d1 = ...
774 where f* is a SpecPragmaId. The **sole** purpose of SpecPragmaIds is to
775 retain a right-hand-side that the simplifier will otherwise discard as
776 dead code... the simplifier has a flag that tells it not to discard
777 SpecPragmaId bindings.
779 In this case the f* retains a call-instance of the overloaded
780 function, f, (including appropriate dictionaries) so that the
781 specialiser will subsequently discover that there's a call of @f@ at
782 Int, and will create a specialisation for @f@. After that, the
783 binding for @f*@ can be discarded.
785 We used to have a form
786 {-# SPECIALISE f :: <type> = g #-}
787 which promised that g implemented f at <type>, but we do that with
789 {-# SPECIALISE (f::<type) = g #-}
792 tcSpecSigs :: [RenamedSig] -> TcM TcMonoBinds
793 tcSpecSigs (SpecSig name poly_ty src_loc : sigs)
794 = -- SPECIALISE f :: forall b. theta => tau = g
796 addErrCtxt (valSpecSigCtxt name poly_ty) $
798 -- Get and instantiate its alleged specialised type
799 tcHsSigType (FunSigCtxt name) poly_ty `thenM` \ sig_ty ->
801 -- Check that f has a more general type, and build a RHS for
802 -- the spec-pragma-id at the same time
803 getLIE (tcExpr (HsVar name) sig_ty) `thenM` \ (spec_expr, spec_lie) ->
805 -- Squeeze out any Methods (see comments with tcSimplifyToDicts)
806 tcSimplifyToDicts spec_lie `thenM` \ spec_binds ->
808 -- Just specialise "f" by building a SpecPragmaId binding
809 -- It is the thing that makes sure we don't prematurely
810 -- dead-code-eliminate the binding we are really interested in.
811 newLocalName name `thenM` \ spec_name ->
813 spec_bind = VarMonoBind (mkSpecPragmaId spec_name sig_ty)
814 (mkHsLet spec_binds spec_expr)
817 -- Do the rest and combine
818 tcSpecSigs sigs `thenM` \ binds_rest ->
819 returnM (binds_rest `andMonoBinds` spec_bind)
821 tcSpecSigs (other_sig : sigs) = tcSpecSigs sigs
822 tcSpecSigs [] = returnM EmptyMonoBinds
826 %************************************************************************
828 \subsection[TcBinds-errors]{Error contexts and messages}
830 %************************************************************************
834 patMonoBindsCtxt bind
835 = hang (ptext SLIT("In a pattern binding:")) 4 (ppr bind)
837 -----------------------------------------------
839 = sep [ptext SLIT("In a SPECIALIZE pragma for a value:"),
840 nest 4 (ppr v <+> dcolon <+> ppr ty)]
842 -----------------------------------------------
843 sigContextsErr = ptext SLIT("Mismatched contexts")
845 sigContextsCtxt s1 s2
846 = vcat [ptext SLIT("When matching the contexts of the signatures for"),
847 nest 2 (vcat [ppr s1 <+> dcolon <+> ppr (idType s1),
848 ppr s2 <+> dcolon <+> ppr (idType s2)]),
849 ptext SLIT("The signature contexts in a mutually recursive group should all be identical")]
851 -----------------------------------------------
852 unliftedBindErr flavour mbind
853 = hang (text flavour <+> ptext SLIT("bindings for unlifted types aren't allowed:"))
856 -----------------------------------------------
857 existentialExplode mbinds
858 = hang (vcat [text "My brain just exploded.",
859 text "I can't handle pattern bindings for existentially-quantified constructors.",
860 text "In the binding group"])
863 -----------------------------------------------
864 restrictedBindCtxtErr binder_names
865 = hang (ptext SLIT("Illegal overloaded type signature(s)"))
866 4 (vcat [ptext SLIT("in a binding group for") <+> pprBinders binder_names,
867 ptext SLIT("that falls under the monomorphism restriction")])
870 = ptext SLIT("When generalising the type(s) for") <+> pprBinders binder_names
872 -- Used in error messages
873 -- Use quotes for a single one; they look a bit "busy" for several
874 pprBinders [bndr] = quotes (ppr bndr)
875 pprBinders bndrs = pprWithCommas ppr bndrs