[project @ 2003-12-30 16:29:17 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 )
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 (srcLocSpan (minimum (map getSrcLoc binder_names)))      $
272         -- TODO: location wrong
273
274     addErrCtxt (genCtxt binder_names)                           $
275     getLIE (generalise binder_names mbind tau_tvs lie_req tc_ty_sigs)
276                         `thenM` \ ((tc_tyvars_to_gen, dict_binds, dict_ids), lie_free) ->
277
278
279         -- ZONK THE GENERALISED TYPE VARIABLES TO REAL TyVars
280         -- This commits any unbound kind variables to boxed kind, by unification
281         -- It's important that the final quanfified type variables
282         -- are fully zonked, *including boxity*, because they'll be 
283         -- included in the forall types of the polymorphic Ids.
284         -- At calls of these Ids we'll instantiate fresh type variables from
285         -- them, and we use their boxity then.
286     mappM zonkTcTyVarToTyVar tc_tyvars_to_gen   `thenM` \ real_tyvars_to_gen ->
287
288         -- ZONK THE Ids
289         -- It's important that the dict Ids are zonked, including the boxity set
290         -- in the previous step, because they are later used to form the type of 
291         -- the polymorphic thing, and forall-types must be zonked so far as 
292         -- their bound variables are concerned
293     mappM zonkId dict_ids                               `thenM` \ zonked_dict_ids ->
294     mappM zonkId mono_ids                               `thenM` \ zonked_mono_ids ->
295
296         -- BUILD THE POLYMORPHIC RESULT IDs
297     let
298         exports  = zipWith mk_export binder_names zonked_mono_ids
299         poly_ids = [poly_id | (_, poly_id, _) <- exports]
300         dict_tys = map idType zonked_dict_ids
301
302         inlines    = mkNameSet [ name
303                                | L _ (InlineSig True (L _ name) _) <- sigs]
304                         -- Any INLINE sig (regardless of phase control) 
305                         -- makes the RHS look small
306
307         inline_phases = listToFM [ (name, phase)
308                                  | L _ (InlineSig _ (L _ name) phase) <- sigs, 
309                                    not (isAlwaysActive phase)]
310                         -- Set the IdInfo field to control the inline phase
311                         -- AlwaysActive is the default, so don't bother with them
312
313         mk_export binder_name zonked_mono_id
314           = (tyvars, 
315              attachInlinePhase inline_phases poly_id,
316              zonked_mono_id)
317           where
318             (tyvars, poly_id) = 
319                 case maybeSig tc_ty_sigs binder_name of
320                   Just sig -> (sig_tvs sig,        sig_poly_id sig)
321                   Nothing  -> (real_tyvars_to_gen, new_poly_id)
322
323             new_poly_id = mkLocalId binder_name poly_ty
324             poly_ty = mkForAllTys real_tyvars_to_gen
325                     $ mkFunTys dict_tys 
326                     $ idType zonked_mono_id
327                 -- It's important to build a fully-zonked poly_ty, because
328                 -- we'll slurp out its free type variables when extending the
329                 -- local environment (tcExtendLocalValEnv); if it's not zonked
330                 -- it appears to have free tyvars that aren't actually free 
331                 -- at all.
332     in
333
334     traceTc (text "binding:" <+> ppr ((zonked_dict_ids, dict_binds),
335                                       exports, map idType poly_ids)) `thenM_`
336
337         -- Check for an unlifted, non-overloaded group
338         -- In that case we must make extra checks
339     if any (isUnLiftedType . idType) zonked_mono_ids && null zonked_dict_ids 
340     then        -- Some bindings are unlifted
341         checkUnliftedBinds top_lvl is_rec real_tyvars_to_gen mbind      `thenM_` 
342         
343         extendLIEs lie_req                      `thenM_`
344         returnM (
345             unitBag $ noLoc $
346             AbsBinds [] [] exports inlines mbind',
347                 -- Do not generate even any x=y bindings
348             poly_ids
349         )
350
351     else        -- The normal case
352         extendLIEs lie_free                             `thenM_`
353         returnM (
354             unitBag $ noLoc $
355             AbsBinds real_tyvars_to_gen
356                  zonked_dict_ids
357                  exports
358                  inlines
359                  (dict_binds `unionBags` mbind'),
360             poly_ids
361         )
362
363 attachInlinePhase inline_phases bndr
364   = case lookupFM inline_phases (idName bndr) of
365         Just prag -> bndr `setInlinePragma` prag
366         Nothing   -> bndr
367
368 -- Check that non-overloaded unlifted bindings are
369 --      a) non-recursive,
370 --      b) not top level, 
371 --      c) non-polymorphic
372 --      d) not a multiple-binding group (more or less implied by (a))
373
374 checkUnliftedBinds top_lvl is_rec real_tyvars_to_gen mbind
375   = ASSERT( not (any (isUnliftedTypeKind . tyVarKind) real_tyvars_to_gen) )
376                 -- The instCantBeGeneralised stuff in tcSimplify should have
377                 -- already raised an error if we're trying to generalise an 
378                 -- unboxed tyvar (NB: unboxed tyvars are always introduced 
379                 -- along with a class constraint) and it's better done there 
380                 -- because we have more precise origin information.
381                 -- That's why we just use an ASSERT here.
382
383     checkTc (isNotTopLevel top_lvl)
384             (unliftedBindErr "Top-level" mbind)         `thenM_`
385     checkTc (isNonRec is_rec)
386             (unliftedBindErr "Recursive" mbind)         `thenM_`
387     checkTc (isSingletonBag mbind)
388             (unliftedBindErr "Multiple" mbind)          `thenM_`
389     checkTc (null real_tyvars_to_gen)
390             (unliftedBindErr "Polymorphic" mbind)
391 \end{code}
392
393
394 Polymorphic recursion
395 ~~~~~~~~~~~~~~~~~~~~~
396 The game plan for polymorphic recursion in the code above is 
397
398         * Bind any variable for which we have a type signature
399           to an Id with a polymorphic type.  Then when type-checking 
400           the RHSs we'll make a full polymorphic call.
401
402 This fine, but if you aren't a bit careful you end up with a horrendous
403 amount of partial application and (worse) a huge space leak. For example:
404
405         f :: Eq a => [a] -> [a]
406         f xs = ...f...
407
408 If we don't take care, after typechecking we get
409
410         f = /\a -> \d::Eq a -> let f' = f a d
411                                in
412                                \ys:[a] -> ...f'...
413
414 Notice the the stupid construction of (f a d), which is of course
415 identical to the function we're executing.  In this case, the
416 polymorphic recursion isn't being used (but that's a very common case).
417 We'd prefer
418
419         f = /\a -> \d::Eq a -> letrec
420                                  fm = \ys:[a] -> ...fm...
421                                in
422                                fm
423
424 This can lead to a massive space leak, from the following top-level defn
425 (post-typechecking)
426
427         ff :: [Int] -> [Int]
428         ff = f Int dEqInt
429
430 Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but
431 f' is another thunk which evaluates to the same thing... and you end
432 up with a chain of identical values all hung onto by the CAF ff.
433
434         ff = f Int dEqInt
435
436            = let f' = f Int dEqInt in \ys. ...f'...
437
438            = let f' = let f' = f Int dEqInt in \ys. ...f'...
439                       in \ys. ...f'...
440
441 Etc.
442 Solution: when typechecking the RHSs we always have in hand the
443 *monomorphic* Ids for each binding.  So we just need to make sure that
444 if (Method f a d) shows up in the constraints emerging from (...f...)
445 we just use the monomorphic Id.  We achieve this by adding monomorphic Ids
446 to the "givens" when simplifying constraints.  That's what the "lies_avail"
447 is doing.
448
449
450 %************************************************************************
451 %*                                                                      *
452 \subsection{getTyVarsToGen}
453 %*                                                                      *
454 %************************************************************************
455
456 \begin{code}
457 generalise binder_names mbind tau_tvs lie_req sigs =
458
459   -- check for -fno-monomorphism-restriction
460   doptM Opt_NoMonomorphismRestriction           `thenM` \ no_MR ->
461   let is_unrestricted | no_MR     = True
462                       | otherwise = isUnRestrictedGroup tysig_names mbind
463   in
464
465   if not is_unrestricted then   -- RESTRICTED CASE
466         -- Check signature contexts are empty 
467     checkTc (all is_mono_sig sigs)
468             (restrictedBindCtxtErr binder_names)        `thenM_`
469
470         -- Now simplify with exactly that set of tyvars
471         -- We have to squash those Methods
472     tcSimplifyRestricted doc tau_tvs lie_req            `thenM` \ (qtvs, binds) ->
473
474         -- Check that signature type variables are OK
475     checkSigsTyVars qtvs sigs                           `thenM` \ final_qtvs ->
476
477     returnM (final_qtvs, binds, [])
478
479   else if null sigs then        -- UNRESTRICTED CASE, NO TYPE SIGS
480     tcSimplifyInfer doc tau_tvs lie_req
481
482   else                          -- UNRESTRICTED CASE, WITH TYPE SIGS
483         -- CHECKING CASE: Unrestricted group, there are type signatures
484         -- Check signature contexts are identical
485     checkSigsCtxts sigs                 `thenM` \ (sig_avails, sig_dicts) ->
486     
487         -- Check that the needed dicts can be
488         -- expressed in terms of the signature ones
489     tcSimplifyInferCheck doc tau_tvs sig_avails lie_req `thenM` \ (forall_tvs, dict_binds) ->
490         
491         -- Check that signature type variables are OK
492     checkSigsTyVars forall_tvs sigs                     `thenM` \ final_qtvs ->
493
494     returnM (final_qtvs, dict_binds, sig_dicts)
495
496   where
497     tysig_names     = map (idName . sig_poly_id) sigs
498     is_mono_sig sig = null (sig_theta sig)
499
500     doc = ptext SLIT("type signature(s) for") <+> pprBinders binder_names
501
502 -----------------------
503         -- CHECK THAT ALL THE SIGNATURE CONTEXTS ARE UNIFIABLE
504         -- The type signatures on a mutually-recursive group of definitions
505         -- must all have the same context (or none).
506         --
507         -- We unify them because, with polymorphic recursion, their types
508         -- might not otherwise be related.  This is a rather subtle issue.
509         -- ToDo: amplify
510 checkSigsCtxts sigs@(TySigInfo { sig_poly_id = id1, sig_tvs = sig_tvs, sig_theta = theta1, sig_loc = span}
511                      : other_sigs)
512   = addSrcSpan span                     $
513     mappM_ check_one other_sigs         `thenM_` 
514     if null theta1 then
515         returnM ([], [])                -- Non-overloaded type signatures
516     else
517     newDicts SignatureOrigin theta1     `thenM` \ sig_dicts ->
518     let
519         -- The "sig_avails" is the stuff available.  We get that from
520         -- the context of the type signature, BUT ALSO the lie_avail
521         -- so that polymorphic recursion works right (see comments at end of fn)
522         sig_avails = sig_dicts ++ sig_meths
523     in
524     returnM (sig_avails, map instToId sig_dicts)
525   where
526     sig1_dict_tys = map mkPredTy theta1
527     sig_meths     = concatMap sig_insts sigs
528
529     check_one (TySigInfo {sig_poly_id = id, sig_theta = theta})
530        = addErrCtxt (sigContextsCtxt id1 id)                    $
531          checkTc (equalLength theta theta1) sigContextsErr      `thenM_`
532          unifyTauTyLists sig1_dict_tys (map mkPredTy theta)
533
534 checkSigsTyVars :: [TcTyVar] -> [TcSigInfo] -> TcM [TcTyVar]
535 checkSigsTyVars qtvs sigs 
536   = mappM check_one sigs        `thenM` \ sig_tvs_s ->
537     let
538         -- Sigh.  Make sure that all the tyvars in the type sigs
539         -- appear in the returned ty var list, which is what we are
540         -- going to generalise over.  Reason: we occasionally get
541         -- silly types like
542         --      type T a = () -> ()
543         --      f :: T a
544         --      f () = ()
545         -- Here, 'a' won't appear in qtvs, so we have to add it
546
547         sig_tvs = foldl extendVarSetList emptyVarSet sig_tvs_s
548         all_tvs = extendVarSetList sig_tvs qtvs
549     in
550     returnM (varSetElems all_tvs)
551   where
552     check_one (TySigInfo {sig_poly_id = id, sig_tvs = tvs, sig_theta = theta, sig_tau = tau})
553       = addErrCtxt (ptext SLIT("In the type signature for") 
554                       <+> quotes (ppr id))              $
555         addErrCtxtM (sigCtxt id tvs theta tau)          $
556         checkSigTyVarsWrt (idFreeTyVars id) tvs
557 \end{code}
558
559 @getTyVarsToGen@ decides what type variables to generalise over.
560
561 For a "restricted group" -- see the monomorphism restriction
562 for a definition -- we bind no dictionaries, and
563 remove from tyvars_to_gen any constrained type variables
564
565 *Don't* simplify dicts at this point, because we aren't going
566 to generalise over these dicts.  By the time we do simplify them
567 we may well know more.  For example (this actually came up)
568         f :: Array Int Int
569         f x = array ... xs where xs = [1,2,3,4,5]
570 We don't want to generate lots of (fromInt Int 1), (fromInt Int 2)
571 stuff.  If we simplify only at the f-binding (not the xs-binding)
572 we'll know that the literals are all Ints, and we can just produce
573 Int literals!
574
575 Find all the type variables involved in overloading, the
576 "constrained_tyvars".  These are the ones we *aren't* going to
577 generalise.  We must be careful about doing this:
578
579  (a) If we fail to generalise a tyvar which is not actually
580         constrained, then it will never, ever get bound, and lands
581         up printed out in interface files!  Notorious example:
582                 instance Eq a => Eq (Foo a b) where ..
583         Here, b is not constrained, even though it looks as if it is.
584         Another, more common, example is when there's a Method inst in
585         the LIE, whose type might very well involve non-overloaded
586         type variables.
587   [NOTE: Jan 2001: I don't understand the problem here so I'm doing 
588         the simple thing instead]
589
590  (b) On the other hand, we mustn't generalise tyvars which are constrained,
591         because we are going to pass on out the unmodified LIE, with those
592         tyvars in it.  They won't be in scope if we've generalised them.
593
594 So we are careful, and do a complete simplification just to find the
595 constrained tyvars. We don't use any of the results, except to
596 find which tyvars are constrained.
597
598 \begin{code}
599 isUnRestrictedGroup :: [Name]           -- Signatures given for these
600                     -> LHsBinds Name
601                     -> Bool
602 isUnRestrictedGroup sigs binds = all (unrestricted . unLoc) (bagToList binds)
603   where 
604     unrestricted (PatBind other _)      = False
605     unrestricted (VarBind v _)          = v `is_elem` sigs
606     unrestricted (FunBind v _ matches)  = unrestricted_match matches 
607                                            || unLoc v `is_elem` sigs
608
609     unrestricted_match (L _ (Match [] _ _) : _) = False
610         -- No args => like a pattern binding
611     unrestricted_match other              = True
612         -- Some args => a function binding
613
614 is_elem v vs = isIn "isUnResMono" v vs
615 \end{code}
616
617
618 %************************************************************************
619 %*                                                                      *
620 \subsection{tcMonoBind}
621 %*                                                                      *
622 %************************************************************************
623
624 @tcMonoBinds@ deals with a single @MonoBind@.  
625 The signatures have been dealt with already.
626
627 \begin{code}
628 tcMonoBinds :: LHsBinds Name
629             -> [TcSigInfo] -> RecFlag
630             -> TcM (LHsBinds TcId, 
631                     Bag (Name,          -- Bound names
632                          TcId))         -- Corresponding monomorphic bound things
633
634 tcMonoBinds mbinds tc_ty_sigs is_rec
635         -- Three stages: 
636         -- 1. Check the patterns, building up an environment binding
637         --    the variables in this group (in the recursive case)
638         -- 2. Extend the environment
639         -- 3. Check the RHSs
640   = mapBagM tc_lbind_pats mbinds                `thenM` \ bag_of_pairs ->
641     let
642         (complete_it, xve) 
643                 = foldrBag combine 
644                            (returnM (emptyBag, emptyBag), emptyBag)
645                            bag_of_pairs
646         combine (complete_it1, xve1) (complete_it2, xve2)
647            = (complete_it, xve1 `unionBags` xve2)
648            where
649               complete_it = complete_it1        `thenM` \ (b1, bs1) ->
650                             complete_it2        `thenM` \ (b2, bs2) ->
651                             returnM (b1 `consBag` b2, bs1 `unionBags` bs2)
652     in
653     tcExtendLocalValEnv2 (bagToList xve) complete_it
654   where
655     tc_lbind_pats :: LHsBind Name
656                  -> TcM (TcM (LHsBind TcId, Bag (Name,TcId)),   -- Completer
657                          Bag (Name,TcId))
658         -- wrapper for tc_bind_pats to deal with the location stuff
659     tc_lbind_pats (L loc bind)
660         = addSrcSpan loc $ do
661             (tc, bag) <- tc_bind_pats bind
662             return (wrap tc, bag)
663          where
664             wrap tc = addSrcSpan loc $ do
665                         (bind, stuff) <- tc
666                         return (L loc bind, stuff)
667
668
669     tc_bind_pats :: HsBind Name
670                  -> TcM (TcM (HsBind TcId, Bag (Name,TcId)),    -- Completer
671                          Bag (Name,TcId))
672     tc_bind_pats (FunBind (L nm_loc name) inf matches)
673                 -- Three cases:
674                 --      a) Type sig supplied
675                 --      b) No type sig and recursive
676                 --      c) No type sig and non-recursive
677
678       | Just sig <- maybeSig tc_ty_sigs name 
679       = let     -- (a) There is a type signature
680                 -- Use it for the environment extension, and check
681                 -- the RHS has the appropriate type (with outer for-alls stripped off)
682            mono_id = sig_mono_id sig
683            mono_ty = idType mono_id
684            complete_it = tcMatchesFun name matches (Check mono_ty)      `thenM` \ matches' ->
685                          returnM (FunBind (L nm_loc mono_id) inf matches',
686                                   unitBag (name, mono_id))
687         in
688         returnM (complete_it, if isRec is_rec then unitBag (name, sig_poly_id sig) 
689                                               else emptyBag)
690
691       | isRec is_rec
692       =         -- (b) No type signature, and recursive
693                 -- So we must use an ordinary H-M type variable
694                 -- which means the variable gets an inferred tau-type
695         newLocalName name               `thenM` \ mono_name ->
696         newTyVarTy argTypeKind          `thenM` \ mono_ty ->
697         let
698            mono_id     = mkLocalId mono_name mono_ty
699            complete_it = tcMatchesFun name matches (Check mono_ty)      `thenM` \ matches' ->
700                          returnM (FunBind (L nm_loc mono_id) inf matches', 
701                                   unitBag (name, mono_id))
702         in
703         returnM (complete_it, unitBag (name, mono_id))
704
705       | otherwise       -- (c) No type signature, and non-recursive
706       = let             -- So we can use a 'hole' type to infer a higher-rank type
707            complete_it 
708                 = newHole                                       `thenM` \ hole -> 
709                   tcMatchesFun name matches (Infer hole)        `thenM` \ matches' ->
710                   readMutVar hole                               `thenM` \ fun_ty ->
711                   newLocalName name                             `thenM` \ mono_name ->
712                   let
713                      mono_id = mkLocalId mono_name fun_ty
714                   in
715                   returnM (FunBind (L nm_loc mono_id) inf matches', 
716                            unitBag (name, mono_id))
717         in
718         returnM (complete_it, emptyBag)
719         
720     tc_bind_pats bind@(PatBind pat grhss)
721       =         --      Now typecheck the pattern
722                 -- We do now support binding fresh (not-already-in-scope) scoped 
723                 -- type variables in the pattern of a pattern binding.  
724                 -- For example, this is now legal:
725                 --      (x::a, y::b) = e
726                 -- The type variables are brought into scope in tc_binds_and_then,
727                 -- so we don't have to do anything here.
728         newHole                                 `thenM` \ hole -> 
729         tcPat tc_pat_bndr pat (Infer hole)      `thenM` \ (pat', tvs, ids, lie_avail) ->
730         readMutVar hole                         `thenM` \ pat_ty ->
731
732         -- Don't know how to deal with pattern-bound existentials yet
733         checkTc (isEmptyBag tvs && null lie_avail) 
734                 (existentialExplode bind)       `thenM_` 
735
736         let
737            complete_it = addErrCtxt (patMonoBindsCtxt bind)             $
738                          tcGRHSsPat grhss (Check pat_ty)        `thenM` \ grhss' ->
739                          returnM (PatBind pat' grhss', ids)
740         in
741         returnM (complete_it, if isRec is_rec then ids else emptyBag)
742
743         -- tc_pat_bndr is used when dealing with a LHS binder in a pattern.
744         -- If there was a type sig for that Id, we want to make it much
745         -- as if that type signature had been on the binder as a SigPatIn.
746         -- We check for a type signature; if there is one, we use the mono_id
747         -- from the signature.  This is how we make sure the tau part of the
748         -- signature actually matches the type of the LHS; then tc_bind_pats
749         -- ensures the LHS and RHS have the same type
750         
751     tc_pat_bndr name pat_ty
752         = case maybeSig tc_ty_sigs name of
753             Nothing  -> newLocalName name                       `thenM` \ bndr_name ->
754                         tcMonoPatBndr bndr_name pat_ty
755
756             Just sig -> addSrcSpan (srcLocSpan (getSrcLoc name))        $
757                                 -- TODO: location wrong
758                         tcSubPat (idType mono_id) pat_ty        `thenM` \ co_fn ->
759                         returnM (co_fn, mono_id)
760                      where
761                         mono_id = sig_mono_id sig
762 \end{code}
763
764
765 %************************************************************************
766 %*                                                                      *
767 \subsection{SPECIALIZE pragmas}
768 %*                                                                      *
769 %************************************************************************
770
771 @tcSpecSigs@ munches up the specialisation "signatures" that arise through *user*
772 pragmas.  It is convenient for them to appear in the @[RenamedSig]@
773 part of a binding because then the same machinery can be used for
774 moving them into place as is done for type signatures.
775
776 They look like this:
777
778 \begin{verbatim}
779         f :: Ord a => [a] -> b -> b
780         {-# SPECIALIZE f :: [Int] -> b -> b #-}
781 \end{verbatim}
782
783 For this we generate:
784 \begin{verbatim}
785         f* = /\ b -> let d1 = ...
786                      in f Int b d1
787 \end{verbatim}
788
789 where f* is a SpecPragmaId.  The **sole** purpose of SpecPragmaIds is to
790 retain a right-hand-side that the simplifier will otherwise discard as
791 dead code... the simplifier has a flag that tells it not to discard
792 SpecPragmaId bindings.
793
794 In this case the f* retains a call-instance of the overloaded
795 function, f, (including appropriate dictionaries) so that the
796 specialiser will subsequently discover that there's a call of @f@ at
797 Int, and will create a specialisation for @f@.  After that, the
798 binding for @f*@ can be discarded.
799
800 We used to have a form
801         {-# SPECIALISE f :: <type> = g #-}
802 which promised that g implemented f at <type>, but we do that with 
803 a RULE now:
804         {-# SPECIALISE (f::<type) = g #-}
805
806 \begin{code}
807 tcSpecSigs :: [LSig Name] -> TcM (LHsBinds TcId)
808 tcSpecSigs (L loc (SpecSig (L nm_loc name) poly_ty) : sigs)
809   =     -- SPECIALISE f :: forall b. theta => tau  =  g
810     addSrcSpan loc                              $
811     addErrCtxt (valSpecSigCtxt name poly_ty)    $
812
813         -- Get and instantiate its alleged specialised type
814     tcHsSigType (FunSigCtxt name) poly_ty       `thenM` \ sig_ty ->
815
816         -- Check that f has a more general type, and build a RHS for
817         -- the spec-pragma-id at the same time
818     getLIE (tcCheckSigma (L nm_loc (HsVar name)) sig_ty)        `thenM` \ (spec_expr, spec_lie) ->
819
820         -- Squeeze out any Methods (see comments with tcSimplifyToDicts)
821     tcSimplifyToDicts spec_lie                  `thenM` \ spec_binds ->
822
823         -- Just specialise "f" by building a SpecPragmaId binding
824         -- It is the thing that makes sure we don't prematurely 
825         -- dead-code-eliminate the binding we are really interested in.
826     newLocalName name                   `thenM` \ spec_name ->
827     let
828         spec_bind = VarBind (mkSpecPragmaId spec_name sig_ty)
829                                 (mkHsLet spec_binds spec_expr)
830     in
831
832         -- Do the rest and combine
833     tcSpecSigs sigs                     `thenM` \ binds_rest ->
834     returnM (binds_rest `snocBag` L loc spec_bind)
835
836 tcSpecSigs (other_sig : sigs) = tcSpecSigs sigs
837 tcSpecSigs []                 = returnM emptyBag
838 \end{code}
839
840 %************************************************************************
841 %*                                                                      *
842 \subsection[TcBinds-errors]{Error contexts and messages}
843 %*                                                                      *
844 %************************************************************************
845
846
847 \begin{code}
848 patMonoBindsCtxt bind
849   = hang (ptext SLIT("In a pattern binding:")) 4 (ppr bind)
850
851 -----------------------------------------------
852 valSpecSigCtxt v ty
853   = sep [ptext SLIT("In a SPECIALIZE pragma for a value:"),
854          nest 4 (ppr v <+> dcolon <+> ppr ty)]
855
856 -----------------------------------------------
857 sigContextsErr = ptext SLIT("Mismatched contexts")
858
859 sigContextsCtxt s1 s2
860   = vcat [ptext SLIT("When matching the contexts of the signatures for"), 
861           nest 2 (vcat [ppr s1 <+> dcolon <+> ppr (idType s1),
862                         ppr s2 <+> dcolon <+> ppr (idType s2)]),
863           ptext SLIT("The signature contexts in a mutually recursive group should all be identical")]
864
865 -----------------------------------------------
866 unliftedBindErr flavour mbind
867   = hang (text flavour <+> ptext SLIT("bindings for unlifted types aren't allowed:"))
868          4 (ppr mbind)
869
870 -----------------------------------------------
871 existentialExplode mbinds
872   = hang (vcat [text "My brain just exploded.",
873                 text "I can't handle pattern bindings for existentially-quantified constructors.",
874                 text "In the binding group"])
875         4 (ppr mbinds)
876
877 -----------------------------------------------
878 restrictedBindCtxtErr binder_names
879   = hang (ptext SLIT("Illegal overloaded type signature(s)"))
880        4 (vcat [ptext SLIT("in a binding group for") <+> pprBinders binder_names,
881                 ptext SLIT("that falls under the monomorphism restriction")])
882
883 genCtxt binder_names
884   = ptext SLIT("When generalising the type(s) for") <+> pprBinders binder_names
885
886 -- Used in error messages
887 -- Use quotes for a single one; they look a bit "busy" for several
888 pprBinders [bndr] = quotes (ppr bndr)
889 pprBinders bndrs  = pprWithCommas ppr bndrs
890 \end{code}