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