Improve error message layouts
[ghc-hetmet.git] / compiler / typecheck / TcBinds.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcBinds]{TcBinds}
5
6 \begin{code}
7 module TcBinds ( tcLocalBinds, tcTopBinds, 
8                  tcHsBootSigs, tcMonoBinds, 
9                  TcPragFun, tcSpecPrag, tcPrags, mkPragFun, 
10                  TcSigInfo(..), TcSigFun, mkTcSigFun,
11                  badBootDeclErr ) where
12
13 #include "HsVersions.h"
14
15 import {-# SOURCE #-} TcMatches ( tcGRHSsPat, tcMatchesFun )
16 import {-# SOURCE #-} TcExpr  ( tcMonoExpr )
17
18 import DynFlags         ( dopt, DynFlags,
19                           DynFlag(Opt_MonomorphismRestriction, Opt_MonoPatBinds, Opt_GlasgowExts) )
20 import HsSyn            ( HsExpr(..), HsBind(..), LHsBinds, LHsBind, Sig(..),
21                           HsLocalBinds(..), HsValBinds(..), HsIPBinds(..),
22                           LSig, Match(..), IPBind(..), Prag(..),
23                           HsType(..), LHsType, HsExplicitForAll(..), hsLTyVarNames, 
24                           isVanillaLSig, sigName, placeHolderNames, isPragLSig,
25                           LPat, GRHSs, MatchGroup(..), pprLHsBinds, mkHsCoerce,
26                           collectHsBindBinders, collectPatBinders, pprPatBind, isBangHsBind
27                         )
28 import TcHsSyn          ( zonkId )
29
30 import TcRnMonad
31 import Inst             ( newDictsAtLoc, newIPDict, instToId )
32 import TcEnv            ( tcExtendIdEnv, tcExtendIdEnv2, tcExtendTyVarEnv2, 
33                           pprBinders, tcLookupLocalId_maybe, tcLookupId,
34                           tcGetGlobalTyVars )
35 import TcUnify          ( tcInfer, tcSubExp, unifyTheta, 
36                           bleatEscapedTvs, sigCtxt )
37 import TcSimplify       ( tcSimplifyInfer, tcSimplifyInferCheck, 
38                           tcSimplifyRestricted, tcSimplifyIPs )
39 import TcHsType         ( tcHsSigType, UserTypeCtxt(..) )
40 import TcPat            ( tcPat, PatCtxt(..) )
41 import TcSimplify       ( bindInstsOfLocalFuns )
42 import TcMType          ( newFlexiTyVarTy, zonkQuantifiedTyVar, zonkSigTyVar,
43                           tcInstSigTyVars, tcInstSkolTyVars, tcInstType, 
44                           zonkTcType, zonkTcTypes, zonkTcTyVars )
45 import TcType           ( TcType, TcTyVar, TcThetaType, 
46                           SkolemInfo(SigSkol), UserTypeCtxt(FunSigCtxt), 
47                           TcTauType, TcSigmaType, isUnboxedTupleType,
48                           mkTyVarTy, mkForAllTys, mkFunTys, exactTyVarsOfType, 
49                           mkForAllTy, isUnLiftedType, tcGetTyVar, 
50                           mkTyVarTys, tidyOpenTyVar )
51 import Kind             ( argTypeKind )
52 import VarEnv           ( TyVarEnv, emptyVarEnv, lookupVarEnv, extendVarEnv ) 
53 import TysWiredIn       ( unitTy )
54 import TysPrim          ( alphaTyVar )
55 import Id               ( Id, mkLocalId, mkVanillaGlobal )
56 import IdInfo           ( vanillaIdInfo )
57 import Var              ( TyVar, idType, idName )
58 import Name             ( Name )
59 import NameSet
60 import NameEnv
61 import VarSet
62 import SrcLoc           ( Located(..), unLoc, getLoc )
63 import Bag
64 import ErrUtils         ( Message )
65 import Digraph          ( SCC(..), stronglyConnComp )
66 import Maybes           ( expectJust, isJust, isNothing, orElse )
67 import Util             ( singleton )
68 import BasicTypes       ( TopLevelFlag(..), isTopLevel, isNotTopLevel,
69                           RecFlag(..), isNonRec, InlineSpec, defaultInlineSpec )
70 import Outputable
71 \end{code}
72
73
74 %************************************************************************
75 %*                                                                      *
76 \subsection{Type-checking bindings}
77 %*                                                                      *
78 %************************************************************************
79
80 @tcBindsAndThen@ typechecks a @HsBinds@.  The "and then" part is because
81 it needs to know something about the {\em usage} of the things bound,
82 so that it can create specialisations of them.  So @tcBindsAndThen@
83 takes a function which, given an extended environment, E, typechecks
84 the scope of the bindings returning a typechecked thing and (most
85 important) an LIE.  It is this LIE which is then used as the basis for
86 specialising the things bound.
87
88 @tcBindsAndThen@ also takes a "combiner" which glues together the
89 bindings and the "thing" to make a new "thing".
90
91 The real work is done by @tcBindWithSigsAndThen@.
92
93 Recursive and non-recursive binds are handled in essentially the same
94 way: because of uniques there are no scoping issues left.  The only
95 difference is that non-recursive bindings can bind primitive values.
96
97 Even for non-recursive binding groups we add typings for each binder
98 to the LVE for the following reason.  When each individual binding is
99 checked the type of its LHS is unified with that of its RHS; and
100 type-checking the LHS of course requires that the binder is in scope.
101
102 At the top-level the LIE is sure to contain nothing but constant
103 dictionaries, which we resolve at the module level.
104
105 \begin{code}
106 tcTopBinds :: HsValBinds Name -> TcM (LHsBinds TcId, TcLclEnv)
107         -- Note: returning the TcLclEnv is more than we really
108         --       want.  The bit we care about is the local bindings
109         --       and the free type variables thereof
110 tcTopBinds binds
111   = do  { (ValBindsOut prs _, env) <- tcValBinds TopLevel binds getLclEnv
112         ; return (foldr (unionBags . snd) emptyBag prs, env) }
113         -- The top level bindings are flattened into a giant 
114         -- implicitly-mutually-recursive LHsBinds
115
116 tcHsBootSigs :: HsValBinds Name -> TcM [Id]
117 -- A hs-boot file has only one BindGroup, and it only has type
118 -- signatures in it.  The renamer checked all this
119 tcHsBootSigs (ValBindsOut binds sigs)
120   = do  { checkTc (null binds) badBootDeclErr
121         ; mapM (addLocM tc_boot_sig) (filter isVanillaLSig sigs) }
122   where
123     tc_boot_sig (TypeSig (L _ name) ty)
124       = do { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
125            ; return (mkVanillaGlobal name sigma_ty vanillaIdInfo) }
126         -- Notice that we make GlobalIds, not LocalIds
127 tcHsBootSigs groups = pprPanic "tcHsBootSigs" (ppr groups)
128
129 badBootDeclErr :: Message
130 badBootDeclErr = ptext SLIT("Illegal declarations in an hs-boot file")
131
132 ------------------------
133 tcLocalBinds :: HsLocalBinds Name -> TcM thing
134              -> TcM (HsLocalBinds TcId, thing)
135
136 tcLocalBinds EmptyLocalBinds thing_inside 
137   = do  { thing <- thing_inside
138         ; return (EmptyLocalBinds, thing) }
139
140 tcLocalBinds (HsValBinds binds) thing_inside
141   = do  { (binds', thing) <- tcValBinds NotTopLevel binds thing_inside
142         ; return (HsValBinds binds', thing) }
143
144 tcLocalBinds (HsIPBinds (IPBinds ip_binds _)) thing_inside
145   = do  { (thing, lie) <- getLIE thing_inside
146         ; (avail_ips, ip_binds') <- mapAndUnzipM (wrapLocSndM tc_ip_bind) ip_binds
147
148         -- If the binding binds ?x = E, we  must now 
149         -- discharge any ?x constraints in expr_lie
150         ; dict_binds <- tcSimplifyIPs avail_ips lie
151         ; return (HsIPBinds (IPBinds ip_binds' dict_binds), thing) }
152   where
153         -- I wonder if we should do these one at at time
154         -- Consider     ?x = 4
155         --              ?y = ?x + 1
156     tc_ip_bind (IPBind ip expr)
157       = newFlexiTyVarTy argTypeKind             `thenM` \ ty ->
158         newIPDict (IPBindOrigin ip) ip ty       `thenM` \ (ip', ip_inst) ->
159         tcMonoExpr expr ty                      `thenM` \ expr' ->
160         returnM (ip_inst, (IPBind ip' expr'))
161
162 ------------------------
163 tcValBinds :: TopLevelFlag 
164            -> HsValBinds Name -> TcM thing
165            -> TcM (HsValBinds TcId, thing) 
166
167 tcValBinds top_lvl (ValBindsIn binds sigs) thing_inside
168   = pprPanic "tcValBinds" (ppr binds)
169
170 tcValBinds top_lvl (ValBindsOut binds sigs) thing_inside
171   = do  {       -- Typecheck the signature
172         ; let { prag_fn = mkPragFun sigs
173               ; ty_sigs = filter isVanillaLSig sigs
174               ; sig_fn  = mkTcSigFun ty_sigs }
175
176         ; poly_ids <- mapM tcTySig ty_sigs
177                 -- No recovery from bad signatures, because the type sigs
178                 -- may bind type variables, so proceeding without them
179                 -- can lead to a cascade of errors
180                 -- ToDo: this means we fall over immediately if any type sig
181                 -- is wrong, which is over-conservative, see Trac bug #745
182
183                 -- Extend the envt right away with all 
184                 -- the Ids declared with type signatures
185         ; (binds', thing) <- tcExtendIdEnv poly_ids $
186                              tc_val_binds top_lvl sig_fn prag_fn 
187                                           binds thing_inside
188
189         ; return (ValBindsOut binds' sigs, thing) }
190
191 ------------------------
192 tc_val_binds :: TopLevelFlag -> TcSigFun -> TcPragFun
193              -> [(RecFlag, LHsBinds Name)] -> TcM thing
194              -> TcM ([(RecFlag, LHsBinds TcId)], thing)
195 -- Typecheck a whole lot of value bindings,
196 -- one strongly-connected component at a time
197
198 tc_val_binds top_lvl sig_fn prag_fn [] thing_inside
199   = do  { thing <- thing_inside
200         ; return ([], thing) }
201
202 tc_val_binds top_lvl sig_fn prag_fn (group : groups) thing_inside
203   = do  { (group', (groups', thing))
204                 <- tc_group top_lvl sig_fn prag_fn group $ 
205                    tc_val_binds top_lvl sig_fn prag_fn groups thing_inside
206         ; return (group' ++ groups', thing) }
207
208 ------------------------
209 tc_group :: TopLevelFlag -> TcSigFun -> TcPragFun
210          -> (RecFlag, LHsBinds Name) -> TcM thing
211          -> TcM ([(RecFlag, LHsBinds TcId)], thing)
212
213 -- Typecheck one strongly-connected component of the original program.
214 -- We get a list of groups back, because there may 
215 -- be specialisations etc as well
216
217 tc_group top_lvl sig_fn prag_fn (NonRecursive, binds) thing_inside
218   =     -- A single non-recursive binding
219         -- We want to keep non-recursive things non-recursive
220         -- so that we desugar unlifted bindings correctly
221     do  { (binds, thing) <- tcPolyBinds top_lvl NonRecursive NonRecursive
222                                         sig_fn prag_fn binds thing_inside
223         ; return ([(NonRecursive, b) | b <- binds], thing) }
224
225 tc_group top_lvl sig_fn prag_fn (Recursive, binds) thing_inside
226   =     -- A recursive strongly-connected component
227         -- To maximise polymorphism (with -fglasgow-exts), we do a new 
228         -- strongly-connected-component analysis, this time omitting 
229         -- any references to variables with type signatures.
230         --
231         -- Then we bring into scope all the variables with type signatures
232     do  { traceTc (text "tc_group rec" <+> pprLHsBinds binds)
233         ; gla_exts     <- doptM Opt_GlasgowExts
234         ; (binds,thing) <- if gla_exts 
235                            then go new_sccs
236                            else tc_binds Recursive binds thing_inside
237         ; return ([(Recursive, unionManyBags binds)], thing) }
238                 -- Rec them all together
239   where
240     new_sccs :: [SCC (LHsBind Name)]
241     new_sccs = stronglyConnComp (mkEdges sig_fn binds)
242
243 --  go :: SCC (LHsBind Name) -> TcM ([LHsBind TcId], thing)
244     go (scc:sccs) = do  { (binds1, (binds2, thing)) <- go1 scc (go sccs)
245                         ; return (binds1 ++ binds2, thing) }
246     go []         = do  { thing <- thing_inside; return ([], thing) }
247
248     go1 (AcyclicSCC bind) = tc_binds NonRecursive (unitBag bind)
249     go1 (CyclicSCC binds) = tc_binds Recursive    (listToBag binds)
250
251     tc_binds rec_tc binds = tcPolyBinds top_lvl Recursive rec_tc sig_fn prag_fn binds
252
253 ------------------------
254 mkEdges :: TcSigFun -> LHsBinds Name
255         -> [(LHsBind Name, BKey, [BKey])]
256
257 type BKey  = Int -- Just number off the bindings
258
259 mkEdges sig_fn binds
260   = [ (bind, key, [key | n <- nameSetToList (bind_fvs (unLoc bind)),
261                          Just key <- [lookupNameEnv key_map n], no_sig n ])
262     | (bind, key) <- keyd_binds
263     ]
264   where
265     no_sig :: Name -> Bool
266     no_sig n = isNothing (sig_fn n)
267
268     keyd_binds = bagToList binds `zip` [0::BKey ..]
269
270     key_map :: NameEnv BKey     -- Which binding it comes from
271     key_map = mkNameEnv [(bndr, key) | (L _ bind, key) <- keyd_binds
272                                      , bndr <- bindersOfHsBind bind ]
273
274 bindersOfHsBind :: HsBind Name -> [Name]
275 bindersOfHsBind (PatBind { pat_lhs = pat })  = collectPatBinders pat
276 bindersOfHsBind (FunBind { fun_id = L _ f }) = [f]
277
278 ------------------------
279 tcPolyBinds :: TopLevelFlag 
280             -> RecFlag                  -- Whether the group is really recursive
281             -> RecFlag                  -- Whether it's recursive for typechecking purposes
282             -> TcSigFun -> TcPragFun
283             -> LHsBinds Name
284             -> TcM thing
285             -> TcM ([LHsBinds TcId], thing)
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 -- Deals with the bindInstsOfLocalFuns thing too
292 --
293 -- Returns a list because the input may be a single non-recursive binding,
294 -- in which case the dependency order of the resulting bindings is
295 -- important.  
296
297 tcPolyBinds top_lvl rec_group rec_tc sig_fn prag_fn scc thing_inside
298   =     -- NB: polymorphic recursion means that a function
299         -- may use an instance of itself, we must look at the LIE arising
300         -- from the function's own right hand side.  Hence the getLIE
301         -- encloses the tc_poly_binds. 
302     do  { traceTc (text "tcPolyBinds" <+> ppr scc)
303         ; ((binds1, poly_ids, thing), lie) <- getLIE $ 
304                 do { (binds1, poly_ids) <- tc_poly_binds top_lvl rec_group rec_tc
305                                                          sig_fn prag_fn scc
306                    ; thing <- tcExtendIdEnv poly_ids thing_inside
307                    ; return (binds1, poly_ids, thing) }
308
309         ; if isTopLevel top_lvl 
310           then          -- For the top level don't bother will all this
311                         -- bindInstsOfLocalFuns stuff. All the top level 
312                         -- things are rec'd together anyway, so it's fine to
313                         -- leave them to the tcSimplifyTop, 
314                         -- and quite a bit faster too
315                 do { extendLIEs lie; return (binds1, thing) }
316
317           else do       -- Nested case
318                 { lie_binds <- bindInstsOfLocalFuns lie poly_ids
319                 ; return (binds1 ++ [lie_binds], thing) }}
320
321 ------------------------
322 tc_poly_binds :: TopLevelFlag           -- See comments on tcPolyBinds
323               -> RecFlag -> RecFlag
324               -> TcSigFun -> TcPragFun
325               -> LHsBinds Name
326               -> TcM ([LHsBinds TcId], [TcId])
327 -- Typechecks the bindings themselves
328 -- Knows nothing about the scope of the bindings
329
330 tc_poly_binds top_lvl rec_group rec_tc sig_fn prag_fn binds
331   = let 
332         binder_names = collectHsBindBinders binds
333         bind_list    = bagToList binds
334
335         loc = getLoc (head bind_list)
336                 -- TODO: location a bit awkward, but the mbinds have been
337                 --       dependency analysed and may no longer be adjacent
338     in
339         -- SET UP THE MAIN RECOVERY; take advantage of any type sigs
340     setSrcSpan loc                              $
341     recoverM (recoveryCode binder_names)        $ do 
342
343   { traceTc (ptext SLIT("------------------------------------------------"))
344   ; traceTc (ptext SLIT("Bindings for") <+> ppr binder_names)
345
346         -- TYPECHECK THE BINDINGS
347   ; ((binds', mono_bind_infos), lie_req) 
348         <- getLIE (tcMonoBinds bind_list sig_fn rec_tc)
349
350         -- CHECK FOR UNLIFTED BINDINGS
351         -- These must be non-recursive etc, and are not generalised
352         -- They desugar to a case expression in the end
353   ; zonked_mono_tys <- zonkTcTypes (map getMonoType mono_bind_infos)
354   ; is_strict <- checkStrictBinds top_lvl rec_group binds' 
355                                   zonked_mono_tys mono_bind_infos
356   ; if is_strict then
357     do  { extendLIEs lie_req
358         ; let exports = zipWith mk_export mono_bind_infos zonked_mono_tys
359               mk_export (name, Nothing,  mono_id) mono_ty = ([], mkLocalId name mono_ty, mono_id, [])
360               mk_export (name, Just sig, mono_id) mono_ty = ([], sig_id sig,             mono_id, [])
361                         -- ToDo: prags for unlifted bindings
362
363         ; return ( [unitBag $ L loc $ AbsBinds [] [] exports binds'],
364                    [poly_id | (_, poly_id, _, _) <- exports]) } -- Guaranteed zonked
365
366     else do     -- The normal lifted case: GENERALISE
367   { dflags <- getDOpts 
368   ; (tyvars_to_gen, dict_binds, dict_ids)
369         <- addErrCtxt (genCtxt (bndrNames mono_bind_infos)) $
370            generalise dflags top_lvl bind_list sig_fn mono_bind_infos lie_req
371
372         -- FINALISE THE QUANTIFIED TYPE VARIABLES
373         -- The quantified type variables often include meta type variables
374         -- we want to freeze them into ordinary type variables, and
375         -- default their kind (e.g. from OpenTypeKind to TypeKind)
376   ; tyvars_to_gen' <- mappM zonkQuantifiedTyVar tyvars_to_gen
377
378         -- BUILD THE POLYMORPHIC RESULT IDs
379   ; exports <- mapM (mkExport prag_fn tyvars_to_gen' (map idType dict_ids))
380                     mono_bind_infos
381
382         -- ZONK THE poly_ids, because they are used to extend the type 
383         -- environment; see the invariant on TcEnv.tcExtendIdEnv 
384   ; let poly_ids = [poly_id | (_, poly_id, _, _) <- exports]
385   ; zonked_poly_ids <- mappM zonkId poly_ids
386
387   ; traceTc (text "binding:" <+> ppr (zonked_poly_ids `zip` map idType zonked_poly_ids))
388
389   ; let abs_bind = L loc $ AbsBinds tyvars_to_gen'
390                                     dict_ids exports
391                                     (dict_binds `unionBags` binds')
392
393   ; return ([unitBag abs_bind], zonked_poly_ids)
394   } }
395
396
397 --------------
398 mkExport :: TcPragFun -> [TyVar] -> [TcType] -> MonoBindInfo
399          -> TcM ([TyVar], Id, Id, [Prag])
400 mkExport prag_fn inferred_tvs dict_tys (poly_name, mb_sig, mono_id)
401   = case mb_sig of
402       Nothing  -> do { prags <- tcPrags poly_id (prag_fn poly_name)
403                      ; return (inferred_tvs, poly_id, mono_id, prags) }
404           where
405             poly_id = mkLocalId poly_name poly_ty
406             poly_ty = mkForAllTys inferred_tvs
407                                        $ mkFunTys dict_tys 
408                                        $ idType mono_id
409
410       Just sig -> do { let poly_id = sig_id sig
411                      ; prags <- tcPrags poly_id (prag_fn poly_name)
412                      ; sig_tys <- zonkTcTyVars (sig_tvs sig)
413                      ; let sig_tvs' = map (tcGetTyVar "mkExport") sig_tys
414                      ; return (sig_tvs', poly_id, mono_id, prags) }
415                 -- We zonk the sig_tvs here so that the export triple
416                 -- always has zonked type variables; 
417                 -- a convenient invariant
418
419
420 ------------------------
421 type TcPragFun = Name -> [LSig Name]
422
423 mkPragFun :: [LSig Name] -> TcPragFun
424 mkPragFun sigs = \n -> lookupNameEnv env n `orElse` []
425         where
426           prs = [(expectJust "mkPragFun" (sigName sig), sig) 
427                 | sig <- sigs, isPragLSig sig]
428           env = foldl add emptyNameEnv prs
429           add env (n,p) = extendNameEnv_Acc (:) singleton env n p
430
431 tcPrags :: Id -> [LSig Name] -> TcM [Prag]
432 tcPrags poly_id prags = mapM tc_prag prags
433   where
434     tc_prag (L loc prag) = setSrcSpan loc $ 
435                            addErrCtxt (pragSigCtxt prag) $ 
436                            tcPrag poly_id prag
437
438 pragSigCtxt prag = hang (ptext SLIT("In the pragma")) 2 (ppr prag)
439
440 tcPrag :: TcId -> Sig Name -> TcM Prag
441 tcPrag poly_id (SpecSig orig_name hs_ty inl) = tcSpecPrag poly_id hs_ty inl
442 tcPrag poly_id (SpecInstSig hs_ty)           = tcSpecPrag poly_id hs_ty defaultInlineSpec
443 tcPrag poly_id (InlineSig v inl)             = return (InlinePrag inl)
444
445
446 tcSpecPrag :: TcId -> LHsType Name -> InlineSpec -> TcM Prag
447 tcSpecPrag poly_id hs_ty inl
448   = do  { spec_ty <- tcHsSigType (FunSigCtxt (idName poly_id)) hs_ty
449         ; (co_fn, lie) <- getLIE (tcSubExp (idType poly_id) spec_ty)
450         ; extendLIEs lie
451         ; let const_dicts = map instToId lie
452         ; return (SpecPrag (mkHsCoerce co_fn (HsVar poly_id)) spec_ty const_dicts inl) }
453         -- Most of the work of specialisation is done by 
454         -- the desugarer, guided by the SpecPrag
455   
456 --------------
457 -- If typechecking the binds fails, then return with each
458 -- signature-less binder given type (forall a.a), to minimise 
459 -- subsequent error messages
460 recoveryCode binder_names
461   = do  { traceTc (text "tcBindsWithSigs: error recovery" <+> ppr binder_names)
462         ; poly_ids <- mapM mk_dummy binder_names
463         ; return ([], poly_ids) }
464   where
465     mk_dummy name = do { mb_id <- tcLookupLocalId_maybe name
466                         ; case mb_id of
467                               Just id -> return id              -- Had signature, was in envt
468                               Nothing -> return (mkLocalId name forall_a_a) }    -- No signature
469
470 forall_a_a :: TcType
471 forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
472
473
474 -- Check that non-overloaded unlifted bindings are
475 --      a) non-recursive,
476 --      b) not top level, 
477 --      c) not a multiple-binding group (more or less implied by (a))
478
479 checkStrictBinds :: TopLevelFlag -> RecFlag
480                  -> LHsBinds TcId -> [TcType] -> [MonoBindInfo]
481                  -> TcM Bool
482 checkStrictBinds top_lvl rec_group mbind mono_tys infos
483   | unlifted || bang_pat
484   = do  { checkTc (isNotTopLevel top_lvl)
485                   (strictBindErr "Top-level" unlifted mbind)
486         ; checkTc (isNonRec rec_group)
487                   (strictBindErr "Recursive" unlifted mbind)
488         ; checkTc (isSingletonBag mbind)
489                   (strictBindErr "Multiple" unlifted mbind) 
490         ; mapM_ check_sig infos
491         ; return True }
492   | otherwise
493   = return False
494   where
495     unlifted = any isUnLiftedType mono_tys
496     bang_pat = anyBag (isBangHsBind . unLoc) mbind
497     check_sig (_, Just sig, _) = checkTc (null (sig_tvs sig) && null (sig_theta sig))
498                                          (badStrictSig unlifted sig)
499     check_sig other            = return ()
500
501 strictBindErr flavour unlifted mbind
502   = hang (text flavour <+> msg <+> ptext SLIT("aren't allowed:")) 
503          4 (pprLHsBinds mbind)
504   where
505     msg | unlifted  = ptext SLIT("bindings for unlifted types")
506         | otherwise = ptext SLIT("bang-pattern bindings")
507
508 badStrictSig unlifted sig
509   = hang (ptext SLIT("Illegal polymorphic signature in") <+> msg)
510          4 (ppr sig)
511   where
512     msg | unlifted  = ptext SLIT("an unlifted binding")
513         | otherwise = ptext SLIT("a bang-pattern binding")
514 \end{code}
515
516
517 %************************************************************************
518 %*                                                                      *
519 \subsection{tcMonoBind}
520 %*                                                                      *
521 %************************************************************************
522
523 @tcMonoBinds@ deals with a perhaps-recursive group of HsBinds.
524 The signatures have been dealt with already.
525
526 \begin{code}
527 tcMonoBinds :: [LHsBind Name]
528             -> TcSigFun
529             -> RecFlag  -- Whether the binding is recursive for typechecking purposes
530                         -- i.e. the binders are mentioned in their RHSs, and
531                         --      we are not resuced by a type signature
532             -> TcM (LHsBinds TcId, [MonoBindInfo])
533
534 tcMonoBinds [L b_loc (FunBind { fun_id = L nm_loc name, fun_infix = inf, 
535                                 fun_matches = matches, bind_fvs = fvs })]
536             sig_fn              -- Single function binding,
537             NonRecursive        -- binder isn't mentioned in RHS,
538   | Nothing <- sig_fn name      -- ...with no type signature
539   =     -- In this very special case we infer the type of the
540         -- right hand side first (it may have a higher-rank type)
541         -- and *then* make the monomorphic Id for the LHS
542         -- e.g.         f = \(x::forall a. a->a) -> <body>
543         --      We want to infer a higher-rank type for f
544     setSrcSpan b_loc    $
545     do  { ((co_fn, matches'), rhs_ty) <- tcInfer (tcMatchesFun name matches)
546
547                 -- Check for an unboxed tuple type
548                 --      f = (# True, False #)
549                 -- Zonk first just in case it's hidden inside a meta type variable
550                 -- (This shows up as a (more obscure) kind error 
551                 --  in the 'otherwise' case of tcMonoBinds.)
552         ; zonked_rhs_ty <- zonkTcType rhs_ty
553         ; checkTc (not (isUnboxedTupleType zonked_rhs_ty))
554                   (unboxedTupleErr name zonked_rhs_ty)
555
556         ; mono_name <- newLocalName name
557         ; let mono_id = mkLocalId mono_name zonked_rhs_ty
558         ; return (unitBag (L b_loc (FunBind { fun_id = L nm_loc mono_id, fun_infix = inf,
559                                               fun_matches = matches', bind_fvs = fvs,
560                                               fun_co_fn = co_fn })),
561                   [(name, Nothing, mono_id)]) }
562
563 tcMonoBinds [L b_loc (FunBind { fun_id = L nm_loc name, fun_infix = inf, 
564                                 fun_matches = matches, bind_fvs = fvs })]
565             sig_fn              -- Single function binding
566             non_rec     
567   | Just scoped_tvs <- sig_fn name      -- ...with a type signature
568   =     -- When we have a single function binding, with a type signature
569         -- we can (a) use genuine, rigid skolem constants for the type variables
570         --        (b) bring (rigid) scoped type variables into scope
571     setSrcSpan b_loc    $
572     do  { tc_sig <- tcInstSig True name scoped_tvs
573         ; mono_name <- newLocalName name
574         ; let mono_ty = sig_tau tc_sig
575               mono_id = mkLocalId mono_name mono_ty
576               rhs_tvs = [ (name, mkTyVarTy tv)
577                         | (name, tv) <- sig_scoped tc_sig `zip` sig_tvs tc_sig ]
578
579         ; (co_fn, matches') <- tcExtendTyVarEnv2 rhs_tvs    $
580                                tcMatchesFun mono_name matches mono_ty
581
582         ; let fun_bind' = FunBind { fun_id = L nm_loc mono_id, 
583                                     fun_infix = inf, fun_matches = matches',
584                                     bind_fvs = placeHolderNames, fun_co_fn = co_fn }
585         ; return (unitBag (L b_loc fun_bind'),
586                   [(name, Just tc_sig, mono_id)]) }
587
588 tcMonoBinds binds sig_fn non_rec
589   = do  { tc_binds <- mapM (wrapLocM (tcLhs sig_fn)) binds
590
591         -- Bring the monomorphic Ids, into scope for the RHSs
592         ; let mono_info  = getMonoBindInfo tc_binds
593               rhs_id_env = [(name,mono_id) | (name, Nothing, mono_id) <- mono_info]
594                                 -- A monomorphic binding for each term variable that lacks 
595                                 -- a type sig.  (Ones with a sig are already in scope.)
596
597         ; binds' <- tcExtendIdEnv2    rhs_id_env $
598                     traceTc (text "tcMonoBinds" <+> vcat [ ppr n <+> ppr id <+> ppr (idType id) 
599                                                          | (n,id) <- rhs_id_env]) `thenM_`
600                     mapM (wrapLocM tcRhs) tc_binds
601         ; return (listToBag binds', mono_info) }
602
603 ------------------------
604 -- tcLhs typechecks the LHS of the bindings, to construct the environment in which
605 -- we typecheck the RHSs.  Basically what we are doing is this: for each binder:
606 --      if there's a signature for it, use the instantiated signature type
607 --      otherwise invent a type variable
608 -- You see that quite directly in the FunBind case.
609 -- 
610 -- But there's a complication for pattern bindings:
611 --      data T = MkT (forall a. a->a)
612 --      MkT f = e
613 -- Here we can guess a type variable for the entire LHS (which will be refined to T)
614 -- but we want to get (f::forall a. a->a) as the RHS environment.
615 -- The simplest way to do this is to typecheck the pattern, and then look up the
616 -- bound mono-ids.  Then we want to retain the typechecked pattern to avoid re-doing
617 -- it; hence the TcMonoBind data type in which the LHS is done but the RHS isn't
618
619 data TcMonoBind         -- Half completed; LHS done, RHS not done
620   = TcFunBind  MonoBindInfo  (Located TcId) Bool (MatchGroup Name) 
621   | TcPatBind [MonoBindInfo] (LPat TcId) (GRHSs Name) TcSigmaType
622
623 type MonoBindInfo = (Name, Maybe TcSigInfo, TcId)
624         -- Type signature (if any), and
625         -- the monomorphic bound things
626
627 bndrNames :: [MonoBindInfo] -> [Name]
628 bndrNames mbi = [n | (n,_,_) <- mbi]
629
630 getMonoType :: MonoBindInfo -> TcTauType
631 getMonoType (_,_,mono_id) = idType mono_id
632
633 tcLhs :: TcSigFun -> HsBind Name -> TcM TcMonoBind
634 tcLhs sig_fn (FunBind { fun_id = L nm_loc name, fun_infix = inf, fun_matches = matches })
635   = do  { mb_sig <- tcInstSig_maybe sig_fn name
636         ; mono_name <- newLocalName name
637         ; mono_ty   <- mk_mono_ty mb_sig
638         ; let mono_id = mkLocalId mono_name mono_ty
639         ; return (TcFunBind (name, mb_sig, mono_id) (L nm_loc mono_id) inf matches) }
640   where
641     mk_mono_ty (Just sig) = return (sig_tau sig)
642     mk_mono_ty Nothing    = newFlexiTyVarTy argTypeKind
643
644 tcLhs sig_fn bind@(PatBind { pat_lhs = pat, pat_rhs = grhss })
645   = do  { mb_sigs <- mapM (tcInstSig_maybe sig_fn) names
646
647         ; let nm_sig_prs  = names `zip` mb_sigs
648               tau_sig_env = mkNameEnv [ (name, sig_tau sig) | (name, Just sig) <- nm_sig_prs]
649               sig_tau_fn  = lookupNameEnv tau_sig_env
650
651               tc_pat exp_ty = tcPat (LetPat sig_tau_fn) pat exp_ty unitTy $ \ _ ->
652                               mapM lookup_info nm_sig_prs
653                 -- The unitTy is a bit bogus; it's the "result type" for lookup_info.  
654
655                 -- After typechecking the pattern, look up the binder
656                 -- names, which the pattern has brought into scope.
657               lookup_info :: (Name, Maybe TcSigInfo) -> TcM MonoBindInfo
658               lookup_info (name, mb_sig) = do { mono_id <- tcLookupId name
659                                               ; return (name, mb_sig, mono_id) }
660
661         ; ((pat', infos), pat_ty) <- addErrCtxt (patMonoBindsCtxt pat grhss) $
662                                      tcInfer tc_pat
663
664         ; return (TcPatBind infos pat' grhss pat_ty) }
665   where
666     names = collectPatBinders pat
667
668
669 tcLhs sig_fn other_bind = pprPanic "tcLhs" (ppr other_bind)
670         -- AbsBind, VarBind impossible
671
672 -------------------
673 tcRhs :: TcMonoBind -> TcM (HsBind TcId)
674 tcRhs (TcFunBind info fun'@(L _ mono_id) inf matches)
675   = do  { (co_fn, matches') <- tcMatchesFun (idName mono_id) matches 
676                                             (idType mono_id)
677         ; return (FunBind { fun_id = fun', fun_infix = inf, fun_matches = matches',
678                             bind_fvs = placeHolderNames, fun_co_fn = co_fn }) }
679
680 tcRhs bind@(TcPatBind _ pat' grhss pat_ty)
681   = do  { grhss' <- addErrCtxt (patMonoBindsCtxt pat' grhss) $
682                     tcGRHSsPat grhss pat_ty
683         ; return (PatBind { pat_lhs = pat', pat_rhs = grhss', pat_rhs_ty = pat_ty, 
684                             bind_fvs = placeHolderNames }) }
685
686
687 ---------------------
688 getMonoBindInfo :: [Located TcMonoBind] -> [MonoBindInfo]
689 getMonoBindInfo tc_binds
690   = foldr (get_info . unLoc) [] tc_binds
691   where
692     get_info (TcFunBind info _ _ _)  rest = info : rest
693     get_info (TcPatBind infos _ _ _) rest = infos ++ rest
694 \end{code}
695
696
697 %************************************************************************
698 %*                                                                      *
699                 Generalisation
700 %*                                                                      *
701 %************************************************************************
702
703 \begin{code}
704 generalise :: DynFlags -> TopLevelFlag 
705            -> [LHsBind Name] -> TcSigFun 
706            -> [MonoBindInfo] -> [Inst]
707            -> TcM ([TcTyVar], TcDictBinds, [TcId])
708 generalise dflags top_lvl bind_list sig_fn mono_infos lie_req
709   | isMonoGroup dflags bind_list
710   = do { extendLIEs lie_req; 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
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
738         -- Check that the needed dicts can be
739         -- expressed in terms of the signature ones
740         ; (forall_tvs, dict_binds) <- tcSimplifyInferCheck doc tau_tvs sig_avails lie_req
741         
742         -- Check that signature type variables are OK
743         ; final_qtvs <- checkSigsTyVars forall_tvs sigs
744
745         ; returnM (final_qtvs, dict_binds, map instToId sig_lie) }
746   where
747     bndrs   = bndrNames mono_infos
748     sigs    = [sig | (_, Just sig, _) <- mono_infos]
749     tau_tvs = foldr (unionVarSet . exactTyVarsOfType . getMonoType) emptyVarSet mono_infos
750                 -- NB: exactTyVarsOfType; see Note [Silly type synonym] 
751                 --     near defn of TcType.exactTyVarsOfType
752     is_mono_sig sig = null (sig_theta sig)
753     doc = ptext SLIT("type signature(s) for") <+> pprBinders bndrs
754
755     mkMethInst (TcSigInfo { sig_id = poly_id, sig_tvs = tvs, 
756                             sig_theta = theta, sig_loc = loc }) mono_id
757       = Method mono_id poly_id (mkTyVarTys tvs) theta loc
758 \end{code}
759
760 unifyCtxts checks that all the signature contexts are the same
761 The type signatures on a mutually-recursive group of definitions
762 must all have the same context (or none).
763
764 The trick here is that all the signatures should have the same
765 context, and we want to share type variables for that context, so that
766 all the right hand sides agree a common vocabulary for their type
767 constraints
768
769 We unify them because, with polymorphic recursion, their types
770 might not otherwise be related.  This is a rather subtle issue.
771
772 \begin{code}
773 unifyCtxts :: [TcSigInfo] -> TcM [Inst]
774 unifyCtxts (sig1 : sigs)        -- Argument is always non-empty
775   = do  { mapM unify_ctxt sigs
776         ; newDictsAtLoc (sig_loc sig1) (sig_theta sig1) }
777   where
778     theta1 = sig_theta sig1
779     unify_ctxt :: TcSigInfo -> TcM ()
780     unify_ctxt sig@(TcSigInfo { sig_theta = theta })
781         = setSrcSpan (instLocSrcSpan (sig_loc sig))     $
782           addErrCtxt (sigContextsCtxt sig1 sig)         $
783           unifyTheta theta1 theta
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, scoped_tyvars hs_ty)
977                     | L span (TypeSig (L _ name) (L _ hs_ty)) <- sigs]
978     scoped_tyvars (HsForAllTy Explicit tvs _ _) = hsLTyVarNames tvs
979     scoped_tyvars other                         = []
980         -- The scoped names are the ones explicitly mentioned
981         -- in the HsForAll.  (There may be more in sigma_ty, because
982         -- of nested type synonyms.  See Note [Scoped] with TcSigInfo.)
983
984 ---------------
985 data TcSigInfo
986   = TcSigInfo {
987         sig_id     :: TcId,             --  *Polymorphic* binder for this value...
988
989         sig_scoped :: [Name],           -- Names for any scoped type variables
990                                         -- Invariant: correspond 1-1 with an initial
991                                         -- segment of sig_tvs (see Note [Scoped])
992
993         sig_tvs    :: [TcTyVar],        -- Instantiated type variables
994                                         -- See Note [Instantiate sig]
995
996         sig_theta  :: TcThetaType,      -- Instantiated theta
997         sig_tau    :: TcTauType,        -- Instantiated tau
998         sig_loc    :: InstLoc           -- The location of the signature
999     }
1000
1001 --      Note [Scoped]
1002 -- There may be more instantiated type variables than scoped 
1003 -- ones.  For example:
1004 --      type T a = forall b. b -> (a,b)
1005 --      f :: forall c. T c
1006 -- Here, the signature for f will have one scoped type variable, c,
1007 -- but two instantiated type variables, c' and b'.  
1008 --
1009 -- We assume that the scoped ones are at the *front* of sig_tvs,
1010 -- and remember the names from the original HsForAllTy in sig_scoped
1011
1012 --      Note [Instantiate sig]
1013 -- It's vital to instantiate a type signature with fresh variable.
1014 -- For example:
1015 --      type S = forall a. a->a
1016 --      f,g :: S
1017 --      f = ...
1018 --      g = ...
1019 -- Here, we must use distinct type variables when checking f,g's right hand sides.
1020 -- (Instantiation is only necessary because of type synonyms.  Otherwise,
1021 -- it's all cool; each signature has distinct type variables from the renamer.)
1022
1023 instance Outputable TcSigInfo where
1024     ppr (TcSigInfo { sig_id = id, sig_tvs = tyvars, sig_theta = theta, sig_tau = tau})
1025         = ppr id <+> ptext SLIT("::") <+> ppr tyvars <+> ppr theta <+> ptext SLIT("=>") <+> ppr tau
1026 \end{code}
1027
1028 \begin{code}
1029 tcTySig :: LSig Name -> TcM TcId
1030 tcTySig (L span (TypeSig (L _ name) ty))
1031   = setSrcSpan span             $
1032     do  { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
1033         ; return (mkLocalId name sigma_ty) }
1034
1035 -------------------
1036 tcInstSig_maybe :: TcSigFun -> Name -> TcM (Maybe TcSigInfo)
1037 -- Instantiate with *meta* type variables; 
1038 -- this signature is part of a multi-signature group
1039 tcInstSig_maybe sig_fn name 
1040   = case sig_fn name of
1041         Nothing  -> return Nothing
1042         Just tvs -> do  { tc_sig <- tcInstSig False name tvs
1043                         ; return (Just tc_sig) }
1044
1045 tcInstSig :: Bool -> Name -> [Name] -> TcM TcSigInfo
1046 -- Instantiate the signature, with either skolems or meta-type variables
1047 -- depending on the use_skols boolean
1048 --
1049 -- We always instantiate with freshs uniques,
1050 -- although we keep the same print-name
1051 --      
1052 --      type T = forall a. [a] -> [a]
1053 --      f :: T; 
1054 --      f = g where { g :: T; g = <rhs> }
1055 --
1056 -- We must not use the same 'a' from the defn of T at both places!!
1057
1058 tcInstSig use_skols name scoped_names
1059   = do  { poly_id <- tcLookupId name    -- Cannot fail; the poly ids are put into 
1060                                         -- scope when starting the binding group
1061         ; let skol_info = SigSkol (FunSigCtxt name)
1062               inst_tyvars | use_skols = tcInstSkolTyVars skol_info
1063                           | otherwise = tcInstSigTyVars  skol_info
1064         ; (tvs, theta, tau) <- tcInstType inst_tyvars (idType poly_id)
1065         ; loc <- getInstLoc (SigOrigin skol_info)
1066         ; return (TcSigInfo { sig_id = poly_id,
1067                               sig_tvs = tvs, sig_theta = theta, sig_tau = tau, 
1068                               sig_scoped = final_scoped_names, sig_loc = loc }) }
1069                 -- Note that the scoped_names and the sig_tvs will have
1070                 -- different Names. That's quite ok; when we bring the 
1071                 -- scoped_names into scope, we just bind them to the sig_tvs
1072   where
1073         -- We also only have scoped type variables when we are instantiating
1074         -- with true skolems
1075     final_scoped_names | use_skols = scoped_names
1076                        | otherwise = []
1077
1078 -------------------
1079 isMonoGroup :: DynFlags -> [LHsBind Name] -> Bool
1080 -- No generalisation at all
1081 isMonoGroup dflags binds
1082   = dopt Opt_MonoPatBinds dflags && any is_pat_bind binds
1083   where
1084     is_pat_bind (L _ (PatBind {})) = True
1085     is_pat_bind other              = False
1086
1087 -------------------
1088 isRestrictedGroup :: DynFlags -> [LHsBind Name] -> TcSigFun -> Bool
1089 isRestrictedGroup dflags binds sig_fn
1090   = mono_restriction && not all_unrestricted
1091   where 
1092     mono_restriction = dopt Opt_MonomorphismRestriction dflags
1093     all_unrestricted = all (unrestricted . unLoc) binds
1094     has_sig n = isJust (sig_fn n)
1095
1096     unrestricted (PatBind {})                                    = False
1097     unrestricted (VarBind { var_id = v })                        = has_sig v
1098     unrestricted (FunBind { fun_id = v, fun_matches = matches }) = unrestricted_match matches 
1099                                                                  || has_sig (unLoc v)
1100
1101     unrestricted_match (MatchGroup (L _ (Match [] _ _) : _) _) = False
1102         -- No args => like a pattern binding
1103     unrestricted_match other              = True
1104         -- Some args => a function binding
1105 \end{code}
1106
1107
1108 %************************************************************************
1109 %*                                                                      *
1110 \subsection[TcBinds-errors]{Error contexts and messages}
1111 %*                                                                      *
1112 %************************************************************************
1113
1114
1115 \begin{code}
1116 -- This one is called on LHS, when pat and grhss are both Name 
1117 -- and on RHS, when pat is TcId and grhss is still Name
1118 patMonoBindsCtxt pat grhss
1119   = hang (ptext SLIT("In a pattern binding:")) 4 (pprPatBind pat grhss)
1120
1121 -----------------------------------------------
1122 sigContextsCtxt sig1 sig2
1123   = vcat [ptext SLIT("When matching the contexts of the signatures for"), 
1124           nest 2 (vcat [ppr id1 <+> dcolon <+> ppr (idType id1),
1125                         ppr id2 <+> dcolon <+> ppr (idType id2)]),
1126           ptext SLIT("The signature contexts in a mutually recursive group should all be identical")]
1127   where
1128     id1 = sig_id sig1
1129     id2 = sig_id sig2
1130
1131
1132 -----------------------------------------------
1133 unboxedTupleErr name ty
1134   = hang (ptext SLIT("Illegal binding of unboxed tuple"))
1135          4 (ppr name <+> dcolon <+> ppr ty)
1136
1137 -----------------------------------------------
1138 restrictedBindCtxtErr binder_names
1139   = hang (ptext SLIT("Illegal overloaded type signature(s)"))
1140        4 (vcat [ptext SLIT("in a binding group for") <+> pprBinders binder_names,
1141                 ptext SLIT("that falls under the monomorphism restriction")])
1142
1143 genCtxt binder_names
1144   = ptext SLIT("When generalising the type(s) for") <+> pprBinders binder_names
1145 \end{code}