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, tcVectDecls, 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
134 -- If the binding binds ?x = E, we must now
135 -- discharge any ?x constraints in expr_lie
136 -- See Note [Implicit parameter untouchables]
137 ; (ev_binds, result) <- checkConstraints (IPSkol ips)
138 [] given_ips thing_inside
140 ; return (HsIPBinds (IPBinds ip_binds' ev_binds), result) }
142 ips = [ip | L _ (IPBind ip _) <- ip_binds]
144 -- I wonder if we should do these one at at time
147 tc_ip_bind (IPBind ip expr)
148 = do { ty <- newFlexiTyVarTy argTypeKind
149 ; ip_id <- newIP ip ty
150 ; expr' <- tcMonoExpr expr ty
151 ; return (ip_id, (IPBind (IPName ip_id) expr')) }
154 Note [Implicit parameter untouchables]
155 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
156 We add the type variables in the types of the implicit parameters
157 as untouchables, not so much because we really must not unify them,
158 but rather because we otherwise end up with constraints like this
159 Num alpha, Implic { wanted = alpha ~ Int }
160 The constraint solver solves alpha~Int by unification, but then
161 doesn't float that solved constraint out (it's not an unsolved
162 wanted. Result disaster: the (Num alpha) is again solved, this
163 time by defaulting. No no no.
165 However [Oct 10] this is all handled automatically by the
166 untouchable-range idea.
169 tcValBinds :: TopLevelFlag
170 -> HsValBinds Name -> TcM thing
171 -> TcM (HsValBinds TcId, thing)
173 tcValBinds _ (ValBindsIn binds _) _
174 = pprPanic "tcValBinds" (ppr binds)
176 tcValBinds top_lvl (ValBindsOut binds sigs) thing_inside
177 = do { -- Typecheck the signature
178 ; let { prag_fn = mkPragFun sigs (foldr (unionBags . snd) emptyBag binds)
179 ; ty_sigs = filter isTypeLSig sigs
180 ; sig_fn = mkSigFun ty_sigs }
182 ; poly_ids <- checkNoErrs (mapAndRecoverM tcTySig ty_sigs)
183 -- No recovery from bad signatures, because the type sigs
184 -- may bind type variables, so proceeding without them
185 -- can lead to a cascade of errors
186 -- ToDo: this means we fall over immediately if any type sig
187 -- is wrong, which is over-conservative, see Trac bug #745
189 -- Extend the envt right away with all
190 -- the Ids declared with type signatures
191 ; (binds', thing) <- tcExtendIdEnv poly_ids $
192 tcBindGroups top_lvl sig_fn prag_fn
195 ; return (ValBindsOut binds' sigs, thing) }
197 ------------------------
198 tcBindGroups :: TopLevelFlag -> SigFun -> PragFun
199 -> [(RecFlag, LHsBinds Name)] -> TcM thing
200 -> TcM ([(RecFlag, LHsBinds TcId)], thing)
201 -- Typecheck a whole lot of value bindings,
202 -- one strongly-connected component at a time
203 -- Here a "strongly connected component" has the strightforward
204 -- meaning of a group of bindings that mention each other,
205 -- ignoring type signatures (that part comes later)
207 tcBindGroups _ _ _ [] thing_inside
208 = do { thing <- thing_inside
209 ; return ([], thing) }
211 tcBindGroups top_lvl sig_fn prag_fn (group : groups) thing_inside
212 = do { (group', (groups', thing))
213 <- tc_group top_lvl sig_fn prag_fn group $
214 tcBindGroups top_lvl sig_fn prag_fn groups thing_inside
215 ; return (group' ++ groups', thing) }
217 ------------------------
218 tc_group :: forall thing.
219 TopLevelFlag -> SigFun -> PragFun
220 -> (RecFlag, LHsBinds Name) -> TcM thing
221 -> TcM ([(RecFlag, LHsBinds TcId)], thing)
223 -- Typecheck one strongly-connected component of the original program.
224 -- We get a list of groups back, because there may
225 -- be specialisations etc as well
227 tc_group top_lvl sig_fn prag_fn (NonRecursive, binds) thing_inside
228 -- A single non-recursive binding
229 -- We want to keep non-recursive things non-recursive
230 -- so that we desugar unlifted bindings correctly
231 = do { (binds1, ids) <- tcPolyBinds top_lvl sig_fn prag_fn NonRecursive NonRecursive
233 ; thing <- tcExtendIdEnv ids thing_inside
234 ; return ( [(NonRecursive, binds1)], thing) }
236 tc_group top_lvl sig_fn prag_fn (Recursive, binds) thing_inside
237 = -- To maximise polymorphism (assumes -XRelaxedPolyRec), we do a new
238 -- strongly-connected-component analysis, this time omitting
239 -- any references to variables with type signatures.
240 do { traceTc "tc_group rec" (pprLHsBinds binds)
241 ; (binds1, _ids, thing) <- go sccs
242 -- Here is where we should do bindInstsOfLocalFuns
243 -- if we start having Methods again
244 ; return ([(Recursive, binds1)], thing) }
245 -- Rec them all together
247 sccs :: [SCC (LHsBind Name)]
248 sccs = stronglyConnCompFromEdgedVertices (mkEdges sig_fn binds)
250 go :: [SCC (LHsBind Name)] -> TcM (LHsBinds TcId, [TcId], thing)
251 go (scc:sccs) = do { (binds1, ids1) <- tc_scc scc
252 ; (binds2, ids2, thing) <- tcExtendIdEnv ids1 $ go sccs
253 ; return (binds1 `unionBags` binds2, ids1 ++ ids2, thing) }
254 go [] = do { thing <- thing_inside; return (emptyBag, [], thing) }
256 tc_scc (AcyclicSCC bind) = tc_sub_group NonRecursive [bind]
257 tc_scc (CyclicSCC binds) = tc_sub_group Recursive binds
259 tc_sub_group = tcPolyBinds top_lvl sig_fn prag_fn Recursive
262 ------------------------
264 bindLocalInsts :: TopLevelFlag
265 -> TcM (LHsBinds TcId, [TcId], a)
266 -> TcM (LHsBinds TcId, TcEvBinds, a)
267 bindLocalInsts top_lvl thing_inside
269 = do { (binds, _, thing) <- thing_inside; return (binds, emptyBag, thing) }
270 -- For the top level don't bother with all this bindInstsOfLocalFuns stuff.
271 -- All the top level things are rec'd together anyway, so it's fine to
272 -- leave them to the tcSimplifyTop, and quite a bit faster too
274 | otherwise -- Nested case
275 = do { ((binds, ids, thing), lie) <- captureConstraints thing_inside
276 ; lie_binds <- bindLocalMethods lie ids
277 ; return (binds, lie_binds, thing) }
280 ------------------------
281 mkEdges :: SigFun -> LHsBinds Name
282 -> [(LHsBind Name, BKey, [BKey])]
284 type BKey = Int -- Just number off the bindings
287 = [ (bind, key, [key | n <- nameSetToList (bind_fvs (unLoc bind)),
288 Just key <- [lookupNameEnv key_map n], no_sig n ])
289 | (bind, key) <- keyd_binds
292 no_sig :: Name -> Bool
293 no_sig n = isNothing (sig_fn n)
295 keyd_binds = bagToList binds `zip` [0::BKey ..]
297 key_map :: NameEnv BKey -- Which binding it comes from
298 key_map = mkNameEnv [(bndr, key) | (L _ bind, key) <- keyd_binds
299 , bndr <- bindersOfHsBind bind ]
301 bindersOfHsBind :: HsBind Name -> [Name]
302 bindersOfHsBind (PatBind { pat_lhs = pat }) = collectPatBinders pat
303 bindersOfHsBind (FunBind { fun_id = L _ f }) = [f]
304 bindersOfHsBind (AbsBinds {}) = panic "bindersOfHsBind AbsBinds"
305 bindersOfHsBind (VarBind {}) = panic "bindersOfHsBind VarBind"
307 ------------------------
308 tcPolyBinds :: TopLevelFlag -> SigFun -> PragFun
309 -> RecFlag -- Whether the group is really recursive
310 -> RecFlag -- Whether it's recursive after breaking
311 -- dependencies based on type signatures
313 -> TcM (LHsBinds TcId, [TcId])
315 -- Typechecks a single bunch of bindings all together,
316 -- and generalises them. The bunch may be only part of a recursive
317 -- group, because we use type signatures to maximise polymorphism
319 -- Returns a list because the input may be a single non-recursive binding,
320 -- in which case the dependency order of the resulting bindings is
323 -- Knows nothing about the scope of the bindings
325 tcPolyBinds top_lvl sig_fn prag_fn rec_group rec_tc bind_list
327 recoverM (recoveryCode binder_names sig_fn) $ do
328 -- Set up main recover; take advantage of any type sigs
330 { traceTc "------------------------------------------------" empty
331 ; traceTc "Bindings for" (ppr binder_names)
333 -- Instantiate the polytypes of any binders that have signatures
334 -- (as determined by sig_fn), returning a TcSigInfo for each
335 ; tc_sig_fn <- tcInstSigs sig_fn binder_names
338 ; let plan = decideGeneralisationPlan dflags top_lvl binder_names bind_list tc_sig_fn
339 ; traceTc "Generalisation plan" (ppr plan)
340 ; (binds, poly_ids) <- case plan of
341 NoGen -> tcPolyNoGen tc_sig_fn prag_fn rec_tc bind_list
342 InferGen mono -> tcPolyInfer top_lvl mono tc_sig_fn prag_fn rec_tc bind_list
343 CheckGen sig -> tcPolyCheck sig prag_fn rec_tc bind_list
345 -- Check whether strict bindings are ok
346 -- These must be non-recursive etc, and are not generalised
347 -- They desugar to a case expression in the end
348 ; checkStrictBinds top_lvl rec_group bind_list poly_ids
350 ; return (binds, poly_ids) }
352 binder_names = collectHsBindListBinders bind_list
353 loc = getLoc (head bind_list)
354 -- TODO: location a bit awkward, but the mbinds have been
355 -- dependency analysed and may no longer be adjacent
359 :: TcSigFun -> PragFun
360 -> RecFlag -- Whether it's recursive after breaking
361 -- dependencies based on type signatures
363 -> TcM (LHsBinds TcId, [TcId])
364 -- No generalisation whatsoever
366 tcPolyNoGen tc_sig_fn prag_fn rec_tc bind_list
367 = do { (binds', mono_infos) <- tcMonoBinds tc_sig_fn (LetGblBndr prag_fn)
369 ; mono_ids' <- mapM tc_mono_info mono_infos
370 ; return (binds', mono_ids') }
372 tc_mono_info (name, _, mono_id)
373 = do { mono_ty' <- zonkTcTypeCarefully (idType mono_id)
374 -- Zonk, mainly to expose unboxed types to checkStrictBinds
375 ; let mono_id' = setIdType mono_id mono_ty'
376 ; _specs <- tcSpecPrags mono_id' (prag_fn name)
378 -- NB: tcPrags generates error messages for
379 -- specialisation pragmas for non-overloaded sigs
380 -- Indeed that is why we call it here!
381 -- So we can safely ignore _specs
384 tcPolyCheck :: TcSigInfo -> PragFun
385 -> RecFlag -- Whether it's recursive after breaking
386 -- dependencies based on type signatures
388 -> TcM (LHsBinds TcId, [TcId])
389 -- There is just one binding,
390 -- it binds a single variable,
391 -- it has a signature,
392 tcPolyCheck sig@(TcSigInfo { sig_id = id, sig_tvs = tvs, sig_scoped = scoped
393 , sig_theta = theta, sig_tau = tau, sig_loc = loc })
394 prag_fn rec_tc bind_list
395 = do { ev_vars <- newEvVars theta
396 ; let skol_info = SigSkol (FunSigCtxt (idName id)) (mkPhiTy theta tau)
397 ; (ev_binds, (binds', [mono_info]))
398 <- checkConstraints skol_info tvs ev_vars $
399 tcExtendTyVarEnv2 (scoped `zip` mkTyVarTys tvs) $
400 tcMonoBinds (\_ -> Just sig) LetLclBndr rec_tc bind_list
402 ; export <- mkExport prag_fn tvs theta mono_info
404 ; let (_, poly_id, _, _) = export
405 abs_bind = L loc $ AbsBinds
407 , abs_ev_vars = ev_vars, abs_ev_binds = ev_binds
408 , abs_exports = [export], abs_binds = binds' }
409 ; return (unitBag abs_bind, [poly_id]) }
414 -> Bool -- True <=> apply the monomorphism restriction
415 -> TcSigFun -> PragFun
416 -> RecFlag -- Whether it's recursive after breaking
417 -- dependencies based on type signatures
419 -> TcM (LHsBinds TcId, [TcId])
420 tcPolyInfer top_lvl mono tc_sig_fn prag_fn rec_tc bind_list
421 = do { ((binds', mono_infos), wanted)
422 <- captureConstraints $
423 tcMonoBinds tc_sig_fn LetLclBndr rec_tc bind_list
425 ; unifyCtxts [sig | (_, Just sig, _) <- mono_infos]
427 ; let name_taus = [(name, idType mono_id) | (name, _, mono_id) <- mono_infos]
428 ; (qtvs, givens, ev_binds) <- simplifyInfer top_lvl mono name_taus wanted
430 ; exports <- mapM (mkExport prag_fn qtvs (map evVarPred givens))
433 ; let poly_ids = [poly_id | (_, poly_id, _, _) <- exports]
434 ; traceTc "Binding:" (ppr (poly_ids `zip` map idType poly_ids))
437 ; let abs_bind = L loc $ AbsBinds { abs_tvs = qtvs
438 , abs_ev_vars = givens, abs_ev_binds = ev_binds
439 , abs_exports = exports, abs_binds = binds' }
441 ; return (unitBag abs_bind, poly_ids) -- poly_ids are guaranteed zonked by mkExport
446 mkExport :: PragFun -> [TyVar] -> TcThetaType
448 -> TcM ([TyVar], Id, Id, TcSpecPrags)
449 -- mkExport generates exports with
450 -- zonked type variables,
452 -- The former is just because no further unifications will change
453 -- the quantified type variables, so we can fix their final form
455 -- The latter is needed because the poly_ids are used to extend the
456 -- type environment; see the invariant on TcEnv.tcExtendIdEnv
458 -- Pre-condition: the inferred_tvs are already zonked
460 mkExport prag_fn inferred_tvs theta
461 (poly_name, mb_sig, mono_id)
462 = do { (tvs, poly_id) <- mk_poly_id mb_sig
463 -- poly_id has a zonked type
465 ; poly_id' <- addInlinePrags poly_id prag_sigs
467 ; spec_prags <- tcSpecPrags poly_id prag_sigs
468 -- tcPrags requires a zonked poly_id
470 ; return (tvs, poly_id', mono_id, SpecPrags spec_prags) }
472 prag_sigs = prag_fn poly_name
473 poly_ty = mkSigmaTy inferred_tvs theta (idType mono_id)
475 mk_poly_id Nothing = do { poly_ty' <- zonkTcTypeCarefully poly_ty
476 ; return (inferred_tvs, mkLocalId poly_name poly_ty') }
477 mk_poly_id (Just sig) = do { tvs <- mapM zonk_tv (sig_tvs sig)
478 ; return (tvs, sig_id sig) }
480 zonk_tv tv = do { ty <- zonkTcTyVar tv; return (tcGetTyVar "mkExport" ty) }
482 ------------------------
483 type PragFun = Name -> [LSig Name]
485 mkPragFun :: [LSig Name] -> LHsBinds Name -> PragFun
486 mkPragFun sigs binds = \n -> lookupNameEnv prag_env n `orElse` []
488 prs = mapCatMaybes get_sig sigs
490 get_sig :: LSig Name -> Maybe (Located Name, LSig Name)
491 get_sig (L l (SpecSig nm ty inl)) = Just (nm, L l $ SpecSig nm ty (add_arity nm inl))
492 get_sig (L l (InlineSig nm inl)) = Just (nm, L l $ InlineSig nm (add_arity nm inl))
495 add_arity (L _ n) inl_prag -- Adjust inl_sat field to match visible arity of function
496 | Just ar <- lookupNameEnv ar_env n,
497 Inline <- inl_inline inl_prag = inl_prag { inl_sat = Just ar }
498 -- add arity only for real INLINE pragmas, not INLINABLE
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 ; warnIf (not (isOverloadedTy poly_ty || isInlinePragma inl))
543 (ptext (sLit "SPECIALISE pragma for non-overloaded function") <+> quotes (ppr poly_id))
544 -- Note [SPECIALISE pragmas]
545 ; wrap <- tcSubType origin sig_ctxt (idType poly_id) spec_ty
546 ; return (SpecPrag poly_id wrap inl) }
548 name = idName poly_id
549 poly_ty = idType poly_id
550 origin = SpecPragOrigin name
551 sig_ctxt = FunSigCtxt name
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 (isAnyInlinePragma (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 (vcat [ ptext (sLit "because its definition has no INLINE/INLINABLE pragma")
583 , ptext (sLit "(or you compiled its defining module without -O)")])
586 tcVectDecls :: [LVectDecl Name] -> TcM [LVectDecl TcId]
588 = do { decls' <- mapM (wrapLocM tcVect) decls
589 ; let ids = [unLoc id | L _ (HsVect id _) <- decls']
590 dups = findDupsEq (==) ids
591 ; mapM_ reportVectDups dups
595 reportVectDups (first:_second:_more)
596 = addErrAt (getSrcSpan first) $
597 ptext (sLit "Duplicate vectorisation declarations for") <+> ppr first
598 reportVectDups _ = return ()
601 tcVect :: VectDecl Name -> TcM (VectDecl TcId)
602 -- We can't typecheck the expression of a vectorisation declaration against the vectorised type
603 -- of the original definition as this requires internals of the vectoriser not available during
604 -- type checking. Instead, we infer the type of the expression and leave it to the vectoriser
605 -- to check the compatibility of the Core types.
606 tcVect (HsVect name Nothing)
607 = addErrCtxt (vectCtxt name) $
608 do { id <- wrapLocM tcLookupId name
609 ; return (HsVect id Nothing)
611 tcVect (HsVect name@(L loc _) (Just rhs))
612 = addErrCtxt (vectCtxt name) $
613 do { _id <- wrapLocM tcLookupId name -- need to ensure that the name is already defined
615 -- turn the vectorisation declaration into a single non-recursive binding
616 ; let bind = L loc $ mkFunBind name [mkSimpleMatch [] rhs]
617 sigFun = const Nothing
618 pragFun = mkPragFun [] (unitBag bind)
620 -- perform type inference (including generalisation)
621 ; (binds, [id']) <- tcPolyInfer TopLevel False sigFun pragFun NonRecursive [bind]
623 ; traceTc "tcVect inferred type" $ ppr (varType id')
625 -- add the type variable and dictionary bindings produced by type generalisation to the
626 -- right-hand side of the vectorisation declaration
627 ; let [AbsBinds tvs evs _ evBinds actualBinds] = (map unLoc . bagToList) binds
628 ; let [bind'] = bagToList actualBinds
630 [L _ (Match _ _ (GRHSs [L _ (GRHS _ rhs')] _))]
631 _ = (fun_matches . unLoc) bind'
632 rhsWrapped = mkHsLams tvs evs (mkHsDictLet evBinds rhs')
634 -- We return the type-checked 'Id', to propagate the inferred signature
635 -- to the vectoriser - see "Note [Typechecked vectorisation pragmas]" in HsDecls
636 ; return $ HsVect (L loc id') (Just rhsWrapped)
639 vectCtxt :: Located Name -> SDoc
640 vectCtxt name = ptext (sLit "When checking the vectorisation declaration for") <+> ppr name
643 -- If typechecking the binds fails, then return with each
644 -- signature-less binder given type (forall a.a), to minimise
645 -- subsequent error messages
646 recoveryCode :: [Name] -> SigFun -> TcM (LHsBinds TcId, [Id])
647 recoveryCode binder_names sig_fn
648 = do { traceTc "tcBindsWithSigs: error recovery" (ppr binder_names)
649 ; poly_ids <- mapM mk_dummy binder_names
650 ; return (emptyBag, poly_ids) }
653 | isJust (sig_fn name) = tcLookupId name -- Had signature; look it up
654 | otherwise = return (mkLocalId name forall_a_a) -- No signature
657 forall_a_a = mkForAllTy openAlphaTyVar (mkTyVarTy openAlphaTyVar)
660 Note [SPECIALISE pragmas]
661 ~~~~~~~~~~~~~~~~~~~~~~~~~
662 There is no point in a SPECIALISE pragma for a non-overloaded function:
663 reverse :: [a] -> [a]
664 {-# SPECIALISE reverse :: [Int] -> [Int] #-}
666 But SPECIALISE INLINE *can* make sense for GADTS:
668 ArrInt :: !Int -> ByteArray# -> Arr Int
669 ArrPair :: !Int -> Arr e1 -> Arr e2 -> Arr (e1, e2)
671 (!:) :: Arr e -> Int -> e
672 {-# SPECIALISE INLINE (!:) :: Arr Int -> Int -> Int #-}
673 {-# SPECIALISE INLINE (!:) :: Arr (a, b) -> Int -> (a, b) #-}
674 (ArrInt _ ba) !: (I# i) = I# (indexIntArray# ba i)
675 (ArrPair _ a1 a2) !: i = (a1 !: i, a2 !: i)
677 When (!:) is specialised it becomes non-recursive, and can usefully
678 be inlined. Scary! So we only warn for SPECIALISE *without* INLINE
679 for a non-overloaded function.
681 %************************************************************************
683 \subsection{tcMonoBind}
685 %************************************************************************
687 @tcMonoBinds@ deals with a perhaps-recursive group of HsBinds.
688 The signatures have been dealt with already.
691 tcMonoBinds :: TcSigFun -> LetBndrSpec
692 -> RecFlag -- Whether the binding is recursive for typechecking purposes
693 -- i.e. the binders are mentioned in their RHSs, and
694 -- we are not resuced by a type signature
696 -> TcM (LHsBinds TcId, [MonoBindInfo])
698 tcMonoBinds sig_fn no_gen is_rec
699 [ L b_loc (FunBind { fun_id = L nm_loc name, fun_infix = inf,
700 fun_matches = matches, bind_fvs = fvs })]
701 -- Single function binding,
702 | NonRecursive <- is_rec -- ...binder isn't mentioned in RHS
703 , Nothing <- sig_fn name -- ...with no type signature
704 = -- In this very special case we infer the type of the
705 -- right hand side first (it may have a higher-rank type)
706 -- and *then* make the monomorphic Id for the LHS
707 -- e.g. f = \(x::forall a. a->a) -> <body>
708 -- We want to infer a higher-rank type for f
710 do { ((co_fn, matches'), rhs_ty) <- tcInfer (tcMatchesFun name inf matches)
712 ; mono_id <- newNoSigLetBndr no_gen name rhs_ty
713 ; return (unitBag (L b_loc (FunBind { fun_id = L nm_loc mono_id, fun_infix = inf,
714 fun_matches = matches', bind_fvs = fvs,
715 fun_co_fn = co_fn, fun_tick = Nothing })),
716 [(name, Nothing, mono_id)]) }
718 tcMonoBinds sig_fn no_gen _ binds
719 = do { tc_binds <- mapM (wrapLocM (tcLhs sig_fn no_gen)) binds
721 -- Bring the monomorphic Ids, into scope for the RHSs
722 ; let mono_info = getMonoBindInfo tc_binds
723 rhs_id_env = [(name,mono_id) | (name, Nothing, mono_id) <- mono_info]
724 -- A monomorphic binding for each term variable that lacks
725 -- a type sig. (Ones with a sig are already in scope.)
727 ; binds' <- tcExtendIdEnv2 rhs_id_env $ do
728 traceTc "tcMonoBinds" $ vcat [ ppr n <+> ppr id <+> ppr (idType id)
729 | (n,id) <- rhs_id_env]
730 mapM (wrapLocM tcRhs) tc_binds
731 ; return (listToBag binds', mono_info) }
733 ------------------------
734 -- tcLhs typechecks the LHS of the bindings, to construct the environment in which
735 -- we typecheck the RHSs. Basically what we are doing is this: for each binder:
736 -- if there's a signature for it, use the instantiated signature type
737 -- otherwise invent a type variable
738 -- You see that quite directly in the FunBind case.
740 -- But there's a complication for pattern bindings:
741 -- data T = MkT (forall a. a->a)
743 -- Here we can guess a type variable for the entire LHS (which will be refined to T)
744 -- but we want to get (f::forall a. a->a) as the RHS environment.
745 -- The simplest way to do this is to typecheck the pattern, and then look up the
746 -- bound mono-ids. Then we want to retain the typechecked pattern to avoid re-doing
747 -- it; hence the TcMonoBind data type in which the LHS is done but the RHS isn't
749 data TcMonoBind -- Half completed; LHS done, RHS not done
750 = TcFunBind MonoBindInfo SrcSpan Bool (MatchGroup Name)
751 | TcPatBind [MonoBindInfo] (LPat TcId) (GRHSs Name) TcSigmaType
753 type MonoBindInfo = (Name, Maybe TcSigInfo, TcId)
754 -- Type signature (if any), and
755 -- the monomorphic bound things
757 tcLhs :: TcSigFun -> LetBndrSpec -> HsBind Name -> TcM TcMonoBind
758 tcLhs sig_fn no_gen (FunBind { fun_id = L nm_loc name, fun_infix = inf, fun_matches = matches })
759 | Just sig <- sig_fn name
760 = do { mono_id <- newSigLetBndr no_gen name sig
761 ; return (TcFunBind (name, Just sig, mono_id) nm_loc inf matches) }
763 = do { mono_ty <- newFlexiTyVarTy argTypeKind
764 ; mono_id <- newNoSigLetBndr no_gen name mono_ty
765 ; return (TcFunBind (name, Nothing, mono_id) nm_loc inf matches) }
767 tcLhs sig_fn no_gen (PatBind { pat_lhs = pat, pat_rhs = grhss })
768 = do { let tc_pat exp_ty = tcLetPat sig_fn no_gen pat exp_ty $
769 mapM lookup_info (collectPatBinders pat)
771 -- After typechecking the pattern, look up the binder
772 -- names, which the pattern has brought into scope.
773 lookup_info :: Name -> TcM MonoBindInfo
774 lookup_info name = do { mono_id <- tcLookupId name
775 ; return (name, sig_fn name, mono_id) }
777 ; ((pat', infos), pat_ty) <- addErrCtxt (patMonoBindsCtxt pat grhss) $
780 ; return (TcPatBind infos pat' grhss pat_ty) }
782 tcLhs _ _ other_bind = pprPanic "tcLhs" (ppr other_bind)
783 -- AbsBind, VarBind impossible
786 tcRhs :: TcMonoBind -> TcM (HsBind TcId)
787 -- When we are doing pattern bindings, or multiple function bindings at a time
788 -- we *don't* bring any scoped type variables into scope
789 -- Wny not? They are not completely rigid.
790 -- That's why we have the special case for a single FunBind in tcMonoBinds
791 tcRhs (TcFunBind (_,_,mono_id) loc inf matches)
792 = do { (co_fn, matches') <- tcMatchesFun (idName mono_id) inf
793 matches (idType mono_id)
794 ; return (FunBind { fun_id = L loc mono_id, fun_infix = inf
795 , fun_matches = matches'
797 , bind_fvs = placeHolderNames, fun_tick = Nothing }) }
799 tcRhs (TcPatBind _ pat' grhss pat_ty)
800 = do { grhss' <- addErrCtxt (patMonoBindsCtxt pat' grhss) $
801 tcGRHSsPat grhss pat_ty
802 ; return (PatBind { pat_lhs = pat', pat_rhs = grhss', pat_rhs_ty = pat_ty
803 , bind_fvs = placeHolderNames }) }
806 ---------------------
807 getMonoBindInfo :: [Located TcMonoBind] -> [MonoBindInfo]
808 getMonoBindInfo tc_binds
809 = foldr (get_info . unLoc) [] tc_binds
811 get_info (TcFunBind info _ _ _) rest = info : rest
812 get_info (TcPatBind infos _ _ _) rest = infos ++ rest
816 %************************************************************************
820 %************************************************************************
822 unifyCtxts checks that all the signature contexts are the same
823 The type signatures on a mutually-recursive group of definitions
824 must all have the same context (or none).
826 The trick here is that all the signatures should have the same
827 context, and we want to share type variables for that context, so that
828 all the right hand sides agree a common vocabulary for their type
831 We unify them because, with polymorphic recursion, their types
832 might not otherwise be related. This is a rather subtle issue.
835 unifyCtxts :: [TcSigInfo] -> TcM ()
836 -- Post-condition: the returned Insts are full zonked
837 unifyCtxts [] = return ()
838 unifyCtxts (sig1 : sigs)
839 = do { traceTc "unifyCtxts" (ppr (sig1 : sigs))
840 ; mapM_ unify_ctxt sigs }
842 theta1 = sig_theta sig1
843 unify_ctxt :: TcSigInfo -> TcM ()
844 unify_ctxt sig@(TcSigInfo { sig_theta = theta })
845 = setSrcSpan (sig_loc sig) $
846 addErrCtxt (sigContextsCtxt sig1 sig) $
847 do { cois <- unifyTheta theta1 theta
848 ; -- Check whether all coercions are identity coercions
849 -- That can happen if we have, say
851 -- g :: C (F a) => ...
852 -- where F is a type function and (F a ~ [a])
853 -- Then unification might succeed with a coercion. But it's much
854 -- much simpler to require that such signatures have identical contexts
855 checkTc (all isIdentityCoI cois)
856 (ptext (sLit "Mutually dependent functions have syntactically distinct contexts"))
861 @getTyVarsToGen@ decides what type variables to generalise over.
863 For a "restricted group" -- see the monomorphism restriction
864 for a definition -- we bind no dictionaries, and
865 remove from tyvars_to_gen any constrained type variables
867 *Don't* simplify dicts at this point, because we aren't going
868 to generalise over these dicts. By the time we do simplify them
869 we may well know more. For example (this actually came up)
871 f x = array ... xs where xs = [1,2,3,4,5]
872 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
873 stuff. If we simplify only at the f-binding (not the xs-binding)
874 we'll know that the literals are all Ints, and we can just produce
877 Find all the type variables involved in overloading, the
878 "constrained_tyvars". These are the ones we *aren't* going to
879 generalise. We must be careful about doing this:
881 (a) If we fail to generalise a tyvar which is not actually
882 constrained, then it will never, ever get bound, and lands
883 up printed out in interface files! Notorious example:
884 instance Eq a => Eq (Foo a b) where ..
885 Here, b is not constrained, even though it looks as if it is.
886 Another, more common, example is when there's a Method inst in
887 the LIE, whose type might very well involve non-overloaded
889 [NOTE: Jan 2001: I don't understand the problem here so I'm doing
890 the simple thing instead]
892 (b) On the other hand, we mustn't generalise tyvars which are constrained,
893 because we are going to pass on out the unmodified LIE, with those
894 tyvars in it. They won't be in scope if we've generalised them.
896 So we are careful, and do a complete simplification just to find the
897 constrained tyvars. We don't use any of the results, except to
898 find which tyvars are constrained.
900 Note [Polymorphic recursion]
901 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
902 The game plan for polymorphic recursion in the code above is
904 * Bind any variable for which we have a type signature
905 to an Id with a polymorphic type. Then when type-checking
906 the RHSs we'll make a full polymorphic call.
908 This fine, but if you aren't a bit careful you end up with a horrendous
909 amount of partial application and (worse) a huge space leak. For example:
911 f :: Eq a => [a] -> [a]
914 If we don't take care, after typechecking we get
916 f = /\a -> \d::Eq a -> let f' = f a d
920 Notice the the stupid construction of (f a d), which is of course
921 identical to the function we're executing. In this case, the
922 polymorphic recursion isn't being used (but that's a very common case).
923 This can lead to a massive space leak, from the following top-level defn
929 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
930 f' is another thunk which evaluates to the same thing... and you end
931 up with a chain of identical values all hung onto by the CAF ff.
935 = let f' = f Int dEqInt in \ys. ...f'...
937 = let f' = let f' = f Int dEqInt in \ys. ...f'...
942 NOTE: a bit of arity anaysis would push the (f a d) inside the (\ys...),
943 which would make the space leak go away in this case
945 Solution: when typechecking the RHSs we always have in hand the
946 *monomorphic* Ids for each binding. So we just need to make sure that
947 if (Method f a d) shows up in the constraints emerging from (...f...)
948 we just use the monomorphic Id. We achieve this by adding monomorphic Ids
949 to the "givens" when simplifying constraints. That's what the "lies_avail"
954 f = /\a -> \d::Eq a -> letrec
955 fm = \ys:[a] -> ...fm...
959 %************************************************************************
963 %************************************************************************
965 Type signatures are tricky. See Note [Signature skolems] in TcType
967 @tcSigs@ checks the signatures for validity, and returns a list of
968 {\em freshly-instantiated} signatures. That is, the types are already
969 split up, and have fresh type variables installed. All non-type-signature
970 "RenamedSigs" are ignored.
972 The @TcSigInfo@ contains @TcTypes@ because they are unified with
973 the variable's type, and after that checked to see whether they've
978 The -XScopedTypeVariables flag brings lexically-scoped type variables
979 into scope for any explicitly forall-quantified type variables:
980 f :: forall a. a -> a
982 Then 'a' is in scope inside 'e'.
984 However, we do *not* support this
985 - For pattern bindings e.g
989 - For multiple function bindings, unless Opt_RelaxedPolyRec is on
990 f :: forall a. a -> a
992 g :: forall b. b -> b
994 Reason: we use mutable variables for 'a' and 'b', since they may
995 unify to each other, and that means the scoped type variable would
996 not stand for a completely rigid variable.
998 Currently, we simply make Opt_ScopedTypeVariables imply Opt_RelaxedPolyRec
1001 Note [More instantiated than scoped]
1002 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1003 There may be more instantiated type variables than lexically-scoped
1005 type T a = forall b. b -> (a,b)
1007 Here, the signature for f will have one scoped type variable, c,
1008 but two instantiated type variables, c' and b'.
1010 We assume that the scoped ones are at the *front* of sig_tvs,
1011 and remember the names from the original HsForAllTy in the TcSigFun.
1013 Note [Signature skolems]
1014 ~~~~~~~~~~~~~~~~~~~~~~~~
1015 When instantiating a type signature, we do so with either skolems or
1016 SigTv meta-type variables depending on the use_skols boolean. This
1017 variable is set True when we are typechecking a single function
1018 binding; and False for pattern bindings and a group of several
1021 Reason: in the latter cases, the "skolems" can be unified together,
1022 so they aren't properly rigid in the type-refinement sense.
1023 NB: unless we are doing H98, each function with a sig will be done
1024 separately, even if it's mutually recursive, so use_skols will be True
1027 Note [Only scoped tyvars are in the TyVarEnv]
1028 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1029 We are careful to keep only the *lexically scoped* type variables in
1030 the type environment. Why? After all, the renamer has ensured
1031 that only legal occurrences occur, so we could put all type variables
1034 But we want to check that two distinct lexically scoped type variables
1035 do not map to the same internal type variable. So we need to know which
1036 the lexically-scoped ones are... and at the moment we do that by putting
1037 only the lexically scoped ones into the environment.
1039 Note [Instantiate sig with fresh variables]
1040 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1041 It's vital to instantiate a type signature with fresh variables.
1043 type T = forall a. [a] -> [a]
1045 f = g where { g :: T; g = <rhs> }
1047 We must not use the same 'a' from the defn of T at both places!!
1048 (Instantiation is only necessary because of type synonyms. Otherwise,
1049 it's all cool; each signature has distinct type variables from the renamer.)
1052 type SigFun = Name -> Maybe ([Name], SrcSpan)
1053 -- Maps a let-binder to the list of
1054 -- type variables brought into scope
1055 -- by its type signature, plus location
1056 -- Nothing => no type signature
1058 mkSigFun :: [LSig Name] -> SigFun
1059 -- Search for a particular type signature
1060 -- Precondition: the sigs are all type sigs
1061 -- Precondition: no duplicates
1062 mkSigFun sigs = lookupNameEnv env
1064 env = mkNameEnv (mapCatMaybes mk_pair sigs)
1065 mk_pair (L loc (TypeSig (L _ name) lhs_ty)) = Just (name, (hsExplicitTvs lhs_ty, loc))
1066 mk_pair (L loc (IdSig id)) = Just (idName id, ([], loc))
1068 -- The scoped names are the ones explicitly mentioned
1069 -- in the HsForAll. (There may be more in sigma_ty, because
1070 -- of nested type synonyms. See Note [More instantiated than scoped].)
1071 -- See Note [Only scoped tyvars are in the TyVarEnv]
1075 tcTySig :: LSig Name -> TcM TcId
1076 tcTySig (L span (TypeSig (L _ name) ty))
1078 do { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
1079 ; return (mkLocalId name sigma_ty) }
1080 tcTySig (L _ (IdSig id))
1082 tcTySig s = pprPanic "tcTySig" (ppr s)
1085 tcInstSigs :: SigFun -> [Name] -> TcM TcSigFun
1086 tcInstSigs sig_fn bndrs
1087 = do { prs <- mapMaybeM (tcInstSig sig_fn use_skols) bndrs
1088 ; return (lookupNameEnv (mkNameEnv prs)) }
1090 use_skols = isSingleton bndrs -- See Note [Signature skolems]
1092 tcInstSig :: SigFun -> Bool -> Name -> TcM (Maybe (Name, TcSigInfo))
1093 -- For use_skols :: Bool see Note [Signature skolems]
1095 -- We must instantiate with fresh uniques,
1096 -- (see Note [Instantiate sig with fresh variables])
1097 -- although we keep the same print-name.
1099 tcInstSig sig_fn use_skols name
1100 | Just (scoped_tvs, loc) <- sig_fn name
1101 = do { poly_id <- tcLookupId name -- Cannot fail; the poly ids are put into
1102 -- scope when starting the binding group
1103 ; let poly_ty = idType poly_id
1104 ; (tvs, theta, tau) <- if use_skols
1105 then tcInstType tcInstSkolTyVars poly_ty
1106 else tcInstType tcInstSigTyVars poly_ty
1107 ; let sig = TcSigInfo { sig_id = poly_id
1108 , sig_scoped = scoped_tvs
1109 , sig_tvs = tvs, sig_theta = theta, sig_tau = tau
1111 ; return (Just (name, sig)) }
1115 -------------------------------
1116 data GeneralisationPlan
1117 = NoGen -- No generalisation, no AbsBinds
1118 | InferGen Bool -- Implicit generalisation; there is an AbsBinds
1119 -- True <=> apply the MR; generalise only unconstrained type vars
1120 | CheckGen TcSigInfo -- Explicit generalisation; there is an AbsBinds
1122 -- A consequence of the no-AbsBinds choice (NoGen) is that there is
1123 -- no "polymorphic Id" and "monmomorphic Id"; there is just the one
1125 instance Outputable GeneralisationPlan where
1126 ppr NoGen = ptext (sLit "NoGen")
1127 ppr (InferGen b) = ptext (sLit "InferGen") <+> ppr b
1128 ppr (CheckGen s) = ptext (sLit "CheckGen") <+> ppr s
1130 decideGeneralisationPlan
1131 :: DynFlags -> TopLevelFlag -> [Name] -> [LHsBind Name] -> TcSigFun -> GeneralisationPlan
1132 decideGeneralisationPlan dflags top_lvl _bndrs binds sig_fn
1133 | bang_pat_binds = NoGen
1134 | mono_pat_binds = NoGen
1135 | Just sig <- one_funbind_with_sig binds = if null (sig_tvs sig) && null (sig_theta sig)
1136 then NoGen -- Optimise common case
1138 | (xopt Opt_MonoLocalBinds dflags
1139 && isNotTopLevel top_lvl) = NoGen
1140 | otherwise = InferGen mono_restriction
1143 bang_pat_binds = any (isBangHsBind . unLoc) binds
1144 -- Bang patterns must not be polymorphic,
1145 -- because we are going to force them
1148 mono_pat_binds = xopt Opt_MonoPatBinds dflags
1149 && any (is_pat_bind . unLoc) binds
1151 mono_restriction = xopt Opt_MonomorphismRestriction dflags
1152 && any (restricted . unLoc) binds
1154 no_sig n = isNothing (sig_fn n)
1156 -- With OutsideIn, all nested bindings are monomorphic
1157 -- except a single function binding with a signature
1158 one_funbind_with_sig [L _ FunBind { fun_id = v }] = sig_fn (unLoc v)
1159 one_funbind_with_sig _ = Nothing
1161 -- The Haskell 98 monomorphism resetriction
1162 restricted (PatBind {}) = True
1163 restricted (VarBind { var_id = v }) = no_sig v
1164 restricted (FunBind { fun_id = v, fun_matches = m }) = restricted_match m
1166 restricted (AbsBinds {}) = panic "isRestrictedGroup/unrestricted AbsBinds"
1168 restricted_match (MatchGroup (L _ (Match [] _ _) : _) _) = True
1169 restricted_match _ = False
1170 -- No args => like a pattern binding
1171 -- Some args => a function binding
1173 is_pat_bind (PatBind {}) = True
1174 is_pat_bind _ = False
1177 checkStrictBinds :: TopLevelFlag -> RecFlag
1178 -> [LHsBind Name] -> [Id]
1180 -- Check that non-overloaded unlifted bindings are
1181 -- a) non-recursive,
1182 -- b) not top level,
1183 -- c) not a multiple-binding group (more or less implied by (a))
1185 checkStrictBinds top_lvl rec_group binds poly_ids
1186 | unlifted || bang_pat
1187 = do { checkTc (isNotTopLevel top_lvl)
1188 (strictBindErr "Top-level" unlifted binds)
1189 ; checkTc (isNonRec rec_group)
1190 (strictBindErr "Recursive" unlifted binds)
1191 ; checkTc (isSingleton binds)
1192 (strictBindErr "Multiple" unlifted binds)
1193 -- This should be a checkTc, not a warnTc, but as of GHC 6.11
1194 -- the versions of alex and happy available have non-conforming
1195 -- templates, so the GHC build fails if it's an error:
1196 ; warnUnlifted <- doptM Opt_WarnLazyUnliftedBindings
1197 ; warnTc (warnUnlifted && not bang_pat && lifted_pat)
1198 -- No outer bang, but it's a compound pattern
1199 -- E.g (I# x#) = blah
1200 -- Warn about this, but not about
1203 (unliftedMustBeBang binds) }
1207 unlifted = any is_unlifted poly_ids
1208 bang_pat = any (isBangHsBind . unLoc) binds
1209 lifted_pat = any (isLiftedPatBind . unLoc) binds
1210 is_unlifted id = case tcSplitForAllTys (idType id) of
1211 (_, rho) -> isUnLiftedType rho
1213 unliftedMustBeBang :: [LHsBind Name] -> SDoc
1214 unliftedMustBeBang binds
1215 = hang (text "Pattern bindings containing unlifted types should use an outermost bang pattern:")
1216 2 (pprBindList binds)
1218 strictBindErr :: String -> Bool -> [LHsBind Name] -> SDoc
1219 strictBindErr flavour unlifted binds
1220 = hang (text flavour <+> msg <+> ptext (sLit "aren't allowed:"))
1221 2 (pprBindList binds)
1223 msg | unlifted = ptext (sLit "bindings for unlifted types")
1224 | otherwise = ptext (sLit "bang-pattern bindings")
1226 pprBindList :: [LHsBind Name] -> SDoc
1227 pprBindList binds = vcat (map ppr binds)
1231 %************************************************************************
1233 \subsection[TcBinds-errors]{Error contexts and messages}
1235 %************************************************************************
1239 -- This one is called on LHS, when pat and grhss are both Name
1240 -- and on RHS, when pat is TcId and grhss is still Name
1241 patMonoBindsCtxt :: OutputableBndr id => LPat id -> GRHSs Name -> SDoc
1242 patMonoBindsCtxt pat grhss
1243 = hang (ptext (sLit "In a pattern binding:")) 2 (pprPatBind pat grhss)
1245 -----------------------------------------------
1246 sigContextsCtxt :: TcSigInfo -> TcSigInfo -> SDoc
1247 sigContextsCtxt sig1 sig2
1248 = vcat [ptext (sLit "When matching the contexts of the signatures for"),
1249 nest 2 (vcat [ppr id1 <+> dcolon <+> ppr (idType id1),
1250 ppr id2 <+> dcolon <+> ppr (idType id2)]),
1251 ptext (sLit "The signature contexts in a mutually recursive group should all be identical")]