Use data con name instead of parent in lookupRecFieldOcc
[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 HsSyn
52 import RdrName
53 import HscTypes
54 import TcEnv
55 import TcRnMonad
56 import RdrHsSyn ( 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 Util
72 import Maybes
73 import DynFlags
74 import FastString
75 import Control.Monad
76 import ListSetOps ( minusList )
77 import qualified GHC.LanguageExtensions as LangExt
78 import RnUnbound
79 import RnUtils
80 import Data.Maybe (isJust)
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 (Trac #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 (Trac #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 (Trac #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 picked_gres gres
642 | isUnqual rdr_name
643 = mconcat (map right_parent gres)
644 | otherwise
645 = mconcat (map right_parent (pickGREs rdr_name gres))
646
647
648 right_parent :: GlobalRdrElt -> DisambigInfo
649 right_parent p
650 | Just cur_parent <- getParent p
651 = if parent == cur_parent
652 then DisambiguatedOccurrence p
653 else NoOccurrence
654 | otherwise
655 = 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 (Trac #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 ; type_operators <- xoptM LangExt.TypeOperators
934 ; star_is_type <- xoptM LangExt.StarIsType
935 ; let star_info = starInfo (type_operators, star_is_type) rdr_name
936 ; if data_kinds
937 then do { mb_demoted_name <- lookupOccRn_maybe demoted_rdr
938 ; case mb_demoted_name of
939 Nothing -> unboundNameX WL_Any rdr_name star_info
940 Just demoted_name ->
941 do { whenWOptM Opt_WarnUntickedPromotedConstructors $
942 addWarn
943 (Reason Opt_WarnUntickedPromotedConstructors)
944 (untickedPromConstrWarn demoted_name)
945 ; return demoted_name } }
946 else do { -- We need to check if a data constructor of this name is
947 -- in scope to give good error messages. However, we do
948 -- not want to give an additional error if the data
949 -- constructor happens to be out of scope! See #13947.
950 mb_demoted_name <- discardErrs $
951 lookupOccRn_maybe demoted_rdr
952 ; let suggestion | isJust mb_demoted_name = suggest_dk
953 | otherwise = star_info
954 ; unboundNameX WL_Any rdr_name suggestion } }
955
956 | otherwise
957 = reportUnboundName rdr_name
958
959 where
960 suggest_dk = text "A data constructor of that name is in scope; did you mean DataKinds?"
961 untickedPromConstrWarn name =
962 text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot
963 $$
964 hsep [ text "Use"
965 , quotes (char '\'' <> ppr name)
966 , text "instead of"
967 , quotes (ppr name) <> dot ]
968
969 badVarInType :: RdrName -> RnM Name
970 badVarInType rdr_name
971 = do { addErr (text "Illegal promoted term variable in a type:"
972 <+> ppr rdr_name)
973 ; return (mkUnboundNameRdr rdr_name) }
974
975 {- Note [Promoted variables in types]
976 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
977 Consider this (Trac #12686):
978 x = True
979 data Bad = Bad 'x
980
981 The parser treats the quote in 'x as saying "use the term
982 namespace", so we'll get (Bad x{v}), with 'x' in the
983 VarName namespace. If we don't test for this, the renamer
984 will happily rename it to the x bound at top level, and then
985 the typecheck falls over because it doesn't have 'x' in scope
986 when kind-checking.
987
988 Note [Demotion]
989 ~~~~~~~~~~~~~~~
990 When the user writes:
991 data Nat = Zero | Succ Nat
992 foo :: f Zero -> Int
993
994 'Zero' in the type signature of 'foo' is parsed as:
995 HsTyVar ("Zero", TcClsName)
996
997 When the renamer hits this occurrence of 'Zero' it's going to realise
998 that it's not in scope. But because it is renaming a type, it knows
999 that 'Zero' might be a promoted data constructor, so it will demote
1000 its namespace to DataName and do a second lookup.
1001
1002 The final result (after the renamer) will be:
1003 HsTyVar ("Zero", DataName)
1004 -}
1005
1006 lookupOccRnX_maybe :: (RdrName -> RnM (Maybe r)) -> (Name -> r) -> RdrName
1007 -> RnM (Maybe r)
1008 lookupOccRnX_maybe globalLookup wrapper rdr_name
1009 = runMaybeT . msum . map MaybeT $
1010 [ fmap wrapper <$> lookupLocalOccRn_maybe rdr_name
1011 , globalLookup rdr_name ]
1012
1013 lookupOccRn_maybe :: RdrName -> RnM (Maybe Name)
1014 lookupOccRn_maybe = lookupOccRnX_maybe lookupGlobalOccRn_maybe id
1015
1016 lookupOccRn_overloaded :: Bool -> RdrName
1017 -> RnM (Maybe (Either Name [Name]))
1018 lookupOccRn_overloaded overload_ok
1019 = lookupOccRnX_maybe global_lookup Left
1020 where
1021 global_lookup :: RdrName -> RnM (Maybe (Either Name [Name]))
1022 global_lookup n =
1023 runMaybeT . msum . map MaybeT $
1024 [ lookupGlobalOccRn_overloaded overload_ok n
1025 , fmap Left . listToMaybe <$> lookupQualifiedNameGHCi n ]
1026
1027
1028
1029 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
1030 -- Looks up a RdrName occurrence in the top-level
1031 -- environment, including using lookupQualifiedNameGHCi
1032 -- for the GHCi case
1033 -- No filter function; does not report an error on failure
1034 -- Uses addUsedRdrName to record use and deprecations
1035 lookupGlobalOccRn_maybe rdr_name =
1036 lookupExactOrOrig rdr_name Just $
1037 runMaybeT . msum . map MaybeT $
1038 [ fmap gre_name <$> lookupGreRn_maybe rdr_name
1039 , listToMaybe <$> lookupQualifiedNameGHCi rdr_name ]
1040 -- This test is not expensive,
1041 -- and only happens for failed lookups
1042
1043 lookupGlobalOccRn :: RdrName -> RnM Name
1044 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
1045 -- environment. Adds an error message if the RdrName is not in scope.
1046 -- You usually want to use "lookupOccRn" which also looks in the local
1047 -- environment.
1048 lookupGlobalOccRn rdr_name
1049 = do { mb_name <- lookupGlobalOccRn_maybe rdr_name
1050 ; case mb_name of
1051 Just n -> return n
1052 Nothing -> do { traceRn "lookupGlobalOccRn" (ppr rdr_name)
1053 ; unboundName WL_Global rdr_name } }
1054
1055 lookupInfoOccRn :: RdrName -> RnM [Name]
1056 -- lookupInfoOccRn is intended for use in GHCi's ":info" command
1057 -- It finds all the GREs that RdrName could mean, not complaining
1058 -- about ambiguity, but rather returning them all
1059 -- C.f. Trac #9881
1060 lookupInfoOccRn rdr_name =
1061 lookupExactOrOrig rdr_name (:[]) $
1062 do { rdr_env <- getGlobalRdrEnv
1063 ; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env)
1064 ; qual_ns <- lookupQualifiedNameGHCi rdr_name
1065 ; return (ns ++ (qual_ns `minusList` ns)) }
1066
1067 -- | Like 'lookupOccRn_maybe', but with a more informative result if
1068 -- the 'RdrName' happens to be a record selector:
1069 --
1070 -- * Nothing -> name not in scope (no error reported)
1071 -- * Just (Left x) -> name uniquely refers to x,
1072 -- or there is a name clash (reported)
1073 -- * Just (Right xs) -> name refers to one or more record selectors;
1074 -- if overload_ok was False, this list will be
1075 -- a singleton.
1076
1077 lookupGlobalOccRn_overloaded :: Bool -> RdrName
1078 -> RnM (Maybe (Either Name [Name]))
1079 lookupGlobalOccRn_overloaded overload_ok rdr_name =
1080 lookupExactOrOrig rdr_name (Just . Left) $
1081 do { res <- lookupGreRn_helper rdr_name
1082 ; case res of
1083 GreNotFound -> return Nothing
1084 OneNameMatch gre -> do
1085 let wrapper = if isRecFldGRE gre then Right . (:[]) else Left
1086 return $ Just (wrapper (gre_name gre))
1087 MultipleNames gres | all isRecFldGRE gres && overload_ok ->
1088 -- Don't record usage for ambiguous selectors
1089 -- until we know which is meant
1090 return $ Just (Right (map gre_name gres))
1091 MultipleNames gres -> do
1092 addNameClashErrRn rdr_name gres
1093 return (Just (Left (gre_name (head gres)))) }
1094
1095
1096 --------------------------------------------------
1097 -- Lookup in the Global RdrEnv of the module
1098 --------------------------------------------------
1099
1100 data GreLookupResult = GreNotFound
1101 | OneNameMatch GlobalRdrElt
1102 | MultipleNames [GlobalRdrElt]
1103
1104 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
1105 -- Look up the RdrName in the GlobalRdrEnv
1106 -- Exactly one binding: records it as "used", return (Just gre)
1107 -- No bindings: return Nothing
1108 -- Many bindings: report "ambiguous", return an arbitrary (Just gre)
1109 -- Uses addUsedRdrName to record use and deprecations
1110 lookupGreRn_maybe rdr_name
1111 = do
1112 res <- lookupGreRn_helper rdr_name
1113 case res of
1114 OneNameMatch gre -> return $ Just gre
1115 MultipleNames gres -> do
1116 traceRn "lookupGreRn_maybe:NameClash" (ppr gres)
1117 addNameClashErrRn rdr_name gres
1118 return $ Just (head gres)
1119 GreNotFound -> return Nothing
1120
1121 {-
1122
1123 Note [ Unbound vs Ambiguous Names ]
1124
1125 lookupGreRn_maybe deals with failures in two different ways. If a name
1126 is unbound then we return a `Nothing` but if the name is ambiguous
1127 then we raise an error and return a dummy name.
1128
1129 The reason for this is that when we call `lookupGreRn_maybe` we are
1130 speculatively looking for whatever we are looking up. If we don't find it,
1131 then we might have been looking for the wrong thing and can keep trying.
1132 On the other hand, if we find a clash then there is no way to recover as
1133 we found the thing we were looking for but can no longer resolve which
1134 the correct one is.
1135
1136 One example of this is in `lookupTypeOccRn` which first looks in the type
1137 constructor namespace before looking in the data constructor namespace to
1138 deal with `DataKinds`.
1139
1140 There is however, as always, one exception to this scheme. If we find
1141 an ambiguous occurence of a record selector and DuplicateRecordFields
1142 is enabled then we defer the selection until the typechecker.
1143
1144 -}
1145
1146
1147
1148
1149 -- Internal Function
1150 lookupGreRn_helper :: RdrName -> RnM GreLookupResult
1151 lookupGreRn_helper rdr_name
1152 = do { env <- getGlobalRdrEnv
1153 ; case lookupGRE_RdrName rdr_name env of
1154 [] -> return GreNotFound
1155 [gre] -> do { addUsedGRE True gre
1156 ; return (OneNameMatch gre) }
1157 gres -> return (MultipleNames gres) }
1158
1159 lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo)
1160 -- Used in export lists
1161 -- If not found or ambiguous, add error message, and fake with UnboundName
1162 -- Uses addUsedRdrName to record use and deprecations
1163 lookupGreAvailRn rdr_name
1164 = do
1165 mb_gre <- lookupGreRn_helper rdr_name
1166 case mb_gre of
1167 GreNotFound ->
1168 do
1169 traceRn "lookupGreAvailRn" (ppr rdr_name)
1170 name <- unboundName WL_Global rdr_name
1171 return (name, avail name)
1172 MultipleNames gres ->
1173 do
1174 addNameClashErrRn rdr_name gres
1175 let unbound_name = mkUnboundNameRdr rdr_name
1176 return (unbound_name, avail unbound_name)
1177 -- Returning an unbound name here prevents an error
1178 -- cascade
1179 OneNameMatch gre ->
1180 return (gre_name gre, availFromGRE gre)
1181
1182
1183 {-
1184 *********************************************************
1185 * *
1186 Deprecations
1187 * *
1188 *********************************************************
1189
1190 Note [Handling of deprecations]
1191 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1192 * We report deprecations at each *occurrence* of the deprecated thing
1193 (see Trac #5867)
1194
1195 * We do not report deprecations for locally-defined names. For a
1196 start, we may be exporting a deprecated thing. Also we may use a
1197 deprecated thing in the defn of another deprecated things. We may
1198 even use a deprecated thing in the defn of a non-deprecated thing,
1199 when changing a module's interface.
1200
1201 * addUsedGREs: we do not report deprecations for sub-binders:
1202 - the ".." completion for records
1203 - the ".." in an export item 'T(..)'
1204 - the things exported by a module export 'module M'
1205 -}
1206
1207 addUsedDataCons :: GlobalRdrEnv -> TyCon -> RnM ()
1208 -- Remember use of in-scope data constructors (Trac #7969)
1209 addUsedDataCons rdr_env tycon
1210 = addUsedGREs [ gre
1211 | dc <- tyConDataCons tycon
1212 , Just gre <- [lookupGRE_Name rdr_env (dataConName dc)] ]
1213
1214 addUsedGRE :: Bool -> GlobalRdrElt -> RnM ()
1215 -- Called for both local and imported things
1216 -- Add usage *and* warn if deprecated
1217 addUsedGRE warn_if_deprec gre
1218 = do { when warn_if_deprec (warnIfDeprecated gre)
1219 ; unless (isLocalGRE gre) $
1220 do { env <- getGblEnv
1221 ; traceRn "addUsedGRE" (ppr gre)
1222 ; updMutVar (tcg_used_gres env) (gre :) } }
1223
1224 addUsedGREs :: [GlobalRdrElt] -> RnM ()
1225 -- Record uses of any *imported* GREs
1226 -- Used for recording used sub-bndrs
1227 -- NB: no call to warnIfDeprecated; see Note [Handling of deprecations]
1228 addUsedGREs gres
1229 | null imp_gres = return ()
1230 | otherwise = do { env <- getGblEnv
1231 ; traceRn "addUsedGREs" (ppr imp_gres)
1232 ; updMutVar (tcg_used_gres env) (imp_gres ++) }
1233 where
1234 imp_gres = filterOut isLocalGRE gres
1235
1236 warnIfDeprecated :: GlobalRdrElt -> RnM ()
1237 warnIfDeprecated gre@(GRE { gre_name = name, gre_imp = iss })
1238 | (imp_spec : _) <- iss
1239 = do { dflags <- getDynFlags
1240 ; this_mod <- getModule
1241 ; when (wopt Opt_WarnWarningsDeprecations dflags &&
1242 not (nameIsLocalOrFrom this_mod name)) $
1243 -- See Note [Handling of deprecations]
1244 do { iface <- loadInterfaceForName doc name
1245 ; case lookupImpDeprec iface gre of
1246 Just txt -> addWarn (Reason Opt_WarnWarningsDeprecations)
1247 (mk_msg imp_spec txt)
1248 Nothing -> return () } }
1249 | otherwise
1250 = return ()
1251 where
1252 occ = greOccName gre
1253 name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1254 doc = text "The name" <+> quotes (ppr occ) <+> ptext (sLit "is mentioned explicitly")
1255
1256 mk_msg imp_spec txt
1257 = sep [ sep [ text "In the use of"
1258 <+> pprNonVarNameSpace (occNameSpace occ)
1259 <+> quotes (ppr occ)
1260 , parens imp_msg <> colon ]
1261 , pprWarningTxtForMsg txt ]
1262 where
1263 imp_mod = importSpecModule imp_spec
1264 imp_msg = text "imported from" <+> ppr imp_mod <> extra
1265 extra | imp_mod == moduleName name_mod = Outputable.empty
1266 | otherwise = text ", but defined in" <+> ppr name_mod
1267
1268 lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt
1269 lookupImpDeprec iface gre
1270 = mi_warn_fn iface (greOccName gre) `mplus` -- Bleat if the thing,
1271 case gre_par gre of -- or its parent, is warn'd
1272 ParentIs p -> mi_warn_fn iface (nameOccName p)
1273 FldParent { par_is = p } -> mi_warn_fn iface (nameOccName p)
1274 NoParent -> Nothing
1275
1276 {-
1277 Note [Used names with interface not loaded]
1278 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1279 It's (just) possible to find a used
1280 Name whose interface hasn't been loaded:
1281
1282 a) It might be a WiredInName; in that case we may not load
1283 its interface (although we could).
1284
1285 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1286 These are seen as "used" by the renamer (if -XRebindableSyntax)
1287 is on), but the typechecker may discard their uses
1288 if in fact the in-scope fromRational is GHC.Read.fromRational,
1289 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
1290 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1291 In that obscure case it won't force the interface in.
1292
1293 In both cases we simply don't permit deprecations;
1294 this is, after all, wired-in stuff.
1295
1296
1297 *********************************************************
1298 * *
1299 GHCi support
1300 * *
1301 *********************************************************
1302
1303 A qualified name on the command line can refer to any module at
1304 all: we try to load the interface if we don't already have it, just
1305 as if there was an "import qualified M" declaration for every
1306 module.
1307
1308 For example, writing `Data.List.sort` will load the interface file for
1309 `Data.List` as if the user had written `import qualified Data.List`.
1310
1311 If we fail we just return Nothing, rather than bleating
1312 about "attempting to use module ā€˜Dā€™ (./D.hs) which is not loaded"
1313 which is what loadSrcInterface does.
1314
1315 It is enabled by default and disabled by the flag
1316 `-fno-implicit-import-qualified`.
1317
1318 Note [Safe Haskell and GHCi]
1319 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1320 We DON'T do this Safe Haskell as we need to check imports. We can
1321 and should instead check the qualified import but at the moment
1322 this requires some refactoring so leave as a TODO
1323 -}
1324
1325
1326
1327 lookupQualifiedNameGHCi :: RdrName -> RnM [Name]
1328 lookupQualifiedNameGHCi rdr_name
1329 = -- We want to behave as we would for a source file import here,
1330 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
1331 do { dflags <- getDynFlags
1332 ; is_ghci <- getIsGHCi
1333 ; go_for_it dflags is_ghci }
1334
1335 where
1336 go_for_it dflags is_ghci
1337 | Just (mod,occ) <- isQual_maybe rdr_name
1338 , is_ghci
1339 , gopt Opt_ImplicitImportQualified dflags -- Enables this GHCi behaviour
1340 , not (safeDirectImpsReq dflags) -- See Note [Safe Haskell and GHCi]
1341 = do { res <- loadSrcInterface_maybe doc mod False Nothing
1342 ; case res of
1343 Succeeded iface
1344 -> return [ name
1345 | avail <- mi_exports iface
1346 , name <- availNames avail
1347 , nameOccName name == occ ]
1348
1349 _ -> -- Either we couldn't load the interface, or
1350 -- we could but we didn't find the name in it
1351 do { traceRn "lookupQualifiedNameGHCi" (ppr rdr_name)
1352 ; return [] } }
1353
1354 | otherwise
1355 = do { traceRn "lookupQualifiedNameGHCi: off" (ppr rdr_name)
1356 ; return [] }
1357
1358 doc = text "Need to find" <+> ppr rdr_name
1359
1360 {-
1361 Note [Looking up signature names]
1362 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1363 lookupSigOccRn is used for type signatures and pragmas
1364 Is this valid?
1365 module A
1366 import M( f )
1367 f :: Int -> Int
1368 f x = x
1369 It's clear that the 'f' in the signature must refer to A.f
1370 The Haskell98 report does not stipulate this, but it will!
1371 So we must treat the 'f' in the signature in the same way
1372 as the binding occurrence of 'f', using lookupBndrRn
1373
1374 However, consider this case:
1375 import M( f )
1376 f :: Int -> Int
1377 g x = x
1378 We don't want to say 'f' is out of scope; instead, we want to
1379 return the imported 'f', so that later on the reanamer will
1380 correctly report "misplaced type sig".
1381
1382 Note [Signatures for top level things]
1383 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1384 data HsSigCtxt = ... | TopSigCtxt NameSet | ....
1385
1386 * The NameSet says what is bound in this group of bindings.
1387 We can't use isLocalGRE from the GlobalRdrEnv, because of this:
1388 f x = x
1389 $( ...some TH splice... )
1390 f :: Int -> Int
1391 When we encounter the signature for 'f', the binding for 'f'
1392 will be in the GlobalRdrEnv, and will be a LocalDef. Yet the
1393 signature is mis-placed
1394
1395 * For type signatures the NameSet should be the names bound by the
1396 value bindings; for fixity declarations, the NameSet should also
1397 include class sigs and record selectors
1398
1399 infix 3 `f` -- Yes, ok
1400 f :: C a => a -> a -- No, not ok
1401 class C a where
1402 f :: a -> a
1403 -}
1404
1405 data HsSigCtxt
1406 = TopSigCtxt NameSet -- At top level, binding these names
1407 -- See Note [Signatures for top level things]
1408 | LocalBindCtxt NameSet -- In a local binding, binding these names
1409 | ClsDeclCtxt Name -- Class decl for this class
1410 | InstDeclCtxt NameSet -- Instance decl whose user-written method
1411 -- bindings are for these methods
1412 | HsBootCtxt NameSet -- Top level of a hs-boot file, binding these names
1413 | RoleAnnotCtxt NameSet -- A role annotation, with the names of all types
1414 -- in the group
1415
1416 instance Outputable HsSigCtxt where
1417 ppr (TopSigCtxt ns) = text "TopSigCtxt" <+> ppr ns
1418 ppr (LocalBindCtxt ns) = text "LocalBindCtxt" <+> ppr ns
1419 ppr (ClsDeclCtxt n) = text "ClsDeclCtxt" <+> ppr n
1420 ppr (InstDeclCtxt ns) = text "InstDeclCtxt" <+> ppr ns
1421 ppr (HsBootCtxt ns) = text "HsBootCtxt" <+> ppr ns
1422 ppr (RoleAnnotCtxt ns) = text "RoleAnnotCtxt" <+> ppr ns
1423
1424 lookupSigOccRn :: HsSigCtxt
1425 -> Sig GhcPs
1426 -> Located RdrName -> RnM (Located Name)
1427 lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig)
1428
1429 -- | Lookup a name in relation to the names in a 'HsSigCtxt'
1430 lookupSigCtxtOccRn :: HsSigCtxt
1431 -> SDoc -- ^ description of thing we're looking up,
1432 -- like "type family"
1433 -> Located RdrName -> RnM (Located Name)
1434 lookupSigCtxtOccRn ctxt what
1435 = wrapLocM $ \ rdr_name ->
1436 do { mb_name <- lookupBindGroupOcc ctxt what rdr_name
1437 ; case mb_name of
1438 Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) }
1439 Right name -> return name }
1440
1441 lookupBindGroupOcc :: HsSigCtxt
1442 -> SDoc
1443 -> RdrName -> RnM (Either MsgDoc Name)
1444 -- Looks up the RdrName, expecting it to resolve to one of the
1445 -- bound names passed in. If not, return an appropriate error message
1446 --
1447 -- See Note [Looking up signature names]
1448 lookupBindGroupOcc ctxt what rdr_name
1449 | Just n <- isExact_maybe rdr_name
1450 = lookupExactOcc_either n -- allow for the possibility of missing Exacts;
1451 -- see Note [dataTcOccs and Exact Names]
1452 -- Maybe we should check the side conditions
1453 -- but it's a pain, and Exact things only show
1454 -- up when you know what you are doing
1455
1456 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
1457 = do { n' <- lookupOrig rdr_mod rdr_occ
1458 ; return (Right n') }
1459
1460 | otherwise
1461 = case ctxt of
1462 HsBootCtxt ns -> lookup_top (`elemNameSet` ns)
1463 TopSigCtxt ns -> lookup_top (`elemNameSet` ns)
1464 RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns)
1465 LocalBindCtxt ns -> lookup_group ns
1466 ClsDeclCtxt cls -> lookup_cls_op cls
1467 InstDeclCtxt ns -> lookup_top (`elemNameSet` ns)
1468 where
1469 lookup_cls_op cls
1470 = lookupSubBndrOcc True cls doc rdr_name
1471 where
1472 doc = text "method of class" <+> quotes (ppr cls)
1473
1474 lookup_top keep_me
1475 = do { env <- getGlobalRdrEnv
1476 ; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
1477 ; case filter (keep_me . gre_name) all_gres of
1478 [] | null all_gres -> bale_out_with Outputable.empty
1479 | otherwise -> bale_out_with local_msg
1480 (gre:_) -> return (Right (gre_name gre)) }
1481
1482 lookup_group bound_names -- Look in the local envt (not top level)
1483 = do { mname <- lookupLocalOccRn_maybe rdr_name
1484 ; case mname of
1485 Just n
1486 | n `elemNameSet` bound_names -> return (Right n)
1487 | otherwise -> bale_out_with local_msg
1488 Nothing -> bale_out_with Outputable.empty }
1489
1490 bale_out_with msg
1491 = return (Left (sep [ text "The" <+> what
1492 <+> text "for" <+> quotes (ppr rdr_name)
1493 , nest 2 $ text "lacks an accompanying binding"]
1494 $$ nest 2 msg))
1495
1496 local_msg = parens $ text "The" <+> what <+> ptext (sLit "must be given where")
1497 <+> quotes (ppr rdr_name) <+> text "is declared"
1498
1499
1500 ---------------
1501 lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [(RdrName, Name)]
1502 -- GHC extension: look up both the tycon and data con or variable.
1503 -- Used for top-level fixity signatures and deprecations.
1504 -- Complain if neither is in scope.
1505 -- See Note [Fixity signature lookup]
1506 lookupLocalTcNames ctxt what rdr_name
1507 = do { mb_gres <- mapM lookup (dataTcOccs rdr_name)
1508 ; let (errs, names) = partitionEithers mb_gres
1509 ; when (null names) $ addErr (head errs) -- Bleat about one only
1510 ; return names }
1511 where
1512 lookup rdr = do { name <- lookupBindGroupOcc ctxt what rdr
1513 ; return (fmap ((,) rdr) name) }
1514
1515 dataTcOccs :: RdrName -> [RdrName]
1516 -- Return both the given name and the same name promoted to the TcClsName
1517 -- namespace. This is useful when we aren't sure which we are looking at.
1518 -- See also Note [dataTcOccs and Exact Names]
1519 dataTcOccs rdr_name
1520 | isDataOcc occ || isVarOcc occ
1521 = [rdr_name, rdr_name_tc]
1522 | otherwise
1523 = [rdr_name]
1524 where
1525 occ = rdrNameOcc rdr_name
1526 rdr_name_tc = setRdrNameSpace rdr_name tcName
1527
1528 {-
1529 Note [dataTcOccs and Exact Names]
1530 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1531 Exact RdrNames can occur in code generated by Template Haskell, and generally
1532 those references are, well, exact. However, the TH `Name` type isn't expressive
1533 enough to always track the correct namespace information, so we sometimes get
1534 the right Unique but wrong namespace. Thus, we still have to do the double-lookup
1535 for Exact RdrNames.
1536
1537 There is also an awkward situation for built-in syntax. Example in GHCi
1538 :info []
1539 This parses as the Exact RdrName for nilDataCon, but we also want
1540 the list type constructor.
1541
1542 Note that setRdrNameSpace on an Exact name requires the Name to be External,
1543 which it always is for built in syntax.
1544 -}
1545
1546
1547
1548 {-
1549 ************************************************************************
1550 * *
1551 Rebindable names
1552 Dealing with rebindable syntax is driven by the
1553 Opt_RebindableSyntax dynamic flag.
1554
1555 In "deriving" code we don't want to use rebindable syntax
1556 so we switch off the flag locally
1557
1558 * *
1559 ************************************************************************
1560
1561 Haskell 98 says that when you say "3" you get the "fromInteger" from the
1562 Standard Prelude, regardless of what is in scope. However, to experiment
1563 with having a language that is less coupled to the standard prelude, we're
1564 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
1565 happens to be in scope. Then you can
1566 import Prelude ()
1567 import MyPrelude as Prelude
1568 to get the desired effect.
1569
1570 At the moment this just happens for
1571 * fromInteger, fromRational on literals (in expressions and patterns)
1572 * negate (in expressions)
1573 * minus (arising from n+k patterns)
1574 * "do" notation
1575
1576 We store the relevant Name in the HsSyn tree, in
1577 * HsIntegral/HsFractional/HsIsString
1578 * NegApp
1579 * NPlusKPat
1580 * HsDo
1581 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
1582 fromRationalName etc), but the renamer changes this to the appropriate user
1583 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
1584
1585 We treat the original (standard) names as free-vars too, because the type checker
1586 checks the type of the user thing against the type of the standard thing.
1587 -}
1588
1589 lookupIfThenElse :: RnM (Maybe (SyntaxExpr GhcRn), FreeVars)
1590 -- Different to lookupSyntaxName because in the non-rebindable
1591 -- case we desugar directly rather than calling an existing function
1592 -- Hence the (Maybe (SyntaxExpr GhcRn)) return type
1593 lookupIfThenElse
1594 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1595 ; if not rebindable_on
1596 then return (Nothing, emptyFVs)
1597 else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse"))
1598 ; return ( Just (mkRnSyntaxExpr ite)
1599 , unitFV ite ) } }
1600
1601 lookupSyntaxName' :: Name -- ^ The standard name
1602 -> RnM Name -- ^ Possibly a non-standard name
1603 lookupSyntaxName' std_name
1604 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1605 ; if not rebindable_on then
1606 return std_name
1607 else
1608 -- Get the similarly named thing from the local environment
1609 lookupOccRn (mkRdrUnqual (nameOccName std_name)) }
1610
1611 lookupSyntaxName :: Name -- The standard name
1612 -> RnM (SyntaxExpr GhcRn, FreeVars) -- Possibly a non-standard
1613 -- name
1614 lookupSyntaxName std_name
1615 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1616 ; if not rebindable_on then
1617 return (mkRnSyntaxExpr std_name, emptyFVs)
1618 else
1619 -- Get the similarly named thing from the local environment
1620 do { usr_name <- lookupOccRn (mkRdrUnqual (nameOccName std_name))
1621 ; return (mkRnSyntaxExpr usr_name, unitFV usr_name) } }
1622
1623 lookupSyntaxNames :: [Name] -- Standard names
1624 -> RnM ([HsExpr GhcRn], FreeVars) -- See comments with HsExpr.ReboundNames
1625 -- this works with CmdTop, which wants HsExprs, not SyntaxExprs
1626 lookupSyntaxNames std_names
1627 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1628 ; if not rebindable_on then
1629 return (map (HsVar noExt . noLoc) std_names, emptyFVs)
1630 else
1631 do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names
1632 ; return (map (HsVar noExt . noLoc) usr_names, mkFVs usr_names) } }
1633
1634 -- Error messages
1635
1636
1637 opDeclErr :: RdrName -> SDoc
1638 opDeclErr n
1639 = hang (text "Illegal declaration of a type or class operator" <+> quotes (ppr n))
1640 2 (text "Use TypeOperators to declare operators in type and declarations")
1641
1642 badOrigBinding :: RdrName -> SDoc
1643 badOrigBinding name
1644 | Just _ <- isBuiltInOcc_maybe occ
1645 = text "Illegal binding of built-in syntax:" <+> ppr occ
1646 -- Use an OccName here because we don't want to print Prelude.(,)
1647 | otherwise
1648 = text "Cannot redefine a Name retrieved by a Template Haskell quote:"
1649 <+> ppr name
1650 -- This can happen when one tries to use a Template Haskell splice to
1651 -- define a top-level identifier with an already existing name, e.g.,
1652 --
1653 -- $(pure [ValD (VarP 'succ) (NormalB (ConE 'True)) []])
1654 --
1655 -- (See Trac #13968.)
1656 where
1657 occ = rdrNameOcc name