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