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