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