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