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