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