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