Add -fmono-pat-binds, and make it the default
[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:")) 4 (ppr mbind)
503   where
504     msg | unlifted  = ptext SLIT("bindings for unlifted types")
505         | otherwise = ptext SLIT("bang-pattern bindings")
506
507 badStrictSig unlifted sig
508   = hang (ptext SLIT("Illegal polymorphic signature in") <+> msg)
509          4 (ppr sig)
510   where
511     msg | unlifted  = ptext SLIT("an unlifted binding")
512         | otherwise = ptext SLIT("a bang-pattern binding")
513 \end{code}
514
515
516 %************************************************************************
517 %*                                                                      *
518 \subsection{tcMonoBind}
519 %*                                                                      *
520 %************************************************************************
521
522 @tcMonoBinds@ deals with a perhaps-recursive group of HsBinds.
523 The signatures have been dealt with already.
524
525 \begin{code}
526 tcMonoBinds :: [LHsBind Name]
527             -> TcSigFun
528             -> RecFlag  -- Whether the binding is recursive for typechecking purposes
529                         -- i.e. the binders are mentioned in their RHSs, and
530                         --      we are not resuced by a type signature
531             -> TcM (LHsBinds TcId, [MonoBindInfo])
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             NonRecursive        -- binder isn't mentioned in RHS,
537   | Nothing <- sig_fn name      -- ...with no type signature
538   =     -- In this very special case we infer the type of the
539         -- right hand side first (it may have a higher-rank type)
540         -- and *then* make the monomorphic Id for the LHS
541         -- e.g.         f = \(x::forall a. a->a) -> <body>
542         --      We want to infer a higher-rank type for f
543     setSrcSpan b_loc    $
544     do  { ((co_fn, matches'), rhs_ty) <- tcInfer (tcMatchesFun name matches)
545
546                 -- Check for an unboxed tuple type
547                 --      f = (# True, False #)
548                 -- Zonk first just in case it's hidden inside a meta type variable
549                 -- (This shows up as a (more obscure) kind error 
550                 --  in the 'otherwise' case of tcMonoBinds.)
551         ; zonked_rhs_ty <- zonkTcType rhs_ty
552         ; checkTc (not (isUnboxedTupleType zonked_rhs_ty))
553                   (unboxedTupleErr name zonked_rhs_ty)
554
555         ; mono_name <- newLocalName name
556         ; let mono_id = mkLocalId mono_name zonked_rhs_ty
557         ; return (unitBag (L b_loc (FunBind { fun_id = L nm_loc mono_id, fun_infix = inf,
558                                               fun_matches = matches', bind_fvs = fvs,
559                                               fun_co_fn = co_fn })),
560                   [(name, Nothing, mono_id)]) }
561
562 tcMonoBinds [L b_loc (FunBind { fun_id = L nm_loc name, fun_infix = inf, 
563                                 fun_matches = matches, bind_fvs = fvs })]
564             sig_fn              -- Single function binding
565             non_rec     
566   | Just scoped_tvs <- sig_fn name      -- ...with a type signature
567   =     -- When we have a single function binding, with a type signature
568         -- we can (a) use genuine, rigid skolem constants for the type variables
569         --        (b) bring (rigid) scoped type variables into scope
570     setSrcSpan b_loc    $
571     do  { tc_sig <- tcInstSig True name scoped_tvs
572         ; mono_name <- newLocalName name
573         ; let mono_ty = sig_tau tc_sig
574               mono_id = mkLocalId mono_name mono_ty
575               rhs_tvs = [ (name, mkTyVarTy tv)
576                         | (name, tv) <- sig_scoped tc_sig `zip` sig_tvs tc_sig ]
577
578         ; (co_fn, matches') <- tcExtendTyVarEnv2 rhs_tvs    $
579                                tcMatchesFun mono_name matches mono_ty
580
581         ; let fun_bind' = FunBind { fun_id = L nm_loc mono_id, 
582                                     fun_infix = inf, fun_matches = matches',
583                                     bind_fvs = placeHolderNames, fun_co_fn = co_fn }
584         ; return (unitBag (L b_loc fun_bind'),
585                   [(name, Just tc_sig, mono_id)]) }
586
587 tcMonoBinds binds sig_fn non_rec
588   = do  { tc_binds <- mapM (wrapLocM (tcLhs sig_fn)) binds
589
590         -- Bring the monomorphic Ids, into scope for the RHSs
591         ; let mono_info  = getMonoBindInfo tc_binds
592               rhs_id_env = [(name,mono_id) | (name, Nothing, mono_id) <- mono_info]
593                                 -- A monomorphic binding for each term variable that lacks 
594                                 -- a type sig.  (Ones with a sig are already in scope.)
595
596         ; binds' <- tcExtendIdEnv2    rhs_id_env $
597                     traceTc (text "tcMonoBinds" <+> vcat [ ppr n <+> ppr id <+> ppr (idType id) 
598                                                          | (n,id) <- rhs_id_env]) `thenM_`
599                     mapM (wrapLocM tcRhs) tc_binds
600         ; return (listToBag binds', mono_info) }
601
602 ------------------------
603 -- tcLhs typechecks the LHS of the bindings, to construct the environment in which
604 -- we typecheck the RHSs.  Basically what we are doing is this: for each binder:
605 --      if there's a signature for it, use the instantiated signature type
606 --      otherwise invent a type variable
607 -- You see that quite directly in the FunBind case.
608 -- 
609 -- But there's a complication for pattern bindings:
610 --      data T = MkT (forall a. a->a)
611 --      MkT f = e
612 -- Here we can guess a type variable for the entire LHS (which will be refined to T)
613 -- but we want to get (f::forall a. a->a) as the RHS environment.
614 -- The simplest way to do this is to typecheck the pattern, and then look up the
615 -- bound mono-ids.  Then we want to retain the typechecked pattern to avoid re-doing
616 -- it; hence the TcMonoBind data type in which the LHS is done but the RHS isn't
617
618 data TcMonoBind         -- Half completed; LHS done, RHS not done
619   = TcFunBind  MonoBindInfo  (Located TcId) Bool (MatchGroup Name) 
620   | TcPatBind [MonoBindInfo] (LPat TcId) (GRHSs Name) TcSigmaType
621
622 type MonoBindInfo = (Name, Maybe TcSigInfo, TcId)
623         -- Type signature (if any), and
624         -- the monomorphic bound things
625
626 bndrNames :: [MonoBindInfo] -> [Name]
627 bndrNames mbi = [n | (n,_,_) <- mbi]
628
629 getMonoType :: MonoBindInfo -> TcTauType
630 getMonoType (_,_,mono_id) = idType mono_id
631
632 tcLhs :: TcSigFun -> HsBind Name -> TcM TcMonoBind
633 tcLhs sig_fn (FunBind { fun_id = L nm_loc name, fun_infix = inf, fun_matches = matches })
634   = do  { mb_sig <- tcInstSig_maybe sig_fn name
635         ; mono_name <- newLocalName name
636         ; mono_ty   <- mk_mono_ty mb_sig
637         ; let mono_id = mkLocalId mono_name mono_ty
638         ; return (TcFunBind (name, mb_sig, mono_id) (L nm_loc mono_id) inf matches) }
639   where
640     mk_mono_ty (Just sig) = return (sig_tau sig)
641     mk_mono_ty Nothing    = newFlexiTyVarTy argTypeKind
642
643 tcLhs sig_fn bind@(PatBind { pat_lhs = pat, pat_rhs = grhss })
644   = do  { mb_sigs <- mapM (tcInstSig_maybe sig_fn) names
645
646         ; let nm_sig_prs  = names `zip` mb_sigs
647               tau_sig_env = mkNameEnv [ (name, sig_tau sig) | (name, Just sig) <- nm_sig_prs]
648               sig_tau_fn  = lookupNameEnv tau_sig_env
649
650               tc_pat exp_ty = tcPat (LetPat sig_tau_fn) pat exp_ty unitTy $ \ _ ->
651                               mapM lookup_info nm_sig_prs
652                 -- The unitTy is a bit bogus; it's the "result type" for lookup_info.  
653
654                 -- After typechecking the pattern, look up the binder
655                 -- names, which the pattern has brought into scope.
656               lookup_info :: (Name, Maybe TcSigInfo) -> TcM MonoBindInfo
657               lookup_info (name, mb_sig) = do { mono_id <- tcLookupId name
658                                               ; return (name, mb_sig, mono_id) }
659
660         ; ((pat', infos), pat_ty) <- addErrCtxt (patMonoBindsCtxt pat grhss) $
661                                      tcInfer tc_pat
662
663         ; return (TcPatBind infos pat' grhss pat_ty) }
664   where
665     names = collectPatBinders pat
666
667
668 tcLhs sig_fn other_bind = pprPanic "tcLhs" (ppr other_bind)
669         -- AbsBind, VarBind impossible
670
671 -------------------
672 tcRhs :: TcMonoBind -> TcM (HsBind TcId)
673 tcRhs (TcFunBind info fun'@(L _ mono_id) inf matches)
674   = do  { (co_fn, matches') <- tcMatchesFun (idName mono_id) matches 
675                                             (idType mono_id)
676         ; return (FunBind { fun_id = fun', fun_infix = inf, fun_matches = matches',
677                             bind_fvs = placeHolderNames, fun_co_fn = co_fn }) }
678
679 tcRhs bind@(TcPatBind _ pat' grhss pat_ty)
680   = do  { grhss' <- addErrCtxt (patMonoBindsCtxt pat' grhss) $
681                     tcGRHSsPat grhss pat_ty
682         ; return (PatBind { pat_lhs = pat', pat_rhs = grhss', pat_rhs_ty = pat_ty, 
683                             bind_fvs = placeHolderNames }) }
684
685
686 ---------------------
687 getMonoBindInfo :: [Located TcMonoBind] -> [MonoBindInfo]
688 getMonoBindInfo tc_binds
689   = foldr (get_info . unLoc) [] tc_binds
690   where
691     get_info (TcFunBind info _ _ _)  rest = info : rest
692     get_info (TcPatBind infos _ _ _) rest = infos ++ rest
693 \end{code}
694
695
696 %************************************************************************
697 %*                                                                      *
698                 Generalisation
699 %*                                                                      *
700 %************************************************************************
701
702 \begin{code}
703 generalise :: DynFlags -> TopLevelFlag 
704            -> [LHsBind Name] -> TcSigFun 
705            -> [MonoBindInfo] -> [Inst]
706            -> TcM ([TcTyVar], TcDictBinds, [TcId])
707 generalise dflags top_lvl bind_list sig_fn mono_infos lie_req
708   | isMonoGroup dflags bind_list
709   = do { extendLIEs lie_req; return ([], emptyBag, []) }
710
711   | isRestrictedGroup dflags bind_list sig_fn   -- RESTRICTED CASE
712   =     -- Check signature contexts are empty 
713     do  { checkTc (all is_mono_sig sigs)
714                   (restrictedBindCtxtErr bndrs)
715
716         -- Now simplify with exactly that set of tyvars
717         -- We have to squash those Methods
718         ; (qtvs, binds) <- tcSimplifyRestricted doc top_lvl bndrs 
719                                                 tau_tvs lie_req
720
721         -- Check that signature type variables are OK
722         ; final_qtvs <- checkSigsTyVars qtvs sigs
723
724         ; return (final_qtvs, binds, []) }
725
726   | null sigs   -- UNRESTRICTED CASE, NO TYPE SIGS
727   = tcSimplifyInfer doc tau_tvs lie_req
728
729   | otherwise   -- UNRESTRICTED CASE, WITH TYPE SIGS
730   = do  { sig_lie <- unifyCtxts sigs    -- sigs is non-empty
731         ; let   -- The "sig_avails" is the stuff available.  We get that from
732                 -- the context of the type signature, BUT ALSO the lie_avail
733                 -- so that polymorphic recursion works right (see Note [Polymorphic recursion])
734                 local_meths = [mkMethInst sig mono_id | (_, Just sig, mono_id) <- mono_infos]
735                 sig_avails = sig_lie ++ local_meths
736
737         -- Check that the needed dicts can be
738         -- expressed in terms of the signature ones
739         ; (forall_tvs, dict_binds) <- tcSimplifyInferCheck doc tau_tvs sig_avails lie_req
740         
741         -- Check that signature type variables are OK
742         ; final_qtvs <- checkSigsTyVars forall_tvs sigs
743
744         ; returnM (final_qtvs, dict_binds, map instToId sig_lie) }
745   where
746     bndrs   = bndrNames mono_infos
747     sigs    = [sig | (_, Just sig, _) <- mono_infos]
748     tau_tvs = foldr (unionVarSet . exactTyVarsOfType . getMonoType) emptyVarSet mono_infos
749                 -- NB: exactTyVarsOfType; see Note [Silly type synonym] 
750                 --     near defn of TcType.exactTyVarsOfType
751     is_mono_sig sig = null (sig_theta sig)
752     doc = ptext SLIT("type signature(s) for") <+> pprBinders bndrs
753
754     mkMethInst (TcSigInfo { sig_id = poly_id, sig_tvs = tvs, 
755                             sig_theta = theta, sig_loc = loc }) mono_id
756       = Method mono_id poly_id (mkTyVarTys tvs) theta loc
757 \end{code}
758
759 unifyCtxts checks that all the signature contexts are the same
760 The type signatures on a mutually-recursive group of definitions
761 must all have the same context (or none).
762
763 The trick here is that all the signatures should have the same
764 context, and we want to share type variables for that context, so that
765 all the right hand sides agree a common vocabulary for their type
766 constraints
767
768 We unify them because, with polymorphic recursion, their types
769 might not otherwise be related.  This is a rather subtle issue.
770
771 \begin{code}
772 unifyCtxts :: [TcSigInfo] -> TcM [Inst]
773 unifyCtxts (sig1 : sigs)        -- Argument is always non-empty
774   = do  { mapM unify_ctxt sigs
775         ; newDictsAtLoc (sig_loc sig1) (sig_theta sig1) }
776   where
777     theta1 = sig_theta sig1
778     unify_ctxt :: TcSigInfo -> TcM ()
779     unify_ctxt sig@(TcSigInfo { sig_theta = theta })
780         = setSrcSpan (instLocSrcSpan (sig_loc sig))     $
781           addErrCtxt (sigContextsCtxt sig1 sig)         $
782           unifyTheta theta1 theta
783
784 checkSigsTyVars :: [TcTyVar] -> [TcSigInfo] -> TcM [TcTyVar]
785 checkSigsTyVars qtvs sigs 
786   = do  { gbl_tvs <- tcGetGlobalTyVars
787         ; sig_tvs_s <- mappM (check_sig gbl_tvs) sigs
788
789         ; let   -- Sigh.  Make sure that all the tyvars in the type sigs
790                 -- appear in the returned ty var list, which is what we are
791                 -- going to generalise over.  Reason: we occasionally get
792                 -- silly types like
793                 --      type T a = () -> ()
794                 --      f :: T a
795                 --      f () = ()
796                 -- Here, 'a' won't appear in qtvs, so we have to add it
797                 sig_tvs = foldl extendVarSetList emptyVarSet sig_tvs_s
798                 all_tvs = varSetElems (extendVarSetList sig_tvs qtvs)
799         ; returnM all_tvs }
800   where
801     check_sig gbl_tvs (TcSigInfo {sig_id = id, sig_tvs = tvs, 
802                                   sig_theta = theta, sig_tau = tau})
803       = addErrCtxt (ptext SLIT("In the type signature for") <+> quotes (ppr id))        $
804         addErrCtxtM (sigCtxt id tvs theta tau)                                          $
805         do { tvs' <- checkDistinctTyVars tvs
806            ; ifM (any (`elemVarSet` gbl_tvs) tvs')
807                  (bleatEscapedTvs gbl_tvs tvs tvs') 
808            ; return tvs' }
809
810 checkDistinctTyVars :: [TcTyVar] -> TcM [TcTyVar]
811 -- (checkDistinctTyVars tvs) checks that the tvs from one type signature
812 -- are still all type variables, and all distinct from each other.  
813 -- It returns a zonked set of type variables.
814 -- For example, if the type sig is
815 --      f :: forall a b. a -> b -> b
816 -- we want to check that 'a' and 'b' haven't 
817 --      (a) been unified with a non-tyvar type
818 --      (b) been unified with each other (all distinct)
819
820 checkDistinctTyVars sig_tvs
821   = do  { zonked_tvs <- mapM zonkSigTyVar sig_tvs
822         ; foldlM check_dup emptyVarEnv (sig_tvs `zip` zonked_tvs)
823         ; return zonked_tvs }
824   where
825     check_dup :: TyVarEnv TcTyVar -> (TcTyVar, TcTyVar) -> TcM (TyVarEnv TcTyVar)
826         -- The TyVarEnv maps each zonked type variable back to its
827         -- corresponding user-written signature type variable
828     check_dup acc (sig_tv, zonked_tv)
829         = case lookupVarEnv acc zonked_tv of
830                 Just sig_tv' -> bomb_out sig_tv sig_tv'
831
832                 Nothing -> return (extendVarEnv acc zonked_tv sig_tv)
833
834     bomb_out sig_tv1 sig_tv2
835        = do { env0 <- tcInitTidyEnv
836             ; let (env1, tidy_tv1) = tidyOpenTyVar env0 sig_tv1
837                   (env2, tidy_tv2) = tidyOpenTyVar env1 sig_tv2
838                   msg = ptext SLIT("Quantified type variable") <+> quotes (ppr tidy_tv1) 
839                          <+> ptext SLIT("is unified with another quantified type variable") 
840                          <+> quotes (ppr tidy_tv2)
841             ; failWithTcM (env2, msg) }
842        where
843 \end{code}    
844
845
846 @getTyVarsToGen@ decides what type variables to generalise over.
847
848 For a "restricted group" -- see the monomorphism restriction
849 for a definition -- we bind no dictionaries, and
850 remove from tyvars_to_gen any constrained type variables
851
852 *Don't* simplify dicts at this point, because we aren't going
853 to generalise over these dicts.  By the time we do simplify them
854 we may well know more.  For example (this actually came up)
855         f :: Array Int Int
856         f x = array ... xs where xs = [1,2,3,4,5]
857 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
858 stuff.  If we simplify only at the f-binding (not the xs-binding)
859 we'll know that the literals are all Ints, and we can just produce
860 Int literals!
861
862 Find all the type variables involved in overloading, the
863 "constrained_tyvars".  These are the ones we *aren't* going to
864 generalise.  We must be careful about doing this:
865
866  (a) If we fail to generalise a tyvar which is not actually
867         constrained, then it will never, ever get bound, and lands
868         up printed out in interface files!  Notorious example:
869                 instance Eq a => Eq (Foo a b) where ..
870         Here, b is not constrained, even though it looks as if it is.
871         Another, more common, example is when there's a Method inst in
872         the LIE, whose type might very well involve non-overloaded
873         type variables.
874   [NOTE: Jan 2001: I don't understand the problem here so I'm doing 
875         the simple thing instead]
876
877  (b) On the other hand, we mustn't generalise tyvars which are constrained,
878         because we are going to pass on out the unmodified LIE, with those
879         tyvars in it.  They won't be in scope if we've generalised them.
880
881 So we are careful, and do a complete simplification just to find the
882 constrained tyvars. We don't use any of the results, except to
883 find which tyvars are constrained.
884
885 Note [Polymorphic recursion]
886 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
887 The game plan for polymorphic recursion in the code above is 
888
889         * Bind any variable for which we have a type signature
890           to an Id with a polymorphic type.  Then when type-checking 
891           the RHSs we'll make a full polymorphic call.
892
893 This fine, but if you aren't a bit careful you end up with a horrendous
894 amount of partial application and (worse) a huge space leak. For example:
895
896         f :: Eq a => [a] -> [a]
897         f xs = ...f...
898
899 If we don't take care, after typechecking we get
900
901         f = /\a -> \d::Eq a -> let f' = f a d
902                                in
903                                \ys:[a] -> ...f'...
904
905 Notice the the stupid construction of (f a d), which is of course
906 identical to the function we're executing.  In this case, the
907 polymorphic recursion isn't being used (but that's a very common case).
908 This can lead to a massive space leak, from the following top-level defn
909 (post-typechecking)
910
911         ff :: [Int] -> [Int]
912         ff = f Int dEqInt
913
914 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
915 f' is another thunk which evaluates to the same thing... and you end
916 up with a chain of identical values all hung onto by the CAF ff.
917
918         ff = f Int dEqInt
919
920            = let f' = f Int dEqInt in \ys. ...f'...
921
922            = let f' = let f' = f Int dEqInt in \ys. ...f'...
923                       in \ys. ...f'...
924
925 Etc.
926
927 NOTE: a bit of arity anaysis would push the (f a d) inside the (\ys...),
928 which would make the space leak go away in this case
929
930 Solution: when typechecking the RHSs we always have in hand the
931 *monomorphic* Ids for each binding.  So we just need to make sure that
932 if (Method f a d) shows up in the constraints emerging from (...f...)
933 we just use the monomorphic Id.  We achieve this by adding monomorphic Ids
934 to the "givens" when simplifying constraints.  That's what the "lies_avail"
935 is doing.
936
937 Then we get
938
939         f = /\a -> \d::Eq a -> letrec
940                                  fm = \ys:[a] -> ...fm...
941                                in
942                                fm
943
944
945
946 %************************************************************************
947 %*                                                                      *
948                 Signatures
949 %*                                                                      *
950 %************************************************************************
951
952 Type signatures are tricky.  See Note [Signature skolems] in TcType
953
954 @tcSigs@ checks the signatures for validity, and returns a list of
955 {\em freshly-instantiated} signatures.  That is, the types are already
956 split up, and have fresh type variables installed.  All non-type-signature
957 "RenamedSigs" are ignored.
958
959 The @TcSigInfo@ contains @TcTypes@ because they are unified with
960 the variable's type, and after that checked to see whether they've
961 been instantiated.
962
963 \begin{code}
964 type TcSigFun = Name -> Maybe [Name]    -- Maps a let-binder to the list of
965                                         -- type variables brought into scope
966                                         -- by its type signature.
967                                         -- Nothing => no type signature
968
969 mkTcSigFun :: [LSig Name] -> TcSigFun
970 -- Search for a particular type signature
971 -- Precondition: the sigs are all type sigs
972 -- Precondition: no duplicates
973 mkTcSigFun sigs = lookupNameEnv env
974   where
975     env = mkNameEnv [(name, scoped_tyvars hs_ty)
976                     | L span (TypeSig (L _ name) (L _ hs_ty)) <- sigs]
977     scoped_tyvars (HsForAllTy Explicit tvs _ _) = hsLTyVarNames tvs
978     scoped_tyvars other                         = []
979         -- The scoped names are the ones explicitly mentioned
980         -- in the HsForAll.  (There may be more in sigma_ty, because
981         -- of nested type synonyms.  See Note [Scoped] with TcSigInfo.)
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 --      Note [Scoped]
1001 -- There may be more instantiated type variables than scoped 
1002 -- ones.  For example:
1003 --      type T a = forall b. b -> (a,b)
1004 --      f :: forall c. T c
1005 -- Here, the signature for f will have one scoped type variable, c,
1006 -- but two instantiated type variables, c' and b'.  
1007 --
1008 -- We assume that the scoped ones are at the *front* of sig_tvs,
1009 -- and remember the names from the original HsForAllTy in sig_scoped
1010
1011 --      Note [Instantiate sig]
1012 -- It's vital to instantiate a type signature with fresh variable.
1013 -- For example:
1014 --      type S = forall a. a->a
1015 --      f,g :: S
1016 --      f = ...
1017 --      g = ...
1018 -- Here, we must use distinct type variables when checking f,g's right hand sides.
1019 -- (Instantiation is only necessary because of type synonyms.  Otherwise,
1020 -- it's all cool; each signature has distinct type variables from the renamer.)
1021
1022 instance Outputable TcSigInfo where
1023     ppr (TcSigInfo { sig_id = id, sig_tvs = tyvars, sig_theta = theta, sig_tau = tau})
1024         = ppr id <+> ptext SLIT("::") <+> ppr tyvars <+> ppr theta <+> ptext SLIT("=>") <+> ppr tau
1025 \end{code}
1026
1027 \begin{code}
1028 tcTySig :: LSig Name -> TcM TcId
1029 tcTySig (L span (TypeSig (L _ name) ty))
1030   = setSrcSpan span             $
1031     do  { sigma_ty <- tcHsSigType (FunSigCtxt name) ty
1032         ; return (mkLocalId name sigma_ty) }
1033
1034 -------------------
1035 tcInstSig_maybe :: TcSigFun -> Name -> TcM (Maybe TcSigInfo)
1036 -- Instantiate with *meta* type variables; 
1037 -- this signature is part of a multi-signature group
1038 tcInstSig_maybe sig_fn name 
1039   = case sig_fn name of
1040         Nothing  -> return Nothing
1041         Just tvs -> do  { tc_sig <- tcInstSig False name tvs
1042                         ; return (Just tc_sig) }
1043
1044 tcInstSig :: Bool -> Name -> [Name] -> TcM TcSigInfo
1045 -- Instantiate the signature, with either skolems or meta-type variables
1046 -- depending on the use_skols boolean
1047 --
1048 -- We always instantiate with freshs uniques,
1049 -- although we keep the same print-name
1050 --      
1051 --      type T = forall a. [a] -> [a]
1052 --      f :: T; 
1053 --      f = g where { g :: T; g = <rhs> }
1054 --
1055 -- We must not use the same 'a' from the defn of T at both places!!
1056
1057 tcInstSig use_skols name scoped_names
1058   = do  { poly_id <- tcLookupId name    -- Cannot fail; the poly ids are put into 
1059                                         -- scope when starting the binding group
1060         ; let skol_info = SigSkol (FunSigCtxt name)
1061               inst_tyvars | use_skols = tcInstSkolTyVars skol_info
1062                           | otherwise = tcInstSigTyVars  skol_info
1063         ; (tvs, theta, tau) <- tcInstType inst_tyvars (idType poly_id)
1064         ; loc <- getInstLoc (SigOrigin skol_info)
1065         ; return (TcSigInfo { sig_id = poly_id,
1066                               sig_tvs = tvs, sig_theta = theta, sig_tau = tau, 
1067                               sig_scoped = final_scoped_names, sig_loc = loc }) }
1068                 -- Note that the scoped_names and the sig_tvs will have
1069                 -- different Names. That's quite ok; when we bring the 
1070                 -- scoped_names into scope, we just bind them to the sig_tvs
1071   where
1072         -- We also only have scoped type variables when we are instantiating
1073         -- with true skolems
1074     final_scoped_names | use_skols = scoped_names
1075                        | otherwise = []
1076
1077 -------------------
1078 isMonoGroup :: DynFlags -> [LHsBind Name] -> Bool
1079 -- No generalisation at all
1080 isMonoGroup dflags binds
1081   = dopt Opt_MonoPatBinds dflags && any is_pat_bind binds
1082   where
1083     is_pat_bind (L _ (PatBind {})) = True
1084     is_pat_bind other              = False
1085
1086 -------------------
1087 isRestrictedGroup :: DynFlags -> [LHsBind Name] -> TcSigFun -> Bool
1088 isRestrictedGroup dflags binds sig_fn
1089   = mono_restriction && not all_unrestricted
1090   where 
1091     mono_restriction = dopt Opt_MonomorphismRestriction dflags
1092     all_unrestricted = all (unrestricted . unLoc) binds
1093     has_sig n = isJust (sig_fn n)
1094
1095     unrestricted (PatBind {})                                    = False
1096     unrestricted (VarBind { var_id = v })                        = has_sig v
1097     unrestricted (FunBind { fun_id = v, fun_matches = matches }) = unrestricted_match matches 
1098                                                                  || has_sig (unLoc v)
1099
1100     unrestricted_match (MatchGroup (L _ (Match [] _ _) : _) _) = False
1101         -- No args => like a pattern binding
1102     unrestricted_match other              = True
1103         -- Some args => a function binding
1104 \end{code}
1105
1106
1107 %************************************************************************
1108 %*                                                                      *
1109 \subsection[TcBinds-errors]{Error contexts and messages}
1110 %*                                                                      *
1111 %************************************************************************
1112
1113
1114 \begin{code}
1115 -- This one is called on LHS, when pat and grhss are both Name 
1116 -- and on RHS, when pat is TcId and grhss is still Name
1117 patMonoBindsCtxt pat grhss
1118   = hang (ptext SLIT("In a pattern binding:")) 4 (pprPatBind pat grhss)
1119
1120 -----------------------------------------------
1121 sigContextsCtxt sig1 sig2
1122   = vcat [ptext SLIT("When matching the contexts of the signatures for"), 
1123           nest 2 (vcat [ppr id1 <+> dcolon <+> ppr (idType id1),
1124                         ppr id2 <+> dcolon <+> ppr (idType id2)]),
1125           ptext SLIT("The signature contexts in a mutually recursive group should all be identical")]
1126   where
1127     id1 = sig_id sig1
1128     id2 = sig_id sig2
1129
1130
1131 -----------------------------------------------
1132 unboxedTupleErr name ty
1133   = hang (ptext SLIT("Illegal binding of unboxed tuple"))
1134          4 (ppr name <+> dcolon <+> ppr ty)
1135
1136 -----------------------------------------------
1137 restrictedBindCtxtErr binder_names
1138   = hang (ptext SLIT("Illegal overloaded type signature(s)"))
1139        4 (vcat [ptext SLIT("in a binding group for") <+> pprBinders binder_names,
1140                 ptext SLIT("that falls under the monomorphism restriction")])
1141
1142 genCtxt binder_names
1143   = ptext SLIT("When generalising the type(s) for") <+> pprBinders binder_names
1144 \end{code}