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_MonomorphismRestriction) )
15 import HsSyn ( HsExpr(..), HsBind(..), LHsBinds, Sig(..),
16 LSig, Match(..), HsBindGroup(..), IPBind(..),
17 HsType(..), hsLTyVarNames,
18 LPat, GRHSs, MatchGroup(..), emptyLHsBinds, isEmptyLHsBinds,
19 collectHsBindBinders, collectPatBinders, pprPatBind
21 import TcHsSyn ( TcId, TcDictBinds, zonkId, mkHsLet )
24 import Inst ( InstOrigin(..), newDictsAtLoc, newIPDict, instToId )
25 import TcEnv ( tcExtendIdEnv, tcExtendIdEnv2, tcExtendTyVarEnv2, newLocalName, tcLookupLocalIds )
26 import TcUnify ( Expected(..), tcInfer, checkSigTyVars, sigCtxt )
27 import TcSimplify ( tcSimplifyInfer, tcSimplifyInferCheck, tcSimplifyRestricted,
28 tcSimplifyToDicts, tcSimplifyIPs )
29 import TcHsType ( tcHsSigType, UserTypeCtxt(..), tcAddLetBoundTyVars,
30 TcSigInfo(..), TcSigFun, lookupSig
32 import TcPat ( tcPat, PatCtxt(..) )
33 import TcSimplify ( bindInstsOfLocalFuns )
34 import TcMType ( newTyFlexiVarTy, tcSkolType, zonkQuantifiedTyVar, zonkTcTypes )
35 import TcType ( TcTyVar, SkolemInfo(SigSkol),
36 TcTauType, TcSigmaType,
37 TvSubstEnv, mkTvSubst, substTheta, substTy,
38 mkTyVarTy, mkForAllTys, mkFunTys, tyVarsOfType,
39 mkForAllTy, isUnLiftedType, tcGetTyVar_maybe,
41 import Unify ( tcMatchPreds )
42 import Kind ( argTypeKind )
43 import VarEnv ( lookupVarEnv )
44 import TysPrim ( alphaTyVar )
45 import Id ( mkLocalId, mkSpecPragmaId, setInlinePragma )
46 import Var ( idType, idName )
50 import SrcLoc ( Located(..), unLoc, noLoc, getLoc )
53 import Maybes ( orElse )
54 import BasicTypes ( TopLevelFlag(..), RecFlag(..), isNonRec, isRec,
55 isNotTopLevel, isAlwaysActive )
56 import FiniteMap ( listToFM, lookupFM )
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 tcTopBinds :: [HsBindGroup Name] -> TcM (LHsBinds TcId, TcLclEnv)
94 -- Note: returning the TcLclEnv is more than we really
95 -- want. The bit we care about is the local bindings
96 -- and the free type variables thereof
98 = tc_binds_and_then TopLevel glue binds $
99 getLclEnv `thenM` \ env ->
100 returnM (emptyLHsBinds, env)
102 -- The top level bindings are flattened into a giant
103 -- implicitly-mutually-recursive MonoBinds
104 glue (HsBindGroup binds1 _ _) (binds2, env) = (binds1 `unionBags` binds2, env)
105 -- Can't have a HsIPBinds at top level
109 :: (HsBindGroup TcId -> thing -> thing) -- Combinator
110 -> [HsBindGroup Name]
114 tcBindsAndThen = tc_binds_and_then NotTopLevel
116 tc_binds_and_then top_lvl combiner [] do_next
118 tc_binds_and_then top_lvl combiner (group : groups) do_next
119 = tc_bind_and_then top_lvl combiner group $
120 tc_binds_and_then top_lvl combiner groups do_next
122 tc_bind_and_then top_lvl combiner (HsIPBinds binds) do_next
123 = getLIE do_next `thenM` \ (result, expr_lie) ->
124 mapAndUnzipM (wrapLocSndM tc_ip_bind) binds `thenM` \ (avail_ips, binds') ->
126 -- If the binding binds ?x = E, we must now
127 -- discharge any ?x constraints in expr_lie
128 tcSimplifyIPs avail_ips expr_lie `thenM` \ dict_binds ->
130 returnM (combiner (HsIPBinds binds') $
131 combiner (HsBindGroup dict_binds [] Recursive) result)
133 -- I wonder if we should do these one at at time
136 tc_ip_bind (IPBind ip expr)
137 = newTyFlexiVarTy argTypeKind `thenM` \ ty ->
138 newIPDict (IPBindOrigin ip) ip ty `thenM` \ (ip', ip_inst) ->
139 tcCheckRho expr ty `thenM` \ expr' ->
140 returnM (ip_inst, (IPBind ip' expr'))
142 tc_bind_and_then top_lvl combiner (HsBindGroup binds sigs is_rec) do_next
143 | isEmptyLHsBinds binds
146 = -- BRING ANY SCOPED TYPE VARIABLES INTO SCOPE
147 -- Notice that they scope over
148 -- a) the type signatures in the binding group
149 -- b) the bindings in the group
150 -- c) the scope of the binding group (the "in" part)
151 tcAddLetBoundTyVars binds $
154 TopLevel -- For the top level don't bother will all this
155 -- bindInstsOfLocalFuns stuff. All the top level
156 -- things are rec'd together anyway, so it's fine to
157 -- leave them to the tcSimplifyTop, and quite a bit faster too
158 -> tcBindWithSigs top_lvl binds sigs is_rec `thenM` \ (poly_binds, poly_ids) ->
159 tc_body poly_ids `thenM` \ (prag_binds, thing) ->
160 returnM (combiner (HsBindGroup
161 (poly_binds `unionBags` prag_binds)
166 NotTopLevel -- For nested bindings we must do the bindInstsOfLocalFuns thing.
167 | not (isRec is_rec) -- Non-recursive group
168 -> -- We want to keep non-recursive things non-recursive
169 -- so that we desugar unlifted bindings correctly
170 tcBindWithSigs top_lvl binds sigs is_rec `thenM` \ (poly_binds, poly_ids) ->
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 ->
177 combiner (HsBindGroup poly_binds [] NonRecursive) $
178 combiner (HsBindGroup prag_binds [] NonRecursive) $
179 combiner (HsBindGroup lie_binds [] Recursive) $
180 -- NB: the binds returned by tcSimplify and
181 -- bindInstsOfLocalFuns aren't guaranteed in
182 -- dependency order (though we could change that);
183 -- hence the Recursive marker.
187 -> -- NB: polymorphic recursion means that a function
188 -- may use an instance of itself, we must look at the LIE arising
189 -- from the function's own right hand side. Hence the getLIE
190 -- encloses the tcBindWithSigs.
193 tcBindWithSigs top_lvl binds sigs is_rec `thenM` \ (poly_binds, poly_ids) ->
194 tc_body poly_ids `thenM` \ (prag_binds, thing) ->
195 returnM (poly_ids, poly_binds `unionBags` prag_binds, thing)
196 ) `thenM` \ ((poly_ids, extra_binds, thing), lie) ->
198 bindInstsOfLocalFuns lie poly_ids `thenM` \ lie_binds ->
200 returnM (combiner (HsBindGroup
201 (extra_binds `unionBags` lie_binds)
205 tc_body poly_ids -- Type check the pragmas and "thing inside"
206 = -- Extend the environment to bind the new polymorphic Ids
207 tcExtendIdEnv poly_ids $
209 -- Build bindings and IdInfos corresponding to user pragmas
210 tcSpecSigs sigs `thenM` \ prag_binds ->
212 -- Now do whatever happens next, in the augmented envt
213 do_next `thenM` \ thing ->
215 returnM (prag_binds, thing)
219 %************************************************************************
221 \subsection{tcBindWithSigs}
223 %************************************************************************
225 @tcBindWithSigs@ deals with a single binding group. It does generalisation,
226 so all the clever stuff is in here.
228 * binder_names and mbind must define the same set of Names
230 * The Names in tc_ty_sigs must be a subset of binder_names
232 * The Ids in tc_ty_sigs don't necessarily have to have the same name
233 as the Name in the tc_ty_sig
236 tcBindWithSigs :: TopLevelFlag
240 -> TcM (LHsBinds TcId, [TcId])
241 -- The returned TcIds are guaranteed zonked
243 tcBindWithSigs top_lvl mbind sigs is_rec = do
244 { -- TYPECHECK THE SIGNATURES
245 tc_ty_sigs <- recoverM (returnM []) $
246 tcTySigs [sig | sig@(L _(Sig name _)) <- sigs]
247 ; let lookup_sig = lookupSig tc_ty_sigs
249 -- SET UP THE MAIN RECOVERY; take advantage of any type sigs
250 ; recoverM (recoveryCode mbind lookup_sig) $ do
252 { traceTc (ptext SLIT("--------------------------------------------------------"))
253 ; traceTc (ptext SLIT("Bindings for") <+> ppr (collectHsBindBinders mbind))
255 -- TYPECHECK THE BINDINGS
256 ; ((mbind', mono_bind_infos), lie_req)
257 <- getLIE (tcMonoBinds mbind lookup_sig is_rec)
259 -- CHECK FOR UNLIFTED BINDINGS
260 -- These must be non-recursive etc, and are not generalised
261 -- They desugar to a case expression in the end
262 ; zonked_mono_tys <- zonkTcTypes (map getMonoType mono_bind_infos)
263 ; if any isUnLiftedType zonked_mono_tys then
264 do { -- Unlifted bindings
265 checkUnliftedBinds top_lvl is_rec mbind
267 ; let exports = zipWith mk_export mono_bind_infos zonked_mono_tys
268 mk_export (name, Nothing, mono_id) mono_ty = ([], mkLocalId name mono_ty, mono_id)
269 mk_export (name, Just sig, mono_id) mono_ty = ([], sig_id sig, mono_id)
271 ; return ( unitBag $ noLoc $ AbsBinds [] [] exports emptyNameSet mbind',
272 [poly_id | (_, poly_id, _) <- exports]) } -- Guaranteed zonked
274 else do -- The normal lifted case: GENERALISE
275 { is_unres <- isUnRestrictedGroup mbind tc_ty_sigs
276 ; (tyvars_to_gen, dict_binds, dict_ids)
277 <- setSrcSpan (getLoc (head (bagToList mbind))) $
278 -- TODO: location a bit awkward, but the mbinds have been
279 -- dependency analysed and may no longer be adjacent
280 addErrCtxt (genCtxt (bndrNames mono_bind_infos)) $
281 generalise is_unres mono_bind_infos tc_ty_sigs lie_req
283 -- FINALISE THE QUANTIFIED TYPE VARIABLES
284 -- The quantified type variables often include meta type variables
285 -- we want to freeze them into ordinary type variables, and
286 -- default their kind (e.g. from OpenTypeKind to TypeKind)
287 ; tyvars_to_gen' <- mappM zonkQuantifiedTyVar tyvars_to_gen
289 -- BUILD THE POLYMORPHIC RESULT IDs
291 exports = map mk_export mono_bind_infos
292 poly_ids = [poly_id | (_, poly_id, _) <- exports]
293 dict_tys = map idType dict_ids
295 inlines = mkNameSet [ name
296 | L _ (InlineSig True (L _ name) _) <- sigs]
297 -- Any INLINE sig (regardless of phase control)
298 -- makes the RHS look small
299 inline_phases = listToFM [ (name, phase)
300 | L _ (InlineSig _ (L _ name) phase) <- sigs,
301 not (isAlwaysActive phase)]
302 -- Set the IdInfo field to control the inline phase
303 -- AlwaysActive is the default, so don't bother with them
304 add_inlines id = attachInlinePhase inline_phases id
306 mk_export (binder_name, mb_sig, mono_id)
308 Just sig -> (sig_tvs sig, add_inlines (sig_id sig), mono_id)
309 Nothing -> (tyvars_to_gen', add_inlines new_poly_id, mono_id)
311 new_poly_id = mkLocalId binder_name poly_ty
312 poly_ty = mkForAllTys tyvars_to_gen'
316 -- ZONK THE poly_ids, because they are used to extend the type
317 -- environment; see the invariant on TcEnv.tcExtendIdEnv
318 ; zonked_poly_ids <- mappM zonkId poly_ids
320 ; traceTc (text "binding:" <+> ppr ((dict_ids, dict_binds),
321 exports, map idType zonked_poly_ids))
325 AbsBinds tyvars_to_gen'
329 (dict_binds `unionBags` mbind'),
334 -- If typechecking the binds fails, then return with each
335 -- signature-less binder given type (forall a.a), to minimise
336 -- subsequent error messages
337 recoveryCode mbind lookup_sig
338 = do { traceTc (text "tcBindsWithSigs: error recovery" <+> ppr binder_names)
339 ; return (emptyLHsBinds, poly_ids) }
341 forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
342 binder_names = collectHsBindBinders mbind
343 poly_ids = map mk_dummy binder_names
344 mk_dummy name = case lookup_sig name of
345 Just sig -> sig_id sig -- Signature
346 Nothing -> mkLocalId name forall_a_a -- No signature
348 attachInlinePhase inline_phases bndr
349 = case lookupFM inline_phases (idName bndr) of
350 Just prag -> bndr `setInlinePragma` prag
353 -- Check that non-overloaded unlifted bindings are
356 -- c) not a multiple-binding group (more or less implied by (a))
358 checkUnliftedBinds top_lvl is_rec mbind
359 = checkTc (isNotTopLevel top_lvl)
360 (unliftedBindErr "Top-level" mbind) `thenM_`
361 checkTc (isNonRec is_rec)
362 (unliftedBindErr "Recursive" mbind) `thenM_`
363 checkTc (isSingletonBag mbind)
364 (unliftedBindErr "Multiple" mbind)
368 Polymorphic recursion
369 ~~~~~~~~~~~~~~~~~~~~~
370 The game plan for polymorphic recursion in the code above is
372 * Bind any variable for which we have a type signature
373 to an Id with a polymorphic type. Then when type-checking
374 the RHSs we'll make a full polymorphic call.
376 This fine, but if you aren't a bit careful you end up with a horrendous
377 amount of partial application and (worse) a huge space leak. For example:
379 f :: Eq a => [a] -> [a]
382 If we don't take care, after typechecking we get
384 f = /\a -> \d::Eq a -> let f' = f a d
388 Notice the the stupid construction of (f a d), which is of course
389 identical to the function we're executing. In this case, the
390 polymorphic recursion isn't being used (but that's a very common case).
393 f = /\a -> \d::Eq a -> letrec
394 fm = \ys:[a] -> ...fm...
398 This can lead to a massive space leak, from the following top-level defn
404 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
405 f' is another thunk which evaluates to the same thing... and you end
406 up with a chain of identical values all hung onto by the CAF ff.
410 = let f' = f Int dEqInt in \ys. ...f'...
412 = let f' = let f' = f Int dEqInt in \ys. ...f'...
416 Solution: when typechecking the RHSs we always have in hand the
417 *monomorphic* Ids for each binding. So we just need to make sure that
418 if (Method f a d) shows up in the constraints emerging from (...f...)
419 we just use the monomorphic Id. We achieve this by adding monomorphic Ids
420 to the "givens" when simplifying constraints. That's what the "lies_avail"
424 %************************************************************************
426 \subsection{tcMonoBind}
428 %************************************************************************
430 @tcMonoBinds@ deals with a single @MonoBind@.
431 The signatures have been dealt with already.
434 tcMonoBinds :: LHsBinds Name
435 -> TcSigFun -> RecFlag
436 -> TcM (LHsBinds TcId, [MonoBindInfo])
438 tcMonoBinds binds lookup_sig is_rec
439 = do { tc_binds <- mapBagM (wrapLocM (tcLhs lookup_sig)) binds
441 -- Bring (a) the scoped type variables, and (b) the Ids, into scope for the RHSs
442 -- For (a) it's ok to bring them all into scope at once, even
443 -- though each type sig should scope only over its own RHS,
444 -- because the renamer has sorted all that out.
445 ; let mono_info = getMonoBindInfo tc_binds
446 rhs_tvs = [ (name, mkTyVarTy tv)
447 | (_, Just sig, _) <- mono_info,
448 (name, tv) <- sig_scoped sig `zip` sig_tvs sig ]
449 rhs_id_env = map mk mono_info -- A binding for each term variable
451 ; binds' <- tcExtendTyVarEnv2 rhs_tvs $
452 tcExtendIdEnv2 rhs_id_env $
453 mapBagM (wrapLocM tcRhs) tc_binds
454 ; return (binds', mono_info) }
456 mk (name, Just sig, _) = (name, sig_id sig) -- Use the type sig if there is one
457 mk (name, Nothing, mono_id) = (name, mono_id) -- otherwise use a monomorphic version
459 ------------------------
460 -- tcLhs typechecks the LHS of the bindings, to construct the environment in which
461 -- we typecheck the RHSs. Basically what we are doing is this: for each binder:
462 -- if there's a signature for it, use the instantiated signature type
463 -- otherwise invent a type variable
464 -- You see that quite directly in the FunBind case.
466 -- But there's a complication for pattern bindings:
467 -- data T = MkT (forall a. a->a)
469 -- Here we can guess a type variable for the entire LHS (which will be refined to T)
470 -- but we want to get (f::forall a. a->a) as the RHS environment.
471 -- The simplest way to do this is to typecheck the pattern, and then look up the
472 -- bound mono-ids. Then we want to retain the typechecked pattern to avoid re-doing
473 -- it; hence the TcMonoBind data type in which the LHS is done but the RHS isn't
475 data TcMonoBind -- Half completed; LHS done, RHS not done
476 = TcFunBind MonoBindInfo (Located TcId) Bool (MatchGroup Name)
477 | TcPatBind [MonoBindInfo] (LPat TcId) (GRHSs Name) TcSigmaType
479 type MonoBindInfo = (Name, Maybe TcSigInfo, TcId)
480 -- Type signature (if any), and
481 -- the monomorphic bound things
483 bndrNames :: [MonoBindInfo] -> [Name]
484 bndrNames mbi = [n | (n,_,_) <- mbi]
486 getMonoType :: MonoBindInfo -> TcTauType
487 getMonoType (_,_,mono_id) = idType mono_id
489 tcLhs :: TcSigFun -> HsBind Name -> TcM TcMonoBind
490 tcLhs lookup_sig (FunBind (L nm_loc name) inf matches)
491 = do { let mb_sig = lookup_sig name
492 ; mono_name <- newLocalName name
493 ; mono_ty <- mk_mono_ty mb_sig
494 ; let mono_id = mkLocalId mono_name mono_ty
495 ; return (TcFunBind (name, mb_sig, mono_id) (L nm_loc mono_id) inf matches) }
497 mk_mono_ty (Just sig) = return (sig_tau sig)
498 mk_mono_ty Nothing = newTyFlexiVarTy argTypeKind
500 tcLhs lookup_sig bind@(PatBind pat grhss _)
501 = do { let tc_pat exp_ty = tcPat (LetPat lookup_sig) pat exp_ty lookup_infos
502 ; ((pat', ex_tvs, infos), pat_ty)
503 <- addErrCtxt (patMonoBindsCtxt pat grhss)
506 -- Don't know how to deal with pattern-bound existentials yet
507 ; checkTc (null ex_tvs) (existentialExplode bind)
509 ; return (TcPatBind infos pat' grhss pat_ty) }
511 names = collectPatBinders pat
513 -- After typechecking the pattern, look up the binder
514 -- names, which the pattern has brought into scope.
515 lookup_infos :: TcM [MonoBindInfo]
516 lookup_infos = do { mono_ids <- tcLookupLocalIds names
517 ; return [ (name, lookup_sig name, mono_id)
518 | (name, mono_id) <- names `zip` mono_ids] }
521 tcRhs :: TcMonoBind -> TcM (HsBind TcId)
522 tcRhs (TcFunBind info fun'@(L _ mono_id) inf matches)
523 = do { matches' <- tcMatchesFun (idName mono_id) matches
524 (Check (idType mono_id))
525 ; return (FunBind fun' inf matches') }
527 tcRhs bind@(TcPatBind _ pat' grhss pat_ty)
528 = do { grhss' <- addErrCtxt (patMonoBindsCtxt pat' grhss) $
529 tcGRHSsPat grhss (Check pat_ty)
530 ; return (PatBind pat' grhss' pat_ty) }
533 ---------------------
534 getMonoBindInfo :: Bag (Located TcMonoBind) -> [MonoBindInfo]
535 getMonoBindInfo tc_binds
536 = foldrBag (get_info . unLoc) [] tc_binds
538 get_info (TcFunBind info _ _ _) rest = info : rest
539 get_info (TcPatBind infos _ _ _) rest = infos ++ rest
543 %************************************************************************
545 \subsection{getTyVarsToGen}
547 %************************************************************************
550 tcTySigs :: [LSig Name] -> TcM [TcSigInfo]
551 -- The trick here is that all the signatures should have the same
552 -- context, and we want to share type variables for that context, so that
553 -- all the right hand sides agree a common vocabulary for their type
555 tcTySigs [] = return []
558 = do { (tc_sig1 : tc_sigs) <- mappM tcTySig sigs
559 ; tc_sigs' <- mapM (checkSigCtxt tc_sig1) tc_sigs
560 ; return (tc_sig1 : tc_sigs') }
562 tcTySig :: LSig Name -> TcM TcSigInfo
563 tcTySig (L span (Sig (L _ name) ty))
565 do { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
566 ; let rigid_info = SigSkol name
567 poly_id = mkLocalId name sigma_ty
569 -- The scoped names are the ones explicitly mentioned
570 -- in the HsForAll. (There may be more in sigma_ty, because
571 -- of nested type synonyms. See Note [Scoped] with TcSigInfo.)
572 scoped_names = case ty of
573 L _ (HsForAllTy _ tvs _ _) -> hsLTyVarNames tvs
576 ; (tvs, theta, tau) <- tcSkolType rigid_info sigma_ty
577 ; loc <- getInstLoc (SigOrigin rigid_info)
578 ; return (TcSigInfo { sig_id = poly_id, sig_scoped = scoped_names,
579 sig_tvs = tvs, sig_theta = theta, sig_tau = tau,
582 checkSigCtxt :: TcSigInfo -> TcSigInfo -> TcM TcSigInfo
583 checkSigCtxt sig1 sig@(TcSigInfo { sig_tvs = tvs, sig_theta = theta, sig_tau = tau })
584 = -- Try to match the context of this signature with
585 -- that of the first signature
586 case tcMatchPreds (sig_tvs sig) (sig_theta sig) (sig_theta sig1) of {
587 Nothing -> bale_out ;
590 case check_tvs tenv tvs of {
591 Nothing -> bale_out ;
595 subst = mkTvSubst tenv
597 return (sig { sig_tvs = tvs',
598 sig_theta = substTheta subst theta,
599 sig_tau = substTy subst tau }) }}
602 bale_out = setSrcSpan (instLocSrcSpan (sig_loc sig)) $
604 sigContextsErr (sig_id sig1) (sig_id sig)
606 -- Rather tedious check that the type variables
607 -- have been matched only with another type variable,
608 -- and that two type variables have not been matched
610 -- A return of Nothing indicates that one of the bad
611 -- things has happened
612 check_tvs :: TvSubstEnv -> [TcTyVar] -> Maybe [TcTyVar]
613 check_tvs tenv [] = Just []
614 check_tvs tenv (tv:tvs)
615 = do { let ty = lookupVarEnv tenv tv `orElse` mkTyVarTy tv
616 ; tv' <- tcGetTyVar_maybe ty
617 ; tvs' <- check_tvs tenv tvs
620 else Just (tv':tvs') }
624 generalise :: Bool -> [MonoBindInfo] -> [TcSigInfo] -> [Inst]
625 -> TcM ([TcTyVar], TcDictBinds, [TcId])
626 generalise is_unrestricted mono_infos sigs lie_req
627 | not is_unrestricted -- RESTRICTED CASE
628 = -- Check signature contexts are empty
629 do { checkTc (all is_mono_sig sigs)
630 (restrictedBindCtxtErr bndr_names)
632 -- Now simplify with exactly that set of tyvars
633 -- We have to squash those Methods
634 ; (qtvs, binds) <- tcSimplifyRestricted doc tau_tvs lie_req
636 -- Check that signature type variables are OK
637 ; final_qtvs <- checkSigsTyVars qtvs sigs
639 ; return (final_qtvs, binds, []) }
641 | null sigs -- UNRESTRICTED CASE, NO TYPE SIGS
642 = tcSimplifyInfer doc tau_tvs lie_req
644 | otherwise -- UNRESTRICTED CASE, WITH TYPE SIGS
645 = do { let sig1 = head sigs
646 ; sig_lie <- newDictsAtLoc (sig_loc sig1) (sig_theta sig1)
647 ; let -- The "sig_avails" is the stuff available. We get that from
648 -- the context of the type signature, BUT ALSO the lie_avail
649 -- so that polymorphic recursion works right (see comments at end of fn)
650 local_meths = [mkMethInst sig mono_id | (_, Just sig, mono_id) <- mono_infos]
651 sig_avails = sig_lie ++ local_meths
653 -- Check that the needed dicts can be
654 -- expressed in terms of the signature ones
655 ; (forall_tvs, dict_binds) <- tcSimplifyInferCheck doc tau_tvs sig_avails lie_req
657 -- Check that signature type variables are OK
658 ; final_qtvs <- checkSigsTyVars forall_tvs sigs
660 ; returnM (final_qtvs, dict_binds, map instToId sig_lie) }
663 bndr_names = bndrNames mono_infos
664 tau_tvs = foldr (unionVarSet . tyVarsOfType . getMonoType) emptyVarSet mono_infos
665 is_mono_sig sig = null (sig_theta sig)
666 doc = ptext SLIT("type signature(s) for") <+> pprBinders bndr_names
668 mkMethInst (TcSigInfo { sig_id = poly_id, sig_tvs = tvs,
669 sig_theta = theta, sig_tau = tau, sig_loc = loc }) mono_id
670 = Method mono_id poly_id (mkTyVarTys tvs) theta tau loc
672 checkSigsTyVars :: [TcTyVar] -> [TcSigInfo] -> TcM [TcTyVar]
673 checkSigsTyVars qtvs sigs
674 = mappM check_one sigs `thenM` \ sig_tvs_s ->
676 -- Sigh. Make sure that all the tyvars in the type sigs
677 -- appear in the returned ty var list, which is what we are
678 -- going to generalise over. Reason: we occasionally get
680 -- type T a = () -> ()
683 -- Here, 'a' won't appear in qtvs, so we have to add it
685 sig_tvs = foldl extendVarSetList emptyVarSet sig_tvs_s
686 all_tvs = extendVarSetList sig_tvs qtvs
688 returnM (varSetElems all_tvs)
690 check_one (TcSigInfo {sig_id = id, sig_tvs = tvs, sig_theta = theta, sig_tau = tau})
691 = addErrCtxt (ptext SLIT("In the type signature for")
692 <+> quotes (ppr id)) $
693 addErrCtxtM (sigCtxt id tvs theta tau) $
694 do { checkSigTyVars tvs; return tvs }
697 @getTyVarsToGen@ decides what type variables to generalise over.
699 For a "restricted group" -- see the monomorphism restriction
700 for a definition -- we bind no dictionaries, and
701 remove from tyvars_to_gen any constrained type variables
703 *Don't* simplify dicts at this point, because we aren't going
704 to generalise over these dicts. By the time we do simplify them
705 we may well know more. For example (this actually came up)
707 f x = array ... xs where xs = [1,2,3,4,5]
708 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
709 stuff. If we simplify only at the f-binding (not the xs-binding)
710 we'll know that the literals are all Ints, and we can just produce
713 Find all the type variables involved in overloading, the
714 "constrained_tyvars". These are the ones we *aren't* going to
715 generalise. We must be careful about doing this:
717 (a) If we fail to generalise a tyvar which is not actually
718 constrained, then it will never, ever get bound, and lands
719 up printed out in interface files! Notorious example:
720 instance Eq a => Eq (Foo a b) where ..
721 Here, b is not constrained, even though it looks as if it is.
722 Another, more common, example is when there's a Method inst in
723 the LIE, whose type might very well involve non-overloaded
725 [NOTE: Jan 2001: I don't understand the problem here so I'm doing
726 the simple thing instead]
728 (b) On the other hand, we mustn't generalise tyvars which are constrained,
729 because we are going to pass on out the unmodified LIE, with those
730 tyvars in it. They won't be in scope if we've generalised them.
732 So we are careful, and do a complete simplification just to find the
733 constrained tyvars. We don't use any of the results, except to
734 find which tyvars are constrained.
737 isUnRestrictedGroup :: LHsBinds Name -> [TcSigInfo] -> TcM Bool
738 isUnRestrictedGroup binds sigs
739 = do { mono_restriction <- doptM Opt_MonomorphismRestriction
740 ; return (not mono_restriction || all_unrestricted) }
742 all_unrestricted = all (unrestricted . unLoc) (bagToList binds)
743 tysig_names = map (idName . sig_id) sigs
745 unrestricted (PatBind other _ _) = False
746 unrestricted (VarBind v _) = v `is_elem` tysig_names
747 unrestricted (FunBind v _ matches) = unrestricted_match matches
748 || unLoc v `is_elem` tysig_names
750 unrestricted_match (MatchGroup (L _ (Match [] _ _) : _) _) = False
751 -- No args => like a pattern binding
752 unrestricted_match other = True
753 -- Some args => a function binding
755 is_elem v vs = isIn "isUnResMono" v vs
759 %************************************************************************
761 \subsection{SPECIALIZE pragmas}
763 %************************************************************************
765 @tcSpecSigs@ munches up the specialisation "signatures" that arise through *user*
766 pragmas. It is convenient for them to appear in the @[RenamedSig]@
767 part of a binding because then the same machinery can be used for
768 moving them into place as is done for type signatures.
773 f :: Ord a => [a] -> b -> b
774 {-# SPECIALIZE f :: [Int] -> b -> b #-}
777 For this we generate:
779 f* = /\ b -> let d1 = ...
783 where f* is a SpecPragmaId. The **sole** purpose of SpecPragmaIds is to
784 retain a right-hand-side that the simplifier will otherwise discard as
785 dead code... the simplifier has a flag that tells it not to discard
786 SpecPragmaId bindings.
788 In this case the f* retains a call-instance of the overloaded
789 function, f, (including appropriate dictionaries) so that the
790 specialiser will subsequently discover that there's a call of @f@ at
791 Int, and will create a specialisation for @f@. After that, the
792 binding for @f*@ can be discarded.
794 We used to have a form
795 {-# SPECIALISE f :: <type> = g #-}
796 which promised that g implemented f at <type>, but we do that with
798 {-# RULES (f::<type>) = g #-}
801 tcSpecSigs :: [LSig Name] -> TcM (LHsBinds TcId)
802 tcSpecSigs (L loc (SpecSig (L nm_loc name) poly_ty) : sigs)
803 = -- SPECIALISE f :: forall b. theta => tau = g
805 addErrCtxt (valSpecSigCtxt name poly_ty) $
807 -- Get and instantiate its alleged specialised type
808 tcHsSigType (FunSigCtxt name) poly_ty `thenM` \ sig_ty ->
810 -- Check that f has a more general type, and build a RHS for
811 -- the spec-pragma-id at the same time
812 getLIE (tcCheckSigma (L nm_loc (HsVar name)) sig_ty) `thenM` \ (spec_expr, spec_lie) ->
814 -- Squeeze out any Methods (see comments with tcSimplifyToDicts)
815 tcSimplifyToDicts spec_lie `thenM` \ spec_binds ->
817 -- Just specialise "f" by building a SpecPragmaId binding
818 -- It is the thing that makes sure we don't prematurely
819 -- dead-code-eliminate the binding we are really interested in.
820 newLocalName name `thenM` \ spec_name ->
822 spec_bind = VarBind (mkSpecPragmaId spec_name sig_ty)
823 (mkHsLet spec_binds spec_expr)
826 -- Do the rest and combine
827 tcSpecSigs sigs `thenM` \ binds_rest ->
828 returnM (binds_rest `snocBag` L loc spec_bind)
830 tcSpecSigs (other_sig : sigs) = tcSpecSigs sigs
831 tcSpecSigs [] = returnM emptyLHsBinds
834 %************************************************************************
836 \subsection[TcBinds-errors]{Error contexts and messages}
838 %************************************************************************
842 -- This one is called on LHS, when pat and grhss are both Name
843 -- and on RHS, when pat is TcId and grhss is still Name
844 patMonoBindsCtxt pat grhss
845 = hang (ptext SLIT("In a pattern binding:")) 4 (pprPatBind pat grhss)
847 -----------------------------------------------
849 = sep [ptext SLIT("In a SPECIALIZE pragma for a value:"),
850 nest 4 (ppr v <+> dcolon <+> ppr ty)]
852 -----------------------------------------------
853 sigContextsErr id1 id2
854 = vcat [ptext SLIT("Mis-match between the contexts of the signatures for"),
855 nest 2 (vcat [ppr id1 <+> dcolon <+> ppr (idType id1),
856 ppr id2 <+> dcolon <+> ppr (idType id2)]),
857 ptext SLIT("The signature contexts in a mutually recursive group should all be identical")]
860 -----------------------------------------------
861 unliftedBindErr flavour mbind
862 = hang (text flavour <+> ptext SLIT("bindings for unlifted types aren't allowed:"))
865 -----------------------------------------------
866 existentialExplode mbinds
867 = hang (vcat [text "My brain just exploded.",
868 text "I can't handle pattern bindings for existentially-quantified constructors.",
869 text "In the binding group"])
872 -----------------------------------------------
873 restrictedBindCtxtErr binder_names
874 = hang (ptext SLIT("Illegal overloaded type signature(s)"))
875 4 (vcat [ptext SLIT("in a binding group for") <+> pprBinders binder_names,
876 ptext SLIT("that falls under the monomorphism restriction")])
879 = ptext SLIT("When generalising the type(s) for") <+> pprBinders binder_names
881 -- Used in error messages
882 -- Use quotes for a single one; they look a bit "busy" for several
883 pprBinders [bndr] = quotes (ppr bndr)
884 pprBinders bndrs = pprWithCommas ppr bndrs