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