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