2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 \section[TcBinds]{TcBinds}
8 module TcBinds ( tcLocalBinds, tcTopBinds,
9 tcHsBootSigs, tcPolyBinds,
10 PragFun, tcSpecPrags, mkPragFun,
11 TcSigInfo(..), SigFun, mkSigFun,
12 badBootDeclErr ) where
14 import {-# SOURCE #-} TcMatches ( tcGRHSsPat, tcMatchesFun )
15 import {-# SOURCE #-} TcExpr ( tcMonoExpr )
28 import RnBinds( misplacedSigErr )
47 import Data.List( partition )
50 #include "HsVersions.h"
54 %************************************************************************
56 \subsection{Type-checking bindings}
58 %************************************************************************
60 @tcBindsAndThen@ typechecks a @HsBinds@. The "and then" part is because
61 it needs to know something about the {\em usage} of the things bound,
62 so that it can create specialisations of them. So @tcBindsAndThen@
63 takes a function which, given an extended environment, E, typechecks
64 the scope of the bindings returning a typechecked thing and (most
65 important) an LIE. It is this LIE which is then used as the basis for
66 specialising the things bound.
68 @tcBindsAndThen@ also takes a "combiner" which glues together the
69 bindings and the "thing" to make a new "thing".
71 The real work is done by @tcBindWithSigsAndThen@.
73 Recursive and non-recursive binds are handled in essentially the same
74 way: because of uniques there are no scoping issues left. The only
75 difference is that non-recursive bindings can bind primitive values.
77 Even for non-recursive binding groups we add typings for each binder
78 to the LVE for the following reason. When each individual binding is
79 checked the type of its LHS is unified with that of its RHS; and
80 type-checking the LHS of course requires that the binder is in scope.
82 At the top-level the LIE is sure to contain nothing but constant
83 dictionaries, which we resolve at the module level.
86 tcTopBinds :: HsValBinds Name
87 -> TcM ( LHsBinds TcId -- Typechecked bindings
88 , [LTcSpecPrag] -- SPECIALISE prags for imported Ids
89 , TcLclEnv) -- Augmented environment
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 = do { (ValBindsOut prs sigs, env) <- tcValBinds TopLevel binds getLclEnv
96 ; let binds = foldr (unionBags . snd) emptyBag prs
97 ; specs <- tcImpPrags sigs
98 ; return (binds, specs, env) }
99 -- The top level bindings are flattened into a giant
100 -- implicitly-mutually-recursive LHsBinds
102 tcHsBootSigs :: HsValBinds Name -> TcM [Id]
103 -- A hs-boot file has only one BindGroup, and it only has type
104 -- signatures in it. The renamer checked all this
105 tcHsBootSigs (ValBindsOut binds sigs)
106 = do { checkTc (null binds) badBootDeclErr
107 ; mapM (addLocM tc_boot_sig) (filter isTypeLSig sigs) }
109 tc_boot_sig (TypeSig (L _ name) ty)
110 = do { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
111 ; return (mkVanillaGlobal name sigma_ty) }
112 -- Notice that we make GlobalIds, not LocalIds
113 tc_boot_sig s = pprPanic "tcHsBootSigs/tc_boot_sig" (ppr s)
114 tcHsBootSigs groups = pprPanic "tcHsBootSigs" (ppr groups)
116 badBootDeclErr :: Message
117 badBootDeclErr = ptext (sLit "Illegal declarations in an hs-boot file")
119 ------------------------
120 tcLocalBinds :: HsLocalBinds Name -> TcM thing
121 -> TcM (HsLocalBinds TcId, thing)
123 tcLocalBinds EmptyLocalBinds thing_inside
124 = do { thing <- thing_inside
125 ; return (EmptyLocalBinds, thing) }
127 tcLocalBinds (HsValBinds binds) thing_inside
128 = do { (binds', thing) <- tcValBinds NotTopLevel binds thing_inside
129 ; return (HsValBinds binds', thing) }
131 tcLocalBinds (HsIPBinds (IPBinds ip_binds _)) thing_inside
132 = do { (given_ips, ip_binds') <- mapAndUnzipM (wrapLocSndM tc_ip_bind) ip_binds
133 ; let ip_tvs = foldr (unionVarSet . tyVarsOfType . idType) emptyVarSet given_ips
135 -- If the binding binds ?x = E, we must now
136 -- discharge any ?x constraints in expr_lie
137 ; (ev_binds, result) <- checkConstraints (IPSkol ips)
138 ip_tvs -- See Note [Implicit parameter untouchables]
142 ; return (HsIPBinds (IPBinds ip_binds' ev_binds), result) }
144 ips = [ip | L _ (IPBind ip _) <- ip_binds]
146 -- I wonder if we should do these one at at time
149 tc_ip_bind (IPBind ip expr)
150 = do { ty <- newFlexiTyVarTy argTypeKind
151 ; ip_id <- newIP ip ty
152 ; expr' <- tcMonoExpr expr ty
153 ; return (ip_id, (IPBind (IPName ip_id) expr')) }
156 Note [Implicit parameter untouchables]
157 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
158 We add the type variables in the types of the implicit parameters
159 as untouchables, not so much because we really must not unify them,
160 but rather because we otherwise end up with constraints like this
161 Num alpha, Implic { wanted = alpha ~ Int }
162 The constraint solver solves alpha~Int by unification, but then
163 doesn't float that solved constraint out (it's not an unsolved
164 wanted. Result disaster: the (Num alpha) is again solved, this
165 time by defaulting. No no no.
168 tcValBinds :: TopLevelFlag
169 -> HsValBinds Name -> TcM thing
170 -> TcM (HsValBinds TcId, thing)
172 tcValBinds _ (ValBindsIn binds _) _
173 = pprPanic "tcValBinds" (ppr binds)
175 tcValBinds top_lvl (ValBindsOut binds sigs) thing_inside
176 = do { -- Typecheck the signature
177 ; let { prag_fn = mkPragFun sigs (foldr (unionBags . snd) emptyBag binds)
178 ; ty_sigs = filter isTypeLSig sigs
179 ; sig_fn = mkSigFun ty_sigs }
181 ; poly_ids <- checkNoErrs (mapAndRecoverM tcTySig ty_sigs)
182 -- No recovery from bad signatures, because the type sigs
183 -- may bind type variables, so proceeding without them
184 -- can lead to a cascade of errors
185 -- ToDo: this means we fall over immediately if any type sig
186 -- is wrong, which is over-conservative, see Trac bug #745
188 -- Extend the envt right away with all
189 -- the Ids declared with type signatures
190 ; (binds', thing) <- tcExtendIdEnv poly_ids $
191 tcBindGroups top_lvl sig_fn prag_fn
194 ; return (ValBindsOut binds' sigs, thing) }
196 ------------------------
197 tcBindGroups :: TopLevelFlag -> SigFun -> PragFun
198 -> [(RecFlag, LHsBinds Name)] -> TcM thing
199 -> TcM ([(RecFlag, LHsBinds TcId)], thing)
200 -- Typecheck a whole lot of value bindings,
201 -- one strongly-connected component at a time
202 -- Here a "strongly connected component" has the strightforward
203 -- meaning of a group of bindings that mention each other,
204 -- ignoring type signatures (that part comes later)
206 tcBindGroups _ _ _ [] thing_inside
207 = do { thing <- thing_inside
208 ; return ([], thing) }
210 tcBindGroups top_lvl sig_fn prag_fn (group : groups) thing_inside
211 = do { (group', (groups', thing))
212 <- tc_group top_lvl sig_fn prag_fn group $
213 tcBindGroups top_lvl sig_fn prag_fn groups thing_inside
214 ; return (group' ++ groups', thing) }
216 ------------------------
217 tc_group :: forall thing.
218 TopLevelFlag -> SigFun -> PragFun
219 -> (RecFlag, LHsBinds Name) -> TcM thing
220 -> TcM ([(RecFlag, LHsBinds TcId)], thing)
222 -- Typecheck one strongly-connected component of the original program.
223 -- We get a list of groups back, because there may
224 -- be specialisations etc as well
226 tc_group top_lvl sig_fn prag_fn (NonRecursive, binds) thing_inside
227 -- A single non-recursive binding
228 -- We want to keep non-recursive things non-recursive
229 -- so that we desugar unlifted bindings correctly
230 = do { (binds1, ids) <- tcPolyBinds top_lvl sig_fn prag_fn NonRecursive NonRecursive
232 ; thing <- tcExtendIdEnv ids thing_inside
233 ; return ( [(NonRecursive, binds1)], thing) }
235 tc_group top_lvl sig_fn prag_fn (Recursive, binds) thing_inside
236 = -- To maximise polymorphism (assumes -XRelaxedPolyRec), we do a new
237 -- strongly-connected-component analysis, this time omitting
238 -- any references to variables with type signatures.
239 do { traceTc "tc_group rec" (pprLHsBinds binds)
240 ; (binds1, _ids, thing) <- go sccs
241 -- Here is where we should do bindInstsOfLocalFuns
242 -- if we start having Methods again
243 ; return ([(Recursive, binds1)], thing) }
244 -- Rec them all together
246 sccs :: [SCC (LHsBind Name)]
247 sccs = stronglyConnCompFromEdgedVertices (mkEdges sig_fn binds)
249 go :: [SCC (LHsBind Name)] -> TcM (LHsBinds TcId, [TcId], thing)
250 go (scc:sccs) = do { (binds1, ids1) <- tc_scc scc
251 ; (binds2, ids2, thing) <- tcExtendIdEnv ids1 $ go sccs
252 ; return (binds1 `unionBags` binds2, ids1 ++ ids2, thing) }
253 go [] = do { thing <- thing_inside; return (emptyBag, [], thing) }
255 tc_scc (AcyclicSCC bind) = tc_sub_group NonRecursive [bind]
256 tc_scc (CyclicSCC binds) = tc_sub_group Recursive binds
258 tc_sub_group = tcPolyBinds top_lvl sig_fn prag_fn Recursive
261 ------------------------
263 bindLocalInsts :: TopLevelFlag
264 -> TcM (LHsBinds TcId, [TcId], a)
265 -> TcM (LHsBinds TcId, TcEvBinds, a)
266 bindLocalInsts top_lvl thing_inside
268 = do { (binds, _, thing) <- thing_inside; return (binds, emptyBag, thing) }
269 -- For the top level don't bother with all this bindInstsOfLocalFuns stuff.
270 -- All the top level things are rec'd together anyway, so it's fine to
271 -- leave them to the tcSimplifyTop, and quite a bit faster too
273 | otherwise -- Nested case
274 = do { ((binds, ids, thing), lie) <- captureConstraints thing_inside
275 ; lie_binds <- bindLocalMethods lie ids
276 ; return (binds, lie_binds, thing) }
279 ------------------------
280 mkEdges :: SigFun -> LHsBinds Name
281 -> [(LHsBind Name, BKey, [BKey])]
283 type BKey = Int -- Just number off the bindings
286 = [ (bind, key, [key | n <- nameSetToList (bind_fvs (unLoc bind)),
287 Just key <- [lookupNameEnv key_map n], no_sig n ])
288 | (bind, key) <- keyd_binds
291 no_sig :: Name -> Bool
292 no_sig n = isNothing (sig_fn n)
294 keyd_binds = bagToList binds `zip` [0::BKey ..]
296 key_map :: NameEnv BKey -- Which binding it comes from
297 key_map = mkNameEnv [(bndr, key) | (L _ bind, key) <- keyd_binds
298 , bndr <- bindersOfHsBind bind ]
300 bindersOfHsBind :: HsBind Name -> [Name]
301 bindersOfHsBind (PatBind { pat_lhs = pat }) = collectPatBinders pat
302 bindersOfHsBind (FunBind { fun_id = L _ f }) = [f]
303 bindersOfHsBind (AbsBinds {}) = panic "bindersOfHsBind AbsBinds"
304 bindersOfHsBind (VarBind {}) = panic "bindersOfHsBind VarBind"
306 ------------------------
307 tcPolyBinds :: TopLevelFlag -> SigFun -> PragFun
308 -> RecFlag -- Whether the group is really recursive
309 -> RecFlag -- Whether it's recursive after breaking
310 -- dependencies based on type signatures
312 -> TcM (LHsBinds TcId, [TcId])
314 -- Typechecks a single bunch of bindings all together,
315 -- and generalises them. The bunch may be only part of a recursive
316 -- group, because we use type signatures to maximise polymorphism
318 -- Returns a list because the input may be a single non-recursive binding,
319 -- in which case the dependency order of the resulting bindings is
322 -- Knows nothing about the scope of the bindings
324 tcPolyBinds top_lvl sig_fn prag_fn rec_group rec_tc bind_list
326 recoverM (recoveryCode binder_names sig_fn) $ do
327 -- Set up main recoer; take advantage of any type sigs
329 { traceTc "------------------------------------------------" empty
330 ; traceTc "Bindings for" (ppr binder_names)
332 ; tc_sig_fn <- tcInstSigs sig_fn binder_names
335 ; let plan = decideGeneralisationPlan dflags top_lvl binder_names bind_list tc_sig_fn
336 ; traceTc "Generalisation plan" (ppr plan)
337 ; (binds, poly_ids) <- case plan of
338 NoGen -> tcPolyNoGen tc_sig_fn prag_fn rec_tc bind_list
339 InferGen mono -> tcPolyInfer top_lvl mono tc_sig_fn prag_fn rec_tc bind_list
340 CheckGen sig -> tcPolyCheck sig prag_fn rec_tc bind_list
342 -- Check whether strict bindings are ok
343 -- These must be non-recursive etc, and are not generalised
344 -- They desugar to a case expression in the end
345 ; checkStrictBinds top_lvl rec_group bind_list poly_ids
347 ; return (binds, poly_ids) }
349 binder_names = collectHsBindListBinders bind_list
350 loc = getLoc (head bind_list)
351 -- TODO: location a bit awkward, but the mbinds have been
352 -- dependency analysed and may no longer be adjacent
356 :: TcSigFun -> PragFun
357 -> RecFlag -- Whether it's recursive after breaking
358 -- dependencies based on type signatures
360 -> TcM (LHsBinds TcId, [TcId])
361 -- No generalisation whatsoever
363 tcPolyNoGen tc_sig_fn prag_fn rec_tc bind_list
364 = do { (binds', mono_infos) <- tcMonoBinds tc_sig_fn (LetGblBndr prag_fn)
366 ; mono_ids' <- mapM tc_mono_info mono_infos
367 ; return (binds', mono_ids') }
369 tc_mono_info (name, _, mono_id)
370 = do { mono_ty' <- zonkTcTypeCarefully (idType mono_id)
371 -- Zonk, mainly to expose unboxed types to checkStrictBinds
372 ; let mono_id' = setIdType mono_id mono_ty'
373 ; _specs <- tcSpecPrags mono_id' (prag_fn name)
375 -- NB: tcPrags generates error messages for
376 -- specialisation pragmas for non-overloaded sigs
377 -- Indeed that is why we call it here!
378 -- So we can safely ignore _specs
381 tcPolyCheck :: TcSigInfo -> PragFun
382 -> RecFlag -- Whether it's recursive after breaking
383 -- dependencies based on type signatures
385 -> TcM (LHsBinds TcId, [TcId])
386 -- There is just one binding,
387 -- it binds a single variable,
388 -- it has a signature,
389 tcPolyCheck sig@(TcSigInfo { sig_id = id, sig_tvs = tvs, sig_scoped = scoped
390 , sig_theta = theta, sig_loc = loc })
391 prag_fn rec_tc bind_list
392 = do { ev_vars <- newEvVars theta
394 ; let skol_info = SigSkol (FunSigCtxt (idName id))
395 ; (ev_binds, (binds', [mono_info]))
396 <- checkConstraints skol_info emptyVarSet tvs ev_vars $
397 tcExtendTyVarEnv2 (scoped `zip` mkTyVarTys tvs) $
398 tcMonoBinds (\_ -> Just sig) LetLclBndr rec_tc bind_list
400 ; export <- mkExport prag_fn tvs theta mono_info
402 ; let (_, poly_id, _, _) = export
403 abs_bind = L loc $ AbsBinds
405 , abs_ev_vars = ev_vars, abs_ev_binds = ev_binds
406 , abs_exports = [export], abs_binds = binds' }
407 ; return (unitBag abs_bind, [poly_id]) }
412 -> Bool -- True <=> apply the monomorphism restriction
413 -> TcSigFun -> PragFun
414 -> RecFlag -- Whether it's recursive after breaking
415 -- dependencies based on type signatures
417 -> TcM (LHsBinds TcId, [TcId])
418 tcPolyInfer top_lvl mono sig_fn prag_fn rec_tc bind_list
419 = do { ((binds', mono_infos), wanted)
420 <- captureConstraints $
421 tcMonoBinds sig_fn LetLclBndr rec_tc bind_list
423 ; unifyCtxts [sig | (_, Just sig, _) <- mono_infos]
425 ; let get_tvs | isTopLevel top_lvl = tyVarsOfType
426 | otherwise = exactTyVarsOfType
427 -- See Note [Silly type synonym] in TcType
428 tau_tvs = foldr (unionVarSet . get_tvs . getMonoType) emptyVarSet mono_infos
430 ; (qtvs, givens, ev_binds) <- simplifyInfer mono tau_tvs wanted
432 ; exports <- mapM (mkExport prag_fn qtvs (map evVarPred givens))
435 ; let poly_ids = [poly_id | (_, poly_id, _, _) <- exports]
436 ; traceTc "Binding:" (ppr (poly_ids `zip` map idType poly_ids))
439 ; let abs_bind = L loc $ AbsBinds { abs_tvs = qtvs
440 , abs_ev_vars = givens, abs_ev_binds = ev_binds
441 , abs_exports = exports, abs_binds = binds' }
443 ; return (unitBag abs_bind, poly_ids) -- poly_ids are guaranteed zonked by mkExport
448 mkExport :: PragFun -> [TyVar] -> TcThetaType
450 -> TcM ([TyVar], Id, Id, TcSpecPrags)
451 -- mkExport generates exports with
452 -- zonked type variables,
454 -- The former is just because no further unifications will change
455 -- the quantified type variables, so we can fix their final form
457 -- The latter is needed because the poly_ids are used to extend the
458 -- type environment; see the invariant on TcEnv.tcExtendIdEnv
460 -- Pre-condition: the inferred_tvs are already zonked
462 mkExport prag_fn inferred_tvs theta
463 (poly_name, mb_sig, mono_id)
464 = do { (tvs, poly_id) <- mk_poly_id mb_sig
465 -- poly_id has a zonked type
467 ; poly_id' <- addInlinePrags poly_id prag_sigs
469 ; spec_prags <- tcSpecPrags poly_id prag_sigs
470 -- tcPrags requires a zonked poly_id
472 ; return (tvs, poly_id', mono_id, SpecPrags spec_prags) }
474 prag_sigs = prag_fn poly_name
475 poly_ty = mkSigmaTy inferred_tvs theta (idType mono_id)
477 mk_poly_id Nothing = do { poly_ty' <- zonkTcTypeCarefully poly_ty
478 ; return (inferred_tvs, mkLocalId poly_name poly_ty') }
479 mk_poly_id (Just sig) = do { tvs <- mapM zonk_tv (sig_tvs sig)
480 ; return (tvs, sig_id sig) }
482 zonk_tv tv = do { ty <- zonkTcTyVar tv; return (tcGetTyVar "mkExport" ty) }
484 ------------------------
485 type PragFun = Name -> [LSig Name]
487 mkPragFun :: [LSig Name] -> LHsBinds Name -> PragFun
488 mkPragFun sigs binds = \n -> lookupNameEnv prag_env n `orElse` []
490 prs = mapCatMaybes get_sig sigs
492 get_sig :: LSig Name -> Maybe (Located Name, LSig Name)
493 get_sig (L l (SpecSig nm ty inl)) = Just (nm, L l $ SpecSig nm ty (add_arity nm inl))
494 get_sig (L l (InlineSig nm inl)) = Just (nm, L l $ InlineSig nm (add_arity nm inl))
497 add_arity (L _ n) inl_prag -- Adjust inl_sat field to match visible arity of function
498 | Just ar <- lookupNameEnv ar_env n = inl_prag { inl_sat = Just ar }
499 | otherwise = inl_prag
501 prag_env :: NameEnv [LSig Name]
502 prag_env = foldl add emptyNameEnv prs
503 add env (L _ n,p) = extendNameEnv_Acc (:) singleton env n p
505 -- ar_env maps a local to the arity of its definition
506 ar_env :: NameEnv Arity
507 ar_env = foldrBag lhsBindArity emptyNameEnv binds
509 lhsBindArity :: LHsBind Name -> NameEnv Arity -> NameEnv Arity
510 lhsBindArity (L _ (FunBind { fun_id = id, fun_matches = ms })) env
511 = extendNameEnv env (unLoc id) (matchGroupArity ms)
512 lhsBindArity _ env = env -- PatBind/VarBind
515 tcSpecPrags :: Id -> [LSig Name]
517 -- Add INLINE and SPECIALSE pragmas
518 -- INLINE prags are added to the (polymorphic) Id directly
519 -- SPECIALISE prags are passed to the desugarer via TcSpecPrags
520 -- Pre-condition: the poly_id is zonked
521 -- Reason: required by tcSubExp
522 tcSpecPrags poly_id prag_sigs
523 = do { unless (null bad_sigs) warn_discarded_sigs
524 ; mapAndRecoverM (wrapLocM (tcSpec poly_id)) spec_sigs }
526 spec_sigs = filter isSpecLSig prag_sigs
527 bad_sigs = filter is_bad_sig prag_sigs
528 is_bad_sig s = not (isSpecLSig s || isInlineLSig s)
530 warn_discarded_sigs = warnPrags poly_id bad_sigs $
531 ptext (sLit "Discarding unexpected pragmas for")
535 tcSpec :: TcId -> Sig Name -> TcM TcSpecPrag
536 tcSpec poly_id prag@(SpecSig _ hs_ty inl)
537 -- The Name in the SpecSig may not be the same as that of the poly_id
538 -- Example: SPECIALISE for a class method: the Name in the SpecSig is
539 -- for the selector Id, but the poly_id is something like $cop
540 = addErrCtxt (spec_ctxt prag) $
541 do { spec_ty <- tcHsSigType sig_ctxt hs_ty
542 ; checkTc (isOverloadedTy poly_ty)
543 (ptext (sLit "Discarding pragma for non-overloaded function") <+> quotes (ppr poly_id))
544 ; wrap <- tcSubType origin skol_info (idType poly_id) spec_ty
545 ; return (SpecPrag poly_id wrap inl) }
547 name = idName poly_id
548 poly_ty = idType poly_id
549 origin = SpecPragOrigin name
550 sig_ctxt = FunSigCtxt name
551 skol_info = SigSkol sig_ctxt
552 spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag)
554 tcSpec _ prag = pprPanic "tcSpec" (ppr prag)
557 tcImpPrags :: [LSig Name] -> TcM [LTcSpecPrag]
559 = do { this_mod <- getModule
561 = case sigName prag of
563 Just name -> not (nameIsLocalOrFrom this_mod name)
564 (spec_prags, others) = partition isSpecLSig $
566 ; mapM_ misplacedSigErr others
567 -- Messy that this misplaced-sig error comes here
568 -- but the others come from the renamer
569 ; mapAndRecoverM (wrapLocM tcImpSpec) spec_prags }
571 tcImpSpec :: Sig Name -> TcM TcSpecPrag
572 tcImpSpec prag@(SpecSig (L _ name) _ _)
573 = do { id <- tcLookupId name
574 ; checkTc (isInlinePragma (idInlinePragma id))
577 tcImpSpec p = pprPanic "tcImpSpec" (ppr p)
579 impSpecErr :: Name -> SDoc
581 = hang (ptext (sLit "You cannot SPECIALISE") <+> quotes (ppr name))
582 2 (ptext (sLit "because its definition has no INLINE/INLINABLE pragma"))
585 -- If typechecking the binds fails, then return with each
586 -- signature-less binder given type (forall a.a), to minimise
587 -- subsequent error messages
588 recoveryCode :: [Name] -> SigFun -> TcM (LHsBinds TcId, [Id])
589 recoveryCode binder_names sig_fn
590 = do { traceTc "tcBindsWithSigs: error recovery" (ppr binder_names)
591 ; poly_ids <- mapM mk_dummy binder_names
592 ; return (emptyBag, poly_ids) }
595 | isJust (sig_fn name) = tcLookupId name -- Had signature; look it up
596 | otherwise = return (mkLocalId name forall_a_a) -- No signature
599 forall_a_a = mkForAllTy openAlphaTyVar (mkTyVarTy openAlphaTyVar)
603 %************************************************************************
605 \subsection{tcMonoBind}
607 %************************************************************************
609 @tcMonoBinds@ deals with a perhaps-recursive group of HsBinds.
610 The signatures have been dealt with already.
613 tcMonoBinds :: TcSigFun -> LetBndrSpec
614 -> RecFlag -- Whether the binding is recursive for typechecking purposes
615 -- i.e. the binders are mentioned in their RHSs, and
616 -- we are not resuced by a type signature
618 -> TcM (LHsBinds TcId, [MonoBindInfo])
620 tcMonoBinds sig_fn no_gen is_rec
621 [ L b_loc (FunBind { fun_id = L nm_loc name, fun_infix = inf,
622 fun_matches = matches, bind_fvs = fvs })]
623 -- Single function binding,
624 | NonRecursive <- is_rec -- ...binder isn't mentioned in RHS
625 , Nothing <- sig_fn name -- ...with no type signature
626 = -- In this very special case we infer the type of the
627 -- right hand side first (it may have a higher-rank type)
628 -- and *then* make the monomorphic Id for the LHS
629 -- e.g. f = \(x::forall a. a->a) -> <body>
630 -- We want to infer a higher-rank type for f
632 do { ((co_fn, matches'), rhs_ty) <- tcInfer (tcMatchesFun name inf matches)
634 ; mono_id <- newNoSigLetBndr no_gen name rhs_ty
635 ; return (unitBag (L b_loc (FunBind { fun_id = L nm_loc mono_id, fun_infix = inf,
636 fun_matches = matches', bind_fvs = fvs,
637 fun_co_fn = co_fn, fun_tick = Nothing })),
638 [(name, Nothing, mono_id)]) }
640 tcMonoBinds sig_fn no_gen _ binds
641 = do { tc_binds <- mapM (wrapLocM (tcLhs sig_fn no_gen)) binds
643 -- Bring the monomorphic Ids, into scope for the RHSs
644 ; let mono_info = getMonoBindInfo tc_binds
645 rhs_id_env = [(name,mono_id) | (name, Nothing, mono_id) <- mono_info]
646 -- A monomorphic binding for each term variable that lacks
647 -- a type sig. (Ones with a sig are already in scope.)
649 ; binds' <- tcExtendIdEnv2 rhs_id_env $ do
650 traceTc "tcMonoBinds" $ vcat [ ppr n <+> ppr id <+> ppr (idType id)
651 | (n,id) <- rhs_id_env]
652 mapM (wrapLocM tcRhs) tc_binds
653 ; return (listToBag binds', mono_info) }
655 ------------------------
656 -- tcLhs typechecks the LHS of the bindings, to construct the environment in which
657 -- we typecheck the RHSs. Basically what we are doing is this: for each binder:
658 -- if there's a signature for it, use the instantiated signature type
659 -- otherwise invent a type variable
660 -- You see that quite directly in the FunBind case.
662 -- But there's a complication for pattern bindings:
663 -- data T = MkT (forall a. a->a)
665 -- Here we can guess a type variable for the entire LHS (which will be refined to T)
666 -- but we want to get (f::forall a. a->a) as the RHS environment.
667 -- The simplest way to do this is to typecheck the pattern, and then look up the
668 -- bound mono-ids. Then we want to retain the typechecked pattern to avoid re-doing
669 -- it; hence the TcMonoBind data type in which the LHS is done but the RHS isn't
671 data TcMonoBind -- Half completed; LHS done, RHS not done
672 = TcFunBind MonoBindInfo SrcSpan Bool (MatchGroup Name)
673 | TcPatBind [MonoBindInfo] (LPat TcId) (GRHSs Name) TcSigmaType
675 type MonoBindInfo = (Name, Maybe TcSigInfo, TcId)
676 -- Type signature (if any), and
677 -- the monomorphic bound things
679 getMonoType :: MonoBindInfo -> TcTauType
680 getMonoType (_,_,mono_id) = idType mono_id
682 tcLhs :: TcSigFun -> LetBndrSpec -> HsBind Name -> TcM TcMonoBind
683 tcLhs sig_fn no_gen (FunBind { fun_id = L nm_loc name, fun_infix = inf, fun_matches = matches })
684 | Just sig <- sig_fn name
685 = do { mono_id <- newSigLetBndr no_gen name sig
686 ; return (TcFunBind (name, Just sig, mono_id) nm_loc inf matches) }
688 = do { mono_ty <- newFlexiTyVarTy argTypeKind
689 ; mono_id <- newNoSigLetBndr no_gen name mono_ty
690 ; return (TcFunBind (name, Nothing, mono_id) nm_loc inf matches) }
692 tcLhs sig_fn no_gen (PatBind { pat_lhs = pat, pat_rhs = grhss })
693 = do { let tc_pat exp_ty = tcLetPat sig_fn no_gen pat exp_ty $
694 mapM lookup_info (collectPatBinders pat)
696 -- After typechecking the pattern, look up the binder
697 -- names, which the pattern has brought into scope.
698 lookup_info :: Name -> TcM MonoBindInfo
699 lookup_info name = do { mono_id <- tcLookupId name
700 ; return (name, sig_fn name, mono_id) }
702 ; ((pat', infos), pat_ty) <- addErrCtxt (patMonoBindsCtxt pat grhss) $
705 ; return (TcPatBind infos pat' grhss pat_ty) }
707 tcLhs _ _ other_bind = pprPanic "tcLhs" (ppr other_bind)
708 -- AbsBind, VarBind impossible
711 tcRhs :: TcMonoBind -> TcM (HsBind TcId)
712 -- When we are doing pattern bindings, or multiple function bindings at a time
713 -- we *don't* bring any scoped type variables into scope
714 -- Wny not? They are not completely rigid.
715 -- That's why we have the special case for a single FunBind in tcMonoBinds
716 tcRhs (TcFunBind (_,_,mono_id) loc inf matches)
717 = do { (co_fn, matches') <- tcMatchesFun (idName mono_id) inf
718 matches (idType mono_id)
719 ; return (FunBind { fun_id = L loc mono_id, fun_infix = inf
720 , fun_matches = matches'
722 , bind_fvs = placeHolderNames, fun_tick = Nothing }) }
724 tcRhs (TcPatBind _ pat' grhss pat_ty)
725 = do { grhss' <- addErrCtxt (patMonoBindsCtxt pat' grhss) $
726 tcGRHSsPat grhss pat_ty
727 ; return (PatBind { pat_lhs = pat', pat_rhs = grhss', pat_rhs_ty = pat_ty
728 , bind_fvs = placeHolderNames }) }
731 ---------------------
732 getMonoBindInfo :: [Located TcMonoBind] -> [MonoBindInfo]
733 getMonoBindInfo tc_binds
734 = foldr (get_info . unLoc) [] tc_binds
736 get_info (TcFunBind info _ _ _) rest = info : rest
737 get_info (TcPatBind infos _ _ _) rest = infos ++ rest
741 %************************************************************************
745 %************************************************************************
747 unifyCtxts checks that all the signature contexts are the same
748 The type signatures on a mutually-recursive group of definitions
749 must all have the same context (or none).
751 The trick here is that all the signatures should have the same
752 context, and we want to share type variables for that context, so that
753 all the right hand sides agree a common vocabulary for their type
756 We unify them because, with polymorphic recursion, their types
757 might not otherwise be related. This is a rather subtle issue.
760 unifyCtxts :: [TcSigInfo] -> TcM ()
761 -- Post-condition: the returned Insts are full zonked
762 unifyCtxts [] = return ()
763 unifyCtxts (sig1 : sigs)
764 = do { traceTc "unifyCtxts" (ppr (sig1 : sigs))
765 ; mapM_ unify_ctxt sigs }
767 theta1 = sig_theta sig1
768 unify_ctxt :: TcSigInfo -> TcM ()
769 unify_ctxt sig@(TcSigInfo { sig_theta = theta })
770 = setSrcSpan (sig_loc sig) $
771 addErrCtxt (sigContextsCtxt sig1 sig) $
772 do { cois <- unifyTheta theta1 theta
773 ; -- Check whether all coercions are identity coercions
774 -- That can happen if we have, say
776 -- g :: C (F a) => ...
777 -- where F is a type function and (F a ~ [a])
778 -- Then unification might succeed with a coercion. But it's much
779 -- much simpler to require that such signatures have identical contexts
780 checkTc (all isIdentityCoI cois)
781 (ptext (sLit "Mutually dependent functions have syntactically distinct contexts"))
786 @getTyVarsToGen@ decides what type variables to generalise over.
788 For a "restricted group" -- see the monomorphism restriction
789 for a definition -- we bind no dictionaries, and
790 remove from tyvars_to_gen any constrained type variables
792 *Don't* simplify dicts at this point, because we aren't going
793 to generalise over these dicts. By the time we do simplify them
794 we may well know more. For example (this actually came up)
796 f x = array ... xs where xs = [1,2,3,4,5]
797 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
798 stuff. If we simplify only at the f-binding (not the xs-binding)
799 we'll know that the literals are all Ints, and we can just produce
802 Find all the type variables involved in overloading, the
803 "constrained_tyvars". These are the ones we *aren't* going to
804 generalise. We must be careful about doing this:
806 (a) If we fail to generalise a tyvar which is not actually
807 constrained, then it will never, ever get bound, and lands
808 up printed out in interface files! Notorious example:
809 instance Eq a => Eq (Foo a b) where ..
810 Here, b is not constrained, even though it looks as if it is.
811 Another, more common, example is when there's a Method inst in
812 the LIE, whose type might very well involve non-overloaded
814 [NOTE: Jan 2001: I don't understand the problem here so I'm doing
815 the simple thing instead]
817 (b) On the other hand, we mustn't generalise tyvars which are constrained,
818 because we are going to pass on out the unmodified LIE, with those
819 tyvars in it. They won't be in scope if we've generalised them.
821 So we are careful, and do a complete simplification just to find the
822 constrained tyvars. We don't use any of the results, except to
823 find which tyvars are constrained.
825 Note [Polymorphic recursion]
826 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
827 The game plan for polymorphic recursion in the code above is
829 * Bind any variable for which we have a type signature
830 to an Id with a polymorphic type. Then when type-checking
831 the RHSs we'll make a full polymorphic call.
833 This fine, but if you aren't a bit careful you end up with a horrendous
834 amount of partial application and (worse) a huge space leak. For example:
836 f :: Eq a => [a] -> [a]
839 If we don't take care, after typechecking we get
841 f = /\a -> \d::Eq a -> let f' = f a d
845 Notice the the stupid construction of (f a d), which is of course
846 identical to the function we're executing. In this case, the
847 polymorphic recursion isn't being used (but that's a very common case).
848 This can lead to a massive space leak, from the following top-level defn
854 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
855 f' is another thunk which evaluates to the same thing... and you end
856 up with a chain of identical values all hung onto by the CAF ff.
860 = let f' = f Int dEqInt in \ys. ...f'...
862 = let f' = let f' = f Int dEqInt in \ys. ...f'...
867 NOTE: a bit of arity anaysis would push the (f a d) inside the (\ys...),
868 which would make the space leak go away in this case
870 Solution: when typechecking the RHSs we always have in hand the
871 *monomorphic* Ids for each binding. So we just need to make sure that
872 if (Method f a d) shows up in the constraints emerging from (...f...)
873 we just use the monomorphic Id. We achieve this by adding monomorphic Ids
874 to the "givens" when simplifying constraints. That's what the "lies_avail"
879 f = /\a -> \d::Eq a -> letrec
880 fm = \ys:[a] -> ...fm...
884 %************************************************************************
888 %************************************************************************
890 Type signatures are tricky. See Note [Signature skolems] in TcType
892 @tcSigs@ checks the signatures for validity, and returns a list of
893 {\em freshly-instantiated} signatures. That is, the types are already
894 split up, and have fresh type variables installed. All non-type-signature
895 "RenamedSigs" are ignored.
897 The @TcSigInfo@ contains @TcTypes@ because they are unified with
898 the variable's type, and after that checked to see whether they've
903 The -XScopedTypeVariables flag brings lexically-scoped type variables
904 into scope for any explicitly forall-quantified type variables:
905 f :: forall a. a -> a
907 Then 'a' is in scope inside 'e'.
909 However, we do *not* support this
910 - For pattern bindings e.g
914 - For multiple function bindings, unless Opt_RelaxedPolyRec is on
915 f :: forall a. a -> a
917 g :: forall b. b -> b
919 Reason: we use mutable variables for 'a' and 'b', since they may
920 unify to each other, and that means the scoped type variable would
921 not stand for a completely rigid variable.
923 Currently, we simply make Opt_ScopedTypeVariables imply Opt_RelaxedPolyRec
926 Note [More instantiated than scoped]
927 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
928 There may be more instantiated type variables than lexically-scoped
930 type T a = forall b. b -> (a,b)
932 Here, the signature for f will have one scoped type variable, c,
933 but two instantiated type variables, c' and b'.
935 We assume that the scoped ones are at the *front* of sig_tvs,
936 and remember the names from the original HsForAllTy in the TcSigFun.
938 Note [Signature skolems]
939 ~~~~~~~~~~~~~~~~~~~~~~~~
940 When instantiating a type signature, we do so with either skolems or
941 SigTv meta-type variables depending on the use_skols boolean. This
942 variable is set True when we are typechecking a single function
943 binding; and False for pattern bindings and a group of several
946 Reason: in the latter cases, the "skolems" can be unified together,
947 so they aren't properly rigid in the type-refinement sense.
948 NB: unless we are doing H98, each function with a sig will be done
949 separately, even if it's mutually recursive, so use_skols will be True
952 Note [Only scoped tyvars are in the TyVarEnv]
953 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
954 We are careful to keep only the *lexically scoped* type variables in
955 the type environment. Why? After all, the renamer has ensured
956 that only legal occurrences occur, so we could put all type variables
959 But we want to check that two distinct lexically scoped type variables
960 do not map to the same internal type variable. So we need to know which
961 the lexically-scoped ones are... and at the moment we do that by putting
962 only the lexically scoped ones into the environment.
964 Note [Instantiate sig with fresh variables]
965 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
966 It's vital to instantiate a type signature with fresh variables.
968 type T = forall a. [a] -> [a]
970 f = g where { g :: T; g = <rhs> }
972 We must not use the same 'a' from the defn of T at both places!!
973 (Instantiation is only necessary because of type synonyms. Otherwise,
974 it's all cool; each signature has distinct type variables from the renamer.)
977 type SigFun = Name -> Maybe ([Name], SrcSpan)
978 -- Maps a let-binder to the list of
979 -- type variables brought into scope
980 -- by its type signature, plus location
981 -- Nothing => no type signature
983 mkSigFun :: [LSig Name] -> SigFun
984 -- Search for a particular type signature
985 -- Precondition: the sigs are all type sigs
986 -- Precondition: no duplicates
987 mkSigFun sigs = lookupNameEnv env
989 env = mkNameEnv (mapCatMaybes mk_pair sigs)
990 mk_pair (L loc (TypeSig (L _ name) lhs_ty)) = Just (name, (hsExplicitTvs lhs_ty, loc))
991 mk_pair (L loc (IdSig id)) = Just (idName id, ([], loc))
993 -- The scoped names are the ones explicitly mentioned
994 -- in the HsForAll. (There may be more in sigma_ty, because
995 -- of nested type synonyms. See Note [More instantiated than scoped].)
996 -- See Note [Only scoped tyvars are in the TyVarEnv]
1000 tcTySig :: LSig Name -> TcM TcId
1001 tcTySig (L span (TypeSig (L _ name) ty))
1003 do { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
1004 ; return (mkLocalId name sigma_ty) }
1005 tcTySig (L _ (IdSig id))
1007 tcTySig s = pprPanic "tcTySig" (ppr s)
1010 tcInstSigs :: SigFun -> [Name] -> TcM TcSigFun
1011 tcInstSigs sig_fn bndrs
1012 = do { prs <- mapMaybeM (tcInstSig sig_fn use_skols) bndrs
1013 ; return (lookupNameEnv (mkNameEnv prs)) }
1015 use_skols = isSingleton bndrs -- See Note [Signature skolems]
1017 tcInstSig :: SigFun -> Bool -> Name -> TcM (Maybe (Name, TcSigInfo))
1018 -- For use_skols :: Bool see Note [Signature skolems]
1020 -- We must instantiate with fresh uniques,
1021 -- (see Note [Instantiate sig with fresh variables])
1022 -- although we keep the same print-name.
1024 tcInstSig sig_fn use_skols name
1025 | Just (scoped_tvs, loc) <- sig_fn name
1026 = do { poly_id <- tcLookupId name -- Cannot fail; the poly ids are put into
1027 -- scope when starting the binding group
1028 ; (tvs, theta, tau) <- tcInstSigType use_skols name (idType poly_id)
1029 ; let sig = TcSigInfo { sig_id = poly_id
1030 , sig_scoped = scoped_tvs
1031 , sig_tvs = tvs, sig_theta = theta, sig_tau = tau
1033 ; return (Just (name, sig)) }
1037 -------------------------------
1038 data GeneralisationPlan
1039 = NoGen -- No generalisation, no AbsBinds
1040 | InferGen Bool -- Implicit generalisation; there is an AbsBinds
1041 -- True <=> apply the MR; generalise only unconstrained type vars
1042 | CheckGen TcSigInfo -- Explicit generalisation; there is an AbsBinds
1044 -- A consequence of the no-AbsBinds choice (NoGen) is that there is
1045 -- no "polymorphic Id" and "monmomorphic Id"; there is just the one
1047 instance Outputable GeneralisationPlan where
1048 ppr NoGen = ptext (sLit "NoGen")
1049 ppr (InferGen b) = ptext (sLit "InferGen") <+> ppr b
1050 ppr (CheckGen s) = ptext (sLit "CheckGen") <+> ppr s
1052 decideGeneralisationPlan
1053 :: DynFlags -> TopLevelFlag -> [Name] -> [LHsBind Name] -> TcSigFun -> GeneralisationPlan
1054 decideGeneralisationPlan dflags top_lvl _bndrs binds sig_fn
1055 | mono_pat_binds = NoGen
1056 | Just sig <- one_funbind_with_sig binds = if null (sig_tvs sig) && null (sig_theta sig)
1057 then NoGen -- Optimise common case
1059 | (xopt Opt_MonoLocalBinds dflags
1060 && isNotTopLevel top_lvl) = NoGen
1061 | otherwise = InferGen mono_restriction
1064 mono_pat_binds = xopt Opt_MonoPatBinds dflags
1065 && any (is_pat_bind . unLoc) binds
1067 mono_restriction = xopt Opt_MonomorphismRestriction dflags
1068 && any (restricted . unLoc) binds
1070 no_sig n = isNothing (sig_fn n)
1072 -- With OutsideIn, all nested bindings are monomorphic
1073 -- except a single function binding with a signature
1074 one_funbind_with_sig [L _ FunBind { fun_id = v }] = sig_fn (unLoc v)
1075 one_funbind_with_sig _ = Nothing
1077 -- The Haskell 98 monomorphism resetriction
1078 restricted (PatBind {}) = True
1079 restricted (VarBind { var_id = v }) = no_sig v
1080 restricted (FunBind { fun_id = v, fun_matches = m }) = restricted_match m
1082 restricted (AbsBinds {}) = panic "isRestrictedGroup/unrestricted AbsBinds"
1084 restricted_match (MatchGroup (L _ (Match [] _ _) : _) _) = True
1085 restricted_match _ = False
1086 -- No args => like a pattern binding
1087 -- Some args => a function binding
1089 is_pat_bind (PatBind {}) = True
1090 is_pat_bind _ = False
1093 checkStrictBinds :: TopLevelFlag -> RecFlag
1094 -> [LHsBind Name] -> [Id]
1096 -- Check that non-overloaded unlifted bindings are
1097 -- a) non-recursive,
1098 -- b) not top level,
1099 -- c) not a multiple-binding group (more or less implied by (a))
1101 checkStrictBinds top_lvl rec_group binds poly_ids
1102 | unlifted || bang_pat
1103 = do { checkTc (isNotTopLevel top_lvl)
1104 (strictBindErr "Top-level" unlifted binds)
1105 ; checkTc (isNonRec rec_group)
1106 (strictBindErr "Recursive" unlifted binds)
1107 ; checkTc (isSingleton binds)
1108 (strictBindErr "Multiple" unlifted binds)
1109 -- This should be a checkTc, not a warnTc, but as of GHC 6.11
1110 -- the versions of alex and happy available have non-conforming
1111 -- templates, so the GHC build fails if it's an error:
1112 ; warnUnlifted <- doptM Opt_WarnLazyUnliftedBindings
1113 ; warnTc (warnUnlifted && not bang_pat)
1114 (unliftedMustBeBang binds) }
1118 unlifted = any is_unlifted poly_ids
1119 bang_pat = any (isBangHsBind . unLoc) binds
1120 is_unlifted id = case tcSplitForAllTys (idType id) of
1121 (_, rho) -> isUnLiftedType rho
1123 unliftedMustBeBang :: [LHsBind Name] -> SDoc
1124 unliftedMustBeBang binds
1125 = hang (text "Bindings containing unlifted types should use an outermost bang pattern:")
1126 2 (pprBindList binds)
1128 strictBindErr :: String -> Bool -> [LHsBind Name] -> SDoc
1129 strictBindErr flavour unlifted binds
1130 = hang (text flavour <+> msg <+> ptext (sLit "aren't allowed:"))
1131 2 (pprBindList binds)
1133 msg | unlifted = ptext (sLit "bindings for unlifted types")
1134 | otherwise = ptext (sLit "bang-pattern bindings")
1136 pprBindList :: [LHsBind Name] -> SDoc
1137 pprBindList binds = vcat (map ppr binds)
1141 %************************************************************************
1143 \subsection[TcBinds-errors]{Error contexts and messages}
1145 %************************************************************************
1149 -- This one is called on LHS, when pat and grhss are both Name
1150 -- and on RHS, when pat is TcId and grhss is still Name
1151 patMonoBindsCtxt :: OutputableBndr id => LPat id -> GRHSs Name -> SDoc
1152 patMonoBindsCtxt pat grhss
1153 = hang (ptext (sLit "In a pattern binding:")) 2 (pprPatBind pat grhss)
1155 -----------------------------------------------
1156 sigContextsCtxt :: TcSigInfo -> TcSigInfo -> SDoc
1157 sigContextsCtxt sig1 sig2
1158 = vcat [ptext (sLit "When matching the contexts of the signatures for"),
1159 nest 2 (vcat [ppr id1 <+> dcolon <+> ppr (idType id1),
1160 ppr id2 <+> dcolon <+> ppr (idType id2)]),
1161 ptext (sLit "The signature contexts in a mutually recursive group should all be identical")]