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