nonmoving: Drop redundant write barrier on stack underflow
[ghc.git] / compiler / rename / RnEnv.hs
1 {-
2 (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
3
4 RnEnv contains functions which convert RdrNames into Names.
5
6 -}
7
8 {-# LANGUAGE CPP, MultiWayIf, NamedFieldPuns #-}
9
10 module RnEnv (
11 newTopSrcBinder,
12 lookupLocatedTopBndrRn, lookupTopBndrRn,
13 lookupLocatedOccRn, lookupOccRn, lookupOccRn_maybe,
14 lookupLocalOccRn_maybe, lookupInfoOccRn,
15 lookupLocalOccThLvl_maybe, lookupLocalOccRn,
16 lookupTypeOccRn,
17 lookupGlobalOccRn, lookupGlobalOccRn_maybe,
18 lookupOccRn_overloaded, lookupGlobalOccRn_overloaded, lookupExactOcc,
19
20 ChildLookupResult(..),
21 lookupSubBndrOcc_helper,
22 combineChildLookupResult, -- Called by lookupChildrenExport
23
24 HsSigCtxt(..), lookupLocalTcNames, lookupSigOccRn,
25 lookupSigCtxtOccRn,
26
27 lookupInstDeclBndr, lookupRecFieldOcc, lookupFamInstName,
28 lookupConstructorFields,
29
30 lookupGreAvailRn,
31
32 -- Rebindable Syntax
33 lookupSyntaxName, lookupSyntaxName', lookupSyntaxNames,
34 lookupIfThenElse,
35
36 -- Constructing usage information
37 addUsedGRE, addUsedGREs, addUsedDataCons,
38
39
40
41 dataTcOccs, --TODO: Move this somewhere, into utils?
42
43 ) where
44
45 #include "HsVersions.h"
46
47 import GhcPrelude
48
49 import LoadIface ( loadInterfaceForName, loadSrcInterface_maybe )
50 import IfaceEnv
51 import GHC.Hs
52 import RdrName
53 import HscTypes
54 import TcEnv
55 import TcRnMonad
56 import RdrHsSyn ( filterCTuple, setRdrNameSpace )
57 import TysWiredIn
58 import Name
59 import NameSet
60 import NameEnv
61 import Avail
62 import Module
63 import ConLike
64 import DataCon
65 import TyCon
66 import ErrUtils ( MsgDoc )
67 import PrelNames ( rOOT_MAIN )
68 import BasicTypes ( pprWarningTxtForMsg, TopLevelFlag(..))
69 import SrcLoc
70 import Outputable
71 import UniqSet ( uniqSetAny )
72 import Util
73 import Maybes
74 import DynFlags
75 import FastString
76 import Control.Monad
77 import ListSetOps ( minusList )
78 import qualified GHC.LanguageExtensions as LangExt
79 import RnUnbound
80 import RnUtils
81 import qualified Data.Semigroup as Semi
82 import Data.Either ( partitionEithers )
83 import Data.List (find)
84
85 {-
86 *********************************************************
87 * *
88 Source-code binders
89 * *
90 *********************************************************
91
92 Note [Signature lazy interface loading]
93 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
94
95 GHC's lazy interface loading can be a bit confusing, so this Note is an
96 empirical description of what happens in one interesting case. When
97 compiling a signature module against an its implementation, we do NOT
98 load interface files associated with its names until after the type
99 checking phase. For example:
100
101 module ASig where
102 data T
103 f :: T -> T
104
105 Suppose we compile this with -sig-of "A is ASig":
106
107 module B where
108 data T = T
109 f T = T
110
111 module A(module B) where
112 import B
113
114 During type checking, we'll load A.hi because we need to know what the
115 RdrEnv for the module is, but we DO NOT load the interface for B.hi!
116 It's wholly unnecessary: our local definition 'data T' in ASig is all
117 the information we need to finish type checking. This is contrast to
118 type checking of ordinary Haskell files, in which we would not have the
119 local definition "data T" and would need to consult B.hi immediately.
120 (Also, this situation never occurs for hs-boot files, since you're not
121 allowed to reexport from another module.)
122
123 After type checking, we then check that the types we provided are
124 consistent with the backing implementation (in checkHiBootOrHsigIface).
125 At this point, B.hi is loaded, because we need something to compare
126 against.
127
128 I discovered this behavior when trying to figure out why type class
129 instances for Data.Map weren't in the EPS when I was type checking a
130 test very much like ASig (sigof02dm): the associated interface hadn't
131 been loaded yet! (The larger issue is a moot point, since an instance
132 declared in a signature can never be a duplicate.)
133
134 This behavior might change in the future. Consider this
135 alternate module B:
136
137 module B where
138 {-# DEPRECATED T, f "Don't use" #-}
139 data T = T
140 f T = T
141
142 One might conceivably want to report deprecation warnings when compiling
143 ASig with -sig-of B, in which case we need to look at B.hi to find the
144 deprecation warnings during renaming. At the moment, you don't get any
145 warning until you use the identifier further downstream. This would
146 require adjusting addUsedGRE so that during signature compilation,
147 we do not report deprecation warnings for LocalDef. See also
148 Note [Handling of deprecations]
149 -}
150
151 newTopSrcBinder :: Located RdrName -> RnM Name
152 newTopSrcBinder (L loc rdr_name)
153 | Just name <- isExact_maybe rdr_name
154 = -- This is here to catch
155 -- (a) Exact-name binders created by Template Haskell
156 -- (b) The PrelBase defn of (say) [] and similar, for which
157 -- the parser reads the special syntax and returns an Exact RdrName
158 -- We are at a binding site for the name, so check first that it
159 -- the current module is the correct one; otherwise GHC can get
160 -- very confused indeed. This test rejects code like
161 -- data T = (,) Int Int
162 -- unless we are in GHC.Tup
163 if isExternalName name then
164 do { this_mod <- getModule
165 ; unless (this_mod == nameModule name)
166 (addErrAt loc (badOrigBinding rdr_name))
167 ; return name }
168 else -- See Note [Binders in Template Haskell] in Convert.hs
169 do { this_mod <- getModule
170 ; externaliseName this_mod name }
171
172 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
173 = do { this_mod <- getModule
174 ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
175 (addErrAt loc (badOrigBinding rdr_name))
176 -- When reading External Core we get Orig names as binders,
177 -- but they should agree with the module gotten from the monad
178 --
179 -- We can get built-in syntax showing up here too, sadly. If you type
180 -- data T = (,,,)
181 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
182 -- uses setRdrNameSpace to make it into a data constructors. At that point
183 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
184 -- Hence the badOrigBinding error message.
185 --
186 -- Except for the ":Main.main = ..." definition inserted into
187 -- the Main module; ugh!
188
189 -- Because of this latter case, we call newGlobalBinder with a module from
190 -- the RdrName, not from the environment. In principle, it'd be fine to
191 -- have an arbitrary mixture of external core definitions in a single module,
192 -- (apart from module-initialisation issues, perhaps).
193 ; newGlobalBinder rdr_mod rdr_occ loc }
194
195 | otherwise
196 = do { when (isQual rdr_name)
197 (addErrAt loc (badQualBndrErr rdr_name))
198 -- Binders should not be qualified; if they are, and with a different
199 -- module name, we get a confusing "M.T is not in scope" error later
200
201 ; stage <- getStage
202 ; if isBrackStage stage then
203 -- We are inside a TH bracket, so make an *Internal* name
204 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
205 do { uniq <- newUnique
206 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
207 else
208 do { this_mod <- getModule
209 ; traceRn "newTopSrcBinder" (ppr this_mod $$ ppr rdr_name $$ ppr loc)
210 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
211 }
212
213 {-
214 *********************************************************
215 * *
216 Source code occurrences
217 * *
218 *********************************************************
219
220 Looking up a name in the RnEnv.
221
222 Note [Type and class operator definitions]
223 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
224 We want to reject all of these unless we have -XTypeOperators (#3265)
225 data a :*: b = ...
226 class a :*: b where ...
227 data (:*:) a b = ....
228 class (:*:) a b where ...
229 The latter two mean that we are not just looking for a
230 *syntactically-infix* declaration, but one that uses an operator
231 OccName. We use OccName.isSymOcc to detect that case, which isn't
232 terribly efficient, but there seems to be no better way.
233 -}
234
235 -- Can be made to not be exposed
236 -- Only used unwrapped in rnAnnProvenance
237 lookupTopBndrRn :: RdrName -> RnM Name
238 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
239 case nopt of
240 Just n' -> return n'
241 Nothing -> do traceRn "lookupTopBndrRn fail" (ppr n)
242 unboundName WL_LocalTop n
243
244 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
245 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
246
247 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
248 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
249 -- and there may be several imported 'f's too, which must not confuse us.
250 -- For example, this is OK:
251 -- import Foo( f )
252 -- infix 9 f -- The 'f' here does not need to be qualified
253 -- f x = x -- Nor here, of course
254 -- So we have to filter out the non-local ones.
255 --
256 -- A separate function (importsFromLocalDecls) reports duplicate top level
257 -- decls, so here it's safe just to choose an arbitrary one.
258 --
259 -- There should never be a qualified name in a binding position in Haskell,
260 -- but there can be if we have read in an external-Core file.
261 -- The Haskell parser checks for the illegal qualified name in Haskell
262 -- source files, so we don't need to do so here.
263
264 lookupTopBndrRn_maybe rdr_name =
265 lookupExactOrOrig rdr_name Just $
266 do { -- Check for operators in type or class declarations
267 -- See Note [Type and class operator definitions]
268 let occ = rdrNameOcc rdr_name
269 ; when (isTcOcc occ && isSymOcc occ)
270 (do { op_ok <- xoptM LangExt.TypeOperators
271 ; unless op_ok (addErr (opDeclErr rdr_name)) })
272
273 ; env <- getGlobalRdrEnv
274 ; case filter isLocalGRE (lookupGRE_RdrName rdr_name env) of
275 [gre] -> return (Just (gre_name gre))
276 _ -> return Nothing -- Ambiguous (can't happen) or unbound
277 }
278
279 -----------------------------------------------
280 -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
281 -- This adds an error if the name cannot be found.
282 lookupExactOcc :: Name -> RnM Name
283 lookupExactOcc name
284 = do { result <- lookupExactOcc_either name
285 ; case result of
286 Left err -> do { addErr err
287 ; return name }
288 Right name' -> return name' }
289
290 -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
291 -- This never adds an error, but it may return one.
292 lookupExactOcc_either :: Name -> RnM (Either MsgDoc Name)
293 -- See Note [Looking up Exact RdrNames]
294 lookupExactOcc_either name
295 | Just thing <- wiredInNameTyThing_maybe name
296 , Just tycon <- case thing of
297 ATyCon tc -> Just tc
298 AConLike (RealDataCon dc) -> Just (dataConTyCon dc)
299 _ -> Nothing
300 , isTupleTyCon tycon
301 = do { checkTupSize (tyConArity tycon)
302 ; return (Right name) }
303
304 | isExternalName name
305 = return (Right name)
306
307 | otherwise
308 = do { env <- getGlobalRdrEnv
309 ; let -- See Note [Splicing Exact names]
310 main_occ = nameOccName name
311 demoted_occs = case demoteOccName main_occ of
312 Just occ -> [occ]
313 Nothing -> []
314 gres = [ gre | occ <- main_occ : demoted_occs
315 , gre <- lookupGlobalRdrEnv env occ
316 , gre_name gre == name ]
317 ; case gres of
318 [gre] -> return (Right (gre_name gre))
319
320 [] -> -- See Note [Splicing Exact names]
321 do { lcl_env <- getLocalRdrEnv
322 ; if name `inLocalRdrEnvScope` lcl_env
323 then return (Right name)
324 else
325 do { th_topnames_var <- fmap tcg_th_topnames getGblEnv
326 ; th_topnames <- readTcRef th_topnames_var
327 ; if name `elemNameSet` th_topnames
328 then return (Right name)
329 else return (Left exact_nm_err)
330 }
331 }
332 gres -> return (Left (sameNameErr gres)) -- Ugh! See Note [Template Haskell ambiguity]
333 }
334 where
335 exact_nm_err = hang (text "The exact Name" <+> quotes (ppr name) <+> ptext (sLit "is not in scope"))
336 2 (vcat [ text "Probable cause: you used a unique Template Haskell name (NameU), "
337 , text "perhaps via newName, but did not bind it"
338 , text "If that's it, then -ddump-splices might be useful" ])
339
340 sameNameErr :: [GlobalRdrElt] -> MsgDoc
341 sameNameErr [] = panic "addSameNameErr: empty list"
342 sameNameErr gres@(_ : _)
343 = hang (text "Same exact name in multiple name-spaces:")
344 2 (vcat (map pp_one sorted_names) $$ th_hint)
345 where
346 sorted_names = sortWith nameSrcLoc (map gre_name gres)
347 pp_one name
348 = hang (pprNameSpace (occNameSpace (getOccName name))
349 <+> quotes (ppr name) <> comma)
350 2 (text "declared at:" <+> ppr (nameSrcLoc name))
351
352 th_hint = vcat [ text "Probable cause: you bound a unique Template Haskell name (NameU),"
353 , text "perhaps via newName, in different name-spaces."
354 , text "If that's it, then -ddump-splices might be useful" ]
355
356
357 -----------------------------------------------
358 lookupInstDeclBndr :: Name -> SDoc -> RdrName -> RnM Name
359 -- This is called on the method name on the left-hand side of an
360 -- instance declaration binding. eg. instance Functor T where
361 -- fmap = ...
362 -- ^^^^ called on this
363 -- Regardless of how many unqualified fmaps are in scope, we want
364 -- the one that comes from the Functor class.
365 --
366 -- Furthermore, note that we take no account of whether the
367 -- name is only in scope qualified. I.e. even if method op is
368 -- in scope as M.op, we still allow plain 'op' on the LHS of
369 -- an instance decl
370 --
371 -- The "what" parameter says "method" or "associated type",
372 -- depending on what we are looking up
373 lookupInstDeclBndr cls what rdr
374 = do { when (isQual rdr)
375 (addErr (badQualBndrErr rdr))
376 -- In an instance decl you aren't allowed
377 -- to use a qualified name for the method
378 -- (Although it'd make perfect sense.)
379 ; mb_name <- lookupSubBndrOcc
380 False -- False => we don't give deprecated
381 -- warnings when a deprecated class
382 -- method is defined. We only warn
383 -- when it's used
384 cls doc rdr
385 ; case mb_name of
386 Left err -> do { addErr err; return (mkUnboundNameRdr rdr) }
387 Right nm -> return nm }
388 where
389 doc = what <+> text "of class" <+> quotes (ppr cls)
390
391 -----------------------------------------------
392 lookupFamInstName :: Maybe Name -> Located RdrName
393 -> RnM (Located Name)
394 -- Used for TyData and TySynonym family instances only,
395 -- See Note [Family instance binders]
396 lookupFamInstName (Just cls) tc_rdr -- Associated type; c.f RnBinds.rnMethodBind
397 = wrapLocM (lookupInstDeclBndr cls (text "associated type")) tc_rdr
398 lookupFamInstName Nothing tc_rdr -- Family instance; tc_rdr is an *occurrence*
399 = lookupLocatedOccRn tc_rdr
400
401 -----------------------------------------------
402 lookupConstructorFields :: Name -> RnM [FieldLabel]
403 -- Look up the fields of a given constructor
404 -- * For constructors from this module, use the record field env,
405 -- which is itself gathered from the (as yet un-typechecked)
406 -- data type decls
407 --
408 -- * For constructors from imported modules, use the *type* environment
409 -- since imported modles are already compiled, the info is conveniently
410 -- right there
411
412 lookupConstructorFields con_name
413 = do { this_mod <- getModule
414 ; if nameIsLocalOrFrom this_mod con_name then
415 do { field_env <- getRecFieldEnv
416 ; traceTc "lookupCF" (ppr con_name $$ ppr (lookupNameEnv field_env con_name) $$ ppr field_env)
417 ; return (lookupNameEnv field_env con_name `orElse` []) }
418 else
419 do { con <- tcLookupConLike con_name
420 ; traceTc "lookupCF 2" (ppr con)
421 ; return (conLikeFieldLabels con) } }
422
423
424 -- In CPS style as `RnM r` is monadic
425 lookupExactOrOrig :: RdrName -> (Name -> r) -> RnM r -> RnM r
426 lookupExactOrOrig rdr_name res k
427 | Just n <- isExact_maybe rdr_name -- This happens in derived code
428 = res <$> lookupExactOcc n
429 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
430 = res <$> lookupOrig rdr_mod rdr_occ
431 | otherwise = k
432
433
434
435 -----------------------------------------------
436 -- | Look up an occurrence of a field in record construction or pattern
437 -- matching (but not update). When the -XDisambiguateRecordFields
438 -- flag is on, take account of the data constructor name to
439 -- disambiguate which field to use.
440 --
441 -- See Note [DisambiguateRecordFields].
442 lookupRecFieldOcc :: Maybe Name -- Nothing => just look it up as usual
443 -- Just con => use data con to disambiguate
444 -> RdrName
445 -> RnM Name
446 lookupRecFieldOcc mb_con rdr_name
447 | Just con <- mb_con
448 , isUnboundName con -- Avoid error cascade
449 = return (mkUnboundNameRdr rdr_name)
450 | Just con <- mb_con
451 = do { flds <- lookupConstructorFields con
452 ; env <- getGlobalRdrEnv
453 ; let lbl = occNameFS (rdrNameOcc rdr_name)
454 mb_field = do fl <- find ((== lbl) . flLabel) flds
455 -- We have the label, now check it is in
456 -- scope (with the correct qualifier if
457 -- there is one, hence calling pickGREs).
458 gre <- lookupGRE_FieldLabel env fl
459 guard (not (isQual rdr_name
460 && null (pickGREs rdr_name [gre])))
461 return (fl, gre)
462 ; case mb_field of
463 Just (fl, gre) -> do { addUsedGRE True gre
464 ; return (flSelector fl) }
465 Nothing -> lookupGlobalOccRn rdr_name }
466 -- See Note [Fall back on lookupGlobalOccRn in lookupRecFieldOcc]
467 | otherwise
468 -- This use of Global is right as we are looking up a selector which
469 -- can only be defined at the top level.
470 = lookupGlobalOccRn rdr_name
471
472 {- Note [DisambiguateRecordFields]
473 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
474 When we are looking up record fields in record construction or pattern
475 matching, we can take advantage of the data constructor name to
476 resolve fields that would otherwise be ambiguous (provided the
477 -XDisambiguateRecordFields flag is on).
478
479 For example, consider:
480
481 data S = MkS { x :: Int }
482 data T = MkT { x :: Int }
483
484 e = MkS { x = 3 }
485
486 When we are renaming the occurrence of `x` in `e`, instead of looking
487 `x` up directly (and finding both fields), lookupRecFieldOcc will
488 search the fields of `MkS` to find the only possible `x` the user can
489 mean.
490
491 Of course, we still have to check the field is in scope, using
492 lookupGRE_FieldLabel. The handling of qualified imports is slightly
493 subtle: the occurrence may be unqualified even if the field is
494 imported only qualified (but if the occurrence is qualified, the
495 qualifier must be correct). For example:
496
497 module A where
498 data S = MkS { x :: Int }
499 data T = MkT { x :: Int }
500
501 module B where
502 import qualified A (S(..))
503 import A (T(MkT))
504
505 e1 = MkT { x = 3 } -- x not in scope, so fail
506 e2 = A.MkS { B.x = 3 } -- module qualifier is wrong, so fail
507 e3 = A.MkS { x = 3 } -- x in scope (lack of module qualifier permitted)
508
509 In case `e1`, lookupGRE_FieldLabel will return Nothing. In case `e2`,
510 lookupGRE_FieldLabel will return the GRE for `A.x`, but then the guard
511 will fail because the field RdrName `B.x` is qualified and pickGREs
512 rejects the GRE. In case `e3`, lookupGRE_FieldLabel will return the
513 GRE for `A.x` and the guard will succeed because the field RdrName `x`
514 is unqualified.
515
516
517 Note [Fall back on lookupGlobalOccRn in lookupRecFieldOcc]
518 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
519 Whenever we fail to find the field or it is not in scope, mb_field
520 will be False, and we fall back on looking it up normally using
521 lookupGlobalOccRn. We don't report an error immediately because the
522 actual problem might be located elsewhere. For example (#9975):
523
524 data Test = Test { x :: Int }
525 pattern Test wat = Test { x = wat }
526
527 Here there are multiple declarations of Test (as a data constructor
528 and as a pattern synonym), which will be reported as an error. We
529 shouldn't also report an error about the occurrence of `x` in the
530 pattern synonym RHS. However, if the pattern synonym gets added to
531 the environment first, we will try and fail to find `x` amongst the
532 (nonexistent) fields of the pattern synonym.
533
534 Alternatively, the scope check can fail due to Template Haskell.
535 Consider (#12130):
536
537 module Foo where
538 import M
539 b = $(funny)
540
541 module M(funny) where
542 data T = MkT { x :: Int }
543 funny :: Q Exp
544 funny = [| MkT { x = 3 } |]
545
546 When we splice, `MkT` is not lexically in scope, so
547 lookupGRE_FieldLabel will fail. But there is no need for
548 disambiguation anyway, because `x` is an original name, and
549 lookupGlobalOccRn will find it.
550 -}
551
552
553
554 -- | Used in export lists to lookup the children.
555 lookupSubBndrOcc_helper :: Bool -> Bool -> Name -> RdrName
556 -> RnM ChildLookupResult
557 lookupSubBndrOcc_helper must_have_parent warn_if_deprec parent rdr_name
558 | isUnboundName parent
559 -- Avoid an error cascade
560 = return (FoundName NoParent (mkUnboundNameRdr rdr_name))
561
562 | otherwise = do
563 gre_env <- getGlobalRdrEnv
564
565 let original_gres = lookupGlobalRdrEnv gre_env (rdrNameOcc rdr_name)
566 -- Disambiguate the lookup based on the parent information.
567 -- The remaining GREs are things that we *could* export here, note that
568 -- this includes things which have `NoParent`. Those are sorted in
569 -- `checkPatSynParent`.
570 traceRn "parent" (ppr parent)
571 traceRn "lookupExportChild original_gres:" (ppr original_gres)
572 traceRn "lookupExportChild picked_gres:" (ppr $ picked_gres original_gres)
573 case picked_gres original_gres of
574 NoOccurrence ->
575 noMatchingParentErr original_gres
576 UniqueOccurrence g ->
577 if must_have_parent then noMatchingParentErr original_gres
578 else checkFld g
579 DisambiguatedOccurrence g ->
580 checkFld g
581 AmbiguousOccurrence gres ->
582 mkNameClashErr gres
583 where
584 -- Convert into FieldLabel if necessary
585 checkFld :: GlobalRdrElt -> RnM ChildLookupResult
586 checkFld g@GRE{gre_name, gre_par} = do
587 addUsedGRE warn_if_deprec g
588 return $ case gre_par of
589 FldParent _ mfs ->
590 FoundFL (fldParentToFieldLabel gre_name mfs)
591 _ -> FoundName gre_par gre_name
592
593 fldParentToFieldLabel :: Name -> Maybe FastString -> FieldLabel
594 fldParentToFieldLabel name mfs =
595 case mfs of
596 Nothing ->
597 let fs = occNameFS (nameOccName name)
598 in FieldLabel fs False name
599 Just fs -> FieldLabel fs True name
600
601 -- Called when we find no matching GREs after disambiguation but
602 -- there are three situations where this happens.
603 -- 1. There were none to begin with.
604 -- 2. None of the matching ones were the parent but
605 -- a. They were from an overloaded record field so we can report
606 -- a better error
607 -- b. The original lookup was actually ambiguous.
608 -- For example, the case where overloading is off and two
609 -- record fields are in scope from different record
610 -- constructors, neither of which is the parent.
611 noMatchingParentErr :: [GlobalRdrElt] -> RnM ChildLookupResult
612 noMatchingParentErr original_gres = do
613 overload_ok <- xoptM LangExt.DuplicateRecordFields
614 case original_gres of
615 [] -> return NameNotFound
616 [g] -> return $ IncorrectParent parent
617 (gre_name g) (ppr $ gre_name g)
618 [p | Just p <- [getParent g]]
619 gss@(g:_:_) ->
620 if all isRecFldGRE gss && overload_ok
621 then return $
622 IncorrectParent parent
623 (gre_name g)
624 (ppr $ expectJust "noMatchingParentErr" (greLabel g))
625 [p | x <- gss, Just p <- [getParent x]]
626 else mkNameClashErr gss
627
628 mkNameClashErr :: [GlobalRdrElt] -> RnM ChildLookupResult
629 mkNameClashErr gres = do
630 addNameClashErrRn rdr_name gres
631 return (FoundName (gre_par (head gres)) (gre_name (head gres)))
632
633 getParent :: GlobalRdrElt -> Maybe Name
634 getParent (GRE { gre_par = p } ) =
635 case p of
636 ParentIs cur_parent -> Just cur_parent
637 FldParent { par_is = cur_parent } -> Just cur_parent
638 NoParent -> Nothing
639
640 picked_gres :: [GlobalRdrElt] -> DisambigInfo
641 -- For Unqual, find GREs that are in scope qualified or unqualified
642 -- For Qual, find GREs that are in scope with that qualification
643 picked_gres gres
644 | isUnqual rdr_name
645 = mconcat (map right_parent gres)
646 | otherwise
647 = mconcat (map right_parent (pickGREs rdr_name gres))
648
649 right_parent :: GlobalRdrElt -> DisambigInfo
650 right_parent p
651 = case getParent p of
652 Just cur_parent
653 | parent == cur_parent -> DisambiguatedOccurrence p
654 | otherwise -> NoOccurrence
655 Nothing -> UniqueOccurrence p
656
657
658 -- This domain specific datatype is used to record why we decided it was
659 -- possible that a GRE could be exported with a parent.
660 data DisambigInfo
661 = NoOccurrence
662 -- The GRE could never be exported. It has the wrong parent.
663 | UniqueOccurrence GlobalRdrElt
664 -- The GRE has no parent. It could be a pattern synonym.
665 | DisambiguatedOccurrence GlobalRdrElt
666 -- The parent of the GRE is the correct parent
667 | AmbiguousOccurrence [GlobalRdrElt]
668 -- For example, two normal identifiers with the same name are in
669 -- scope. They will both be resolved to "UniqueOccurrence" and the
670 -- monoid will combine them to this failing case.
671
672 instance Outputable DisambigInfo where
673 ppr NoOccurrence = text "NoOccurence"
674 ppr (UniqueOccurrence gre) = text "UniqueOccurrence:" <+> ppr gre
675 ppr (DisambiguatedOccurrence gre) = text "DiambiguatedOccurrence:" <+> ppr gre
676 ppr (AmbiguousOccurrence gres) = text "Ambiguous:" <+> ppr gres
677
678 instance Semi.Semigroup DisambigInfo where
679 -- This is the key line: We prefer disambiguated occurrences to other
680 -- names.
681 _ <> DisambiguatedOccurrence g' = DisambiguatedOccurrence g'
682 DisambiguatedOccurrence g' <> _ = DisambiguatedOccurrence g'
683
684 NoOccurrence <> m = m
685 m <> NoOccurrence = m
686 UniqueOccurrence g <> UniqueOccurrence g'
687 = AmbiguousOccurrence [g, g']
688 UniqueOccurrence g <> AmbiguousOccurrence gs
689 = AmbiguousOccurrence (g:gs)
690 AmbiguousOccurrence gs <> UniqueOccurrence g'
691 = AmbiguousOccurrence (g':gs)
692 AmbiguousOccurrence gs <> AmbiguousOccurrence gs'
693 = AmbiguousOccurrence (gs ++ gs')
694
695 instance Monoid DisambigInfo where
696 mempty = NoOccurrence
697 mappend = (Semi.<>)
698
699 -- Lookup SubBndrOcc can never be ambiguous
700 --
701 -- Records the result of looking up a child.
702 data ChildLookupResult
703 = NameNotFound -- We couldn't find a suitable name
704 | IncorrectParent Name -- Parent
705 Name -- Name of thing we were looking for
706 SDoc -- How to print the name
707 [Name] -- List of possible parents
708 | FoundName Parent Name -- We resolved to a normal name
709 | FoundFL FieldLabel -- We resolved to a FL
710
711 -- | Specialised version of msum for RnM ChildLookupResult
712 combineChildLookupResult :: [RnM ChildLookupResult] -> RnM ChildLookupResult
713 combineChildLookupResult [] = return NameNotFound
714 combineChildLookupResult (x:xs) = do
715 res <- x
716 case res of
717 NameNotFound -> combineChildLookupResult xs
718 _ -> return res
719
720 instance Outputable ChildLookupResult where
721 ppr NameNotFound = text "NameNotFound"
722 ppr (FoundName p n) = text "Found:" <+> ppr p <+> ppr n
723 ppr (FoundFL fls) = text "FoundFL:" <+> ppr fls
724 ppr (IncorrectParent p n td ns) = text "IncorrectParent"
725 <+> hsep [ppr p, ppr n, td, ppr ns]
726
727 lookupSubBndrOcc :: Bool
728 -> Name -- Parent
729 -> SDoc
730 -> RdrName
731 -> RnM (Either MsgDoc Name)
732 -- Find all the things the rdr-name maps to
733 -- and pick the one with the right parent namep
734 lookupSubBndrOcc warn_if_deprec the_parent doc rdr_name = do
735 res <-
736 lookupExactOrOrig rdr_name (FoundName NoParent) $
737 -- This happens for built-in classes, see mod052 for example
738 lookupSubBndrOcc_helper True warn_if_deprec the_parent rdr_name
739 case res of
740 NameNotFound -> return (Left (unknownSubordinateErr doc rdr_name))
741 FoundName _p n -> return (Right n)
742 FoundFL fl -> return (Right (flSelector fl))
743 IncorrectParent {}
744 -- See [Mismatched class methods and associated type families]
745 -- in TcInstDecls.
746 -> return $ Left (unknownSubordinateErr doc rdr_name)
747
748 {-
749 Note [Family instance binders]
750 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
751 Consider
752 data family F a
753 data instance F T = X1 | X2
754
755 The 'data instance' decl has an *occurrence* of F (and T), and *binds*
756 X1 and X2. (This is unlike a normal data type declaration which would
757 bind F too.) So we want an AvailTC F [X1,X2].
758
759 Now consider a similar pair:
760 class C a where
761 data G a
762 instance C S where
763 data G S = Y1 | Y2
764
765 The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G.
766
767 But there is a small complication: in an instance decl, we don't use
768 qualified names on the LHS; instead we use the class to disambiguate.
769 Thus:
770 module M where
771 import Blib( G )
772 class C a where
773 data G a
774 instance C S where
775 data G S = Y1 | Y2
776 Even though there are two G's in scope (M.G and Blib.G), the occurrence
777 of 'G' in the 'instance C S' decl is unambiguous, because C has only
778 one associated type called G. This is exactly what happens for methods,
779 and it is only consistent to do the same thing for types. That's the
780 role of the function lookupTcdName; the (Maybe Name) give the class of
781 the encloseing instance decl, if any.
782
783 Note [Looking up Exact RdrNames]
784 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
785 Exact RdrNames are generated by Template Haskell. See Note [Binders
786 in Template Haskell] in Convert.
787
788 For data types and classes have Exact system Names in the binding
789 positions for constructors, TyCons etc. For example
790 [d| data T = MkT Int |]
791 when we splice in and Convert to HsSyn RdrName, we'll get
792 data (Exact (system Name "T")) = (Exact (system Name "MkT")) ...
793 These System names are generated by Convert.thRdrName
794
795 But, constructors and the like need External Names, not System Names!
796 So we do the following
797
798 * In RnEnv.newTopSrcBinder we spot Exact RdrNames that wrap a
799 non-External Name, and make an External name for it. This is
800 the name that goes in the GlobalRdrEnv
801
802 * When looking up an occurrence of an Exact name, done in
803 RnEnv.lookupExactOcc, we find the Name with the right unique in the
804 GlobalRdrEnv, and use the one from the envt -- it will be an
805 External Name in the case of the data type/constructor above.
806
807 * Exact names are also use for purely local binders generated
808 by TH, such as \x_33. x_33
809 Both binder and occurrence are Exact RdrNames. The occurrence
810 gets looked up in the LocalRdrEnv by RnEnv.lookupOccRn, and
811 misses, because lookupLocalRdrEnv always returns Nothing for
812 an Exact Name. Now we fall through to lookupExactOcc, which
813 will find the Name is not in the GlobalRdrEnv, so we just use
814 the Exact supplied Name.
815
816 Note [Splicing Exact names]
817 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
818 Consider the splice $(do { x <- newName "x"; return (VarE x) })
819 This will generate a (HsExpr RdrName) term that mentions the
820 Exact RdrName "x_56" (or whatever), but does not bind it. So
821 when looking such Exact names we want to check that it's in scope,
822 otherwise the type checker will get confused. To do this we need to
823 keep track of all the Names in scope, and the LocalRdrEnv does just that;
824 we consult it with RdrName.inLocalRdrEnvScope.
825
826 There is another wrinkle. With TH and -XDataKinds, consider
827 $( [d| data Nat = Zero
828 data T = MkT (Proxy 'Zero) |] )
829 After splicing, but before renaming we get this:
830 data Nat_77{tc} = Zero_78{d}
831 data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc}) |] )
832 The occurrence of 'Zero in the data type for T has the right unique,
833 but it has a TcClsName name-space in its OccName. (This is set by
834 the ctxt_ns argument of Convert.thRdrName.) When we check that is
835 in scope in the GlobalRdrEnv, we need to look up the DataName namespace
836 too. (An alternative would be to make the GlobalRdrEnv also have
837 a Name -> GRE mapping.)
838
839 Note [Template Haskell ambiguity]
840 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
841 The GlobalRdrEnv invariant says that if
842 occ -> [gre1, ..., gren]
843 then the gres have distinct Names (INVARIANT 1 of GlobalRdrEnv).
844 This is guaranteed by extendGlobalRdrEnvRn (the dups check in add_gre).
845
846 So how can we get multiple gres in lookupExactOcc_maybe? Because in
847 TH we might use the same TH NameU in two different name spaces.
848 eg (#7241):
849 $(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]])
850 Here we generate a type constructor and data constructor with the same
851 unique, but different name spaces.
852
853 It'd be nicer to rule this out in extendGlobalRdrEnvRn, but that would
854 mean looking up the OccName in every name-space, just in case, and that
855 seems a bit brutal. So it's just done here on lookup. But we might
856 need to revisit that choice.
857
858 Note [Usage for sub-bndrs]
859 ~~~~~~~~~~~~~~~~~~~~~~~~~~
860 If you have this
861 import qualified M( C( f ) )
862 instance M.C T where
863 f x = x
864 then is the qualified import M.f used? Obviously yes.
865 But the RdrName used in the instance decl is unqualified. In effect,
866 we fill in the qualification by looking for f's whose class is M.C
867 But when adding to the UsedRdrNames we must make that qualification
868 explicit (saying "used M.f"), otherwise we get "Redundant import of M.f".
869
870 So we make up a suitable (fake) RdrName. But be careful
871 import qualified M
872 import M( C(f) )
873 instance C T where
874 f x = x
875 Here we want to record a use of 'f', not of 'M.f', otherwise
876 we'll miss the fact that the qualified import is redundant.
877
878 --------------------------------------------------
879 -- Occurrences
880 --------------------------------------------------
881 -}
882
883
884 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
885 lookupLocatedOccRn = wrapLocM lookupOccRn
886
887 lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name)
888 -- Just look in the local environment
889 lookupLocalOccRn_maybe rdr_name
890 = do { local_env <- getLocalRdrEnv
891 ; return (lookupLocalRdrEnv local_env rdr_name) }
892
893 lookupLocalOccThLvl_maybe :: Name -> RnM (Maybe (TopLevelFlag, ThLevel))
894 -- Just look in the local environment
895 lookupLocalOccThLvl_maybe name
896 = do { lcl_env <- getLclEnv
897 ; return (lookupNameEnv (tcl_th_bndrs lcl_env) name) }
898
899 -- lookupOccRn looks up an occurrence of a RdrName
900 lookupOccRn :: RdrName -> RnM Name
901 lookupOccRn rdr_name
902 = do { mb_name <- lookupOccRn_maybe rdr_name
903 ; case mb_name of
904 Just name -> return name
905 Nothing -> reportUnboundName rdr_name }
906
907 -- Only used in one place, to rename pattern synonym binders.
908 -- See Note [Renaming pattern synonym variables] in RnBinds
909 lookupLocalOccRn :: RdrName -> RnM Name
910 lookupLocalOccRn rdr_name
911 = do { mb_name <- lookupLocalOccRn_maybe rdr_name
912 ; case mb_name of
913 Just name -> return name
914 Nothing -> unboundName WL_LocalOnly rdr_name }
915
916 -- lookupPromotedOccRn looks up an optionally promoted RdrName.
917 lookupTypeOccRn :: RdrName -> RnM Name
918 -- see Note [Demotion]
919 lookupTypeOccRn rdr_name
920 | isVarOcc (rdrNameOcc rdr_name) -- See Note [Promoted variables in types]
921 = badVarInType rdr_name
922 | otherwise
923 = do { mb_name <- lookupOccRn_maybe rdr_name
924 ; case mb_name of
925 Just name -> return name
926 Nothing -> lookup_demoted rdr_name }
927
928 lookup_demoted :: RdrName -> RnM Name
929 lookup_demoted rdr_name
930 | Just demoted_rdr <- demoteRdrName rdr_name
931 -- Maybe it's the name of a *data* constructor
932 = do { data_kinds <- xoptM LangExt.DataKinds
933 ; star_is_type <- xoptM LangExt.StarIsType
934 ; let star_info = starInfo star_is_type rdr_name
935 ; if data_kinds
936 then do { mb_demoted_name <- lookupOccRn_maybe demoted_rdr
937 ; case mb_demoted_name of
938 Nothing -> unboundNameX WL_Any rdr_name star_info
939 Just demoted_name ->
940 do { whenWOptM Opt_WarnUntickedPromotedConstructors $
941 addWarn
942 (Reason Opt_WarnUntickedPromotedConstructors)
943 (untickedPromConstrWarn demoted_name)
944 ; return demoted_name } }
945 else do { -- We need to check if a data constructor of this name is
946 -- in scope to give good error messages. However, we do
947 -- not want to give an additional error if the data
948 -- constructor happens to be out of scope! See #13947.
949 mb_demoted_name <- discardErrs $
950 lookupOccRn_maybe demoted_rdr
951 ; let suggestion | isJust mb_demoted_name = suggest_dk
952 | otherwise = star_info
953 ; unboundNameX WL_Any rdr_name suggestion } }
954
955 | otherwise
956 = reportUnboundName rdr_name
957
958 where
959 suggest_dk = text "A data constructor of that name is in scope; did you mean DataKinds?"
960 untickedPromConstrWarn name =
961 text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot
962 $$
963 hsep [ text "Use"
964 , quotes (char '\'' <> ppr name)
965 , text "instead of"
966 , quotes (ppr name) <> dot ]
967
968 badVarInType :: RdrName -> RnM Name
969 badVarInType rdr_name
970 = do { addErr (text "Illegal promoted term variable in a type:"
971 <+> ppr rdr_name)
972 ; return (mkUnboundNameRdr rdr_name) }
973
974 {- Note [Promoted variables in types]
975 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
976 Consider this (#12686):
977 x = True
978 data Bad = Bad 'x
979
980 The parser treats the quote in 'x as saying "use the term
981 namespace", so we'll get (Bad x{v}), with 'x' in the
982 VarName namespace. If we don't test for this, the renamer
983 will happily rename it to the x bound at top level, and then
984 the typecheck falls over because it doesn't have 'x' in scope
985 when kind-checking.
986
987 Note [Demotion]
988 ~~~~~~~~~~~~~~~
989 When the user writes:
990 data Nat = Zero | Succ Nat
991 foo :: f Zero -> Int
992
993 'Zero' in the type signature of 'foo' is parsed as:
994 HsTyVar ("Zero", TcClsName)
995
996 When the renamer hits this occurrence of 'Zero' it's going to realise
997 that it's not in scope. But because it is renaming a type, it knows
998 that 'Zero' might be a promoted data constructor, so it will demote
999 its namespace to DataName and do a second lookup.
1000
1001 The final result (after the renamer) will be:
1002 HsTyVar ("Zero", DataName)
1003 -}
1004
1005 lookupOccRnX_maybe :: (RdrName -> RnM (Maybe r)) -> (Name -> r) -> RdrName
1006 -> RnM (Maybe r)
1007 lookupOccRnX_maybe globalLookup wrapper rdr_name
1008 = runMaybeT . msum . map MaybeT $
1009 [ fmap wrapper <$> lookupLocalOccRn_maybe rdr_name
1010 , globalLookup rdr_name ]
1011
1012 lookupOccRn_maybe :: RdrName -> RnM (Maybe Name)
1013 lookupOccRn_maybe = lookupOccRnX_maybe lookupGlobalOccRn_maybe id
1014
1015 lookupOccRn_overloaded :: Bool -> RdrName
1016 -> RnM (Maybe (Either Name [Name]))
1017 lookupOccRn_overloaded overload_ok
1018 = lookupOccRnX_maybe global_lookup Left
1019 where
1020 global_lookup :: RdrName -> RnM (Maybe (Either Name [Name]))
1021 global_lookup n =
1022 runMaybeT . msum . map MaybeT $
1023 [ lookupGlobalOccRn_overloaded overload_ok n
1024 , fmap Left . listToMaybe <$> lookupQualifiedNameGHCi n ]
1025
1026
1027
1028 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
1029 -- Looks up a RdrName occurrence in the top-level
1030 -- environment, including using lookupQualifiedNameGHCi
1031 -- for the GHCi case
1032 -- No filter function; does not report an error on failure
1033 -- Uses addUsedRdrName to record use and deprecations
1034 lookupGlobalOccRn_maybe rdr_name =
1035 lookupExactOrOrig rdr_name Just $
1036 runMaybeT . msum . map MaybeT $
1037 [ fmap gre_name <$> lookupGreRn_maybe rdr_name
1038 , listToMaybe <$> lookupQualifiedNameGHCi rdr_name ]
1039 -- This test is not expensive,
1040 -- and only happens for failed lookups
1041
1042 lookupGlobalOccRn :: RdrName -> RnM Name
1043 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
1044 -- environment. Adds an error message if the RdrName is not in scope.
1045 -- You usually want to use "lookupOccRn" which also looks in the local
1046 -- environment.
1047 lookupGlobalOccRn rdr_name
1048 = do { mb_name <- lookupGlobalOccRn_maybe rdr_name
1049 ; case mb_name of
1050 Just n -> return n
1051 Nothing -> do { traceRn "lookupGlobalOccRn" (ppr rdr_name)
1052 ; unboundName WL_Global rdr_name } }
1053
1054 lookupInfoOccRn :: RdrName -> RnM [Name]
1055 -- lookupInfoOccRn is intended for use in GHCi's ":info" command
1056 -- It finds all the GREs that RdrName could mean, not complaining
1057 -- about ambiguity, but rather returning them all
1058 -- C.f. #9881
1059 lookupInfoOccRn rdr_name =
1060 lookupExactOrOrig rdr_name (:[]) $
1061 do { rdr_env <- getGlobalRdrEnv
1062 ; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env)
1063 ; qual_ns <- lookupQualifiedNameGHCi rdr_name
1064 ; return (ns ++ (qual_ns `minusList` ns)) }
1065
1066 -- | Like 'lookupOccRn_maybe', but with a more informative result if
1067 -- the 'RdrName' happens to be a record selector:
1068 --
1069 -- * Nothing -> name not in scope (no error reported)
1070 -- * Just (Left x) -> name uniquely refers to x,
1071 -- or there is a name clash (reported)
1072 -- * Just (Right xs) -> name refers to one or more record selectors;
1073 -- if overload_ok was False, this list will be
1074 -- a singleton.
1075
1076 lookupGlobalOccRn_overloaded :: Bool -> RdrName
1077 -> RnM (Maybe (Either Name [Name]))
1078 lookupGlobalOccRn_overloaded overload_ok rdr_name =
1079 lookupExactOrOrig rdr_name (Just . Left) $
1080 do { res <- lookupGreRn_helper rdr_name
1081 ; case res of
1082 GreNotFound -> return Nothing
1083 OneNameMatch gre -> do
1084 let wrapper = if isRecFldGRE gre then Right . (:[]) else Left
1085 return $ Just (wrapper (gre_name gre))
1086 MultipleNames gres | all isRecFldGRE gres && overload_ok ->
1087 -- Don't record usage for ambiguous selectors
1088 -- until we know which is meant
1089 return $ Just (Right (map gre_name gres))
1090 MultipleNames gres -> do
1091 addNameClashErrRn rdr_name gres
1092 return (Just (Left (gre_name (head gres)))) }
1093
1094
1095 --------------------------------------------------
1096 -- Lookup in the Global RdrEnv of the module
1097 --------------------------------------------------
1098
1099 data GreLookupResult = GreNotFound
1100 | OneNameMatch GlobalRdrElt
1101 | MultipleNames [GlobalRdrElt]
1102
1103 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
1104 -- Look up the RdrName in the GlobalRdrEnv
1105 -- Exactly one binding: records it as "used", return (Just gre)
1106 -- No bindings: return Nothing
1107 -- Many bindings: report "ambiguous", return an arbitrary (Just gre)
1108 -- Uses addUsedRdrName to record use and deprecations
1109 lookupGreRn_maybe rdr_name
1110 = do
1111 res <- lookupGreRn_helper rdr_name
1112 case res of
1113 OneNameMatch gre -> return $ Just gre
1114 MultipleNames gres -> do
1115 traceRn "lookupGreRn_maybe:NameClash" (ppr gres)
1116 addNameClashErrRn rdr_name gres
1117 return $ Just (head gres)
1118 GreNotFound -> return Nothing
1119
1120 {-
1121
1122 Note [ Unbound vs Ambiguous Names ]
1123
1124 lookupGreRn_maybe deals with failures in two different ways. If a name
1125 is unbound then we return a `Nothing` but if the name is ambiguous
1126 then we raise an error and return a dummy name.
1127
1128 The reason for this is that when we call `lookupGreRn_maybe` we are
1129 speculatively looking for whatever we are looking up. If we don't find it,
1130 then we might have been looking for the wrong thing and can keep trying.
1131 On the other hand, if we find a clash then there is no way to recover as
1132 we found the thing we were looking for but can no longer resolve which
1133 the correct one is.
1134
1135 One example of this is in `lookupTypeOccRn` which first looks in the type
1136 constructor namespace before looking in the data constructor namespace to
1137 deal with `DataKinds`.
1138
1139 There is however, as always, one exception to this scheme. If we find
1140 an ambiguous occurence of a record selector and DuplicateRecordFields
1141 is enabled then we defer the selection until the typechecker.
1142
1143 -}
1144
1145
1146
1147
1148 -- Internal Function
1149 lookupGreRn_helper :: RdrName -> RnM GreLookupResult
1150 lookupGreRn_helper rdr_name
1151 = do { env <- getGlobalRdrEnv
1152 ; case lookupGRE_RdrName rdr_name env of
1153 [] -> return GreNotFound
1154 [gre] -> do { addUsedGRE True gre
1155 ; return (OneNameMatch gre) }
1156 gres -> return (MultipleNames gres) }
1157
1158 lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo)
1159 -- Used in export lists
1160 -- If not found or ambiguous, add error message, and fake with UnboundName
1161 -- Uses addUsedRdrName to record use and deprecations
1162 lookupGreAvailRn rdr_name
1163 = do
1164 mb_gre <- lookupGreRn_helper rdr_name
1165 case mb_gre of
1166 GreNotFound ->
1167 do
1168 traceRn "lookupGreAvailRn" (ppr rdr_name)
1169 name <- unboundName WL_Global rdr_name
1170 return (name, avail name)
1171 MultipleNames gres ->
1172 do
1173 addNameClashErrRn rdr_name gres
1174 let unbound_name = mkUnboundNameRdr rdr_name
1175 return (unbound_name, avail unbound_name)
1176 -- Returning an unbound name here prevents an error
1177 -- cascade
1178 OneNameMatch gre ->
1179 return (gre_name gre, availFromGRE gre)
1180
1181
1182 {-
1183 *********************************************************
1184 * *
1185 Deprecations
1186 * *
1187 *********************************************************
1188
1189 Note [Handling of deprecations]
1190 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1191 * We report deprecations at each *occurrence* of the deprecated thing
1192 (see #5867)
1193
1194 * We do not report deprecations for locally-defined names. For a
1195 start, we may be exporting a deprecated thing. Also we may use a
1196 deprecated thing in the defn of another deprecated things. We may
1197 even use a deprecated thing in the defn of a non-deprecated thing,
1198 when changing a module's interface.
1199
1200 * addUsedGREs: we do not report deprecations for sub-binders:
1201 - the ".." completion for records
1202 - the ".." in an export item 'T(..)'
1203 - the things exported by a module export 'module M'
1204 -}
1205
1206 addUsedDataCons :: GlobalRdrEnv -> TyCon -> RnM ()
1207 -- Remember use of in-scope data constructors (#7969)
1208 addUsedDataCons rdr_env tycon
1209 = addUsedGREs [ gre
1210 | dc <- tyConDataCons tycon
1211 , Just gre <- [lookupGRE_Name rdr_env (dataConName dc)] ]
1212
1213 addUsedGRE :: Bool -> GlobalRdrElt -> RnM ()
1214 -- Called for both local and imported things
1215 -- Add usage *and* warn if deprecated
1216 addUsedGRE warn_if_deprec gre
1217 = do { when warn_if_deprec (warnIfDeprecated gre)
1218 ; unless (isLocalGRE gre) $
1219 do { env <- getGblEnv
1220 ; traceRn "addUsedGRE" (ppr gre)
1221 ; updMutVar (tcg_used_gres env) (gre :) } }
1222
1223 addUsedGREs :: [GlobalRdrElt] -> RnM ()
1224 -- Record uses of any *imported* GREs
1225 -- Used for recording used sub-bndrs
1226 -- NB: no call to warnIfDeprecated; see Note [Handling of deprecations]
1227 addUsedGREs gres
1228 | null imp_gres = return ()
1229 | otherwise = do { env <- getGblEnv
1230 ; traceRn "addUsedGREs" (ppr imp_gres)
1231 ; updMutVar (tcg_used_gres env) (imp_gres ++) }
1232 where
1233 imp_gres = filterOut isLocalGRE gres
1234
1235 warnIfDeprecated :: GlobalRdrElt -> RnM ()
1236 warnIfDeprecated gre@(GRE { gre_name = name, gre_imp = iss })
1237 | (imp_spec : _) <- iss
1238 = do { dflags <- getDynFlags
1239 ; this_mod <- getModule
1240 ; when (wopt Opt_WarnWarningsDeprecations dflags &&
1241 not (nameIsLocalOrFrom this_mod name)) $
1242 -- See Note [Handling of deprecations]
1243 do { iface <- loadInterfaceForName doc name
1244 ; case lookupImpDeprec iface gre of
1245 Just txt -> addWarn (Reason Opt_WarnWarningsDeprecations)
1246 (mk_msg imp_spec txt)
1247 Nothing -> return () } }
1248 | otherwise
1249 = return ()
1250 where
1251 occ = greOccName gre
1252 name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1253 doc = text "The name" <+> quotes (ppr occ) <+> ptext (sLit "is mentioned explicitly")
1254
1255 mk_msg imp_spec txt
1256 = sep [ sep [ text "In the use of"
1257 <+> pprNonVarNameSpace (occNameSpace occ)
1258 <+> quotes (ppr occ)
1259 , parens imp_msg <> colon ]
1260 , pprWarningTxtForMsg txt ]
1261 where
1262 imp_mod = importSpecModule imp_spec
1263 imp_msg = text "imported from" <+> ppr imp_mod <> extra
1264 extra | imp_mod == moduleName name_mod = Outputable.empty
1265 | otherwise = text ", but defined in" <+> ppr name_mod
1266
1267 lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt
1268 lookupImpDeprec iface gre
1269 = mi_warn_fn (mi_final_exts iface) (greOccName gre) `mplus` -- Bleat if the thing,
1270 case gre_par gre of -- or its parent, is warn'd
1271 ParentIs p -> mi_warn_fn (mi_final_exts iface) (nameOccName p)
1272 FldParent { par_is = p } -> mi_warn_fn (mi_final_exts iface) (nameOccName p)
1273 NoParent -> Nothing
1274
1275 {-
1276 Note [Used names with interface not loaded]
1277 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1278 It's (just) possible to find a used
1279 Name whose interface hasn't been loaded:
1280
1281 a) It might be a WiredInName; in that case we may not load
1282 its interface (although we could).
1283
1284 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1285 These are seen as "used" by the renamer (if -XRebindableSyntax)
1286 is on), but the typechecker may discard their uses
1287 if in fact the in-scope fromRational is GHC.Read.fromRational,
1288 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
1289 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1290 In that obscure case it won't force the interface in.
1291
1292 In both cases we simply don't permit deprecations;
1293 this is, after all, wired-in stuff.
1294
1295
1296 *********************************************************
1297 * *
1298 GHCi support
1299 * *
1300 *********************************************************
1301
1302 A qualified name on the command line can refer to any module at
1303 all: we try to load the interface if we don't already have it, just
1304 as if there was an "import qualified M" declaration for every
1305 module.
1306
1307 For example, writing `Data.List.sort` will load the interface file for
1308 `Data.List` as if the user had written `import qualified Data.List`.
1309
1310 If we fail we just return Nothing, rather than bleating
1311 about "attempting to use module ā€˜Dā€™ (./D.hs) which is not loaded"
1312 which is what loadSrcInterface does.
1313
1314 It is enabled by default and disabled by the flag
1315 `-fno-implicit-import-qualified`.
1316
1317 Note [Safe Haskell and GHCi]
1318 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1319 We DON'T do this Safe Haskell as we need to check imports. We can
1320 and should instead check the qualified import but at the moment
1321 this requires some refactoring so leave as a TODO
1322 -}
1323
1324
1325
1326 lookupQualifiedNameGHCi :: RdrName -> RnM [Name]
1327 lookupQualifiedNameGHCi rdr_name
1328 = -- We want to behave as we would for a source file import here,
1329 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
1330 do { dflags <- getDynFlags
1331 ; is_ghci <- getIsGHCi
1332 ; go_for_it dflags is_ghci }
1333
1334 where
1335 go_for_it dflags is_ghci
1336 | Just (mod,occ) <- isQual_maybe rdr_name
1337 , is_ghci
1338 , gopt Opt_ImplicitImportQualified dflags -- Enables this GHCi behaviour
1339 , not (safeDirectImpsReq dflags) -- See Note [Safe Haskell and GHCi]
1340 = do { res <- loadSrcInterface_maybe doc mod False Nothing
1341 ; case res of
1342 Succeeded iface
1343 -> return [ name
1344 | avail <- mi_exports iface
1345 , name <- availNames avail
1346 , nameOccName name == occ ]
1347
1348 _ -> -- Either we couldn't load the interface, or
1349 -- we could but we didn't find the name in it
1350 do { traceRn "lookupQualifiedNameGHCi" (ppr rdr_name)
1351 ; return [] } }
1352
1353 | otherwise
1354 = do { traceRn "lookupQualifiedNameGHCi: off" (ppr rdr_name)
1355 ; return [] }
1356
1357 doc = text "Need to find" <+> ppr rdr_name
1358
1359 {-
1360 Note [Looking up signature names]
1361 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1362 lookupSigOccRn is used for type signatures and pragmas
1363 Is this valid?
1364 module A
1365 import M( f )
1366 f :: Int -> Int
1367 f x = x
1368 It's clear that the 'f' in the signature must refer to A.f
1369 The Haskell98 report does not stipulate this, but it will!
1370 So we must treat the 'f' in the signature in the same way
1371 as the binding occurrence of 'f', using lookupBndrRn
1372
1373 However, consider this case:
1374 import M( f )
1375 f :: Int -> Int
1376 g x = x
1377 We don't want to say 'f' is out of scope; instead, we want to
1378 return the imported 'f', so that later on the renamer will
1379 correctly report "misplaced type sig".
1380
1381 Note [Signatures for top level things]
1382 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1383 data HsSigCtxt = ... | TopSigCtxt NameSet | ....
1384
1385 * The NameSet says what is bound in this group of bindings.
1386 We can't use isLocalGRE from the GlobalRdrEnv, because of this:
1387 f x = x
1388 $( ...some TH splice... )
1389 f :: Int -> Int
1390 When we encounter the signature for 'f', the binding for 'f'
1391 will be in the GlobalRdrEnv, and will be a LocalDef. Yet the
1392 signature is mis-placed
1393
1394 * For type signatures the NameSet should be the names bound by the
1395 value bindings; for fixity declarations, the NameSet should also
1396 include class sigs and record selectors
1397
1398 infix 3 `f` -- Yes, ok
1399 f :: C a => a -> a -- No, not ok
1400 class C a where
1401 f :: a -> a
1402 -}
1403
1404 data HsSigCtxt
1405 = TopSigCtxt NameSet -- At top level, binding these names
1406 -- See Note [Signatures for top level things]
1407 | LocalBindCtxt NameSet -- In a local binding, binding these names
1408 | ClsDeclCtxt Name -- Class decl for this class
1409 | InstDeclCtxt NameSet -- Instance decl whose user-written method
1410 -- bindings are for these methods
1411 | HsBootCtxt NameSet -- Top level of a hs-boot file, binding these names
1412 | RoleAnnotCtxt NameSet -- A role annotation, with the names of all types
1413 -- in the group
1414
1415 instance Outputable HsSigCtxt where
1416 ppr (TopSigCtxt ns) = text "TopSigCtxt" <+> ppr ns
1417 ppr (LocalBindCtxt ns) = text "LocalBindCtxt" <+> ppr ns
1418 ppr (ClsDeclCtxt n) = text "ClsDeclCtxt" <+> ppr n
1419 ppr (InstDeclCtxt ns) = text "InstDeclCtxt" <+> ppr ns
1420 ppr (HsBootCtxt ns) = text "HsBootCtxt" <+> ppr ns
1421 ppr (RoleAnnotCtxt ns) = text "RoleAnnotCtxt" <+> ppr ns
1422
1423 lookupSigOccRn :: HsSigCtxt
1424 -> Sig GhcPs
1425 -> Located RdrName -> RnM (Located Name)
1426 lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig)
1427
1428 -- | Lookup a name in relation to the names in a 'HsSigCtxt'
1429 lookupSigCtxtOccRn :: HsSigCtxt
1430 -> SDoc -- ^ description of thing we're looking up,
1431 -- like "type family"
1432 -> Located RdrName -> RnM (Located Name)
1433 lookupSigCtxtOccRn ctxt what
1434 = wrapLocM $ \ rdr_name ->
1435 do { mb_name <- lookupBindGroupOcc ctxt what rdr_name
1436 ; case mb_name of
1437 Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) }
1438 Right name -> return name }
1439
1440 lookupBindGroupOcc :: HsSigCtxt
1441 -> SDoc
1442 -> RdrName -> RnM (Either MsgDoc Name)
1443 -- Looks up the RdrName, expecting it to resolve to one of the
1444 -- bound names passed in. If not, return an appropriate error message
1445 --
1446 -- See Note [Looking up signature names]
1447 lookupBindGroupOcc ctxt what rdr_name
1448 | Just n <- isExact_maybe rdr_name
1449 = lookupExactOcc_either n -- allow for the possibility of missing Exacts;
1450 -- see Note [dataTcOccs and Exact Names]
1451 -- Maybe we should check the side conditions
1452 -- but it's a pain, and Exact things only show
1453 -- up when you know what you are doing
1454
1455 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
1456 = do { n' <- lookupOrig rdr_mod rdr_occ
1457 ; return (Right n') }
1458
1459 | otherwise
1460 = case ctxt of
1461 HsBootCtxt ns -> lookup_top (`elemNameSet` ns)
1462 TopSigCtxt ns -> lookup_top (`elemNameSet` ns)
1463 RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns)
1464 LocalBindCtxt ns -> lookup_group ns
1465 ClsDeclCtxt cls -> lookup_cls_op cls
1466 InstDeclCtxt ns -> if uniqSetAny isUnboundName ns -- #16610
1467 then return (Right $ mkUnboundNameRdr rdr_name)
1468 else lookup_top (`elemNameSet` ns)
1469 where
1470 lookup_cls_op cls
1471 = lookupSubBndrOcc True cls doc rdr_name
1472 where
1473 doc = text "method of class" <+> quotes (ppr cls)
1474
1475 lookup_top keep_me
1476 = do { env <- getGlobalRdrEnv
1477 ; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
1478 ; let candidates_msg = candidates $ map gre_name
1479 $ filter isLocalGRE
1480 $ globalRdrEnvElts env
1481 ; case filter (keep_me . gre_name) all_gres of
1482 [] | null all_gres -> bale_out_with candidates_msg
1483 | otherwise -> bale_out_with local_msg
1484 (gre:_) -> return (Right (gre_name gre)) }
1485
1486 lookup_group bound_names -- Look in the local envt (not top level)
1487 = do { mname <- lookupLocalOccRn_maybe rdr_name
1488 ; env <- getLocalRdrEnv
1489 ; let candidates_msg = candidates $ localRdrEnvElts env
1490 ; case mname of
1491 Just n
1492 | n `elemNameSet` bound_names -> return (Right n)
1493 | otherwise -> bale_out_with local_msg
1494 Nothing -> bale_out_with candidates_msg }
1495
1496 bale_out_with msg
1497 = return (Left (sep [ text "The" <+> what
1498 <+> text "for" <+> quotes (ppr rdr_name)
1499 , nest 2 $ text "lacks an accompanying binding"]
1500 $$ nest 2 msg))
1501
1502 local_msg = parens $ text "The" <+> what <+> ptext (sLit "must be given where")
1503 <+> quotes (ppr rdr_name) <+> text "is declared"
1504
1505 -- Identify all similar names and produce a message listing them
1506 candidates :: [Name] -> MsgDoc
1507 candidates names_in_scope
1508 = case similar_names of
1509 [] -> Outputable.empty
1510 [n] -> text "Perhaps you meant" <+> pp_item n
1511 _ -> sep [ text "Perhaps you meant one of these:"
1512 , nest 2 (pprWithCommas pp_item similar_names) ]
1513 where
1514 similar_names
1515 = fuzzyLookup (unpackFS $ occNameFS $ rdrNameOcc rdr_name)
1516 $ map (\x -> ((unpackFS $ occNameFS $ nameOccName x), x))
1517 names_in_scope
1518
1519 pp_item x = quotes (ppr x) <+> parens (pprDefinedAt x)
1520
1521
1522 ---------------
1523 lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [(RdrName, Name)]
1524 -- GHC extension: look up both the tycon and data con or variable.
1525 -- Used for top-level fixity signatures and deprecations.
1526 -- Complain if neither is in scope.
1527 -- See Note [Fixity signature lookup]
1528 lookupLocalTcNames ctxt what rdr_name
1529 = do { mb_gres <- mapM lookup (dataTcOccs rdr_name)
1530 ; let (errs, names) = partitionEithers mb_gres
1531 ; when (null names) $ addErr (head errs) -- Bleat about one only
1532 ; return names }
1533 where
1534 lookup rdr = do { this_mod <- getModule
1535 ; nameEither <- lookupBindGroupOcc ctxt what rdr
1536 ; return (guard_builtin_syntax this_mod rdr nameEither) }
1537
1538 -- Guard against the built-in syntax (ex: `infixl 6 :`), see #15233
1539 guard_builtin_syntax this_mod rdr (Right name)
1540 | Just _ <- isBuiltInOcc_maybe (occName rdr)
1541 , this_mod /= nameModule name
1542 = Left (hsep [text "Illegal", what, text "of built-in syntax:", ppr rdr])
1543 | otherwise
1544 = Right (rdr, name)
1545 guard_builtin_syntax _ _ (Left err) = Left err
1546
1547 dataTcOccs :: RdrName -> [RdrName]
1548 -- Return both the given name and the same name promoted to the TcClsName
1549 -- namespace. This is useful when we aren't sure which we are looking at.
1550 -- See also Note [dataTcOccs and Exact Names]
1551 dataTcOccs rdr_name
1552 | isDataOcc occ || isVarOcc occ
1553 = [rdr_name, rdr_name_tc]
1554 | otherwise
1555 = [rdr_name]
1556 where
1557 occ = rdrNameOcc rdr_name
1558 rdr_name_tc = setRdrNameSpace rdr_name tcName
1559
1560 {-
1561 Note [dataTcOccs and Exact Names]
1562 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1563 Exact RdrNames can occur in code generated by Template Haskell, and generally
1564 those references are, well, exact. However, the TH `Name` type isn't expressive
1565 enough to always track the correct namespace information, so we sometimes get
1566 the right Unique but wrong namespace. Thus, we still have to do the double-lookup
1567 for Exact RdrNames.
1568
1569 There is also an awkward situation for built-in syntax. Example in GHCi
1570 :info []
1571 This parses as the Exact RdrName for nilDataCon, but we also want
1572 the list type constructor.
1573
1574 Note that setRdrNameSpace on an Exact name requires the Name to be External,
1575 which it always is for built in syntax.
1576 -}
1577
1578
1579
1580 {-
1581 ************************************************************************
1582 * *
1583 Rebindable names
1584 Dealing with rebindable syntax is driven by the
1585 Opt_RebindableSyntax dynamic flag.
1586
1587 In "deriving" code we don't want to use rebindable syntax
1588 so we switch off the flag locally
1589
1590 * *
1591 ************************************************************************
1592
1593 Haskell 98 says that when you say "3" you get the "fromInteger" from the
1594 Standard Prelude, regardless of what is in scope. However, to experiment
1595 with having a language that is less coupled to the standard prelude, we're
1596 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
1597 happens to be in scope. Then you can
1598 import Prelude ()
1599 import MyPrelude as Prelude
1600 to get the desired effect.
1601
1602 At the moment this just happens for
1603 * fromInteger, fromRational on literals (in expressions and patterns)
1604 * negate (in expressions)
1605 * minus (arising from n+k patterns)
1606 * "do" notation
1607
1608 We store the relevant Name in the HsSyn tree, in
1609 * HsIntegral/HsFractional/HsIsString
1610 * NegApp
1611 * NPlusKPat
1612 * HsDo
1613 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
1614 fromRationalName etc), but the renamer changes this to the appropriate user
1615 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
1616
1617 We treat the original (standard) names as free-vars too, because the type checker
1618 checks the type of the user thing against the type of the standard thing.
1619 -}
1620
1621 lookupIfThenElse :: RnM (Maybe (SyntaxExpr GhcRn), FreeVars)
1622 -- Different to lookupSyntaxName because in the non-rebindable
1623 -- case we desugar directly rather than calling an existing function
1624 -- Hence the (Maybe (SyntaxExpr GhcRn)) return type
1625 lookupIfThenElse
1626 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1627 ; if not rebindable_on
1628 then return (Nothing, emptyFVs)
1629 else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse"))
1630 ; return ( Just (mkRnSyntaxExpr ite)
1631 , unitFV ite ) } }
1632
1633 lookupSyntaxName' :: Name -- ^ The standard name
1634 -> RnM Name -- ^ Possibly a non-standard name
1635 lookupSyntaxName' std_name
1636 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1637 ; if not rebindable_on then
1638 return std_name
1639 else
1640 -- Get the similarly named thing from the local environment
1641 lookupOccRn (mkRdrUnqual (nameOccName std_name)) }
1642
1643 lookupSyntaxName :: Name -- The standard name
1644 -> RnM (SyntaxExpr GhcRn, FreeVars) -- Possibly a non-standard
1645 -- name
1646 lookupSyntaxName std_name
1647 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1648 ; if not rebindable_on then
1649 return (mkRnSyntaxExpr std_name, emptyFVs)
1650 else
1651 -- Get the similarly named thing from the local environment
1652 do { usr_name <- lookupOccRn (mkRdrUnqual (nameOccName std_name))
1653 ; return (mkRnSyntaxExpr usr_name, unitFV usr_name) } }
1654
1655 lookupSyntaxNames :: [Name] -- Standard names
1656 -> RnM ([HsExpr GhcRn], FreeVars) -- See comments with HsExpr.ReboundNames
1657 -- this works with CmdTop, which wants HsExprs, not SyntaxExprs
1658 lookupSyntaxNames std_names
1659 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1660 ; if not rebindable_on then
1661 return (map (HsVar noExtField . noLoc) std_names, emptyFVs)
1662 else
1663 do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names
1664 ; return (map (HsVar noExtField . noLoc) usr_names, mkFVs usr_names) } }
1665
1666 -- Error messages
1667
1668
1669 opDeclErr :: RdrName -> SDoc
1670 opDeclErr n
1671 = hang (text "Illegal declaration of a type or class operator" <+> quotes (ppr n))
1672 2 (text "Use TypeOperators to declare operators in type and declarations")
1673
1674 badOrigBinding :: RdrName -> SDoc
1675 badOrigBinding name
1676 | Just _ <- isBuiltInOcc_maybe occ
1677 = text "Illegal binding of built-in syntax:" <+> ppr occ
1678 -- Use an OccName here because we don't want to print Prelude.(,)
1679 | otherwise
1680 = text "Cannot redefine a Name retrieved by a Template Haskell quote:"
1681 <+> ppr name
1682 -- This can happen when one tries to use a Template Haskell splice to
1683 -- define a top-level identifier with an already existing name, e.g.,
1684 --
1685 -- $(pure [ValD (VarP 'succ) (NormalB (ConE 'True)) []])
1686 --
1687 -- (See #13968.)
1688 where
1689 occ = rdrNameOcc $ filterCTuple name