[project @ 2003-12-17 11:29:40 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcBinds.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcBinds]{TcBinds}
5
6 \begin{code}
7 module TcBinds ( tcBindsAndThen, tcTopBinds, tcMonoBinds, tcSpecSigs ) where
8
9 #include "HsVersions.h"
10
11 import {-# SOURCE #-} TcMatches ( tcGRHSsPat, tcMatchesFun )
12 import {-# SOURCE #-} TcExpr  ( tcCheckSigma, tcCheckRho )
13
14 import CmdLineOpts      ( DynFlag(Opt_NoMonomorphismRestriction) )
15 import HsSyn            ( HsExpr(..), HsBind(..), LHsBind, LHsBinds, Sig(..),
16                           LSig, Match(..), HsBindGroup(..), IPBind(..),
17                           collectSigTysFromHsBinds, collectHsBindBinders,
18                         )
19 import TcHsSyn          ( TcId, zonkId, mkHsLet )
20
21 import TcRnMonad
22 import Inst             ( InstOrigin(..), newDicts, newIPDict, instToId )
23 import TcEnv            ( tcExtendLocalValEnv, tcExtendLocalValEnv2, newLocalName )
24 import TcUnify          ( Expected(..), newHole, unifyTauTyLists, checkSigTyVarsWrt, sigCtxt )
25 import TcSimplify       ( tcSimplifyInfer, tcSimplifyInferCheck, tcSimplifyRestricted, 
26                           tcSimplifyToDicts, tcSimplifyIPs )
27 import TcHsType         ( tcHsSigType, UserTypeCtxt(..), TcSigInfo(..), 
28                           tcTySig, maybeSig, tcAddScopedTyVars
29                         )
30 import TcPat            ( tcPat, tcSubPat, tcMonoPatBndr )
31 import TcSimplify       ( bindInstsOfLocalFuns )
32 import TcMType          ( newTyVar, newTyVarTy, zonkTcTyVarToTyVar )
33 import TcType           ( TcTyVar, mkTyVarTy, mkForAllTys, mkFunTys, tyVarsOfType, 
34                           mkPredTy, mkForAllTy, isUnLiftedType, 
35                           unliftedTypeKind, liftedTypeKind, openTypeKind, eqKind
36                         )
37
38 import CoreFVs          ( idFreeTyVars )
39 import Id               ( mkLocalId, mkSpecPragmaId, setInlinePragma )
40 import Var              ( idType, idName )
41 import Name             ( Name, getSrcLoc )
42 import NameSet
43 import Var              ( tyVarKind )
44 import VarSet
45 import SrcLoc           ( Located(..), srcLocSpan, unLoc, noLoc )
46 import Bag
47 import Util             ( isIn, equalLength )
48 import BasicTypes       ( TopLevelFlag(..), RecFlag(..), isNonRec, isRec, 
49                           isNotTopLevel, isAlwaysActive )
50 import FiniteMap        ( listToFM, lookupFM )
51 import Outputable
52 \end{code}
53
54
55 %************************************************************************
56 %*                                                                      *
57 \subsection{Type-checking bindings}
58 %*                                                                      *
59 %************************************************************************
60
61 @tcBindsAndThen@ typechecks a @HsBinds@.  The "and then" part is because
62 it needs to know something about the {\em usage} of the things bound,
63 so that it can create specialisations of them.  So @tcBindsAndThen@
64 takes a function which, given an extended environment, E, typechecks
65 the scope of the bindings returning a typechecked thing and (most
66 important) an LIE.  It is this LIE which is then used as the basis for
67 specialising the things bound.
68
69 @tcBindsAndThen@ also takes a "combiner" which glues together the
70 bindings and the "thing" to make a new "thing".
71
72 The real work is done by @tcBindWithSigsAndThen@.
73
74 Recursive and non-recursive binds are handled in essentially the same
75 way: because of uniques there are no scoping issues left.  The only
76 difference is that non-recursive bindings can bind primitive values.
77
78 Even for non-recursive binding groups we add typings for each binder
79 to the LVE for the following reason.  When each individual binding is
80 checked the type of its LHS is unified with that of its RHS; and
81 type-checking the LHS of course requires that the binder is in scope.
82
83 At the top-level the LIE is sure to contain nothing but constant
84 dictionaries, which we resolve at the module level.
85
86 \begin{code}
87 tcTopBinds :: [HsBindGroup Name] -> TcM (LHsBinds TcId, TcLclEnv)
88         -- Note: returning the TcLclEnv is more than we really
89         --       want.  The bit we care about is the local bindings
90         --       and the free type variables thereof
91 tcTopBinds binds
92   = tc_binds_and_then TopLevel glue binds       $
93     getLclEnv                                   `thenM` \ env ->
94     returnM (emptyBag, env)
95   where
96         -- The top level bindings are flattened into a giant 
97         -- implicitly-mutually-recursive MonoBinds
98     glue (HsBindGroup binds1 _ _) (binds2, env) = (binds1 `unionBags` binds2, env)
99         -- Can't have a HsIPBinds at top level
100
101
102 tcBindsAndThen
103         :: (HsBindGroup TcId -> thing -> thing)         -- Combinator
104         -> [HsBindGroup Name]
105         -> TcM thing
106         -> TcM thing
107
108 tcBindsAndThen = tc_binds_and_then NotTopLevel
109
110 tc_binds_and_then top_lvl combiner [] do_next
111   = do_next
112 tc_binds_and_then top_lvl combiner (group : groups) do_next
113   = tc_bind_and_then top_lvl combiner group $ 
114     tc_binds_and_then top_lvl combiner groups do_next
115
116 tc_bind_and_then top_lvl combiner (HsIPBinds binds) do_next
117   = getLIE do_next                              `thenM` \ (result, expr_lie) ->
118     mapAndUnzipM (wrapLocSndM tc_ip_bind) binds `thenM` \ (avail_ips, binds') ->
119
120         -- If the binding binds ?x = E, we  must now 
121         -- discharge any ?x constraints in expr_lie
122     tcSimplifyIPs avail_ips expr_lie    `thenM` \ dict_binds ->
123
124     returnM (combiner (HsIPBinds binds') $
125              combiner (HsBindGroup dict_binds [] Recursive) result)
126   where
127         -- I wonder if we should do these one at at time
128         -- Consider     ?x = 4
129         --              ?y = ?x + 1
130     tc_ip_bind (IPBind ip expr)
131       = newTyVarTy openTypeKind                 `thenM` \ ty ->
132         newIPDict (IPBindOrigin ip) ip ty       `thenM` \ (ip', ip_inst) ->
133         tcCheckRho expr ty                      `thenM` \ expr' ->
134         returnM (ip_inst, (IPBind ip' expr'))
135
136 tc_bind_and_then top_lvl combiner (HsBindGroup binds sigs is_rec) do_next
137   | isEmptyBag binds 
138   = do_next
139   | otherwise
140  =      -- BRING ANY SCOPED TYPE VARIABLES INTO SCOPE
141           -- Notice that they scope over 
142           --       a) the type signatures in the binding group
143           --       b) the bindings in the group
144           --       c) the scope of the binding group (the "in" part)
145       tcAddScopedTyVars (collectSigTysFromHsBinds (bagToList binds))  $
146       tcBindWithSigs top_lvl binds sigs is_rec  `thenM` \ (poly_binds, poly_ids) ->
147  
148       case top_lvl of
149           TopLevel       -- For the top level don't bother will all this
150                          --  bindInstsOfLocalFuns stuff. All the top level 
151                          -- things are rec'd together anyway, so it's fine to
152                          -- leave them to the tcSimplifyTop, and quite a bit faster too
153                          --
154                          -- Subtle (and ugly) point: furthermore at top level we
155                          -- return the TcLclEnv, which contains the LIE var; we
156                          -- don't want to return the wrong one!
157                 -> tc_body poly_ids                         `thenM` \ (prag_binds, thing) ->
158                    returnM (combiner (HsBindGroup
159                                         (poly_binds `unionBags` prag_binds)
160                                         [] -- no sigs
161                                         Recursive)
162                                      thing)
163  
164           NotTopLevel   -- For nested bindings we must do the 
165                         -- bindInstsOfLocalFuns thing.   We must include 
166                         -- the LIE from the RHSs too -- polymorphic recursion!
167                    -> getLIE (tc_body poly_ids)         `thenM` \ ((prag_binds, thing), lie) ->
168  
169                              -- Create specialisations of functions bound here
170                        bindInstsOfLocalFuns lie poly_ids `thenM` \ lie_binds ->
171  
172                              -- We want to keep non-recursive things non-recursive
173                              -- so that we desugar unlifted bindings correctly
174                    if isRec is_rec then
175                      returnM (
176                         combiner (HsBindGroup
177                                         (poly_binds `unionBags` 
178                                          lie_binds  `unionBags`
179                                          prag_binds)
180                                         [] Recursive) thing
181                      )
182                    else
183                      returnM (
184                         combiner (HsBindGroup poly_binds [] NonRecursive) $
185                         combiner (HsBindGroup prag_binds [] NonRecursive) $
186                         combiner (HsBindGroup lie_binds  [] Recursive)    $
187                          -- NB: the binds returned by tcSimplify and
188                          -- bindInstsOfLocalFuns aren't guaranteed in
189                          -- dependency order (though we could change
190                          -- that); hence the Recursive marker.
191                         thing)
192
193 {-
194    =    -- BRING ANY SCOPED TYPE VARIABLES INTO SCOPE
195         -- Notice that they scope over 
196         --      a) the type signatures in the binding group
197         --      b) the bindings in the group
198         --      c) the scope of the binding group (the "in" part)
199       tcAddScopedTyVars (collectSigTysFromHsBinds (bagToList binds))    $
200
201       tcBindWithSigs top_lvl binds sigs is_rec  `thenM` \ (poly_binds, poly_ids) ->
202   
203       case top_lvl of
204         TopLevel        -- For the top level don't bother will all this
205                         --  bindInstsOfLocalFuns stuff. All the top level 
206                         -- things are rec'd together anyway, so it's fine to
207                         -- leave them to the tcSimplifyTop, and quite a bit faster too
208                         --
209                         -- Subtle (and ugly) point: furthermore at top level we
210                         -- return the TcLclEnv, which contains the LIE var; we
211                         -- don't want to return the wrong one!
212                 -> tc_body poly_ids                     `thenM` \ (prag_binds, thing) ->
213                    returnM (combiner (HsBindGroup
214                                         (poly_binds `unionBags` prag_binds)
215                                         [] -- no sigs
216                                         Recursive)
217                                      thing)
218
219         NotTopLevel     -- For nested bindings we must do teh bindInstsOfLocalFuns thing
220                 -> getLIE (tc_body poly_ids)            `thenM` \ ((prag_binds, thing), lie) ->
221
222                         -- Create specialisations of functions bound here
223                     bindInstsOfLocalFuns lie poly_ids   `thenM` \ lie_binds ->
224
225                         -- We want to keep non-recursive things non-recursive
226                         -- so that we desugar unlifted bindings correctly
227                    if isRec is_rec then
228                      returnM (
229                         combiner (HsBindGroup (
230                                         poly_binds `unionBags`
231                                         lie_binds  `unionBags`
232                                         prag_binds)
233                                      [] Recursive) thing
234                      )
235                    else
236                      returnM (
237                         combiner (HsBindGroup poly_binds [] NonRecursive) $
238                         combiner (HsBindGroup prag_binds [] NonRecursive) $
239                         combiner (HsBindGroup lie_binds  [] Recursive)     $
240                                 -- NB: the binds returned by tcSimplify and bindInstsOfLocalFuns
241                                 -- aren't guaranteed in dependency order (though we could change
242                                 -- that); hence the Recursive marker.
243                         thing)
244 -}
245   where
246     tc_body poly_ids    -- Type check the pragmas and "thing inside"
247       =   -- Extend the environment to bind the new polymorphic Ids
248           tcExtendLocalValEnv poly_ids  $
249   
250           -- Build bindings and IdInfos corresponding to user pragmas
251           tcSpecSigs sigs               `thenM` \ prag_binds ->
252
253           -- Now do whatever happens next, in the augmented envt
254           do_next                       `thenM` \ thing ->
255
256           returnM (prag_binds, thing)
257 \end{code}
258
259
260 %************************************************************************
261 %*                                                                      *
262 \subsection{tcBindWithSigs}
263 %*                                                                      *
264 %************************************************************************
265
266 @tcBindWithSigs@ deals with a single binding group.  It does generalisation,
267 so all the clever stuff is in here.
268
269 * binder_names and mbind must define the same set of Names
270
271 * The Names in tc_ty_sigs must be a subset of binder_names
272
273 * The Ids in tc_ty_sigs don't necessarily have to have the same name
274   as the Name in the tc_ty_sig
275
276 \begin{code}
277 tcBindWithSigs  :: TopLevelFlag
278                 -> LHsBinds Name
279                 -> [LSig Name]
280                 -> RecFlag
281                 -> TcM (LHsBinds TcId, [TcId])
282
283 tcBindWithSigs top_lvl mbind sigs is_rec
284   =     -- TYPECHECK THE SIGNATURES
285      recoverM (returnM []) (
286         mappM tcTySig [sig | sig@(L _(Sig name _)) <- sigs]
287      )                                          `thenM` \ tc_ty_sigs ->
288
289         -- SET UP THE MAIN RECOVERY; take advantage of any type sigs
290    recoverM (
291         -- If typechecking the binds fails, then return with each
292         -- signature-less binder given type (forall a.a), to minimise subsequent
293         -- error messages
294         newTyVar liftedTypeKind         `thenM` \ alpha_tv ->
295         let
296           forall_a_a    = mkForAllTy alpha_tv (mkTyVarTy alpha_tv)
297           binder_names  = collectHsBindBinders mbind
298           poly_ids      = map mk_dummy binder_names
299           mk_dummy name = case maybeSig tc_ty_sigs name of
300                             Just sig -> sig_poly_id sig                 -- Signature
301                             Nothing  -> mkLocalId name forall_a_a       -- No signature
302         in
303         traceTc (text "tcBindsWithSigs: error recovery" <+> ppr binder_names)   `thenM_`
304         returnM (emptyBag, poly_ids)
305     )                                           $
306
307         -- TYPECHECK THE BINDINGS
308     traceTc (ptext SLIT("--------------------------------------------------------"))    `thenM_`
309     traceTc (ptext SLIT("Bindings for") <+> ppr (collectHsBindBinders mbind))           `thenM_`
310     getLIE (tcMonoBinds mbind tc_ty_sigs is_rec)        `thenM` \ ((mbind', bndr_names_w_ids), lie_req) ->
311     let
312         (binder_names, mono_ids) = unzip (bagToList bndr_names_w_ids)
313         tau_tvs = foldr (unionVarSet . tyVarsOfType . idType) emptyVarSet mono_ids
314     in
315
316         -- GENERALISE
317         --      (it seems a bit crude to have to do getLIE twice,
318         --       but I can't see a better way just now)
319     addSrcSpan (srcLocSpan (minimum (map getSrcLoc binder_names)))      $
320         -- TODO: location wrong
321
322     addErrCtxt (genCtxt binder_names)                           $
323     getLIE (generalise binder_names mbind tau_tvs lie_req tc_ty_sigs)
324                         `thenM` \ ((tc_tyvars_to_gen, dict_binds, dict_ids), lie_free) ->
325
326
327         -- ZONK THE GENERALISED TYPE VARIABLES TO REAL TyVars
328         -- This commits any unbound kind variables to boxed kind, by unification
329         -- It's important that the final quanfified type variables
330         -- are fully zonked, *including boxity*, because they'll be 
331         -- included in the forall types of the polymorphic Ids.
332         -- At calls of these Ids we'll instantiate fresh type variables from
333         -- them, and we use their boxity then.
334     mappM zonkTcTyVarToTyVar tc_tyvars_to_gen   `thenM` \ real_tyvars_to_gen ->
335
336         -- ZONK THE Ids
337         -- It's important that the dict Ids are zonked, including the boxity set
338         -- in the previous step, because they are later used to form the type of 
339         -- the polymorphic thing, and forall-types must be zonked so far as 
340         -- their bound variables are concerned
341     mappM zonkId dict_ids                               `thenM` \ zonked_dict_ids ->
342     mappM zonkId mono_ids                               `thenM` \ zonked_mono_ids ->
343
344         -- BUILD THE POLYMORPHIC RESULT IDs
345     let
346         exports  = zipWith mk_export binder_names zonked_mono_ids
347         poly_ids = [poly_id | (_, poly_id, _) <- exports]
348         dict_tys = map idType zonked_dict_ids
349
350         inlines    = mkNameSet [ name
351                                | L _ (InlineSig True (L _ name) _) <- sigs]
352                         -- Any INLINE sig (regardless of phase control) 
353                         -- makes the RHS look small
354
355         inline_phases = listToFM [ (name, phase)
356                                  | L _ (InlineSig _ (L _ name) phase) <- sigs, 
357                                    not (isAlwaysActive phase)]
358                         -- Set the IdInfo field to control the inline phase
359                         -- AlwaysActive is the default, so don't bother with them
360
361         mk_export binder_name zonked_mono_id
362           = (tyvars, 
363              attachInlinePhase inline_phases poly_id,
364              zonked_mono_id)
365           where
366             (tyvars, poly_id) = 
367                 case maybeSig tc_ty_sigs binder_name of
368                   Just sig -> (sig_tvs sig,        sig_poly_id sig)
369                   Nothing  -> (real_tyvars_to_gen, new_poly_id)
370
371             new_poly_id = mkLocalId binder_name poly_ty
372             poly_ty = mkForAllTys real_tyvars_to_gen
373                     $ mkFunTys dict_tys 
374                     $ idType zonked_mono_id
375                 -- It's important to build a fully-zonked poly_ty, because
376                 -- we'll slurp out its free type variables when extending the
377                 -- local environment (tcExtendLocalValEnv); if it's not zonked
378                 -- it appears to have free tyvars that aren't actually free 
379                 -- at all.
380     in
381
382     traceTc (text "binding:" <+> ppr ((zonked_dict_ids, dict_binds),
383                                       exports, map idType poly_ids)) `thenM_`
384
385         -- Check for an unlifted, non-overloaded group
386         -- In that case we must make extra checks
387     if any (isUnLiftedType . idType) zonked_mono_ids && null zonked_dict_ids 
388     then        -- Some bindings are unlifted
389         checkUnliftedBinds top_lvl is_rec real_tyvars_to_gen mbind      `thenM_` 
390         
391         extendLIEs lie_req                      `thenM_`
392         returnM (
393             unitBag $ noLoc $
394             AbsBinds [] [] exports inlines mbind',
395                 -- Do not generate even any x=y bindings
396             poly_ids
397         )
398
399     else        -- The normal case
400         extendLIEs lie_free                             `thenM_`
401         returnM (
402             unitBag $ noLoc $
403             AbsBinds real_tyvars_to_gen
404                  zonked_dict_ids
405                  exports
406                  inlines
407                  (dict_binds `unionBags` mbind'),
408             poly_ids
409         )
410
411 attachInlinePhase inline_phases bndr
412   = case lookupFM inline_phases (idName bndr) of
413         Just prag -> bndr `setInlinePragma` prag
414         Nothing   -> bndr
415
416 -- Check that non-overloaded unlifted bindings are
417 --      a) non-recursive,
418 --      b) not top level, 
419 --      c) non-polymorphic
420 --      d) not a multiple-binding group (more or less implied by (a))
421
422 checkUnliftedBinds top_lvl is_rec real_tyvars_to_gen mbind
423   = ASSERT( not (any ((eqKind unliftedTypeKind) . tyVarKind) real_tyvars_to_gen) )
424                 -- The instCantBeGeneralised stuff in tcSimplify should have
425                 -- already raised an error if we're trying to generalise an 
426                 -- unboxed tyvar (NB: unboxed tyvars are always introduced 
427                 -- along with a class constraint) and it's better done there 
428                 -- because we have more precise origin information.
429                 -- That's why we just use an ASSERT here.
430
431     checkTc (isNotTopLevel top_lvl)
432             (unliftedBindErr "Top-level" mbind)         `thenM_`
433     checkTc (isNonRec is_rec)
434             (unliftedBindErr "Recursive" mbind)         `thenM_`
435     checkTc (isSingletonBag mbind)
436             (unliftedBindErr "Multiple" mbind)          `thenM_`
437     checkTc (null real_tyvars_to_gen)
438             (unliftedBindErr "Polymorphic" mbind)
439 \end{code}
440
441
442 Polymorphic recursion
443 ~~~~~~~~~~~~~~~~~~~~~
444 The game plan for polymorphic recursion in the code above is 
445
446         * Bind any variable for which we have a type signature
447           to an Id with a polymorphic type.  Then when type-checking 
448           the RHSs we'll make a full polymorphic call.
449
450 This fine, but if you aren't a bit careful you end up with a horrendous
451 amount of partial application and (worse) a huge space leak. For example:
452
453         f :: Eq a => [a] -> [a]
454         f xs = ...f...
455
456 If we don't take care, after typechecking we get
457
458         f = /\a -> \d::Eq a -> let f' = f a d
459                                in
460                                \ys:[a] -> ...f'...
461
462 Notice the the stupid construction of (f a d), which is of course
463 identical to the function we're executing.  In this case, the
464 polymorphic recursion isn't being used (but that's a very common case).
465 We'd prefer
466
467         f = /\a -> \d::Eq a -> letrec
468                                  fm = \ys:[a] -> ...fm...
469                                in
470                                fm
471
472 This can lead to a massive space leak, from the following top-level defn
473 (post-typechecking)
474
475         ff :: [Int] -> [Int]
476         ff = f Int dEqInt
477
478 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
479 f' is another thunk which evaluates to the same thing... and you end
480 up with a chain of identical values all hung onto by the CAF ff.
481
482         ff = f Int dEqInt
483
484            = let f' = f Int dEqInt in \ys. ...f'...
485
486            = let f' = let f' = f Int dEqInt in \ys. ...f'...
487                       in \ys. ...f'...
488
489 Etc.
490 Solution: when typechecking the RHSs we always have in hand the
491 *monomorphic* Ids for each binding.  So we just need to make sure that
492 if (Method f a d) shows up in the constraints emerging from (...f...)
493 we just use the monomorphic Id.  We achieve this by adding monomorphic Ids
494 to the "givens" when simplifying constraints.  That's what the "lies_avail"
495 is doing.
496
497
498 %************************************************************************
499 %*                                                                      *
500 \subsection{getTyVarsToGen}
501 %*                                                                      *
502 %************************************************************************
503
504 \begin{code}
505 generalise binder_names mbind tau_tvs lie_req sigs =
506
507   -- check for -fno-monomorphism-restriction
508   doptM Opt_NoMonomorphismRestriction           `thenM` \ no_MR ->
509   let is_unrestricted | no_MR     = True
510                       | otherwise = isUnRestrictedGroup tysig_names mbind
511   in
512
513   if not is_unrestricted then   -- RESTRICTED CASE
514         -- Check signature contexts are empty 
515     checkTc (all is_mono_sig sigs)
516             (restrictedBindCtxtErr binder_names)        `thenM_`
517
518         -- Now simplify with exactly that set of tyvars
519         -- We have to squash those Methods
520     tcSimplifyRestricted doc tau_tvs lie_req            `thenM` \ (qtvs, binds) ->
521
522         -- Check that signature type variables are OK
523     checkSigsTyVars qtvs sigs                           `thenM` \ final_qtvs ->
524
525     returnM (final_qtvs, binds, [])
526
527   else if null sigs then        -- UNRESTRICTED CASE, NO TYPE SIGS
528     tcSimplifyInfer doc tau_tvs lie_req
529
530   else                          -- UNRESTRICTED CASE, WITH TYPE SIGS
531         -- CHECKING CASE: Unrestricted group, there are type signatures
532         -- Check signature contexts are identical
533     checkSigsCtxts sigs                 `thenM` \ (sig_avails, sig_dicts) ->
534     
535         -- Check that the needed dicts can be
536         -- expressed in terms of the signature ones
537     tcSimplifyInferCheck doc tau_tvs sig_avails lie_req `thenM` \ (forall_tvs, dict_binds) ->
538         
539         -- Check that signature type variables are OK
540     checkSigsTyVars forall_tvs sigs                     `thenM` \ final_qtvs ->
541
542     returnM (final_qtvs, dict_binds, sig_dicts)
543
544   where
545     tysig_names     = map (idName . sig_poly_id) sigs
546     is_mono_sig sig = null (sig_theta sig)
547
548     doc = ptext SLIT("type signature(s) for") <+> pprBinders binder_names
549
550 -----------------------
551         -- CHECK THAT ALL THE SIGNATURE CONTEXTS ARE UNIFIABLE
552         -- The type signatures on a mutually-recursive group of definitions
553         -- must all have the same context (or none).
554         --
555         -- We unify them because, with polymorphic recursion, their types
556         -- might not otherwise be related.  This is a rather subtle issue.
557         -- ToDo: amplify
558 checkSigsCtxts sigs@(TySigInfo { sig_poly_id = id1, sig_tvs = sig_tvs, sig_theta = theta1, sig_loc = span}
559                      : other_sigs)
560   = addSrcSpan span                     $
561     mappM_ check_one other_sigs         `thenM_` 
562     if null theta1 then
563         returnM ([], [])                -- Non-overloaded type signatures
564     else
565     newDicts SignatureOrigin theta1     `thenM` \ sig_dicts ->
566     let
567         -- The "sig_avails" is the stuff available.  We get that from
568         -- the context of the type signature, BUT ALSO the lie_avail
569         -- so that polymorphic recursion works right (see comments at end of fn)
570         sig_avails = sig_dicts ++ sig_meths
571     in
572     returnM (sig_avails, map instToId sig_dicts)
573   where
574     sig1_dict_tys = map mkPredTy theta1
575     sig_meths     = concatMap sig_insts sigs
576
577     check_one (TySigInfo {sig_poly_id = id, sig_theta = theta})
578        = addErrCtxt (sigContextsCtxt id1 id)                    $
579          checkTc (equalLength theta theta1) sigContextsErr      `thenM_`
580          unifyTauTyLists sig1_dict_tys (map mkPredTy theta)
581
582 checkSigsTyVars :: [TcTyVar] -> [TcSigInfo] -> TcM [TcTyVar]
583 checkSigsTyVars qtvs sigs 
584   = mappM check_one sigs        `thenM` \ sig_tvs_s ->
585     let
586         -- Sigh.  Make sure that all the tyvars in the type sigs
587         -- appear in the returned ty var list, which is what we are
588         -- going to generalise over.  Reason: we occasionally get
589         -- silly types like
590         --      type T a = () -> ()
591         --      f :: T a
592         --      f () = ()
593         -- Here, 'a' won't appear in qtvs, so we have to add it
594
595         sig_tvs = foldl extendVarSetList emptyVarSet sig_tvs_s
596         all_tvs = extendVarSetList sig_tvs qtvs
597     in
598     returnM (varSetElems all_tvs)
599   where
600     check_one (TySigInfo {sig_poly_id = id, sig_tvs = tvs, sig_theta = theta, sig_tau = tau})
601       = addErrCtxt (ptext SLIT("In the type signature for") 
602                       <+> quotes (ppr id))              $
603         addErrCtxtM (sigCtxt id tvs theta tau)          $
604         checkSigTyVarsWrt (idFreeTyVars id) tvs
605 \end{code}
606
607 @getTyVarsToGen@ decides what type variables to generalise over.
608
609 For a "restricted group" -- see the monomorphism restriction
610 for a definition -- we bind no dictionaries, and
611 remove from tyvars_to_gen any constrained type variables
612
613 *Don't* simplify dicts at this point, because we aren't going
614 to generalise over these dicts.  By the time we do simplify them
615 we may well know more.  For example (this actually came up)
616         f :: Array Int Int
617         f x = array ... xs where xs = [1,2,3,4,5]
618 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
619 stuff.  If we simplify only at the f-binding (not the xs-binding)
620 we'll know that the literals are all Ints, and we can just produce
621 Int literals!
622
623 Find all the type variables involved in overloading, the
624 "constrained_tyvars".  These are the ones we *aren't* going to
625 generalise.  We must be careful about doing this:
626
627  (a) If we fail to generalise a tyvar which is not actually
628         constrained, then it will never, ever get bound, and lands
629         up printed out in interface files!  Notorious example:
630                 instance Eq a => Eq (Foo a b) where ..
631         Here, b is not constrained, even though it looks as if it is.
632         Another, more common, example is when there's a Method inst in
633         the LIE, whose type might very well involve non-overloaded
634         type variables.
635   [NOTE: Jan 2001: I don't understand the problem here so I'm doing 
636         the simple thing instead]
637
638  (b) On the other hand, we mustn't generalise tyvars which are constrained,
639         because we are going to pass on out the unmodified LIE, with those
640         tyvars in it.  They won't be in scope if we've generalised them.
641
642 So we are careful, and do a complete simplification just to find the
643 constrained tyvars. We don't use any of the results, except to
644 find which tyvars are constrained.
645
646 \begin{code}
647 isUnRestrictedGroup :: [Name]           -- Signatures given for these
648                     -> LHsBinds Name
649                     -> Bool
650 isUnRestrictedGroup sigs binds = all (unrestricted . unLoc) (bagToList binds)
651   where 
652     unrestricted (PatBind other _)      = False
653     unrestricted (VarBind v _)          = v `is_elem` sigs
654     unrestricted (FunBind v _ matches)  = unrestricted_match matches 
655                                            || unLoc v `is_elem` sigs
656
657     unrestricted_match (L _ (Match [] _ _) : _) = False
658         -- No args => like a pattern binding
659     unrestricted_match other              = True
660         -- Some args => a function binding
661
662 is_elem v vs = isIn "isUnResMono" v vs
663 \end{code}
664
665
666 %************************************************************************
667 %*                                                                      *
668 \subsection{tcMonoBind}
669 %*                                                                      *
670 %************************************************************************
671
672 @tcMonoBinds@ deals with a single @MonoBind@.  
673 The signatures have been dealt with already.
674
675 \begin{code}
676 tcMonoBinds :: LHsBinds Name
677             -> [TcSigInfo] -> RecFlag
678             -> TcM (LHsBinds TcId, 
679                     Bag (Name,          -- Bound names
680                          TcId))         -- Corresponding monomorphic bound things
681
682 tcMonoBinds mbinds tc_ty_sigs is_rec
683         -- Three stages: 
684         -- 1. Check the patterns, building up an environment binding
685         --    the variables in this group (in the recursive case)
686         -- 2. Extend the environment
687         -- 3. Check the RHSs
688   = mapBagM tc_lbind_pats mbinds                `thenM` \ bag_of_pairs ->
689     let
690         (complete_it, xve) 
691                 = foldrBag combine 
692                            (returnM (emptyBag, emptyBag), emptyBag)
693                            bag_of_pairs
694         combine (complete_it1, xve1) (complete_it2, xve2)
695            = (complete_it, xve1 `unionBags` xve2)
696            where
697               complete_it = complete_it1        `thenM` \ (b1, bs1) ->
698                             complete_it2        `thenM` \ (b2, bs2) ->
699                             returnM (b1 `consBag` b2, bs1 `unionBags` bs2)
700     in
701     tcExtendLocalValEnv2 (bagToList xve) complete_it
702   where
703     tc_lbind_pats :: LHsBind Name
704                  -> TcM (TcM (LHsBind TcId, Bag (Name,TcId)),   -- Completer
705                          Bag (Name,TcId))
706         -- wrapper for tc_bind_pats to deal with the location stuff
707     tc_lbind_pats (L loc bind)
708         = addSrcSpan loc $ do
709             (tc, bag) <- tc_bind_pats bind
710             return (wrap tc, bag)
711          where
712             wrap tc = addSrcSpan loc $ do
713                         (bind, stuff) <- tc
714                         return (L loc bind, stuff)
715
716
717     tc_bind_pats :: HsBind Name
718                  -> TcM (TcM (HsBind TcId, Bag (Name,TcId)),    -- Completer
719                          Bag (Name,TcId))
720     tc_bind_pats (FunBind (L nm_loc name) inf matches)
721                 -- Three cases:
722                 --      a) Type sig supplied
723                 --      b) No type sig and recursive
724                 --      c) No type sig and non-recursive
725
726       | Just sig <- maybeSig tc_ty_sigs name 
727       = let     -- (a) There is a type signature
728                 -- Use it for the environment extension, and check
729                 -- the RHS has the appropriate type (with outer for-alls stripped off)
730            mono_id = sig_mono_id sig
731            mono_ty = idType mono_id
732            complete_it = tcMatchesFun name matches (Check mono_ty)      `thenM` \ matches' ->
733                          returnM (FunBind (L nm_loc mono_id) inf matches',
734                                   unitBag (name, mono_id))
735         in
736         returnM (complete_it, if isRec is_rec then unitBag (name, sig_poly_id sig) 
737                                               else emptyBag)
738
739       | isRec is_rec
740       =         -- (b) No type signature, and recursive
741                 -- So we must use an ordinary H-M type variable
742                 -- which means the variable gets an inferred tau-type
743         newLocalName name               `thenM` \ mono_name ->
744         newTyVarTy openTypeKind         `thenM` \ mono_ty ->
745         let
746            mono_id     = mkLocalId mono_name mono_ty
747            complete_it = tcMatchesFun name matches (Check mono_ty)      `thenM` \ matches' ->
748                          returnM (FunBind (L nm_loc mono_id) inf matches', 
749                                   unitBag (name, mono_id))
750         in
751         returnM (complete_it, unitBag (name, mono_id))
752
753       | otherwise       -- (c) No type signature, and non-recursive
754       = let             -- So we can use a 'hole' type to infer a higher-rank type
755            complete_it 
756                 = newHole                                       `thenM` \ hole -> 
757                   tcMatchesFun name matches (Infer hole)        `thenM` \ matches' ->
758                   readMutVar hole                               `thenM` \ fun_ty ->
759                   newLocalName name                             `thenM` \ mono_name ->
760                   let
761                      mono_id = mkLocalId mono_name fun_ty
762                   in
763                   returnM (FunBind (L nm_loc mono_id) inf matches', 
764                            unitBag (name, mono_id))
765         in
766         returnM (complete_it, emptyBag)
767         
768     tc_bind_pats bind@(PatBind pat grhss)
769       =         --      Now typecheck the pattern
770                 -- We do now support binding fresh (not-already-in-scope) scoped 
771                 -- type variables in the pattern of a pattern binding.  
772                 -- For example, this is now legal:
773                 --      (x::a, y::b) = e
774                 -- The type variables are brought into scope in tc_binds_and_then,
775                 -- so we don't have to do anything here.
776         newHole                                 `thenM` \ hole -> 
777         tcPat tc_pat_bndr pat (Infer hole)      `thenM` \ (pat', tvs, ids, lie_avail) ->
778         readMutVar hole                         `thenM` \ pat_ty ->
779
780         -- Don't know how to deal with pattern-bound existentials yet
781         checkTc (isEmptyBag tvs && null lie_avail) 
782                 (existentialExplode bind)       `thenM_` 
783
784         let
785            complete_it = addErrCtxt (patMonoBindsCtxt bind)             $
786                          tcGRHSsPat grhss (Check pat_ty)        `thenM` \ grhss' ->
787                          returnM (PatBind pat' grhss', ids)
788         in
789         returnM (complete_it, if isRec is_rec then ids else emptyBag)
790
791         -- tc_pat_bndr is used when dealing with a LHS binder in a pattern.
792         -- If there was a type sig for that Id, we want to make it much
793         -- as if that type signature had been on the binder as a SigPatIn.
794         -- We check for a type signature; if there is one, we use the mono_id
795         -- from the signature.  This is how we make sure the tau part of the
796         -- signature actually matches the type of the LHS; then tc_bind_pats
797         -- ensures the LHS and RHS have the same type
798         
799     tc_pat_bndr name pat_ty
800         = case maybeSig tc_ty_sigs name of
801             Nothing  -> newLocalName name                       `thenM` \ bndr_name ->
802                         tcMonoPatBndr bndr_name pat_ty
803
804             Just sig -> addSrcSpan (srcLocSpan (getSrcLoc name))        $
805                                 -- TODO: location wrong
806                         tcSubPat (idType mono_id) pat_ty        `thenM` \ co_fn ->
807                         returnM (co_fn, mono_id)
808                      where
809                         mono_id = sig_mono_id sig
810 \end{code}
811
812
813 %************************************************************************
814 %*                                                                      *
815 \subsection{SPECIALIZE pragmas}
816 %*                                                                      *
817 %************************************************************************
818
819 @tcSpecSigs@ munches up the specialisation "signatures" that arise through *user*
820 pragmas.  It is convenient for them to appear in the @[RenamedSig]@
821 part of a binding because then the same machinery can be used for
822 moving them into place as is done for type signatures.
823
824 They look like this:
825
826 \begin{verbatim}
827         f :: Ord a => [a] -> b -> b
828         {-# SPECIALIZE f :: [Int] -> b -> b #-}
829 \end{verbatim}
830
831 For this we generate:
832 \begin{verbatim}
833         f* = /\ b -> let d1 = ...
834                      in f Int b d1
835 \end{verbatim}
836
837 where f* is a SpecPragmaId.  The **sole** purpose of SpecPragmaIds is to
838 retain a right-hand-side that the simplifier will otherwise discard as
839 dead code... the simplifier has a flag that tells it not to discard
840 SpecPragmaId bindings.
841
842 In this case the f* retains a call-instance of the overloaded
843 function, f, (including appropriate dictionaries) so that the
844 specialiser will subsequently discover that there's a call of @f@ at
845 Int, and will create a specialisation for @f@.  After that, the
846 binding for @f*@ can be discarded.
847
848 We used to have a form
849         {-# SPECIALISE f :: <type> = g #-}
850 which promised that g implemented f at <type>, but we do that with 
851 a RULE now:
852         {-# SPECIALISE (f::<type) = g #-}
853
854 \begin{code}
855 tcSpecSigs :: [LSig Name] -> TcM (LHsBinds TcId)
856 tcSpecSigs (L loc (SpecSig (L nm_loc name) poly_ty) : sigs)
857   =     -- SPECIALISE f :: forall b. theta => tau  =  g
858     addSrcSpan loc                              $
859     addErrCtxt (valSpecSigCtxt name poly_ty)    $
860
861         -- Get and instantiate its alleged specialised type
862     tcHsSigType (FunSigCtxt name) poly_ty       `thenM` \ sig_ty ->
863
864         -- Check that f has a more general type, and build a RHS for
865         -- the spec-pragma-id at the same time
866     getLIE (tcCheckSigma (L nm_loc (HsVar name)) sig_ty)        `thenM` \ (spec_expr, spec_lie) ->
867
868         -- Squeeze out any Methods (see comments with tcSimplifyToDicts)
869     tcSimplifyToDicts spec_lie                  `thenM` \ spec_binds ->
870
871         -- Just specialise "f" by building a SpecPragmaId binding
872         -- It is the thing that makes sure we don't prematurely 
873         -- dead-code-eliminate the binding we are really interested in.
874     newLocalName name                   `thenM` \ spec_name ->
875     let
876         spec_bind = VarBind (mkSpecPragmaId spec_name sig_ty)
877                                 (mkHsLet spec_binds spec_expr)
878     in
879
880         -- Do the rest and combine
881     tcSpecSigs sigs                     `thenM` \ binds_rest ->
882     returnM (binds_rest `snocBag` L loc spec_bind)
883
884 tcSpecSigs (other_sig : sigs) = tcSpecSigs sigs
885 tcSpecSigs []                 = returnM emptyBag
886 \end{code}
887
888 %************************************************************************
889 %*                                                                      *
890 \subsection[TcBinds-errors]{Error contexts and messages}
891 %*                                                                      *
892 %************************************************************************
893
894
895 \begin{code}
896 patMonoBindsCtxt bind
897   = hang (ptext SLIT("In a pattern binding:")) 4 (ppr bind)
898
899 -----------------------------------------------
900 valSpecSigCtxt v ty
901   = sep [ptext SLIT("In a SPECIALIZE pragma for a value:"),
902          nest 4 (ppr v <+> dcolon <+> ppr ty)]
903
904 -----------------------------------------------
905 sigContextsErr = ptext SLIT("Mismatched contexts")
906
907 sigContextsCtxt s1 s2
908   = vcat [ptext SLIT("When matching the contexts of the signatures for"), 
909           nest 2 (vcat [ppr s1 <+> dcolon <+> ppr (idType s1),
910                         ppr s2 <+> dcolon <+> ppr (idType s2)]),
911           ptext SLIT("The signature contexts in a mutually recursive group should all be identical")]
912
913 -----------------------------------------------
914 unliftedBindErr flavour mbind
915   = hang (text flavour <+> ptext SLIT("bindings for unlifted types aren't allowed:"))
916          4 (ppr mbind)
917
918 -----------------------------------------------
919 existentialExplode mbinds
920   = hang (vcat [text "My brain just exploded.",
921                 text "I can't handle pattern bindings for existentially-quantified constructors.",
922                 text "In the binding group"])
923         4 (ppr mbinds)
924
925 -----------------------------------------------
926 restrictedBindCtxtErr binder_names
927   = hang (ptext SLIT("Illegal overloaded type signature(s)"))
928        4 (vcat [ptext SLIT("in a binding group for") <+> pprBinders binder_names,
929                 ptext SLIT("that falls under the monomorphism restriction")])
930
931 genCtxt binder_names
932   = ptext SLIT("When generalising the type(s) for") <+> pprBinders binder_names
933
934 -- Used in error messages
935 -- Use quotes for a single one; they look a bit "busy" for several
936 pprBinders [bndr] = quotes (ppr bndr)
937 pprBinders bndrs  = pprWithCommas ppr bndrs
938 \end{code}