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