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