1 //! This crate is responsible for the part of name resolution that doesn't require type checker.
3 //! Module structure of the crate is built here.
4 //! Paths in macros, imports, expressions, types, patterns are resolved here.
5 //! Label and lifetime names are resolved here as well.
7 //! Type-relative name resolution (methods, fields, associated items) happens in `rustc_hir_analysis`.
9 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
10 #![feature(assert_matches)]
11 #![feature(box_patterns)]
12 #![feature(drain_filter)]
13 #![feature(if_let_guard)]
14 #![feature(iter_intersperse)]
15 #![feature(let_chains)]
16 #![feature(never_type)]
17 #![recursion_limit = "256"]
18 #![allow(rustdoc::private_intra_doc_links)]
19 #![allow(rustc::potential_query_instability)]
24 use rustc_arena
::{DroplessArena, TypedArena}
;
25 use rustc_ast
::node_id
::NodeMap
;
26 use rustc_ast
::{self as ast, NodeId, CRATE_NODE_ID}
;
27 use rustc_ast
::{AngleBracketedArg, Crate, Expr, ExprKind, GenericArg, GenericArgs, LitKind, Path}
;
28 use rustc_data_structures
::fx
::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}
;
29 use rustc_data_structures
::intern
::Interned
;
30 use rustc_data_structures
::sync
::{Lrc, MappedReadGuard}
;
32 Applicability
, DiagnosticBuilder
, DiagnosticMessage
, ErrorGuaranteed
, SubdiagnosticMessage
,
34 use rustc_expand
::base
::{DeriveResolutions, SyntaxExtension, SyntaxExtensionKind}
;
35 use rustc_hir
::def
::Namespace
::{self, *}
;
36 use rustc_hir
::def
::{self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, PartialRes, PerNS}
;
37 use rustc_hir
::def_id
::{CrateNum, DefId, DefIdMap, LocalDefId}
;
38 use rustc_hir
::def_id
::{CRATE_DEF_ID, LOCAL_CRATE}
;
39 use rustc_hir
::definitions
::DefPathData
;
40 use rustc_hir
::TraitCandidate
;
41 use rustc_index
::vec
::IndexVec
;
42 use rustc_macros
::fluent_messages
;
43 use rustc_metadata
::creader
::{CStore, CrateLoader}
;
44 use rustc_middle
::metadata
::ModChild
;
45 use rustc_middle
::middle
::privacy
::EffectiveVisibilities
;
46 use rustc_middle
::span_bug
;
47 use rustc_middle
::ty
::{self, DefIdTree, MainDefinition, RegisteredTools, TyCtxt}
;
48 use rustc_middle
::ty
::{ResolverGlobalCtxt, ResolverOutputs}
;
49 use rustc_query_system
::ich
::StableHashingContext
;
50 use rustc_session
::cstore
::CrateStore
;
51 use rustc_session
::lint
::LintBuffer
;
52 use rustc_span
::hygiene
::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency}
;
53 use rustc_span
::source_map
::Spanned
;
54 use rustc_span
::symbol
::{kw, sym, Ident, Symbol}
;
55 use rustc_span
::{Span, DUMMY_SP}
;
57 use smallvec
::{smallvec, SmallVec}
;
58 use std
::cell
::{Cell, RefCell}
;
59 use std
::collections
::BTreeSet
;
62 use diagnostics
::{ImportSuggestion, LabelSuggestion, Suggestion}
;
63 use imports
::{Import, ImportKind, NameResolution}
;
64 use late
::{HasGenericParams, PathSource, PatternSource}
;
65 use macros
::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef}
;
67 use crate::effective_visibilities
::EffectiveVisibilitiesVisitor
;
69 type Res
= def
::Res
<NodeId
>;
71 mod build_reduced_graph
;
75 mod effective_visibilities
;
83 fluent_messages
! { "../locales/en-US.ftl" }
90 #[derive(Copy, Clone, PartialEq, Debug)]
97 fn determined(determined
: bool
) -> Determinacy
{
98 if determined { Determinacy::Determined }
else { Determinacy::Undetermined }
102 /// A specific scope in which a name can be looked up.
103 /// This enum is currently used only for early resolution (imports and macros),
104 /// but not for late resolution yet.
105 #[derive(Clone, Copy)]
107 DeriveHelpers(LocalExpnId
),
109 MacroRules(MacroRulesScopeRef
<'a
>),
111 // The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK`
112 // lint if it should be reported.
113 Module(Module
<'a
>, Option
<NodeId
>),
122 /// Names from different contexts may want to visit different subsets of all specific scopes
123 /// with different restrictions when looking up the resolution.
124 /// This enum is currently used only for early resolution (imports and macros),
125 /// but not for late resolution yet.
126 #[derive(Clone, Copy)]
128 /// All scopes with the given namespace.
129 All(Namespace
, /*is_import*/ bool
),
130 /// Crate root, then extern prelude (used for mixed 2015-2018 mode in macros).
131 AbsolutePath(Namespace
),
132 /// All scopes with macro namespace and the given macro kind restriction.
134 /// All scopes with the given namespace, used for partially performing late resolution.
135 /// The node id enables lints and is used for reporting them.
136 Late(Namespace
, Module
<'a
>, Option
<NodeId
>),
139 /// Everything you need to know about a name's location to resolve it.
140 /// Serves as a starting point for the scope visitor.
141 /// This struct is currently used only for early resolution (imports and macros),
142 /// but not for late resolution yet.
143 #[derive(Clone, Copy, Debug)]
144 struct ParentScope
<'a
> {
146 expansion
: LocalExpnId
,
147 macro_rules
: MacroRulesScopeRef
<'a
>,
148 derives
: &'a
[ast
::Path
],
151 impl<'a
> ParentScope
<'a
> {
152 /// Creates a parent scope with the passed argument used as the module scope component,
153 /// and other scope components set to default empty values.
154 fn module(module
: Module
<'a
>, resolver
: &Resolver
<'a
, '_
>) -> ParentScope
<'a
> {
157 expansion
: LocalExpnId
::ROOT
,
158 macro_rules
: resolver
.arenas
.alloc_macro_rules_scope(MacroRulesScope
::Empty
),
164 #[derive(Copy, Debug, Clone)]
165 enum ImplTraitContext
{
167 Universal(LocalDefId
),
170 struct BindingError
{
172 origin
: BTreeSet
<Span
>,
173 target
: BTreeSet
<Span
>,
177 enum ResolutionError
<'a
> {
178 /// Error E0401: can't use type or const parameters from outer function.
179 GenericParamsFromOuterFunction(Res
, HasGenericParams
),
180 /// Error E0403: the name is already used for a type or const parameter in this generic
182 NameAlreadyUsedInParameterList(Symbol
, Span
),
183 /// Error E0407: method is not a member of trait.
184 MethodNotMemberOfTrait(Ident
, String
, Option
<Symbol
>),
185 /// Error E0437: type is not a member of trait.
186 TypeNotMemberOfTrait(Ident
, String
, Option
<Symbol
>),
187 /// Error E0438: const is not a member of trait.
188 ConstNotMemberOfTrait(Ident
, String
, Option
<Symbol
>),
189 /// Error E0408: variable `{}` is not bound in all patterns.
190 VariableNotBoundInPattern(BindingError
, ParentScope
<'a
>),
191 /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
192 VariableBoundWithDifferentMode(Symbol
, Span
),
193 /// Error E0415: identifier is bound more than once in this parameter list.
194 IdentifierBoundMoreThanOnceInParameterList(Symbol
),
195 /// Error E0416: identifier is bound more than once in the same pattern.
196 IdentifierBoundMoreThanOnceInSamePattern(Symbol
),
197 /// Error E0426: use of undeclared label.
198 UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> }
,
199 /// Error E0429: `self` imports are only allowed within a `{ }` list.
200 SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span }
,
201 /// Error E0430: `self` import can only appear once in the list.
202 SelfImportCanOnlyAppearOnceInTheList
,
203 /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
204 SelfImportOnlyInImportListWithNonEmptyPrefix
,
205 /// Error E0433: failed to resolve.
206 FailedToResolve { label: String, suggestion: Option<Suggestion> }
,
207 /// Error E0434: can't capture dynamic environment in a fn item.
208 CannotCaptureDynamicEnvironmentInFnItem
,
209 /// Error E0435: attempt to use a non-constant value in a constant.
210 AttemptToUseNonConstantValueInConstant(
212 /* suggestion */ &'
static str,
213 /* current */ &'
static str,
215 /// Error E0530: `X` bindings cannot shadow `Y`s.
216 BindingShadowsSomethingUnacceptable
{
217 shadowing_binding
: PatternSource
,
219 participle
: &'
static str,
220 article
: &'
static str,
221 shadowed_binding
: Res
,
222 shadowed_binding_span
: Span
,
224 /// Error E0128: generic parameters with a default cannot use forward-declared identifiers.
225 ForwardDeclaredGenericParam
,
226 /// ERROR E0770: the type of const parameters must not depend on other generic parameters.
227 ParamInTyOfConstParam(Symbol
),
228 /// generic parameters must not be used inside const evaluations.
230 /// This error is only emitted when using `min_const_generics`.
231 ParamInNonTrivialAnonConst { name: Symbol, is_type: bool }
,
232 /// Error E0735: generic parameters with a default cannot use `Self`
233 SelfInGenericParamDefault
,
234 /// Error E0767: use of unreachable label
235 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> }
,
236 /// Error E0323, E0324, E0325: mismatch between trait item and impl item.
241 trait_item_span
: Span
,
242 code
: rustc_errors
::DiagnosticId
,
244 /// Error E0201: multiple impl items for the same trait item.
245 TraitImplDuplicate { name: Symbol, trait_item_span: Span, old_span: Span }
,
246 /// Inline asm `sym` operand must refer to a `fn` or `static`.
250 enum VisResolutionError
<'a
> {
251 Relative2018(Span
, &'a ast
::Path
),
253 FailedToResolve(Span
, String
, Option
<Suggestion
>),
254 ExpectedFound(Span
, String
, Res
),
259 /// A minimal representation of a path segment. We use this in resolve because we synthesize 'path
260 /// segments' which don't have the rest of an AST or HIR `PathSegment`.
261 #[derive(Clone, Copy, Debug)]
265 /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing
266 /// nonsensical suggestions.
267 has_generic_args
: bool
,
268 /// Signals whether this `PathSegment` has lifetime arguments.
269 has_lifetime_args
: bool
,
274 fn from_path(path
: &Path
) -> Vec
<Segment
> {
275 path
.segments
.iter().map(|s
| s
.into()).collect()
278 fn from_ident(ident
: Ident
) -> Segment
{
282 has_generic_args
: false,
283 has_lifetime_args
: false,
288 fn from_ident_and_id(ident
: Ident
, id
: NodeId
) -> Segment
{
292 has_generic_args
: false,
293 has_lifetime_args
: false,
298 fn names_to_string(segments
: &[Segment
]) -> String
{
299 names_to_string(&segments
.iter().map(|seg
| seg
.ident
.name
).collect
::<Vec
<_
>>())
303 impl<'a
> From
<&'a ast
::PathSegment
> for Segment
{
304 fn from(seg
: &'a ast
::PathSegment
) -> Segment
{
305 let has_generic_args
= seg
.args
.is_some();
306 let (args_span
, has_lifetime_args
) = if let Some(args
) = seg
.args
.as_deref() {
308 GenericArgs
::AngleBracketed(args
) => {
309 let found_lifetimes
= args
312 .any(|arg
| matches
!(arg
, AngleBracketedArg
::Arg(GenericArg
::Lifetime(_
))));
313 (args
.span
, found_lifetimes
)
315 GenericArgs
::Parenthesized(args
) => (args
.span
, true),
330 /// An intermediate resolution result.
332 /// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
333 /// items are visible in their whole block, while `Res`es only from the place they are defined
336 enum LexicalScopeBinding
<'a
> {
337 Item(&'a NameBinding
<'a
>),
341 impl<'a
> LexicalScopeBinding
<'a
> {
342 fn res(self) -> Res
{
344 LexicalScopeBinding
::Item(binding
) => binding
.res(),
345 LexicalScopeBinding
::Res(res
) => res
,
350 #[derive(Copy, Clone, Debug)]
351 enum ModuleOrUniformRoot
<'a
> {
355 /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
356 CrateRootAndExternPrelude
,
358 /// Virtual module that denotes resolution in extern prelude.
359 /// Used for paths starting with `::` on 2018 edition.
362 /// Virtual module that denotes resolution in current scope.
363 /// Used only for resolving single-segment imports. The reason it exists is that import paths
364 /// are always split into two parts, the first of which should be some kind of module.
368 impl ModuleOrUniformRoot
<'_
> {
369 fn same_def(lhs
: Self, rhs
: Self) -> bool
{
371 (ModuleOrUniformRoot
::Module(lhs
), ModuleOrUniformRoot
::Module(rhs
)) => {
375 ModuleOrUniformRoot
::CrateRootAndExternPrelude
,
376 ModuleOrUniformRoot
::CrateRootAndExternPrelude
,
378 | (ModuleOrUniformRoot
::ExternPrelude
, ModuleOrUniformRoot
::ExternPrelude
)
379 | (ModuleOrUniformRoot
::CurrentScope
, ModuleOrUniformRoot
::CurrentScope
) => true,
386 enum PathResult
<'a
> {
387 Module(ModuleOrUniformRoot
<'a
>),
388 NonModule(PartialRes
),
393 suggestion
: Option
<Suggestion
>,
394 is_error_from_last_segment
: bool
,
398 impl<'a
> PathResult
<'a
> {
401 is_error_from_last_segment
: bool
,
403 label_and_suggestion
: impl FnOnce() -> (String
, Option
<Suggestion
>),
404 ) -> PathResult
<'a
> {
405 let (label
, suggestion
) =
406 if finalize { label_and_suggestion() }
else { (String::new(), None) }
;
407 PathResult
::Failed { span, label, suggestion, is_error_from_last_segment }
413 /// An anonymous module; e.g., just a block.
418 /// { // This is an anonymous module
419 /// f(); // This resolves to (2) as we are inside the block.
422 /// f(); // Resolves to (1)
426 /// Any module with a name.
430 /// * A normal module – either `mod from_file;` or `mod from_block { }` –
431 /// or the crate root (which is conceptually a top-level module).
432 /// Note that the crate root's [name][Self::name] will be [`kw::Empty`].
433 /// * A trait or an enum (it implicitly contains associated types, methods and variant
435 Def(DefKind
, DefId
, Symbol
),
439 /// Get name of the module.
440 fn name(&self) -> Option
<Symbol
> {
442 ModuleKind
::Block
=> None
,
443 ModuleKind
::Def(.., name
) => Some(*name
),
448 /// A key that identifies a binding in a given `Module`.
450 /// Multiple bindings in the same module can have the same key (in a valid
451 /// program) if all but one of them come from glob imports.
452 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
454 /// The identifier for the binding, always the `normalize_to_macros_2_0` version of the
458 /// 0 if ident is not `_`, otherwise a value that's unique to the specific
459 /// `_` in the expanded AST that introduced this binding.
463 type Resolutions
<'a
> = RefCell
<FxIndexMap
<BindingKey
, &'a RefCell
<NameResolution
<'a
>>>>;
465 /// One node in the tree of modules.
467 /// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these:
470 /// * crate root (aka, top-level anonymous module)
473 /// * curly-braced block with statements
475 /// You can use [`ModuleData::kind`] to determine the kind of module this is.
476 struct ModuleData
<'a
> {
477 /// The direct parent module (it may not be a `mod`, however).
478 parent
: Option
<Module
<'a
>>,
479 /// What kind of module this is, because this may not be a `mod`.
482 /// Mapping between names and their (possibly in-progress) resolutions in this module.
483 /// Resolutions in modules from other crates are not populated until accessed.
484 lazy_resolutions
: Resolutions
<'a
>,
485 /// True if this is a module from other crate that needs to be populated on access.
486 populate_on_access
: Cell
<bool
>,
488 /// Macro invocations that can expand into items in this module.
489 unexpanded_invocations
: RefCell
<FxHashSet
<LocalExpnId
>>,
491 /// Whether `#[no_implicit_prelude]` is active.
492 no_implicit_prelude
: bool
,
494 glob_importers
: RefCell
<Vec
<&'a Import
<'a
>>>,
495 globs
: RefCell
<Vec
<&'a Import
<'a
>>>,
497 /// Used to memoize the traits in this module for faster searches through all traits in scope.
498 traits
: RefCell
<Option
<Box
<[(Ident
, &'a NameBinding
<'a
>)]>>>,
500 /// Span of the module itself. Used for error reporting.
506 type Module
<'a
> = &'a ModuleData
<'a
>;
508 impl<'a
> ModuleData
<'a
> {
510 parent
: Option
<Module
<'a
>>,
514 no_implicit_prelude
: bool
,
516 let is_foreign
= match kind
{
517 ModuleKind
::Def(_
, def_id
, _
) => !def_id
.is_local(),
518 ModuleKind
::Block
=> false,
523 lazy_resolutions
: Default
::default(),
524 populate_on_access
: Cell
::new(is_foreign
),
525 unexpanded_invocations
: Default
::default(),
527 glob_importers
: RefCell
::new(Vec
::new()),
528 globs
: RefCell
::new(Vec
::new()),
529 traits
: RefCell
::new(None
),
535 fn for_each_child
<'tcx
, R
, F
>(&'a
self, resolver
: &mut R
, mut f
: F
)
537 R
: AsMut
<Resolver
<'a
, 'tcx
>>,
538 F
: FnMut(&mut R
, Ident
, Namespace
, &'a NameBinding
<'a
>),
540 for (key
, name_resolution
) in resolver
.as_mut().resolutions(self).borrow().iter() {
541 if let Some(binding
) = name_resolution
.borrow().binding
{
542 f(resolver
, key
.ident
, key
.ns
, binding
);
547 /// This modifies `self` in place. The traits will be stored in `self.traits`.
548 fn ensure_traits
<'tcx
, R
>(&'a
self, resolver
: &mut R
)
550 R
: AsMut
<Resolver
<'a
, 'tcx
>>,
552 let mut traits
= self.traits
.borrow_mut();
553 if traits
.is_none() {
554 let mut collected_traits
= Vec
::new();
555 self.for_each_child(resolver
, |_
, name
, ns
, binding
| {
559 if let Res
::Def(DefKind
::Trait
| DefKind
::TraitAlias
, _
) = binding
.res() {
560 collected_traits
.push((name
, binding
))
563 *traits
= Some(collected_traits
.into_boxed_slice());
567 fn res(&self) -> Option
<Res
> {
569 ModuleKind
::Def(kind
, def_id
, _
) => Some(Res
::Def(kind
, def_id
)),
574 // Public for rustdoc.
575 fn def_id(&self) -> DefId
{
576 self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
579 fn opt_def_id(&self) -> Option
<DefId
> {
581 ModuleKind
::Def(_
, def_id
, _
) => Some(def_id
),
586 // `self` resolves to the first module ancestor that `is_normal`.
587 fn is_normal(&self) -> bool
{
588 matches
!(self.kind
, ModuleKind
::Def(DefKind
::Mod
, _
, _
))
591 fn is_trait(&self) -> bool
{
592 matches
!(self.kind
, ModuleKind
::Def(DefKind
::Trait
, _
, _
))
595 fn nearest_item_scope(&'a
self) -> Module
<'a
> {
597 ModuleKind
::Def(DefKind
::Enum
| DefKind
::Trait
, ..) => {
598 self.parent
.expect("enum or trait module without a parent")
604 /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module).
605 /// This may be the crate root.
606 fn nearest_parent_mod(&self) -> DefId
{
608 ModuleKind
::Def(DefKind
::Mod
, def_id
, _
) => def_id
,
609 _
=> self.parent
.expect("non-root module without parent").nearest_parent_mod(),
613 fn is_ancestor_of(&self, mut other
: &Self) -> bool
{
614 while !ptr
::eq(self, other
) {
615 if let Some(parent
) = other
.parent
{
625 impl<'a
> fmt
::Debug
for ModuleData
<'a
> {
626 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
627 write
!(f
, "{:?}", self.res())
631 /// Records a possibly-private value, type, or module definition.
632 #[derive(Clone, Debug)]
633 struct NameBinding
<'a
> {
634 kind
: NameBindingKind
<'a
>,
635 ambiguity
: Option
<(&'a NameBinding
<'a
>, AmbiguityKind
)>,
636 expansion
: LocalExpnId
,
638 vis
: ty
::Visibility
<DefId
>,
641 trait ToNameBinding
<'a
> {
642 fn to_name_binding(self, arenas
: &'a ResolverArenas
<'a
>) -> &'a NameBinding
<'a
>;
645 impl<'a
> ToNameBinding
<'a
> for &'a NameBinding
<'a
> {
646 fn to_name_binding(self, _
: &'a ResolverArenas
<'a
>) -> &'a NameBinding
<'a
> {
651 #[derive(Clone, Debug)]
652 enum NameBindingKind
<'a
> {
655 Import { binding: &'a NameBinding<'a>, import: &'a Import<'a>, used: Cell<bool> }
,
658 impl<'a
> NameBindingKind
<'a
> {
659 /// Is this a name binding of an import?
660 fn is_import(&self) -> bool
{
661 matches
!(*self, NameBindingKind
::Import { .. }
)
665 struct PrivacyError
<'a
> {
667 binding
: &'a NameBinding
<'a
>,
671 struct UseError
<'a
> {
672 err
: DiagnosticBuilder
<'a
, ErrorGuaranteed
>,
673 /// Candidates which user could `use` to access the missing type.
674 candidates
: Vec
<ImportSuggestion
>,
675 /// The `DefId` of the module to place the use-statements in.
677 /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`).
679 /// Extra free-form suggestion.
680 suggestion
: Option
<(Span
, &'
static str, String
, Applicability
)>,
681 /// Path `Segment`s at the place of use that failed. Used for accurate suggestion after telling
682 /// the user to import the item directly.
684 /// Whether the expected source is a call
688 #[derive(Clone, Copy, PartialEq, Debug)]
693 MacroRulesVsModularized
,
701 fn descr(self) -> &'
static str {
703 AmbiguityKind
::Import
=> "multiple potential import sources",
704 AmbiguityKind
::BuiltinAttr
=> "a name conflict with a builtin attribute",
705 AmbiguityKind
::DeriveHelper
=> "a name conflict with a derive helper attribute",
706 AmbiguityKind
::MacroRulesVsModularized
=> {
707 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
709 AmbiguityKind
::GlobVsOuter
=> {
710 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
712 AmbiguityKind
::GlobVsGlob
=> "multiple glob imports of a name in the same module",
713 AmbiguityKind
::GlobVsExpanded
=> {
714 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
716 AmbiguityKind
::MoreExpandedVsOuter
=> {
717 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
723 /// Miscellaneous bits of metadata for better ambiguity error reporting.
724 #[derive(Clone, Copy, PartialEq)]
725 enum AmbiguityErrorMisc
{
732 struct AmbiguityError
<'a
> {
735 b1
: &'a NameBinding
<'a
>,
736 b2
: &'a NameBinding
<'a
>,
737 misc1
: AmbiguityErrorMisc
,
738 misc2
: AmbiguityErrorMisc
,
741 impl<'a
> NameBinding
<'a
> {
742 fn module(&self) -> Option
<Module
<'a
>> {
744 NameBindingKind
::Module(module
) => Some(module
),
745 NameBindingKind
::Import { binding, .. }
=> binding
.module(),
750 fn res(&self) -> Res
{
752 NameBindingKind
::Res(res
) => res
,
753 NameBindingKind
::Module(module
) => module
.res().unwrap(),
754 NameBindingKind
::Import { binding, .. }
=> binding
.res(),
758 fn is_ambiguity(&self) -> bool
{
759 self.ambiguity
.is_some()
761 NameBindingKind
::Import { binding, .. }
=> binding
.is_ambiguity(),
766 fn is_possibly_imported_variant(&self) -> bool
{
768 NameBindingKind
::Import { binding, .. }
=> binding
.is_possibly_imported_variant(),
769 NameBindingKind
::Res(Res
::Def(
770 DefKind
::Variant
| DefKind
::Ctor(CtorOf
::Variant
, ..),
773 NameBindingKind
::Res(..) | NameBindingKind
::Module(..) => false,
777 fn is_extern_crate(&self) -> bool
{
779 NameBindingKind
::Import
{
780 import
: &Import { kind: ImportKind::ExternCrate { .. }
, .. },
783 NameBindingKind
::Module(&ModuleData
{
784 kind
: ModuleKind
::Def(DefKind
::Mod
, def_id
, _
),
786 }) => def_id
.is_crate_root(),
791 fn is_import(&self) -> bool
{
792 matches
!(self.kind
, NameBindingKind
::Import { .. }
)
795 /// The binding introduced by `#[macro_export] macro_rules` is a public import, but it might
796 /// not be perceived as such by users, so treat it as a non-import in some diagnostics.
797 fn is_import_user_facing(&self) -> bool
{
798 matches
!(self.kind
, NameBindingKind
::Import { import, .. }
799 if !matches
!(import
.kind
, ImportKind
::MacroExport
))
802 fn is_glob_import(&self) -> bool
{
804 NameBindingKind
::Import { import, .. }
=> import
.is_glob(),
809 fn is_importable(&self) -> bool
{
812 Res
::Def(DefKind
::AssocConst
| DefKind
::AssocFn
| DefKind
::AssocTy
, _
)
816 fn macro_kind(&self) -> Option
<MacroKind
> {
817 self.res().macro_kind()
820 // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
821 // at some expansion round `max(invoc, binding)` when they both emerged from macros.
822 // Then this function returns `true` if `self` may emerge from a macro *after* that
823 // in some later round and screw up our previously found resolution.
824 // See more detailed explanation in
825 // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
828 invoc_parent_expansion
: LocalExpnId
,
829 binding
: &NameBinding
<'_
>,
831 // self > max(invoc, binding) => !(self <= invoc || self <= binding)
832 // Expansions are partially ordered, so "may appear after" is an inversion of
833 // "certainly appears before or simultaneously" and includes unordered cases.
834 let self_parent_expansion
= self.expansion
;
835 let other_parent_expansion
= binding
.expansion
;
836 let certainly_before_other_or_simultaneously
=
837 other_parent_expansion
.is_descendant_of(self_parent_expansion
);
838 let certainly_before_invoc_or_simultaneously
=
839 invoc_parent_expansion
.is_descendant_of(self_parent_expansion
);
840 !(certainly_before_other_or_simultaneously
|| certainly_before_invoc_or_simultaneously
)
844 #[derive(Default, Clone)]
845 struct ExternPreludeEntry
<'a
> {
846 extern_crate_item
: Option
<&'a NameBinding
<'a
>>,
847 introduced_by_item
: bool
,
850 /// Used for better errors for E0773
851 enum BuiltinMacroState
{
852 NotYetSeen(SyntaxExtensionKind
),
857 resolutions
: DeriveResolutions
,
858 helper_attrs
: Vec
<(usize, Ident
)>,
859 has_derive_copy
: bool
,
864 ext
: Lrc
<SyntaxExtension
>,
868 /// The main resolver class.
870 /// This is the visitor that walks the whole crate.
871 pub struct Resolver
<'a
, 'tcx
> {
874 /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
875 expn_that_defined
: FxHashMap
<LocalDefId
, ExpnId
>,
877 graph_root
: Module
<'a
>,
879 prelude
: Option
<Module
<'a
>>,
880 extern_prelude
: FxHashMap
<Ident
, ExternPreludeEntry
<'a
>>,
882 /// N.B., this is used only for better diagnostics, not name resolution itself.
883 has_self
: FxHashSet
<DefId
>,
885 /// Names of fields of an item `DefId` accessible with dot syntax.
886 /// Used for hints during error reporting.
887 field_names
: FxHashMap
<DefId
, Vec
<Spanned
<Symbol
>>>,
889 /// Span of the privacy modifier in fields of an item `DefId` accessible with dot syntax.
890 /// Used for hints during error reporting.
891 field_visibility_spans
: FxHashMap
<DefId
, Vec
<Span
>>,
893 /// All imports known to succeed or fail.
894 determined_imports
: Vec
<&'a Import
<'a
>>,
896 /// All non-determined imports.
897 indeterminate_imports
: Vec
<&'a Import
<'a
>>,
899 // Spans for local variables found during pattern resolution.
900 // Used for suggestions during error reporting.
901 pat_span_map
: NodeMap
<Span
>,
903 /// Resolutions for nodes that have a single resolution.
904 partial_res_map
: NodeMap
<PartialRes
>,
905 /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
906 import_res_map
: NodeMap
<PerNS
<Option
<Res
>>>,
907 /// Resolutions for labels (node IDs of their corresponding blocks or loops).
908 label_res_map
: NodeMap
<NodeId
>,
909 /// Resolutions for lifetimes.
910 lifetimes_res_map
: NodeMap
<LifetimeRes
>,
911 /// Lifetime parameters that lowering will have to introduce.
912 extra_lifetime_params_map
: NodeMap
<Vec
<(Ident
, NodeId
, LifetimeRes
)>>,
914 /// `CrateNum` resolutions of `extern crate` items.
915 extern_crate_map
: FxHashMap
<LocalDefId
, CrateNum
>,
916 reexport_map
: FxHashMap
<LocalDefId
, Vec
<ModChild
>>,
917 trait_map
: NodeMap
<Vec
<TraitCandidate
>>,
919 /// A map from nodes to anonymous modules.
920 /// Anonymous modules are pseudo-modules that are implicitly created around items
921 /// contained within blocks.
923 /// For example, if we have this:
931 /// There will be an anonymous module created around `g` with the ID of the
932 /// entry block for `f`.
933 block_map
: NodeMap
<Module
<'a
>>,
934 /// A fake module that contains no definition and no prelude. Used so that
935 /// some AST passes can generate identifiers that only resolve to local or
937 empty_module
: Module
<'a
>,
938 module_map
: FxHashMap
<DefId
, Module
<'a
>>,
939 binding_parent_modules
: FxHashMap
<Interned
<'a
, NameBinding
<'a
>>, Module
<'a
>>,
940 underscore_disambiguator
: u32,
942 /// Maps glob imports to the names of items actually imported.
943 glob_map
: FxHashMap
<LocalDefId
, FxHashSet
<Symbol
>>,
944 /// Visibilities in "lowered" form, for all entities that have them.
945 visibilities
: FxHashMap
<LocalDefId
, ty
::Visibility
>,
946 has_pub_restricted
: bool
,
947 used_imports
: FxHashSet
<NodeId
>,
948 maybe_unused_trait_imports
: FxIndexSet
<LocalDefId
>,
950 /// Privacy errors are delayed until the end in order to deduplicate them.
951 privacy_errors
: Vec
<PrivacyError
<'a
>>,
952 /// Ambiguity errors are delayed for deduplication.
953 ambiguity_errors
: Vec
<AmbiguityError
<'a
>>,
954 /// `use` injections are delayed for better placement and deduplication.
955 use_injections
: Vec
<UseError
<'tcx
>>,
956 /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
957 macro_expanded_macro_export_errors
: BTreeSet
<(Span
, Span
)>,
959 arenas
: &'a ResolverArenas
<'a
>,
960 dummy_binding
: &'a NameBinding
<'a
>,
962 used_extern_options
: FxHashSet
<Symbol
>,
963 macro_names
: FxHashSet
<Ident
>,
964 builtin_macros
: FxHashMap
<Symbol
, BuiltinMacroState
>,
965 /// A small map keeping true kinds of built-in macros that appear to be fn-like on
966 /// the surface (`macro` items in libcore), but are actually attributes or derives.
967 builtin_macro_kinds
: FxHashMap
<LocalDefId
, MacroKind
>,
968 registered_tools
: RegisteredTools
,
969 macro_use_prelude
: FxHashMap
<Symbol
, &'a NameBinding
<'a
>>,
970 macro_map
: FxHashMap
<DefId
, MacroData
>,
971 dummy_ext_bang
: Lrc
<SyntaxExtension
>,
972 dummy_ext_derive
: Lrc
<SyntaxExtension
>,
973 non_macro_attr
: Lrc
<SyntaxExtension
>,
974 local_macro_def_scopes
: FxHashMap
<LocalDefId
, Module
<'a
>>,
975 ast_transform_scopes
: FxHashMap
<LocalExpnId
, Module
<'a
>>,
976 unused_macros
: FxHashMap
<LocalDefId
, (NodeId
, Ident
)>,
977 unused_macro_rules
: FxHashMap
<(LocalDefId
, usize), (Ident
, Span
)>,
978 proc_macro_stubs
: FxHashSet
<LocalDefId
>,
979 /// Traces collected during macro resolution and validated when it's complete.
980 single_segment_macro_resolutions
:
981 Vec
<(Ident
, MacroKind
, ParentScope
<'a
>, Option
<&'a NameBinding
<'a
>>)>,
982 multi_segment_macro_resolutions
:
983 Vec
<(Vec
<Segment
>, Span
, MacroKind
, ParentScope
<'a
>, Option
<Res
>)>,
984 builtin_attrs
: Vec
<(Ident
, ParentScope
<'a
>)>,
985 /// `derive(Copy)` marks items they are applied to so they are treated specially later.
986 /// Derive macros cannot modify the item themselves and have to store the markers in the global
987 /// context, so they attach the markers to derive container IDs using this resolver table.
988 containers_deriving_copy
: FxHashSet
<LocalExpnId
>,
989 /// Parent scopes in which the macros were invoked.
990 /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
991 invocation_parent_scopes
: FxHashMap
<LocalExpnId
, ParentScope
<'a
>>,
992 /// `macro_rules` scopes *produced* by expanding the macro invocations,
993 /// include all the `macro_rules` items and other invocations generated by them.
994 output_macro_rules_scopes
: FxHashMap
<LocalExpnId
, MacroRulesScopeRef
<'a
>>,
995 /// `macro_rules` scopes produced by `macro_rules` item definitions.
996 macro_rules_scopes
: FxHashMap
<LocalDefId
, MacroRulesScopeRef
<'a
>>,
997 /// Helper attributes that are in scope for the given expansion.
998 helper_attrs
: FxHashMap
<LocalExpnId
, Vec
<Ident
>>,
999 /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute
1000 /// with the given `ExpnId`.
1001 derive_data
: FxHashMap
<LocalExpnId
, DeriveData
>,
1003 /// Avoid duplicated errors for "name already defined".
1004 name_already_seen
: FxHashMap
<Symbol
, Span
>,
1006 potentially_unused_imports
: Vec
<&'a Import
<'a
>>,
1008 /// Table for mapping struct IDs into struct constructor IDs,
1009 /// it's not used during normal resolution, only for better error reporting.
1010 /// Also includes of list of each fields visibility
1011 struct_constructors
: DefIdMap
<(Res
, ty
::Visibility
<DefId
>, Vec
<ty
::Visibility
<DefId
>>)>,
1013 /// Features enabled for this crate.
1014 active_features
: FxHashSet
<Symbol
>,
1016 lint_buffer
: LintBuffer
,
1018 next_node_id
: NodeId
,
1020 node_id_to_def_id
: FxHashMap
<ast
::NodeId
, LocalDefId
>,
1021 def_id_to_node_id
: IndexVec
<LocalDefId
, ast
::NodeId
>,
1023 /// Indices of unnamed struct or variant fields with unresolved attributes.
1024 placeholder_field_indices
: FxHashMap
<NodeId
, usize>,
1025 /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
1026 /// we know what parent node that fragment should be attached to thanks to this table,
1027 /// and how the `impl Trait` fragments were introduced.
1028 invocation_parents
: FxHashMap
<LocalExpnId
, (LocalDefId
, ImplTraitContext
)>,
1030 /// Some way to know that we are in a *trait* impl in `visit_assoc_item`.
1031 /// FIXME: Replace with a more general AST map (together with some other fields).
1032 trait_impl_items
: FxHashSet
<LocalDefId
>,
1034 legacy_const_generic_args
: FxHashMap
<DefId
, Option
<Vec
<usize>>>,
1035 /// Amount of lifetime parameters for each item in the crate.
1036 item_generics_num_lifetimes
: FxHashMap
<LocalDefId
, usize>,
1038 main_def
: Option
<MainDefinition
>,
1039 trait_impls
: FxIndexMap
<DefId
, Vec
<LocalDefId
>>,
1040 /// A list of proc macro LocalDefIds, written out in the order in which
1041 /// they are declared in the static array generated by proc_macro_harness.
1042 proc_macros
: Vec
<NodeId
>,
1043 confused_type_with_std_module
: FxHashMap
<Span
, Span
>,
1044 /// Whether lifetime elision was successful.
1045 lifetime_elision_allowed
: FxHashSet
<NodeId
>,
1047 effective_visibilities
: EffectiveVisibilities
,
1048 doc_link_resolutions
: FxHashMap
<LocalDefId
, DocLinkResMap
>,
1049 doc_link_traits_in_scope
: FxHashMap
<LocalDefId
, Vec
<DefId
>>,
1050 all_macro_rules
: FxHashMap
<Symbol
, Res
>,
1053 /// Nothing really interesting here; it just provides memory for the rest of the crate.
1055 pub struct ResolverArenas
<'a
> {
1056 modules
: TypedArena
<ModuleData
<'a
>>,
1057 local_modules
: RefCell
<Vec
<Module
<'a
>>>,
1058 imports
: TypedArena
<Import
<'a
>>,
1059 name_resolutions
: TypedArena
<RefCell
<NameResolution
<'a
>>>,
1060 ast_paths
: TypedArena
<ast
::Path
>,
1061 dropless
: DroplessArena
,
1064 impl<'a
> ResolverArenas
<'a
> {
1067 parent
: Option
<Module
<'a
>>,
1071 no_implicit_prelude
: bool
,
1072 module_map
: &mut FxHashMap
<DefId
, Module
<'a
>>,
1075 self.modules
.alloc(ModuleData
::new(parent
, kind
, expn_id
, span
, no_implicit_prelude
));
1076 let def_id
= module
.opt_def_id();
1077 if def_id
.map_or(true, |def_id
| def_id
.is_local()) {
1078 self.local_modules
.borrow_mut().push(module
);
1080 if let Some(def_id
) = def_id
{
1081 module_map
.insert(def_id
, module
);
1085 fn local_modules(&'a
self) -> std
::cell
::Ref
<'a
, Vec
<Module
<'a
>>> {
1086 self.local_modules
.borrow()
1088 fn alloc_name_binding(&'a
self, name_binding
: NameBinding
<'a
>) -> &'a NameBinding
<'a
> {
1089 self.dropless
.alloc(name_binding
)
1091 fn alloc_import(&'a
self, import
: Import
<'a
>) -> &'a Import
<'_
> {
1092 self.imports
.alloc(import
)
1094 fn alloc_name_resolution(&'a
self) -> &'a RefCell
<NameResolution
<'a
>> {
1095 self.name_resolutions
.alloc(Default
::default())
1097 fn alloc_macro_rules_scope(&'a
self, scope
: MacroRulesScope
<'a
>) -> MacroRulesScopeRef
<'a
> {
1098 Interned
::new_unchecked(self.dropless
.alloc(Cell
::new(scope
)))
1100 fn alloc_macro_rules_binding(
1102 binding
: MacroRulesBinding
<'a
>,
1103 ) -> &'a MacroRulesBinding
<'a
> {
1104 self.dropless
.alloc(binding
)
1106 fn alloc_ast_paths(&'a
self, paths
: &[ast
::Path
]) -> &'a
[ast
::Path
] {
1107 self.ast_paths
.alloc_from_iter(paths
.iter().cloned())
1109 fn alloc_pattern_spans(&'a
self, spans
: impl Iterator
<Item
= Span
>) -> &'a
[Span
] {
1110 self.dropless
.alloc_from_iter(spans
)
1114 impl<'a
, 'tcx
> AsMut
<Resolver
<'a
, 'tcx
>> for Resolver
<'a
, 'tcx
> {
1115 fn as_mut(&mut self) -> &mut Resolver
<'a
, 'tcx
> {
1120 impl<'a
, 'b
, 'tcx
> DefIdTree
for &'a Resolver
<'b
, 'tcx
> {
1122 fn opt_parent(self, id
: DefId
) -> Option
<DefId
> {
1123 self.tcx
.opt_parent(id
)
1127 impl<'tcx
> Resolver
<'_
, 'tcx
> {
1128 fn opt_local_def_id(&self, node
: NodeId
) -> Option
<LocalDefId
> {
1129 self.node_id_to_def_id
.get(&node
).copied()
1132 fn local_def_id(&self, node
: NodeId
) -> LocalDefId
{
1133 self.opt_local_def_id(node
).unwrap_or_else(|| panic
!("no entry for node id: `{:?}`", node
))
1136 /// Adds a definition with a parent definition.
1140 node_id
: ast
::NodeId
,
1146 !self.node_id_to_def_id
.contains_key(&node_id
),
1147 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
1150 self.tcx
.definitions_untracked().def_key(self.node_id_to_def_id
[&node_id
]),
1153 // FIXME: remove `def_span` body, pass in the right spans here and call `tcx.at().create_def()`
1154 let def_id
= self.tcx
.untracked().definitions
.write().create_def(parent
, data
);
1156 // Create the definition.
1157 if expn_id
!= ExpnId
::root() {
1158 self.expn_that_defined
.insert(def_id
, expn_id
);
1161 // A relative span's parent must be an absolute span.
1162 debug_assert_eq
!(span
.data_untracked().parent
, None
);
1163 let _id
= self.tcx
.untracked().source_span
.push(span
);
1164 debug_assert_eq
!(_id
, def_id
);
1166 // Some things for which we allocate `LocalDefId`s don't correspond to
1167 // anything in the AST, so they don't have a `NodeId`. For these cases
1168 // we don't need a mapping from `NodeId` to `LocalDefId`.
1169 if node_id
!= ast
::DUMMY_NODE_ID
{
1170 debug
!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id
, node_id
);
1171 self.node_id_to_def_id
.insert(node_id
, def_id
);
1173 assert_eq
!(self.def_id_to_node_id
.push(node_id
), def_id
);
1178 fn item_generics_num_lifetimes(&self, def_id
: DefId
) -> usize {
1179 if let Some(def_id
) = def_id
.as_local() {
1180 self.item_generics_num_lifetimes
[&def_id
]
1182 self.cstore().item_generics_num_lifetimes(def_id
, self.tcx
.sess
)
1186 pub fn tcx(&self) -> TyCtxt
<'tcx
> {
1191 impl<'a
, 'tcx
> Resolver
<'a
, 'tcx
> {
1195 arenas
: &'a ResolverArenas
<'a
>,
1196 ) -> Resolver
<'a
, 'tcx
> {
1197 let root_def_id
= CRATE_DEF_ID
.to_def_id();
1198 let mut module_map
= FxHashMap
::default();
1199 let graph_root
= arenas
.new_module(
1201 ModuleKind
::Def(DefKind
::Mod
, root_def_id
, kw
::Empty
),
1203 krate
.spans
.inner_span
,
1204 tcx
.sess
.contains_name(&krate
.attrs
, sym
::no_implicit_prelude
),
1207 let empty_module
= arenas
.new_module(
1209 ModuleKind
::Def(DefKind
::Mod
, root_def_id
, kw
::Empty
),
1213 &mut FxHashMap
::default(),
1216 let mut visibilities
= FxHashMap
::default();
1217 visibilities
.insert(CRATE_DEF_ID
, ty
::Visibility
::Public
);
1219 let mut def_id_to_node_id
= IndexVec
::default();
1220 assert_eq
!(def_id_to_node_id
.push(CRATE_NODE_ID
), CRATE_DEF_ID
);
1221 let mut node_id_to_def_id
= FxHashMap
::default();
1222 node_id_to_def_id
.insert(CRATE_NODE_ID
, CRATE_DEF_ID
);
1224 let mut invocation_parents
= FxHashMap
::default();
1225 invocation_parents
.insert(LocalExpnId
::ROOT
, (CRATE_DEF_ID
, ImplTraitContext
::Existential
));
1227 let mut extern_prelude
: FxHashMap
<Ident
, ExternPreludeEntry
<'_
>> = tcx
1232 .filter(|(_
, entry
)| entry
.add_prelude
)
1233 .map(|(name
, _
)| (Ident
::from_str(name
), Default
::default()))
1236 if !tcx
.sess
.contains_name(&krate
.attrs
, sym
::no_core
) {
1237 extern_prelude
.insert(Ident
::with_dummy_span(sym
::core
), Default
::default());
1238 if !tcx
.sess
.contains_name(&krate
.attrs
, sym
::no_std
) {
1239 extern_prelude
.insert(Ident
::with_dummy_span(sym
::std
), Default
::default());
1243 let registered_tools
= macros
::registered_tools(tcx
.sess
, &krate
.attrs
);
1245 let features
= tcx
.sess
.features_untracked();
1247 let mut resolver
= Resolver
{
1250 expn_that_defined
: Default
::default(),
1252 // The outermost module has def ID 0; this is not reflected in the
1258 has_self
: FxHashSet
::default(),
1259 field_names
: FxHashMap
::default(),
1260 field_visibility_spans
: FxHashMap
::default(),
1262 determined_imports
: Vec
::new(),
1263 indeterminate_imports
: Vec
::new(),
1265 pat_span_map
: Default
::default(),
1266 partial_res_map
: Default
::default(),
1267 import_res_map
: Default
::default(),
1268 label_res_map
: Default
::default(),
1269 lifetimes_res_map
: Default
::default(),
1270 extra_lifetime_params_map
: Default
::default(),
1271 extern_crate_map
: Default
::default(),
1272 reexport_map
: FxHashMap
::default(),
1273 trait_map
: NodeMap
::default(),
1274 underscore_disambiguator
: 0,
1277 block_map
: Default
::default(),
1278 binding_parent_modules
: FxHashMap
::default(),
1279 ast_transform_scopes
: FxHashMap
::default(),
1281 glob_map
: Default
::default(),
1283 has_pub_restricted
: false,
1284 used_imports
: FxHashSet
::default(),
1285 maybe_unused_trait_imports
: Default
::default(),
1287 privacy_errors
: Vec
::new(),
1288 ambiguity_errors
: Vec
::new(),
1289 use_injections
: Vec
::new(),
1290 macro_expanded_macro_export_errors
: BTreeSet
::new(),
1293 dummy_binding
: arenas
.alloc_name_binding(NameBinding
{
1294 kind
: NameBindingKind
::Res(Res
::Err
),
1296 expansion
: LocalExpnId
::ROOT
,
1298 vis
: ty
::Visibility
::Public
,
1301 used_extern_options
: Default
::default(),
1302 macro_names
: FxHashSet
::default(),
1303 builtin_macros
: Default
::default(),
1304 builtin_macro_kinds
: Default
::default(),
1306 macro_use_prelude
: FxHashMap
::default(),
1307 macro_map
: FxHashMap
::default(),
1308 dummy_ext_bang
: Lrc
::new(SyntaxExtension
::dummy_bang(tcx
.sess
.edition())),
1309 dummy_ext_derive
: Lrc
::new(SyntaxExtension
::dummy_derive(tcx
.sess
.edition())),
1310 non_macro_attr
: Lrc
::new(SyntaxExtension
::non_macro_attr(tcx
.sess
.edition())),
1311 invocation_parent_scopes
: Default
::default(),
1312 output_macro_rules_scopes
: Default
::default(),
1313 macro_rules_scopes
: Default
::default(),
1314 helper_attrs
: Default
::default(),
1315 derive_data
: Default
::default(),
1316 local_macro_def_scopes
: FxHashMap
::default(),
1317 name_already_seen
: FxHashMap
::default(),
1318 potentially_unused_imports
: Vec
::new(),
1319 struct_constructors
: Default
::default(),
1320 unused_macros
: Default
::default(),
1321 unused_macro_rules
: Default
::default(),
1322 proc_macro_stubs
: Default
::default(),
1323 single_segment_macro_resolutions
: Default
::default(),
1324 multi_segment_macro_resolutions
: Default
::default(),
1325 builtin_attrs
: Default
::default(),
1326 containers_deriving_copy
: Default
::default(),
1327 active_features
: features
1328 .declared_lib_features
1330 .map(|(feat
, ..)| *feat
)
1331 .chain(features
.declared_lang_features
.iter().map(|(feat
, ..)| *feat
))
1333 lint_buffer
: LintBuffer
::default(),
1334 next_node_id
: CRATE_NODE_ID
,
1337 placeholder_field_indices
: Default
::default(),
1339 trait_impl_items
: Default
::default(),
1340 legacy_const_generic_args
: Default
::default(),
1341 item_generics_num_lifetimes
: Default
::default(),
1342 main_def
: Default
::default(),
1343 trait_impls
: Default
::default(),
1344 proc_macros
: Default
::default(),
1345 confused_type_with_std_module
: Default
::default(),
1346 lifetime_elision_allowed
: Default
::default(),
1347 effective_visibilities
: Default
::default(),
1348 doc_link_resolutions
: Default
::default(),
1349 doc_link_traits_in_scope
: Default
::default(),
1350 all_macro_rules
: Default
::default(),
1353 let root_parent_scope
= ParentScope
::module(graph_root
, &resolver
);
1354 resolver
.invocation_parent_scopes
.insert(LocalExpnId
::ROOT
, root_parent_scope
);
1361 parent
: Option
<Module
<'a
>>,
1365 no_implicit_prelude
: bool
,
1367 let module_map
= &mut self.module_map
;
1368 self.arenas
.new_module(parent
, kind
, expn_id
, span
, no_implicit_prelude
, module_map
)
1371 fn next_node_id(&mut self) -> NodeId
{
1372 let start
= self.next_node_id
;
1373 let next
= start
.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1374 self.next_node_id
= ast
::NodeId
::from_u32(next
);
1378 fn next_node_ids(&mut self, count
: usize) -> std
::ops
::Range
<NodeId
> {
1379 let start
= self.next_node_id
;
1380 let end
= start
.as_usize().checked_add(count
).expect("input too large; ran out of NodeIds");
1381 self.next_node_id
= ast
::NodeId
::from_usize(end
);
1382 start
..self.next_node_id
1385 pub fn lint_buffer(&mut self) -> &mut LintBuffer
{
1386 &mut self.lint_buffer
1389 pub fn arenas() -> ResolverArenas
<'a
> {
1393 pub fn into_outputs(self) -> ResolverOutputs
{
1394 let proc_macros
= self.proc_macros
.iter().map(|id
| self.local_def_id(*id
)).collect();
1395 let expn_that_defined
= self.expn_that_defined
;
1396 let visibilities
= self.visibilities
;
1397 let has_pub_restricted
= self.has_pub_restricted
;
1398 let extern_crate_map
= self.extern_crate_map
;
1399 let reexport_map
= self.reexport_map
;
1400 let maybe_unused_trait_imports
= self.maybe_unused_trait_imports
;
1401 let glob_map
= self.glob_map
;
1402 let main_def
= self.main_def
;
1403 let confused_type_with_std_module
= self.confused_type_with_std_module
;
1404 let effective_visibilities
= self.effective_visibilities
;
1405 let global_ctxt
= ResolverGlobalCtxt
{
1409 effective_visibilities
,
1413 maybe_unused_trait_imports
,
1415 trait_impls
: self.trait_impls
,
1417 confused_type_with_std_module
,
1418 registered_tools
: self.registered_tools
,
1419 doc_link_resolutions
: self.doc_link_resolutions
,
1420 doc_link_traits_in_scope
: self.doc_link_traits_in_scope
,
1421 all_macro_rules
: self.all_macro_rules
,
1423 let ast_lowering
= ty
::ResolverAstLowering
{
1424 legacy_const_generic_args
: self.legacy_const_generic_args
,
1425 partial_res_map
: self.partial_res_map
,
1426 import_res_map
: self.import_res_map
,
1427 label_res_map
: self.label_res_map
,
1428 lifetimes_res_map
: self.lifetimes_res_map
,
1429 extra_lifetime_params_map
: self.extra_lifetime_params_map
,
1430 next_node_id
: self.next_node_id
,
1431 node_id_to_def_id
: self.node_id_to_def_id
,
1432 def_id_to_node_id
: self.def_id_to_node_id
,
1433 trait_map
: self.trait_map
,
1434 builtin_macro_kinds
: self.builtin_macro_kinds
,
1435 lifetime_elision_allowed
: self.lifetime_elision_allowed
,
1437 ResolverOutputs { global_ctxt, ast_lowering }
1440 fn create_stable_hashing_context(&self) -> StableHashingContext
<'_
> {
1441 StableHashingContext
::new(self.tcx
.sess
, self.tcx
.untracked())
1444 fn crate_loader
<T
>(&mut self, f
: impl FnOnce(&mut CrateLoader
<'_
, '_
>) -> T
) -> T
{
1445 let mut cstore
= self.tcx
.untracked().cstore
.write();
1446 let cstore
= cstore
.untracked_as_any().downcast_mut().unwrap();
1447 f(&mut CrateLoader
::new(self.tcx
, &mut *cstore
, &mut self.used_extern_options
))
1450 fn cstore(&self) -> MappedReadGuard
<'_
, CStore
> {
1451 CStore
::from_tcx(self.tcx
)
1454 fn dummy_ext(&self, macro_kind
: MacroKind
) -> Lrc
<SyntaxExtension
> {
1456 MacroKind
::Bang
=> self.dummy_ext_bang
.clone(),
1457 MacroKind
::Derive
=> self.dummy_ext_derive
.clone(),
1458 MacroKind
::Attr
=> self.non_macro_attr
.clone(),
1462 /// Runs the function on each namespace.
1463 fn per_ns
<F
: FnMut(&mut Self, Namespace
)>(&mut self, mut f
: F
) {
1469 fn is_builtin_macro(&mut self, res
: Res
) -> bool
{
1470 self.get_macro(res
).map_or(false, |macro_data
| macro_data
.ext
.builtin_name
.is_some())
1473 fn macro_def(&self, mut ctxt
: SyntaxContext
) -> DefId
{
1475 match ctxt
.outer_expn_data().macro_def_id
{
1476 Some(def_id
) => return def_id
,
1477 None
=> ctxt
.remove_mark(),
1482 /// Entry point to crate resolution.
1483 pub fn resolve_crate(&mut self, krate
: &Crate
) {
1484 self.tcx
.sess
.time("resolve_crate", || {
1485 self.tcx
.sess
.time("finalize_imports", || self.finalize_imports());
1486 self.tcx
.sess
.time("compute_effective_visibilities", || {
1487 EffectiveVisibilitiesVisitor
::compute_effective_visibilities(self, krate
)
1489 self.tcx
.sess
.time("finalize_macro_resolutions", || self.finalize_macro_resolutions());
1490 self.tcx
.sess
.time("late_resolve_crate", || self.late_resolve_crate(krate
));
1491 self.tcx
.sess
.time("resolve_main", || self.resolve_main());
1492 self.tcx
.sess
.time("resolve_check_unused", || self.check_unused(krate
));
1493 self.tcx
.sess
.time("resolve_report_errors", || self.report_errors(krate
));
1496 .time("resolve_postprocess", || self.crate_loader(|c
| c
.postprocess(krate
)));
1499 // Make sure we don't mutate the cstore from here on.
1500 self.tcx
.untracked().cstore
.leak();
1505 current_trait
: Option
<Module
<'a
>>,
1506 parent_scope
: &ParentScope
<'a
>,
1507 ctxt
: SyntaxContext
,
1508 assoc_item
: Option
<(Symbol
, Namespace
)>,
1509 ) -> Vec
<TraitCandidate
> {
1510 let mut found_traits
= Vec
::new();
1512 if let Some(module
) = current_trait
{
1513 if self.trait_may_have_item(Some(module
), assoc_item
) {
1514 let def_id
= module
.def_id();
1515 found_traits
.push(TraitCandidate { def_id, import_ids: smallvec![] }
);
1519 self.visit_scopes(ScopeSet
::All(TypeNS
, false), parent_scope
, ctxt
, |this
, scope
, _
, _
| {
1521 Scope
::Module(module
, _
) => {
1522 this
.traits_in_module(module
, assoc_item
, &mut found_traits
);
1524 Scope
::StdLibPrelude
=> {
1525 if let Some(module
) = this
.prelude
{
1526 this
.traits_in_module(module
, assoc_item
, &mut found_traits
);
1529 Scope
::ExternPrelude
| Scope
::ToolPrelude
| Scope
::BuiltinTypes
=> {}
1530 _
=> unreachable
!(),
1538 fn traits_in_module(
1541 assoc_item
: Option
<(Symbol
, Namespace
)>,
1542 found_traits
: &mut Vec
<TraitCandidate
>,
1544 module
.ensure_traits(self);
1545 let traits
= module
.traits
.borrow();
1546 for (trait_name
, trait_binding
) in traits
.as_ref().unwrap().iter() {
1547 if self.trait_may_have_item(trait_binding
.module(), assoc_item
) {
1548 let def_id
= trait_binding
.res().def_id();
1549 let import_ids
= self.find_transitive_imports(&trait_binding
.kind
, *trait_name
);
1550 found_traits
.push(TraitCandidate { def_id, import_ids }
);
1555 // List of traits in scope is pruned on best effort basis. We reject traits not having an
1556 // associated item with the given name and namespace (if specified). This is a conservative
1557 // optimization, proper hygienic type-based resolution of associated items is done in typeck.
1558 // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
1559 // associated items.
1560 fn trait_may_have_item(
1562 trait_module
: Option
<Module
<'a
>>,
1563 assoc_item
: Option
<(Symbol
, Namespace
)>,
1565 match (trait_module
, assoc_item
) {
1566 (Some(trait_module
), Some((name
, ns
))) => {
1567 self.resolutions(trait_module
).borrow().iter().any(|resolution
| {
1568 let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }
, _
) = resolution
;
1569 assoc_ns
== ns
&& assoc_ident
.name
== name
1576 fn find_transitive_imports(
1578 mut kind
: &NameBindingKind
<'_
>,
1580 ) -> SmallVec
<[LocalDefId
; 1]> {
1581 let mut import_ids
= smallvec
![];
1582 while let NameBindingKind
::Import { import, binding, .. }
= kind
{
1583 if let Some(node_id
) = import
.id() {
1584 let def_id
= self.local_def_id(node_id
);
1585 self.maybe_unused_trait_imports
.insert(def_id
);
1586 import_ids
.push(def_id
);
1588 self.add_to_glob_map(&import
, trait_name
);
1589 kind
= &binding
.kind
;
1594 fn new_key(&mut self, ident
: Ident
, ns
: Namespace
) -> BindingKey
{
1595 let ident
= ident
.normalize_to_macros_2_0();
1596 let disambiguator
= if ident
.name
== kw
::Underscore
{
1597 self.underscore_disambiguator
+= 1;
1598 self.underscore_disambiguator
1602 BindingKey { ident, ns, disambiguator }
1605 fn resolutions(&mut self, module
: Module
<'a
>) -> &'a Resolutions
<'a
> {
1606 if module
.populate_on_access
.get() {
1607 module
.populate_on_access
.set(false);
1608 self.build_reduced_graph_external(module
);
1610 &module
.lazy_resolutions
1617 ) -> &'a RefCell
<NameResolution
<'a
>> {
1619 .resolutions(module
)
1622 .or_insert_with(|| self.arenas
.alloc_name_resolution())
1625 /// Test if AmbiguityError ambi is any identical to any one inside ambiguity_errors
1626 fn matches_previous_ambiguity_error(&mut self, ambi
: &AmbiguityError
<'_
>) -> bool
{
1627 for ambiguity_error
in &self.ambiguity_errors
{
1628 // if the span location and ident as well as its span are the same
1629 if ambiguity_error
.kind
== ambi
.kind
1630 && ambiguity_error
.ident
== ambi
.ident
1631 && ambiguity_error
.ident
.span
== ambi
.ident
.span
1632 && ambiguity_error
.b1
.span
== ambi
.b1
.span
1633 && ambiguity_error
.b2
.span
== ambi
.b2
.span
1634 && ambiguity_error
.misc1
== ambi
.misc1
1635 && ambiguity_error
.misc2
== ambi
.misc2
1646 used_binding
: &'a NameBinding
<'a
>,
1647 is_lexical_scope
: bool
,
1649 if let Some((b2
, kind
)) = used_binding
.ambiguity
{
1650 let ambiguity_error
= AmbiguityError
{
1655 misc1
: AmbiguityErrorMisc
::None
,
1656 misc2
: AmbiguityErrorMisc
::None
,
1658 if !self.matches_previous_ambiguity_error(&ambiguity_error
) {
1659 // avoid dumplicated span information to be emitt out
1660 self.ambiguity_errors
.push(ambiguity_error
);
1663 if let NameBindingKind
::Import { import, binding, ref used }
= used_binding
.kind
{
1664 // Avoid marking `extern crate` items that refer to a name from extern prelude,
1665 // but not introduce it, as used if they are accessed from lexical scope.
1666 if is_lexical_scope
{
1667 if let Some(entry
) = self.extern_prelude
.get(&ident
.normalize_to_macros_2_0()) {
1668 if let Some(crate_item
) = entry
.extern_crate_item
{
1669 if ptr
::eq(used_binding
, crate_item
) && !entry
.introduced_by_item
{
1676 import
.used
.set(true);
1677 if let Some(id
) = import
.id() {
1678 self.used_imports
.insert(id
);
1680 self.add_to_glob_map(&import
, ident
);
1681 self.record_use(ident
, binding
, false);
1686 fn add_to_glob_map(&mut self, import
: &Import
<'_
>, ident
: Ident
) {
1687 if let ImportKind
::Glob { id, .. }
= import
.kind
{
1688 let def_id
= self.local_def_id(id
);
1689 self.glob_map
.entry(def_id
).or_default().insert(ident
.name
);
1693 fn resolve_crate_root(&mut self, ident
: Ident
) -> Module
<'a
> {
1694 debug
!("resolve_crate_root({:?})", ident
);
1695 let mut ctxt
= ident
.span
.ctxt();
1696 let mark
= if ident
.name
== kw
::DollarCrate
{
1697 // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
1698 // we don't want to pretend that the `macro_rules!` definition is in the `macro`
1699 // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
1700 // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
1701 // definitions actually produced by `macro` and `macro` definitions produced by
1702 // `macro_rules!`, but at least such configurations are not stable yet.
1703 ctxt
= ctxt
.normalize_to_macro_rules();
1705 "resolve_crate_root: marks={:?}",
1706 ctxt
.marks().into_iter().map(|(i
, t
)| (i
.expn_data(), t
)).collect
::<Vec
<_
>>()
1708 let mut iter
= ctxt
.marks().into_iter().rev().peekable();
1709 let mut result
= None
;
1710 // Find the last opaque mark from the end if it exists.
1711 while let Some(&(mark
, transparency
)) = iter
.peek() {
1712 if transparency
== Transparency
::Opaque
{
1713 result
= Some(mark
);
1720 "resolve_crate_root: found opaque mark {:?} {:?}",
1722 result
.map(|r
| r
.expn_data())
1724 // Then find the last semi-transparent mark from the end if it exists.
1725 for (mark
, transparency
) in iter
{
1726 if transparency
== Transparency
::SemiTransparent
{
1727 result
= Some(mark
);
1733 "resolve_crate_root: found semi-transparent mark {:?} {:?}",
1735 result
.map(|r
| r
.expn_data())
1739 debug
!("resolve_crate_root: not DollarCrate");
1740 ctxt
= ctxt
.normalize_to_macros_2_0();
1741 ctxt
.adjust(ExpnId
::root())
1743 let module
= match mark
{
1744 Some(def
) => self.expn_def_scope(def
),
1747 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
1750 return self.graph_root
;
1753 let module
= self.expect_module(
1754 module
.opt_def_id().map_or(LOCAL_CRATE
, |def_id
| def_id
.krate
).as_def_id(),
1757 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
1766 fn resolve_self(&mut self, ctxt
: &mut SyntaxContext
, module
: Module
<'a
>) -> Module
<'a
> {
1767 let mut module
= self.expect_module(module
.nearest_parent_mod());
1768 while module
.span
.ctxt().normalize_to_macros_2_0() != *ctxt
{
1769 let parent
= module
.parent
.unwrap_or_else(|| self.expn_def_scope(ctxt
.remove_mark()));
1770 module
= self.expect_module(parent
.nearest_parent_mod());
1775 fn record_partial_res(&mut self, node_id
: NodeId
, resolution
: PartialRes
) {
1776 debug
!("(recording res) recording {:?} for {}", resolution
, node_id
);
1777 if let Some(prev_res
) = self.partial_res_map
.insert(node_id
, resolution
) {
1778 panic
!("path resolved multiple times ({:?} before, {:?} now)", prev_res
, resolution
);
1782 fn record_pat_span(&mut self, node
: NodeId
, span
: Span
) {
1783 debug
!("(recording pat) recording {:?} for {:?}", node
, span
);
1784 self.pat_span_map
.insert(node
, span
);
1787 fn is_accessible_from(
1789 vis
: ty
::Visibility
<impl Into
<DefId
>>,
1792 vis
.is_accessible_from(module
.nearest_parent_mod(), self)
1795 fn set_binding_parent_module(&mut self, binding
: &'a NameBinding
<'a
>, module
: Module
<'a
>) {
1796 if let Some(old_module
) =
1797 self.binding_parent_modules
.insert(Interned
::new_unchecked(binding
), module
)
1799 if !ptr
::eq(module
, old_module
) {
1800 span_bug
!(binding
.span
, "parent module is reset for binding");
1805 fn disambiguate_macro_rules_vs_modularized(
1807 macro_rules
: &'a NameBinding
<'a
>,
1808 modularized
: &'a NameBinding
<'a
>,
1810 // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
1811 // is disambiguated to mitigate regressions from macro modularization.
1812 // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
1814 self.binding_parent_modules
.get(&Interned
::new_unchecked(macro_rules
)),
1815 self.binding_parent_modules
.get(&Interned
::new_unchecked(modularized
)),
1817 (Some(macro_rules
), Some(modularized
)) => {
1818 macro_rules
.nearest_parent_mod() == modularized
.nearest_parent_mod()
1819 && modularized
.is_ancestor_of(macro_rules
)
1825 fn extern_prelude_get(&mut self, ident
: Ident
, finalize
: bool
) -> Option
<&'a NameBinding
<'a
>> {
1826 if ident
.is_path_segment_keyword() {
1827 // Make sure `self`, `super` etc produce an error when passed to here.
1830 self.extern_prelude
.get(&ident
.normalize_to_macros_2_0()).cloned().and_then(|entry
| {
1831 if let Some(binding
) = entry
.extern_crate_item
{
1832 if finalize
&& entry
.introduced_by_item
{
1833 self.record_use(ident
, binding
, false);
1837 let crate_id
= if finalize
{
1838 let Some(crate_id
) =
1839 self.crate_loader(|c
| c
.process_path_extern(ident
.name
, ident
.span
)) else { return Some(self.dummy_binding); }
;
1842 self.crate_loader(|c
| c
.maybe_process_path_extern(ident
.name
))?
1844 let crate_root
= self.expect_module(crate_id
.as_def_id());
1845 let vis
= ty
::Visibility
::<LocalDefId
>::Public
;
1846 Some((crate_root
, vis
, DUMMY_SP
, LocalExpnId
::ROOT
).to_name_binding(self.arenas
))
1851 /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
1852 /// isn't something that can be returned because it can't be made to live that long,
1853 /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1854 /// just that an error occurred.
1855 fn resolve_rustdoc_path(
1859 mut parent_scope
: ParentScope
<'a
>,
1862 Vec
::from_iter(path_str
.split("::").map(Ident
::from_str
).map(Segment
::from_ident
));
1863 if let Some(segment
) = segments
.first_mut() {
1864 if segment
.ident
.name
== kw
::Crate
{
1865 // FIXME: `resolve_path` always resolves `crate` to the current crate root, but
1866 // rustdoc wants it to resolve to the `parent_scope`'s crate root. This trick of
1867 // replacing `crate` with `self` and changing the current module should achieve
1869 segment
.ident
.name
= kw
::SelfLower
;
1870 parent_scope
.module
=
1871 self.expect_module(parent_scope
.module
.def_id().krate
.as_def_id());
1872 } else if segment
.ident
.name
== kw
::Empty
{
1873 segment
.ident
.name
= kw
::PathRoot
;
1877 match self.maybe_resolve_path(&segments
, Some(ns
), &parent_scope
) {
1878 PathResult
::Module(ModuleOrUniformRoot
::Module(module
)) => Some(module
.res().unwrap()),
1879 PathResult
::NonModule(path_res
) => path_res
.full_res(),
1880 PathResult
::Module(ModuleOrUniformRoot
::ExternPrelude
) | PathResult
::Failed { .. }
=> {
1883 PathResult
::Module(..) | PathResult
::Indeterminate
=> unreachable
!(),
1887 /// Retrieves the span of the given `DefId` if `DefId` is in the local crate.
1889 fn opt_span(&self, def_id
: DefId
) -> Option
<Span
> {
1890 def_id
.as_local().map(|def_id
| self.tcx
.source_span(def_id
))
1893 /// Retrieves the name of the given `DefId`.
1895 fn opt_name(&self, def_id
: DefId
) -> Option
<Symbol
> {
1896 let def_key
= match def_id
.as_local() {
1897 Some(def_id
) => self.tcx
.definitions_untracked().def_key(def_id
),
1898 None
=> self.cstore().def_key(def_id
),
1900 def_key
.get_opt_name()
1903 /// Checks if an expression refers to a function marked with
1904 /// `#[rustc_legacy_const_generics]` and returns the argument index list
1905 /// from the attribute.
1906 fn legacy_const_generic_args(&mut self, expr
: &Expr
) -> Option
<Vec
<usize>> {
1907 if let ExprKind
::Path(None
, path
) = &expr
.kind
{
1908 // Don't perform legacy const generics rewriting if the path already
1909 // has generic arguments.
1910 if path
.segments
.last().unwrap().args
.is_some() {
1914 let res
= self.partial_res_map
.get(&expr
.id
)?
.full_res()?
;
1915 if let Res
::Def(def
::DefKind
::Fn
, def_id
) = res
{
1916 // We only support cross-crate argument rewriting. Uses
1917 // within the same crate should be updated to use the new
1918 // const generics style.
1919 if def_id
.is_local() {
1923 if let Some(v
) = self.legacy_const_generic_args
.get(&def_id
) {
1929 .item_attrs_untracked(def_id
, self.tcx
.sess
)
1930 .find(|a
| a
.has_name(sym
::rustc_legacy_const_generics
))?
;
1931 let mut ret
= Vec
::new();
1932 for meta
in attr
.meta_item_list()?
{
1933 match meta
.lit()?
.kind
{
1934 LitKind
::Int(a
, _
) => ret
.push(a
as usize),
1935 _
=> panic
!("invalid arg index"),
1938 // Cache the lookup to avoid parsing attributes for an item multiple times.
1939 self.legacy_const_generic_args
.insert(def_id
, Some(ret
.clone()));
1946 fn resolve_main(&mut self) {
1947 let module
= self.graph_root
;
1948 let ident
= Ident
::with_dummy_span(sym
::main
);
1949 let parent_scope
= &ParentScope
::module(module
, self);
1951 let Ok(name_binding
) = self.maybe_resolve_ident_in_module(
1952 ModuleOrUniformRoot
::Module(module
),
1960 let res
= name_binding
.res();
1961 let is_import
= name_binding
.is_import();
1962 let span
= name_binding
.span
;
1963 if let Res
::Def(DefKind
::Fn
, _
) = res
{
1964 self.record_use(ident
, name_binding
, false);
1966 self.main_def
= Some(MainDefinition { res, is_import, span }
);
1969 // Items that go to reexport table encoded to metadata and visible through it to other crates.
1970 fn is_reexport(&self, binding
: &NameBinding
<'a
>) -> Option
<def
::Res
<!>> {
1971 if binding
.is_import() {
1972 let res
= binding
.res().expect_non_local();
1973 // Ambiguous imports are treated as errors at this point and are
1974 // not exposed to other crates (see #36837 for more details).
1975 if res
!= def
::Res
::Err
&& !binding
.is_ambiguity() {
1984 fn names_to_string(names
: &[Symbol
]) -> String
{
1985 let mut result
= String
::new();
1986 for (i
, name
) in names
.iter().filter(|name
| **name
!= kw
::PathRoot
).enumerate() {
1988 result
.push_str("::");
1990 if Ident
::with_dummy_span(*name
).is_raw_guess() {
1991 result
.push_str("r#");
1993 result
.push_str(name
.as_str());
1998 fn path_names_to_string(path
: &Path
) -> String
{
1999 names_to_string(&path
.segments
.iter().map(|seg
| seg
.ident
.name
).collect
::<Vec
<_
>>())
2002 /// A somewhat inefficient routine to obtain the name of a module.
2003 fn module_to_string(module
: Module
<'_
>) -> Option
<String
> {
2004 let mut names
= Vec
::new();
2006 fn collect_mod(names
: &mut Vec
<Symbol
>, module
: Module
<'_
>) {
2007 if let ModuleKind
::Def(.., name
) = module
.kind
{
2008 if let Some(parent
) = module
.parent
{
2010 collect_mod(names
, parent
);
2013 names
.push(Symbol
::intern("<opaque>"));
2014 collect_mod(names
, module
.parent
.unwrap());
2017 collect_mod(&mut names
, module
);
2019 if names
.is_empty() {
2023 Some(names_to_string(&names
))
2026 #[derive(Copy, Clone, Debug)]
2028 /// Node ID for linting.
2030 /// Span of the whole path or some its characteristic fragment.
2031 /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2033 /// Span of the path start, suitable for prepending something to it.
2034 /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2036 /// Whether to report privacy errors or silently return "no resolution" for them,
2037 /// similarly to speculative resolution.
2038 report_private
: bool
,
2042 fn new(node_id
: NodeId
, path_span
: Span
) -> Finalize
{
2043 Finalize
::with_root_span(node_id
, path_span
, path_span
)
2046 fn with_root_span(node_id
: NodeId
, path_span
: Span
, root_span
: Span
) -> Finalize
{
2047 Finalize { node_id, path_span, root_span, report_private: true }