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