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