Refactor treatment of wildcards
[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,
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 env :: NameEnv [Name]
562 env = foldr add_scoped_sig emptyNameEnv sigs
563
564 add_scoped_sig :: LSig Name -> NameEnv [Name] -> NameEnv [Name]
565 add_scoped_sig (L _ (ClassOpSig _ names sig_ty)) env
566 = add_scoped_tvs names (hsScopedTvs sig_ty) env
567 add_scoped_sig (L _ (TypeSig names sig_ty)) env
568 = add_scoped_tvs names (hsWcScopedTvs sig_ty) env
569 add_scoped_sig _ env = env
570
571 add_scoped_tvs :: [Located Name] -> [Name] -> NameEnv [Name] -> NameEnv [Name]
572 add_scoped_tvs id_names tv_names env
573 = foldr (\(L _ id_n) env -> extendNameEnv env id_n tv_names) env id_names
574
575 -- Process the fixity declarations, making a FastString -> (Located Fixity) map
576 -- (We keep the location around for reporting duplicate fixity declarations.)
577 --
578 -- Checks for duplicates, but not that only locally defined things are fixed.
579 -- Note: for local fixity declarations, duplicates would also be checked in
580 -- check_sigs below. But we also use this function at the top level.
581
582 makeMiniFixityEnv :: [LFixitySig RdrName] -> RnM MiniFixityEnv
583
584 makeMiniFixityEnv decls = foldlM add_one_sig emptyFsEnv decls
585 where
586 add_one_sig env (L loc (FixitySig names fixity)) =
587 foldlM add_one env [ (loc,name_loc,name,fixity)
588 | L name_loc name <- names ]
589
590 add_one env (loc, name_loc, name,fixity) = do
591 { -- this fixity decl is a duplicate iff
592 -- the ReaderName's OccName's FastString is already in the env
593 -- (we only need to check the local fix_env because
594 -- definitions of non-local will be caught elsewhere)
595 let { fs = occNameFS (rdrNameOcc name)
596 ; fix_item = L loc fixity };
597
598 case lookupFsEnv env fs of
599 Nothing -> return $ extendFsEnv env fs fix_item
600 Just (L loc' _) -> do
601 { setSrcSpan loc $
602 addErrAt name_loc (dupFixityDecl loc' name)
603 ; return env}
604 }
605
606 dupFixityDecl :: SrcSpan -> RdrName -> SDoc
607 dupFixityDecl loc rdr_name
608 = vcat [ptext (sLit "Multiple fixity declarations for") <+> quotes (ppr rdr_name),
609 ptext (sLit "also at ") <+> ppr loc]
610
611
612 {- *********************************************************************
613 * *
614 Pattern synonym bindings
615 * *
616 ********************************************************************* -}
617
618 rnPatSynBind :: (Name -> [Name]) -- Signature tyvar function
619 -> PatSynBind Name RdrName
620 -> RnM (PatSynBind Name Name, [Name], Uses)
621 rnPatSynBind _sig_fn bind@(PSB { psb_id = L _ name
622 , psb_args = details
623 , psb_def = pat
624 , psb_dir = dir })
625 -- invariant: no free vars here when it's a FunBind
626 = do { pattern_synonym_ok <- xoptM Opt_PatternSynonyms
627 ; unless pattern_synonym_ok (addErr patternSynonymErr)
628
629 ; ((pat', details'), fvs1) <- rnPat PatSyn pat $ \pat' -> do
630 -- We check the 'RdrName's instead of the 'Name's
631 -- so that the binding locations are reported
632 -- from the left-hand side
633 { (details', fvs) <- case details of
634 PrefixPatSyn vars ->
635 do { checkDupRdrNames vars
636 ; names <- mapM lookupVar vars
637 ; return (PrefixPatSyn names, mkFVs (map unLoc names)) }
638 InfixPatSyn var1 var2 ->
639 do { checkDupRdrNames [var1, var2]
640 ; name1 <- lookupVar var1
641 ; name2 <- lookupVar var2
642 -- ; checkPrecMatch -- TODO
643 ; return (InfixPatSyn name1 name2, mkFVs (map unLoc [name1, name2])) }
644 RecordPatSyn vars ->
645 do { checkDupRdrNames (map recordPatSynSelectorId vars)
646 ; let rnRecordPatSynField
647 (RecordPatSynField visible hidden) = do {
648 ; visible' <- lookupLocatedTopBndrRn visible
649 ; hidden' <- lookupVar hidden
650 ; return $ RecordPatSynField visible' hidden' }
651 ; names <- mapM rnRecordPatSynField vars
652 ; return (RecordPatSyn names
653 , mkFVs (map (unLoc . recordPatSynPatVar) names)) }
654
655
656 ; return ((pat', details'), fvs) }
657 ; (dir', fvs2) <- case dir of
658 Unidirectional -> return (Unidirectional, emptyFVs)
659 ImplicitBidirectional -> return (ImplicitBidirectional, emptyFVs)
660 ExplicitBidirectional mg ->
661 do { (mg', fvs) <- rnMatchGroup PatSyn rnLExpr mg
662 ; return (ExplicitBidirectional mg', fvs) }
663
664 ; mod <- getModule
665 ; let fvs = fvs1 `plusFV` fvs2
666 fvs' = filterNameSet (nameIsLocalOrFrom mod) fvs
667 -- Keep locally-defined Names
668 -- As well as dependency analysis, we need these for the
669 -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan
670
671 ; let bind' = bind{ psb_args = details'
672 , psb_def = pat'
673 , psb_dir = dir'
674 , psb_fvs = fvs' }
675 ; let selector_names = case details' of
676 RecordPatSyn names ->
677 map (unLoc . recordPatSynSelectorId) names
678 _ -> []
679
680 ; fvs' `seq` -- See Note [Free-variable space leak]
681 return (bind', name : selector_names , fvs1)
682 -- See Note [Pattern synonym builders don't yield dependencies]
683 }
684 where
685 lookupVar = wrapLocM lookupOccRn
686
687 patternSynonymErr :: SDoc
688 patternSynonymErr
689 = hang (ptext (sLit "Illegal pattern synonym declaration"))
690 2 (ptext (sLit "Use -XPatternSynonyms to enable this extension"))
691
692 {-
693 Note [Pattern synonym builders don't yield dependencies]
694 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
695 When renaming a pattern synonym that has an explicit builder,
696 references in the builder definition should not be used when
697 calculating dependencies. For example, consider the following pattern
698 synonym definition:
699
700 pattern P x <- C1 x where
701 P x = f (C1 x)
702
703 f (P x) = C2 x
704
705 In this case, 'P' needs to be typechecked in two passes:
706
707 1. Typecheck the pattern definition of 'P', which fully determines the
708 type of 'P'. This step doesn't require knowing anything about 'f',
709 since the builder definition is not looked at.
710
711 2. Typecheck the builder definition, which needs the typechecked
712 definition of 'f' to be in scope.
713
714 This behaviour is implemented in 'tcValBinds', but it crucially
715 depends on 'P' not being put in a recursive group with 'f' (which
716 would make it look like a recursive pattern synonym a la 'pattern P =
717 P' which is unsound and rejected).
718
719 -}
720
721 {- *********************************************************************
722 * *
723 Class/instance method bindings
724 * *
725 ********************************************************************* -}
726
727 {- @rnMethodBinds@ is used for the method bindings of a class and an instance
728 declaration. Like @rnBinds@ but without dependency analysis.
729
730 NOTA BENE: we record each {\em binder} of a method-bind group as a free variable.
731 That's crucial when dealing with an instance decl:
732 \begin{verbatim}
733 instance Foo (T a) where
734 op x = ...
735 \end{verbatim}
736 This might be the {\em sole} occurrence of @op@ for an imported class @Foo@,
737 and unless @op@ occurs we won't treat the type signature of @op@ in the class
738 decl for @Foo@ as a source of instance-decl gates. But we should! Indeed,
739 in many ways the @op@ in an instance decl is just like an occurrence, not
740 a binder.
741 -}
742
743 rnMethodBinds :: Bool -- True <=> is a class declaration
744 -> Name -- Class name
745 -> [Name] -- Type variables from the class/instance header
746 -> LHsBinds RdrName -- Binds
747 -> [LSig RdrName] -- and signatures/pragmas
748 -> RnM (LHsBinds Name, [LSig Name], FreeVars)
749 -- Used for
750 -- * the default method bindings in a class decl
751 -- * the method bindings in an instance decl
752 rnMethodBinds is_cls_decl cls ktv_names binds sigs
753 = do { checkDupRdrNames (collectMethodBinders binds)
754 -- Check that the same method is not given twice in the
755 -- same instance decl instance C T where
756 -- f x = ...
757 -- g y = ...
758 -- f x = ...
759 -- We must use checkDupRdrNames because the Name of the
760 -- method is the Name of the class selector, whose SrcSpan
761 -- points to the class declaration; and we use rnMethodBinds
762 -- for instance decls too
763
764 -- Rename the bindings LHSs
765 ; binds' <- foldrBagM (rnMethodBindLHS is_cls_decl cls) emptyBag binds
766
767 -- Rename the pragmas and signatures
768 -- Annoyingly the type variables /are/ in scope for signatures, but
769 -- /are not/ in scope in the SPECIALISE instance pramas; e.g.
770 -- instance Eq a => Eq (T a) where
771 -- (==) :: a -> a -> a
772 -- {-# SPECIALISE instance Eq a => Eq (T [a]) #-}
773 ; let (spec_inst_prags, other_sigs) = partition isSpecInstLSig sigs
774 bound_nms = mkNameSet (collectHsBindsBinders binds')
775 sig_ctxt | is_cls_decl = ClsDeclCtxt cls
776 | otherwise = InstDeclCtxt bound_nms
777 ; (spec_inst_prags', sip_fvs) <- renameSigs sig_ctxt spec_inst_prags
778 ; (other_sigs', sig_fvs) <- extendTyVarEnvFVRn ktv_names $
779 renameSigs sig_ctxt other_sigs
780
781 -- Rename the bindings RHSs. Again there's an issue about whether the
782 -- type variables from the class/instance head are in scope.
783 -- Answer no in Haskell 2010, but yes if you have -XScopedTypeVariables
784 ; scoped_tvs <- xoptM Opt_ScopedTypeVariables
785 ; (binds'', bind_fvs) <- maybe_extend_tyvar_env scoped_tvs $
786 do { binds_w_dus <- mapBagM (rnLBind (mkSigTvFn other_sigs')) binds'
787 ; let bind_fvs = foldrBag (\(_,_,fv1) fv2 -> fv1 `plusFV` fv2)
788 emptyFVs binds_w_dus
789 ; return (mapBag fstOf3 binds_w_dus, bind_fvs) }
790
791 ; return ( binds'', spec_inst_prags' ++ other_sigs'
792 , sig_fvs `plusFV` sip_fvs `plusFV` bind_fvs) }
793 where
794 -- For the method bindings in class and instance decls, we extend
795 -- the type variable environment iff -XScopedTypeVariables
796 maybe_extend_tyvar_env scoped_tvs thing_inside
797 | scoped_tvs = extendTyVarEnvFVRn ktv_names thing_inside
798 | otherwise = thing_inside
799
800 rnMethodBindLHS :: Bool -> Name
801 -> LHsBindLR RdrName RdrName
802 -> LHsBindsLR Name RdrName
803 -> RnM (LHsBindsLR Name RdrName)
804 rnMethodBindLHS _ cls (L loc bind@(FunBind { fun_id = name })) rest
805 = setSrcSpan loc $ do
806 do { sel_name <- wrapLocM (lookupInstDeclBndr cls (ptext (sLit "method"))) name
807 -- We use the selector name as the binder
808 ; let bind' = bind { fun_id = sel_name
809 , bind_fvs = placeHolderNamesTc }
810
811 ; return (L loc bind' `consBag` rest ) }
812
813 -- Report error for all other forms of bindings
814 -- This is why we use a fold rather than map
815 rnMethodBindLHS is_cls_decl _ (L loc bind) rest
816 = do { addErrAt loc $
817 vcat [ what <+> ptext (sLit "not allowed in") <+> decl_sort
818 , nest 2 (ppr bind) ]
819 ; return rest }
820 where
821 decl_sort | is_cls_decl = ptext (sLit "class declaration:")
822 | otherwise = ptext (sLit "instance declaration:")
823 what = case bind of
824 PatBind {} -> ptext (sLit "Pattern bindings (except simple variables)")
825 PatSynBind {} -> ptext (sLit "Pattern synonyms")
826 -- Associated pattern synonyms are not implemented yet
827 _ -> pprPanic "rnMethodBind" (ppr bind)
828
829 {-
830 ************************************************************************
831 * *
832 \subsubsection[dep-Sigs]{Signatures (and user-pragmas for values)}
833 * *
834 ************************************************************************
835
836 @renameSigs@ checks for:
837 \begin{enumerate}
838 \item more than one sig for one thing;
839 \item signatures given for things not bound here;
840 \end{enumerate}
841
842 At the moment we don't gather free-var info from the types in
843 signatures. We'd only need this if we wanted to report unused tyvars.
844 -}
845
846 renameSigs :: HsSigCtxt
847 -> [LSig RdrName]
848 -> RnM ([LSig Name], FreeVars)
849 -- Renames the signatures and performs error checks
850 renameSigs ctxt sigs
851 = do { mapM_ dupSigDeclErr (findDupSigs sigs)
852
853 ; checkDupMinimalSigs sigs
854
855 ; (sigs', sig_fvs) <- mapFvRn (wrapLocFstM (renameSig ctxt)) sigs
856
857 ; let (good_sigs, bad_sigs) = partition (okHsSig ctxt) sigs'
858 ; mapM_ misplacedSigErr bad_sigs -- Misplaced
859
860 ; return (good_sigs, sig_fvs) }
861
862 ----------------------
863 -- We use lookupSigOccRn in the signatures, which is a little bit unsatisfactory
864 -- because this won't work for:
865 -- instance Foo T where
866 -- {-# INLINE op #-}
867 -- Baz.op = ...
868 -- We'll just rename the INLINE prag to refer to whatever other 'op'
869 -- is in scope. (I'm assuming that Baz.op isn't in scope unqualified.)
870 -- Doesn't seem worth much trouble to sort this.
871
872 renameSig :: HsSigCtxt -> Sig RdrName -> RnM (Sig Name, FreeVars)
873 -- FixitySig is renamed elsewhere.
874 renameSig _ (IdSig x)
875 = return (IdSig x, emptyFVs) -- Actually this never occurs
876
877 renameSig ctxt sig@(TypeSig vs ty)
878 = do { new_vs <- mapM (lookupSigOccRn ctxt sig) vs
879 ; let doc = TypeSigCtx (ppr_sig_bndrs vs)
880 ; (new_ty, fvs) <- rnHsSigWcType doc ty
881 ; return (TypeSig new_vs new_ty, fvs) }
882
883 renameSig ctxt sig@(ClassOpSig is_deflt vs ty)
884 = do { defaultSigs_on <- xoptM Opt_DefaultSignatures
885 ; when (is_deflt && not defaultSigs_on) $
886 addErr (defaultSigErr sig)
887 ; new_v <- mapM (lookupSigOccRn ctxt sig) vs
888 ; (new_ty, fvs) <- rnHsSigType ty_ctxt ty
889 ; return (ClassOpSig is_deflt new_v new_ty, fvs) }
890 where
891 (v1:_) = vs
892 ty_ctxt = GenericCtx (ptext (sLit "a class method signature for")
893 <+> quotes (ppr v1))
894
895 renameSig _ (SpecInstSig src ty)
896 = do { (new_ty, fvs) <- rnHsSigType SpecInstSigCtx ty
897 ; return (SpecInstSig src new_ty,fvs) }
898
899 -- {-# SPECIALISE #-} pragmas can refer to imported Ids
900 -- so, in the top-level case (when mb_names is Nothing)
901 -- we use lookupOccRn. If there's both an imported and a local 'f'
902 -- then the SPECIALISE pragma is ambiguous, unlike all other signatures
903 renameSig ctxt sig@(SpecSig v tys inl)
904 = do { new_v <- case ctxt of
905 TopSigCtxt {} -> lookupLocatedOccRn v
906 _ -> lookupSigOccRn ctxt sig v
907 ; (new_ty, fvs) <- foldM do_one ([],emptyFVs) tys
908 ; return (SpecSig new_v new_ty inl, fvs) }
909 where
910 ty_ctxt = GenericCtx (ptext (sLit "a SPECIALISE signature for")
911 <+> quotes (ppr v))
912 do_one (tys,fvs) ty
913 = do { (new_ty, fvs_ty) <- rnHsSigType ty_ctxt ty
914 ; return ( new_ty:tys, fvs_ty `plusFV` fvs) }
915
916 renameSig ctxt sig@(InlineSig v s)
917 = do { new_v <- lookupSigOccRn ctxt sig v
918 ; return (InlineSig new_v s, emptyFVs) }
919
920 renameSig ctxt sig@(FixSig (FixitySig vs f))
921 = do { new_vs <- mapM (lookupSigOccRn ctxt sig) vs
922 ; return (FixSig (FixitySig new_vs f), emptyFVs) }
923
924 renameSig ctxt sig@(MinimalSig s (L l bf))
925 = do new_bf <- traverse (lookupSigOccRn ctxt sig) bf
926 return (MinimalSig s (L l new_bf), emptyFVs)
927
928 renameSig ctxt sig@(PatSynSig v ty)
929 = do { v' <- lookupSigOccRn ctxt sig v
930 ; (ty', fvs) <- rnHsSigType ty_ctxt ty
931 ; return (PatSynSig v' ty', fvs) }
932 where
933 ty_ctxt = GenericCtx (ptext (sLit "a pattern synonym signature for")
934 <+> quotes (ppr v))
935
936 ppr_sig_bndrs :: [Located RdrName] -> SDoc
937 ppr_sig_bndrs bs = quotes (pprWithCommas ppr bs)
938
939 okHsSig :: HsSigCtxt -> LSig a -> Bool
940 okHsSig ctxt (L _ sig)
941 = case (sig, ctxt) of
942 (ClassOpSig {}, ClsDeclCtxt {}) -> True
943 (ClassOpSig {}, InstDeclCtxt {}) -> True
944 (ClassOpSig {}, _) -> False
945
946 (TypeSig {}, ClsDeclCtxt {}) -> False
947 (TypeSig {}, InstDeclCtxt {}) -> False
948 (TypeSig {}, _) -> True
949
950 (PatSynSig {}, TopSigCtxt{}) -> True
951 (PatSynSig {}, _) -> False
952
953 (FixSig {}, InstDeclCtxt {}) -> False
954 (FixSig {}, _) -> True
955
956 (IdSig {}, TopSigCtxt {}) -> True
957 (IdSig {}, InstDeclCtxt {}) -> True
958 (IdSig {}, _) -> False
959
960 (InlineSig {}, HsBootCtxt) -> False
961 (InlineSig {}, _) -> True
962
963 (SpecSig {}, TopSigCtxt {}) -> True
964 (SpecSig {}, LocalBindCtxt {}) -> True
965 (SpecSig {}, InstDeclCtxt {}) -> True
966 (SpecSig {}, _) -> False
967
968 (SpecInstSig {}, InstDeclCtxt {}) -> True
969 (SpecInstSig {}, _) -> False
970
971 (MinimalSig {}, ClsDeclCtxt {}) -> True
972 (MinimalSig {}, _) -> False
973
974 -------------------
975 findDupSigs :: [LSig RdrName] -> [[(Located RdrName, Sig RdrName)]]
976 -- Check for duplicates on RdrName version,
977 -- because renamed version has unboundName for
978 -- not-in-scope binders, which gives bogus dup-sig errors
979 -- NB: in a class decl, a 'generic' sig is not considered
980 -- equal to an ordinary sig, so we allow, say
981 -- class C a where
982 -- op :: a -> a
983 -- default op :: Eq a => a -> a
984 findDupSigs sigs
985 = findDupsEq matching_sig (concatMap (expand_sig . unLoc) sigs)
986 where
987 expand_sig sig@(FixSig (FixitySig ns _)) = zip ns (repeat sig)
988 expand_sig sig@(InlineSig n _) = [(n,sig)]
989 expand_sig sig@(TypeSig ns _) = [(n,sig) | n <- ns]
990 expand_sig sig@(ClassOpSig _ ns _) = [(n,sig) | n <- ns]
991 expand_sig _ = []
992
993 matching_sig (L _ n1,sig1) (L _ n2,sig2) = n1 == n2 && mtch sig1 sig2
994 mtch (FixSig {}) (FixSig {}) = True
995 mtch (InlineSig {}) (InlineSig {}) = True
996 mtch (TypeSig {}) (TypeSig {}) = True
997 mtch (ClassOpSig d1 _ _) (ClassOpSig d2 _ _) = d1 == d2
998 mtch _ _ = False
999
1000 -- Warn about multiple MINIMAL signatures
1001 checkDupMinimalSigs :: [LSig RdrName] -> RnM ()
1002 checkDupMinimalSigs sigs
1003 = case filter isMinimalLSig sigs of
1004 minSigs@(_:_:_) -> dupMinimalSigErr minSigs
1005 _ -> return ()
1006
1007 {-
1008 ************************************************************************
1009 * *
1010 \subsection{Match}
1011 * *
1012 ************************************************************************
1013 -}
1014
1015 rnMatchGroup :: Outputable (body RdrName) => HsMatchContext Name
1016 -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
1017 -> MatchGroup RdrName (Located (body RdrName))
1018 -> RnM (MatchGroup Name (Located (body Name)), FreeVars)
1019 rnMatchGroup ctxt rnBody (MG { mg_alts = L _ ms, mg_origin = origin })
1020 = do { empty_case_ok <- xoptM Opt_EmptyCase
1021 ; when (null ms && not empty_case_ok) (addErr (emptyCaseErr ctxt))
1022 ; (new_ms, ms_fvs) <- mapFvRn (rnMatch ctxt rnBody) ms
1023 ; return (mkMatchGroupName origin new_ms, ms_fvs) }
1024
1025 rnMatch :: Outputable (body RdrName) => HsMatchContext Name
1026 -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
1027 -> LMatch RdrName (Located (body RdrName))
1028 -> RnM (LMatch Name (Located (body Name)), FreeVars)
1029 rnMatch ctxt rnBody = wrapLocFstM (rnMatch' ctxt rnBody)
1030
1031 rnMatch' :: Outputable (body RdrName) => HsMatchContext Name
1032 -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
1033 -> Match RdrName (Located (body RdrName))
1034 -> RnM (Match Name (Located (body Name)), FreeVars)
1035 rnMatch' ctxt rnBody match@(Match { m_fixity = mf, m_pats = pats
1036 , m_type = maybe_rhs_sig, m_grhss = grhss })
1037 = do { -- Result type signatures are no longer supported
1038 case maybe_rhs_sig of
1039 Nothing -> return ()
1040 Just (L loc ty) -> addErrAt loc (resSigErr ctxt match ty)
1041
1042 ; let isinfix = isInfixMatch match
1043 -- Now the main event
1044 -- Note that there are no local fixity decls for matches
1045 ; rnPats ctxt pats $ \ pats' -> do
1046 { (grhss', grhss_fvs) <- rnGRHSs ctxt rnBody grhss
1047 ; let mf' = case (ctxt,mf) of
1048 (FunRhs funid,FunBindMatch (L lf _) _)
1049 -> FunBindMatch (L lf funid) isinfix
1050 _ -> NonFunBindMatch
1051 ; return (Match { m_fixity = mf', m_pats = pats'
1052 , m_type = Nothing, m_grhss = grhss'}, grhss_fvs ) }}
1053
1054 emptyCaseErr :: HsMatchContext Name -> SDoc
1055 emptyCaseErr ctxt = hang (ptext (sLit "Empty list of alternatives in") <+> pp_ctxt)
1056 2 (ptext (sLit "Use EmptyCase to allow this"))
1057 where
1058 pp_ctxt = case ctxt of
1059 CaseAlt -> ptext (sLit "case expression")
1060 LambdaExpr -> ptext (sLit "\\case expression")
1061 _ -> ptext (sLit "(unexpected)") <+> pprMatchContextNoun ctxt
1062
1063
1064 resSigErr :: Outputable body
1065 => HsMatchContext Name -> Match RdrName body -> HsType RdrName -> SDoc
1066 resSigErr ctxt match ty
1067 = vcat [ ptext (sLit "Illegal result type signature") <+> quotes (ppr ty)
1068 , nest 2 $ ptext (sLit
1069 "Result signatures are no longer supported in pattern matches")
1070 , pprMatchInCtxt ctxt match ]
1071
1072 {-
1073 ************************************************************************
1074 * *
1075 \subsubsection{Guarded right-hand sides (GRHSs)}
1076 * *
1077 ************************************************************************
1078 -}
1079
1080 rnGRHSs :: HsMatchContext Name
1081 -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
1082 -> GRHSs RdrName (Located (body RdrName))
1083 -> RnM (GRHSs Name (Located (body Name)), FreeVars)
1084 rnGRHSs ctxt rnBody (GRHSs grhss (L l binds))
1085 = rnLocalBindsAndThen binds $ \ binds' _ -> do
1086 (grhss', fvGRHSs) <- mapFvRn (rnGRHS ctxt rnBody) grhss
1087 return (GRHSs grhss' (L l binds'), fvGRHSs)
1088
1089 rnGRHS :: HsMatchContext Name
1090 -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
1091 -> LGRHS RdrName (Located (body RdrName))
1092 -> RnM (LGRHS Name (Located (body Name)), FreeVars)
1093 rnGRHS ctxt rnBody = wrapLocFstM (rnGRHS' ctxt rnBody)
1094
1095 rnGRHS' :: HsMatchContext Name
1096 -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
1097 -> GRHS RdrName (Located (body RdrName))
1098 -> RnM (GRHS Name (Located (body Name)), FreeVars)
1099 rnGRHS' ctxt rnBody (GRHS guards rhs)
1100 = do { pattern_guards_allowed <- xoptM Opt_PatternGuards
1101 ; ((guards', rhs'), fvs) <- rnStmts (PatGuard ctxt) rnLExpr guards $ \ _ ->
1102 rnBody rhs
1103
1104 ; unless (pattern_guards_allowed || is_standard_guard guards')
1105 (addWarn (nonStdGuardErr guards'))
1106
1107 ; return (GRHS guards' rhs', fvs) }
1108 where
1109 -- Standard Haskell 1.4 guards are just a single boolean
1110 -- expression, rather than a list of qualifiers as in the
1111 -- Glasgow extension
1112 is_standard_guard [] = True
1113 is_standard_guard [L _ (BodyStmt _ _ _ _)] = True
1114 is_standard_guard _ = False
1115
1116 {-
1117 ************************************************************************
1118 * *
1119 \subsection{Error messages}
1120 * *
1121 ************************************************************************
1122 -}
1123
1124 dupSigDeclErr :: [(Located RdrName, Sig RdrName)] -> RnM ()
1125 dupSigDeclErr pairs@((L loc name, sig) : _)
1126 = addErrAt loc $
1127 vcat [ ptext (sLit "Duplicate") <+> what_it_is
1128 <> ptext (sLit "s for") <+> quotes (ppr name)
1129 , ptext (sLit "at") <+> vcat (map ppr $ sort $ map (getLoc . fst) pairs) ]
1130 where
1131 what_it_is = hsSigDoc sig
1132
1133 dupSigDeclErr [] = panic "dupSigDeclErr"
1134
1135 misplacedSigErr :: LSig Name -> RnM ()
1136 misplacedSigErr (L loc sig)
1137 = addErrAt loc $
1138 sep [ptext (sLit "Misplaced") <+> hsSigDoc sig <> colon, ppr sig]
1139
1140 defaultSigErr :: Sig RdrName -> SDoc
1141 defaultSigErr sig = vcat [ hang (ptext (sLit "Unexpected default signature:"))
1142 2 (ppr sig)
1143 , ptext (sLit "Use DefaultSignatures to enable default signatures") ]
1144
1145 bindsInHsBootFile :: LHsBindsLR Name RdrName -> SDoc
1146 bindsInHsBootFile mbinds
1147 = hang (ptext (sLit "Bindings in hs-boot files are not allowed"))
1148 2 (ppr mbinds)
1149
1150 nonStdGuardErr :: Outputable body => [LStmtLR Name Name body] -> SDoc
1151 nonStdGuardErr guards
1152 = hang (ptext (sLit "accepting non-standard pattern guards (use PatternGuards to suppress this message)"))
1153 4 (interpp'SP guards)
1154
1155 unusedPatBindWarn :: HsBind Name -> SDoc
1156 unusedPatBindWarn bind
1157 = hang (ptext (sLit "This pattern-binding binds no variables:"))
1158 2 (ppr bind)
1159
1160 dupMinimalSigErr :: [LSig RdrName] -> RnM ()
1161 dupMinimalSigErr sigs@(L loc _ : _)
1162 = addErrAt loc $
1163 vcat [ ptext (sLit "Multiple minimal complete definitions")
1164 , ptext (sLit "at") <+> vcat (map ppr $ sort $ map getLoc sigs)
1165 , ptext (sLit "Combine alternative minimal complete definitions with `|'") ]
1166 dupMinimalSigErr [] = panic "dupMinimalSigErr"