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