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