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