0db76d14f7898d657f0aaad191777f0c5cb1f338
[ghc-hetmet.git] / compiler / typecheck / TcBinds.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5 \section[TcBinds]{TcBinds}
6
7 \begin{code}
8 module TcBinds ( tcLocalBinds, tcTopBinds, 
9                  tcHsBootSigs, tcPolyBinds,
10                  PragFun, tcSpecPrags, mkPragFun, 
11                  TcSigInfo(..), SigFun, mkSigFun,
12                  badBootDeclErr ) where
13
14 import {-# SOURCE #-} TcMatches ( tcGRHSsPat, tcMatchesFun )
15 import {-# SOURCE #-} TcExpr  ( tcMonoExpr )
16
17 import DynFlags
18 import HsSyn
19
20 import TcRnMonad
21 import TcEnv
22 import TcUnify
23 import TcSimplify
24 import TcHsType
25 import TcPat
26 import TcMType
27 import TcType
28 import Coercion
29 import TysPrim
30 import Id
31 import Var
32 import Name
33 import NameSet
34 import NameEnv
35 import VarSet
36 import SrcLoc
37 import Bag
38 import ErrUtils
39 import Digraph
40 import Maybes
41 import Util
42 import BasicTypes
43 import Outputable
44 import FastString
45
46 import Control.Monad
47 \end{code}
48
49
50 %************************************************************************
51 %*                                                                      *
52 \subsection{Type-checking bindings}
53 %*                                                                      *
54 %************************************************************************
55
56 @tcBindsAndThen@ typechecks a @HsBinds@.  The "and then" part is because
57 it needs to know something about the {\em usage} of the things bound,
58 so that it can create specialisations of them.  So @tcBindsAndThen@
59 takes a function which, given an extended environment, E, typechecks
60 the scope of the bindings returning a typechecked thing and (most
61 important) an LIE.  It is this LIE which is then used as the basis for
62 specialising the things bound.
63
64 @tcBindsAndThen@ also takes a "combiner" which glues together the
65 bindings and the "thing" to make a new "thing".
66
67 The real work is done by @tcBindWithSigsAndThen@.
68
69 Recursive and non-recursive binds are handled in essentially the same
70 way: because of uniques there are no scoping issues left.  The only
71 difference is that non-recursive bindings can bind primitive values.
72
73 Even for non-recursive binding groups we add typings for each binder
74 to the LVE for the following reason.  When each individual binding is
75 checked the type of its LHS is unified with that of its RHS; and
76 type-checking the LHS of course requires that the binder is in scope.
77
78 At the top-level the LIE is sure to contain nothing but constant
79 dictionaries, which we resolve at the module level.
80
81 \begin{code}
82 tcTopBinds :: HsValBinds Name -> TcM (LHsBinds TcId, TcLclEnv)
83         -- Note: returning the TcLclEnv is more than we really
84         --       want.  The bit we care about is the local bindings
85         --       and the free type variables thereof
86 tcTopBinds binds
87   = do  { (ValBindsOut prs _, env) <- tcValBinds TopLevel binds getLclEnv
88         ; return (foldr (unionBags . snd) emptyBag prs, env) }
89         -- The top level bindings are flattened into a giant 
90         -- implicitly-mutually-recursive LHsBinds
91
92 tcHsBootSigs :: HsValBinds Name -> TcM [Id]
93 -- A hs-boot file has only one BindGroup, and it only has type
94 -- signatures in it.  The renamer checked all this
95 tcHsBootSigs (ValBindsOut binds sigs)
96   = do  { checkTc (null binds) badBootDeclErr
97         ; mapM (addLocM tc_boot_sig) (filter isTypeLSig sigs) }
98   where
99     tc_boot_sig (TypeSig (L _ name) ty)
100       = do { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
101            ; return (mkVanillaGlobal name sigma_ty) }
102         -- Notice that we make GlobalIds, not LocalIds
103     tc_boot_sig s = pprPanic "tcHsBootSigs/tc_boot_sig" (ppr s)
104 tcHsBootSigs groups = pprPanic "tcHsBootSigs" (ppr groups)
105
106 badBootDeclErr :: Message
107 badBootDeclErr = ptext (sLit "Illegal declarations in an hs-boot file")
108
109 ------------------------
110 tcLocalBinds :: HsLocalBinds Name -> TcM thing
111              -> TcM (HsLocalBinds TcId, thing)
112
113 tcLocalBinds EmptyLocalBinds thing_inside 
114   = do  { thing <- thing_inside
115         ; return (EmptyLocalBinds, thing) }
116
117 tcLocalBinds (HsValBinds binds) thing_inside
118   = do  { (binds', thing) <- tcValBinds NotTopLevel binds thing_inside
119         ; return (HsValBinds binds', thing) }
120
121 tcLocalBinds (HsIPBinds (IPBinds ip_binds _)) thing_inside
122   = do  { (given_ips, ip_binds') <- mapAndUnzipM (wrapLocSndM tc_ip_bind) ip_binds
123         ; let ip_tvs = foldr (unionVarSet . tyVarsOfType . idType) emptyVarSet given_ips
124
125         -- If the binding binds ?x = E, we  must now 
126         -- discharge any ?x constraints in expr_lie
127         ; (ev_binds, result) <- checkConstraints (IPSkol ips) 
128                                   ip_tvs  -- See Note [Implicit parameter untouchables]
129                                   [] given_ips $
130                                 thing_inside
131
132         ; return (HsIPBinds (IPBinds ip_binds' ev_binds), result) }
133   where
134     ips = [ip | L _ (IPBind ip _) <- ip_binds]
135
136         -- I wonder if we should do these one at at time
137         -- Consider     ?x = 4
138         --              ?y = ?x + 1
139     tc_ip_bind (IPBind ip expr) 
140        = do { ty <- newFlexiTyVarTy argTypeKind
141             ; ip_id <- newIP ip ty
142             ; expr' <- tcMonoExpr expr ty
143             ; return (ip_id, (IPBind (IPName ip_id) expr')) }
144 \end{code}
145
146 Note [Implicit parameter untouchables]
147 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
148 We add the type variables in the types of the implicit parameters
149 as untouchables, not so much because we really must not unify them,
150 but rather because we otherwise end up with constraints like this
151     Num alpha, Implic { wanted = alpha ~ Int }
152 The constraint solver solves alpha~Int by unification, but then
153 doesn't float that solved constraint out (it's not an unsolved 
154 wanted.  Result disaster: the (Num alpha) is again solved, this
155 time by defaulting.  No no no.
156
157 \begin{code}
158 tcValBinds :: TopLevelFlag 
159            -> HsValBinds Name -> TcM thing
160            -> TcM (HsValBinds TcId, thing) 
161
162 tcValBinds _ (ValBindsIn binds _) _
163   = pprPanic "tcValBinds" (ppr binds)
164
165 tcValBinds top_lvl (ValBindsOut binds sigs) thing_inside
166   = do  {       -- Typecheck the signature
167         ; let { prag_fn = mkPragFun sigs (foldr (unionBags . snd) emptyBag binds)
168               ; ty_sigs = filter isTypeLSig sigs
169               ; sig_fn  = mkSigFun ty_sigs }
170
171         ; poly_ids <- checkNoErrs (mapAndRecoverM tcTySig ty_sigs)
172                 -- No recovery from bad signatures, because the type sigs
173                 -- may bind type variables, so proceeding without them
174                 -- can lead to a cascade of errors
175                 -- ToDo: this means we fall over immediately if any type sig
176                 -- is wrong, which is over-conservative, see Trac bug #745
177
178                 -- Extend the envt right away with all 
179                 -- the Ids declared with type signatures
180         ; (binds', thing) <- tcExtendIdEnv poly_ids $
181                              tcBindGroups top_lvl sig_fn prag_fn 
182                                           binds thing_inside
183
184         ; return (ValBindsOut binds' sigs, thing) }
185
186 ------------------------
187 tcBindGroups :: TopLevelFlag -> SigFun -> PragFun
188              -> [(RecFlag, LHsBinds Name)] -> TcM thing
189              -> TcM ([(RecFlag, LHsBinds TcId)], thing)
190 -- Typecheck a whole lot of value bindings,
191 -- one strongly-connected component at a time
192 -- Here a "strongly connected component" has the strightforward
193 -- meaning of a group of bindings that mention each other, 
194 -- ignoring type signatures (that part comes later)
195
196 tcBindGroups _ _ _ [] thing_inside
197   = do  { thing <- thing_inside
198         ; return ([], thing) }
199
200 tcBindGroups top_lvl sig_fn prag_fn (group : groups) thing_inside
201   = do  { (group', (groups', thing))
202                 <- tc_group top_lvl sig_fn prag_fn group $ 
203                    tcBindGroups top_lvl sig_fn prag_fn groups thing_inside
204         ; return (group' ++ groups', thing) }
205
206 ------------------------
207 tc_group :: forall thing. 
208             TopLevelFlag -> SigFun -> PragFun
209          -> (RecFlag, LHsBinds Name) -> TcM thing
210          -> TcM ([(RecFlag, LHsBinds TcId)], thing)
211
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
215
216 tc_group 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 { (binds1, ids) <- tcPolyBinds top_lvl sig_fn prag_fn NonRecursive NonRecursive
221                                       (bagToList binds)
222        ; thing <- tcExtendIdEnv ids thing_inside
223        ; return ( [(NonRecursive, binds1)], thing) }
224
225 tc_group top_lvl sig_fn prag_fn (Recursive, binds) thing_inside
226   =     -- To maximise polymorphism (assumes -XRelaxedPolyRec), we do a new 
227         -- strongly-connected-component analysis, this time omitting 
228         -- any references to variables with type signatures.
229     do  { traceTc "tc_group rec" (pprLHsBinds binds)
230         ; (binds1, _ids, thing) <- go sccs
231              -- Here is where we should do bindInstsOfLocalFuns
232              -- if we start having Methods again
233         ; return ([(Recursive, binds1)], thing) }
234                 -- Rec them all together
235   where
236     sccs :: [SCC (LHsBind Name)]
237     sccs = stronglyConnCompFromEdgedVertices (mkEdges sig_fn binds)
238
239     go :: [SCC (LHsBind Name)] -> TcM (LHsBinds TcId, [TcId], thing)
240     go (scc:sccs) = do  { (binds1, ids1)        <- tc_scc scc
241                         ; (binds2, ids2, thing) <- tcExtendIdEnv ids1 $ go sccs
242                         ; return (binds1 `unionBags` binds2, ids1 ++ ids2, thing) }
243     go []         = do  { thing <- thing_inside; return (emptyBag, [], thing) }
244
245     tc_scc (AcyclicSCC bind) = tc_sub_group NonRecursive [bind]
246     tc_scc (CyclicSCC binds) = tc_sub_group Recursive    binds
247
248     tc_sub_group = tcPolyBinds top_lvl sig_fn prag_fn Recursive
249
250
251 ------------------------
252 {-
253 bindLocalInsts :: TopLevelFlag
254                -> TcM (LHsBinds TcId, [TcId],    a)
255                -> TcM (LHsBinds TcId, TcEvBinds, a)
256 bindLocalInsts top_lvl thing_inside
257   | isTopLevel top_lvl
258   = do { (binds, _, thing) <- thing_inside; return (binds, emptyBag, thing) }
259         -- For the top level don't bother with all this bindInstsOfLocalFuns stuff. 
260         -- All the top level things are rec'd together anyway, so it's fine to
261         -- leave them to the tcSimplifyTop, and quite a bit faster too
262
263   | otherwise   -- Nested case
264   = do  { ((binds, ids, thing), lie) <- getConstraints thing_inside
265         ; lie_binds <- bindLocalMethods lie ids
266         ; return (binds, lie_binds, thing) }
267 -}
268
269 ------------------------
270 mkEdges :: SigFun -> LHsBinds Name
271         -> [(LHsBind Name, BKey, [BKey])]
272
273 type BKey  = Int -- Just number off the bindings
274
275 mkEdges sig_fn binds
276   = [ (bind, key, [key | n <- nameSetToList (bind_fvs (unLoc bind)),
277                          Just key <- [lookupNameEnv key_map n], no_sig n ])
278     | (bind, key) <- keyd_binds
279     ]
280   where
281     no_sig :: Name -> Bool
282     no_sig n = isNothing (sig_fn n)
283
284     keyd_binds = bagToList binds `zip` [0::BKey ..]
285
286     key_map :: NameEnv BKey     -- Which binding it comes from
287     key_map = mkNameEnv [(bndr, key) | (L _ bind, key) <- keyd_binds
288                                      , bndr <- bindersOfHsBind bind ]
289
290 bindersOfHsBind :: HsBind Name -> [Name]
291 bindersOfHsBind (PatBind { pat_lhs = pat })  = collectPatBinders pat
292 bindersOfHsBind (FunBind { fun_id = L _ f }) = [f]
293 bindersOfHsBind (AbsBinds {})                = panic "bindersOfHsBind AbsBinds"
294 bindersOfHsBind (VarBind {})                 = panic "bindersOfHsBind VarBind"
295
296 ------------------------
297 tcPolyBinds :: TopLevelFlag -> SigFun -> PragFun
298             -> RecFlag       -- Whether the group is really recursive
299             -> RecFlag       -- Whether it's recursive after breaking
300                              -- dependencies based on type signatures
301             -> [LHsBind Name]
302             -> TcM (LHsBinds TcId, [TcId])
303
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
307 --
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
310 -- important.  
311 -- 
312 -- Knows nothing about the scope of the bindings
313
314 tcPolyBinds top_lvl sig_fn prag_fn rec_group rec_tc bind_list
315   = setSrcSpan loc                              $
316     recoverM (recoveryCode binder_names sig_fn) $ do 
317         -- Set up main recoer; take advantage of any type sigs
318
319     { traceTc "------------------------------------------------" empty
320     ; traceTc "Bindings for" (ppr binder_names)
321
322     ; tc_sig_fn <- tcInstSigs sig_fn binder_names
323
324     ; dflags <- getDOpts
325     ; let plan = decideGeneralisationPlan dflags top_lvl binder_names bind_list tc_sig_fn
326     ; traceTc "Generalisation plan" (ppr plan)
327     ; (binds, poly_ids) <- case plan of
328          NoGen         -> tcPolyNoGen tc_sig_fn prag_fn rec_tc bind_list
329          InferGen mono -> tcPolyInfer top_lvl mono tc_sig_fn prag_fn rec_tc bind_list
330          CheckGen sig  -> tcPolyCheck sig prag_fn rec_tc bind_list
331
332         -- Check whether strict bindings are ok
333         -- These must be non-recursive etc, and are not generalised
334         -- They desugar to a case expression in the end
335     ; checkStrictBinds top_lvl rec_group bind_list poly_ids
336
337     ; return (binds, poly_ids) }
338   where
339     binder_names = collectHsBindListBinders bind_list
340     loc = getLoc (head bind_list)
341          -- TODO: location a bit awkward, but the mbinds have been
342          --       dependency analysed and may no longer be adjacent
343
344 ------------------
345 tcPolyNoGen 
346   :: TcSigFun -> PragFun
347   -> RecFlag       -- Whether it's recursive after breaking
348                    -- dependencies based on type signatures
349   -> [LHsBind Name]
350   -> TcM (LHsBinds TcId, [TcId])
351 -- No generalisation whatsoever
352
353 tcPolyNoGen tc_sig_fn prag_fn rec_tc bind_list
354   = do { (binds', mono_infos) <- tcMonoBinds tc_sig_fn (LetGblBndr prag_fn) 
355                                              rec_tc bind_list
356        ; mono_ids' <- mapM tc_mono_info mono_infos
357        ; return (binds', mono_ids') }
358   where
359     tc_mono_info (name, _, mono_id)
360       = do { mono_ty' <- zonkTcTypeCarefully (idType mono_id)
361              -- Zonk, mainly to expose unboxed types to checkStrictBinds
362            ; let mono_id' = setIdType mono_id mono_ty'
363            ; _specs <- tcSpecPrags False mono_id' (prag_fn name)
364            ; return mono_id' }
365            -- NB: tcPrags generates error messages for
366            --     specialisation pragmas for non-overloaded sigs
367            -- Indeed that is why we call it here!
368            -- So we can safely ignore _specs
369
370 ------------------
371 tcPolyCheck :: TcSigInfo -> PragFun
372             -> RecFlag       -- Whether it's recursive after breaking
373                              -- dependencies based on type signatures
374             -> [LHsBind Name]
375             -> TcM (LHsBinds TcId, [TcId])
376 -- There is just one binding, 
377 --   it binds a single variable,
378 --   it has a signature,
379 tcPolyCheck sig@(TcSigInfo { sig_id = id, sig_tvs = tvs, sig_scoped = scoped
380                            , sig_theta = theta, sig_loc = loc })
381     prag_fn rec_tc bind_list
382   = do { ev_vars <- newEvVars theta
383
384        ; let skol_info = SigSkol (FunSigCtxt (idName id))
385        ; (ev_binds, (binds', [mono_info])) 
386             <- checkConstraints skol_info emptyVarSet tvs ev_vars $
387                tcExtendTyVarEnv2 (scoped `zip` mkTyVarTys tvs)    $
388                tcMonoBinds (\_ -> Just sig) LetLclBndr rec_tc bind_list
389
390        ; export <- mkExport prag_fn tvs theta mono_info
391
392        ; let (_, poly_id, _, _) = export
393              abs_bind = L loc $ AbsBinds 
394                         { abs_tvs = tvs
395                         , abs_ev_vars = ev_vars, abs_ev_binds = ev_binds
396                         , abs_exports = [export], abs_binds = binds' }
397        ; return (unitBag abs_bind, [poly_id]) }
398
399 ------------------
400 tcPolyInfer 
401   :: TopLevelFlag 
402   -> Bool         -- True <=> apply the monomorphism restriction
403   -> TcSigFun -> PragFun
404   -> RecFlag       -- Whether it's recursive after breaking
405                    -- dependencies based on type signatures
406   -> [LHsBind Name]
407   -> TcM (LHsBinds TcId, [TcId])
408 tcPolyInfer top_lvl mono sig_fn prag_fn rec_tc bind_list
409   = do { ((binds', mono_infos), wanted) 
410              <- getConstraints $
411                 tcMonoBinds sig_fn LetLclBndr rec_tc bind_list
412
413        ; unifyCtxts [sig | (_, Just sig, _) <- mono_infos] 
414
415        ; let get_tvs | isTopLevel top_lvl = tyVarsOfType  
416                      | otherwise          = exactTyVarsOfType
417                      -- See Note [Silly type synonym] in TcType
418              tau_tvs = foldr (unionVarSet . get_tvs . getMonoType) emptyVarSet mono_infos
419
420        ; (qtvs, givens, ev_binds) <- simplifyInfer mono tau_tvs wanted
421
422        ; exports <- mapM (mkExport prag_fn qtvs (map evVarPred givens))
423                     mono_infos
424
425        ; let poly_ids = [poly_id | (_, poly_id, _, _) <- exports]
426        ; traceTc "Binding:" (ppr (poly_ids `zip` map idType poly_ids))
427
428        ; loc <- getSrcSpanM
429        ; let abs_bind = L loc $ AbsBinds { abs_tvs = qtvs
430                                          , abs_ev_vars = givens, abs_ev_binds = ev_binds
431                                          , abs_exports = exports, abs_binds = binds' }
432
433        ; return (unitBag abs_bind, poly_ids)   -- poly_ids are guaranteed zonked by mkExport
434   }
435
436
437 --------------
438 mkExport :: PragFun -> [TyVar] -> TcThetaType
439          -> MonoBindInfo
440          -> TcM ([TyVar], Id, Id, TcSpecPrags)
441 -- mkExport generates exports with 
442 --      zonked type variables, 
443 --      zonked poly_ids
444 -- The former is just because no further unifications will change
445 -- the quantified type variables, so we can fix their final form
446 -- right now.
447 -- The latter is needed because the poly_ids are used to extend the
448 -- type environment; see the invariant on TcEnv.tcExtendIdEnv 
449
450 -- Pre-condition: the inferred_tvs are already zonked
451
452 mkExport prag_fn inferred_tvs theta
453          (poly_name, mb_sig, mono_id)
454   = do  { (tvs, poly_id) <- mk_poly_id mb_sig
455                 -- poly_id has a zonked type
456
457         ; poly_id' <- addInlinePrags poly_id prag_sigs
458
459         ; spec_prags <- tcSpecPrags (notNull theta) poly_id prag_sigs
460                 -- tcPrags requires a zonked poly_id
461
462         ; return (tvs, poly_id', mono_id, SpecPrags spec_prags) }
463   where
464     prag_sigs = prag_fn poly_name
465     poly_ty = mkSigmaTy inferred_tvs theta (idType mono_id)
466
467     mk_poly_id Nothing    = do { poly_ty' <- zonkTcTypeCarefully poly_ty
468                                ; return (inferred_tvs, mkLocalId poly_name poly_ty') }
469     mk_poly_id (Just sig) = do { tvs <- mapM zonk_tv (sig_tvs sig)
470                                ; return (tvs,  sig_id sig) }
471
472     zonk_tv tv = do { ty <- zonkTcTyVar tv; return (tcGetTyVar "mkExport" ty) }
473
474 ------------------------
475 type PragFun = Name -> [LSig Name]
476
477 mkPragFun :: [LSig Name] -> LHsBinds Name -> PragFun
478 mkPragFun sigs binds = \n -> lookupNameEnv prag_env n `orElse` []
479   where
480     prs = mapCatMaybes get_sig sigs
481
482     get_sig :: LSig Name -> Maybe (Located Name, LSig Name)
483     get_sig (L l (SpecSig nm ty inl)) = Just (nm, L l $ SpecSig  nm ty (add_arity nm inl))
484     get_sig (L l (InlineSig nm inl))  = Just (nm, L l $ InlineSig nm   (add_arity nm inl))
485     get_sig _                         = Nothing
486
487     add_arity (L _ n) inl_prag   -- Adjust inl_sat field to match visible arity of function
488       | Just ar <- lookupNameEnv ar_env n = inl_prag { inl_sat = Just ar }
489       | otherwise                         = inl_prag
490
491     prag_env :: NameEnv [LSig Name]
492     prag_env = foldl add emptyNameEnv prs
493     add env (L _ n,p) = extendNameEnv_Acc (:) singleton env n p
494
495     -- ar_env maps a local to the arity of its definition
496     ar_env :: NameEnv Arity
497     ar_env = foldrBag lhsBindArity emptyNameEnv binds
498
499 lhsBindArity :: LHsBind Name -> NameEnv Arity -> NameEnv Arity
500 lhsBindArity (L _ (FunBind { fun_id = id, fun_matches = ms })) env
501   = extendNameEnv env (unLoc id) (matchGroupArity ms)
502 lhsBindArity _ env = env        -- PatBind/VarBind
503
504 ------------------
505 tcSpecPrags :: Bool     -- True <=> function is overloaded
506             -> Id -> [LSig Name]
507             -> TcM [Located TcSpecPrag]
508 -- Add INLINE and SPECIALSE pragmas
509 --    INLINE prags are added to the (polymorphic) Id directly
510 --    SPECIALISE prags are passed to the desugarer via TcSpecPrags
511 -- Pre-condition: the poly_id is zonked
512 -- Reason: required by tcSubExp
513 tcSpecPrags is_overloaded_id poly_id prag_sigs
514   = do { unless (null spec_sigs || is_overloaded_id) warn_discarded_spec
515        ; unless (null bad_sigs) warn_discarded_sigs
516        ; mapM (wrapLocM tc_spec) spec_sigs }
517   where
518     spec_sigs = filter isSpecLSig prag_sigs
519     bad_sigs  = filter is_bad_sig prag_sigs
520     is_bad_sig s = not (isSpecLSig s || isInlineLSig s)
521
522     name      = idName poly_id
523     poly_ty   = idType poly_id
524     sig_ctxt  = FunSigCtxt name
525     origin    = SpecPragOrigin name
526     skol_info = SigSkol sig_ctxt
527
528     tc_spec prag@(SpecSig _ hs_ty inl) 
529       = addErrCtxt (spec_ctxt prag) $
530         do  { spec_ty <- tcHsSigType sig_ctxt hs_ty
531             ; wrap <- tcSubType origin skol_info poly_ty spec_ty
532             ; return (SpecPrag wrap inl) }
533     tc_spec sig = pprPanic "tcSpecPrag" (ppr sig)
534
535     warn_discarded_spec = warnPrags poly_id spec_sigs $
536                           ptext (sLit "SPECIALISE pragmas for non-overloaded function")
537     warn_discarded_sigs = warnPrags poly_id bad_sigs $
538                           ptext (sLit "Discarding unexpected pragmas for")
539
540     spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag)
541
542 --------------
543 -- If typechecking the binds fails, then return with each
544 -- signature-less binder given type (forall a.a), to minimise 
545 -- subsequent error messages
546 recoveryCode :: [Name] -> SigFun -> TcM (LHsBinds TcId, [Id])
547 recoveryCode binder_names sig_fn
548   = do  { traceTc "tcBindsWithSigs: error recovery" (ppr binder_names)
549         ; poly_ids <- mapM mk_dummy binder_names
550         ; return (emptyBag, poly_ids) }
551   where
552     mk_dummy name 
553         | isJust (sig_fn name) = tcLookupId name        -- Had signature; look it up
554         | otherwise            = return (mkLocalId name forall_a_a)    -- No signature
555
556 forall_a_a :: TcType
557 forall_a_a = mkForAllTy openAlphaTyVar (mkTyVarTy openAlphaTyVar)
558 \end{code}
559
560
561 %************************************************************************
562 %*                                                                      *
563 \subsection{tcMonoBind}
564 %*                                                                      *
565 %************************************************************************
566
567 @tcMonoBinds@ deals with a perhaps-recursive group of HsBinds.
568 The signatures have been dealt with already.
569
570 \begin{code}
571 tcMonoBinds :: TcSigFun -> LetBndrSpec 
572             -> RecFlag  -- Whether the binding is recursive for typechecking purposes
573                         -- i.e. the binders are mentioned in their RHSs, and
574                         --      we are not resuced by a type signature
575             -> [LHsBind Name]
576             -> TcM (LHsBinds TcId, [MonoBindInfo])
577
578 tcMonoBinds sig_fn no_gen is_rec
579            [ L b_loc (FunBind { fun_id = L nm_loc name, fun_infix = inf, 
580                                 fun_matches = matches, bind_fvs = fvs })]
581                              -- Single function binding, 
582   | NonRecursive <- is_rec   -- ...binder isn't mentioned in RHS
583   , Nothing <- sig_fn name   -- ...with no type signature
584   =     -- In this very special case we infer the type of the
585         -- right hand side first (it may have a higher-rank type)
586         -- and *then* make the monomorphic Id for the LHS
587         -- e.g.         f = \(x::forall a. a->a) -> <body>
588         --      We want to infer a higher-rank type for f
589     setSrcSpan b_loc    $
590     do  { ((co_fn, matches'), rhs_ty) <- tcInfer (tcMatchesFun name inf matches)
591
592         ; mono_id <- newNoSigLetBndr no_gen name rhs_ty
593         ; return (unitBag (L b_loc (FunBind { fun_id = L nm_loc mono_id, fun_infix = inf,
594                                               fun_matches = matches', bind_fvs = fvs,
595                                               fun_co_fn = co_fn, fun_tick = Nothing })),
596                   [(name, Nothing, mono_id)]) }
597
598 tcMonoBinds sig_fn no_gen _ binds
599   = do  { tc_binds <- mapM (wrapLocM (tcLhs sig_fn no_gen)) binds
600
601         -- Bring the monomorphic Ids, into scope for the RHSs
602         ; let mono_info  = getMonoBindInfo tc_binds
603               rhs_id_env = [(name,mono_id) | (name, Nothing, mono_id) <- mono_info]
604                     -- A monomorphic binding for each term variable that lacks 
605                     -- a type sig.  (Ones with a sig are already in scope.)
606
607         ; binds' <- tcExtendIdEnv2 rhs_id_env $ do
608                     traceTc "tcMonoBinds" $  vcat [ ppr n <+> ppr id <+> ppr (idType id) 
609                                                   | (n,id) <- rhs_id_env]
610                     mapM (wrapLocM tcRhs) tc_binds
611         ; return (listToBag binds', mono_info) }
612
613 ------------------------
614 -- tcLhs typechecks the LHS of the bindings, to construct the environment in which
615 -- we typecheck the RHSs.  Basically what we are doing is this: for each binder:
616 --      if there's a signature for it, use the instantiated signature type
617 --      otherwise invent a type variable
618 -- You see that quite directly in the FunBind case.
619 -- 
620 -- But there's a complication for pattern bindings:
621 --      data T = MkT (forall a. a->a)
622 --      MkT f = e
623 -- Here we can guess a type variable for the entire LHS (which will be refined to T)
624 -- but we want to get (f::forall a. a->a) as the RHS environment.
625 -- The simplest way to do this is to typecheck the pattern, and then look up the
626 -- bound mono-ids.  Then we want to retain the typechecked pattern to avoid re-doing
627 -- it; hence the TcMonoBind data type in which the LHS is done but the RHS isn't
628
629 data TcMonoBind         -- Half completed; LHS done, RHS not done
630   = TcFunBind  MonoBindInfo  SrcSpan Bool (MatchGroup Name) 
631   | TcPatBind [MonoBindInfo] (LPat TcId) (GRHSs Name) TcSigmaType
632
633 type MonoBindInfo = (Name, Maybe TcSigInfo, TcId)
634         -- Type signature (if any), and
635         -- the monomorphic bound things
636
637 getMonoType :: MonoBindInfo -> TcTauType
638 getMonoType (_,_,mono_id) = idType mono_id
639
640 tcLhs :: TcSigFun -> LetBndrSpec -> HsBind Name -> TcM TcMonoBind
641 tcLhs sig_fn no_gen (FunBind { fun_id = L nm_loc name, fun_infix = inf, fun_matches = matches })
642   | Just sig <- sig_fn name
643   = do  { mono_id <- newSigLetBndr no_gen name sig
644         ; return (TcFunBind (name, Just sig, mono_id) nm_loc inf matches) }
645   | otherwise
646   = do  { mono_ty <- newFlexiTyVarTy argTypeKind
647         ; mono_id <- newNoSigLetBndr no_gen name mono_ty
648         ; return (TcFunBind (name, Nothing, mono_id) nm_loc inf matches) }
649
650 tcLhs sig_fn no_gen (PatBind { pat_lhs = pat, pat_rhs = grhss })
651   = do  { let tc_pat exp_ty = tcLetPat sig_fn no_gen pat exp_ty $
652                               mapM lookup_info (collectPatBinders pat)
653
654                 -- After typechecking the pattern, look up the binder
655                 -- names, which the pattern has brought into scope.
656               lookup_info :: Name -> TcM MonoBindInfo
657               lookup_info name = do { mono_id <- tcLookupId name
658                                     ; return (name, sig_fn name, mono_id) }
659
660         ; ((pat', infos), pat_ty) <- addErrCtxt (patMonoBindsCtxt pat grhss) $
661                                      tcInfer tc_pat
662
663         ; return (TcPatBind infos pat' grhss pat_ty) }
664
665 tcLhs _ _ other_bind = pprPanic "tcLhs" (ppr other_bind)
666         -- AbsBind, VarBind impossible
667
668 -------------------
669 tcRhs :: TcMonoBind -> TcM (HsBind TcId)
670 -- When we are doing pattern bindings, or multiple function bindings at a time
671 -- we *don't* bring any scoped type variables into scope
672 -- Wny not?  They are not completely rigid.
673 -- That's why we have the special case for a single FunBind in tcMonoBinds
674 tcRhs (TcFunBind (_,_,mono_id) loc inf matches)
675   = do  { (co_fn, matches') <- tcMatchesFun (idName mono_id) inf 
676                                             matches (idType mono_id)
677         ; return (FunBind { fun_id = L loc mono_id, fun_infix = inf
678                           , fun_matches = matches'
679                           , fun_co_fn = co_fn 
680                           , bind_fvs = placeHolderNames, fun_tick = Nothing }) }
681
682 tcRhs (TcPatBind _ pat' grhss pat_ty)
683   = do  { grhss' <- addErrCtxt (patMonoBindsCtxt pat' grhss) $
684                     tcGRHSsPat grhss pat_ty
685         ; return (PatBind { pat_lhs = pat', pat_rhs = grhss', pat_rhs_ty = pat_ty 
686                           , bind_fvs = placeHolderNames }) }
687
688
689 ---------------------
690 getMonoBindInfo :: [Located TcMonoBind] -> [MonoBindInfo]
691 getMonoBindInfo tc_binds
692   = foldr (get_info . unLoc) [] tc_binds
693   where
694     get_info (TcFunBind info _ _ _)  rest = info : rest
695     get_info (TcPatBind infos _ _ _) rest = infos ++ rest
696 \end{code}
697
698
699 %************************************************************************
700 %*                                                                      *
701                 Generalisation
702 %*                                                                      *
703 %************************************************************************
704
705 unifyCtxts checks that all the signature contexts are the same
706 The type signatures on a mutually-recursive group of definitions
707 must all have the same context (or none).
708
709 The trick here is that all the signatures should have the same
710 context, and we want to share type variables for that context, so that
711 all the right hand sides agree a common vocabulary for their type
712 constraints
713
714 We unify them because, with polymorphic recursion, their types
715 might not otherwise be related.  This is a rather subtle issue.
716
717 \begin{code}
718 unifyCtxts :: [TcSigInfo] -> TcM ()
719 -- Post-condition: the returned Insts are full zonked
720 unifyCtxts [] = return ()
721 unifyCtxts (sig1 : sigs)
722   = do  { traceTc "unifyCtxts" (ppr (sig1 : sigs))
723         ; mapM_ unify_ctxt sigs }
724   where
725     theta1 = sig_theta sig1
726     unify_ctxt :: TcSigInfo -> TcM ()
727     unify_ctxt sig@(TcSigInfo { sig_theta = theta })
728         = setSrcSpan (sig_loc sig)                      $
729           addErrCtxt (sigContextsCtxt sig1 sig)         $
730           do { cois <- unifyTheta theta1 theta
731              ; -- Check whether all coercions are identity coercions
732                -- That can happen if we have, say
733                --         f :: C [a]   => ...
734                --         g :: C (F a) => ...
735                -- where F is a type function and (F a ~ [a])
736                -- Then unification might succeed with a coercion.  But it's much
737                -- much simpler to require that such signatures have identical contexts
738                checkTc (all isIdentityCoI cois)
739                        (ptext (sLit "Mutually dependent functions have syntactically distinct contexts"))
740              }
741 \end{code}
742
743
744 @getTyVarsToGen@ decides what type variables to generalise over.
745
746 For a "restricted group" -- see the monomorphism restriction
747 for a definition -- we bind no dictionaries, and
748 remove from tyvars_to_gen any constrained type variables
749
750 *Don't* simplify dicts at this point, because we aren't going
751 to generalise over these dicts.  By the time we do simplify them
752 we may well know more.  For example (this actually came up)
753         f :: Array Int Int
754         f x = array ... xs where xs = [1,2,3,4,5]
755 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
756 stuff.  If we simplify only at the f-binding (not the xs-binding)
757 we'll know that the literals are all Ints, and we can just produce
758 Int literals!
759
760 Find all the type variables involved in overloading, the
761 "constrained_tyvars".  These are the ones we *aren't* going to
762 generalise.  We must be careful about doing this:
763
764  (a) If we fail to generalise a tyvar which is not actually
765         constrained, then it will never, ever get bound, and lands
766         up printed out in interface files!  Notorious example:
767                 instance Eq a => Eq (Foo a b) where ..
768         Here, b is not constrained, even though it looks as if it is.
769         Another, more common, example is when there's a Method inst in
770         the LIE, whose type might very well involve non-overloaded
771         type variables.
772   [NOTE: Jan 2001: I don't understand the problem here so I'm doing 
773         the simple thing instead]
774
775  (b) On the other hand, we mustn't generalise tyvars which are constrained,
776         because we are going to pass on out the unmodified LIE, with those
777         tyvars in it.  They won't be in scope if we've generalised them.
778
779 So we are careful, and do a complete simplification just to find the
780 constrained tyvars. We don't use any of the results, except to
781 find which tyvars are constrained.
782
783 Note [Polymorphic recursion]
784 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
785 The game plan for polymorphic recursion in the code above is 
786
787         * Bind any variable for which we have a type signature
788           to an Id with a polymorphic type.  Then when type-checking 
789           the RHSs we'll make a full polymorphic call.
790
791 This fine, but if you aren't a bit careful you end up with a horrendous
792 amount of partial application and (worse) a huge space leak. For example:
793
794         f :: Eq a => [a] -> [a]
795         f xs = ...f...
796
797 If we don't take care, after typechecking we get
798
799         f = /\a -> \d::Eq a -> let f' = f a d
800                                in
801                                \ys:[a] -> ...f'...
802
803 Notice the the stupid construction of (f a d), which is of course
804 identical to the function we're executing.  In this case, the
805 polymorphic recursion isn't being used (but that's a very common case).
806 This can lead to a massive space leak, from the following top-level defn
807 (post-typechecking)
808
809         ff :: [Int] -> [Int]
810         ff = f Int dEqInt
811
812 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
813 f' is another thunk which evaluates to the same thing... and you end
814 up with a chain of identical values all hung onto by the CAF ff.
815
816         ff = f Int dEqInt
817
818            = let f' = f Int dEqInt in \ys. ...f'...
819
820            = let f' = let f' = f Int dEqInt in \ys. ...f'...
821                       in \ys. ...f'...
822
823 Etc.
824
825 NOTE: a bit of arity anaysis would push the (f a d) inside the (\ys...),
826 which would make the space leak go away in this case
827
828 Solution: when typechecking the RHSs we always have in hand the
829 *monomorphic* Ids for each binding.  So we just need to make sure that
830 if (Method f a d) shows up in the constraints emerging from (...f...)
831 we just use the monomorphic Id.  We achieve this by adding monomorphic Ids
832 to the "givens" when simplifying constraints.  That's what the "lies_avail"
833 is doing.
834
835 Then we get
836
837         f = /\a -> \d::Eq a -> letrec
838                                  fm = \ys:[a] -> ...fm...
839                                in
840                                fm
841
842 %************************************************************************
843 %*                                                                      *
844                 Signatures
845 %*                                                                      *
846 %************************************************************************
847
848 Type signatures are tricky.  See Note [Signature skolems] in TcType
849
850 @tcSigs@ checks the signatures for validity, and returns a list of
851 {\em freshly-instantiated} signatures.  That is, the types are already
852 split up, and have fresh type variables installed.  All non-type-signature
853 "RenamedSigs" are ignored.
854
855 The @TcSigInfo@ contains @TcTypes@ because they are unified with
856 the variable's type, and after that checked to see whether they've
857 been instantiated.
858
859 Note [Scoped tyvars]
860 ~~~~~~~~~~~~~~~~~~~~
861 The -XScopedTypeVariables flag brings lexically-scoped type variables
862 into scope for any explicitly forall-quantified type variables:
863         f :: forall a. a -> a
864         f x = e
865 Then 'a' is in scope inside 'e'.
866
867 However, we do *not* support this 
868   - For pattern bindings e.g
869         f :: forall a. a->a
870         (f,g) = e
871
872   - For multiple function bindings, unless Opt_RelaxedPolyRec is on
873         f :: forall a. a -> a
874         f = g
875         g :: forall b. b -> b
876         g = ...f...
877     Reason: we use mutable variables for 'a' and 'b', since they may
878     unify to each other, and that means the scoped type variable would
879     not stand for a completely rigid variable.
880
881     Currently, we simply make Opt_ScopedTypeVariables imply Opt_RelaxedPolyRec
882
883
884 Note [More instantiated than scoped]
885 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
886 There may be more instantiated type variables than lexically-scoped 
887 ones.  For example:
888         type T a = forall b. b -> (a,b)
889         f :: forall c. T c
890 Here, the signature for f will have one scoped type variable, c,
891 but two instantiated type variables, c' and b'.  
892
893 We assume that the scoped ones are at the *front* of sig_tvs,
894 and remember the names from the original HsForAllTy in the TcSigFun.
895
896 Note [Signature skolems]
897 ~~~~~~~~~~~~~~~~~~~~~~~~
898 When instantiating a type signature, we do so with either skolems or
899 SigTv meta-type variables depending on the use_skols boolean.  This
900 variable is set True when we are typechecking a single function
901 binding; and False for pattern bindings and a group of several
902 function bindings.
903
904 Reason: in the latter cases, the "skolems" can be unified together, 
905         so they aren't properly rigid in the type-refinement sense.
906 NB: unless we are doing H98, each function with a sig will be done
907     separately, even if it's mutually recursive, so use_skols will be True
908
909
910 Note [Only scoped tyvars are in the TyVarEnv]
911 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
912 We are careful to keep only the *lexically scoped* type variables in
913 the type environment.  Why?  After all, the renamer has ensured
914 that only legal occurrences occur, so we could put all type variables
915 into the type env.
916
917 But we want to check that two distinct lexically scoped type variables
918 do not map to the same internal type variable.  So we need to know which
919 the lexically-scoped ones are... and at the moment we do that by putting
920 only the lexically scoped ones into the environment.
921
922 Note [Instantiate sig with fresh variables]
923 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
924 It's vital to instantiate a type signature with fresh variables.
925 For example:
926       type T = forall a. [a] -> [a]
927       f :: T; 
928       f = g where { g :: T; g = <rhs> }
929
930  We must not use the same 'a' from the defn of T at both places!!
931 (Instantiation is only necessary because of type synonyms.  Otherwise,
932 it's all cool; each signature has distinct type variables from the renamer.)
933
934 \begin{code}
935 type SigFun = Name -> Maybe ([Name], SrcSpan)
936          -- Maps a let-binder to the list of
937          -- type variables brought into scope
938          -- by its type signature, plus location
939          -- Nothing => no type signature
940
941 mkSigFun :: [LSig Name] -> SigFun
942 -- Search for a particular type signature
943 -- Precondition: the sigs are all type sigs
944 -- Precondition: no duplicates
945 mkSigFun sigs = lookupNameEnv env
946   where
947     env = mkNameEnv (mapCatMaybes mk_pair sigs)
948     mk_pair (L loc (TypeSig (L _ name) lhs_ty)) = Just (name, (hsExplicitTvs lhs_ty, loc))
949     mk_pair (L loc (IdSig id))                  = Just (idName id, ([], loc))
950     mk_pair _                                   = Nothing    
951         -- The scoped names are the ones explicitly mentioned
952         -- in the HsForAll.  (There may be more in sigma_ty, because
953         -- of nested type synonyms.  See Note [More instantiated than scoped].)
954         -- See Note [Only scoped tyvars are in the TyVarEnv]
955 \end{code}
956
957 \begin{code}
958 tcTySig :: LSig Name -> TcM TcId
959 tcTySig (L span (TypeSig (L _ name) ty))
960   = setSrcSpan span             $
961     do  { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
962         ; return (mkLocalId name sigma_ty) }
963 tcTySig (L _ (IdSig id))
964   = return id
965 tcTySig s = pprPanic "tcTySig" (ppr s)
966
967 -------------------
968 tcInstSigs :: SigFun -> [Name] -> TcM TcSigFun
969 tcInstSigs sig_fn bndrs
970   = do { prs <- mapMaybeM (tcInstSig sig_fn use_skols) bndrs
971        ; return (lookupNameEnv (mkNameEnv prs)) }
972   where
973     use_skols = isSingleton bndrs       -- See Note [Signature skolems]
974
975 tcInstSig :: SigFun -> Bool -> Name -> TcM (Maybe (Name, TcSigInfo))
976 -- For use_skols :: Bool see Note [Signature skolems]
977 --
978 -- We must instantiate with fresh uniques, 
979 -- (see Note [Instantiate sig with fresh variables])
980 -- although we keep the same print-name.
981
982 tcInstSig sig_fn use_skols name
983   | Just (scoped_tvs, loc) <- sig_fn name
984   = do  { poly_id <- tcLookupId name    -- Cannot fail; the poly ids are put into 
985                                         -- scope when starting the binding group
986         ; (tvs, theta, tau) <- tcInstSigType use_skols name (idType poly_id)
987         ; let sig = TcSigInfo { sig_id = poly_id
988                               , sig_scoped = scoped_tvs
989                               , sig_tvs = tvs, sig_theta = theta, sig_tau = tau
990                               , sig_loc = loc }
991         ; return (Just (name, sig)) } 
992   | otherwise
993   = return Nothing
994
995 -------------------------------
996 data GeneralisationPlan 
997   = NoGen               -- No generalisation, no AbsBinds
998   | InferGen Bool       -- Implicit generalisation; there is an AbsBinds
999                         --   True <=> apply the MR; generalise only unconstrained type vars
1000   | CheckGen TcSigInfo  -- Explicit generalisation; there is an AbsBinds
1001
1002 -- A consequence of the no-AbsBinds choice (NoGen) is that there is
1003 -- no "polymorphic Id" and "monmomorphic Id"; there is just the one
1004
1005 instance Outputable GeneralisationPlan where
1006   ppr NoGen        = ptext (sLit "NoGen")
1007   ppr (InferGen b) = ptext (sLit "InferGen") <+> ppr b
1008   ppr (CheckGen s) = ptext (sLit "CheckGen") <+> ppr s
1009
1010 decideGeneralisationPlan 
1011    :: DynFlags -> TopLevelFlag -> [Name] -> [LHsBind Name] -> TcSigFun -> GeneralisationPlan
1012 decideGeneralisationPlan dflags top_lvl _bndrs binds sig_fn
1013   | mono_pat_binds                         = NoGen
1014   | Just sig <- one_funbind_with_sig binds = if null (sig_tvs sig) && null (sig_theta sig)
1015                                              then NoGen       -- Optimise common case
1016                                              else CheckGen sig
1017   | (xopt Opt_MonoLocalBinds dflags 
1018       && isNotTopLevel top_lvl)            = NoGen
1019   | otherwise                              = InferGen mono_restriction
1020
1021   where
1022     mono_pat_binds = xopt Opt_MonoPatBinds dflags 
1023                   && any (is_pat_bind . unLoc) binds
1024
1025     mono_restriction = xopt Opt_MonomorphismRestriction dflags 
1026                     && any (restricted . unLoc) binds
1027
1028     no_sig n = isNothing (sig_fn n)
1029
1030     -- With OutsideIn, all nested bindings are monomorphic
1031     -- except a single function binding with a signature
1032     one_funbind_with_sig [L _ FunBind { fun_id = v }] = sig_fn (unLoc v)
1033     one_funbind_with_sig _                            = Nothing
1034
1035     -- The Haskell 98 monomorphism resetriction
1036     restricted (PatBind {})                              = True
1037     restricted (VarBind { var_id = v })                  = no_sig v
1038     restricted (FunBind { fun_id = v, fun_matches = m }) = restricted_match m
1039                                                            && no_sig (unLoc v)
1040     restricted (AbsBinds {}) = panic "isRestrictedGroup/unrestricted AbsBinds"
1041
1042     restricted_match (MatchGroup (L _ (Match [] _ _) : _) _) = True
1043     restricted_match _                                       = False
1044         -- No args => like a pattern binding
1045         -- Some args => a function binding
1046
1047     is_pat_bind (PatBind {}) = True
1048     is_pat_bind _            = False
1049
1050 -------------------
1051 checkStrictBinds :: TopLevelFlag -> RecFlag
1052                  -> [LHsBind Name] -> [Id]
1053                  -> TcM ()
1054 -- Check that non-overloaded unlifted bindings are
1055 --      a) non-recursive,
1056 --      b) not top level, 
1057 --      c) not a multiple-binding group (more or less implied by (a))
1058
1059 checkStrictBinds top_lvl rec_group binds poly_ids
1060   | unlifted || bang_pat
1061   = do  { checkTc (isNotTopLevel top_lvl)
1062                   (strictBindErr "Top-level" unlifted binds)
1063         ; checkTc (isNonRec rec_group)
1064                   (strictBindErr "Recursive" unlifted binds)
1065         ; checkTc (isSingleton binds)
1066                   (strictBindErr "Multiple" unlifted binds) 
1067         -- This should be a checkTc, not a warnTc, but as of GHC 6.11
1068         -- the versions of alex and happy available have non-conforming
1069         -- templates, so the GHC build fails if it's an error:
1070         ; warnUnlifted <- doptM Opt_WarnLazyUnliftedBindings
1071         ; warnTc (warnUnlifted && not bang_pat)
1072                  (unliftedMustBeBang binds) }
1073   | otherwise
1074   = return ()
1075   where
1076     unlifted = any is_unlifted poly_ids
1077     bang_pat = any (isBangHsBind . unLoc) binds
1078     is_unlifted id = case tcSplitForAllTys (idType id) of
1079                        (_, rho) -> isUnLiftedType rho
1080
1081 unliftedMustBeBang :: [LHsBind Name] -> SDoc
1082 unliftedMustBeBang binds
1083   = hang (text "Bindings containing unlifted types should use an outermost bang pattern:")
1084        2 (pprBindList binds)
1085
1086 strictBindErr :: String -> Bool -> [LHsBind Name] -> SDoc
1087 strictBindErr flavour unlifted binds
1088   = hang (text flavour <+> msg <+> ptext (sLit "aren't allowed:")) 
1089        2 (pprBindList binds)
1090   where
1091     msg | unlifted  = ptext (sLit "bindings for unlifted types")
1092         | otherwise = ptext (sLit "bang-pattern bindings")
1093
1094 pprBindList :: [LHsBind Name] -> SDoc
1095 pprBindList binds = vcat (map ppr binds)
1096 \end{code}
1097
1098
1099 %************************************************************************
1100 %*                                                                      *
1101 \subsection[TcBinds-errors]{Error contexts and messages}
1102 %*                                                                      *
1103 %************************************************************************
1104
1105
1106 \begin{code}
1107 -- This one is called on LHS, when pat and grhss are both Name 
1108 -- and on RHS, when pat is TcId and grhss is still Name
1109 patMonoBindsCtxt :: OutputableBndr id => LPat id -> GRHSs Name -> SDoc
1110 patMonoBindsCtxt pat grhss
1111   = hang (ptext (sLit "In a pattern binding:")) 2 (pprPatBind pat grhss)
1112
1113 -----------------------------------------------
1114 sigContextsCtxt :: TcSigInfo -> TcSigInfo -> SDoc
1115 sigContextsCtxt sig1 sig2
1116   = vcat [ptext (sLit "When matching the contexts of the signatures for"), 
1117           nest 2 (vcat [ppr id1 <+> dcolon <+> ppr (idType id1),
1118                         ppr id2 <+> dcolon <+> ppr (idType id2)]),
1119           ptext (sLit "The signature contexts in a mutually recursive group should all be identical")]
1120   where
1121     id1 = sig_id sig1
1122     id2 = sig_id sig2
1123 \end{code}