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