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