9ec71df7e1857100c1ff96b73b756c2199962cd5
[ghc.git] / compiler / rename / RnBinds.hs
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
12 {-# LANGUAGE CPP #-}
13
14 module RnBinds (
15 -- Renaming top-level bindings
16 rnTopBindsLHS, rnTopBindsRHS, rnValBindsRHS,
17
18 -- Renaming local bindings
19 rnLocalBindsAndThen, rnLocalValBindsLHS, rnLocalValBindsRHS,
20
21 -- Other bindings
22 rnMethodBinds, renameSigs, mkSigTvFn,
23 rnMatchGroup, rnGRHSs, rnGRHS,
24 makeMiniFixityEnv, MiniFixityEnv,
25 HsSigCtxt(..)
26 ) where
27
28 import {-# SOURCE #-} RnExpr( rnLExpr, rnStmts )
29
30 import HsSyn
31 import TcRnMonad
32 import TcEvidence ( emptyTcEvBinds )
33 import RnTypes
34 import RnPat
35 import RnNames
36 import RnEnv
37 import DynFlags
38 import Module
39 import Name
40 import NameEnv
41 import NameSet
42 import RdrName ( RdrName, rdrNameOcc )
43 import SrcLoc
44 import ListSetOps ( findDupsEq )
45 import BasicTypes ( RecFlag(..) )
46 import Digraph ( SCC(..) )
47 import Bag
48 import Util
49 import Outputable
50 import FastString
51 import Data.List ( partition, sort )
52 import Maybes ( orElse )
53 import Control.Monad
54 #if __GLASGOW_HASKELL__ < 709
55 import Data.Traversable ( traverse )
56 #endif
57
58 {-
59 -- ToDo: Put the annotations into the monad, so that they arrive in the proper
60 -- place and can be used when complaining.
61
62 The code tree received by the function @rnBinds@ contains definitions
63 in where-clauses which are all apparently mutually recursive, but which may
64 not really depend upon each other. For example, in the top level program
65 \begin{verbatim}
66 f x = y where a = x
67 y = x
68 \end{verbatim}
69 the definitions of @a@ and @y@ do not depend on each other at all.
70 Unfortunately, the typechecker cannot always check such definitions.
71 \footnote{Mycroft, A. 1984. Polymorphic type schemes and recursive
72 definitions. In Proceedings of the International Symposium on Programming,
73 Toulouse, pp. 217-39. LNCS 167. Springer Verlag.}
74 However, the typechecker usually can check definitions in which only the
75 strongly connected components have been collected into recursive bindings.
76 This is precisely what the function @rnBinds@ does.
77
78 ToDo: deal with case where a single monobinds binds the same variable
79 twice.
80
81 The vertag tag is a unique @Int@; the tags only need to be unique
82 within one @MonoBinds@, so that unique-Int plumbing is done explicitly
83 (heavy monad machinery not needed).
84
85
86 ************************************************************************
87 * *
88 * naming conventions *
89 * *
90 ************************************************************************
91
92 \subsection[name-conventions]{Name conventions}
93
94 The basic algorithm involves walking over the tree and returning a tuple
95 containing the new tree plus its free variables. Some functions, such
96 as those walking polymorphic bindings (HsBinds) and qualifier lists in
97 list comprehensions (@Quals@), return the variables bound in local
98 environments. These are then used to calculate the free variables of the
99 expression evaluated in these environments.
100
101 Conventions for variable names are as follows:
102 \begin{itemize}
103 \item
104 new code is given a prime to distinguish it from the old.
105
106 \item
107 a set of variables defined in @Exp@ is written @dvExp@
108
109 \item
110 a set of variables free in @Exp@ is written @fvExp@
111 \end{itemize}
112
113 ************************************************************************
114 * *
115 * analysing polymorphic bindings (HsBindGroup, HsBind)
116 * *
117 ************************************************************************
118
119 \subsubsection[dep-HsBinds]{Polymorphic bindings}
120
121 Non-recursive expressions are reconstructed without any changes at top
122 level, although their component expressions may have to be altered.
123 However, non-recursive expressions are currently not expected as
124 \Haskell{} programs, and this code should not be executed.
125
126 Monomorphic bindings contain information that is returned in a tuple
127 (a @FlatMonoBinds@) containing:
128
129 \begin{enumerate}
130 \item
131 a unique @Int@ that serves as the ``vertex tag'' for this binding.
132
133 \item
134 the name of a function or the names in a pattern. These are a set
135 referred to as @dvLhs@, the defined variables of the left hand side.
136
137 \item
138 the free variables of the body. These are referred to as @fvBody@.
139
140 \item
141 the definition's actual code. This is referred to as just @code@.
142 \end{enumerate}
143
144 The function @nonRecDvFv@ returns two sets of variables. The first is
145 the set of variables defined in the set of monomorphic bindings, while the
146 second is the set of free variables in those bindings.
147
148 The set of variables defined in a non-recursive binding is just the
149 union of all of them, as @union@ removes duplicates. However, the
150 free variables in each successive set of cumulative bindings is the
151 union of those in the previous set plus those of the newest binding after
152 the defined variables of the previous set have been removed.
153
154 @rnMethodBinds@ deals only with the declarations in class and
155 instance declarations. It expects only to see @FunMonoBind@s, and
156 it expects the global environment to contain bindings for the binders
157 (which are all class operations).
158
159 ************************************************************************
160 * *
161 \subsubsection{ Top-level bindings}
162 * *
163 ************************************************************************
164 -}
165
166 -- for top-level bindings, we need to make top-level names,
167 -- so we have a different entry point than for local bindings
168 rnTopBindsLHS :: MiniFixityEnv
169 -> HsValBinds RdrName
170 -> RnM (HsValBindsLR Name RdrName)
171 rnTopBindsLHS fix_env binds
172 = rnValBindsLHS (topRecNameMaker fix_env) binds
173
174 rnTopBindsRHS :: NameSet -> HsValBindsLR Name RdrName
175 -> RnM (HsValBinds Name, DefUses)
176 rnTopBindsRHS bound_names binds
177 = do { is_boot <- tcIsHsBootOrSig
178 ; if is_boot
179 then rnTopBindsBoot binds
180 else rnValBindsRHS (TopSigCtxt bound_names) binds }
181
182 rnTopBindsBoot :: HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses)
183 -- A hs-boot file has no bindings.
184 -- Return a single HsBindGroup with empty binds and renamed signatures
185 rnTopBindsBoot (ValBindsIn mbinds sigs)
186 = do { checkErr (isEmptyLHsBinds mbinds) (bindsInHsBootFile mbinds)
187 ; (sigs', fvs) <- renameSigs HsBootCtxt sigs
188 ; return (ValBindsOut [] sigs', usesOnly fvs) }
189 rnTopBindsBoot b = pprPanic "rnTopBindsBoot" (ppr b)
190
191 {-
192 *********************************************************
193 * *
194 HsLocalBinds
195 * *
196 *********************************************************
197 -}
198
199 rnLocalBindsAndThen :: HsLocalBinds RdrName
200 -> (HsLocalBinds Name -> FreeVars -> RnM (result, FreeVars))
201 -> RnM (result, FreeVars)
202 -- This version (a) assumes that the binding vars are *not* already in scope
203 -- (b) removes the binders from the free vars of the thing inside
204 -- The parser doesn't produce ThenBinds
205 rnLocalBindsAndThen EmptyLocalBinds thing_inside =
206 thing_inside EmptyLocalBinds emptyNameSet
207
208 rnLocalBindsAndThen (HsValBinds val_binds) thing_inside
209 = rnLocalValBindsAndThen val_binds $ \ val_binds' ->
210 thing_inside (HsValBinds val_binds')
211
212 rnLocalBindsAndThen (HsIPBinds binds) thing_inside = do
213 (binds',fv_binds) <- rnIPBinds binds
214 (thing, fvs_thing) <- thing_inside (HsIPBinds binds') fv_binds
215 return (thing, fvs_thing `plusFV` fv_binds)
216
217 rnIPBinds :: HsIPBinds RdrName -> RnM (HsIPBinds Name, FreeVars)
218 rnIPBinds (IPBinds ip_binds _no_dict_binds) = do
219 (ip_binds', fvs_s) <- mapAndUnzipM (wrapLocFstM rnIPBind) ip_binds
220 return (IPBinds ip_binds' emptyTcEvBinds, plusFVs fvs_s)
221
222 rnIPBind :: IPBind RdrName -> RnM (IPBind Name, FreeVars)
223 rnIPBind (IPBind ~(Left n) expr) = do
224 (expr',fvExpr) <- rnLExpr expr
225 return (IPBind (Left n) expr', fvExpr)
226
227 {-
228 ************************************************************************
229 * *
230 ValBinds
231 * *
232 ************************************************************************
233 -}
234
235 -- Renaming local binding groups
236 -- Does duplicate/shadow check
237 rnLocalValBindsLHS :: MiniFixityEnv
238 -> HsValBinds RdrName
239 -> RnM ([Name], HsValBindsLR Name RdrName)
240 rnLocalValBindsLHS fix_env binds
241 = do { binds' <- rnValBindsLHS (localRecNameMaker fix_env) binds
242
243 -- Check for duplicates and shadowing
244 -- Must do this *after* renaming the patterns
245 -- See Note [Collect binders only after renaming] in HsUtils
246
247 -- We need to check for dups here because we
248 -- don't don't bind all of the variables from the ValBinds at once
249 -- with bindLocatedLocals any more.
250 --
251 -- Note that we don't want to do this at the top level, since
252 -- sorting out duplicates and shadowing there happens elsewhere.
253 -- The behavior is even different. For example,
254 -- import A(f)
255 -- f = ...
256 -- should not produce a shadowing warning (but it will produce
257 -- an ambiguity warning if you use f), but
258 -- import A(f)
259 -- g = let f = ... in f
260 -- should.
261 ; let bound_names = collectHsValBinders binds'
262 -- There should be only Ids, but if there are any bogus
263 -- pattern synonyms, we'll collect them anyway, so that
264 -- we don't generate subsequent out-of-scope messages
265 ; envs <- getRdrEnvs
266 ; checkDupAndShadowedNames envs bound_names
267
268 ; return (bound_names, binds') }
269
270 -- renames the left-hand sides
271 -- generic version used both at the top level and for local binds
272 -- does some error checking, but not what gets done elsewhere at the top level
273 rnValBindsLHS :: NameMaker
274 -> HsValBinds RdrName
275 -> RnM (HsValBindsLR Name RdrName)
276 rnValBindsLHS topP (ValBindsIn mbinds sigs)
277 = do { mbinds' <- mapBagM (wrapLocM (rnBindLHS topP doc)) mbinds
278 ; return $ ValBindsIn mbinds' sigs }
279 where
280 bndrs = collectHsBindsBinders mbinds
281 doc = text "In the binding group for:" <+> pprWithCommas ppr bndrs
282
283 rnValBindsLHS _ b = pprPanic "rnValBindsLHSFromDoc" (ppr b)
284
285 -- General version used both from the top-level and for local things
286 -- Assumes the LHS vars are in scope
287 --
288 -- Does not bind the local fixity declarations
289 rnValBindsRHS :: HsSigCtxt
290 -> HsValBindsLR Name RdrName
291 -> RnM (HsValBinds Name, DefUses)
292
293 rnValBindsRHS ctxt (ValBindsIn mbinds sigs)
294 = do { (sigs', sig_fvs) <- renameSigs ctxt sigs
295 ; binds_w_dus <- mapBagM (rnLBind (mkSigTvFn sigs')) mbinds
296 ; case depAnalBinds binds_w_dus of
297 (anal_binds, anal_dus) -> return (valbind', valbind'_dus)
298 where
299 valbind' = ValBindsOut anal_binds sigs'
300 valbind'_dus = anal_dus `plusDU` usesOnly sig_fvs
301 -- Put the sig uses *after* the bindings
302 -- so that the binders are removed from
303 -- the uses in the sigs
304 }
305
306 rnValBindsRHS _ b = pprPanic "rnValBindsRHS" (ppr b)
307
308 -- Wrapper for local binds
309 --
310 -- The *client* of this function is responsible for checking for unused binders;
311 -- it doesn't (and can't: we don't have the thing inside the binds) happen here
312 --
313 -- The client is also responsible for bringing the fixities into scope
314 rnLocalValBindsRHS :: NameSet -- names bound by the LHSes
315 -> HsValBindsLR Name RdrName
316 -> RnM (HsValBinds Name, DefUses)
317 rnLocalValBindsRHS bound_names binds
318 = rnValBindsRHS (LocalBindCtxt bound_names) binds
319
320 -- for local binds
321 -- wrapper that does both the left- and right-hand sides
322 --
323 -- here there are no local fixity decls passed in;
324 -- the local fixity decls come from the ValBinds sigs
325 rnLocalValBindsAndThen
326 :: HsValBinds RdrName
327 -> (HsValBinds Name -> FreeVars -> RnM (result, FreeVars))
328 -> RnM (result, FreeVars)
329 rnLocalValBindsAndThen binds@(ValBindsIn _ sigs) thing_inside
330 = do { -- (A) Create the local fixity environment
331 new_fixities <- makeMiniFixityEnv [L loc sig
332 | L loc (FixSig sig) <- sigs]
333
334 -- (B) Rename the LHSes
335 ; (bound_names, new_lhs) <- rnLocalValBindsLHS new_fixities binds
336
337 -- ...and bring them (and their fixities) into scope
338 ; bindLocalNamesFV bound_names $
339 addLocalFixities new_fixities bound_names $ do
340
341 { -- (C) Do the RHS and thing inside
342 (binds', dus) <- rnLocalValBindsRHS (mkNameSet bound_names) new_lhs
343 ; (result, result_fvs) <- thing_inside binds' (allUses dus)
344
345 -- Report unused bindings based on the (accurate)
346 -- findUses. E.g.
347 -- let x = x in 3
348 -- should report 'x' unused
349 ; let real_uses = findUses dus result_fvs
350 -- Insert fake uses for variables introduced implicitly by
351 -- wildcards (#4404)
352 implicit_uses = hsValBindsImplicits binds'
353 ; warnUnusedLocalBinds bound_names
354 (real_uses `unionNameSet` implicit_uses)
355
356 ; let
357 -- The variables "used" in the val binds are:
358 -- (1) the uses of the binds (allUses)
359 -- (2) the FVs of the thing-inside
360 all_uses = allUses dus `plusFV` result_fvs
361 -- Note [Unused binding hack]
362 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~
363 -- Note that *in contrast* to the above reporting of
364 -- unused bindings, (1) above uses duUses to return *all*
365 -- the uses, even if the binding is unused. Otherwise consider:
366 -- x = 3
367 -- y = let p = x in 'x' -- NB: p not used
368 -- If we don't "see" the dependency of 'y' on 'x', we may put the
369 -- bindings in the wrong order, and the type checker will complain
370 -- that x isn't in scope
371 --
372 -- But note that this means we won't report 'x' as unused,
373 -- whereas we would if we had { x = 3; p = x; y = 'x' }
374
375 ; return (result, all_uses) }}
376 -- The bound names are pruned out of all_uses
377 -- by the bindLocalNamesFV call above
378
379 rnLocalValBindsAndThen bs _ = pprPanic "rnLocalValBindsAndThen" (ppr bs)
380
381
382 ---------------------
383
384 -- renaming a single bind
385
386 rnBindLHS :: NameMaker
387 -> SDoc
388 -> HsBind RdrName
389 -- returns the renamed left-hand side,
390 -- and the FreeVars *of the LHS*
391 -- (i.e., any free variables of the pattern)
392 -> RnM (HsBindLR Name RdrName)
393
394 rnBindLHS name_maker _ bind@(PatBind { pat_lhs = pat })
395 = do
396 -- we don't actually use the FV processing of rnPatsAndThen here
397 (pat',pat'_fvs) <- rnBindPat name_maker pat
398 return (bind { pat_lhs = pat', bind_fvs = pat'_fvs })
399 -- We temporarily store the pat's FVs in bind_fvs;
400 -- gets updated to the FVs of the whole bind
401 -- when doing the RHS below
402
403 rnBindLHS name_maker _ bind@(FunBind { fun_id = rdr_name })
404 = do { name <- applyNameMaker name_maker rdr_name
405 ; return (bind { fun_id = name
406 , bind_fvs = placeHolderNamesTc }) }
407
408 rnBindLHS name_maker _ (PatSynBind psb@PSB{ psb_id = rdrname })
409 | isTopRecNameMaker name_maker
410 = do { addLocM checkConName rdrname
411 ; name <- lookupLocatedTopBndrRn rdrname -- Should be in scope already
412 ; return (PatSynBind psb{ psb_id = name }) }
413
414 | otherwise -- Pattern synonym, not at top level
415 = do { addErr localPatternSynonymErr -- Complain, but make up a fake
416 -- name so that we can carry on
417 ; name <- applyNameMaker name_maker rdrname
418 ; return (PatSynBind psb{ psb_id = name }) }
419 where
420 localPatternSynonymErr :: SDoc
421 localPatternSynonymErr
422 = hang (ptext (sLit "Illegal pattern synonym declaration for") <+> quotes (ppr rdrname))
423 2 (ptext (sLit "Pattern synonym declarations are only valid at top level"))
424
425 rnBindLHS _ _ b = pprPanic "rnBindHS" (ppr b)
426
427 rnLBind :: (Name -> [Name]) -- Signature tyvar function
428 -> LHsBindLR Name RdrName
429 -> RnM (LHsBind Name, [Name], Uses)
430 rnLBind sig_fn (L loc bind)
431 = setSrcSpan loc $
432 do { (bind', bndrs, dus) <- rnBind sig_fn bind
433 ; return (L loc bind', bndrs, dus) }
434
435 -- assumes the left-hands-side vars are in scope
436 rnBind :: (Name -> [Name]) -- Signature tyvar function
437 -> HsBindLR Name RdrName
438 -> RnM (HsBind Name, [Name], Uses)
439 rnBind _ bind@(PatBind { pat_lhs = pat
440 , pat_rhs = grhss
441 -- pat fvs were stored in bind_fvs
442 -- after processing the LHS
443 , bind_fvs = pat_fvs })
444 = do { mod <- getModule
445 ; (grhss', rhs_fvs) <- rnGRHSs PatBindRhs rnLExpr grhss
446
447 -- No scoped type variables for pattern bindings
448 ; let all_fvs = pat_fvs `plusFV` rhs_fvs
449 fvs' = filterNameSet (nameIsLocalOrFrom mod) all_fvs
450 -- Keep locally-defined Names
451 -- As well as dependency analysis, we need these for the
452 -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan
453 bndrs = collectPatBinders pat
454 bind' = bind { pat_rhs = grhss',
455 pat_rhs_ty = placeHolderType, bind_fvs = fvs' }
456 is_wild_pat = case pat of
457 L _ (WildPat {}) -> True
458 L _ (BangPat (L _ (WildPat {}))) -> True -- #9127
459 _ -> False
460
461 -- Warn if the pattern binds no variables, except for the
462 -- entirely-explicit idiom _ = rhs
463 -- which (a) is not that different from _v = rhs
464 -- (b) is sometimes used to give a type sig for,
465 -- or an occurrence of, a variable on the RHS
466 ; whenWOptM Opt_WarnUnusedPatternBinds $
467 when (null bndrs && not is_wild_pat) $
468 addWarn $ unusedPatBindWarn bind'
469
470 ; fvs' `seq` -- See Note [Free-variable space leak]
471 return (bind', bndrs, all_fvs) }
472
473 rnBind sig_fn bind@(FunBind { fun_id = name
474 , fun_matches = matches })
475 -- invariant: no free vars here when it's a FunBind
476 = do { let plain_name = unLoc name
477
478 ; (matches', rhs_fvs) <- bindSigTyVarsFV (sig_fn plain_name) $
479 -- bindSigTyVars tests for Opt_ScopedTyVars
480 rnMatchGroup (FunRhs plain_name)
481 rnLExpr matches
482 ; let is_infix = isInfixFunBind bind
483 ; when is_infix $ checkPrecMatch plain_name matches'
484
485 ; mod <- getModule
486 ; let fvs' = filterNameSet (nameIsLocalOrFrom mod) rhs_fvs
487 -- Keep locally-defined Names
488 -- As well as dependency analysis, we need these for the
489 -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan
490
491 ; fvs' `seq` -- See Note [Free-variable space leak]
492 return (bind { fun_matches = matches'
493 , bind_fvs = fvs' },
494 [plain_name], rhs_fvs)
495 }
496
497 rnBind sig_fn (PatSynBind bind)
498 = do { (bind', name, fvs) <- rnPatSynBind sig_fn bind
499 ; return (PatSynBind bind', name, fvs) }
500
501 rnBind _ b = pprPanic "rnBind" (ppr b)
502
503 {-
504 Note [Free-variable space leak]
505 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
506 We have
507 fvs' = trim fvs
508 and we seq fvs' before turning it as part of a record.
509
510 The reason is that trim is sometimes something like
511 \xs -> intersectNameSet (mkNameSet bound_names) xs
512 and we don't want to retain the list bound_names. This showed up in
513 trac ticket #1136.
514 -}
515
516 {- *********************************************************************
517 * *
518 Dependency analysis and other support functions
519 * *
520 ********************************************************************* -}
521
522 depAnalBinds :: Bag (LHsBind Name, [Name], Uses)
523 -> ([(RecFlag, LHsBinds Name)], DefUses)
524 -- Dependency analysis; this is important so that
525 -- unused-binding reporting is accurate
526 depAnalBinds binds_w_dus
527 = (map get_binds sccs, map get_du sccs)
528 where
529 sccs = depAnal (\(_, defs, _) -> defs)
530 (\(_, _, uses) -> nameSetElems uses)
531 (bagToList binds_w_dus)
532
533 get_binds (AcyclicSCC (bind, _, _)) = (NonRecursive, unitBag bind)
534 get_binds (CyclicSCC binds_w_dus) = (Recursive, listToBag [b | (b,_,_) <- binds_w_dus])
535
536 get_du (AcyclicSCC (_, bndrs, uses)) = (Just (mkNameSet bndrs), uses)
537 get_du (CyclicSCC binds_w_dus) = (Just defs, uses)
538 where
539 defs = mkNameSet [b | (_,bs,_) <- binds_w_dus, b <- bs]
540 uses = unionNameSets [u | (_,_,u) <- binds_w_dus]
541
542 ---------------------
543 -- Bind the top-level forall'd type variables in the sigs.
544 -- E.g f :: a -> a
545 -- f = rhs
546 -- The 'a' scopes over the rhs
547 --
548 -- NB: there'll usually be just one (for a function binding)
549 -- but if there are many, one may shadow the rest; too bad!
550 -- e.g x :: [a] -> [a]
551 -- y :: [(a,a)] -> a
552 -- (x,y) = e
553 -- In e, 'a' will be in scope, and it'll be the one from 'y'!
554
555 mkSigTvFn :: [LSig Name] -> (Name -> [Name])
556 -- Return a lookup function that maps an Id Name to the names
557 -- of the type variables that should scope over its body..
558 mkSigTvFn sigs
559 = \n -> lookupNameEnv env n `orElse` []
560 where
561 extractScopedTyVars :: LHsType Name -> [Name]
562 extractScopedTyVars (L _ (HsForAllTy Explicit _ ltvs _ _)) = hsLKiTyVarNames ltvs
563 extractScopedTyVars _ = []
564
565 env :: NameEnv [Name]
566 env = mkNameEnv [ (name, nwcs ++ extractScopedTyVars ty) -- Kind variables and type variables
567 -- nwcs: see Note [Scoping of named wildcards]
568 | L _ (TypeSig names ty nwcs) <- sigs
569 , L _ name <- names]
570 -- Note the pattern-match on "Explicit"; we only bind
571 -- type variables from signatures with an explicit top-level for-all
572
573
574 {- Note [Scoping of named wildcards]
575 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
576 Consider
577 f :: _a -> _a
578 f x = let g :: _a -> _a
579 g = ...
580 in ...
581
582 Currently, for better or worse, the "_a" variables are all the same. So
583 although there is no explicit forall, the "_a" scopes over the definition.
584 I don't know if this is a good idea, but there it is.
585 -}
586
587 -- Process the fixity declarations, making a FastString -> (Located Fixity) map
588 -- (We keep the location around for reporting duplicate fixity declarations.)
589 --
590 -- Checks for duplicates, but not that only locally defined things are fixed.
591 -- Note: for local fixity declarations, duplicates would also be checked in
592 -- check_sigs below. But we also use this function at the top level.
593
594 makeMiniFixityEnv :: [LFixitySig RdrName] -> RnM MiniFixityEnv
595
596 makeMiniFixityEnv decls = foldlM add_one_sig emptyFsEnv decls
597 where
598 add_one_sig env (L loc (FixitySig names fixity)) =
599 foldlM add_one env [ (loc,name_loc,name,fixity)
600 | L name_loc name <- names ]
601
602 add_one env (loc, name_loc, name,fixity) = do
603 { -- this fixity decl is a duplicate iff
604 -- the ReaderName's OccName's FastString is already in the env
605 -- (we only need to check the local fix_env because
606 -- definitions of non-local will be caught elsewhere)
607 let { fs = occNameFS (rdrNameOcc name)
608 ; fix_item = L loc fixity };
609
610 case lookupFsEnv env fs of
611 Nothing -> return $ extendFsEnv env fs fix_item
612 Just (L loc' _) -> do
613 { setSrcSpan loc $
614 addErrAt name_loc (dupFixityDecl loc' name)
615 ; return env}
616 }
617
618 dupFixityDecl :: SrcSpan -> RdrName -> SDoc
619 dupFixityDecl loc rdr_name
620 = vcat [ptext (sLit "Multiple fixity declarations for") <+> quotes (ppr rdr_name),
621 ptext (sLit "also at ") <+> ppr loc]
622
623
624 {- *********************************************************************
625 * *
626 Pattern synonym bindings
627 * *
628 ********************************************************************* -}
629
630 rnPatSynBind :: (Name -> [Name]) -- Signature tyvar function
631 -> PatSynBind Name RdrName
632 -> RnM (PatSynBind Name Name, [Name], Uses)
633 rnPatSynBind _sig_fn bind@(PSB { psb_id = L _ name
634 , psb_args = details
635 , psb_def = pat
636 , psb_dir = dir })
637 -- invariant: no free vars here when it's a FunBind
638 = do { pattern_synonym_ok <- xoptM Opt_PatternSynonyms
639 ; unless pattern_synonym_ok (addErr patternSynonymErr)
640
641 ; ((pat', details'), fvs1) <- rnPat PatSyn pat $ \pat' -> do
642 -- We check the 'RdrName's instead of the 'Name's
643 -- so that the binding locations are reported
644 -- from the left-hand side
645 { (details', fvs) <- case details of
646 PrefixPatSyn vars ->
647 do { checkDupRdrNames vars
648 ; names <- mapM lookupVar vars
649 ; return (PrefixPatSyn names, mkFVs (map unLoc names)) }
650 InfixPatSyn var1 var2 ->
651 do { checkDupRdrNames [var1, var2]
652 ; name1 <- lookupVar var1
653 ; name2 <- lookupVar var2
654 -- ; checkPrecMatch -- TODO
655 ; return (InfixPatSyn name1 name2, mkFVs (map unLoc [name1, name2])) }
656 RecordPatSyn vars ->
657 do { checkDupRdrNames (map recordPatSynSelectorId vars)
658 ; let rnRecordPatSynField
659 (RecordPatSynField visible hidden) = do {
660 ; visible' <- lookupLocatedTopBndrRn visible
661 ; hidden' <- lookupVar hidden
662 ; return $ RecordPatSynField visible' hidden' }
663 ; names <- mapM rnRecordPatSynField vars
664 ; return (RecordPatSyn names
665 , mkFVs (map (unLoc . recordPatSynPatVar) names)) }
666
667
668 ; return ((pat', details'), fvs) }
669 ; (dir', fvs2) <- case dir of
670 Unidirectional -> return (Unidirectional, emptyFVs)
671 ImplicitBidirectional -> return (ImplicitBidirectional, emptyFVs)
672 ExplicitBidirectional mg ->
673 do { (mg', fvs) <- rnMatchGroup PatSyn rnLExpr mg
674 ; return (ExplicitBidirectional mg', fvs) }
675
676 ; mod <- getModule
677 ; let fvs = fvs1 `plusFV` fvs2
678 fvs' = filterNameSet (nameIsLocalOrFrom mod) fvs
679 -- Keep locally-defined Names
680 -- As well as dependency analysis, we need these for the
681 -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan
682
683 ; let bind' = bind{ psb_args = details'
684 , psb_def = pat'
685 , psb_dir = dir'
686 , psb_fvs = fvs' }
687 ; let selector_names = case details' of
688 RecordPatSyn names ->
689 map (unLoc . recordPatSynSelectorId) names
690 _ -> []
691
692 ; fvs' `seq` -- See Note [Free-variable space leak]
693 return (bind', name : selector_names , fvs1)
694 -- See Note [Pattern synonym builders don't yield dependencies]
695 }
696 where
697 lookupVar = wrapLocM lookupOccRn
698
699 patternSynonymErr :: SDoc
700 patternSynonymErr
701 = hang (ptext (sLit "Illegal pattern synonym declaration"))
702 2 (ptext (sLit "Use -XPatternSynonyms to enable this extension"))
703
704 {-
705 Note [Pattern synonym builders don't yield dependencies]
706 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
707 When renaming a pattern synonym that has an explicit builder,
708 references in the builder definition should not be used when
709 calculating dependencies. For example, consider the following pattern
710 synonym definition:
711
712 pattern P x <- C1 x where
713 P x = f (C1 x)
714
715 f (P x) = C2 x
716
717 In this case, 'P' needs to be typechecked in two passes:
718
719 1. Typecheck the pattern definition of 'P', which fully determines the
720 type of 'P'. This step doesn't require knowing anything about 'f',
721 since the builder definition is not looked at.
722
723 2. Typecheck the builder definition, which needs the typechecked
724 definition of 'f' to be in scope.
725
726 This behaviour is implemented in 'tcValBinds', but it crucially
727 depends on 'P' not being put in a recursive group with 'f' (which
728 would make it look like a recursive pattern synonym a la 'pattern P =
729 P' which is unsound and rejected).
730
731 -}
732
733 {- *********************************************************************
734 * *
735 Class/instance method bindings
736 * *
737 ********************************************************************* -}
738
739 {- @rnMethodBinds@ is used for the method bindings of a class and an instance
740 declaration. Like @rnBinds@ but without dependency analysis.
741
742 NOTA BENE: we record each {\em binder} of a method-bind group as a free variable.
743 That's crucial when dealing with an instance decl:
744 \begin{verbatim}
745 instance Foo (T a) where
746 op x = ...
747 \end{verbatim}
748 This might be the {\em sole} occurrence of @op@ for an imported class @Foo@,
749 and unless @op@ occurs we won't treat the type signature of @op@ in the class
750 decl for @Foo@ as a source of instance-decl gates. But we should! Indeed,
751 in many ways the @op@ in an instance decl is just like an occurrence, not
752 a binder.
753 -}
754
755 rnMethodBinds :: Bool -- True <=> is a class declaration
756 -> Name -- Class name
757 -> [Name] -- Type variables from the class/instance header
758 -> LHsBinds RdrName -- Binds
759 -> [LSig RdrName] -- and signatures/pragmas
760 -> RnM (LHsBinds Name, [LSig Name], FreeVars)
761 -- Used for
762 -- * the default method bindings in a class decl
763 -- * the method bindings in an instance decl
764 rnMethodBinds is_cls_decl cls ktv_names binds sigs
765 = do { checkDupRdrNames (collectMethodBinders binds)
766 -- Check that the same method is not given twice in the
767 -- same instance decl instance C T where
768 -- f x = ...
769 -- g y = ...
770 -- f x = ...
771 -- We must use checkDupRdrNames because the Name of the
772 -- method is the Name of the class selector, whose SrcSpan
773 -- points to the class declaration; and we use rnMethodBinds
774 -- for instance decls too
775
776 -- Rename the bindings LHSs
777 ; binds' <- foldrBagM (rnMethodBindLHS is_cls_decl cls) emptyBag binds
778
779 -- Rename the pragmas and signatures
780 -- Annoyingly the type variables /are/ in scope for signatures, but
781 -- /are not/ in scope in the SPECIALISE instance pramas; e.g.
782 -- instance Eq a => Eq (T a) where
783 -- (==) :: a -> a -> a
784 -- {-# SPECIALISE instance Eq a => Eq (T [a]) #-}
785 ; let (spec_inst_prags, other_sigs) = partition isSpecInstLSig sigs
786 bound_nms = mkNameSet (collectHsBindsBinders binds')
787 sig_ctxt | is_cls_decl = ClsDeclCtxt cls
788 | otherwise = InstDeclCtxt bound_nms
789 ; (spec_inst_prags', sip_fvs) <- renameSigs sig_ctxt spec_inst_prags
790 ; (other_sigs', sig_fvs) <- extendTyVarEnvFVRn ktv_names $
791 renameSigs sig_ctxt other_sigs
792
793 -- Rename the bindings RHSs. Again there's an issue about whether the
794 -- type variables from the class/instance head are in scope.
795 -- Answer no in Haskell 2010, but yes if you have -XScopedTypeVariables
796 ; scoped_tvs <- xoptM Opt_ScopedTypeVariables
797 ; (binds'', bind_fvs) <- maybe_extend_tyvar_env scoped_tvs $
798 do { binds_w_dus <- mapBagM (rnLBind (mkSigTvFn other_sigs')) binds'
799 ; let bind_fvs = foldrBag (\(_,_,fv1) fv2 -> fv1 `plusFV` fv2)
800 emptyFVs binds_w_dus
801 ; return (mapBag fstOf3 binds_w_dus, bind_fvs) }
802
803 ; return ( binds'', spec_inst_prags' ++ other_sigs'
804 , sig_fvs `plusFV` sip_fvs `plusFV` bind_fvs) }
805 where
806 -- For the method bindings in class and instance decls, we extend
807 -- the type variable environment iff -XScopedTypeVariables
808 maybe_extend_tyvar_env scoped_tvs thing_inside
809 | scoped_tvs = extendTyVarEnvFVRn ktv_names thing_inside
810 | otherwise = thing_inside
811
812 rnMethodBindLHS :: Bool -> Name
813 -> LHsBindLR RdrName RdrName
814 -> LHsBindsLR Name RdrName
815 -> RnM (LHsBindsLR Name RdrName)
816 rnMethodBindLHS _ cls (L loc bind@(FunBind { fun_id = name })) rest
817 = setSrcSpan loc $ do
818 do { sel_name <- wrapLocM (lookupInstDeclBndr cls (ptext (sLit "method"))) name
819 -- We use the selector name as the binder
820 ; let bind' = bind { fun_id = sel_name
821 , bind_fvs = placeHolderNamesTc }
822
823 ; return (L loc bind' `consBag` rest ) }
824
825 -- Report error for all other forms of bindings
826 -- This is why we use a fold rather than map
827 rnMethodBindLHS is_cls_decl _ (L loc bind) rest
828 = do { addErrAt loc $
829 vcat [ what <+> ptext (sLit "not allowed in") <+> decl_sort
830 , nest 2 (ppr bind) ]
831 ; return rest }
832 where
833 decl_sort | is_cls_decl = ptext (sLit "class declaration:")
834 | otherwise = ptext (sLit "instance declaration:")
835 what = case bind of
836 PatBind {} -> ptext (sLit "Pattern bindings (except simple variables)")
837 PatSynBind {} -> ptext (sLit "Pattern synonyms")
838 -- Associated pattern synonyms are not implemented yet
839 _ -> pprPanic "rnMethodBind" (ppr bind)
840
841 {-
842 ************************************************************************
843 * *
844 \subsubsection[dep-Sigs]{Signatures (and user-pragmas for values)}
845 * *
846 ************************************************************************
847
848 @renameSigs@ checks for:
849 \begin{enumerate}
850 \item more than one sig for one thing;
851 \item signatures given for things not bound here;
852 \end{enumerate}
853
854 At the moment we don't gather free-var info from the types in
855 signatures. We'd only need this if we wanted to report unused tyvars.
856 -}
857
858 renameSigs :: HsSigCtxt
859 -> [LSig RdrName]
860 -> RnM ([LSig Name], FreeVars)
861 -- Renames the signatures and performs error checks
862 renameSigs ctxt sigs
863 = do { mapM_ dupSigDeclErr (findDupSigs sigs)
864
865 ; checkDupMinimalSigs sigs
866
867 ; (sigs', sig_fvs) <- mapFvRn (wrapLocFstM (renameSig ctxt)) sigs
868
869 ; let (good_sigs, bad_sigs) = partition (okHsSig ctxt) sigs'
870 ; mapM_ misplacedSigErr bad_sigs -- Misplaced
871
872 ; return (good_sigs, sig_fvs) }
873
874 ----------------------
875 -- We use lookupSigOccRn in the signatures, which is a little bit unsatisfactory
876 -- because this won't work for:
877 -- instance Foo T where
878 -- {-# INLINE op #-}
879 -- Baz.op = ...
880 -- We'll just rename the INLINE prag to refer to whatever other 'op'
881 -- is in scope. (I'm assuming that Baz.op isn't in scope unqualified.)
882 -- Doesn't seem worth much trouble to sort this.
883
884 renameSig :: HsSigCtxt -> Sig RdrName -> RnM (Sig Name, FreeVars)
885 -- FixitySig is renamed elsewhere.
886 renameSig _ (IdSig x)
887 = return (IdSig x, emptyFVs) -- Actually this never occurs
888
889 renameSig ctxt sig@(TypeSig vs ty _)
890 = do { new_vs <- mapM (lookupSigOccRn ctxt sig) vs
891 ; let doc = ppr_sig_bndrs vs
892 wildCardsAllowed = case ctxt of
893 TopSigCtxt _ -> True
894 LocalBindCtxt _ -> True
895 _ -> False
896 ; (new_ty, fvs, wcs)
897 <- if wildCardsAllowed
898 then rnHsSigTypeWithWildCards doc ty
899 else do { (new_ty, fvs) <- rnHsSigType doc ty
900 ; return (new_ty, fvs, []) }
901 ; return (TypeSig new_vs new_ty wcs, fvs) }
902
903 renameSig ctxt sig@(GenericSig vs ty)
904 = do { defaultSigs_on <- xoptM Opt_DefaultSignatures
905 ; unless defaultSigs_on (addErr (defaultSigErr sig))
906 ; new_v <- mapM (lookupSigOccRn ctxt sig) vs
907 ; (new_ty, fvs) <- rnHsSigType (ppr_sig_bndrs vs) ty
908 ; return (GenericSig new_v new_ty, fvs) }
909
910 renameSig _ (SpecInstSig src ty)
911 = do { (new_ty, fvs) <- rnLHsType SpecInstSigCtx ty
912 ; return (SpecInstSig src new_ty,fvs) }
913
914 -- {-# SPECIALISE #-} pragmas can refer to imported Ids
915 -- so, in the top-level case (when mb_names is Nothing)
916 -- we use lookupOccRn. If there's both an imported and a local 'f'
917 -- then the SPECIALISE pragma is ambiguous, unlike all other signatures
918 renameSig ctxt sig@(SpecSig v tys inl)
919 = do { new_v <- case ctxt of
920 TopSigCtxt {} -> lookupLocatedOccRn v
921 _ -> lookupSigOccRn ctxt sig v
922 -- ; (new_ty, fvs) <- rnHsSigType (quotes (ppr v)) ty
923 ; (new_ty, fvs) <- foldM do_one ([],emptyFVs) tys
924 ; return (SpecSig new_v new_ty inl, fvs) }
925 where
926 do_one (tys,fvs) ty
927 = do { (new_ty, fvs_ty) <- rnHsSigType (quotes (ppr v)) ty
928 ; return ( new_ty:tys, fvs_ty `plusFV` fvs) }
929
930 renameSig ctxt sig@(InlineSig v s)
931 = do { new_v <- lookupSigOccRn ctxt sig v
932 ; return (InlineSig new_v s, emptyFVs) }
933
934 renameSig ctxt sig@(FixSig (FixitySig vs f))
935 = do { new_vs <- mapM (lookupSigOccRn ctxt sig) vs
936 ; return (FixSig (FixitySig new_vs f), emptyFVs) }
937
938 renameSig ctxt sig@(MinimalSig s (L l bf))
939 = do new_bf <- traverse (lookupSigOccRn ctxt sig) bf
940 return (MinimalSig s (L l new_bf), emptyFVs)
941
942 renameSig ctxt sig@(PatSynSig v (flag, qtvs) req prov ty)
943 = do { v' <- lookupSigOccRn ctxt sig v
944 ; let doc = TypeSigCtx $ quotes (ppr v)
945 ; loc <- getSrcSpanM
946
947 ; let (tv_kvs, mentioned) = extractHsTysRdrTyVars (ty:unLoc prov ++ unLoc req)
948 ; tv_bndrs <- case flag of
949 Implicit ->
950 return $ mkHsQTvs . userHsTyVarBndrs loc $ mentioned
951 Explicit ->
952 do { let heading = ptext (sLit "In the pattern synonym type signature")
953 <+> quotes (ppr sig)
954 ; warnUnusedForAlls (heading $$ docOfHsDocContext doc) qtvs mentioned
955 ; return qtvs }
956 Qualified -> panic "renameSig: Qualified"
957
958 ; bindHsTyVars doc Nothing tv_kvs tv_bndrs $ \ tyvars -> do
959 { (req', fvs2) <- rnContext doc req
960 ; (prov', fvs1) <- rnContext doc prov
961 ; (ty', fvs3) <- rnLHsType doc ty
962
963 ; let fvs = plusFVs [fvs1, fvs2, fvs3]
964 ; return (PatSynSig v' (flag, tyvars) req' prov' ty', fvs) }}
965
966 ppr_sig_bndrs :: [Located RdrName] -> SDoc
967 ppr_sig_bndrs bs = quotes (pprWithCommas ppr bs)
968
969 okHsSig :: HsSigCtxt -> LSig a -> Bool
970 okHsSig ctxt (L _ sig)
971 = case (sig, ctxt) of
972 (GenericSig {}, ClsDeclCtxt {}) -> True
973 (GenericSig {}, _) -> False
974
975 (TypeSig {}, _) -> True
976
977 (PatSynSig {}, TopSigCtxt{}) -> True
978 (PatSynSig {}, _) -> False
979
980 (FixSig {}, InstDeclCtxt {}) -> False
981 (FixSig {}, _) -> True
982
983 (IdSig {}, TopSigCtxt {}) -> True
984 (IdSig {}, InstDeclCtxt {}) -> True
985 (IdSig {}, _) -> False
986
987 (InlineSig {}, HsBootCtxt) -> False
988 (InlineSig {}, _) -> True
989
990 (SpecSig {}, TopSigCtxt {}) -> True
991 (SpecSig {}, LocalBindCtxt {}) -> True
992 (SpecSig {}, InstDeclCtxt {}) -> True
993 (SpecSig {}, _) -> False
994
995 (SpecInstSig {}, InstDeclCtxt {}) -> True
996 (SpecInstSig {}, _) -> False
997
998 (MinimalSig {}, ClsDeclCtxt {}) -> True
999 (MinimalSig {}, _) -> False
1000
1001 -------------------
1002 findDupSigs :: [LSig RdrName] -> [[(Located RdrName, Sig RdrName)]]
1003 -- Check for duplicates on RdrName version,
1004 -- because renamed version has unboundName for
1005 -- not-in-scope binders, which gives bogus dup-sig errors
1006 -- NB: in a class decl, a 'generic' sig is not considered
1007 -- equal to an ordinary sig, so we allow, say
1008 -- class C a where
1009 -- op :: a -> a
1010 -- default op :: Eq a => a -> a
1011 findDupSigs sigs
1012 = findDupsEq matching_sig (concatMap (expand_sig . unLoc) sigs)
1013 where
1014 expand_sig sig@(FixSig (FixitySig ns _)) = zip ns (repeat sig)
1015 expand_sig sig@(InlineSig n _) = [(n,sig)]
1016 expand_sig sig@(TypeSig ns _ _) = [(n,sig) | n <- ns]
1017 expand_sig sig@(GenericSig ns _) = [(n,sig) | n <- ns]
1018 expand_sig _ = []
1019
1020 matching_sig (L _ n1,sig1) (L _ n2,sig2) = n1 == n2 && mtch sig1 sig2
1021 mtch (FixSig {}) (FixSig {}) = True
1022 mtch (InlineSig {}) (InlineSig {}) = True
1023 mtch (TypeSig {}) (TypeSig {}) = True
1024 mtch (GenericSig {}) (GenericSig {}) = True
1025 mtch _ _ = False
1026
1027 -- Warn about multiple MINIMAL signatures
1028 checkDupMinimalSigs :: [LSig RdrName] -> RnM ()
1029 checkDupMinimalSigs sigs
1030 = case filter isMinimalLSig sigs of
1031 minSigs@(_:_:_) -> dupMinimalSigErr minSigs
1032 _ -> return ()
1033
1034 {-
1035 ************************************************************************
1036 * *
1037 \subsection{Match}
1038 * *
1039 ************************************************************************
1040 -}
1041
1042 rnMatchGroup :: Outputable (body RdrName) => HsMatchContext Name
1043 -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
1044 -> MatchGroup RdrName (Located (body RdrName))
1045 -> RnM (MatchGroup Name (Located (body Name)), FreeVars)
1046 rnMatchGroup ctxt rnBody (MG { mg_alts = L _ ms, mg_origin = origin })
1047 = do { empty_case_ok <- xoptM Opt_EmptyCase
1048 ; when (null ms && not empty_case_ok) (addErr (emptyCaseErr ctxt))
1049 ; (new_ms, ms_fvs) <- mapFvRn (rnMatch ctxt rnBody) ms
1050 ; return (mkMatchGroupName origin new_ms, ms_fvs) }
1051
1052 rnMatch :: Outputable (body RdrName) => HsMatchContext Name
1053 -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
1054 -> LMatch RdrName (Located (body RdrName))
1055 -> RnM (LMatch Name (Located (body Name)), FreeVars)
1056 rnMatch ctxt rnBody = wrapLocFstM (rnMatch' ctxt rnBody)
1057
1058 rnMatch' :: Outputable (body RdrName) => HsMatchContext Name
1059 -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
1060 -> Match RdrName (Located (body RdrName))
1061 -> RnM (Match Name (Located (body Name)), FreeVars)
1062 rnMatch' ctxt rnBody match@(Match { m_fixity = mf, m_pats = pats
1063 , m_type = maybe_rhs_sig, m_grhss = grhss })
1064 = do { -- Result type signatures are no longer supported
1065 case maybe_rhs_sig of
1066 Nothing -> return ()
1067 Just (L loc ty) -> addErrAt loc (resSigErr ctxt match ty)
1068
1069 ; let isinfix = isInfixMatch match
1070 -- Now the main event
1071 -- Note that there are no local fixity decls for matches
1072 ; rnPats ctxt pats $ \ pats' -> do
1073 { (grhss', grhss_fvs) <- rnGRHSs ctxt rnBody grhss
1074 ; let mf' = case (ctxt,mf) of
1075 (FunRhs funid,FunBindMatch (L lf _) _)
1076 -> FunBindMatch (L lf funid) isinfix
1077 _ -> NonFunBindMatch
1078 ; return (Match { m_fixity = mf', m_pats = pats'
1079 , m_type = Nothing, m_grhss = grhss'}, grhss_fvs ) }}
1080
1081 emptyCaseErr :: HsMatchContext Name -> SDoc
1082 emptyCaseErr ctxt = hang (ptext (sLit "Empty list of alternatives in") <+> pp_ctxt)
1083 2 (ptext (sLit "Use EmptyCase to allow this"))
1084 where
1085 pp_ctxt = case ctxt of
1086 CaseAlt -> ptext (sLit "case expression")
1087 LambdaExpr -> ptext (sLit "\\case expression")
1088 _ -> ptext (sLit "(unexpected)") <+> pprMatchContextNoun ctxt
1089
1090
1091 resSigErr :: Outputable body
1092 => HsMatchContext Name -> Match RdrName body -> HsType RdrName -> SDoc
1093 resSigErr ctxt match ty
1094 = vcat [ ptext (sLit "Illegal result type signature") <+> quotes (ppr ty)
1095 , nest 2 $ ptext (sLit
1096 "Result signatures are no longer supported in pattern matches")
1097 , pprMatchInCtxt ctxt match ]
1098
1099 {-
1100 ************************************************************************
1101 * *
1102 \subsubsection{Guarded right-hand sides (GRHSs)}
1103 * *
1104 ************************************************************************
1105 -}
1106
1107 rnGRHSs :: HsMatchContext Name
1108 -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
1109 -> GRHSs RdrName (Located (body RdrName))
1110 -> RnM (GRHSs Name (Located (body Name)), FreeVars)
1111 rnGRHSs ctxt rnBody (GRHSs grhss (L l binds))
1112 = rnLocalBindsAndThen binds $ \ binds' _ -> do
1113 (grhss', fvGRHSs) <- mapFvRn (rnGRHS ctxt rnBody) grhss
1114 return (GRHSs grhss' (L l binds'), fvGRHSs)
1115
1116 rnGRHS :: HsMatchContext Name
1117 -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
1118 -> LGRHS RdrName (Located (body RdrName))
1119 -> RnM (LGRHS Name (Located (body Name)), FreeVars)
1120 rnGRHS ctxt rnBody = wrapLocFstM (rnGRHS' ctxt rnBody)
1121
1122 rnGRHS' :: HsMatchContext Name
1123 -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
1124 -> GRHS RdrName (Located (body RdrName))
1125 -> RnM (GRHS Name (Located (body Name)), FreeVars)
1126 rnGRHS' ctxt rnBody (GRHS guards rhs)
1127 = do { pattern_guards_allowed <- xoptM Opt_PatternGuards
1128 ; ((guards', rhs'), fvs) <- rnStmts (PatGuard ctxt) rnLExpr guards $ \ _ ->
1129 rnBody rhs
1130
1131 ; unless (pattern_guards_allowed || is_standard_guard guards')
1132 (addWarn (nonStdGuardErr guards'))
1133
1134 ; return (GRHS guards' rhs', fvs) }
1135 where
1136 -- Standard Haskell 1.4 guards are just a single boolean
1137 -- expression, rather than a list of qualifiers as in the
1138 -- Glasgow extension
1139 is_standard_guard [] = True
1140 is_standard_guard [L _ (BodyStmt _ _ _ _)] = True
1141 is_standard_guard _ = False
1142
1143 {-
1144 ************************************************************************
1145 * *
1146 \subsection{Error messages}
1147 * *
1148 ************************************************************************
1149 -}
1150
1151 dupSigDeclErr :: [(Located RdrName, Sig RdrName)] -> RnM ()
1152 dupSigDeclErr pairs@((L loc name, sig) : _)
1153 = addErrAt loc $
1154 vcat [ ptext (sLit "Duplicate") <+> what_it_is
1155 <> ptext (sLit "s for") <+> quotes (ppr name)
1156 , ptext (sLit "at") <+> vcat (map ppr $ sort $ map (getLoc . fst) pairs) ]
1157 where
1158 what_it_is = hsSigDoc sig
1159
1160 dupSigDeclErr [] = panic "dupSigDeclErr"
1161
1162 misplacedSigErr :: LSig Name -> RnM ()
1163 misplacedSigErr (L loc sig)
1164 = addErrAt loc $
1165 sep [ptext (sLit "Misplaced") <+> hsSigDoc sig <> colon, ppr sig]
1166
1167 defaultSigErr :: Sig RdrName -> SDoc
1168 defaultSigErr sig = vcat [ hang (ptext (sLit "Unexpected default signature:"))
1169 2 (ppr sig)
1170 , ptext (sLit "Use DefaultSignatures to enable default signatures") ]
1171
1172 bindsInHsBootFile :: LHsBindsLR Name RdrName -> SDoc
1173 bindsInHsBootFile mbinds
1174 = hang (ptext (sLit "Bindings in hs-boot files are not allowed"))
1175 2 (ppr mbinds)
1176
1177 nonStdGuardErr :: Outputable body => [LStmtLR Name Name body] -> SDoc
1178 nonStdGuardErr guards
1179 = hang (ptext (sLit "accepting non-standard pattern guards (use PatternGuards to suppress this message)"))
1180 4 (interpp'SP guards)
1181
1182 unusedPatBindWarn :: HsBind Name -> SDoc
1183 unusedPatBindWarn bind
1184 = hang (ptext (sLit "This pattern-binding binds no variables:"))
1185 2 (ppr bind)
1186
1187 dupMinimalSigErr :: [LSig RdrName] -> RnM ()
1188 dupMinimalSigErr sigs@(L loc _ : _)
1189 = addErrAt loc $
1190 vcat [ ptext (sLit "Multiple minimal complete definitions")
1191 , ptext (sLit "at") <+> vcat (map ppr $ sort $ map getLoc sigs)
1192 , ptext (sLit "Combine alternative minimal complete definitions with `|'") ]
1193 dupMinimalSigErr [] = panic "dupMinimalSigErr"