[project @ 2003-04-16 13:34:13 by simonpj]
[ghc-hetmet.git] / ghc / 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 ( tcBindsAndThen, tcTopBinds, tcMonoBinds, tcSpecSigs ) where
8
9 #include "HsVersions.h"
10
11 import {-# SOURCE #-} TcMatches ( tcGRHSs, tcMatchesFun )
12 import {-# SOURCE #-} TcExpr  ( tcCheckSigma, tcCheckRho )
13
14 import CmdLineOpts      ( DynFlag(Opt_NoMonomorphismRestriction) )
15 import HsSyn            ( HsExpr(..), HsBinds(..), MonoBinds(..), Sig(..), 
16                           Match(..), HsMatchContext(..), mkMonoBind,
17                           collectMonoBinders, andMonoBinds,
18                           collectSigTysFromMonoBinds
19                         )
20 import RnHsSyn          ( RenamedHsBinds, RenamedSig, RenamedMonoBinds )
21 import TcHsSyn          ( TcHsBinds, TcMonoBinds, TcId, zonkId, mkHsLet )
22
23 import TcRnMonad
24 import Inst             ( InstOrigin(..), newDicts, newIPDict, instToId )
25 import TcEnv            ( tcExtendLocalValEnv, tcExtendLocalValEnv2, newLocalName )
26 import TcUnify          ( Expected(..), newHole, unifyTauTyLists, checkSigTyVarsWrt, sigCtxt )
27 import TcSimplify       ( tcSimplifyInfer, tcSimplifyInferCheck, tcSimplifyRestricted, 
28                           tcSimplifyToDicts, tcSimplifyIPs )
29 import TcMonoType       ( tcHsSigType, UserTypeCtxt(..), TcSigInfo(..), 
30                           tcTySig, maybeSig, tcSigPolyId, tcSigMonoId, tcAddScopedTyVars
31                         )
32 import TcPat            ( tcPat, tcSubPat, tcMonoPatBndr )
33 import TcSimplify       ( bindInstsOfLocalFuns )
34 import TcMType          ( newTyVar, newTyVarTy, zonkTcTyVarToTyVar )
35 import TcType           ( TcTyVar, mkTyVarTy, mkForAllTys, mkFunTys, tyVarsOfType, 
36                           mkPredTy, mkForAllTy, isUnLiftedType, 
37                           unliftedTypeKind, liftedTypeKind, openTypeKind, eqKind
38                         )
39
40 import CoreFVs          ( idFreeTyVars )
41 import Id               ( mkLocalId, mkSpecPragmaId, setInlinePragma )
42 import Var              ( idType, idName )
43 import Name             ( Name, getSrcLoc )
44 import NameSet
45 import Var              ( tyVarKind )
46 import VarSet
47 import Bag
48 import Util             ( isIn, equalLength )
49 import BasicTypes       ( TopLevelFlag(..), RecFlag(..), isNonRec, isRec, 
50                           isNotTopLevel, isAlwaysActive )
51 import FiniteMap        ( listToFM, lookupFM )
52 import Outputable
53 \end{code}
54
55
56 %************************************************************************
57 %*                                                                      *
58 \subsection{Type-checking bindings}
59 %*                                                                      *
60 %************************************************************************
61
62 @tcBindsAndThen@ typechecks a @HsBinds@.  The "and then" part is because
63 it needs to know something about the {\em usage} of the things bound,
64 so that it can create specialisations of them.  So @tcBindsAndThen@
65 takes a function which, given an extended environment, E, typechecks
66 the scope of the bindings returning a typechecked thing and (most
67 important) an LIE.  It is this LIE which is then used as the basis for
68 specialising the things bound.
69
70 @tcBindsAndThen@ also takes a "combiner" which glues together the
71 bindings and the "thing" to make a new "thing".
72
73 The real work is done by @tcBindWithSigsAndThen@.
74
75 Recursive and non-recursive binds are handled in essentially the same
76 way: because of uniques there are no scoping issues left.  The only
77 difference is that non-recursive bindings can bind primitive values.
78
79 Even for non-recursive binding groups we add typings for each binder
80 to the LVE for the following reason.  When each individual binding is
81 checked the type of its LHS is unified with that of its RHS; and
82 type-checking the LHS of course requires that the binder is in scope.
83
84 At the top-level the LIE is sure to contain nothing but constant
85 dictionaries, which we resolve at the module level.
86
87 \begin{code}
88 tcTopBinds :: RenamedHsBinds -> TcM (TcMonoBinds, TcLclEnv)
89         -- Note: returning the TcLclEnv is more than we really
90         --       want.  The bit we care about is the local bindings
91         --       and the free type variables thereof
92 tcTopBinds binds
93   = tc_binds_and_then TopLevel glue binds       $
94     getLclEnv                                   `thenM` \ env ->
95     returnM (EmptyMonoBinds, env)
96   where
97         -- The top level bindings are flattened into a giant 
98         -- implicitly-mutually-recursive MonoBinds
99     glue binds1 (binds2, env) = (flatten binds1 `AndMonoBinds` binds2, env)
100     flatten EmptyBinds          = EmptyMonoBinds
101     flatten (b1 `ThenBinds` b2) = flatten b1 `AndMonoBinds` flatten b2
102     flatten (MonoBind b _ _)    = b
103         -- Can't have a IPBinds at top level
104
105
106 tcBindsAndThen
107         :: (TcHsBinds -> thing -> thing)                -- Combinator
108         -> RenamedHsBinds
109         -> TcM thing
110         -> TcM thing
111
112 tcBindsAndThen = tc_binds_and_then NotTopLevel
113
114 tc_binds_and_then top_lvl combiner EmptyBinds do_next
115   = do_next
116 tc_binds_and_then top_lvl combiner (MonoBind EmptyMonoBinds sigs is_rec) do_next
117   = do_next
118
119 tc_binds_and_then top_lvl combiner (ThenBinds b1 b2) do_next
120   = tc_binds_and_then top_lvl combiner b1       $
121     tc_binds_and_then top_lvl combiner b2       $
122     do_next
123
124 tc_binds_and_then top_lvl combiner (IPBinds binds is_with) do_next
125   = getLIE do_next                      `thenM` \ (result, expr_lie) ->
126     mapAndUnzipM tc_ip_bind binds       `thenM` \ (avail_ips, binds') ->
127
128         -- If the binding binds ?x = E, we  must now 
129         -- discharge any ?x constraints in expr_lie
130     tcSimplifyIPs avail_ips expr_lie    `thenM` \ dict_binds ->
131
132     returnM (combiner (IPBinds binds' is_with) $
133              combiner (mkMonoBind Recursive dict_binds) result)
134   where
135         -- I wonder if we should do these one at at time
136         -- Consider     ?x = 4
137         --              ?y = ?x + 1
138     tc_ip_bind (ip, expr)
139       = newTyVarTy openTypeKind         `thenM` \ ty ->
140         getSrcLocM                      `thenM` \ loc ->
141         newIPDict (IPBind ip) ip ty     `thenM` \ (ip', ip_inst) ->
142         tcCheckRho expr ty              `thenM` \ expr' ->
143         returnM (ip_inst, (ip', expr'))
144
145 tc_binds_and_then top_lvl combiner (MonoBind bind sigs is_rec) do_next
146   =     -- BRING ANY SCOPED TYPE VARIABLES INTO SCOPE
147         -- Notice that they scope over 
148         --      a) the type signatures in the binding group
149         --      b) the bindings in the group
150         --      c) the scope of the binding group (the "in" part)
151       tcAddScopedTyVars (collectSigTysFromMonoBinds bind)       $
152
153       tcBindWithSigs top_lvl bind sigs is_rec   `thenM` \ (poly_binds, poly_ids) ->
154   
155       case top_lvl of
156         TopLevel        -- For the top level don't bother will all this
157                         --  bindInstsOfLocalFuns stuff. All the top level 
158                         -- things are rec'd together anyway, so it's fine to
159                         -- leave them to the tcSimplifyTop, and quite a bit faster too
160                         --
161                         -- Subtle (and ugly) point: furthermore at top level we
162                         -- return the TcLclEnv, which contains the LIE var; we
163                         -- don't want to return the wrong one!
164                 -> tc_body poly_ids                     `thenM` \ (prag_binds, thing) ->
165                    returnM (combiner (mkMonoBind Recursive (poly_binds `andMonoBinds` prag_binds)) 
166                                      thing)
167
168         NotTopLevel     -- For nested bindings we must do teh bindInstsOfLocalFuns thing
169                 -> getLIE (tc_body poly_ids)            `thenM` \ ((prag_binds, thing), lie) ->
170
171                         -- Create specialisations of functions bound here
172                     bindInstsOfLocalFuns lie poly_ids   `thenM` \ lie_binds ->
173
174                         -- We want to keep non-recursive things non-recursive
175                         -- so that we desugar unlifted bindings correctly
176                    if isRec is_rec then
177                      returnM (
178                         combiner (mkMonoBind Recursive (
179                                 poly_binds `andMonoBinds`
180                                 lie_binds  `andMonoBinds`
181                                 prag_binds)) thing
182                      )
183                    else
184                      returnM (
185                         combiner (mkMonoBind NonRecursive poly_binds) $
186                         combiner (mkMonoBind NonRecursive prag_binds) $
187                         combiner (mkMonoBind Recursive lie_binds)     $
188                                 -- NB: the binds returned by tcSimplify and bindInstsOfLocalFuns
189                                 -- aren't guaranteed in dependency order (though we could change
190                                 -- that); hence the Recursive marker.
191                         thing)
192   where
193     tc_body poly_ids    -- Type check the pragmas and "thing inside"
194       =   -- Extend the environment to bind the new polymorphic Ids
195           tcExtendLocalValEnv poly_ids  $
196   
197           -- Build bindings and IdInfos corresponding to user pragmas
198           tcSpecSigs sigs               `thenM` \ prag_binds ->
199
200           -- Now do whatever happens next, in the augmented envt
201           do_next                       `thenM` \ thing ->
202
203           returnM (prag_binds, thing)
204 \end{code}
205
206
207 %************************************************************************
208 %*                                                                      *
209 \subsection{tcBindWithSigs}
210 %*                                                                      *
211 %************************************************************************
212
213 @tcBindWithSigs@ deals with a single binding group.  It does generalisation,
214 so all the clever stuff is in here.
215
216 * binder_names and mbind must define the same set of Names
217
218 * The Names in tc_ty_sigs must be a subset of binder_names
219
220 * The Ids in tc_ty_sigs don't necessarily have to have the same name
221   as the Name in the tc_ty_sig
222
223 \begin{code}
224 tcBindWithSigs  
225         :: TopLevelFlag
226         -> RenamedMonoBinds
227         -> [RenamedSig]         -- Used solely to get INLINE, NOINLINE sigs
228         -> RecFlag
229         -> TcM (TcMonoBinds, [TcId])
230
231 tcBindWithSigs top_lvl mbind sigs is_rec
232   =     -- TYPECHECK THE SIGNATURES
233      recoverM (returnM []) (
234         mappM tcTySig [sig | sig@(Sig name _ _) <- sigs]
235      )                                          `thenM` \ tc_ty_sigs ->
236
237         -- SET UP THE MAIN RECOVERY; take advantage of any type sigs
238    recoverM (
239         -- If typechecking the binds fails, then return with each
240         -- signature-less binder given type (forall a.a), to minimise subsequent
241         -- error messages
242         newTyVar liftedTypeKind         `thenM` \ alpha_tv ->
243         let
244           forall_a_a    = mkForAllTy alpha_tv (mkTyVarTy alpha_tv)
245           binder_names  = collectMonoBinders mbind
246           poly_ids      = map mk_dummy binder_names
247           mk_dummy name = case maybeSig tc_ty_sigs name of
248                             Just sig -> tcSigPolyId sig                 -- Signature
249                             Nothing  -> mkLocalId name forall_a_a       -- No signature
250         in
251         traceTc (text "tcBindsWithSigs: error recovery" <+> ppr binder_names)   `thenM_`
252         returnM (EmptyMonoBinds, poly_ids)
253     )                                           $
254
255         -- TYPECHECK THE BINDINGS
256     getLIE (tcMonoBinds mbind tc_ty_sigs is_rec)        `thenM` \ ((mbind', bndr_names_w_ids), lie_req) ->
257     let
258         (binder_names, mono_ids) = unzip (bagToList bndr_names_w_ids)
259         tau_tvs = foldr (unionVarSet . tyVarsOfType . idType) emptyVarSet mono_ids
260     in
261
262         -- GENERALISE
263         --      (it seems a bit crude to have to do getLIE twice,
264         --       but I can't see a better way just now)
265     addSrcLoc  (minimum (map getSrcLoc binder_names))           $
266     addErrCtxt (genCtxt binder_names)                           $
267     getLIE (generalise binder_names mbind tau_tvs lie_req tc_ty_sigs)
268                         `thenM` \ ((tc_tyvars_to_gen, dict_binds, dict_ids), lie_free) ->
269
270
271         -- ZONK THE GENERALISED TYPE VARIABLES TO REAL TyVars
272         -- This commits any unbound kind variables to boxed kind, by unification
273         -- It's important that the final quanfified type variables
274         -- are fully zonked, *including boxity*, because they'll be 
275         -- included in the forall types of the polymorphic Ids.
276         -- At calls of these Ids we'll instantiate fresh type variables from
277         -- them, and we use their boxity then.
278     mappM zonkTcTyVarToTyVar tc_tyvars_to_gen   `thenM` \ real_tyvars_to_gen ->
279
280         -- ZONK THE Ids
281         -- It's important that the dict Ids are zonked, including the boxity set
282         -- in the previous step, because they are later used to form the type of 
283         -- the polymorphic thing, and forall-types must be zonked so far as 
284         -- their bound variables are concerned
285     mappM zonkId dict_ids                               `thenM` \ zonked_dict_ids ->
286     mappM zonkId mono_ids                               `thenM` \ zonked_mono_ids ->
287
288         -- BUILD THE POLYMORPHIC RESULT IDs
289     let
290         exports  = zipWith mk_export binder_names zonked_mono_ids
291         poly_ids = [poly_id | (_, poly_id, _) <- exports]
292         dict_tys = map idType zonked_dict_ids
293
294         inlines    = mkNameSet [name | InlineSig True name _ loc <- sigs]
295                         -- Any INLINE sig (regardless of phase control) 
296                         -- makes the RHS look small
297         inline_phases = listToFM [(name, phase) | InlineSig _ name phase _ <- sigs, 
298                                                   not (isAlwaysActive phase)]
299                         -- Set the IdInfo field to control the inline phase
300                         -- AlwaysActive is the default, so don't bother with them
301
302         mk_export binder_name zonked_mono_id
303           = (tyvars, 
304              attachInlinePhase inline_phases poly_id,
305              zonked_mono_id)
306           where
307             (tyvars, poly_id) = 
308                 case maybeSig tc_ty_sigs binder_name of
309                   Just (TySigInfo sig_poly_id sig_tyvars _ _ _ _ _) -> 
310                         (sig_tyvars, sig_poly_id)
311                   Nothing -> (real_tyvars_to_gen, new_poly_id)
312
313             new_poly_id = mkLocalId binder_name poly_ty
314             poly_ty = mkForAllTys real_tyvars_to_gen
315                     $ mkFunTys dict_tys 
316                     $ idType zonked_mono_id
317                 -- It's important to build a fully-zonked poly_ty, because
318                 -- we'll slurp out its free type variables when extending the
319                 -- local environment (tcExtendLocalValEnv); if it's not zonked
320                 -- it appears to have free tyvars that aren't actually free 
321                 -- at all.
322     in
323
324     traceTc (text "binding:" <+> ppr ((zonked_dict_ids, dict_binds),
325                                       exports, map idType poly_ids)) `thenM_`
326
327         -- Check for an unlifted, non-overloaded group
328         -- In that case we must make extra checks
329     if any (isUnLiftedType . idType) zonked_mono_ids && null zonked_dict_ids 
330     then        -- Some bindings are unlifted
331         checkUnliftedBinds top_lvl is_rec real_tyvars_to_gen mbind      `thenM_` 
332         
333         extendLIEs lie_req                      `thenM_`
334         returnM (
335             AbsBinds [] [] exports inlines mbind',
336                 -- Do not generate even any x=y bindings
337             poly_ids
338         )
339
340     else        -- The normal case
341     extendLIEs lie_free                         `thenM_`
342     returnM (
343         AbsBinds real_tyvars_to_gen
344                  zonked_dict_ids
345                  exports
346                  inlines
347                  (dict_binds `andMonoBinds` mbind'),
348         poly_ids
349     )
350
351 attachInlinePhase inline_phases bndr
352   = case lookupFM inline_phases (idName bndr) of
353         Just prag -> bndr `setInlinePragma` prag
354         Nothing   -> bndr
355
356 -- Check that non-overloaded unlifted bindings are
357 --      a) non-recursive,
358 --      b) not top level, 
359 --      c) non-polymorphic
360 --      d) not a multiple-binding group (more or less implied by (a))
361
362 checkUnliftedBinds top_lvl is_rec real_tyvars_to_gen mbind
363   = ASSERT( not (any ((eqKind unliftedTypeKind) . tyVarKind) real_tyvars_to_gen) )
364                 -- The instCantBeGeneralised stuff in tcSimplify should have
365                 -- already raised an error if we're trying to generalise an 
366                 -- unboxed tyvar (NB: unboxed tyvars are always introduced 
367                 -- along with a class constraint) and it's better done there 
368                 -- because we have more precise origin information.
369                 -- That's why we just use an ASSERT here.
370
371     checkTc (isNotTopLevel top_lvl)
372             (unliftedBindErr "Top-level" mbind)         `thenM_`
373     checkTc (isNonRec is_rec)
374             (unliftedBindErr "Recursive" mbind)         `thenM_`
375     checkTc (single_bind mbind)
376             (unliftedBindErr "Multiple" mbind)          `thenM_`
377     checkTc (null real_tyvars_to_gen)
378             (unliftedBindErr "Polymorphic" mbind)
379
380   where
381     single_bind (PatMonoBind _ _ _)   = True
382     single_bind (FunMonoBind _ _ _ _) = True
383     single_bind other                 = False
384 \end{code}
385
386
387 Polymorphic recursion
388 ~~~~~~~~~~~~~~~~~~~~~
389 The game plan for polymorphic recursion in the code above is 
390
391         * Bind any variable for which we have a type signature
392           to an Id with a polymorphic type.  Then when type-checking 
393           the RHSs we'll make a full polymorphic call.
394
395 This fine, but if you aren't a bit careful you end up with a horrendous
396 amount of partial application and (worse) a huge space leak. For example:
397
398         f :: Eq a => [a] -> [a]
399         f xs = ...f...
400
401 If we don't take care, after typechecking we get
402
403         f = /\a -> \d::Eq a -> let f' = f a d
404                                in
405                                \ys:[a] -> ...f'...
406
407 Notice the the stupid construction of (f a d), which is of course
408 identical to the function we're executing.  In this case, the
409 polymorphic recursion isn't being used (but that's a very common case).
410 We'd prefer
411
412         f = /\a -> \d::Eq a -> letrec
413                                  fm = \ys:[a] -> ...fm...
414                                in
415                                fm
416
417 This can lead to a massive space leak, from the following top-level defn
418 (post-typechecking)
419
420         ff :: [Int] -> [Int]
421         ff = f Int dEqInt
422
423 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
424 f' is another thunk which evaluates to the same thing... and you end
425 up with a chain of identical values all hung onto by the CAF ff.
426
427         ff = f Int dEqInt
428
429            = let f' = f Int dEqInt in \ys. ...f'...
430
431            = let f' = let f' = f Int dEqInt in \ys. ...f'...
432                       in \ys. ...f'...
433
434 Etc.
435 Solution: when typechecking the RHSs we always have in hand the
436 *monomorphic* Ids for each binding.  So we just need to make sure that
437 if (Method f a d) shows up in the constraints emerging from (...f...)
438 we just use the monomorphic Id.  We achieve this by adding monomorphic Ids
439 to the "givens" when simplifying constraints.  That's what the "lies_avail"
440 is doing.
441
442
443 %************************************************************************
444 %*                                                                      *
445 \subsection{getTyVarsToGen}
446 %*                                                                      *
447 %************************************************************************
448
449 \begin{code}
450 generalise binder_names mbind tau_tvs lie_req sigs =
451
452   -- check for -fno-monomorphism-restriction
453   doptM Opt_NoMonomorphismRestriction           `thenM` \ no_MR ->
454   let is_unrestricted | no_MR     = True
455                       | otherwise = isUnRestrictedGroup tysig_names mbind
456   in
457
458   if not is_unrestricted then   -- RESTRICTED CASE
459         -- Check signature contexts are empty 
460     checkTc (all is_mono_sig sigs)
461             (restrictedBindCtxtErr binder_names)        `thenM_`
462
463         -- Now simplify with exactly that set of tyvars
464         -- We have to squash those Methods
465     tcSimplifyRestricted doc tau_tvs lie_req            `thenM` \ (qtvs, binds) ->
466
467         -- Check that signature type variables are OK
468     checkSigsTyVars qtvs sigs                           `thenM` \ final_qtvs ->
469
470     returnM (final_qtvs, binds, [])
471
472   else if null sigs then        -- UNRESTRICTED CASE, NO TYPE SIGS
473     tcSimplifyInfer doc tau_tvs lie_req
474
475   else                          -- UNRESTRICTED CASE, WITH TYPE SIGS
476         -- CHECKING CASE: Unrestricted group, there are type signatures
477         -- Check signature contexts are identical
478     checkSigsCtxts sigs                 `thenM` \ (sig_avails, sig_dicts) ->
479     
480         -- Check that the needed dicts can be
481         -- expressed in terms of the signature ones
482     tcSimplifyInferCheck doc tau_tvs sig_avails lie_req `thenM` \ (forall_tvs, dict_binds) ->
483         
484         -- Check that signature type variables are OK
485     checkSigsTyVars forall_tvs sigs                     `thenM` \ final_qtvs ->
486
487     returnM (final_qtvs, dict_binds, sig_dicts)
488
489   where
490     tysig_names = map (idName . tcSigPolyId) sigs
491     is_mono_sig (TySigInfo _ _ theta _ _ _ _) = null theta
492
493     doc = ptext SLIT("type signature(s) for") <+> pprBinders binder_names
494
495 -----------------------
496         -- CHECK THAT ALL THE SIGNATURE CONTEXTS ARE UNIFIABLE
497         -- The type signatures on a mutually-recursive group of definitions
498         -- must all have the same context (or none).
499         --
500         -- We unify them because, with polymorphic recursion, their types
501         -- might not otherwise be related.  This is a rather subtle issue.
502         -- ToDo: amplify
503 checkSigsCtxts sigs@(TySigInfo id1 sig_tvs theta1 _ _ _ src_loc : other_sigs)
504   = addSrcLoc src_loc                   $
505     mappM_ check_one other_sigs         `thenM_` 
506     if null theta1 then
507         returnM ([], [])                -- Non-overloaded type signatures
508     else
509     newDicts SignatureOrigin theta1     `thenM` \ sig_dicts ->
510     let
511         -- The "sig_avails" is the stuff available.  We get that from
512         -- the context of the type signature, BUT ALSO the lie_avail
513         -- so that polymorphic recursion works right (see comments at end of fn)
514         sig_avails = sig_dicts ++ sig_meths
515     in
516     returnM (sig_avails, map instToId sig_dicts)
517   where
518     sig1_dict_tys = map mkPredTy theta1
519     sig_meths     = concat [insts | TySigInfo _ _ _ _ _ insts _ <- sigs]
520
521     check_one sig@(TySigInfo id _ theta _ _ _ _)
522        = addErrCtxt (sigContextsCtxt id1 id)                    $
523          checkTc (equalLength theta theta1) sigContextsErr      `thenM_`
524          unifyTauTyLists sig1_dict_tys (map mkPredTy theta)
525
526 checkSigsTyVars :: [TcTyVar] -> [TcSigInfo] -> TcM [TcTyVar]
527 checkSigsTyVars qtvs sigs 
528   = mappM check_one sigs        `thenM` \ sig_tvs_s ->
529     let
530         -- Sigh.  Make sure that all the tyvars in the type sigs
531         -- appear in the returned ty var list, which is what we are
532         -- going to generalise over.  Reason: we occasionally get
533         -- silly types like
534         --      type T a = () -> ()
535         --      f :: T a
536         --      f () = ()
537         -- Here, 'a' won't appear in qtvs, so we have to add it
538
539         sig_tvs = foldr (unionVarSet . mkVarSet) emptyVarSet sig_tvs_s
540         all_tvs = mkVarSet qtvs `unionVarSet` sig_tvs
541     in
542     returnM (varSetElems all_tvs)
543   where
544     check_one (TySigInfo id sig_tyvars sig_theta sig_tau _ _ src_loc)
545       = addSrcLoc src_loc                                               $
546         addErrCtxt (ptext SLIT("When checking the type signature for") 
547                       <+> quotes (ppr id))                              $
548         addErrCtxtM (sigCtxt id sig_tyvars sig_theta sig_tau)           $
549         checkSigTyVarsWrt (idFreeTyVars id) sig_tyvars
550 \end{code}
551
552 @getTyVarsToGen@ decides what type variables to generalise over.
553
554 For a "restricted group" -- see the monomorphism restriction
555 for a definition -- we bind no dictionaries, and
556 remove from tyvars_to_gen any constrained type variables
557
558 *Don't* simplify dicts at this point, because we aren't going
559 to generalise over these dicts.  By the time we do simplify them
560 we may well know more.  For example (this actually came up)
561         f :: Array Int Int
562         f x = array ... xs where xs = [1,2,3,4,5]
563 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
564 stuff.  If we simplify only at the f-binding (not the xs-binding)
565 we'll know that the literals are all Ints, and we can just produce
566 Int literals!
567
568 Find all the type variables involved in overloading, the
569 "constrained_tyvars".  These are the ones we *aren't* going to
570 generalise.  We must be careful about doing this:
571
572  (a) If we fail to generalise a tyvar which is not actually
573         constrained, then it will never, ever get bound, and lands
574         up printed out in interface files!  Notorious example:
575                 instance Eq a => Eq (Foo a b) where ..
576         Here, b is not constrained, even though it looks as if it is.
577         Another, more common, example is when there's a Method inst in
578         the LIE, whose type might very well involve non-overloaded
579         type variables.
580   [NOTE: Jan 2001: I don't understand the problem here so I'm doing 
581         the simple thing instead]
582
583  (b) On the other hand, we mustn't generalise tyvars which are constrained,
584         because we are going to pass on out the unmodified LIE, with those
585         tyvars in it.  They won't be in scope if we've generalised them.
586
587 So we are careful, and do a complete simplification just to find the
588 constrained tyvars. We don't use any of the results, except to
589 find which tyvars are constrained.
590
591 \begin{code}
592 isUnRestrictedGroup :: [Name]           -- Signatures given for these
593                     -> RenamedMonoBinds
594                     -> Bool
595
596 is_elem v vs = isIn "isUnResMono" v vs
597
598 isUnRestrictedGroup sigs (PatMonoBind other        _ _) = False
599 isUnRestrictedGroup sigs (VarMonoBind v _)              = v `is_elem` sigs
600 isUnRestrictedGroup sigs (FunMonoBind v _ matches _)    = isUnRestrictedMatch matches || 
601                                                           v `is_elem` sigs
602 isUnRestrictedGroup sigs (AndMonoBinds mb1 mb2)         = isUnRestrictedGroup sigs mb1 &&
603                                                           isUnRestrictedGroup sigs mb2
604 isUnRestrictedGroup sigs EmptyMonoBinds                 = True
605
606 isUnRestrictedMatch (Match [] _ _ : _) = False  -- No args => like a pattern binding
607 isUnRestrictedMatch other              = True   -- Some args => a function binding
608 \end{code}
609
610
611 %************************************************************************
612 %*                                                                      *
613 \subsection{tcMonoBind}
614 %*                                                                      *
615 %************************************************************************
616
617 @tcMonoBinds@ deals with a single @MonoBind@.  
618 The signatures have been dealt with already.
619
620 \begin{code}
621 tcMonoBinds :: RenamedMonoBinds 
622             -> [TcSigInfo] -> RecFlag
623             -> TcM (TcMonoBinds, 
624                     Bag (Name,          -- Bound names
625                          TcId))         -- Corresponding monomorphic bound things
626
627 tcMonoBinds mbinds tc_ty_sigs is_rec
628         -- Three stages: 
629         -- 1. Check the patterns, building up an environment binding
630         --    the variables in this group (in the recursive case)
631         -- 2. Extend the environment
632         -- 3. Check the RHSs
633   = tc_mb_pats mbinds           `thenM` \ (complete_it, xve) ->
634     tcExtendLocalValEnv2 (bagToList xve) complete_it
635   where
636     tc_mb_pats EmptyMonoBinds 
637       = returnM (returnM (EmptyMonoBinds, emptyBag), emptyBag)
638
639     tc_mb_pats (AndMonoBinds mb1 mb2)
640       = tc_mb_pats mb1          `thenM` \ (complete_it1, xve1) ->
641         tc_mb_pats mb2          `thenM` \ (complete_it2, xve2) ->
642         let
643            complete_it = complete_it1   `thenM` \ (mb1', bs1) ->
644                          complete_it2   `thenM` \ (mb2', bs2) ->
645                          returnM (AndMonoBinds mb1' mb2', bs1 `unionBags` bs2)
646         in
647         returnM (complete_it, xve1 `unionBags` xve2)
648
649     tc_mb_pats (FunMonoBind name inf matches locn)
650                 -- Three cases:
651                 --      a) Type sig supplied
652                 --      b) No type sig and recursive
653                 --      c) No type sig and non-recursive
654
655       | Just sig <- maybeSig tc_ty_sigs name 
656       = let     -- (a) There is a type signature
657                 -- Use it for the environment extension, and check
658                 -- the RHS has the appropriate type (with outer for-alls stripped off)
659            mono_id = tcSigMonoId sig
660            mono_ty = idType mono_id
661            complete_it = addSrcLoc locn                                 $
662                          tcMatchesFun name matches (Check mono_ty)      `thenM` \ matches' ->
663                          returnM (FunMonoBind mono_id inf matches' locn, 
664                                   unitBag (name, mono_id))
665         in
666         returnM (complete_it, if isRec is_rec then unitBag (name,tcSigPolyId sig) 
667                                               else emptyBag)
668
669       | isRec is_rec
670       =         -- (b) No type signature, and recursive
671                 -- So we must use an ordinary H-M type variable
672                 -- which means the variable gets an inferred tau-type
673         newLocalName name               `thenM` \ mono_name ->
674         newTyVarTy openTypeKind         `thenM` \ mono_ty ->
675         let
676            mono_id     = mkLocalId mono_name mono_ty
677            complete_it = addSrcLoc locn                                 $
678                          tcMatchesFun name matches (Check mono_ty)      `thenM` \ matches' ->
679                          returnM (FunMonoBind mono_id inf matches' locn, 
680                                   unitBag (name, mono_id))
681         in
682         returnM (complete_it, unitBag (name, mono_id))
683
684       | otherwise       -- (c) No type signature, and non-recursive
685       = let             -- So we can use a 'hole' type to infer a higher-rank type
686            complete_it 
687                 = addSrcLoc locn                                $
688                   newHole                                       `thenM` \ hole -> 
689                   tcMatchesFun name matches (Infer hole)        `thenM` \ matches' ->
690                   readMutVar hole                               `thenM` \ fun_ty ->
691                   newLocalName name                             `thenM` \ mono_name ->
692                   let
693                      mono_id = mkLocalId mono_name fun_ty
694                   in
695                   returnM (FunMonoBind mono_id inf matches' locn, 
696                            unitBag (name, mono_id))
697         in
698         returnM (complete_it, emptyBag)
699         
700     tc_mb_pats bind@(PatMonoBind pat grhss locn)
701       = addSrcLoc locn          $
702
703                 --      Now typecheck the pattern
704                 -- We do now support binding fresh (not-already-in-scope) scoped 
705                 -- type variables in the pattern of a pattern binding.  
706                 -- For example, this is now legal:
707                 --      (x::a, y::b) = e
708                 -- The type variables are brought into scope in tc_binds_and_then,
709                 -- so we don't have to do anything here.
710
711         newHole                                 `thenM` \ hole -> 
712         tcPat tc_pat_bndr pat (Infer hole)      `thenM` \ (pat', tvs, ids, lie_avail) ->
713         readMutVar hole                         `thenM` \ pat_ty ->
714
715         -- Don't know how to deal with pattern-bound existentials yet
716         checkTc (isEmptyBag tvs && null lie_avail) 
717                 (existentialExplode bind)       `thenM_` 
718
719         let
720            complete_it = addSrcLoc locn                                 $
721                          addErrCtxt (patMonoBindsCtxt bind)             $
722                          tcGRHSs PatBindRhs grhss (Check pat_ty)        `thenM` \ grhss' ->
723                          returnM (PatMonoBind pat' grhss' locn, ids)
724         in
725         returnM (complete_it, if isRec is_rec then ids else emptyBag)
726
727         -- tc_pat_bndr is used when dealing with a LHS binder in a pattern.
728         -- If there was a type sig for that Id, we want to make it much
729         -- as if that type signature had been on the binder as a SigPatIn.
730         -- We check for a type signature; if there is one, we use the mono_id
731         -- from the signature.  This is how we make sure the tau part of the
732         -- signature actually matches the type of the LHS; then tc_mb_pats
733         -- ensures the LHS and RHS have the same type
734         
735     tc_pat_bndr name pat_ty
736         = case maybeSig tc_ty_sigs name of
737             Nothing  -> newLocalName name                       `thenM` \ bndr_name ->
738                         tcMonoPatBndr bndr_name pat_ty
739
740             Just sig -> addSrcLoc (getSrcLoc name)              $
741                         tcSubPat (idType mono_id) pat_ty        `thenM` \ co_fn ->
742                         returnM (co_fn, mono_id)
743                      where
744                         mono_id = tcSigMonoId sig
745 \end{code}
746
747
748 %************************************************************************
749 %*                                                                      *
750 \subsection{SPECIALIZE pragmas}
751 %*                                                                      *
752 %************************************************************************
753
754 @tcSpecSigs@ munches up the specialisation "signatures" that arise through *user*
755 pragmas.  It is convenient for them to appear in the @[RenamedSig]@
756 part of a binding because then the same machinery can be used for
757 moving them into place as is done for type signatures.
758
759 They look like this:
760
761 \begin{verbatim}
762         f :: Ord a => [a] -> b -> b
763         {-# SPECIALIZE f :: [Int] -> b -> b #-}
764 \end{verbatim}
765
766 For this we generate:
767 \begin{verbatim}
768         f* = /\ b -> let d1 = ...
769                      in f Int b d1
770 \end{verbatim}
771
772 where f* is a SpecPragmaId.  The **sole** purpose of SpecPragmaIds is to
773 retain a right-hand-side that the simplifier will otherwise discard as
774 dead code... the simplifier has a flag that tells it not to discard
775 SpecPragmaId bindings.
776
777 In this case the f* retains a call-instance of the overloaded
778 function, f, (including appropriate dictionaries) so that the
779 specialiser will subsequently discover that there's a call of @f@ at
780 Int, and will create a specialisation for @f@.  After that, the
781 binding for @f*@ can be discarded.
782
783 We used to have a form
784         {-# SPECIALISE f :: <type> = g #-}
785 which promised that g implemented f at <type>, but we do that with 
786 a RULE now:
787         {-# SPECIALISE (f::<type) = g #-}
788
789 \begin{code}
790 tcSpecSigs :: [RenamedSig] -> TcM TcMonoBinds
791 tcSpecSigs (SpecSig name poly_ty src_loc : sigs)
792   =     -- SPECIALISE f :: forall b. theta => tau  =  g
793     addSrcLoc src_loc                           $
794     addErrCtxt (valSpecSigCtxt name poly_ty)    $
795
796         -- Get and instantiate its alleged specialised type
797     tcHsSigType (FunSigCtxt name) poly_ty       `thenM` \ sig_ty ->
798
799         -- Check that f has a more general type, and build a RHS for
800         -- the spec-pragma-id at the same time
801     getLIE (tcCheckSigma (HsVar name) sig_ty)   `thenM` \ (spec_expr, spec_lie) ->
802
803         -- Squeeze out any Methods (see comments with tcSimplifyToDicts)
804     tcSimplifyToDicts spec_lie                  `thenM` \ spec_binds ->
805
806         -- Just specialise "f" by building a SpecPragmaId binding
807         -- It is the thing that makes sure we don't prematurely 
808         -- dead-code-eliminate the binding we are really interested in.
809     newLocalName name                   `thenM` \ spec_name ->
810     let
811         spec_bind = VarMonoBind (mkSpecPragmaId spec_name sig_ty)
812                                 (mkHsLet spec_binds spec_expr)
813     in
814
815         -- Do the rest and combine
816     tcSpecSigs sigs                     `thenM` \ binds_rest ->
817     returnM (binds_rest `andMonoBinds` spec_bind)
818
819 tcSpecSigs (other_sig : sigs) = tcSpecSigs sigs
820 tcSpecSigs []                 = returnM EmptyMonoBinds
821 \end{code}
822
823
824 %************************************************************************
825 %*                                                                      *
826 \subsection[TcBinds-errors]{Error contexts and messages}
827 %*                                                                      *
828 %************************************************************************
829
830
831 \begin{code}
832 patMonoBindsCtxt bind
833   = hang (ptext SLIT("In a pattern binding:")) 4 (ppr bind)
834
835 -----------------------------------------------
836 valSpecSigCtxt v ty
837   = sep [ptext SLIT("In a SPECIALIZE pragma for a value:"),
838          nest 4 (ppr v <+> dcolon <+> ppr ty)]
839
840 -----------------------------------------------
841 sigContextsErr = ptext SLIT("Mismatched contexts")
842
843 sigContextsCtxt s1 s2
844   = vcat [ptext SLIT("When matching the contexts of the signatures for"), 
845           nest 2 (vcat [ppr s1 <+> dcolon <+> ppr (idType s1),
846                         ppr s2 <+> dcolon <+> ppr (idType s2)]),
847           ptext SLIT("The signature contexts in a mutually recursive group should all be identical")]
848
849 -----------------------------------------------
850 unliftedBindErr flavour mbind
851   = hang (text flavour <+> ptext SLIT("bindings for unlifted types aren't allowed:"))
852          4 (ppr mbind)
853
854 -----------------------------------------------
855 existentialExplode mbinds
856   = hang (vcat [text "My brain just exploded.",
857                 text "I can't handle pattern bindings for existentially-quantified constructors.",
858                 text "In the binding group"])
859         4 (ppr mbinds)
860
861 -----------------------------------------------
862 restrictedBindCtxtErr binder_names
863   = hang (ptext SLIT("Illegal overloaded type signature(s)"))
864        4 (vcat [ptext SLIT("in a binding group for") <+> pprBinders binder_names,
865                 ptext SLIT("that falls under the monomorphism restriction")])
866
867 genCtxt binder_names
868   = ptext SLIT("When generalising the type(s) for") <+> pprBinders binder_names
869
870 -- Used in error messages
871 -- Use quotes for a single one; they look a bit "busy" for several
872 pprBinders [bndr] = quotes (ppr bndr)
873 pprBinders bndrs  = pprWithCommas ppr bndrs
874 \end{code}