[project @ 2005-08-11 08:22:11 by simonpj]
[ghc-hetmet.git] / ghc / compiler / rename / RnBinds.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[RnBinds]{Renaming and dependency analysis of bindings}
5
6 This module does renaming and dependency analysis on value bindings in
7 the abstract syntax.  It does {\em not} do cycle-checks on class or
8 type-synonym declarations; those cannot be done at this stage because
9 they may be affected by renaming (which isn't fully worked out yet).
10
11 \begin{code}
12 module RnBinds (
13         rnTopBinds, 
14         rnLocalBindsAndThen, rnValBindsAndThen, rnValBinds, trimWith,
15         rnMethodBinds, renameSigs, 
16         rnMatchGroup, rnGRHSs
17    ) where
18
19 #include "HsVersions.h"
20
21 import {-# SOURCE #-} RnExpr( rnLExpr, rnStmts )
22
23 import HsSyn
24 import RdrHsSyn
25 import RnHsSyn
26 import TcRnMonad
27 import RnTypes          ( rnHsSigType, rnLHsType, rnHsTypeFVs, 
28                           rnLPat, rnPatsAndThen, patSigErr, checkPrecMatch )
29 import RnEnv            ( bindLocatedLocalsRn, lookupLocatedBndrRn, 
30                           lookupLocatedInstDeclBndr, newIPNameRn,
31                           lookupLocatedSigOccRn, bindPatSigTyVars, bindPatSigTyVarsFV,
32                           bindLocalFixities, bindSigTyVarsFV, 
33                           warnUnusedLocalBinds, mapFvRn, extendTyVarEnvFVRn,
34                         )
35 import DynFlags ( DynFlag(..) )
36 import Name             ( Name, nameOccName, nameSrcLoc )
37 import NameEnv
38 import NameSet
39 import PrelNames        ( isUnboundName )
40 import RdrName          ( RdrName, rdrNameOcc )
41 import SrcLoc           ( mkSrcSpan, Located(..), unLoc )
42 import ListSetOps       ( findDupsEq )
43 import BasicTypes       ( RecFlag(..) )
44 import Digraph          ( SCC(..), stronglyConnComp )
45 import Bag
46 import Outputable
47 import Maybes           ( orElse, fromJust, isJust )
48 import Monad            ( foldM )
49 \end{code}
50
51 -- ToDo: Put the annotations into the monad, so that they arrive in the proper
52 -- place and can be used when complaining.
53
54 The code tree received by the function @rnBinds@ contains definitions
55 in where-clauses which are all apparently mutually recursive, but which may
56 not really depend upon each other. For example, in the top level program
57 \begin{verbatim}
58 f x = y where a = x
59               y = x
60 \end{verbatim}
61 the definitions of @a@ and @y@ do not depend on each other at all.
62 Unfortunately, the typechecker cannot always check such definitions.
63 \footnote{Mycroft, A. 1984. Polymorphic type schemes and recursive
64 definitions. In Proceedings of the International Symposium on Programming,
65 Toulouse, pp. 217-39. LNCS 167. Springer Verlag.}
66 However, the typechecker usually can check definitions in which only the
67 strongly connected components have been collected into recursive bindings.
68 This is precisely what the function @rnBinds@ does.
69
70 ToDo: deal with case where a single monobinds binds the same variable
71 twice.
72
73 The vertag tag is a unique @Int@; the tags only need to be unique
74 within one @MonoBinds@, so that unique-Int plumbing is done explicitly
75 (heavy monad machinery not needed).
76
77
78 %************************************************************************
79 %*                                                                      *
80 %* naming conventions                                                   *
81 %*                                                                      *
82 %************************************************************************
83
84 \subsection[name-conventions]{Name conventions}
85
86 The basic algorithm involves walking over the tree and returning a tuple
87 containing the new tree plus its free variables. Some functions, such
88 as those walking polymorphic bindings (HsBinds) and qualifier lists in
89 list comprehensions (@Quals@), return the variables bound in local
90 environments. These are then used to calculate the free variables of the
91 expression evaluated in these environments.
92
93 Conventions for variable names are as follows:
94 \begin{itemize}
95 \item
96 new code is given a prime to distinguish it from the old.
97
98 \item
99 a set of variables defined in @Exp@ is written @dvExp@
100
101 \item
102 a set of variables free in @Exp@ is written @fvExp@
103 \end{itemize}
104
105 %************************************************************************
106 %*                                                                      *
107 %* analysing polymorphic bindings (HsBindGroup, HsBind)
108 %*                                                                      *
109 %************************************************************************
110
111 \subsubsection[dep-HsBinds]{Polymorphic bindings}
112
113 Non-recursive expressions are reconstructed without any changes at top
114 level, although their component expressions may have to be altered.
115 However, non-recursive expressions are currently not expected as
116 \Haskell{} programs, and this code should not be executed.
117
118 Monomorphic bindings contain information that is returned in a tuple
119 (a @FlatMonoBinds@) containing:
120
121 \begin{enumerate}
122 \item
123 a unique @Int@ that serves as the ``vertex tag'' for this binding.
124
125 \item
126 the name of a function or the names in a pattern. These are a set
127 referred to as @dvLhs@, the defined variables of the left hand side.
128
129 \item
130 the free variables of the body. These are referred to as @fvBody@.
131
132 \item
133 the definition's actual code. This is referred to as just @code@.
134 \end{enumerate}
135
136 The function @nonRecDvFv@ returns two sets of variables. The first is
137 the set of variables defined in the set of monomorphic bindings, while the
138 second is the set of free variables in those bindings.
139
140 The set of variables defined in a non-recursive binding is just the
141 union of all of them, as @union@ removes duplicates. However, the
142 free variables in each successive set of cumulative bindings is the
143 union of those in the previous set plus those of the newest binding after
144 the defined variables of the previous set have been removed.
145
146 @rnMethodBinds@ deals only with the declarations in class and
147 instance declarations.  It expects only to see @FunMonoBind@s, and
148 it expects the global environment to contain bindings for the binders
149 (which are all class operations).
150
151 %************************************************************************
152 %*                                                                      *
153 \subsubsection{ Top-level bindings}
154 %*                                                                      *
155 %************************************************************************
156
157 @rnTopMonoBinds@ assumes that the environment already
158 contains bindings for the binders of this particular binding.
159
160 \begin{code}
161 rnTopBinds :: HsValBinds RdrName -> RnM (HsValBinds Name, DefUses)
162
163 -- The binders of the binding are in scope already;
164 -- the top level scope resolution does that
165
166 rnTopBinds binds
167  =  do  { is_boot <- tcIsHsBoot
168         ; if is_boot then rnTopBindsBoot binds
169                      else rnTopBindsSrc  binds }
170
171 rnTopBindsBoot :: HsValBinds RdrName -> RnM (HsValBinds Name, DefUses)
172 -- A hs-boot file has no bindings. 
173 -- Return a single HsBindGroup with empty binds and renamed signatures
174 rnTopBindsBoot (ValBindsIn mbinds sigs)
175   = do  { checkErr (isEmptyLHsBinds mbinds) (bindsInHsBootFile mbinds)
176         ; sigs' <- renameSigs okHsBootSig sigs
177         ; return (ValBindsIn emptyLHsBinds sigs', usesOnly (hsSigsFVs sigs')) }
178
179 rnTopBindsSrc :: HsValBinds RdrName -> RnM (HsValBinds Name, DefUses)
180 rnTopBindsSrc binds@(ValBindsIn mbinds _)
181   = bindPatSigTyVars (collectSigTysFromHsBinds mbinds) $ \ _ -> 
182         -- Hmm; by analogy with Ids, this doesn't look right
183         -- Top-level bound type vars should really scope over 
184         -- everything, but we only scope them over the other bindings
185
186     do  { (binds', dus) <- rnValBinds noTrim binds
187
188                 -- Warn about missing signatures, 
189         ; let   { ValBindsOut _ sigs' = binds'
190                 ; ty_sig_vars = mkNameSet [ unLoc n | L _ (Sig n _) <- sigs']
191                 ; un_sigd_bndrs = duDefs dus `minusNameSet` ty_sig_vars }
192
193         ; warn_missing_sigs <- doptM Opt_WarnMissingSigs
194         ; ifM (warn_missing_sigs)
195               (mappM_ missingSigWarn (nameSetToList un_sigd_bndrs))
196
197         ; return (binds', dus)
198         }
199 \end{code}
200
201
202
203 %*********************************************************
204 %*                                                      *
205                 HsLocalBinds
206 %*                                                      *
207 %*********************************************************
208
209 \begin{code}
210 rnLocalBindsAndThen 
211   :: HsLocalBinds RdrName
212   -> (HsLocalBinds Name -> RnM (result, FreeVars))
213   -> RnM (result, FreeVars)
214 -- This version (a) assumes that the binding vars are not already in scope
215 --              (b) removes the binders from the free vars of the thing inside
216 -- The parser doesn't produce ThenBinds
217 rnLocalBindsAndThen EmptyLocalBinds thing_inside
218   = thing_inside EmptyLocalBinds
219
220 rnLocalBindsAndThen (HsValBinds val_binds) thing_inside
221   = rnValBindsAndThen val_binds $ \ val_binds' -> 
222     thing_inside (HsValBinds val_binds')
223
224 rnLocalBindsAndThen (HsIPBinds binds) thing_inside
225   = rnIPBinds binds                     `thenM` \ (binds',fv_binds) ->
226     thing_inside (HsIPBinds binds')     `thenM` \ (thing, fvs_thing) ->
227     returnM (thing, fvs_thing `plusFV` fv_binds)
228
229 -------------
230 rnIPBinds (IPBinds ip_binds _no_dict_binds)
231   = do  { (ip_binds', fvs_s) <- mapAndUnzipM (wrapLocFstM rnIPBind) ip_binds
232         ; return (IPBinds ip_binds' emptyLHsBinds, plusFVs fvs_s) }
233
234 rnIPBind (IPBind n expr)
235   = newIPNameRn  n              `thenM` \ name ->
236     rnLExpr expr                `thenM` \ (expr',fvExpr) ->
237     return (IPBind name expr', fvExpr)
238 \end{code}
239
240
241 %************************************************************************
242 %*                                                                      *
243                 ValBinds
244 %*                                                                      *
245 %************************************************************************
246
247 \begin{code}
248 rnValBindsAndThen :: HsValBinds RdrName
249                   -> (HsValBinds Name -> RnM (result, FreeVars))
250                   -> RnM (result, FreeVars)
251
252 rnValBindsAndThen binds@(ValBindsIn mbinds sigs) thing_inside
253   =     -- Extract all the binders in this group, and extend the
254         -- current scope, inventing new names for the new binders
255         -- This also checks that the names form a set
256     bindLocatedLocalsRn doc mbinders_w_srclocs                  $ \ bndrs ->
257     bindPatSigTyVarsFV (collectSigTysFromHsBinds mbinds)        $ 
258
259         -- Then install local fixity declarations
260         -- Notice that they scope over thing_inside too
261     bindLocalFixities [sig | L _ (FixSig sig) <- sigs ]         $
262
263         -- Do the business
264     rnValBinds (trimWith bndrs) binds   `thenM` \ (binds, bind_dus) ->
265
266         -- Now do the "thing inside"
267     thing_inside binds                  `thenM` \ (result,result_fvs) ->
268
269         -- Final error checking
270     let
271         all_uses = duUses bind_dus `plusFV` result_fvs
272         -- duUses: It's important to return all the uses, not the 'real uses' 
273         -- used for warning about unused bindings.  Otherwise consider:
274         --      x = 3
275         --      y = let p = x in 'x'    -- NB: p not used
276         -- If we don't "see" the dependency of 'y' on 'x', we may put the
277         -- bindings in the wrong order, and the type checker will complain
278         -- that x isn't in scope
279
280         unused_bndrs = [ b | b <- bndrs, not (b `elemNameSet` all_uses)]
281     in
282     warnUnusedLocalBinds unused_bndrs   `thenM_`
283
284     returnM (result, delListFromNameSet all_uses bndrs)
285   where
286     mbinders_w_srclocs = collectHsBindLocatedBinders mbinds
287     doc = text "In the binding group for:"
288           <+> pprWithCommas ppr (map unLoc mbinders_w_srclocs)
289
290 ---------------------
291 rnValBinds :: (FreeVars -> FreeVars)
292            -> HsValBinds RdrName
293            -> RnM (HsValBinds Name, DefUses)
294 -- Assumes the binders of the binding are in scope already
295
296 rnValBinds trim (ValBindsIn mbinds sigs)
297   = do  { sigs' <- rename_sigs sigs
298
299         ; binds_w_dus <- mapBagM (rnBind (mkSigTvFn sigs') trim) mbinds
300
301         ; let (binds', bind_dus) = depAnalBinds binds_w_dus
302
303         -- We do the check-sigs after renaming the bindings,
304         -- so that we have convenient access to the binders
305         ; check_sigs (okBindSig (duDefs bind_dus)) sigs'
306
307         ; return (ValBindsOut binds' sigs', 
308                   usesOnly (hsSigsFVs sigs') `plusDU` bind_dus) }
309
310
311 ---------------------
312 depAnalBinds :: Bag (LHsBind Name, [Name], Uses)
313              -> ([(RecFlag, LHsBinds Name)], DefUses)
314 -- Dependency analysis; this is important so that 
315 -- unused-binding reporting is accurate
316 depAnalBinds binds_w_dus
317   = (map get_binds sccs, map get_du sccs)
318   where
319     sccs = stronglyConnComp edges
320
321     keyd_nodes = bagToList binds_w_dus `zip` [0::Int ..]
322
323     edges = [ (node, key, [fromJust mb_key | n <- nameSetToList uses,
324                            let mb_key = lookupNameEnv key_map n,
325                            isJust mb_key ])
326             | (node@(_,_,uses), key) <- keyd_nodes ]
327
328     key_map :: NameEnv Int      -- Which binding it comes from
329     key_map = mkNameEnv [(bndr, key) | ((_, bndrs, _), key) <- keyd_nodes
330                                      , bndr <- bndrs ]
331
332     get_binds (AcyclicSCC (bind, _, _)) = (NonRecursive, unitBag bind)
333     get_binds (CyclicSCC  binds_w_dus)  = (Recursive, listToBag [b | (b,d,u) <- binds_w_dus])
334
335     get_du (AcyclicSCC (_, bndrs, uses)) = (Just (mkNameSet bndrs), uses)
336     get_du (CyclicSCC  binds_w_dus)      = (Just defs, uses)
337         where
338           defs = mkNameSet [b | (_,bs,_) <- binds_w_dus, b <- bs]
339           uses = unionManyNameSets [u | (_,_,u) <- binds_w_dus]
340
341
342 ---------------------
343 -- Bind the top-level forall'd type variables in the sigs.
344 -- E.g  f :: a -> a
345 --      f = rhs
346 --      The 'a' scopes over the rhs
347 --
348 -- NB: there'll usually be just one (for a function binding)
349 --     but if there are many, one may shadow the rest; too bad!
350 --      e.g  x :: [a] -> [a]
351 --           y :: [(a,a)] -> a
352 --           (x,y) = e
353 --      In e, 'a' will be in scope, and it'll be the one from 'y'!
354
355 mkSigTvFn :: [LSig Name] -> (Name -> [Name])
356 -- Return a lookup function that maps an Id Name to the names
357 -- of the type variables that should scope over its body..
358 mkSigTvFn sigs
359   = \n -> lookupNameEnv env n `orElse` []
360   where
361     env :: NameEnv [Name]
362     env = mkNameEnv [ (name, map hsLTyVarName ltvs)
363                     | L _ (Sig (L _ name) 
364                                (L _ (HsForAllTy Explicit ltvs _ _))) <- sigs]
365         -- Note the pattern-match on "Explicit"; we only bind
366         -- type variables from signatures with an explicit top-level for-all
367                                 
368 -- The trimming function trims the free vars we attach to a
369 -- binding so that it stays reasonably small
370 noTrim :: FreeVars -> FreeVars
371 noTrim fvs = fvs        -- Used at top level
372
373 trimWith :: [Name] -> FreeVars -> FreeVars
374 -- Nested bindings; trim by intersection with the names bound here
375 trimWith bndrs = intersectNameSet (mkNameSet bndrs)
376
377 ---------------------
378 rnBind :: (Name -> [Name])              -- Signature tyvar function
379        -> (FreeVars -> FreeVars)        -- Trimming function for rhs free vars
380        -> LHsBind RdrName
381        -> RnM (LHsBind Name, [Name], Uses)
382 rnBind sig_fn trim (L loc (PatBind pat grhss ty _))
383   = setSrcSpan loc $ 
384     do  { (pat', pat_fvs) <- rnLPat pat
385
386         ; let bndrs = collectPatBinders pat'
387
388         ; (grhss', fvs) <- bindSigTyVarsFV (concatMap sig_fn bndrs) $
389                            rnGRHSs PatBindRhs grhss
390
391         ; return (L loc (PatBind pat' grhss' ty (trim fvs)), bndrs, pat_fvs `plusFV` fvs) }
392
393 rnBind sig_fn trim (L loc (FunBind name inf matches _))
394   = setSrcSpan loc $ 
395     do  { new_name <- lookupLocatedBndrRn name
396         ; let plain_name = unLoc new_name
397
398         ; (matches', fvs) <- bindSigTyVarsFV (sig_fn plain_name) $
399                              rnMatchGroup (FunRhs plain_name) matches
400
401         ; checkPrecMatch inf plain_name matches'
402
403         ; return (L loc (FunBind new_name inf matches' (trim fvs)), [plain_name], fvs)
404       }
405 \end{code}
406
407
408 @rnMethodBinds@ is used for the method bindings of a class and an instance
409 declaration.   Like @rnBinds@ but without dependency analysis.
410
411 NOTA BENE: we record each {\em binder} of a method-bind group as a free variable.
412 That's crucial when dealing with an instance decl:
413 \begin{verbatim}
414         instance Foo (T a) where
415            op x = ...
416 \end{verbatim}
417 This might be the {\em sole} occurrence of @op@ for an imported class @Foo@,
418 and unless @op@ occurs we won't treat the type signature of @op@ in the class
419 decl for @Foo@ as a source of instance-decl gates.  But we should!  Indeed,
420 in many ways the @op@ in an instance decl is just like an occurrence, not
421 a binder.
422
423 \begin{code}
424 rnMethodBinds :: Name                   -- Class name
425               -> [Name]                 -- Names for generic type variables
426               -> LHsBinds RdrName
427               -> RnM (LHsBinds Name, FreeVars)
428
429 rnMethodBinds cls gen_tyvars binds
430   = foldM do_one (emptyBag,emptyFVs) (bagToList binds)
431   where do_one (binds,fvs) bind = do
432            (bind', fvs_bind) <- rnMethodBind cls gen_tyvars bind
433            return (bind' `unionBags` binds, fvs_bind `plusFV` fvs)
434
435 rnMethodBind cls gen_tyvars (L loc (FunBind name inf (MatchGroup matches _) _))
436   =  setSrcSpan loc $ 
437      lookupLocatedInstDeclBndr cls name                 `thenM` \ sel_name -> 
438      let plain_name = unLoc sel_name in
439         -- We use the selector name as the binder
440
441     mapFvRn (rn_match plain_name) matches               `thenM` \ (new_matches, fvs) ->
442     let 
443         new_group = MatchGroup new_matches placeHolderType
444     in
445     checkPrecMatch inf plain_name new_group             `thenM_`
446     returnM (unitBag (L loc (FunBind sel_name inf new_group fvs)), fvs `addOneFV` plain_name)
447         -- The 'fvs' field isn't used for method binds
448   where
449         -- Truly gruesome; bring into scope the correct members of the generic 
450         -- type variables.  See comments in RnSource.rnSourceDecl(ClassDecl)
451     rn_match sel_name match@(L _ (Match (L _ (TypePat ty) : _) _ _))
452         = extendTyVarEnvFVRn gen_tvs    $
453           rnMatch (FunRhs sel_name) match
454         where
455           tvs     = map (rdrNameOcc.unLoc) (extractHsTyRdrTyVars ty)
456           gen_tvs = [tv | tv <- gen_tyvars, nameOccName tv `elem` tvs] 
457
458     rn_match sel_name match = rnMatch (FunRhs sel_name) match
459
460
461 -- Can't handle method pattern-bindings which bind multiple methods.
462 rnMethodBind cls gen_tyvars mbind@(L loc (PatBind other_pat _ _ _))
463   = addLocErr mbind methodBindErr       `thenM_`
464     returnM (emptyBag, emptyFVs) 
465 \end{code}
466
467
468 %************************************************************************
469 %*                                                                      *
470 \subsubsection[dep-Sigs]{Signatures (and user-pragmas for values)}
471 %*                                                                      *
472 %************************************************************************
473
474 @renameSigs@ checks for:
475 \begin{enumerate}
476 \item more than one sig for one thing;
477 \item signatures given for things not bound here;
478 \item with suitably flaggery, that all top-level things have type signatures.
479 \end{enumerate}
480 %
481 At the moment we don't gather free-var info from the types in
482 signatures.  We'd only need this if we wanted to report unused tyvars.
483
484 \begin{code}
485 renameSigs :: (LSig Name -> Bool) -> [LSig RdrName] -> RnM [LSig Name]
486 -- Renames the signatures and performs error checks
487 renameSigs ok_sig sigs 
488   = do  { sigs' <- rename_sigs sigs
489         ; check_sigs ok_sig sigs'
490         ; return sigs' }
491
492 ----------------------
493 rename_sigs :: [LSig RdrName] -> RnM [LSig Name]
494 rename_sigs sigs = mappM (wrapLocM renameSig)
495                          (filter (not . isFixityLSig) sigs)
496                 -- Remove fixity sigs which have been dealt with already
497
498 ----------------------
499 check_sigs :: (LSig Name -> Bool) -> [LSig Name] -> RnM ()
500 -- Used for class and instance decls, as well as regular bindings
501 check_sigs ok_sig sigs 
502         -- Check for (a) duplicate signatures
503         --           (b) signatures for things not in this group
504   = do  { mappM_ unknownSigErr (filter bad sigs)
505         ; mappM_ dupSigDeclErr (findDupsEq eqHsSig sigs) }
506   where
507         -- Don't complain about an unbound name again
508     bad sig = not (ok_sig sig) && 
509               case sigName sig of
510                 Just n | isUnboundName n -> False
511                 other                    -> True
512
513 -- We use lookupLocatedSigOccRn in the signatures, which is a little bit unsatisfactory
514 -- because this won't work for:
515 --      instance Foo T where
516 --        {-# INLINE op #-}
517 --        Baz.op = ...
518 -- We'll just rename the INLINE prag to refer to whatever other 'op'
519 -- is in scope.  (I'm assuming that Baz.op isn't in scope unqualified.)
520 -- Doesn't seem worth much trouble to sort this.
521
522 renameSig :: Sig RdrName -> RnM (Sig Name)
523 -- FixitSig is renamed elsewhere.
524 renameSig (Sig v ty)
525   = lookupLocatedSigOccRn v                     `thenM` \ new_v ->
526     rnHsSigType (quotes (ppr v)) ty             `thenM` \ new_ty ->
527     returnM (Sig new_v new_ty)
528
529 renameSig (SpecInstSig ty)
530   = rnLHsType (text "A SPECIALISE instance pragma") ty `thenM` \ new_ty ->
531     returnM (SpecInstSig new_ty)
532
533 renameSig (SpecSig v ty)
534   = lookupLocatedSigOccRn v             `thenM` \ new_v ->
535     rnHsSigType (quotes (ppr v)) ty     `thenM` \ new_ty ->
536     returnM (SpecSig new_v new_ty)
537
538 renameSig (InlineSig b v p)
539   = lookupLocatedSigOccRn v             `thenM` \ new_v ->
540     returnM (InlineSig b new_v p)
541 \end{code}
542
543
544 ************************************************************************
545 *                                                                       *
546 \subsection{Match}
547 *                                                                       *
548 ************************************************************************
549
550 \begin{code}
551 rnMatchGroup :: HsMatchContext Name -> MatchGroup RdrName -> RnM (MatchGroup Name, FreeVars)
552 rnMatchGroup ctxt (MatchGroup ms _)
553   = mapFvRn (rnMatch ctxt) ms   `thenM` \ (new_ms, ms_fvs) ->
554     returnM (MatchGroup new_ms placeHolderType, ms_fvs)
555
556 rnMatch :: HsMatchContext Name -> LMatch RdrName -> RnM (LMatch Name, FreeVars)
557 rnMatch ctxt  = wrapLocFstM (rnMatch' ctxt)
558
559 rnMatch' ctxt match@(Match pats maybe_rhs_sig grhss)
560   = 
561         -- Deal with the rhs type signature
562     bindPatSigTyVarsFV rhs_sig_tys      $ 
563     doptM Opt_GlasgowExts               `thenM` \ opt_GlasgowExts ->
564     (case maybe_rhs_sig of
565         Nothing -> returnM (Nothing, emptyFVs)
566         Just ty | opt_GlasgowExts -> rnHsTypeFVs doc_sig ty     `thenM` \ (ty', ty_fvs) ->
567                                      returnM (Just ty', ty_fvs)
568                 | otherwise       -> addLocErr ty patSigErr     `thenM_`
569                                      returnM (Nothing, emptyFVs)
570     )                                   `thenM` \ (maybe_rhs_sig', ty_fvs) ->
571
572         -- Now the main event
573     rnPatsAndThen ctxt pats     $ \ pats' ->
574     rnGRHSs ctxt grhss          `thenM` \ (grhss', grhss_fvs) ->
575
576     returnM (Match pats' maybe_rhs_sig' grhss', grhss_fvs `plusFV` ty_fvs)
577         -- The bindPatSigTyVarsFV and rnPatsAndThen will remove the bound FVs
578   where
579      rhs_sig_tys =  case maybe_rhs_sig of
580                         Nothing -> []
581                         Just ty -> [ty]
582      doc_sig = text "In a result type-signature"
583 \end{code}
584
585
586 %************************************************************************
587 %*                                                                      *
588 \subsubsection{Guarded right-hand sides (GRHSs)}
589 %*                                                                      *
590 %************************************************************************
591
592 \begin{code}
593 rnGRHSs :: HsMatchContext Name -> GRHSs RdrName -> RnM (GRHSs Name, FreeVars)
594
595 rnGRHSs ctxt (GRHSs grhss binds)
596   = rnLocalBindsAndThen binds   $ \ binds' ->
597     mapFvRn (rnGRHS ctxt) grhss `thenM` \ (grhss', fvGRHSs) ->
598     returnM (GRHSs grhss' binds', fvGRHSs)
599
600 rnGRHS :: HsMatchContext Name -> LGRHS RdrName -> RnM (LGRHS Name, FreeVars)
601 rnGRHS ctxt = wrapLocFstM (rnGRHS' ctxt)
602
603 rnGRHS' ctxt (GRHS guards rhs)
604   = do  { opt_GlasgowExts <- doptM Opt_GlasgowExts
605         ; checkM (opt_GlasgowExts || is_standard_guard guards)
606                  (addWarn (nonStdGuardErr guards))
607
608         ; ((guards', rhs'), fvs) <- rnStmts (PatGuard ctxt) guards $
609                                     rnLExpr rhs
610         ; return (GRHS guards' rhs', fvs) }
611   where
612         -- Standard Haskell 1.4 guards are just a single boolean
613         -- expression, rather than a list of qualifiers as in the
614         -- Glasgow extension
615     is_standard_guard []                     = True
616     is_standard_guard [L _ (ExprStmt _ _ _)] = True
617     is_standard_guard other                  = False
618 \end{code}
619
620 %************************************************************************
621 %*                                                                      *
622 \subsection{Error messages}
623 %*                                                                      *
624 %************************************************************************
625
626 \begin{code}
627 dupSigDeclErr sigs@(L loc sig : _)
628   = addErrAt loc $
629         vcat [ptext SLIT("Duplicate") <+> what_it_is <> colon,
630               nest 2 (vcat (map ppr_sig sigs))]
631   where
632     what_it_is = hsSigDoc sig
633     ppr_sig (L loc sig) = ppr loc <> colon <+> ppr sig
634
635 unknownSigErr (L loc sig)
636   = addErrAt loc $
637         sep [ptext SLIT("Misplaced") <+> what_it_is <> colon, ppr sig]
638   where
639     what_it_is = hsSigDoc sig
640
641 missingSigWarn var
642   = addWarnAt (mkSrcSpan loc loc) $
643       sep [ptext SLIT("Definition but no type signature for"), quotes (ppr var)]
644   where 
645     loc = nameSrcLoc var  -- TODO: make a proper span
646
647 methodBindErr mbind
648  =  hang (ptext SLIT("Pattern bindings (except simple variables) not allowed in instance declarations"))
649        2 (ppr mbind)
650
651 bindsInHsBootFile mbinds
652   = hang (ptext SLIT("Bindings in hs-boot files are not allowed"))
653        2 (ppr mbinds)
654
655 nonStdGuardErr guard
656   = hang (ptext
657     SLIT("accepting non-standard pattern guards (-fglasgow-exts to suppress this message)")
658     ) 4 (ppr guard)
659 \end{code}