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