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