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