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