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