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