Improve the handling of default methods
[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, tcMonoBinds, tcPolyBinds,
10                  TcPragFun, tcPrags, mkPragFun, 
11                  TcSigInfo(..), TcSigFun, mkTcSigFun,
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 Inst
22 import TcEnv
23 import TcUnify
24 import TcSimplify
25 import TcHsType
26 import TcPat
27 import TcMType
28 import TcType
29 import Coercion
30 import VarEnv
31 import TysPrim
32 import Id
33 import Var
34 import Name
35 import NameSet
36 import NameEnv
37 import VarSet
38 import SrcLoc
39 import Bag
40 import ErrUtils
41 import Digraph
42 import Maybes
43 import Util
44 import BasicTypes
45 import Outputable
46 import FastString
47
48 import Data.List( partition )
49 import Control.Monad
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 -> TcM (LHsBinds TcId, TcLclEnv)
86         -- Note: returning the TcLclEnv is more than we really
87         --       want.  The bit we care about is the local bindings
88         --       and the free type variables thereof
89 tcTopBinds binds
90   = do  { (ValBindsOut prs _, env) <- tcValBinds TopLevel binds getLclEnv
91         ; return (foldr (unionBags . snd) emptyBag prs, env) }
92         -- The top level bindings are flattened into a giant 
93         -- implicitly-mutually-recursive LHsBinds
94
95 tcHsBootSigs :: HsValBinds Name -> TcM [Id]
96 -- A hs-boot file has only one BindGroup, and it only has type
97 -- signatures in it.  The renamer checked all this
98 tcHsBootSigs (ValBindsOut binds sigs)
99   = do  { checkTc (null binds) badBootDeclErr
100         ; mapM (addLocM tc_boot_sig) (filter isTypeLSig sigs) }
101   where
102     tc_boot_sig (TypeSig (L _ name) ty)
103       = do { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
104            ; return (mkVanillaGlobal name sigma_ty) }
105         -- Notice that we make GlobalIds, not LocalIds
106     tc_boot_sig s = pprPanic "tcHsBootSigs/tc_boot_sig" (ppr s)
107 tcHsBootSigs groups = pprPanic "tcHsBootSigs" (ppr groups)
108
109 badBootDeclErr :: Message
110 badBootDeclErr = ptext (sLit "Illegal declarations in an hs-boot file")
111
112 ------------------------
113 tcLocalBinds :: HsLocalBinds Name -> TcM thing
114              -> TcM (HsLocalBinds TcId, thing)
115
116 tcLocalBinds EmptyLocalBinds thing_inside 
117   = do  { thing <- thing_inside
118         ; return (EmptyLocalBinds, thing) }
119
120 tcLocalBinds (HsValBinds binds) thing_inside
121   = do  { (binds', thing) <- tcValBinds NotTopLevel binds thing_inside
122         ; return (HsValBinds binds', thing) }
123
124 tcLocalBinds (HsIPBinds (IPBinds ip_binds _)) thing_inside
125   = do  { (thing, lie) <- getLIE thing_inside
126         ; (avail_ips, ip_binds') <- mapAndUnzipM (wrapLocSndM tc_ip_bind) ip_binds
127
128         -- If the binding binds ?x = E, we  must now 
129         -- discharge any ?x constraints in expr_lie
130         ; dict_binds <- tcSimplifyIPs avail_ips lie
131         ; return (HsIPBinds (IPBinds ip_binds' dict_binds), thing) }
132   where
133         -- I wonder if we should do these one at at time
134         -- Consider     ?x = 4
135         --              ?y = ?x + 1
136     tc_ip_bind (IPBind ip expr) = do
137         ty <- newFlexiTyVarTy argTypeKind
138         (ip', ip_inst) <- newIPDict (IPBindOrigin ip) ip ty
139         expr' <- tcMonoExpr expr ty
140         return (ip_inst, (IPBind ip' expr'))
141
142 ------------------------
143 tcValBinds :: TopLevelFlag 
144            -> HsValBinds Name -> TcM thing
145            -> TcM (HsValBinds TcId, thing) 
146
147 tcValBinds _ (ValBindsIn binds _) _
148   = pprPanic "tcValBinds" (ppr binds)
149
150 tcValBinds top_lvl (ValBindsOut binds sigs) thing_inside
151   = do  {       -- Typecheck the signature
152         ; let { prag_fn = mkPragFun sigs (foldr (unionBags . snd) emptyBag binds)
153               ; ty_sigs = filter isTypeLSig sigs
154               ; sig_fn  = mkTcSigFun ty_sigs }
155
156         ; poly_ids <- checkNoErrs (mapAndRecoverM tcTySig ty_sigs)
157                 -- No recovery from bad signatures, because the type sigs
158                 -- may bind type variables, so proceeding without them
159                 -- can lead to a cascade of errors
160                 -- ToDo: this means we fall over immediately if any type sig
161                 -- is wrong, which is over-conservative, see Trac bug #745
162
163                 -- Extend the envt right away with all 
164                 -- the Ids declared with type signatures
165         ; poly_rec <- doptM Opt_RelaxedPolyRec
166         ; (binds', thing) <- tcExtendIdEnv poly_ids $
167                              tcBindGroups poly_rec top_lvl sig_fn prag_fn 
168                                           binds thing_inside
169
170         ; return (ValBindsOut binds' sigs, thing) }
171
172 ------------------------
173 tcBindGroups :: Bool -> TopLevelFlag -> TcSigFun -> TcPragFun
174              -> [(RecFlag, LHsBinds Name)] -> TcM thing
175              -> TcM ([(RecFlag, LHsBinds TcId)], thing)
176 -- Typecheck a whole lot of value bindings,
177 -- one strongly-connected component at a time
178 -- Here a "strongly connected component" has the strightforward
179 -- meaning of a group of bindings that mention each other, 
180 -- ignoring type signatures (that part comes later)
181
182 tcBindGroups _ _ _ _ [] thing_inside
183   = do  { thing <- thing_inside
184         ; return ([], thing) }
185
186 tcBindGroups poly_rec top_lvl sig_fn prag_fn (group : groups) thing_inside
187   = do  { (group', (groups', thing))
188                 <- tc_group poly_rec top_lvl sig_fn prag_fn group $ 
189                    tcBindGroups poly_rec top_lvl sig_fn prag_fn groups thing_inside
190         ; return (group' ++ groups', thing) }
191
192 ------------------------
193 tc_group :: Bool -> TopLevelFlag -> TcSigFun -> TcPragFun
194          -> (RecFlag, LHsBinds Name) -> TcM thing
195          -> TcM ([(RecFlag, LHsBinds TcId)], thing)
196
197 -- Typecheck one strongly-connected component of the original program.
198 -- We get a list of groups back, because there may 
199 -- be specialisations etc as well
200
201 tc_group _ top_lvl sig_fn prag_fn (NonRecursive, binds) thing_inside
202         -- A single non-recursive binding
203         -- We want to keep non-recursive things non-recursive
204         -- so that we desugar unlifted bindings correctly
205  =  do  { (binds1, lie_binds, thing) <- tc_haskell98 top_lvl sig_fn prag_fn 
206                                                      NonRecursive binds thing_inside
207         ; return ( [(NonRecursive, unitBag b) | b <- bagToList binds1]
208                      ++ [(Recursive, lie_binds)]  -- TcDictBinds have scrambled dependency order
209                  , thing) }
210
211 tc_group poly_rec top_lvl sig_fn prag_fn (Recursive, binds) thing_inside
212   | not poly_rec        -- Recursive group, normal Haskell 98 route
213   = do  { (binds1, lie_binds, thing) <- tc_haskell98 top_lvl sig_fn prag_fn 
214                                                      Recursive binds thing_inside
215         ; return ([(Recursive, binds1 `unionBags` lie_binds)], thing) }
216
217   | otherwise           -- Recursive group, with -XRelaxedPolyRec
218   =     -- To maximise polymorphism (with -XRelaxedPolyRec), we do a new 
219         -- strongly-connected-component analysis, this time omitting 
220         -- any references to variables with type signatures.
221         --
222         -- Notice that the bindInsts thing covers *all* the bindings in
223         -- the original group at once; an earlier one may use a later one!
224     do  { traceTc (text "tc_group rec" <+> pprLHsBinds binds)
225         ; (binds1,lie_binds,thing) <- bindLocalInsts top_lvl $
226                             go (stronglyConnCompFromEdgedVertices (mkEdges sig_fn binds))
227         ; return ([(Recursive, binds1 `unionBags` lie_binds)], thing) }
228                 -- Rec them all together
229   where
230 --  go :: SCC (LHsBind Name) -> TcM (LHsBinds TcId, [TcId], thing)
231     go (scc:sccs) = do  { (binds1, ids1) <- tc_scc scc
232                         ; (binds2, ids2, thing) <- tcExtendIdEnv ids1 $ go sccs
233                         ; return (binds1 `unionBags` binds2, ids1 ++ ids2, thing) }
234     go []         = do  { thing <- thing_inside; return (emptyBag, [], thing) }
235
236     tc_scc (AcyclicSCC bind) = tc_sub_group NonRecursive (unitBag bind)
237     tc_scc (CyclicSCC binds) = tc_sub_group Recursive    (listToBag binds)
238
239     tc_sub_group = tcPolyBinds top_lvl sig_fn prag_fn Recursive
240
241 tc_haskell98 :: TopLevelFlag -> TcSigFun -> TcPragFun -> RecFlag
242              -> LHsBinds Name -> TcM a -> TcM (LHsBinds TcId, TcDictBinds, a)
243 tc_haskell98 top_lvl sig_fn prag_fn rec_flag binds thing_inside
244   = bindLocalInsts top_lvl $ 
245     do { (binds1, ids) <- tcPolyBinds top_lvl sig_fn prag_fn rec_flag rec_flag binds
246        ; thing <- tcExtendIdEnv ids thing_inside
247        ; return (binds1, ids, thing) }
248
249 ------------------------
250 bindLocalInsts :: TopLevelFlag
251                -> TcM (LHsBinds TcId, [TcId],      a)
252                -> TcM (LHsBinds TcId, TcDictBinds, a)
253 bindLocalInsts top_lvl thing_inside
254   | isTopLevel top_lvl
255   = do { (binds, _, thing) <- thing_inside; return (binds, emptyBag, thing) }
256         -- For the top level don't bother with all this bindInstsOfLocalFuns stuff. 
257         -- All the top level things are rec'd together anyway, so it's fine to
258         -- leave them to the tcSimplifyTop, and quite a bit faster too
259
260   | otherwise   -- Nested case
261   = do  { ((binds, ids, thing), lie) <- getLIE thing_inside
262         ; lie_binds <- bindInstsOfLocalFuns lie ids
263         ; return (binds, lie_binds, thing) }
264
265 ------------------------
266 mkEdges :: TcSigFun -> LHsBinds Name
267         -> [(LHsBind Name, BKey, [BKey])]
268
269 type BKey  = Int -- Just number off the bindings
270
271 mkEdges sig_fn binds
272   = [ (bind, key, [key | n <- nameSetToList (bind_fvs (unLoc bind)),
273                          Just key <- [lookupNameEnv key_map n], no_sig n ])
274     | (bind, key) <- keyd_binds
275     ]
276   where
277     no_sig :: Name -> Bool
278     no_sig n = isNothing (sig_fn n)
279
280     keyd_binds = bagToList binds `zip` [0::BKey ..]
281
282     key_map :: NameEnv BKey     -- Which binding it comes from
283     key_map = mkNameEnv [(bndr, key) | (L _ bind, key) <- keyd_binds
284                                      , bndr <- bindersOfHsBind bind ]
285
286 bindersOfHsBind :: HsBind Name -> [Name]
287 bindersOfHsBind (PatBind { pat_lhs = pat })  = collectPatBinders pat
288 bindersOfHsBind (FunBind { fun_id = L _ f }) = [f]
289 bindersOfHsBind (AbsBinds {})                = panic "bindersOfHsBind AbsBinds"
290 bindersOfHsBind (VarBind {})                 = panic "bindersOfHsBind VarBind"
291
292 ------------------------
293 tcPolyBinds :: TopLevelFlag -> TcSigFun -> TcPragFun
294             -> RecFlag                  -- Whether the group is really recursive
295             -> RecFlag                  -- Whether it's recursive after breaking
296                                         -- dependencies based on type signatures
297             -> LHsBinds Name
298             -> TcM (LHsBinds TcId, [TcId])
299
300 -- Typechecks a single bunch of bindings all together, 
301 -- and generalises them.  The bunch may be only part of a recursive
302 -- group, because we use type signatures to maximise polymorphism
303 --
304 -- Returns a list because the input may be a single non-recursive binding,
305 -- in which case the dependency order of the resulting bindings is
306 -- important.  
307 -- 
308 -- Knows nothing about the scope of the bindings
309
310 tcPolyBinds top_lvl sig_fn prag_fn rec_group rec_tc binds
311   = let 
312         bind_list    = bagToList binds
313         binder_names = collectHsBindBinders binds
314         loc          = getLoc (head bind_list)
315                 -- TODO: location a bit awkward, but the mbinds have been
316                 --       dependency analysed and may no longer be adjacent
317     in
318         -- SET UP THE MAIN RECOVERY; take advantage of any type sigs
319     setSrcSpan loc                              $
320     recoverM (recoveryCode binder_names sig_fn) $ do 
321
322   { traceTc (ptext (sLit "------------------------------------------------"))
323   ; traceTc (ptext (sLit "Bindings for") <+> ppr binder_names)
324
325         -- TYPECHECK THE BINDINGS
326   ; ((binds', mono_bind_infos), lie_req) 
327         <- getLIE (tcMonoBinds bind_list sig_fn rec_tc)
328   ; traceTc (text "temp" <+> (ppr binds' $$ ppr lie_req))
329
330         -- CHECK FOR UNLIFTED BINDINGS
331         -- These must be non-recursive etc, and are not generalised
332         -- They desugar to a case expression in the end
333   ; zonked_mono_tys <- zonkTcTypes (map getMonoType mono_bind_infos)
334   ; is_strict <- checkStrictBinds top_lvl rec_group binds' 
335                                   zonked_mono_tys mono_bind_infos
336   ; if is_strict then
337     do  { extendLIEs lie_req
338         ; let exports = zipWith mk_export mono_bind_infos zonked_mono_tys
339               mk_export (name, mb_sig,  mono_id) mono_ty 
340                 = ([], the_id, mono_id, noSpecPrags)
341                               -- ToDo: prags for unlifted bindings
342                 where
343                   the_id = case mb_sig of
344                              Just sig -> sig_id sig
345                              Nothing  -> mkLocalId name mono_ty
346
347         ; return ( unitBag $ L loc $ AbsBinds [] [] exports binds',
348                    [poly_id | (_, poly_id, _, _) <- exports]) } -- Guaranteed zonked
349
350     else do     -- The normal lifted case: GENERALISE
351   { dflags <- getDOpts 
352   ; (tyvars_to_gen, dicts, dict_binds)
353         <- addErrCtxt (genCtxt (bndrNames mono_bind_infos)) $
354            generalise dflags top_lvl bind_list sig_fn mono_bind_infos lie_req
355
356         -- BUILD THE POLYMORPHIC RESULT IDs
357   ; let dict_vars = map instToVar dicts -- May include equality constraints
358   ; exports <- mapM (mkExport top_lvl rec_group (length mono_bind_infos > 1)
359                               prag_fn tyvars_to_gen (map varType dict_vars))
360                     mono_bind_infos
361
362   ; let poly_ids = [poly_id | (_, poly_id, _, _) <- exports]
363   ; traceTc (text "binding:" <+> ppr (poly_ids `zip` map idType poly_ids))
364
365   ; let abs_bind = L loc $ AbsBinds tyvars_to_gen
366                                     dict_vars exports
367                                     (dict_binds `unionBags` binds')
368
369   ; return (unitBag abs_bind, poly_ids)       -- poly_ids are guaranteed zonked by mkExport
370   } }
371
372
373 --------------
374 mkExport :: TopLevelFlag -> RecFlag
375          -> Bool         -- More than one variable is bound, so we'll desugar to
376                          -- a tuple, so INLINE pragmas won't work
377          -> TcPragFun -> [TyVar] -> [TcType]
378          -> MonoBindInfo
379          -> TcM ([TyVar], Id, Id, TcSpecPrags)
380 -- mkExport generates exports with 
381 --      zonked type variables, 
382 --      zonked poly_ids
383 -- The former is just because no further unifications will change
384 -- the quantified type variables, so we can fix their final form
385 -- right now.
386 -- The latter is needed because the poly_ids are used to extend the
387 -- type environment; see the invariant on TcEnv.tcExtendIdEnv 
388
389 -- Pre-condition: the inferred_tvs are already zonked
390
391 mkExport top_lvl rec_group multi_bind prag_fn inferred_tvs dict_tys
392          (poly_name, mb_sig, mono_id)
393   = do  { warn_missing_sigs <- doptM Opt_WarnMissingSigs
394         ; let warn = isTopLevel top_lvl && warn_missing_sigs
395         ; (tvs, poly_id) <- mk_poly_id warn mb_sig
396                 -- poly_id has a zonked type
397
398         ; (poly_id', spec_prags) <- tcPrags rec_group multi_bind (notNull dict_tys)
399                                             poly_id (prag_fn poly_name)
400                 -- tcPrags requires a zonked poly_id
401
402         ; return (tvs, poly_id', mono_id, SpecPrags spec_prags) }
403   where
404     poly_ty = mkForAllTys inferred_tvs (mkFunTys dict_tys (idType mono_id))
405
406     mk_poly_id warn Nothing    = do { poly_ty' <- zonkTcType poly_ty
407                                     ; missingSigWarn warn poly_name poly_ty'
408                                     ; return (inferred_tvs, mkLocalId poly_name poly_ty') }
409     mk_poly_id _    (Just sig) = do { tvs <- mapM zonk_tv (sig_tvs sig)
410                                     ; return (tvs,  sig_id sig) }
411
412     zonk_tv tv = do { ty <- zonkTcTyVar tv; return (tcGetTyVar "mkExport" ty) }
413
414 ------------------------
415 type TcPragFun = Name -> [LSig Name]
416
417 mkPragFun :: [LSig Name] -> LHsBinds Name -> TcPragFun
418 mkPragFun sigs binds = \n -> lookupNameEnv prag_env n `orElse` []
419   where
420     prs = mapCatMaybes get_sig sigs
421
422     get_sig :: LSig Name -> Maybe (Located Name, LSig Name)
423     get_sig (L l (SpecSig nm ty inl)) = Just (nm, L l $ SpecSig  nm ty (add_arity nm inl))
424     get_sig (L l (InlineSig nm inl))  = Just (nm, L l $ InlineSig nm   (add_arity nm inl))
425     get_sig _                         = Nothing
426
427     add_arity (L _ n) inl_prag   -- Adjust inl_sat field to match visible arity of function
428       | Just ar <- lookupNameEnv ar_env n = inl_prag { inl_sat = Just ar }
429       | otherwise                         = inl_prag
430
431     prag_env :: NameEnv [LSig Name]
432     prag_env = foldl add emptyNameEnv prs
433     add env (L _ n,p) = extendNameEnv_Acc (:) singleton env n p
434
435     -- ar_env maps a local to the arity of its definition
436     ar_env :: NameEnv Arity
437     ar_env = foldrBag lhsBindArity emptyNameEnv binds
438
439 lhsBindArity :: LHsBind Name -> NameEnv Arity -> NameEnv Arity
440 lhsBindArity (L _ (FunBind { fun_id = id, fun_matches = ms })) env
441   = extendNameEnv env (unLoc id) (matchGroupArity ms)
442 lhsBindArity _ env = env        -- PatBind/VarBind
443
444 tcPrags :: RecFlag
445         -> Bool     -- True <=> AbsBinds binds more than one variable
446         -> Bool     -- True <=> function is overloaded
447         -> Id -> [LSig Name]
448         -> TcM (Id, [Located TcSpecPrag])
449 -- Add INLINE and SPECLIASE pragmas
450 --    INLINE prags are added to the (polymorphic) Id directly
451 --    SPECIALISE prags are passed to the desugarer via TcSpecPrags
452 -- Pre-condition: the poly_id is zonked
453 -- Reason: required by tcSubExp
454 tcPrags _rec_group _multi_bind _is_overloaded_id poly_id prag_sigs
455   = do { poly_id' <- tc_inl inl_sigs
456
457        ; spec_prags <- mapM (wrapLocM (tcSpecPrag poly_id')) spec_sigs
458
459 -- Commented out until bytestring library removes redundant pragmas
460 -- for packWith and unpackWith
461 --       ; unless (null spec_sigs || is_overloaded_id) warn_discarded_spec
462
463        ; unless (null bad_sigs) warn_discarded_sigs
464
465        ; return (poly_id', spec_prags) }
466   where
467     (inl_sigs, other_sigs) = partition isInlineLSig prag_sigs
468     (spec_sigs, bad_sigs)  = partition isSpecLSig   other_sigs
469
470 --    warn_discarded_spec = warnPrags poly_id spec_sigs $
471 --                          ptext (sLit "SPECIALISE pragmas for non-overloaded function")
472     warn_dup_inline     = warnPrags poly_id inl_sigs $
473                           ptext (sLit "Duplicate INLINE pragmas for")
474     warn_discarded_sigs = warnPrags poly_id bad_sigs $
475                           ptext (sLit "Discarding unexpected pragmas for")
476
477     -----------
478     tc_inl [] = return poly_id
479     tc_inl (L loc (InlineSig _ prag) : other_inls)
480        = do { unless (null other_inls) (setSrcSpan loc warn_dup_inline)
481             ; return (poly_id `setInlinePragma` prag) }
482     tc_inl _ = panic "tc_inl"
483
484 {- Earlier we tried to warn about
485    (a) INLINE for recursive function
486    (b) INLINE for function that is part of a multi-binder group
487    Code fragments below. But we want to allow
488        {-# INLINE f #-}
489        f x = x : g y
490        g y = ....f...f....
491    even though they are mutually recursive.  
492    So I'm just omitting the warnings for now
493
494        | multi_bind && isInlinePragma prag
495        = do { setSrcSpan loc $ addWarnTc multi_bind_warn
496             ; return poly_id }
497        | otherwise
498             ; when (isInlinePragma prag && isRec rec_group)
499                    (setSrcSpan loc (addWarnTc rec_inline_warn))
500
501     rec_inline_warn = ptext (sLit "INLINE pragma for recursive binder")
502                       <+> quotes (ppr poly_id) <+> ptext (sLit "may be discarded")
503  
504     multi_bind_warn = hang (ptext (sLit "Discarding INLINE pragma for") <+> quotes (ppr poly_id))
505                          2 (ptext (sLit "because it is bound by a pattern, or mutual recursion") )
506 -}
507
508
509 warnPrags :: Id -> [LSig Name] -> SDoc -> TcM ()
510 warnPrags id bad_sigs herald
511   = addWarnTc (hang (herald <+> quotes (ppr id))
512                   2 (ppr_sigs bad_sigs))
513   where
514     ppr_sigs sigs = vcat (map (ppr . getLoc) sigs)
515
516 --------------
517 tcSpecPrag :: TcId -> Sig Name -> TcM TcSpecPrag
518 tcSpecPrag poly_id prag@(SpecSig _ hs_ty inl) 
519   = addErrCtxt (spec_ctxt prag) $
520     do  { let name = idName poly_id
521         ; spec_ty <- tcHsSigType (FunSigCtxt name) hs_ty
522         ; co_fn <- tcSubExp (SpecPragOrigin name) (idType poly_id) spec_ty
523         ; return (SpecPrag co_fn inl) }
524   where
525     spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag)
526 tcSpecPrag _ sig = pprPanic "tcSpecPrag" (ppr sig)
527
528
529 --------------
530 -- If typechecking the binds fails, then return with each
531 -- signature-less binder given type (forall a.a), to minimise 
532 -- subsequent error messages
533 recoveryCode :: [Name] -> (Name -> Maybe [Name])
534              -> TcM (LHsBinds TcId, [Id])
535 recoveryCode binder_names sig_fn
536   = do  { traceTc (text "tcBindsWithSigs: error recovery" <+> ppr binder_names)
537         ; poly_ids <- mapM mk_dummy binder_names
538         ; return (emptyBag, poly_ids) }
539   where
540     mk_dummy name 
541         | isJust (sig_fn name) = tcLookupId name        -- Had signature; look it up
542         | otherwise            = return (mkLocalId name forall_a_a)    -- No signature
543
544 forall_a_a :: TcType
545 forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
546
547
548 -- Check that non-overloaded unlifted bindings are
549 --      a) non-recursive,
550 --      b) not top level, 
551 --      c) not a multiple-binding group (more or less implied by (a))
552
553 checkStrictBinds :: TopLevelFlag -> RecFlag
554                  -> LHsBinds TcId -> [TcType] -> [MonoBindInfo]
555                  -> TcM Bool
556 checkStrictBinds top_lvl rec_group mbind mono_tys infos
557   | unlifted || bang_pat
558   = do  { checkTc (isNotTopLevel top_lvl)
559                   (strictBindErr "Top-level" unlifted mbind)
560         ; checkTc (isNonRec rec_group)
561                   (strictBindErr "Recursive" unlifted mbind)
562         ; checkTc (isSingletonBag mbind)
563                   (strictBindErr "Multiple" unlifted mbind) 
564         -- This should be a checkTc, not a warnTc, but as of GHC 6.11
565         -- the versions of alex and happy available have non-conforming
566         -- templates, so the GHC build fails if it's an error:
567         ; warnUnlifted <- doptM Opt_WarnLazyUnliftedBindings
568         ; warnTc (warnUnlifted && not bang_pat)
569                  (unliftedMustBeBang mbind)
570         ; mapM_ check_sig infos
571         ; return True }
572   | otherwise
573   = return False
574   where
575     unlifted = any isUnLiftedType mono_tys
576     bang_pat = anyBag (isBangHsBind . unLoc) mbind
577     check_sig (_, Just sig, _) = checkTc (null (sig_tvs sig) && null (sig_theta sig))
578                                          (badStrictSig unlifted sig)
579     check_sig _                = return ()
580
581 unliftedMustBeBang :: LHsBindsLR Var Var -> SDoc
582 unliftedMustBeBang mbind
583   = hang (text "Bindings containing unlifted types must use an outermost bang pattern:")
584          4 (pprLHsBinds mbind)
585  $$ text "*** This will be an error in GHC 6.14! Fix your code now!"
586
587 strictBindErr :: String -> Bool -> LHsBindsLR Var Var -> SDoc
588 strictBindErr flavour unlifted mbind
589   = hang (text flavour <+> msg <+> ptext (sLit "aren't allowed:")) 
590          4 (pprLHsBinds mbind)
591   where
592     msg | unlifted  = ptext (sLit "bindings for unlifted types")
593         | otherwise = ptext (sLit "bang-pattern bindings")
594
595 badStrictSig :: Bool -> TcSigInfo -> SDoc
596 badStrictSig unlifted sig
597   = hang (ptext (sLit "Illegal polymorphic signature in") <+> msg)
598          4 (ppr sig)
599   where
600     msg | unlifted  = ptext (sLit "an unlifted binding")
601         | otherwise = ptext (sLit "a bang-pattern binding")
602 \end{code}
603
604
605 %************************************************************************
606 %*                                                                      *
607 \subsection{tcMonoBind}
608 %*                                                                      *
609 %************************************************************************
610
611 @tcMonoBinds@ deals with a perhaps-recursive group of HsBinds.
612 The signatures have been dealt with already.
613
614 \begin{code}
615 tcMonoBinds :: [LHsBind Name]
616             -> TcSigFun
617             -> RecFlag  -- Whether the binding is recursive for typechecking purposes
618                         -- i.e. the binders are mentioned in their RHSs, and
619                         --      we are not resuced by a type signature
620             -> TcM (LHsBinds TcId, [MonoBindInfo])
621
622 tcMonoBinds [L b_loc (FunBind { fun_id = L nm_loc name, fun_infix = inf, 
623                                 fun_matches = matches, bind_fvs = fvs })]
624             sig_fn              -- Single function binding,
625             NonRecursive        -- binder isn't mentioned in RHS,
626   | Nothing <- sig_fn name      -- ...with no type signature
627   =     -- In this very special case we infer the type of the
628         -- right hand side first (it may have a higher-rank type)
629         -- and *then* make the monomorphic Id for the LHS
630         -- e.g.         f = \(x::forall a. a->a) -> <body>
631         --      We want to infer a higher-rank type for f
632     setSrcSpan b_loc    $
633     do  { ((co_fn, matches'), rhs_ty) <- tcInfer (tcMatchesFun name inf matches)
634
635                 -- Check for an unboxed tuple type
636                 --      f = (# True, False #)
637                 -- Zonk first just in case it's hidden inside a meta type variable
638                 -- (This shows up as a (more obscure) kind error 
639                 --  in the 'otherwise' case of tcMonoBinds.)
640         ; zonked_rhs_ty <- zonkTcType rhs_ty
641         ; checkTc (not (isUnboxedTupleType zonked_rhs_ty))
642                   (unboxedTupleErr name zonked_rhs_ty)
643
644         ; mono_name <- newLocalName name
645         ; let mono_id = mkLocalId mono_name zonked_rhs_ty
646         ; return (unitBag (L b_loc (FunBind { fun_id = L nm_loc mono_id, fun_infix = inf,
647                                               fun_matches = matches', bind_fvs = fvs,
648                                               fun_co_fn = co_fn, fun_tick = Nothing })),
649                   [(name, Nothing, mono_id)]) }
650
651 tcMonoBinds [L b_loc (FunBind { fun_id = L nm_loc name, fun_infix = inf, 
652                                 fun_matches = matches })]
653             sig_fn              -- Single function binding
654             _
655   | Just scoped_tvs <- sig_fn name      -- ...with a type signature
656   =     -- When we have a single function binding, with a type signature
657         -- we can (a) use genuine, rigid skolem constants for the type variables
658         --        (b) bring (rigid) scoped type variables into scope
659     setSrcSpan b_loc    $
660     do  { tc_sig <- tcInstSig True name
661         ; mono_name <- newLocalName name
662         ; let mono_ty = sig_tau tc_sig
663               mono_id = mkLocalId mono_name mono_ty
664               rhs_tvs = [ (name, mkTyVarTy tv)
665                         | (name, tv) <- scoped_tvs `zip` sig_tvs tc_sig ]
666                         -- See Note [More instantiated than scoped]
667                         -- Note that the scoped_tvs and the (sig_tvs sig) 
668                         -- may have different Names. That's quite ok.
669
670         ; traceTc (text "tcMoonBinds" <+> ppr scoped_tvs $$ ppr tc_sig)
671         ; (co_fn, matches') <- tcExtendTyVarEnv2 rhs_tvs $
672                                tcMatchesFun mono_name inf matches mono_ty
673              -- Note that "mono_ty" might actually be a polymorphic type,
674              -- if the original function had a signature like
675              --    forall a. Eq a => forall b. Ord b => ....
676              -- But that's ok: tcMatchesFun can deal with that
677              -- It happens, too!  See Note [Polymorphic methods] in TcClassDcl.
678
679         ; let fun_bind' = FunBind { fun_id = L nm_loc mono_id, 
680                                     fun_infix = inf, fun_matches = matches',
681                                     bind_fvs = placeHolderNames, fun_co_fn = co_fn, 
682                                     fun_tick = Nothing }
683         ; return (unitBag (L b_loc fun_bind'),
684                   [(name, Just tc_sig, mono_id)]) }
685
686 tcMonoBinds binds sig_fn _
687   = do  { tc_binds <- mapM (wrapLocM (tcLhs sig_fn)) binds
688
689         -- Bring the monomorphic Ids, into scope for the RHSs
690         ; let mono_info  = getMonoBindInfo tc_binds
691               rhs_id_env = [(name,mono_id) | (name, Nothing, mono_id) <- mono_info]
692                                 -- A monomorphic binding for each term variable that lacks 
693                                 -- a type sig.  (Ones with a sig are already in scope.)
694
695         ; binds' <- tcExtendIdEnv2 rhs_id_env $ do
696                     traceTc (text "tcMonoBinds" <+> vcat [ ppr n <+> ppr id <+> ppr (idType id) 
697                                                          | (n,id) <- rhs_id_env])
698                     mapM (wrapLocM tcRhs) tc_binds
699         ; return (listToBag binds', mono_info) }
700
701 ------------------------
702 -- tcLhs typechecks the LHS of the bindings, to construct the environment in which
703 -- we typecheck the RHSs.  Basically what we are doing is this: for each binder:
704 --      if there's a signature for it, use the instantiated signature type
705 --      otherwise invent a type variable
706 -- You see that quite directly in the FunBind case.
707 -- 
708 -- But there's a complication for pattern bindings:
709 --      data T = MkT (forall a. a->a)
710 --      MkT f = e
711 -- Here we can guess a type variable for the entire LHS (which will be refined to T)
712 -- but we want to get (f::forall a. a->a) as the RHS environment.
713 -- The simplest way to do this is to typecheck the pattern, and then look up the
714 -- bound mono-ids.  Then we want to retain the typechecked pattern to avoid re-doing
715 -- it; hence the TcMonoBind data type in which the LHS is done but the RHS isn't
716
717 data TcMonoBind         -- Half completed; LHS done, RHS not done
718   = TcFunBind  MonoBindInfo  (Located TcId) Bool (MatchGroup Name) 
719   | TcPatBind [MonoBindInfo] (LPat TcId) (GRHSs Name) TcSigmaType
720
721 type MonoBindInfo = (Name, Maybe TcSigInfo, TcId)
722         -- Type signature (if any), and
723         -- the monomorphic bound things
724
725 bndrNames :: [MonoBindInfo] -> [Name]
726 bndrNames mbi = [n | (n,_,_) <- mbi]
727
728 getMonoType :: MonoBindInfo -> TcTauType
729 getMonoType (_,_,mono_id) = idType mono_id
730
731 tcLhs :: TcSigFun -> HsBind Name -> TcM TcMonoBind
732 tcLhs sig_fn (FunBind { fun_id = L nm_loc name, fun_infix = inf, fun_matches = matches })
733   = do  { mb_sig <- tcInstSig_maybe sig_fn name
734         ; mono_name <- newLocalName name
735         ; mono_ty   <- mk_mono_ty mb_sig
736         ; let mono_id = mkLocalId mono_name mono_ty
737         ; return (TcFunBind (name, mb_sig, mono_id) (L nm_loc mono_id) inf matches) }
738   where
739     mk_mono_ty (Just sig) = return (sig_tau sig)
740     mk_mono_ty Nothing    = newFlexiTyVarTy argTypeKind
741
742 tcLhs sig_fn (PatBind { pat_lhs = pat, pat_rhs = grhss })
743   = do  { mb_sigs <- mapM (tcInstSig_maybe sig_fn) names
744         ; mono_pat_binds <- doptM Opt_MonoPatBinds
745                 -- With -XMonoPatBinds, we do no generalisation of pattern bindings
746                 -- But the signature can still be polymoprhic!
747                 --      data T = MkT (forall a. a->a)
748                 --      x :: forall a. a->a
749                 --      MkT x = <rhs>
750                 -- The function get_sig_ty decides whether the pattern-bound variables
751                 -- should have exactly the type in the type signature (-XMonoPatBinds), 
752                 -- or the instantiated version (-XMonoPatBinds)
753
754         ; let nm_sig_prs  = names `zip` mb_sigs
755               get_sig_ty | mono_pat_binds = idType . sig_id
756                          | otherwise      = sig_tau
757               tau_sig_env = mkNameEnv [ (name, get_sig_ty sig) 
758                                       | (name, Just sig) <- nm_sig_prs]
759               sig_tau_fn  = lookupNameEnv tau_sig_env
760
761               tc_pat exp_ty = tcLetPat sig_tau_fn pat exp_ty $
762                               mapM lookup_info nm_sig_prs
763
764                 -- After typechecking the pattern, look up the binder
765                 -- names, which the pattern has brought into scope.
766               lookup_info :: (Name, Maybe TcSigInfo) -> TcM MonoBindInfo
767               lookup_info (name, mb_sig) = do { mono_id <- tcLookupId name
768                                               ; return (name, mb_sig, mono_id) }
769
770         ; ((pat', infos), pat_ty) <- addErrCtxt (patMonoBindsCtxt pat grhss) $
771                                      tcInfer tc_pat
772
773         ; return (TcPatBind infos pat' grhss pat_ty) }
774   where
775     names = collectPatBinders pat
776
777
778 tcLhs _ other_bind = pprPanic "tcLhs" (ppr other_bind)
779         -- AbsBind, VarBind impossible
780
781 -------------------
782 tcRhs :: TcMonoBind -> TcM (HsBind TcId)
783 -- When we are doing pattern bindings, or multiple function bindings at a time
784 -- we *don't* bring any scoped type variables into scope
785 -- Wny not?  They are not completely rigid.
786 -- That's why we have the special case for a single FunBind in tcMonoBinds
787 tcRhs (TcFunBind (_,_,mono_id) fun' inf matches)
788   = do  { (co_fn, matches') <- tcMatchesFun (idName mono_id) inf 
789                                             matches (idType mono_id)
790         ; return (FunBind { fun_id = fun', fun_infix = inf, fun_matches = matches',
791                             bind_fvs = placeHolderNames, fun_co_fn = co_fn,
792                             fun_tick = Nothing }) }
793
794 tcRhs (TcPatBind _ pat' grhss pat_ty)
795   = do  { grhss' <- addErrCtxt (patMonoBindsCtxt pat' grhss) $
796                     tcGRHSsPat grhss pat_ty
797         ; return (PatBind { pat_lhs = pat', pat_rhs = grhss', pat_rhs_ty = pat_ty, 
798                             bind_fvs = placeHolderNames }) }
799
800
801 ---------------------
802 getMonoBindInfo :: [Located TcMonoBind] -> [MonoBindInfo]
803 getMonoBindInfo tc_binds
804   = foldr (get_info . unLoc) [] tc_binds
805   where
806     get_info (TcFunBind info _ _ _)  rest = info : rest
807     get_info (TcPatBind infos _ _ _) rest = infos ++ rest
808 \end{code}
809
810
811 %************************************************************************
812 %*                                                                      *
813                 Generalisation
814 %*                                                                      *
815 %************************************************************************
816
817 \begin{code}
818 generalise :: DynFlags -> TopLevelFlag 
819            -> [LHsBind Name] -> TcSigFun 
820            -> [MonoBindInfo] -> [Inst]
821            -> TcM ([TyVar], [Inst], TcDictBinds)
822 -- The returned [TyVar] are all ready to quantify
823
824 generalise dflags top_lvl bind_list sig_fn mono_infos lie_req
825   | isMonoGroup dflags top_lvl bind_list sigs
826   = do  { extendLIEs lie_req
827         ; return ([], [], emptyBag) }
828
829   | isRestrictedGroup dflags bind_list sig_fn   -- RESTRICTED CASE
830   =     -- Check signature contexts are empty 
831     do  { checkTc (all is_mono_sig sigs)
832                   (restrictedBindCtxtErr bndrs)
833
834         -- Now simplify with exactly that set of tyvars
835         -- We have to squash those Methods
836         ; (qtvs, binds) <- tcSimplifyRestricted doc top_lvl bndrs 
837                                                 tau_tvs lie_req
838
839         -- Check that signature type variables are OK
840         ; final_qtvs <- checkSigsTyVars qtvs sigs
841
842         ; return (final_qtvs, [], binds) }
843
844   | null sigs   -- UNRESTRICTED CASE, NO TYPE SIGS
845   = tcSimplifyInfer doc tau_tvs lie_req
846
847   | otherwise   -- UNRESTRICTED CASE, WITH TYPE SIGS
848   = do  { sig_lie <- unifyCtxts sigs    -- sigs is non-empty; sig_lie is zonked
849         ; let   -- The "sig_avails" is the stuff available.  We get that from
850                 -- the context of the type signature, BUT ALSO the lie_avail
851                 -- so that polymorphic recursion works right (see Note [Polymorphic recursion])
852                 local_meths = [mkMethInst sig mono_id | (_, Just sig, mono_id) <- mono_infos]
853                 sig_avails = sig_lie ++ local_meths
854                 loc = sig_loc (head sigs)
855
856         -- Check that the needed dicts can be
857         -- expressed in terms of the signature ones
858         ; (qtvs, binds) <- tcSimplifyInferCheck loc tau_tvs sig_avails lie_req
859         
860         -- Check that signature type variables are OK
861         ; final_qtvs <- checkSigsTyVars qtvs sigs
862
863         ; return (final_qtvs, sig_lie, binds) }
864   where
865     bndrs   = bndrNames mono_infos
866     sigs    = [sig | (_, Just sig, _) <- mono_infos]
867     get_tvs | isTopLevel top_lvl = tyVarsOfType  -- See Note [Silly type synonym] in TcType
868             | otherwise          = exactTyVarsOfType
869     tau_tvs = foldr (unionVarSet . get_tvs . getMonoType) emptyVarSet mono_infos
870     is_mono_sig sig = null (sig_theta sig)
871     doc = ptext (sLit "type signature(s) for") <+> pprBinders bndrs
872
873     mkMethInst (TcSigInfo { sig_id = poly_id, sig_tvs = tvs, 
874                             sig_theta = theta, sig_loc = loc }) mono_id
875       = Method {tci_id = mono_id, tci_oid = poly_id, tci_tys = mkTyVarTys tvs,
876                 tci_theta = theta, tci_loc = loc}
877 \end{code}
878
879 unifyCtxts checks that all the signature contexts are the same
880 The type signatures on a mutually-recursive group of definitions
881 must all have the same context (or none).
882
883 The trick here is that all the signatures should have the same
884 context, and we want to share type variables for that context, so that
885 all the right hand sides agree a common vocabulary for their type
886 constraints
887
888 We unify them because, with polymorphic recursion, their types
889 might not otherwise be related.  This is a rather subtle issue.
890
891 \begin{code}
892 unifyCtxts :: [TcSigInfo] -> TcM [Inst]
893 -- Post-condition: the returned Insts are full zonked
894 unifyCtxts [] = panic "unifyCtxts []"
895 unifyCtxts (sig1 : sigs)        -- Argument is always non-empty
896   = do  { traceTc $ text "unifyCtxts" <+> ppr (sig1 : sigs)
897         ; mapM_ unify_ctxt sigs
898         ; theta <- zonkTcThetaType (sig_theta sig1)
899         ; newDictBndrs (sig_loc sig1) theta }
900   where
901     theta1 = sig_theta sig1
902     unify_ctxt :: TcSigInfo -> TcM ()
903     unify_ctxt sig@(TcSigInfo { sig_theta = theta })
904         = setSrcSpan (instLocSpan (sig_loc sig))        $
905           addErrCtxt (sigContextsCtxt sig1 sig)         $
906           do { cois <- unifyTheta theta1 theta
907              ; -- Check whether all coercions are identity coercions
908                -- That can happen if we have, say
909                --         f :: C [a]   => ...
910                --         g :: C (F a) => ...
911                -- where F is a type function and (F a ~ [a])
912                -- Then unification might succeed with a coercion.  But it's much
913                -- much simpler to require that such signatures have identical contexts
914                checkTc (all isIdentityCoI cois)
915                        (ptext (sLit "Mutually dependent functions have syntactically distinct contexts"))
916              }
917
918 checkSigsTyVars :: [TcTyVar] -> [TcSigInfo] -> TcM [TcTyVar]
919 checkSigsTyVars qtvs sigs 
920   = do  { gbl_tvs <- tcGetGlobalTyVars
921         ; sig_tvs_s <- mapM (check_sig gbl_tvs) sigs
922
923         ; let   -- Sigh.  Make sure that all the tyvars in the type sigs
924                 -- appear in the returned ty var list, which is what we are
925                 -- going to generalise over.  Reason: we occasionally get
926                 -- silly types like
927                 --      type T a = () -> ()
928                 --      f :: T a
929                 --      f () = ()
930                 -- Here, 'a' won't appear in qtvs, so we have to add it
931                 sig_tvs = foldl extendVarSetList emptyVarSet sig_tvs_s
932                 all_tvs = varSetElems (extendVarSetList sig_tvs qtvs)
933         ; return all_tvs }
934   where
935     check_sig gbl_tvs (TcSigInfo {sig_id = id, sig_tvs = tvs, 
936                                   sig_theta = theta, sig_tau = tau})
937       = addErrCtxt (ptext (sLit "In the type signature for") <+> quotes (ppr id))       $
938         addErrCtxtM (sigCtxt id tvs theta tau)                                          $
939         do { tvs' <- checkDistinctTyVars tvs
940            ; when (any (`elemVarSet` gbl_tvs) tvs')
941                   (bleatEscapedTvs gbl_tvs tvs tvs')
942            ; return tvs' }
943
944 checkDistinctTyVars :: [TcTyVar] -> TcM [TcTyVar]
945 -- (checkDistinctTyVars tvs) checks that the tvs from one type signature
946 -- are still all type variables, and all distinct from each other.  
947 -- It returns a zonked set of type variables.
948 -- For example, if the type sig is
949 --      f :: forall a b. a -> b -> b
950 -- we want to check that 'a' and 'b' haven't 
951 --      (a) been unified with a non-tyvar type
952 --      (b) been unified with each other (all distinct)
953
954 checkDistinctTyVars sig_tvs
955   = do  { zonked_tvs <- mapM zonkSigTyVar sig_tvs
956         ; foldlM_ check_dup emptyVarEnv (sig_tvs `zip` zonked_tvs)
957         ; return zonked_tvs }
958   where
959     check_dup :: TyVarEnv TcTyVar -> (TcTyVar, TcTyVar) -> TcM (TyVarEnv TcTyVar)
960         -- The TyVarEnv maps each zonked type variable back to its
961         -- corresponding user-written signature type variable
962     check_dup acc (sig_tv, zonked_tv)
963         = case lookupVarEnv acc zonked_tv of
964                 Just sig_tv' -> bomb_out sig_tv sig_tv'
965
966                 Nothing -> return (extendVarEnv acc zonked_tv sig_tv)
967
968     bomb_out sig_tv1 sig_tv2
969        = do { env0 <- tcInitTidyEnv
970             ; let (env1, tidy_tv1) = tidyOpenTyVar env0 sig_tv1
971                   (env2, tidy_tv2) = tidyOpenTyVar env1 sig_tv2
972                   msg = ptext (sLit "Quantified type variable") <+> quotes (ppr tidy_tv1) 
973                          <+> ptext (sLit "is unified with another quantified type variable") 
974                          <+> quotes (ppr tidy_tv2)
975             ; failWithTcM (env2, msg) }
976 \end{code}
977
978
979 @getTyVarsToGen@ decides what type variables to generalise over.
980
981 For a "restricted group" -- see the monomorphism restriction
982 for a definition -- we bind no dictionaries, and
983 remove from tyvars_to_gen any constrained type variables
984
985 *Don't* simplify dicts at this point, because we aren't going
986 to generalise over these dicts.  By the time we do simplify them
987 we may well know more.  For example (this actually came up)
988         f :: Array Int Int
989         f x = array ... xs where xs = [1,2,3,4,5]
990 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
991 stuff.  If we simplify only at the f-binding (not the xs-binding)
992 we'll know that the literals are all Ints, and we can just produce
993 Int literals!
994
995 Find all the type variables involved in overloading, the
996 "constrained_tyvars".  These are the ones we *aren't* going to
997 generalise.  We must be careful about doing this:
998
999  (a) If we fail to generalise a tyvar which is not actually
1000         constrained, then it will never, ever get bound, and lands
1001         up printed out in interface files!  Notorious example:
1002                 instance Eq a => Eq (Foo a b) where ..
1003         Here, b is not constrained, even though it looks as if it is.
1004         Another, more common, example is when there's a Method inst in
1005         the LIE, whose type might very well involve non-overloaded
1006         type variables.
1007   [NOTE: Jan 2001: I don't understand the problem here so I'm doing 
1008         the simple thing instead]
1009
1010  (b) On the other hand, we mustn't generalise tyvars which are constrained,
1011         because we are going to pass on out the unmodified LIE, with those
1012         tyvars in it.  They won't be in scope if we've generalised them.
1013
1014 So we are careful, and do a complete simplification just to find the
1015 constrained tyvars. We don't use any of the results, except to
1016 find which tyvars are constrained.
1017
1018 Note [Polymorphic recursion]
1019 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1020 The game plan for polymorphic recursion in the code above is 
1021
1022         * Bind any variable for which we have a type signature
1023           to an Id with a polymorphic type.  Then when type-checking 
1024           the RHSs we'll make a full polymorphic call.
1025
1026 This fine, but if you aren't a bit careful you end up with a horrendous
1027 amount of partial application and (worse) a huge space leak. For example:
1028
1029         f :: Eq a => [a] -> [a]
1030         f xs = ...f...
1031
1032 If we don't take care, after typechecking we get
1033
1034         f = /\a -> \d::Eq a -> let f' = f a d
1035                                in
1036                                \ys:[a] -> ...f'...
1037
1038 Notice the the stupid construction of (f a d), which is of course
1039 identical to the function we're executing.  In this case, the
1040 polymorphic recursion isn't being used (but that's a very common case).
1041 This can lead to a massive space leak, from the following top-level defn
1042 (post-typechecking)
1043
1044         ff :: [Int] -> [Int]
1045         ff = f Int dEqInt
1046
1047 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
1048 f' is another thunk which evaluates to the same thing... and you end
1049 up with a chain of identical values all hung onto by the CAF ff.
1050
1051         ff = f Int dEqInt
1052
1053            = let f' = f Int dEqInt in \ys. ...f'...
1054
1055            = let f' = let f' = f Int dEqInt in \ys. ...f'...
1056                       in \ys. ...f'...
1057
1058 Etc.
1059
1060 NOTE: a bit of arity anaysis would push the (f a d) inside the (\ys...),
1061 which would make the space leak go away in this case
1062
1063 Solution: when typechecking the RHSs we always have in hand the
1064 *monomorphic* Ids for each binding.  So we just need to make sure that
1065 if (Method f a d) shows up in the constraints emerging from (...f...)
1066 we just use the monomorphic Id.  We achieve this by adding monomorphic Ids
1067 to the "givens" when simplifying constraints.  That's what the "lies_avail"
1068 is doing.
1069
1070 Then we get
1071
1072         f = /\a -> \d::Eq a -> letrec
1073                                  fm = \ys:[a] -> ...fm...
1074                                in
1075                                fm
1076
1077
1078
1079 %************************************************************************
1080 %*                                                                      *
1081                 Signatures
1082 %*                                                                      *
1083 %************************************************************************
1084
1085 Type signatures are tricky.  See Note [Signature skolems] in TcType
1086
1087 @tcSigs@ checks the signatures for validity, and returns a list of
1088 {\em freshly-instantiated} signatures.  That is, the types are already
1089 split up, and have fresh type variables installed.  All non-type-signature
1090 "RenamedSigs" are ignored.
1091
1092 The @TcSigInfo@ contains @TcTypes@ because they are unified with
1093 the variable's type, and after that checked to see whether they've
1094 been instantiated.
1095
1096 Note [Scoped tyvars]
1097 ~~~~~~~~~~~~~~~~~~~~
1098 The -XScopedTypeVariables flag brings lexically-scoped type variables
1099 into scope for any explicitly forall-quantified type variables:
1100         f :: forall a. a -> a
1101         f x = e
1102 Then 'a' is in scope inside 'e'.
1103
1104 However, we do *not* support this 
1105   - For pattern bindings e.g
1106         f :: forall a. a->a
1107         (f,g) = e
1108
1109   - For multiple function bindings, unless Opt_RelaxedPolyRec is on
1110         f :: forall a. a -> a
1111         f = g
1112         g :: forall b. b -> b
1113         g = ...f...
1114     Reason: we use mutable variables for 'a' and 'b', since they may
1115     unify to each other, and that means the scoped type variable would
1116     not stand for a completely rigid variable.
1117
1118     Currently, we simply make Opt_ScopedTypeVariables imply Opt_RelaxedPolyRec
1119
1120
1121 Note [More instantiated than scoped]
1122 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1123 There may be more instantiated type variables than lexically-scoped 
1124 ones.  For example:
1125         type T a = forall b. b -> (a,b)
1126         f :: forall c. T c
1127 Here, the signature for f will have one scoped type variable, c,
1128 but two instantiated type variables, c' and b'.  
1129
1130 We assume that the scoped ones are at the *front* of sig_tvs,
1131 and remember the names from the original HsForAllTy in the TcSigFun.
1132
1133
1134 \begin{code}
1135 type TcSigFun = Name -> Maybe [Name]    -- Maps a let-binder to the list of
1136                                         -- type variables brought into scope
1137                                         -- by its type signature.
1138                                         -- Nothing => no type signature
1139
1140 mkTcSigFun :: [LSig Name] -> TcSigFun
1141 -- Search for a particular type signature
1142 -- Precondition: the sigs are all type sigs
1143 -- Precondition: no duplicates
1144 mkTcSigFun sigs = lookupNameEnv env
1145   where
1146     env = mkNameEnv (mapCatMaybes mk_pair sigs)
1147     mk_pair (L _ (TypeSig (L _ name) lhs_ty)) = Just (name, hsExplicitTvs lhs_ty)
1148     mk_pair (L _ (IdSig id))                  = Just (idName id, [])
1149     mk_pair _                                 = Nothing    
1150         -- The scoped names are the ones explicitly mentioned
1151         -- in the HsForAll.  (There may be more in sigma_ty, because
1152         -- of nested type synonyms.  See Note [More instantiated than scoped].)
1153         -- See Note [Only scoped tyvars are in the TyVarEnv]
1154
1155 ---------------
1156 data TcSigInfo
1157   = TcSigInfo {
1158         sig_id     :: TcId,             --  *Polymorphic* binder for this value...
1159
1160         sig_tvs    :: [TcTyVar],        -- Instantiated type variables
1161                                         -- See Note [Instantiate sig]
1162
1163         sig_theta  :: TcThetaType,      -- Instantiated theta
1164         sig_tau    :: TcTauType,        -- Instantiated tau
1165         sig_loc    :: InstLoc           -- The location of the signature
1166     }
1167
1168
1169 --      Note [Only scoped tyvars are in the TyVarEnv]
1170 -- We are careful to keep only the *lexically scoped* type variables in
1171 -- the type environment.  Why?  After all, the renamer has ensured
1172 -- that only legal occurrences occur, so we could put all type variables
1173 -- into the type env.
1174 --
1175 -- But we want to check that two distinct lexically scoped type variables
1176 -- do not map to the same internal type variable.  So we need to know which
1177 -- the lexically-scoped ones are... and at the moment we do that by putting
1178 -- only the lexically scoped ones into the environment.
1179
1180
1181 --      Note [Instantiate sig]
1182 -- It's vital to instantiate a type signature with fresh variables.
1183 -- For example:
1184 --      type S = forall a. a->a
1185 --      f,g :: S
1186 --      f = ...
1187 --      g = ...
1188 -- Here, we must use distinct type variables when checking f,g's right hand sides.
1189 -- (Instantiation is only necessary because of type synonyms.  Otherwise,
1190 -- it's all cool; each signature has distinct type variables from the renamer.)
1191
1192 instance Outputable TcSigInfo where
1193     ppr (TcSigInfo { sig_id = id, sig_tvs = tyvars, sig_theta = theta, sig_tau = tau})
1194         = ppr id <+> ptext (sLit "::") <+> ppr tyvars <+> ppr theta <+> ptext (sLit "=>") <+> ppr tau
1195 \end{code}
1196
1197 \begin{code}
1198 tcTySig :: LSig Name -> TcM TcId
1199 tcTySig (L span (TypeSig (L _ name) ty))
1200   = setSrcSpan span             $
1201     do  { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
1202         ; return (mkLocalId name sigma_ty) }
1203 tcTySig (L _ (IdSig id))
1204   = return id
1205 tcTySig s = pprPanic "tcTySig" (ppr s)
1206
1207 -------------------
1208 tcInstSig_maybe :: TcSigFun -> Name -> TcM (Maybe TcSigInfo)
1209 -- Instantiate with *meta* type variables; 
1210 -- this signature is part of a multi-signature group
1211 tcInstSig_maybe sig_fn name 
1212   = case sig_fn name of
1213         Nothing -> return Nothing
1214         Just _scoped_tvs -> do   { tc_sig <- tcInstSig False name
1215                                  ; return (Just tc_sig) }
1216         -- NB: the _scoped_tvs may be non-empty, but we can 
1217         -- just ignore them.  See Note [Scoped tyvars].
1218
1219 tcInstSig :: Bool -> Name -> TcM TcSigInfo
1220 -- Instantiate the signature, with either skolems or meta-type variables
1221 -- depending on the use_skols boolean.  This variable is set True
1222 -- when we are typechecking a single function binding; and False for
1223 -- pattern bindings and a group of several function bindings.
1224 -- Reason: in the latter cases, the "skolems" can be unified together, 
1225 --         so they aren't properly rigid in the type-refinement sense.
1226 -- NB: unless we are doing H98, each function with a sig will be done
1227 --     separately, even if it's mutually recursive, so use_skols will be True
1228 --
1229 -- We always instantiate with fresh uniques,
1230 -- although we keep the same print-name
1231 --      
1232 --      type T = forall a. [a] -> [a]
1233 --      f :: T; 
1234 --      f = g where { g :: T; g = <rhs> }
1235 --
1236 -- We must not use the same 'a' from the defn of T at both places!!
1237
1238 tcInstSig use_skols name
1239   = do  { poly_id <- tcLookupId name    -- Cannot fail; the poly ids are put into 
1240                                         -- scope when starting the binding group
1241         ; let skol_info = SigSkol (FunSigCtxt name)
1242         ; (tvs, theta, tau) <- tcInstSigType use_skols skol_info (idType poly_id)
1243         ; loc <- getInstLoc (SigOrigin skol_info)
1244         ; return (TcSigInfo { sig_id = poly_id,
1245                               sig_tvs = tvs, sig_theta = theta, sig_tau = tau, 
1246                               sig_loc = loc }) }
1247
1248 -------------------
1249 isMonoGroup :: DynFlags -> TopLevelFlag -> [LHsBind Name]
1250             -> [TcSigInfo] ->  Bool
1251 -- No generalisation at all
1252 isMonoGroup dflags top_lvl binds sigs
1253   =  (dopt Opt_MonoPatBinds dflags && any is_pat_bind binds)
1254   || (dopt Opt_MonoLocalBinds dflags && null sigs && not (isTopLevel top_lvl))
1255   where
1256     is_pat_bind (L _ (PatBind {})) = True
1257     is_pat_bind _                  = False
1258
1259 -------------------
1260 isRestrictedGroup :: DynFlags -> [LHsBind Name] -> TcSigFun -> Bool
1261 isRestrictedGroup dflags binds sig_fn
1262   = mono_restriction && not all_unrestricted
1263   where 
1264     mono_restriction = dopt Opt_MonomorphismRestriction dflags
1265     all_unrestricted = all (unrestricted . unLoc) binds
1266     has_sig n = isJust (sig_fn n)
1267
1268     unrestricted (PatBind {})                                    = False
1269     unrestricted (VarBind { var_id = v })                        = has_sig v
1270     unrestricted (FunBind { fun_id = v, fun_matches = matches }) = unrestricted_match matches 
1271                                                                  || has_sig (unLoc v)
1272     unrestricted (AbsBinds {})
1273         = panic "isRestrictedGroup/unrestricted AbsBinds"
1274
1275     unrestricted_match (MatchGroup (L _ (Match [] _ _) : _) _) = False
1276         -- No args => like a pattern binding
1277     unrestricted_match _                                       = True
1278         -- Some args => a function binding
1279 \end{code}
1280
1281
1282 %************************************************************************
1283 %*                                                                      *
1284 \subsection[TcBinds-errors]{Error contexts and messages}
1285 %*                                                                      *
1286 %************************************************************************
1287
1288
1289 \begin{code}
1290 -- This one is called on LHS, when pat and grhss are both Name 
1291 -- and on RHS, when pat is TcId and grhss is still Name
1292 patMonoBindsCtxt :: OutputableBndr id => LPat id -> GRHSs Name -> SDoc
1293 patMonoBindsCtxt pat grhss
1294   = hang (ptext (sLit "In a pattern binding:")) 4 (pprPatBind pat grhss)
1295
1296 -----------------------------------------------
1297 sigContextsCtxt :: TcSigInfo -> TcSigInfo -> SDoc
1298 sigContextsCtxt sig1 sig2
1299   = vcat [ptext (sLit "When matching the contexts of the signatures for"), 
1300           nest 2 (vcat [ppr id1 <+> dcolon <+> ppr (idType id1),
1301                         ppr id2 <+> dcolon <+> ppr (idType id2)]),
1302           ptext (sLit "The signature contexts in a mutually recursive group should all be identical")]
1303   where
1304     id1 = sig_id sig1
1305     id2 = sig_id sig2
1306
1307
1308 -----------------------------------------------
1309 unboxedTupleErr :: Name -> Type -> SDoc
1310 unboxedTupleErr name ty
1311   = hang (ptext (sLit "Illegal binding of unboxed tuple"))
1312          4 (ppr name <+> dcolon <+> ppr ty)
1313
1314 -----------------------------------------------
1315 restrictedBindCtxtErr :: [Name] -> SDoc
1316 restrictedBindCtxtErr binder_names
1317   = hang (ptext (sLit "Illegal overloaded type signature(s)"))
1318        4 (vcat [ptext (sLit "in a binding group for") <+> pprBinders binder_names,
1319                 ptext (sLit "that falls under the monomorphism restriction")])
1320
1321 genCtxt :: [Name] -> SDoc
1322 genCtxt binder_names
1323   = ptext (sLit "When generalising the type(s) for") <+> pprBinders binder_names
1324
1325 missingSigWarn :: Bool -> Name -> Type -> TcM ()
1326 missingSigWarn False _    _  = return ()
1327 missingSigWarn True  name ty
1328   = do  { env0 <- tcInitTidyEnv
1329         ; let (env1, tidy_ty) = tidyOpenType env0 ty
1330         ; addWarnTcM (env1, mk_msg tidy_ty) }
1331   where
1332     mk_msg ty = vcat [ptext (sLit "Definition but no type signature for") <+> quotes (ppr name),
1333                       sep [ptext (sLit "Inferred type:") <+> pprHsVar name <+> dcolon <+> ppr ty]]
1334 \end{code}