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