2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcBinds]{TcBinds}
7 module TcBinds ( tcBindsAndThen, tcTopBindsAndThen,
8 tcPragmaSigs, tcBindWithSigs ) where
10 #include "HsVersions.h"
12 import {-# SOURCE #-} TcMatches ( tcGRHSs, tcMatchesFun )
13 import {-# SOURCE #-} TcExpr ( tcExpr )
15 import HsSyn ( HsExpr(..), HsBinds(..), MonoBinds(..), Sig(..), InPat(..), StmtCtxt(..),
16 collectMonoBinders, andMonoBindList, andMonoBinds
18 import RnHsSyn ( RenamedHsBinds, RenamedSig, RenamedMonoBinds )
19 import TcHsSyn ( TcHsBinds, TcMonoBinds, TcId, zonkId )
22 import Inst ( Inst, LIE, emptyLIE, mkLIE, plusLIE, plusLIEs, InstOrigin(..),
23 newDicts, tyVarsOfInst, instToId,
25 import TcEnv ( tcExtendLocalValEnv,
27 tcGetGlobalTyVars, tcExtendGlobalTyVars
29 import TcSimplify ( tcSimplify, tcSimplifyAndCheck )
30 import TcMonoType ( tcHsType, checkSigTyVars,
31 TcSigInfo(..), tcTySig, maybeSig, sigCtxt
33 import TcPat ( tcVarPat, tcPat )
34 import TcSimplify ( bindInstsOfLocalFuns )
35 import TcType ( TcType, TcThetaType,
37 newTyVarTy, newTyVar, newTyVarTy_OpenKind, tcInstTcType,
38 zonkTcType, zonkTcTypes, zonkTcThetaType, zonkTcTyVarToTyVar
40 import TcUnify ( unifyTauTy, unifyTauTyLists )
42 import Id ( mkUserId )
43 import Var ( idType, idName, setIdInfo )
44 import IdInfo ( IdInfo, noIdInfo, setInlinePragInfo, InlinePragInfo(..) )
46 import Type ( mkTyVarTy, tyVarsOfTypes,
47 splitSigmaTy, mkForAllTys, mkFunTys, getTyVar,
48 mkDictTy, splitRhoTy, mkForAllTy, isUnLiftedType,
49 isUnboxedType, unboxedTypeKind, boxedTypeKind
51 import Var ( TyVar, tyVarKind )
55 import BasicTypes ( TopLevelFlag(..), RecFlag(..) )
56 import SrcLoc ( SrcLoc )
61 %************************************************************************
63 \subsection{Type-checking bindings}
65 %************************************************************************
67 @tcBindsAndThen@ typechecks a @HsBinds@. The "and then" part is because
68 it needs to know something about the {\em usage} of the things bound,
69 so that it can create specialisations of them. So @tcBindsAndThen@
70 takes a function which, given an extended environment, E, typechecks
71 the scope of the bindings returning a typechecked thing and (most
72 important) an LIE. It is this LIE which is then used as the basis for
73 specialising the things bound.
75 @tcBindsAndThen@ also takes a "combiner" which glues together the
76 bindings and the "thing" to make a new "thing".
78 The real work is done by @tcBindWithSigsAndThen@.
80 Recursive and non-recursive binds are handled in essentially the same
81 way: because of uniques there are no scoping issues left. The only
82 difference is that non-recursive bindings can bind primitive values.
84 Even for non-recursive binding groups we add typings for each binder
85 to the LVE for the following reason. When each individual binding is
86 checked the type of its LHS is unified with that of its RHS; and
87 type-checking the LHS of course requires that the binder is in scope.
89 At the top-level the LIE is sure to contain nothing but constant
90 dictionaries, which we resolve at the module level.
93 tcTopBindsAndThen, tcBindsAndThen
94 :: (RecFlag -> TcMonoBinds -> thing -> thing) -- Combinator
99 tcTopBindsAndThen = tc_binds_and_then TopLevel
100 tcBindsAndThen = tc_binds_and_then NotTopLevel
102 tc_binds_and_then top_lvl combiner EmptyBinds do_next
104 tc_binds_and_then top_lvl combiner (MonoBind EmptyMonoBinds sigs is_rec) do_next
107 tc_binds_and_then top_lvl combiner (ThenBinds b1 b2) do_next
108 = tc_binds_and_then top_lvl combiner b1 $
109 tc_binds_and_then top_lvl combiner b2 $
112 tc_binds_and_then top_lvl combiner (MonoBind bind sigs is_rec) do_next
113 = fixTc (\ ~(prag_info_fn, _, _) ->
114 -- This is the usual prag_info fix; the PragmaInfo field of an Id
115 -- is not inspected till ages later in the compiler, so there
116 -- should be no black-hole problems here.
118 -- TYPECHECK THE SIGNATURES
119 mapTc tcTySig [sig | sig@(Sig name _ _) <- sigs] `thenTc` \ tc_ty_sigs ->
121 tcBindWithSigs top_lvl bind
122 tc_ty_sigs is_rec prag_info_fn `thenTc` \ (poly_binds, poly_lie, poly_ids) ->
124 -- Extend the environment to bind the new polymorphic Ids
125 tcExtendLocalValEnv [(idName poly_id, poly_id) | poly_id <- poly_ids] $
127 -- Build bindings and IdInfos corresponding to user pragmas
128 tcPragmaSigs sigs `thenTc` \ (prag_info_fn, prag_binds, prag_lie) ->
130 -- Now do whatever happens next, in the augmented envt
131 do_next `thenTc` \ (thing, thing_lie) ->
133 -- Create specialisations of functions bound here
134 -- We want to keep non-recursive things non-recursive
135 -- so that we desugar unboxed bindings correctly
136 case (top_lvl, is_rec) of
138 -- For the top level don't bother will all this bindInstsOfLocalFuns stuff
139 -- All the top level things are rec'd together anyway, so it's fine to
140 -- leave them to the tcSimplifyTop, and quite a bit faster too
142 -> returnTc (prag_info_fn,
143 combiner Recursive (poly_binds `andMonoBinds` prag_binds) thing,
144 thing_lie `plusLIE` prag_lie `plusLIE` poly_lie)
146 (NotTopLevel, NonRecursive)
147 -> bindInstsOfLocalFuns
148 (thing_lie `plusLIE` prag_lie)
149 poly_ids `thenTc` \ (thing_lie', lie_binds) ->
153 combiner NonRecursive poly_binds $
154 combiner NonRecursive prag_binds $
155 combiner Recursive lie_binds $
156 -- NB: the binds returned by tcSimplify and bindInstsOfLocalFuns
157 -- aren't guaranteed in dependency order (though we could change
158 -- that); hence the Recursive marker.
161 thing_lie' `plusLIE` poly_lie
164 (NotTopLevel, Recursive)
165 -> bindInstsOfLocalFuns
166 (thing_lie `plusLIE` poly_lie `plusLIE` prag_lie)
167 poly_ids `thenTc` \ (final_lie, lie_binds) ->
172 poly_binds `andMonoBinds`
173 lie_binds `andMonoBinds`
177 ) `thenTc` \ (_, thing, lie) ->
178 returnTc (thing, lie)
181 An aside. The original version of @tcBindsAndThen@ which lacks a
182 combiner function, appears below. Though it is perfectly well
183 behaved, it cannot be typed by Haskell, because the recursive call is
184 at a different type to the definition itself. There aren't too many
185 examples of this, which is why I thought it worth preserving! [SLPJ]
190 % -> TcM s (thing, LIE, thing_ty))
191 % -> TcM s ((TcHsBinds, thing), LIE, thing_ty)
193 % tcBindsAndThen EmptyBinds do_next
194 % = do_next `thenTc` \ (thing, lie, thing_ty) ->
195 % returnTc ((EmptyBinds, thing), lie, thing_ty)
197 % tcBindsAndThen (ThenBinds binds1 binds2) do_next
198 % = tcBindsAndThen binds1 (tcBindsAndThen binds2 do_next)
199 % `thenTc` \ ((binds1', (binds2', thing')), lie1, thing_ty) ->
201 % returnTc ((binds1' `ThenBinds` binds2', thing'), lie1, thing_ty)
203 % tcBindsAndThen (MonoBind bind sigs is_rec) do_next
204 % = tcBindAndThen bind sigs do_next
208 %************************************************************************
210 \subsection{tcBindWithSigs}
212 %************************************************************************
214 @tcBindWithSigs@ deals with a single binding group. It does generalisation,
215 so all the clever stuff is in here.
217 * binder_names and mbind must define the same set of Names
219 * The Names in tc_ty_sigs must be a subset of binder_names
221 * The Ids in tc_ty_sigs don't necessarily have to have the same name
222 as the Name in the tc_ty_sig
231 -> TcM s (TcMonoBinds, LIE, [TcId])
233 tcBindWithSigs top_lvl mbind tc_ty_sigs is_rec prag_info_fn
235 -- If typechecking the binds fails, then return with each
236 -- signature-less binder given type (forall a.a), to minimise subsequent
238 newTyVar boxedTypeKind `thenNF_Tc` \ alpha_tv ->
240 forall_a_a = mkForAllTy alpha_tv (mkTyVarTy alpha_tv)
241 binder_names = map fst (bagToList (collectMonoBinders mbind))
242 poly_ids = map mk_dummy binder_names
243 mk_dummy name = case maybeSig tc_ty_sigs name of
244 Just (TySigInfo _ poly_id _ _ _ _ _ _) -> poly_id -- Signature
245 Nothing -> mkUserId name forall_a_a -- No signature
247 returnTc (EmptyMonoBinds, emptyLIE, poly_ids)
250 -- TYPECHECK THE BINDINGS
251 tcMonoBinds mbind tc_ty_sigs is_rec `thenTc` \ (mbind', lie_req, binder_names, mono_ids) ->
254 mono_id_tys = map idType mono_ids
257 -- CHECK THAT THE SIGNATURES MATCH
258 -- (must do this before getTyVarsToGen)
259 checkSigMatch tc_ty_sigs `thenTc` \ (sig_theta, lie_avail) ->
261 -- COMPUTE VARIABLES OVER WHICH TO QUANTIFY, namely tyvars_to_gen
262 -- The tyvars_not_to_gen are free in the environment, and hence
263 -- candidates for generalisation, but sometimes the monomorphism
264 -- restriction means we can't generalise them nevertheless
265 getTyVarsToGen is_unrestricted mono_id_tys lie_req `thenNF_Tc` \ (tyvars_not_to_gen, tyvars_to_gen) ->
267 -- Finally, zonk the generalised type variables to real TyVars
268 -- This commits any unbound kind variables to boxed kind
269 -- I'm a little worried that such a kind variable might be
270 -- free in the environment, but I don't think it's possible for
271 -- this to happen when the type variable is not free in the envt
272 -- (which it isn't). SLPJ Nov 98
273 mapTc zonkTcTyVarToTyVar (varSetElems tyvars_to_gen) `thenTc` \ real_tyvars_to_gen_list ->
275 real_tyvars_to_gen = mkVarSet real_tyvars_to_gen_list
276 -- It's important that the final list
277 -- (real_tyvars_to_gen and real_tyvars_to_gen_list) is fully
278 -- zonked, *including boxity*, because they'll be included in the forall types of
279 -- the polymorphic Ids, and instances of these Ids will be generated from them.
281 -- Also NB that tcSimplify takes zonked tyvars as its arg, hence we pass
282 -- real_tyvars_to_gen
286 tcExtendGlobalTyVars tyvars_not_to_gen (
287 if null real_tyvars_to_gen_list then
288 -- No polymorphism, so no need to simplify context
289 returnTc (lie_req, EmptyMonoBinds, [])
291 if null tc_ty_sigs then
292 -- No signatures, so just simplify the lie
293 -- NB: no signatures => no polymorphic recursion, so no
294 -- need to use lie_avail (which will be empty anyway)
295 tcSimplify (text "tcBinds1" <+> ppr binder_names)
296 top_lvl real_tyvars_to_gen lie_req `thenTc` \ (lie_free, dict_binds, lie_bound) ->
297 returnTc (lie_free, dict_binds, map instToId (bagToList lie_bound))
300 zonkTcThetaType sig_theta `thenNF_Tc` \ sig_theta' ->
301 newDicts SignatureOrigin sig_theta' `thenNF_Tc` \ (dicts_sig, dict_ids) ->
302 -- It's important that sig_theta is zonked, because
303 -- dict_id is later used to form the type of the polymorphic thing,
304 -- and forall-types must be zonked so far as their bound variables
308 -- The "givens" is the stuff available. We get that from
309 -- the context of the type signature, BUT ALSO the lie_avail
310 -- so that polymorphic recursion works right (see comments at end of fn)
311 givens = dicts_sig `plusLIE` lie_avail
314 -- Check that the needed dicts can be expressed in
315 -- terms of the signature ones
316 tcAddErrCtxt (bindSigsCtxt tysig_names) $
318 (ptext SLIT("type signature for") <+> pprQuotedList binder_names)
319 real_tyvars_to_gen givens lie_req `thenTc` \ (lie_free, dict_binds) ->
321 returnTc (lie_free, dict_binds, dict_ids)
323 ) `thenTc` \ (lie_free, dict_binds, dicts_bound) ->
325 -- GET THE FINAL MONO_ID_TYS
326 zonkTcTypes mono_id_tys `thenNF_Tc` \ zonked_mono_id_types ->
329 -- CHECK FOR BOGUS UNPOINTED BINDINGS
330 (if any isUnLiftedType zonked_mono_id_types then
331 -- Unlifted bindings must be non-recursive,
332 -- not top level, and non-polymorphic
333 checkTc (case top_lvl of {TopLevel -> False; NotTopLevel -> True})
334 (unliftedBindErr "Top-level" mbind) `thenTc_`
335 checkTc (case is_rec of {Recursive -> False; NonRecursive -> True})
336 (unliftedBindErr "Recursive" mbind) `thenTc_`
337 checkTc (null real_tyvars_to_gen_list)
338 (unliftedBindErr "Polymorphic" mbind)
343 ASSERT( not (any ((== unboxedTypeKind) . tyVarKind) real_tyvars_to_gen_list) )
344 -- The instCantBeGeneralised stuff in tcSimplify should have
345 -- already raised an error if we're trying to generalise an
346 -- unboxed tyvar (NB: unboxed tyvars are always introduced
347 -- along with a class constraint) and it's better done there
348 -- because we have more precise origin information.
349 -- That's why we just use an ASSERT here.
352 -- BUILD THE POLYMORPHIC RESULT IDs
353 mapNF_Tc zonkId mono_ids `thenNF_Tc` \ zonked_mono_ids ->
355 exports = zipWith mk_export binder_names zonked_mono_ids
356 dict_tys = map idType dicts_bound
358 mk_export binder_name zonked_mono_id
360 setIdInfo poly_id (prag_info_fn binder_name),
364 case maybeSig tc_ty_sigs binder_name of
365 Just (TySigInfo _ sig_poly_id sig_tyvars _ _ _ _ _) ->
366 (sig_tyvars, sig_poly_id)
367 Nothing -> (real_tyvars_to_gen_list, new_poly_id)
369 new_poly_id = mkUserId binder_name poly_ty
370 poly_ty = mkForAllTys real_tyvars_to_gen_list
372 $ idType (zonked_mono_id)
373 -- It's important to build a fully-zonked poly_ty, because
374 -- we'll slurp out its free type variables when extending the
375 -- local environment (tcExtendLocalValEnv); if it's not zonked
376 -- it appears to have free tyvars that aren't actually free
379 pat_binders :: [Name]
380 pat_binders = map fst $ bagToList $ collectMonoBinders $
381 (justPatBindings mbind EmptyMonoBinds)
383 -- CHECK FOR UNBOXED BINDERS IN PATTERN BINDINGS
384 mapTc (\id -> checkTc (not (idName id `elem` pat_binders
385 && isUnboxedType (idType id)))
386 (unboxedPatBindErr id)) zonked_mono_ids
391 AbsBinds real_tyvars_to_gen_list
394 (dict_binds `andMonoBinds` mbind'),
396 [poly_id | (_, poly_id, _) <- exports]
399 tysig_names = [name | (TySigInfo name _ _ _ _ _ _ _) <- tc_ty_sigs]
400 is_unrestricted = isUnRestrictedGroup tysig_names mbind
402 justPatBindings bind@(PatMonoBind _ _ _) binds = bind `andMonoBinds` binds
403 justPatBindings (AndMonoBinds b1 b2) binds =
404 justPatBindings b1 (justPatBindings b2 binds)
405 justPatBindings other_bind binds = binds
408 Polymorphic recursion
409 ~~~~~~~~~~~~~~~~~~~~~
410 The game plan for polymorphic recursion in the code above is
412 * Bind any variable for which we have a type signature
413 to an Id with a polymorphic type. Then when type-checking
414 the RHSs we'll make a full polymorphic call.
416 This fine, but if you aren't a bit careful you end up with a horrendous
417 amount of partial application and (worse) a huge space leak. For example:
419 f :: Eq a => [a] -> [a]
422 If we don't take care, after typechecking we get
424 f = /\a -> \d::Eq a -> let f' = f a d
428 Notice the the stupid construction of (f a d), which is of course
429 identical to the function we're executing. In this case, the
430 polymorphic recursion isn't being used (but that's a very common case).
433 f = /\a -> \d::Eq a -> letrec
434 fm = \ys:[a] -> ...fm...
438 This can lead to a massive space leak, from the following top-level defn
444 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
445 f' is another thunk which evaluates to the same thing... and you end
446 up with a chain of identical values all hung onto by the CAF ff.
450 = let f' = f Int dEqInt in \ys. ...f'...
452 = let f' = let f' = f Int dEqInt in \ys. ...f'...
456 Solution: when typechecking the RHSs we always have in hand the
457 *monomorphic* Ids for each binding. So we just need to make sure that
458 if (Method f a d) shows up in the constraints emerging from (...f...)
459 we just use the monomorphic Id. We achieve this by adding monomorphic Ids
460 to the "givens" when simplifying constraints. That's what the "lies_avail"
464 %************************************************************************
466 \subsection{getTyVarsToGen}
468 %************************************************************************
470 @getTyVarsToGen@ decides what type variables generalise over.
472 For a "restricted group" -- see the monomorphism restriction
473 for a definition -- we bind no dictionaries, and
474 remove from tyvars_to_gen any constrained type variables
476 *Don't* simplify dicts at this point, because we aren't going
477 to generalise over these dicts. By the time we do simplify them
478 we may well know more. For example (this actually came up)
480 f x = array ... xs where xs = [1,2,3,4,5]
481 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
482 stuff. If we simplify only at the f-binding (not the xs-binding)
483 we'll know that the literals are all Ints, and we can just produce
486 Find all the type variables involved in overloading, the
487 "constrained_tyvars". These are the ones we *aren't* going to
488 generalise. We must be careful about doing this:
490 (a) If we fail to generalise a tyvar which is not actually
491 constrained, then it will never, ever get bound, and lands
492 up printed out in interface files! Notorious example:
493 instance Eq a => Eq (Foo a b) where ..
494 Here, b is not constrained, even though it looks as if it is.
495 Another, more common, example is when there's a Method inst in
496 the LIE, whose type might very well involve non-overloaded
499 (b) On the other hand, we mustn't generalise tyvars which are constrained,
500 because we are going to pass on out the unmodified LIE, with those
501 tyvars in it. They won't be in scope if we've generalised them.
503 So we are careful, and do a complete simplification just to find the
504 constrained tyvars. We don't use any of the results, except to
505 find which tyvars are constrained.
508 getTyVarsToGen is_unrestricted mono_id_tys lie
509 = tcGetGlobalTyVars `thenNF_Tc` \ free_tyvars ->
510 zonkTcTypes mono_id_tys `thenNF_Tc` \ zonked_mono_id_tys ->
512 tyvars_to_gen = tyVarsOfTypes zonked_mono_id_tys `minusVarSet` free_tyvars
516 returnNF_Tc (emptyVarSet, tyvars_to_gen)
518 -- This recover and discard-errs is to avoid duplicate error
519 -- messages; this, after all, is an "extra" call to tcSimplify
520 recoverNF_Tc (returnNF_Tc (emptyVarSet, tyvars_to_gen)) $
523 tcSimplify (text "getTVG") NotTopLevel tyvars_to_gen lie `thenTc` \ (_, _, constrained_dicts) ->
525 -- ASSERT: dicts_sig is already zonked!
526 constrained_tyvars = foldrBag (unionVarSet . tyVarsOfInst) emptyVarSet constrained_dicts
527 reduced_tyvars_to_gen = tyvars_to_gen `minusVarSet` constrained_tyvars
529 returnTc (constrained_tyvars, reduced_tyvars_to_gen)
534 isUnRestrictedGroup :: [Name] -- Signatures given for these
538 is_elem v vs = isIn "isUnResMono" v vs
540 isUnRestrictedGroup sigs (PatMonoBind (VarPatIn v) _ _) = v `is_elem` sigs
541 isUnRestrictedGroup sigs (PatMonoBind other _ _) = False
542 isUnRestrictedGroup sigs (VarMonoBind v _) = v `is_elem` sigs
543 isUnRestrictedGroup sigs (FunMonoBind _ _ _ _) = True
544 isUnRestrictedGroup sigs (AndMonoBinds mb1 mb2) = isUnRestrictedGroup sigs mb1 &&
545 isUnRestrictedGroup sigs mb2
546 isUnRestrictedGroup sigs EmptyMonoBinds = True
550 %************************************************************************
552 \subsection{tcMonoBind}
554 %************************************************************************
556 @tcMonoBinds@ deals with a single @MonoBind@.
557 The signatures have been dealt with already.
560 tcMonoBinds :: RenamedMonoBinds
563 -> TcM s (TcMonoBinds,
565 [Name], -- Bound names
566 [TcId]) -- Corresponding monomorphic bound things
568 tcMonoBinds mbinds tc_ty_sigs is_rec
569 = tc_mb_pats mbinds `thenTc` \ (complete_it, lie_req_pat, tvs, ids, lie_avail) ->
571 tv_list = bagToList tvs
572 id_list = bagToList ids
573 (names, mono_ids) = unzip id_list
575 -- This last defn is the key one:
576 -- extend the val envt with bindings for the
577 -- things bound in this group, overriding the monomorphic
578 -- ids with the polymorphic ones from the pattern
579 extra_val_env = case is_rec of
580 Recursive -> map mk_bind id_list
583 -- Don't know how to deal with pattern-bound existentials yet
584 checkTc (isEmptyBag tvs && isEmptyBag lie_avail)
585 (existentialExplode mbinds) `thenTc_`
587 -- *Before* checking the RHSs, but *after* checking *all* the patterns,
588 -- extend the envt with bindings for all the bound ids;
589 -- and *then* override with the polymorphic Ids from the signatures
590 -- That is the whole point of the "complete_it" stuff.
592 -- There's a further wrinkle: we have to delay extending the environment
593 -- until after we've dealt with any pattern-bound signature type variables
594 -- Consider f (x::a) = ...f...
595 -- We're going to check that a isn't unified with anything in the envt,
596 -- so f itself had better not be! So we pass the envt binding f into
597 -- complete_it, which extends the actual envt in TcMatches.tcMatch, after
598 -- dealing with the signature tyvars
600 complete_it extra_val_env `thenTc` \ (mbinds', lie_req_rhss) ->
602 returnTc (mbinds', lie_req_pat `plusLIE` lie_req_rhss, names, mono_ids)
604 sig_fn name = case maybeSig tc_ty_sigs name of
606 Just (TySigInfo _ _ _ _ _ mono_id _ _) -> Just mono_id
608 mk_bind (name, mono_id) = case maybeSig tc_ty_sigs name of
609 Nothing -> (name, mono_id)
610 Just (TySigInfo name poly_id _ _ _ _ _ _) -> (name, poly_id)
612 tc_mb_pats EmptyMonoBinds
613 = returnTc (\ xve -> returnTc (EmptyMonoBinds, emptyLIE), emptyLIE, emptyBag, emptyBag, emptyLIE)
615 tc_mb_pats (AndMonoBinds mb1 mb2)
616 = tc_mb_pats mb1 `thenTc` \ (complete_it1, lie_req1, tvs1, ids1, lie_avail1) ->
617 tc_mb_pats mb2 `thenTc` \ (complete_it2, lie_req2, tvs2, ids2, lie_avail2) ->
619 complete_it xve = complete_it1 xve `thenTc` \ (mb1', lie1) ->
620 complete_it2 xve `thenTc` \ (mb2', lie2) ->
621 returnTc (AndMonoBinds mb1' mb2', lie1 `plusLIE` lie2)
623 returnTc (complete_it,
624 lie_req1 `plusLIE` lie_req2,
625 tvs1 `unionBags` tvs2,
626 ids1 `unionBags` ids2,
627 lie_avail1 `plusLIE` lie_avail2)
629 tc_mb_pats (FunMonoBind name inf matches locn)
630 = newTyVarTy boxedTypeKind `thenNF_Tc` \ bndr_ty ->
631 tcVarPat sig_fn name bndr_ty `thenTc` \ bndr_id ->
633 complete_it xve = tcAddSrcLoc locn $
634 tcMatchesFun xve name bndr_ty matches `thenTc` \ (matches', lie) ->
635 returnTc (FunMonoBind bndr_id inf matches' locn, lie)
637 returnTc (complete_it, emptyLIE, emptyBag, unitBag (name, bndr_id), emptyLIE)
639 tc_mb_pats bind@(PatMonoBind pat grhss locn)
642 -- Figure out the appropriate kind for the pattern,
643 -- and generate a suitable type variable
645 Recursive -> newTyVarTy boxedTypeKind -- Recursive, so no unboxed types
646 NonRecursive -> newTyVarTy_OpenKind -- Non-recursive, so we permit unboxed types
647 ) `thenNF_Tc` \ pat_ty ->
649 -- Now typecheck the pattern
650 -- We don't support binding fresh type variables in the
651 -- pattern of a pattern binding. For example, this is illegal:
653 -- whereas this is ok
654 -- (x::Int, y::Bool) = e
656 -- We don't check explicitly for this problem. Instead, we simply
657 -- type check the pattern with tcPat. If the pattern mentions any
658 -- fresh tyvars we simply get an out-of-scope type variable error
659 tcPat sig_fn pat pat_ty `thenTc` \ (pat', lie_req, tvs, ids, lie_avail) ->
661 complete_it xve = tcAddSrcLoc locn $
662 tcAddErrCtxt (patMonoBindsCtxt bind) $
663 tcExtendLocalValEnv xve $
664 tcGRHSs grhss pat_ty PatBindRhs `thenTc` \ (grhss', lie) ->
665 returnTc (PatMonoBind pat' grhss' locn, lie)
667 returnTc (complete_it, lie_req, tvs, ids, lie_avail)
670 %************************************************************************
672 \subsection{Signatures}
674 %************************************************************************
676 @checkSigMatch@ does the next step in checking signature matching.
677 The tau-type part has already been unified. What we do here is to
678 check that this unification has not over-constrained the (polymorphic)
679 type variables of the original signature type.
681 The error message here is somewhat unsatisfactory, but it'll do for
686 = returnTc (error "checkSigMatch", emptyLIE)
688 checkSigMatch tc_ty_sigs@( sig1@(TySigInfo _ id1 _ theta1 _ _ _ _) : all_sigs_but_first )
689 = -- CHECK THAT THE SIGNATURE TYVARS AND TAU_TYPES ARE OK
690 -- Doesn't affect substitution
691 mapTc check_one_sig tc_ty_sigs `thenTc_`
693 -- CHECK THAT ALL THE SIGNATURE CONTEXTS ARE UNIFIABLE
694 -- The type signatures on a mutually-recursive group of definitions
695 -- must all have the same context (or none).
697 -- We unify them because, with polymorphic recursion, their types
698 -- might not otherwise be related. This is a rather subtle issue.
700 mapTc check_one_cxt all_sigs_but_first `thenTc_`
702 returnTc (theta1, sig_lie)
704 sig1_dict_tys = mk_dict_tys theta1
705 n_sig1_dict_tys = length sig1_dict_tys
706 sig_lie = mkLIE [inst | TySigInfo _ _ _ _ _ _ inst _ <- tc_ty_sigs]
708 check_one_cxt sig@(TySigInfo _ id _ theta _ _ _ src_loc)
709 = tcAddSrcLoc src_loc $
710 tcAddErrCtxt (sigContextsCtxt id1 id) $
711 checkTc (length this_sig_dict_tys == n_sig1_dict_tys)
712 sigContextsErr `thenTc_`
713 unifyTauTyLists sig1_dict_tys this_sig_dict_tys
715 this_sig_dict_tys = mk_dict_tys theta
717 check_one_sig (TySigInfo _ id sig_tyvars _ sig_tau _ _ src_loc)
718 = tcAddSrcLoc src_loc $
719 tcAddErrCtxtM (sigCtxt (sig_msg id) (idType id)) $
720 checkSigTyVars sig_tyvars
722 mk_dict_tys theta = [mkDictTy c ts | (c,ts) <- theta]
724 sig_msg id tidy_ty = sep [ptext SLIT("When checking the type signature"),
725 nest 4 (ppr id <+> dcolon <+> ppr tidy_ty)]
729 %************************************************************************
731 \subsection{SPECIALIZE pragmas}
733 %************************************************************************
736 @tcPragmaSigs@ munches up the "signatures" that arise through *user*
737 pragmas. It is convenient for them to appear in the @[RenamedSig]@
738 part of a binding because then the same machinery can be used for
739 moving them into place as is done for type signatures.
742 tcPragmaSigs :: [RenamedSig] -- The pragma signatures
743 -> TcM s (Name -> IdInfo, -- Maps name to the appropriate IdInfo
748 = mapAndUnzip3Tc tcPragmaSig sigs `thenTc` \ (maybe_info_modifiers, binds, lies) ->
750 prag_fn name = foldr ($) noIdInfo [f | Just (n,f) <- maybe_info_modifiers, n==name]
752 returnTc (prag_fn, andMonoBindList binds, plusLIEs lies)
755 The interesting case is for SPECIALISE pragmas. There are two forms.
756 Here's the first form:
758 f :: Ord a => [a] -> b -> b
759 {-# SPECIALIZE f :: [Int] -> b -> b #-}
762 For this we generate:
764 f* = /\ b -> let d1 = ...
768 where f* is a SpecPragmaId. The **sole** purpose of SpecPragmaIds is to
769 retain a right-hand-side that the simplifier will otherwise discard as
770 dead code... the simplifier has a flag that tells it not to discard
771 SpecPragmaId bindings.
773 In this case the f* retains a call-instance of the overloaded
774 function, f, (including appropriate dictionaries) so that the
775 specialiser will subsequently discover that there's a call of @f@ at
776 Int, and will create a specialisation for @f@. After that, the
777 binding for @f*@ can be discarded.
779 The second form is this:
781 f :: Ord a => [a] -> b -> b
782 {-# SPECIALIZE f :: [Int] -> b -> b = g #-}
785 Here @g@ is specified as a function that implements the specialised
786 version of @f@. Suppose that g has type (a->b->b); that is, g's type
787 is more general than that required. For this we generate
789 f@Int = /\b -> g Int b
793 Here @f@@Int@ is a SpecId, the specialised version of @f@. It inherits
794 f's export status etc. @f*@ is a SpecPragmaId, as before, which just serves
795 to prevent @f@@Int@ from being discarded prematurely. After specialisation,
796 if @f@@Int@ is going to be used at all it will be used explicitly, so the simplifier can
797 discard the f* binding.
799 Actually, there is really only point in giving a SPECIALISE pragma on exported things,
800 and the simplifer won't discard SpecIds for exporte things anyway, so maybe this is
804 tcPragmaSig :: RenamedSig -> TcM s (Maybe (Name, IdInfo -> IdInfo), TcMonoBinds, LIE)
805 tcPragmaSig (Sig _ _ _) = returnTc (Nothing, EmptyMonoBinds, emptyLIE)
806 tcPragmaSig (SpecInstSig _ _) = returnTc (Nothing, EmptyMonoBinds, emptyLIE)
808 tcPragmaSig (InlineSig name loc)
809 = returnTc (Just (name, setInlinePragInfo IWantToBeINLINEd), EmptyMonoBinds, emptyLIE)
811 tcPragmaSig (NoInlineSig name loc)
812 = returnTc (Just (name, setInlinePragInfo IMustNotBeINLINEd), EmptyMonoBinds, emptyLIE)
814 tcPragmaSig (SpecSig name poly_ty maybe_spec_name src_loc)
815 = -- SPECIALISE f :: forall b. theta => tau = g
816 tcAddSrcLoc src_loc $
817 tcAddErrCtxt (valSpecSigCtxt name poly_ty) $
819 -- Get and instantiate its alleged specialised type
820 tcHsType poly_ty `thenTc` \ sig_ty ->
822 -- Check that f has a more general type, and build a RHS for
823 -- the spec-pragma-id at the same time
824 tcExpr (HsVar name) sig_ty `thenTc` \ (spec_expr, spec_lie) ->
826 case maybe_spec_name of
827 Nothing -> -- Just specialise "f" by building a SpecPragmaId binding
828 -- It is the thing that makes sure we don't prematurely
829 -- dead-code-eliminate the binding we are really interested in.
830 newSpecPragmaId name sig_ty `thenNF_Tc` \ spec_id ->
831 returnTc (Nothing, VarMonoBind spec_id spec_expr, spec_lie)
833 Just g_name -> -- Don't create a SpecPragmaId. Instead add some suitable IdIfo
835 panic "Can't handle SPECIALISE with a '= g' part"
837 {- Not yet. Because we're still in the TcType world we
838 can't really add to the SpecEnv of the Id. Instead we have to
839 record the information in a different sort of Sig, and add it to
840 the IdInfo after zonking.
842 For now we just leave out this case
844 -- Get the type of f, and find out what types
845 -- f has to be instantiated at to give the signature type
846 tcLookupValue name `thenNF_Tc` \ f_id ->
847 tcInstTcType (idType f_id) `thenNF_Tc` \ (f_tyvars, f_rho) ->
850 (sig_tyvars, sig_theta, sig_tau) = splitSigmaTy sig_ty
851 (f_theta, f_tau) = splitRhoTy f_rho
852 sig_tyvar_set = mkVarSet sig_tyvars
854 unifyTauTy sig_tau f_tau `thenTc_`
856 tcPolyExpr str (HsVar g_name) (mkSigmaTy sig_tyvars f_theta sig_tau) `thenTc` \ (_, _,
859 tcPragmaSig other = pprTrace "tcPragmaSig: ignoring" (ppr other) $
860 returnTc (Nothing, EmptyMonoBinds, emptyLIE)
864 %************************************************************************
866 \subsection[TcBinds-errors]{Error contexts and messages}
868 %************************************************************************
872 patMonoBindsCtxt bind
873 = hang (ptext SLIT("In a pattern binding:")) 4 (ppr bind)
875 -----------------------------------------------
877 = sep [ptext SLIT("In a SPECIALIZE pragma for a value:"),
878 nest 4 (ppr v <+> dcolon <+> ppr ty)]
880 -----------------------------------------------
881 notAsPolyAsSigErr sig_tau mono_tyvars
882 = hang (ptext SLIT("A type signature is more polymorphic than the inferred type"))
883 4 (vcat [text "Can't for-all the type variable(s)" <+>
884 pprQuotedList mono_tyvars,
885 text "in the type" <+> quotes (ppr sig_tau)
888 -----------------------------------------------
889 badMatchErr sig_ty inferred_ty
890 = hang (ptext SLIT("Type signature doesn't match inferred type"))
891 4 (vcat [hang (ptext SLIT("Signature:")) 4 (ppr sig_ty),
892 hang (ptext SLIT("Inferred :")) 4 (ppr inferred_ty)
895 -----------------------------------------------
897 = ptext SLIT("variable in a lazy pattern binding has unboxed type: ")
900 -----------------------------------------------
902 = ptext SLIT("When checking the type signature(s) for") <+> pprQuotedList ids
904 -----------------------------------------------
906 = ptext SLIT("Mismatched contexts")
907 sigContextsCtxt s1 s2
908 = hang (hsep [ptext SLIT("When matching the contexts of the signatures for"),
909 quotes (ppr s1), ptext SLIT("and"), quotes (ppr s2)])
910 4 (ptext SLIT("(the signature contexts in a mutually recursive group should all be identical)"))
912 -----------------------------------------------
913 unliftedBindErr flavour mbind
914 = hang (text flavour <+> ptext SLIT("bindings for unlifted types aren't allowed"))
917 existentialExplode mbinds
918 = hang (vcat [text "My brain just exploded.",
919 text "I can't handle pattern bindings for existentially-quantified constructors.",
920 text "In the binding group"])