2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcBinds]{TcBinds}
7 module TcBinds ( tcLocalBinds, tcTopBinds,
8 tcHsBootSigs, tcMonoBinds,
9 TcPragFun, tcSpecPrag, tcPrags, mkPragFun,
10 TcSigInfo(..), TcSigFun, mkTcSigFun,
11 badBootDeclErr ) where
13 #include "HsVersions.h"
15 import {-# SOURCE #-} TcMatches ( tcGRHSsPat, tcMatchesFun )
16 import {-# SOURCE #-} TcExpr ( tcMonoExpr )
18 import DynFlags ( dopt, DynFlags,
19 DynFlag(Opt_MonomorphismRestriction, Opt_MonoPatBinds, Opt_GlasgowExts) )
20 import HsSyn ( HsExpr(..), HsBind(..), LHsBinds, LHsBind, Sig(..),
21 HsLocalBinds(..), HsValBinds(..), HsIPBinds(..),
22 LSig, Match(..), IPBind(..), Prag(..), LHsType,
23 isVanillaLSig, sigName, placeHolderNames, isPragLSig,
24 LPat, GRHSs, MatchGroup(..), pprLHsBinds, mkHsWrap, hsExplicitTvs,
25 collectHsBindBinders, collectPatBinders, pprPatBind, isBangHsBind
27 import TcHsSyn ( zonkId )
30 import Inst ( newDictBndrs, newIPDict, instToId )
31 import TcEnv ( tcExtendIdEnv, tcExtendIdEnv2, tcExtendTyVarEnv2,
32 pprBinders, tcLookupId,
34 import TcUnify ( tcInfer, tcSubExp, unifyTheta,
35 bleatEscapedTvs, sigCtxt )
36 import TcSimplify ( tcSimplifyInfer, tcSimplifyInferCheck,
37 tcSimplifyRestricted, tcSimplifyIPs )
38 import TcHsType ( tcHsSigType, UserTypeCtxt(..) )
39 import TcPat ( tcLetPat )
40 import TcSimplify ( bindInstsOfLocalFuns )
41 import TcMType ( newFlexiTyVarTy, zonkQuantifiedTyVar, zonkSigTyVar,
42 tcInstSigTyVars, tcInstSkolTyVars, tcInstType,
43 zonkTcType, zonkTcTypes, zonkTcTyVar )
44 import TcType ( TcType, TcTyVar, TcThetaType,
45 SkolemInfo(SigSkol), UserTypeCtxt(FunSigCtxt),
46 TcTauType, TcSigmaType, isUnboxedTupleType,
47 mkTyVarTy, mkForAllTys, mkFunTys, exactTyVarsOfType,
48 mkForAllTy, isUnLiftedType, tcGetTyVar,
49 mkTyVarTys, tidyOpenTyVar )
50 import {- Kind parts of -} Type ( argTypeKind )
51 import VarEnv ( TyVarEnv, emptyVarEnv, lookupVarEnv, extendVarEnv )
52 import TysPrim ( alphaTyVar )
53 import Id ( Id, mkLocalId, mkVanillaGlobal )
54 import IdInfo ( vanillaIdInfo )
55 import Var ( TyVar, idType, idName )
60 import SrcLoc ( Located(..), unLoc, getLoc )
62 import ErrUtils ( Message )
63 import Digraph ( SCC(..), stronglyConnComp )
64 import Maybes ( expectJust, isJust, isNothing, orElse )
65 import Util ( singleton )
66 import BasicTypes ( TopLevelFlag(..), isTopLevel, isNotTopLevel,
67 RecFlag(..), isNonRec, InlineSpec, defaultInlineSpec )
72 %************************************************************************
74 \subsection{Type-checking bindings}
76 %************************************************************************
78 @tcBindsAndThen@ typechecks a @HsBinds@. The "and then" part is because
79 it needs to know something about the {\em usage} of the things bound,
80 so that it can create specialisations of them. So @tcBindsAndThen@
81 takes a function which, given an extended environment, E, typechecks
82 the scope of the bindings returning a typechecked thing and (most
83 important) an LIE. It is this LIE which is then used as the basis for
84 specialising the things bound.
86 @tcBindsAndThen@ also takes a "combiner" which glues together the
87 bindings and the "thing" to make a new "thing".
89 The real work is done by @tcBindWithSigsAndThen@.
91 Recursive and non-recursive binds are handled in essentially the same
92 way: because of uniques there are no scoping issues left. The only
93 difference is that non-recursive bindings can bind primitive values.
95 Even for non-recursive binding groups we add typings for each binder
96 to the LVE for the following reason. When each individual binding is
97 checked the type of its LHS is unified with that of its RHS; and
98 type-checking the LHS of course requires that the binder is in scope.
100 At the top-level the LIE is sure to contain nothing but constant
101 dictionaries, which we resolve at the module level.
104 tcTopBinds :: HsValBinds Name -> TcM (LHsBinds TcId, TcLclEnv)
105 -- Note: returning the TcLclEnv is more than we really
106 -- want. The bit we care about is the local bindings
107 -- and the free type variables thereof
109 = do { (ValBindsOut prs _, env) <- tcValBinds TopLevel binds getLclEnv
110 ; return (foldr (unionBags . snd) emptyBag prs, env) }
111 -- The top level bindings are flattened into a giant
112 -- implicitly-mutually-recursive LHsBinds
114 tcHsBootSigs :: HsValBinds Name -> TcM [Id]
115 -- A hs-boot file has only one BindGroup, and it only has type
116 -- signatures in it. The renamer checked all this
117 tcHsBootSigs (ValBindsOut binds sigs)
118 = do { checkTc (null binds) badBootDeclErr
119 ; mapM (addLocM tc_boot_sig) (filter isVanillaLSig sigs) }
121 tc_boot_sig (TypeSig (L _ name) ty)
122 = do { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
123 ; return (mkVanillaGlobal name sigma_ty vanillaIdInfo) }
124 -- Notice that we make GlobalIds, not LocalIds
125 tcHsBootSigs groups = pprPanic "tcHsBootSigs" (ppr groups)
127 badBootDeclErr :: Message
128 badBootDeclErr = ptext SLIT("Illegal declarations in an hs-boot file")
130 ------------------------
131 tcLocalBinds :: HsLocalBinds Name -> TcM thing
132 -> TcM (HsLocalBinds TcId, thing)
134 tcLocalBinds EmptyLocalBinds thing_inside
135 = do { thing <- thing_inside
136 ; return (EmptyLocalBinds, thing) }
138 tcLocalBinds (HsValBinds binds) thing_inside
139 = do { (binds', thing) <- tcValBinds NotTopLevel binds thing_inside
140 ; return (HsValBinds binds', thing) }
142 tcLocalBinds (HsIPBinds (IPBinds ip_binds _)) thing_inside
143 = do { (thing, lie) <- getLIE thing_inside
144 ; (avail_ips, ip_binds') <- mapAndUnzipM (wrapLocSndM tc_ip_bind) ip_binds
146 -- If the binding binds ?x = E, we must now
147 -- discharge any ?x constraints in expr_lie
148 ; dict_binds <- tcSimplifyIPs avail_ips lie
149 ; return (HsIPBinds (IPBinds ip_binds' dict_binds), thing) }
151 -- I wonder if we should do these one at at time
154 tc_ip_bind (IPBind ip expr)
155 = newFlexiTyVarTy argTypeKind `thenM` \ ty ->
156 newIPDict (IPBindOrigin ip) ip ty `thenM` \ (ip', ip_inst) ->
157 tcMonoExpr expr ty `thenM` \ expr' ->
158 returnM (ip_inst, (IPBind ip' expr'))
160 ------------------------
161 tcValBinds :: TopLevelFlag
162 -> HsValBinds Name -> TcM thing
163 -> TcM (HsValBinds TcId, thing)
165 tcValBinds top_lvl (ValBindsIn binds sigs) thing_inside
166 = pprPanic "tcValBinds" (ppr binds)
168 tcValBinds top_lvl (ValBindsOut binds sigs) thing_inside
169 = do { -- Typecheck the signature
170 ; let { prag_fn = mkPragFun sigs
171 ; ty_sigs = filter isVanillaLSig sigs
172 ; sig_fn = mkTcSigFun ty_sigs }
174 ; poly_ids <- mapM tcTySig ty_sigs
175 -- No recovery from bad signatures, because the type sigs
176 -- may bind type variables, so proceeding without them
177 -- can lead to a cascade of errors
178 -- ToDo: this means we fall over immediately if any type sig
179 -- is wrong, which is over-conservative, see Trac bug #745
181 -- Extend the envt right away with all
182 -- the Ids declared with type signatures
183 ; gla_exts <- doptM Opt_GlasgowExts
184 ; (binds', thing) <- tcExtendIdEnv poly_ids $
185 tc_val_binds gla_exts top_lvl sig_fn prag_fn
188 ; return (ValBindsOut binds' sigs, thing) }
190 ------------------------
191 tc_val_binds :: Bool -> TopLevelFlag -> TcSigFun -> TcPragFun
192 -> [(RecFlag, LHsBinds Name)] -> TcM thing
193 -> TcM ([(RecFlag, LHsBinds TcId)], thing)
194 -- Typecheck a whole lot of value bindings,
195 -- one strongly-connected component at a time
197 tc_val_binds gla_exts top_lvl sig_fn prag_fn [] thing_inside
198 = do { thing <- thing_inside
199 ; return ([], thing) }
201 tc_val_binds gla_exts top_lvl sig_fn prag_fn (group : groups) thing_inside
202 = do { (group', (groups', thing))
203 <- tc_group gla_exts top_lvl sig_fn prag_fn group $
204 tc_val_binds gla_exts top_lvl sig_fn prag_fn groups thing_inside
205 ; return (group' ++ groups', thing) }
207 ------------------------
208 tc_group :: Bool -> TopLevelFlag -> TcSigFun -> TcPragFun
209 -> (RecFlag, LHsBinds Name) -> TcM thing
210 -> TcM ([(RecFlag, LHsBinds TcId)], thing)
212 -- Typecheck one strongly-connected component of the original program.
213 -- We get a list of groups back, because there may
214 -- be specialisations etc as well
216 tc_group gla_exts top_lvl sig_fn prag_fn (NonRecursive, binds) thing_inside
217 -- A single non-recursive binding
218 -- We want to keep non-recursive things non-recursive
219 -- so that we desugar unlifted bindings correctly
220 = do { (binds, thing) <- tc_haskell98 top_lvl sig_fn prag_fn NonRecursive binds thing_inside
221 ; return ([(NonRecursive, b) | b <- binds], thing) }
223 tc_group gla_exts top_lvl sig_fn prag_fn (Recursive, binds) thing_inside
224 | not gla_exts -- Recursive group, normal Haskell 98 route
225 = do { (binds1, thing) <- tc_haskell98 top_lvl sig_fn prag_fn Recursive binds thing_inside
226 ; return ([(Recursive, unionManyBags binds1)], thing) }
228 | otherwise -- Recursive group, with gla-exts
229 = -- To maximise polymorphism (with -fglasgow-exts), we do a new
230 -- strongly-connected-component analysis, this time omitting
231 -- any references to variables with type signatures.
233 -- Notice that the bindInsts thing covers *all* the bindings in the original
234 -- group at once; an earlier one may use a later one!
235 do { traceTc (text "tc_group rec" <+> pprLHsBinds binds)
236 ; (binds1,thing) <- bindLocalInsts top_lvl $
237 go (stronglyConnComp (mkEdges sig_fn binds))
238 ; return ([(Recursive, unionManyBags binds1)], thing) }
239 -- Rec them all together
241 -- go :: SCC (LHsBind Name) -> TcM ([LHsBind TcId], [TcId], thing)
242 go (scc:sccs) = do { (binds1, ids1) <- tc_scc scc
243 ; (binds2, ids2, thing) <- tcExtendIdEnv ids1 $ go sccs
244 ; return (binds1 ++ binds2, ids1 ++ ids2, thing) }
245 go [] = do { thing <- thing_inside; return ([], [], thing) }
247 tc_scc (AcyclicSCC bind) = tc_sub_group NonRecursive (unitBag bind)
248 tc_scc (CyclicSCC binds) = tc_sub_group Recursive (listToBag binds)
250 tc_sub_group = tcPolyBinds top_lvl sig_fn prag_fn Recursive
252 tc_haskell98 top_lvl sig_fn prag_fn rec_flag binds thing_inside
253 = bindLocalInsts top_lvl $ do
254 { (binds1, ids) <- tcPolyBinds top_lvl sig_fn prag_fn rec_flag rec_flag binds
255 ; thing <- tcExtendIdEnv ids thing_inside
256 ; return (binds1, ids, thing) }
258 ------------------------
259 bindLocalInsts :: TopLevelFlag -> TcM ([LHsBinds TcId], [TcId], a) -> TcM ([LHsBinds TcId], a)
260 bindLocalInsts top_lvl thing_inside
261 | isTopLevel top_lvl = do { (binds, ids, thing) <- thing_inside; return (binds, thing) }
262 -- For the top level don't bother will all this bindInstsOfLocalFuns stuff.
263 -- All the top level things are rec'd together anyway, so it's fine to
264 -- leave them to the tcSimplifyTop, and quite a bit faster too
266 | otherwise -- Nested case
267 = do { ((binds, ids, thing), lie) <- getLIE thing_inside
268 ; lie_binds <- bindInstsOfLocalFuns lie ids
269 ; return (binds ++ [lie_binds], thing) }
271 ------------------------
272 mkEdges :: TcSigFun -> LHsBinds Name
273 -> [(LHsBind Name, BKey, [BKey])]
275 type BKey = Int -- Just number off the bindings
278 = [ (bind, key, [key | n <- nameSetToList (bind_fvs (unLoc bind)),
279 Just key <- [lookupNameEnv key_map n], no_sig n ])
280 | (bind, key) <- keyd_binds
283 no_sig :: Name -> Bool
284 no_sig n = isNothing (sig_fn n)
286 keyd_binds = bagToList binds `zip` [0::BKey ..]
288 key_map :: NameEnv BKey -- Which binding it comes from
289 key_map = mkNameEnv [(bndr, key) | (L _ bind, key) <- keyd_binds
290 , bndr <- bindersOfHsBind bind ]
292 bindersOfHsBind :: HsBind Name -> [Name]
293 bindersOfHsBind (PatBind { pat_lhs = pat }) = collectPatBinders pat
294 bindersOfHsBind (FunBind { fun_id = L _ f }) = [f]
296 ------------------------
297 tcPolyBinds :: TopLevelFlag -> TcSigFun -> TcPragFun
298 -> RecFlag -- Whether the group is really recursive
299 -> RecFlag -- Whether it's recursive after breaking
300 -- dependencies based on type signatures
302 -> TcM ([LHsBinds TcId], [TcId])
304 -- Typechecks a single bunch of bindings all together,
305 -- and generalises them. The bunch may be only part of a recursive
306 -- group, because we use type signatures to maximise polymorphism
308 -- Returns a list because the input may be a single non-recursive binding,
309 -- in which case the dependency order of the resulting bindings is
312 -- Knows nothing about the scope of the bindings
314 tcPolyBinds top_lvl sig_fn prag_fn rec_group rec_tc binds
316 bind_list = bagToList binds
317 binder_names = collectHsBindBinders binds
318 loc = getLoc (head bind_list)
319 -- TODO: location a bit awkward, but the mbinds have been
320 -- dependency analysed and may no longer be adjacent
322 -- SET UP THE MAIN RECOVERY; take advantage of any type sigs
324 recoverM (recoveryCode binder_names sig_fn) $ do
326 { traceTc (ptext SLIT("------------------------------------------------"))
327 ; traceTc (ptext SLIT("Bindings for") <+> ppr binder_names)
329 -- TYPECHECK THE BINDINGS
330 ; ((binds', mono_bind_infos), lie_req)
331 <- getLIE (tcMonoBinds bind_list sig_fn rec_tc)
333 -- CHECK FOR UNLIFTED BINDINGS
334 -- These must be non-recursive etc, and are not generalised
335 -- They desugar to a case expression in the end
336 ; zonked_mono_tys <- zonkTcTypes (map getMonoType mono_bind_infos)
337 ; is_strict <- checkStrictBinds top_lvl rec_group binds'
338 zonked_mono_tys mono_bind_infos
340 do { extendLIEs lie_req
341 ; let exports = zipWith mk_export mono_bind_infos zonked_mono_tys
342 mk_export (name, Nothing, mono_id) mono_ty = ([], mkLocalId name mono_ty, mono_id, [])
343 mk_export (name, Just sig, mono_id) mono_ty = ([], sig_id sig, mono_id, [])
344 -- ToDo: prags for unlifted bindings
346 ; return ( [unitBag $ L loc $ AbsBinds [] [] exports binds'],
347 [poly_id | (_, poly_id, _, _) <- exports]) } -- Guaranteed zonked
349 else do -- The normal lifted case: GENERALISE
351 ; (tyvars_to_gen, dict_binds, dict_ids)
352 <- addErrCtxt (genCtxt (bndrNames mono_bind_infos)) $
353 generalise dflags top_lvl bind_list sig_fn mono_bind_infos lie_req
355 -- FINALISE THE QUANTIFIED TYPE VARIABLES
356 -- The quantified type variables often include meta type variables
357 -- we want to freeze them into ordinary type variables, and
358 -- default their kind (e.g. from OpenTypeKind to TypeKind)
359 ; tyvars_to_gen' <- mappM zonkQuantifiedTyVar tyvars_to_gen
361 -- BUILD THE POLYMORPHIC RESULT IDs
362 ; exports <- mapM (mkExport prag_fn tyvars_to_gen' (map idType dict_ids))
365 ; let poly_ids = [poly_id | (_, poly_id, _, _) <- exports]
366 ; traceTc (text "binding:" <+> ppr (poly_ids `zip` map idType poly_ids))
368 ; let abs_bind = L loc $ AbsBinds tyvars_to_gen'
370 (dict_binds `unionBags` binds')
372 ; return ([unitBag abs_bind], poly_ids) -- poly_ids are guaranteed zonked by mkExport
377 mkExport :: TcPragFun -> [TyVar] -> [TcType] -> MonoBindInfo
378 -> TcM ([TyVar], Id, Id, [Prag])
379 -- mkExport generates exports with
380 -- zonked type variables,
382 -- The former is just because no further unifications will change
383 -- the quantified type variables, so we can fix their final form
385 -- The latter is needed because the poly_ids are used to extend the
386 -- type environment; see the invariant on TcEnv.tcExtendIdEnv
388 -- Pre-condition: the inferred_tvs are already zonked
390 mkExport prag_fn inferred_tvs dict_tys (poly_name, mb_sig, mono_id)
391 = do { (tvs, poly_id) <- mk_poly_id mb_sig
393 ; poly_id' <- zonkId poly_id
394 ; prags <- tcPrags poly_id' (prag_fn poly_name)
395 -- tcPrags requires a zonked poly_id
397 ; return (tvs, poly_id', mono_id, prags) }
399 poly_ty = mkForAllTys inferred_tvs (mkFunTys dict_tys (idType mono_id))
401 mk_poly_id Nothing = return (inferred_tvs, mkLocalId poly_name poly_ty)
402 mk_poly_id (Just sig) = do { tvs <- mapM zonk_tv (sig_tvs sig)
403 ; return (tvs, sig_id sig) }
405 zonk_tv tv = do { ty <- zonkTcTyVar tv; return (tcGetTyVar "mkExport" ty) }
407 ------------------------
408 type TcPragFun = Name -> [LSig Name]
410 mkPragFun :: [LSig Name] -> TcPragFun
411 mkPragFun sigs = \n -> lookupNameEnv env n `orElse` []
413 prs = [(expectJust "mkPragFun" (sigName sig), sig)
414 | sig <- sigs, isPragLSig sig]
415 env = foldl add emptyNameEnv prs
416 add env (n,p) = extendNameEnv_Acc (:) singleton env n p
418 tcPrags :: Id -> [LSig Name] -> TcM [Prag]
419 tcPrags poly_id prags = mapM tc_prag prags
421 tc_prag (L loc prag) = setSrcSpan loc $
422 addErrCtxt (pragSigCtxt prag) $
425 pragSigCtxt prag = hang (ptext SLIT("In the pragma")) 2 (ppr prag)
427 tcPrag :: TcId -> Sig Name -> TcM Prag
428 -- Pre-condition: the poly_id is zonked
429 -- Reason: required by tcSubExp
430 tcPrag poly_id (SpecSig orig_name hs_ty inl) = tcSpecPrag poly_id hs_ty inl
431 tcPrag poly_id (SpecInstSig hs_ty) = tcSpecPrag poly_id hs_ty defaultInlineSpec
432 tcPrag poly_id (InlineSig v inl) = return (InlinePrag inl)
435 tcSpecPrag :: TcId -> LHsType Name -> InlineSpec -> TcM Prag
436 tcSpecPrag poly_id hs_ty inl
437 = do { spec_ty <- tcHsSigType (FunSigCtxt (idName poly_id)) hs_ty
438 ; (co_fn, lie) <- getLIE (tcSubExp (idType poly_id) spec_ty)
440 ; let const_dicts = map instToId lie
441 ; return (SpecPrag (mkHsWrap co_fn (HsVar poly_id)) spec_ty const_dicts inl) }
442 -- Most of the work of specialisation is done by
443 -- the desugarer, guided by the SpecPrag
446 -- If typechecking the binds fails, then return with each
447 -- signature-less binder given type (forall a.a), to minimise
448 -- subsequent error messages
449 recoveryCode binder_names sig_fn
450 = do { traceTc (text "tcBindsWithSigs: error recovery" <+> ppr binder_names)
451 ; poly_ids <- mapM mk_dummy binder_names
452 ; return ([], poly_ids) }
455 | isJust (sig_fn name) = tcLookupId name -- Had signature; look it up
456 | otherwise = return (mkLocalId name forall_a_a) -- No signature
459 forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
462 -- Check that non-overloaded unlifted bindings are
465 -- c) not a multiple-binding group (more or less implied by (a))
467 checkStrictBinds :: TopLevelFlag -> RecFlag
468 -> LHsBinds TcId -> [TcType] -> [MonoBindInfo]
470 checkStrictBinds top_lvl rec_group mbind mono_tys infos
471 | unlifted || bang_pat
472 = do { checkTc (isNotTopLevel top_lvl)
473 (strictBindErr "Top-level" unlifted mbind)
474 ; checkTc (isNonRec rec_group)
475 (strictBindErr "Recursive" unlifted mbind)
476 ; checkTc (isSingletonBag mbind)
477 (strictBindErr "Multiple" unlifted mbind)
478 ; mapM_ check_sig infos
483 unlifted = any isUnLiftedType mono_tys
484 bang_pat = anyBag (isBangHsBind . unLoc) mbind
485 check_sig (_, Just sig, _) = checkTc (null (sig_tvs sig) && null (sig_theta sig))
486 (badStrictSig unlifted sig)
487 check_sig other = return ()
489 strictBindErr flavour unlifted mbind
490 = hang (text flavour <+> msg <+> ptext SLIT("aren't allowed:"))
491 4 (pprLHsBinds mbind)
493 msg | unlifted = ptext SLIT("bindings for unlifted types")
494 | otherwise = ptext SLIT("bang-pattern bindings")
496 badStrictSig unlifted sig
497 = hang (ptext SLIT("Illegal polymorphic signature in") <+> msg)
500 msg | unlifted = ptext SLIT("an unlifted binding")
501 | otherwise = ptext SLIT("a bang-pattern binding")
505 %************************************************************************
507 \subsection{tcMonoBind}
509 %************************************************************************
511 @tcMonoBinds@ deals with a perhaps-recursive group of HsBinds.
512 The signatures have been dealt with already.
515 tcMonoBinds :: [LHsBind Name]
517 -> RecFlag -- Whether the binding is recursive for typechecking purposes
518 -- i.e. the binders are mentioned in their RHSs, and
519 -- we are not resuced by a type signature
520 -> TcM (LHsBinds TcId, [MonoBindInfo])
522 tcMonoBinds [L b_loc (FunBind { fun_id = L nm_loc name, fun_infix = inf,
523 fun_matches = matches, bind_fvs = fvs })]
524 sig_fn -- Single function binding,
525 NonRecursive -- binder isn't mentioned in RHS,
526 | Nothing <- sig_fn name -- ...with no type signature
527 = -- In this very special case we infer the type of the
528 -- right hand side first (it may have a higher-rank type)
529 -- and *then* make the monomorphic Id for the LHS
530 -- e.g. f = \(x::forall a. a->a) -> <body>
531 -- We want to infer a higher-rank type for f
533 do { ((co_fn, matches'), rhs_ty) <- tcInfer (tcMatchesFun name matches)
535 -- Check for an unboxed tuple type
536 -- f = (# True, False #)
537 -- Zonk first just in case it's hidden inside a meta type variable
538 -- (This shows up as a (more obscure) kind error
539 -- in the 'otherwise' case of tcMonoBinds.)
540 ; zonked_rhs_ty <- zonkTcType rhs_ty
541 ; checkTc (not (isUnboxedTupleType zonked_rhs_ty))
542 (unboxedTupleErr name zonked_rhs_ty)
544 ; mono_name <- newLocalName name
545 ; let mono_id = mkLocalId mono_name zonked_rhs_ty
546 ; return (unitBag (L b_loc (FunBind { fun_id = L nm_loc mono_id, fun_infix = inf,
547 fun_matches = matches', bind_fvs = fvs,
548 fun_co_fn = co_fn })),
549 [(name, Nothing, mono_id)]) }
551 tcMonoBinds [L b_loc (FunBind { fun_id = L nm_loc name, fun_infix = inf,
552 fun_matches = matches, bind_fvs = fvs })]
553 sig_fn -- Single function binding
555 | Just scoped_tvs <- sig_fn name -- ...with a type signature
556 = -- When we have a single function binding, with a type signature
557 -- we can (a) use genuine, rigid skolem constants for the type variables
558 -- (b) bring (rigid) scoped type variables into scope
560 do { tc_sig <- tcInstSig True name scoped_tvs
561 ; mono_name <- newLocalName name
562 ; let mono_ty = sig_tau tc_sig
563 mono_id = mkLocalId mono_name mono_ty
564 rhs_tvs = [ (name, mkTyVarTy tv)
565 | (name, tv) <- sig_scoped tc_sig `zip` sig_tvs tc_sig ]
567 ; (co_fn, matches') <- tcExtendTyVarEnv2 rhs_tvs $
568 tcMatchesFun mono_name matches mono_ty
570 ; let fun_bind' = FunBind { fun_id = L nm_loc mono_id,
571 fun_infix = inf, fun_matches = matches',
572 bind_fvs = placeHolderNames, fun_co_fn = co_fn }
573 ; return (unitBag (L b_loc fun_bind'),
574 [(name, Just tc_sig, mono_id)]) }
576 tcMonoBinds binds sig_fn non_rec
577 = do { tc_binds <- mapM (wrapLocM (tcLhs sig_fn)) binds
579 -- Bring the monomorphic Ids, into scope for the RHSs
580 ; let mono_info = getMonoBindInfo tc_binds
581 rhs_id_env = [(name,mono_id) | (name, Nothing, mono_id) <- mono_info]
582 -- A monomorphic binding for each term variable that lacks
583 -- a type sig. (Ones with a sig are already in scope.)
585 ; binds' <- tcExtendIdEnv2 rhs_id_env $
586 traceTc (text "tcMonoBinds" <+> vcat [ ppr n <+> ppr id <+> ppr (idType id)
587 | (n,id) <- rhs_id_env]) `thenM_`
588 mapM (wrapLocM tcRhs) tc_binds
589 ; return (listToBag binds', mono_info) }
591 ------------------------
592 -- tcLhs typechecks the LHS of the bindings, to construct the environment in which
593 -- we typecheck the RHSs. Basically what we are doing is this: for each binder:
594 -- if there's a signature for it, use the instantiated signature type
595 -- otherwise invent a type variable
596 -- You see that quite directly in the FunBind case.
598 -- But there's a complication for pattern bindings:
599 -- data T = MkT (forall a. a->a)
601 -- Here we can guess a type variable for the entire LHS (which will be refined to T)
602 -- but we want to get (f::forall a. a->a) as the RHS environment.
603 -- The simplest way to do this is to typecheck the pattern, and then look up the
604 -- bound mono-ids. Then we want to retain the typechecked pattern to avoid re-doing
605 -- it; hence the TcMonoBind data type in which the LHS is done but the RHS isn't
607 data TcMonoBind -- Half completed; LHS done, RHS not done
608 = TcFunBind MonoBindInfo (Located TcId) Bool (MatchGroup Name)
609 | TcPatBind [MonoBindInfo] (LPat TcId) (GRHSs Name) TcSigmaType
611 type MonoBindInfo = (Name, Maybe TcSigInfo, TcId)
612 -- Type signature (if any), and
613 -- the monomorphic bound things
615 bndrNames :: [MonoBindInfo] -> [Name]
616 bndrNames mbi = [n | (n,_,_) <- mbi]
618 getMonoType :: MonoBindInfo -> TcTauType
619 getMonoType (_,_,mono_id) = idType mono_id
621 tcLhs :: TcSigFun -> HsBind Name -> TcM TcMonoBind
622 tcLhs sig_fn (FunBind { fun_id = L nm_loc name, fun_infix = inf, fun_matches = matches })
623 = do { mb_sig <- tcInstSig_maybe sig_fn name
624 ; mono_name <- newLocalName name
625 ; mono_ty <- mk_mono_ty mb_sig
626 ; let mono_id = mkLocalId mono_name mono_ty
627 ; return (TcFunBind (name, mb_sig, mono_id) (L nm_loc mono_id) inf matches) }
629 mk_mono_ty (Just sig) = return (sig_tau sig)
630 mk_mono_ty Nothing = newFlexiTyVarTy argTypeKind
632 tcLhs sig_fn bind@(PatBind { pat_lhs = pat, pat_rhs = grhss })
633 = do { mb_sigs <- mapM (tcInstSig_maybe sig_fn) names
634 ; mono_pat_binds <- doptM Opt_MonoPatBinds
635 -- With -fmono-pat-binds, we do no generalisation of pattern bindings
636 -- But the signature can still be polymoprhic!
637 -- data T = MkT (forall a. a->a)
638 -- x :: forall a. a->a
640 -- The function get_sig_ty decides whether the pattern-bound variables
641 -- should have exactly the type in the type signature (-fmono-pat-binds),
642 -- or the instantiated version (-fmono-pat-binds)
644 ; let nm_sig_prs = names `zip` mb_sigs
645 get_sig_ty | mono_pat_binds = idType . sig_id
646 | otherwise = sig_tau
647 tau_sig_env = mkNameEnv [ (name, get_sig_ty sig)
648 | (name, Just sig) <- nm_sig_prs]
649 sig_tau_fn = lookupNameEnv tau_sig_env
651 tc_pat exp_ty = tcLetPat sig_tau_fn pat exp_ty $
652 mapM lookup_info nm_sig_prs
654 -- After typechecking the pattern, look up the binder
655 -- names, which the pattern has brought into scope.
656 lookup_info :: (Name, Maybe TcSigInfo) -> TcM MonoBindInfo
657 lookup_info (name, mb_sig) = do { mono_id <- tcLookupId name
658 ; return (name, mb_sig, mono_id) }
660 ; ((pat', infos), pat_ty) <- addErrCtxt (patMonoBindsCtxt pat grhss) $
663 ; return (TcPatBind infos pat' grhss pat_ty) }
665 names = collectPatBinders pat
668 tcLhs sig_fn other_bind = pprPanic "tcLhs" (ppr other_bind)
669 -- AbsBind, VarBind impossible
672 tcRhs :: TcMonoBind -> TcM (HsBind TcId)
673 tcRhs (TcFunBind info fun'@(L _ mono_id) inf matches)
674 = do { (co_fn, matches') <- tcMatchesFun (idName mono_id) matches
676 ; return (FunBind { fun_id = fun', fun_infix = inf, fun_matches = matches',
677 bind_fvs = placeHolderNames, fun_co_fn = co_fn }) }
679 tcRhs bind@(TcPatBind _ pat' grhss pat_ty)
680 = do { grhss' <- addErrCtxt (patMonoBindsCtxt pat' grhss) $
681 tcGRHSsPat grhss pat_ty
682 ; return (PatBind { pat_lhs = pat', pat_rhs = grhss', pat_rhs_ty = pat_ty,
683 bind_fvs = placeHolderNames }) }
686 ---------------------
687 getMonoBindInfo :: [Located TcMonoBind] -> [MonoBindInfo]
688 getMonoBindInfo tc_binds
689 = foldr (get_info . unLoc) [] tc_binds
691 get_info (TcFunBind info _ _ _) rest = info : rest
692 get_info (TcPatBind infos _ _ _) rest = infos ++ rest
696 %************************************************************************
700 %************************************************************************
703 generalise :: DynFlags -> TopLevelFlag
704 -> [LHsBind Name] -> TcSigFun
705 -> [MonoBindInfo] -> [Inst]
706 -> TcM ([TcTyVar], TcDictBinds, [TcId])
707 generalise dflags top_lvl bind_list sig_fn mono_infos lie_req
708 | isMonoGroup dflags bind_list
709 = do { extendLIEs lie_req; return ([], emptyBag, []) }
711 | isRestrictedGroup dflags bind_list sig_fn -- RESTRICTED CASE
712 = -- Check signature contexts are empty
713 do { checkTc (all is_mono_sig sigs)
714 (restrictedBindCtxtErr bndrs)
716 -- Now simplify with exactly that set of tyvars
717 -- We have to squash those Methods
718 ; (qtvs, binds) <- tcSimplifyRestricted doc top_lvl bndrs
721 -- Check that signature type variables are OK
722 ; final_qtvs <- checkSigsTyVars qtvs sigs
724 ; return (final_qtvs, binds, []) }
726 | null sigs -- UNRESTRICTED CASE, NO TYPE SIGS
727 = tcSimplifyInfer doc tau_tvs lie_req
729 | otherwise -- UNRESTRICTED CASE, WITH TYPE SIGS
730 = do { sig_lie <- unifyCtxts sigs -- sigs is non-empty
731 ; let -- The "sig_avails" is the stuff available. We get that from
732 -- the context of the type signature, BUT ALSO the lie_avail
733 -- so that polymorphic recursion works right (see Note [Polymorphic recursion])
734 local_meths = [mkMethInst sig mono_id | (_, Just sig, mono_id) <- mono_infos]
735 sig_avails = sig_lie ++ local_meths
737 -- Check that the needed dicts can be
738 -- expressed in terms of the signature ones
739 ; (forall_tvs, dict_binds) <- tcSimplifyInferCheck doc tau_tvs sig_avails lie_req
741 -- Check that signature type variables are OK
742 ; final_qtvs <- checkSigsTyVars forall_tvs sigs
744 ; returnM (final_qtvs, dict_binds, map instToId sig_lie) }
746 bndrs = bndrNames mono_infos
747 sigs = [sig | (_, Just sig, _) <- mono_infos]
748 tau_tvs = foldr (unionVarSet . exactTyVarsOfType . getMonoType) emptyVarSet mono_infos
749 -- NB: exactTyVarsOfType; see Note [Silly type synonym]
750 -- near defn of TcType.exactTyVarsOfType
751 is_mono_sig sig = null (sig_theta sig)
752 doc = ptext SLIT("type signature(s) for") <+> pprBinders bndrs
754 mkMethInst (TcSigInfo { sig_id = poly_id, sig_tvs = tvs,
755 sig_theta = theta, sig_loc = loc }) mono_id
756 = Method mono_id poly_id (mkTyVarTys tvs) theta loc
759 unifyCtxts checks that all the signature contexts are the same
760 The type signatures on a mutually-recursive group of definitions
761 must all have the same context (or none).
763 The trick here is that all the signatures should have the same
764 context, and we want to share type variables for that context, so that
765 all the right hand sides agree a common vocabulary for their type
768 We unify them because, with polymorphic recursion, their types
769 might not otherwise be related. This is a rather subtle issue.
772 unifyCtxts :: [TcSigInfo] -> TcM [Inst]
773 unifyCtxts (sig1 : sigs) -- Argument is always non-empty
774 = do { mapM unify_ctxt sigs
775 ; newDictBndrs (sig_loc sig1) (sig_theta sig1) }
777 theta1 = sig_theta sig1
778 unify_ctxt :: TcSigInfo -> TcM ()
779 unify_ctxt sig@(TcSigInfo { sig_theta = theta })
780 = setSrcSpan (instLocSrcSpan (sig_loc sig)) $
781 addErrCtxt (sigContextsCtxt sig1 sig) $
782 unifyTheta theta1 theta
784 checkSigsTyVars :: [TcTyVar] -> [TcSigInfo] -> TcM [TcTyVar]
785 checkSigsTyVars qtvs sigs
786 = do { gbl_tvs <- tcGetGlobalTyVars
787 ; sig_tvs_s <- mappM (check_sig gbl_tvs) sigs
789 ; let -- Sigh. Make sure that all the tyvars in the type sigs
790 -- appear in the returned ty var list, which is what we are
791 -- going to generalise over. Reason: we occasionally get
793 -- type T a = () -> ()
796 -- Here, 'a' won't appear in qtvs, so we have to add it
797 sig_tvs = foldl extendVarSetList emptyVarSet sig_tvs_s
798 all_tvs = varSetElems (extendVarSetList sig_tvs qtvs)
801 check_sig gbl_tvs (TcSigInfo {sig_id = id, sig_tvs = tvs,
802 sig_theta = theta, sig_tau = tau})
803 = addErrCtxt (ptext SLIT("In the type signature for") <+> quotes (ppr id)) $
804 addErrCtxtM (sigCtxt id tvs theta tau) $
805 do { tvs' <- checkDistinctTyVars tvs
806 ; ifM (any (`elemVarSet` gbl_tvs) tvs')
807 (bleatEscapedTvs gbl_tvs tvs tvs')
810 checkDistinctTyVars :: [TcTyVar] -> TcM [TcTyVar]
811 -- (checkDistinctTyVars tvs) checks that the tvs from one type signature
812 -- are still all type variables, and all distinct from each other.
813 -- It returns a zonked set of type variables.
814 -- For example, if the type sig is
815 -- f :: forall a b. a -> b -> b
816 -- we want to check that 'a' and 'b' haven't
817 -- (a) been unified with a non-tyvar type
818 -- (b) been unified with each other (all distinct)
820 checkDistinctTyVars sig_tvs
821 = do { zonked_tvs <- mapM zonkSigTyVar sig_tvs
822 ; foldlM check_dup emptyVarEnv (sig_tvs `zip` zonked_tvs)
823 ; return zonked_tvs }
825 check_dup :: TyVarEnv TcTyVar -> (TcTyVar, TcTyVar) -> TcM (TyVarEnv TcTyVar)
826 -- The TyVarEnv maps each zonked type variable back to its
827 -- corresponding user-written signature type variable
828 check_dup acc (sig_tv, zonked_tv)
829 = case lookupVarEnv acc zonked_tv of
830 Just sig_tv' -> bomb_out sig_tv sig_tv'
832 Nothing -> return (extendVarEnv acc zonked_tv sig_tv)
834 bomb_out sig_tv1 sig_tv2
835 = do { env0 <- tcInitTidyEnv
836 ; let (env1, tidy_tv1) = tidyOpenTyVar env0 sig_tv1
837 (env2, tidy_tv2) = tidyOpenTyVar env1 sig_tv2
838 msg = ptext SLIT("Quantified type variable") <+> quotes (ppr tidy_tv1)
839 <+> ptext SLIT("is unified with another quantified type variable")
840 <+> quotes (ppr tidy_tv2)
841 ; failWithTcM (env2, msg) }
846 @getTyVarsToGen@ decides what type variables to generalise over.
848 For a "restricted group" -- see the monomorphism restriction
849 for a definition -- we bind no dictionaries, and
850 remove from tyvars_to_gen any constrained type variables
852 *Don't* simplify dicts at this point, because we aren't going
853 to generalise over these dicts. By the time we do simplify them
854 we may well know more. For example (this actually came up)
856 f x = array ... xs where xs = [1,2,3,4,5]
857 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
858 stuff. If we simplify only at the f-binding (not the xs-binding)
859 we'll know that the literals are all Ints, and we can just produce
862 Find all the type variables involved in overloading, the
863 "constrained_tyvars". These are the ones we *aren't* going to
864 generalise. We must be careful about doing this:
866 (a) If we fail to generalise a tyvar which is not actually
867 constrained, then it will never, ever get bound, and lands
868 up printed out in interface files! Notorious example:
869 instance Eq a => Eq (Foo a b) where ..
870 Here, b is not constrained, even though it looks as if it is.
871 Another, more common, example is when there's a Method inst in
872 the LIE, whose type might very well involve non-overloaded
874 [NOTE: Jan 2001: I don't understand the problem here so I'm doing
875 the simple thing instead]
877 (b) On the other hand, we mustn't generalise tyvars which are constrained,
878 because we are going to pass on out the unmodified LIE, with those
879 tyvars in it. They won't be in scope if we've generalised them.
881 So we are careful, and do a complete simplification just to find the
882 constrained tyvars. We don't use any of the results, except to
883 find which tyvars are constrained.
885 Note [Polymorphic recursion]
886 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
887 The game plan for polymorphic recursion in the code above is
889 * Bind any variable for which we have a type signature
890 to an Id with a polymorphic type. Then when type-checking
891 the RHSs we'll make a full polymorphic call.
893 This fine, but if you aren't a bit careful you end up with a horrendous
894 amount of partial application and (worse) a huge space leak. For example:
896 f :: Eq a => [a] -> [a]
899 If we don't take care, after typechecking we get
901 f = /\a -> \d::Eq a -> let f' = f a d
905 Notice the the stupid construction of (f a d), which is of course
906 identical to the function we're executing. In this case, the
907 polymorphic recursion isn't being used (but that's a very common case).
908 This can lead to a massive space leak, from the following top-level defn
914 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
915 f' is another thunk which evaluates to the same thing... and you end
916 up with a chain of identical values all hung onto by the CAF ff.
920 = let f' = f Int dEqInt in \ys. ...f'...
922 = let f' = let f' = f Int dEqInt in \ys. ...f'...
927 NOTE: a bit of arity anaysis would push the (f a d) inside the (\ys...),
928 which would make the space leak go away in this case
930 Solution: when typechecking the RHSs we always have in hand the
931 *monomorphic* Ids for each binding. So we just need to make sure that
932 if (Method f a d) shows up in the constraints emerging from (...f...)
933 we just use the monomorphic Id. We achieve this by adding monomorphic Ids
934 to the "givens" when simplifying constraints. That's what the "lies_avail"
939 f = /\a -> \d::Eq a -> letrec
940 fm = \ys:[a] -> ...fm...
946 %************************************************************************
950 %************************************************************************
952 Type signatures are tricky. See Note [Signature skolems] in TcType
954 @tcSigs@ checks the signatures for validity, and returns a list of
955 {\em freshly-instantiated} signatures. That is, the types are already
956 split up, and have fresh type variables installed. All non-type-signature
957 "RenamedSigs" are ignored.
959 The @TcSigInfo@ contains @TcTypes@ because they are unified with
960 the variable's type, and after that checked to see whether they've
964 type TcSigFun = Name -> Maybe [Name] -- Maps a let-binder to the list of
965 -- type variables brought into scope
966 -- by its type signature.
967 -- Nothing => no type signature
969 mkTcSigFun :: [LSig Name] -> TcSigFun
970 -- Search for a particular type signature
971 -- Precondition: the sigs are all type sigs
972 -- Precondition: no duplicates
973 mkTcSigFun sigs = lookupNameEnv env
975 env = mkNameEnv [(name, hsExplicitTvs lhs_ty)
976 | L span (TypeSig (L _ name) lhs_ty) <- sigs]
977 -- The scoped names are the ones explicitly mentioned
978 -- in the HsForAll. (There may be more in sigma_ty, because
979 -- of nested type synonyms. See Note [Scoped] with TcSigInfo.)
980 -- See Note [Only scoped tyvars are in the TyVarEnv]
985 sig_id :: TcId, -- *Polymorphic* binder for this value...
987 sig_scoped :: [Name], -- Names for any scoped type variables
988 -- Invariant: correspond 1-1 with an initial
989 -- segment of sig_tvs (see Note [Scoped])
991 sig_tvs :: [TcTyVar], -- Instantiated type variables
992 -- See Note [Instantiate sig]
994 sig_theta :: TcThetaType, -- Instantiated theta
995 sig_tau :: TcTauType, -- Instantiated tau
996 sig_loc :: InstLoc -- The location of the signature
1000 -- Note [Only scoped tyvars are in the TyVarEnv]
1001 -- We are careful to keep only the *lexically scoped* type variables in
1002 -- the type environment. Why? After all, the renamer has ensured
1003 -- that only legal occurrences occur, so we could put all type variables
1004 -- into the type env.
1006 -- But we want to check that two distinct lexically scoped type variables
1007 -- do not map to the same internal type variable. So we need to know which
1008 -- the lexically-scoped ones are... and at the moment we do that by putting
1009 -- only the lexically scoped ones into the environment.
1013 -- There may be more instantiated type variables than scoped
1014 -- ones. For example:
1015 -- type T a = forall b. b -> (a,b)
1016 -- f :: forall c. T c
1017 -- Here, the signature for f will have one scoped type variable, c,
1018 -- but two instantiated type variables, c' and b'.
1020 -- We assume that the scoped ones are at the *front* of sig_tvs,
1021 -- and remember the names from the original HsForAllTy in sig_scoped
1023 -- Note [Instantiate sig]
1024 -- It's vital to instantiate a type signature with fresh variables.
1026 -- type S = forall a. a->a
1030 -- Here, we must use distinct type variables when checking f,g's right hand sides.
1031 -- (Instantiation is only necessary because of type synonyms. Otherwise,
1032 -- it's all cool; each signature has distinct type variables from the renamer.)
1034 instance Outputable TcSigInfo where
1035 ppr (TcSigInfo { sig_id = id, sig_tvs = tyvars, sig_theta = theta, sig_tau = tau})
1036 = ppr id <+> ptext SLIT("::") <+> ppr tyvars <+> ppr theta <+> ptext SLIT("=>") <+> ppr tau
1040 tcTySig :: LSig Name -> TcM TcId
1041 tcTySig (L span (TypeSig (L _ name) ty))
1043 do { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
1044 ; return (mkLocalId name sigma_ty) }
1047 tcInstSig_maybe :: TcSigFun -> Name -> TcM (Maybe TcSigInfo)
1048 -- Instantiate with *meta* type variables;
1049 -- this signature is part of a multi-signature group
1050 tcInstSig_maybe sig_fn name
1051 = case sig_fn name of
1052 Nothing -> return Nothing
1053 Just tvs -> do { tc_sig <- tcInstSig False name tvs
1054 ; return (Just tc_sig) }
1056 tcInstSig :: Bool -> Name -> [Name] -> TcM TcSigInfo
1057 -- Instantiate the signature, with either skolems or meta-type variables
1058 -- depending on the use_skols boolean. This variable is set True
1059 -- when we are typechecking a single function binding; and False for
1060 -- pattern bindings and a group of several function bindings.
1061 -- Reason: in the latter cases, the "skolems" can be unified together,
1062 -- so they aren't properly rigid in the type-refinement sense.
1063 -- NB: unless we are doing H98, each function with a sig will be done
1064 -- separately, even if it's mutually recursive, so use_skols will be True
1066 -- We always instantiate with fresh uniques,
1067 -- although we keep the same print-name
1069 -- type T = forall a. [a] -> [a]
1071 -- f = g where { g :: T; g = <rhs> }
1073 -- We must not use the same 'a' from the defn of T at both places!!
1075 tcInstSig use_skols name scoped_names
1076 = do { poly_id <- tcLookupId name -- Cannot fail; the poly ids are put into
1077 -- scope when starting the binding group
1078 ; let skol_info = SigSkol (FunSigCtxt name)
1079 inst_tyvars | use_skols = tcInstSkolTyVars skol_info
1080 | otherwise = tcInstSigTyVars skol_info
1081 ; (tvs, theta, tau) <- tcInstType inst_tyvars (idType poly_id)
1082 ; loc <- getInstLoc (SigOrigin skol_info)
1083 ; return (TcSigInfo { sig_id = poly_id,
1084 sig_tvs = tvs, sig_theta = theta, sig_tau = tau,
1085 sig_scoped = final_scoped_names, sig_loc = loc }) }
1086 -- Note that the scoped_names and the sig_tvs will have
1087 -- different Names. That's quite ok; when we bring the
1088 -- scoped_names into scope, we just bind them to the sig_tvs
1090 -- We also only have scoped type variables when we are instantiating
1091 -- with true skolems
1092 final_scoped_names | use_skols = scoped_names
1096 isMonoGroup :: DynFlags -> [LHsBind Name] -> Bool
1097 -- No generalisation at all
1098 isMonoGroup dflags binds
1099 = dopt Opt_MonoPatBinds dflags && any is_pat_bind binds
1101 is_pat_bind (L _ (PatBind {})) = True
1102 is_pat_bind other = False
1105 isRestrictedGroup :: DynFlags -> [LHsBind Name] -> TcSigFun -> Bool
1106 isRestrictedGroup dflags binds sig_fn
1107 = mono_restriction && not all_unrestricted
1109 mono_restriction = dopt Opt_MonomorphismRestriction dflags
1110 all_unrestricted = all (unrestricted . unLoc) binds
1111 has_sig n = isJust (sig_fn n)
1113 unrestricted (PatBind {}) = False
1114 unrestricted (VarBind { var_id = v }) = has_sig v
1115 unrestricted (FunBind { fun_id = v, fun_matches = matches }) = unrestricted_match matches
1116 || has_sig (unLoc v)
1118 unrestricted_match (MatchGroup (L _ (Match [] _ _) : _) _) = False
1119 -- No args => like a pattern binding
1120 unrestricted_match other = True
1121 -- Some args => a function binding
1125 %************************************************************************
1127 \subsection[TcBinds-errors]{Error contexts and messages}
1129 %************************************************************************
1133 -- This one is called on LHS, when pat and grhss are both Name
1134 -- and on RHS, when pat is TcId and grhss is still Name
1135 patMonoBindsCtxt pat grhss
1136 = hang (ptext SLIT("In a pattern binding:")) 4 (pprPatBind pat grhss)
1138 -----------------------------------------------
1139 sigContextsCtxt sig1 sig2
1140 = vcat [ptext SLIT("When matching the contexts of the signatures for"),
1141 nest 2 (vcat [ppr id1 <+> dcolon <+> ppr (idType id1),
1142 ppr id2 <+> dcolon <+> ppr (idType id2)]),
1143 ptext SLIT("The signature contexts in a mutually recursive group should all be identical")]
1149 -----------------------------------------------
1150 unboxedTupleErr name ty
1151 = hang (ptext SLIT("Illegal binding of unboxed tuple"))
1152 4 (ppr name <+> dcolon <+> ppr ty)
1154 -----------------------------------------------
1155 restrictedBindCtxtErr binder_names
1156 = hang (ptext SLIT("Illegal overloaded type signature(s)"))
1157 4 (vcat [ptext SLIT("in a binding group for") <+> pprBinders binder_names,
1158 ptext SLIT("that falls under the monomorphism restriction")])
1160 genCtxt binder_names
1161 = ptext SLIT("When generalising the type(s) for") <+> pprBinders binder_names