rustc_resolve/
lib.rs

1//! This crate is responsible for the part of name resolution that doesn't require type checker.
2//!
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.
6//!
7//! Type-relative name resolution (methods, fields, associated items) happens in `rustc_hir_analysis`.
8
9// tidy-alphabetical-start
10#![allow(internal_features)]
11#![allow(rustc::diagnostic_outside_of_impl)]
12#![allow(rustc::untranslatable_diagnostic)]
13#![feature(arbitrary_self_types)]
14#![feature(assert_matches)]
15#![feature(box_patterns)]
16#![feature(control_flow_into_value)]
17#![feature(decl_macro)]
18#![feature(default_field_values)]
19#![feature(if_let_guard)]
20#![feature(iter_intersperse)]
21#![feature(ptr_as_ref_unchecked)]
22#![feature(rustc_attrs)]
23#![feature(trim_prefix_suffix)]
24#![recursion_limit = "256"]
25// tidy-alphabetical-end
26
27use std::cell::Ref;
28use std::collections::BTreeSet;
29use std::fmt::{self};
30use std::ops::ControlFlow;
31use std::sync::Arc;
32
33use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
34use effective_visibilities::EffectiveVisibilitiesVisitor;
35use errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
36use imports::{Import, ImportData, ImportKind, NameResolution, PendingBinding};
37use late::{
38    ForwardGenericParamBanReason, HasGenericParams, PathSource, PatternSource,
39    UnnecessaryQualification,
40};
41use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
42use rustc_arena::{DroplessArena, TypedArena};
43use rustc_ast::node_id::NodeMap;
44use rustc_ast::{
45    self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, Expr, ExprKind, GenericArg, GenericArgs,
46    NodeId, Path, attr,
47};
48use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
49use rustc_data_structures::intern::Interned;
50use rustc_data_structures::steal::Steal;
51use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard};
52use rustc_data_structures::unord::{UnordMap, UnordSet};
53use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed, LintBuffer};
54use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};
55use rustc_feature::BUILTIN_ATTRIBUTES;
56use rustc_hir::attrs::{AttributeKind, StrippedCfgItem};
57use rustc_hir::def::Namespace::{self, *};
58use rustc_hir::def::{
59    self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, MacroKinds, NonMacroAttrKind, PartialRes,
60    PerNS,
61};
62use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
63use rustc_hir::definitions::DisambiguatorState;
64use rustc_hir::{PrimTy, TraitCandidate, find_attr};
65use rustc_index::bit_set::DenseBitSet;
66use rustc_metadata::creader::CStore;
67use rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};
68use rustc_middle::middle::privacy::EffectiveVisibilities;
69use rustc_middle::query::Providers;
70use rustc_middle::span_bug;
71use rustc_middle::ty::{
72    self, DelegationFnSig, Feed, MainDefinition, RegisteredTools, ResolverAstLowering,
73    ResolverGlobalCtxt, TyCtxt, TyCtxtFeed, Visibility,
74};
75use rustc_query_system::ich::StableHashingContext;
76use rustc_session::config::CrateType;
77use rustc_session::lint::builtin::PRIVATE_MACRO_USE;
78use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
79use rustc_span::{DUMMY_SP, Ident, Macros20NormalizedIdent, Span, Symbol, kw, sym};
80use smallvec::{SmallVec, smallvec};
81use tracing::debug;
82
83type Res = def::Res<NodeId>;
84
85mod build_reduced_graph;
86mod check_unused;
87mod def_collector;
88mod diagnostics;
89mod effective_visibilities;
90mod errors;
91mod ident;
92mod imports;
93mod late;
94mod macros;
95pub mod rustdoc;
96
97pub use macros::registered_tools_ast;
98
99use crate::ref_mut::{CmCell, CmRefCell};
100
101#[allow(non_upper_case_globals)]
#[doc(hidden)]
#[doc =
r" Auto-generated constants for type-checked references to Fluent messages."]
pub(crate) mod fluent_generated {
    #[doc =
    "Constant referring to Fluent message `resolve_accessible_unsure` from `resolve`"]
    pub const resolve_accessible_unsure: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_accessible_unsure"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_accessible_unsure.note` from `resolve`"]
    pub const resolve_note: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("note"));
    #[doc =
    "Constant referring to Fluent message `resolve_add_as_non_derive` from `resolve`"]
    pub const resolve_add_as_non_derive: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_add_as_non_derive"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_added_macro_use` from `resolve`"]
    pub const resolve_added_macro_use: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_added_macro_use"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_ancestor_only` from `resolve`"]
    pub const resolve_ancestor_only: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_ancestor_only"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_anonymous_lifetime_non_gat_report_error` from `resolve`"]
    pub const resolve_anonymous_lifetime_non_gat_report_error:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_anonymous_lifetime_non_gat_report_error"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_anonymous_lifetime_non_gat_report_error.label` from `resolve`"]
    pub const resolve_label: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("label"));
    #[doc =
    "Constant referring to Fluent message `resolve_arguments_macro_use_not_allowed` from `resolve`"]
    pub const resolve_arguments_macro_use_not_allowed:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_arguments_macro_use_not_allowed"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_associated_const_with_similar_name_exists` from `resolve`"]
    pub const resolve_associated_const_with_similar_name_exists:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_associated_const_with_similar_name_exists"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_associated_fn_with_similar_name_exists` from `resolve`"]
    pub const resolve_associated_fn_with_similar_name_exists:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_associated_fn_with_similar_name_exists"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_associated_type_with_similar_name_exists` from `resolve`"]
    pub const resolve_associated_type_with_similar_name_exists:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_associated_type_with_similar_name_exists"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_attempt_to_use_non_constant_value_in_constant` from `resolve`"]
    pub const resolve_attempt_to_use_non_constant_value_in_constant:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_attempt_to_use_non_constant_value_in_constant"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_attempt_to_use_non_constant_value_in_constant_label_with_suggestion` from `resolve`"]
    pub const
        resolve_attempt_to_use_non_constant_value_in_constant_label_with_suggestion:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_attempt_to_use_non_constant_value_in_constant_label_with_suggestion"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_attempt_to_use_non_constant_value_in_constant_with_suggestion` from `resolve`"]
    pub const
        resolve_attempt_to_use_non_constant_value_in_constant_with_suggestion:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_attempt_to_use_non_constant_value_in_constant_with_suggestion"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_attempt_to_use_non_constant_value_in_constant_without_suggestion` from `resolve`"]
    pub const
        resolve_attempt_to_use_non_constant_value_in_constant_without_suggestion:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_attempt_to_use_non_constant_value_in_constant_without_suggestion"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_attributes_starting_with_rustc_are_reserved` from `resolve`"]
    pub const resolve_attributes_starting_with_rustc_are_reserved:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_attributes_starting_with_rustc_are_reserved"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_binding_in_never_pattern` from `resolve`"]
    pub const resolve_binding_in_never_pattern: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_binding_in_never_pattern"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_binding_in_never_pattern.suggestion` from `resolve`"]
    pub const resolve_suggestion: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("suggestion"));
    #[doc =
    "Constant referring to Fluent message `resolve_binding_shadows_something_unacceptable` from `resolve`"]
    pub const resolve_binding_shadows_something_unacceptable:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_binding_shadows_something_unacceptable"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_binding_shadows_something_unacceptable.label_shadowed_binding` from `resolve`"]
    pub const resolve_label_shadowed_binding: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("label_shadowed_binding"));
    #[doc =
    "Constant referring to Fluent message `resolve_binding_shadows_something_unacceptable_suggestion` from `resolve`"]
    pub const resolve_binding_shadows_something_unacceptable_suggestion:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_binding_shadows_something_unacceptable_suggestion"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_cannot_be_reexported_crate_public` from `resolve`"]
    pub const resolve_cannot_be_reexported_crate_public:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_cannot_be_reexported_crate_public"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_cannot_be_reexported_private` from `resolve`"]
    pub const resolve_cannot_be_reexported_private: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_cannot_be_reexported_private"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_cannot_capture_dynamic_environment_in_fn_item` from `resolve`"]
    pub const resolve_cannot_capture_dynamic_environment_in_fn_item:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_cannot_capture_dynamic_environment_in_fn_item"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_cannot_capture_dynamic_environment_in_fn_item.help` from `resolve`"]
    pub const resolve_help: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("help"));
    #[doc =
    "Constant referring to Fluent message `resolve_cannot_determine_import_resolution` from `resolve`"]
    pub const resolve_cannot_determine_import_resolution:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_cannot_determine_import_resolution"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_cannot_determine_macro_resolution` from `resolve`"]
    pub const resolve_cannot_determine_macro_resolution:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_cannot_determine_macro_resolution"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_cannot_find_builtin_macro_with_name` from `resolve`"]
    pub const resolve_cannot_find_builtin_macro_with_name:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_cannot_find_builtin_macro_with_name"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_cannot_find_ident_in_this_scope` from `resolve`"]
    pub const resolve_cannot_find_ident_in_this_scope:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_cannot_find_ident_in_this_scope"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_cannot_glob_import_possible_crates` from `resolve`"]
    pub const resolve_cannot_glob_import_possible_crates:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_cannot_glob_import_possible_crates"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_cannot_use_through_an_import` from `resolve`"]
    pub const resolve_cannot_use_through_an_import: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_cannot_use_through_an_import"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_change_import_binding` from `resolve`"]
    pub const resolve_change_import_binding: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_change_import_binding"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_consider_adding_a_derive` from `resolve`"]
    pub const resolve_consider_adding_a_derive: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_consider_adding_a_derive"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_consider_adding_macro_export` from `resolve`"]
    pub const resolve_consider_adding_macro_export: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_consider_adding_macro_export"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_consider_declaring_with_pub` from `resolve`"]
    pub const resolve_consider_declaring_with_pub: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_consider_declaring_with_pub"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_consider_making_the_field_public` from `resolve`"]
    pub const resolve_consider_making_the_field_public:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_consider_making_the_field_public"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_consider_marking_as_pub` from `resolve`"]
    pub const resolve_consider_marking_as_pub: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_consider_marking_as_pub"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_consider_marking_as_pub_crate` from `resolve`"]
    pub const resolve_consider_marking_as_pub_crate: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_consider_marking_as_pub_crate"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_consider_move_macro_position` from `resolve`"]
    pub const resolve_consider_move_macro_position: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_consider_move_macro_position"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_const_not_member_of_trait` from `resolve`"]
    pub const resolve_const_not_member_of_trait: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_const_not_member_of_trait"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_const_param_in_enum_discriminant` from `resolve`"]
    pub const resolve_const_param_in_enum_discriminant:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_const_param_in_enum_discriminant"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_const_param_in_non_trivial_anon_const` from `resolve`"]
    pub const resolve_const_param_in_non_trivial_anon_const:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_const_param_in_non_trivial_anon_const"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_constructor_private_if_any_field_private` from `resolve`"]
    pub const resolve_constructor_private_if_any_field_private:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_constructor_private_if_any_field_private"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_elided_anonymous_lifetime_report_error` from `resolve`"]
    pub const resolve_elided_anonymous_lifetime_report_error:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_elided_anonymous_lifetime_report_error"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_elided_anonymous_lifetime_report_error_suggestion` from `resolve`"]
    pub const resolve_elided_anonymous_lifetime_report_error_suggestion:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_elided_anonymous_lifetime_report_error_suggestion"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_expected_module_found` from `resolve`"]
    pub const resolve_expected_module_found: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_expected_module_found"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_explicit_anonymous_lifetime_report_error` from `resolve`"]
    pub const resolve_explicit_anonymous_lifetime_report_error:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_explicit_anonymous_lifetime_report_error"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_explicit_unsafe_traits` from `resolve`"]
    pub const resolve_explicit_unsafe_traits: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_explicit_unsafe_traits"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_extern_crate_loading_macro_not_at_crate_root` from `resolve`"]
    pub const resolve_extern_crate_loading_macro_not_at_crate_root:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_extern_crate_loading_macro_not_at_crate_root"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_extern_crate_not_idiomatic` from `resolve`"]
    pub const resolve_extern_crate_not_idiomatic: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_extern_crate_not_idiomatic"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_extern_crate_self_requires_renaming` from `resolve`"]
    pub const resolve_extern_crate_self_requires_renaming:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_extern_crate_self_requires_renaming"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_forward_declared_generic_in_const_param_ty` from `resolve`"]
    pub const resolve_forward_declared_generic_in_const_param_ty:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_forward_declared_generic_in_const_param_ty"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_forward_declared_generic_param` from `resolve`"]
    pub const resolve_forward_declared_generic_param:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_forward_declared_generic_param"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_found_an_item_configured_out` from `resolve`"]
    pub const resolve_found_an_item_configured_out: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_found_an_item_configured_out"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_generic_arguments_in_macro_path` from `resolve`"]
    pub const resolve_generic_arguments_in_macro_path:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_generic_arguments_in_macro_path"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_generic_params_from_outer_item` from `resolve`"]
    pub const resolve_generic_params_from_outer_item:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_generic_params_from_outer_item"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_generic_params_from_outer_item.refer_to_type_directly` from `resolve`"]
    pub const resolve_refer_to_type_directly: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("refer_to_type_directly"));
    #[doc =
    "Constant referring to Fluent message `resolve_generic_params_from_outer_item_const` from `resolve`"]
    pub const resolve_generic_params_from_outer_item_const:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_generic_params_from_outer_item_const"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_generic_params_from_outer_item_const_param` from `resolve`"]
    pub const resolve_generic_params_from_outer_item_const_param:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_generic_params_from_outer_item_const_param"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_generic_params_from_outer_item_inner_item` from `resolve`"]
    pub const resolve_generic_params_from_outer_item_inner_item:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_generic_params_from_outer_item_inner_item"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_generic_params_from_outer_item_self_ty_alias` from `resolve`"]
    pub const resolve_generic_params_from_outer_item_self_ty_alias:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_generic_params_from_outer_item_self_ty_alias"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_generic_params_from_outer_item_self_ty_param` from `resolve`"]
    pub const resolve_generic_params_from_outer_item_self_ty_param:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_generic_params_from_outer_item_self_ty_param"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_generic_params_from_outer_item_static` from `resolve`"]
    pub const resolve_generic_params_from_outer_item_static:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_generic_params_from_outer_item_static"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_generic_params_from_outer_item_ty_param` from `resolve`"]
    pub const resolve_generic_params_from_outer_item_ty_param:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_generic_params_from_outer_item_ty_param"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_ident_bound_more_than_once_in_parameter_list` from `resolve`"]
    pub const resolve_ident_bound_more_than_once_in_parameter_list:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_ident_bound_more_than_once_in_parameter_list"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_ident_bound_more_than_once_in_same_pattern` from `resolve`"]
    pub const resolve_ident_bound_more_than_once_in_same_pattern:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_ident_bound_more_than_once_in_same_pattern"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_ident_imported_here_but_it_is_desc` from `resolve`"]
    pub const resolve_ident_imported_here_but_it_is_desc:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_ident_imported_here_but_it_is_desc"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_ident_in_scope_but_it_is_desc` from `resolve`"]
    pub const resolve_ident_in_scope_but_it_is_desc: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_ident_in_scope_but_it_is_desc"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_implicit_elided_lifetimes_not_allowed_here` from `resolve`"]
    pub const resolve_implicit_elided_lifetimes_not_allowed_here:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_implicit_elided_lifetimes_not_allowed_here"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_imported_crate` from `resolve`"]
    pub const resolve_imported_crate: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_imported_crate"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_imported_macro_not_found` from `resolve`"]
    pub const resolve_imported_macro_not_found: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_imported_macro_not_found"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_imports_cannot_refer_to` from `resolve`"]
    pub const resolve_imports_cannot_refer_to: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_imports_cannot_refer_to"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_indeterminate` from `resolve`"]
    pub const resolve_indeterminate: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_indeterminate"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_invalid_asm_sym` from `resolve`"]
    pub const resolve_invalid_asm_sym: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_invalid_asm_sym"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_is_private` from `resolve`"]
    pub const resolve_is_private: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_is_private"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_item_was_behind_feature` from `resolve`"]
    pub const resolve_item_was_behind_feature: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_item_was_behind_feature"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_item_was_cfg_out` from `resolve`"]
    pub const resolve_item_was_cfg_out: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_item_was_cfg_out"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_label_with_similar_name_reachable` from `resolve`"]
    pub const resolve_label_with_similar_name_reachable:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_label_with_similar_name_reachable"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_legacy_derive_helpers` from `resolve`"]
    pub const resolve_legacy_derive_helpers: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_legacy_derive_helpers"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_lending_iterator_report_error` from `resolve`"]
    pub const resolve_lending_iterator_report_error: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_lending_iterator_report_error"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_lifetime_param_in_enum_discriminant` from `resolve`"]
    pub const resolve_lifetime_param_in_enum_discriminant:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_lifetime_param_in_enum_discriminant"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_lifetime_param_in_non_trivial_anon_const` from `resolve`"]
    pub const resolve_lifetime_param_in_non_trivial_anon_const:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_lifetime_param_in_non_trivial_anon_const"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_lowercase_self` from `resolve`"]
    pub const resolve_lowercase_self: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_lowercase_self"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_macro_cannot_use_as_attr` from `resolve`"]
    pub const resolve_macro_cannot_use_as_attr: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_macro_cannot_use_as_attr"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_macro_cannot_use_as_derive` from `resolve`"]
    pub const resolve_macro_cannot_use_as_derive: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_macro_cannot_use_as_derive"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_macro_cannot_use_as_fn_like` from `resolve`"]
    pub const resolve_macro_cannot_use_as_fn_like: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_macro_cannot_use_as_fn_like"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_macro_defined_later` from `resolve`"]
    pub const resolve_macro_defined_later: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_macro_defined_later"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_macro_expanded_extern_crate_cannot_shadow_extern_arguments` from `resolve`"]
    pub const
        resolve_macro_expanded_extern_crate_cannot_shadow_extern_arguments:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_macro_expanded_extern_crate_cannot_shadow_extern_arguments"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_macro_expanded_macro_exports_accessed_by_absolute_paths` from `resolve`"]
    pub const resolve_macro_expanded_macro_exports_accessed_by_absolute_paths:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_macro_expanded_macro_exports_accessed_by_absolute_paths"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_macro_expected_found` from `resolve`"]
    pub const resolve_macro_expected_found: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_macro_expected_found"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_macro_extern_deprecated` from `resolve`"]
    pub const resolve_macro_extern_deprecated: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_macro_extern_deprecated"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_macro_is_private` from `resolve`"]
    pub const resolve_macro_is_private: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_macro_is_private"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_macro_rule_never_used` from `resolve`"]
    pub const resolve_macro_rule_never_used: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_macro_rule_never_used"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_macro_use_deprecated` from `resolve`"]
    pub const resolve_macro_use_deprecated: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_macro_use_deprecated"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_macro_use_extern_crate_self` from `resolve`"]
    pub const resolve_macro_use_extern_crate_self: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_macro_use_extern_crate_self"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_macro_use_name_already_in_use` from `resolve`"]
    pub const resolve_macro_use_name_already_in_use: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_macro_use_name_already_in_use"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_method_not_member_of_trait` from `resolve`"]
    pub const resolve_method_not_member_of_trait: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_method_not_member_of_trait"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_missing_macro_rules_name` from `resolve`"]
    pub const resolve_missing_macro_rules_name: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_missing_macro_rules_name"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_module_only` from `resolve`"]
    pub const resolve_module_only: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_module_only"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_name_defined_multiple_time` from `resolve`"]
    pub const resolve_name_defined_multiple_time: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_name_defined_multiple_time"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_name_defined_multiple_time_old_binding_definition` from `resolve`"]
    pub const resolve_name_defined_multiple_time_old_binding_definition:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_name_defined_multiple_time_old_binding_definition"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_name_defined_multiple_time_old_binding_import` from `resolve`"]
    pub const resolve_name_defined_multiple_time_old_binding_import:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_name_defined_multiple_time_old_binding_import"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_name_defined_multiple_time_redefined` from `resolve`"]
    pub const resolve_name_defined_multiple_time_redefined:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_name_defined_multiple_time_redefined"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_name_defined_multiple_time_reimported` from `resolve`"]
    pub const resolve_name_defined_multiple_time_reimported:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_name_defined_multiple_time_reimported"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_name_is_already_used_as_generic_parameter` from `resolve`"]
    pub const resolve_name_is_already_used_as_generic_parameter:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_name_is_already_used_as_generic_parameter"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_name_is_already_used_as_generic_parameter.first_use_of_name` from `resolve`"]
    pub const resolve_first_use_of_name: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("first_use_of_name"));
    #[doc =
    "Constant referring to Fluent message `resolve_name_reserved_in_attribute_namespace` from `resolve`"]
    pub const resolve_name_reserved_in_attribute_namespace:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_name_reserved_in_attribute_namespace"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_note_and_refers_to_the_item_defined_here` from `resolve`"]
    pub const resolve_note_and_refers_to_the_item_defined_here:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_note_and_refers_to_the_item_defined_here"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_out_of_scope_macro_calls` from `resolve`"]
    pub const resolve_out_of_scope_macro_calls: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_out_of_scope_macro_calls"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_outer_ident_is_not_publicly_reexported` from `resolve`"]
    pub const resolve_outer_ident_is_not_publicly_reexported:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_outer_ident_is_not_publicly_reexported"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_param_in_enum_discriminant` from `resolve`"]
    pub const resolve_param_in_enum_discriminant: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_param_in_enum_discriminant"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_param_in_non_trivial_anon_const` from `resolve`"]
    pub const resolve_param_in_non_trivial_anon_const:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_param_in_non_trivial_anon_const"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_param_in_non_trivial_anon_const_help` from `resolve`"]
    pub const resolve_param_in_non_trivial_anon_const_help:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_param_in_non_trivial_anon_const_help"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_param_in_ty_of_const_param` from `resolve`"]
    pub const resolve_param_in_ty_of_const_param: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_param_in_ty_of_const_param"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_pattern_doesnt_bind_name` from `resolve`"]
    pub const resolve_pattern_doesnt_bind_name: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_pattern_doesnt_bind_name"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_private_extern_crate_reexport` from `resolve`"]
    pub const resolve_private_extern_crate_reexport: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_private_extern_crate_reexport"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_proc_macro_derive_resolution_fallback` from `resolve`"]
    pub const resolve_proc_macro_derive_resolution_fallback:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_proc_macro_derive_resolution_fallback"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_proc_macro_same_crate` from `resolve`"]
    pub const resolve_proc_macro_same_crate: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_proc_macro_same_crate"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_redundant_import_visibility` from `resolve`"]
    pub const resolve_redundant_import_visibility: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_redundant_import_visibility"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_reexport_of_crate_public` from `resolve`"]
    pub const resolve_reexport_of_crate_public: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_reexport_of_crate_public"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_reexport_of_private` from `resolve`"]
    pub const resolve_reexport_of_private: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_reexport_of_private"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_reexport_private_dependency` from `resolve`"]
    pub const resolve_reexport_private_dependency: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_reexport_private_dependency"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_relative_2018` from `resolve`"]
    pub const resolve_relative_2018: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_relative_2018"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_remove_surrounding_derive` from `resolve`"]
    pub const resolve_remove_surrounding_derive: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_remove_surrounding_derive"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_remove_unnecessary_import` from `resolve`"]
    pub const resolve_remove_unnecessary_import: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_remove_unnecessary_import"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_self_import_can_only_appear_once_in_the_list` from `resolve`"]
    pub const resolve_self_import_can_only_appear_once_in_the_list:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_self_import_can_only_appear_once_in_the_list"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_self_import_only_in_import_list_with_non_empty_prefix` from `resolve`"]
    pub const resolve_self_import_only_in_import_list_with_non_empty_prefix:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_self_import_only_in_import_list_with_non_empty_prefix"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_self_imports_only_allowed_within` from `resolve`"]
    pub const resolve_self_imports_only_allowed_within:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_self_imports_only_allowed_within"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_self_imports_only_allowed_within_multipart_suggestion` from `resolve`"]
    pub const resolve_self_imports_only_allowed_within_multipart_suggestion:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_self_imports_only_allowed_within_multipart_suggestion"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_self_imports_only_allowed_within_suggestion` from `resolve`"]
    pub const resolve_self_imports_only_allowed_within_suggestion:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_self_imports_only_allowed_within_suggestion"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_self_in_const_generic_ty` from `resolve`"]
    pub const resolve_self_in_const_generic_ty: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_self_in_const_generic_ty"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_self_in_generic_param_default` from `resolve`"]
    pub const resolve_self_in_generic_param_default: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_self_in_generic_param_default"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_similarly_named_defined_here` from `resolve`"]
    pub const resolve_similarly_named_defined_here: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_similarly_named_defined_here"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_single_item_defined_here` from `resolve`"]
    pub const resolve_single_item_defined_here: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_single_item_defined_here"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_static_lifetime_is_reserved` from `resolve`"]
    pub const resolve_static_lifetime_is_reserved: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_static_lifetime_is_reserved"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_suggestion_import_ident_directly` from `resolve`"]
    pub const resolve_suggestion_import_ident_directly:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_suggestion_import_ident_directly"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_suggestion_import_ident_through_reexport` from `resolve`"]
    pub const resolve_suggestion_import_ident_through_reexport:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_suggestion_import_ident_through_reexport"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_tool_module_imported` from `resolve`"]
    pub const resolve_tool_module_imported: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_tool_module_imported"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_tool_only_accepts_identifiers` from `resolve`"]
    pub const resolve_tool_only_accepts_identifiers: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_tool_only_accepts_identifiers"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_tool_was_already_registered` from `resolve`"]
    pub const resolve_tool_was_already_registered: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_tool_was_already_registered"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_trait_impl_duplicate` from `resolve`"]
    pub const resolve_trait_impl_duplicate: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_trait_impl_duplicate"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_trait_impl_duplicate.old_span_label` from `resolve`"]
    pub const resolve_old_span_label: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("old_span_label"));
    #[doc =
    "Constant referring to Fluent message `resolve_trait_impl_duplicate.trait_item_span` from `resolve`"]
    pub const resolve_trait_item_span: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("trait_item_span"));
    #[doc =
    "Constant referring to Fluent message `resolve_trait_impl_mismatch` from `resolve`"]
    pub const resolve_trait_impl_mismatch: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_trait_impl_mismatch"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_trait_impl_mismatch.trait_impl_mismatch_label_item` from `resolve`"]
    pub const resolve_trait_impl_mismatch_label_item:
        rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("trait_impl_mismatch_label_item"));
    #[doc =
    "Constant referring to Fluent message `resolve_try_using_similarly_named_label` from `resolve`"]
    pub const resolve_try_using_similarly_named_label:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_try_using_similarly_named_label"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_type_not_member_of_trait` from `resolve`"]
    pub const resolve_type_not_member_of_trait: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_type_not_member_of_trait"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_type_param_in_enum_discriminant` from `resolve`"]
    pub const resolve_type_param_in_enum_discriminant:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_type_param_in_enum_discriminant"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_type_param_in_non_trivial_anon_const` from `resolve`"]
    pub const resolve_type_param_in_non_trivial_anon_const:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_type_param_in_non_trivial_anon_const"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_undeclared_label` from `resolve`"]
    pub const resolve_undeclared_label: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_undeclared_label"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_underscore_lifetime_is_reserved` from `resolve`"]
    pub const resolve_underscore_lifetime_is_reserved:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_underscore_lifetime_is_reserved"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_unexpected_res_change_ty_to_const_param_sugg` from `resolve`"]
    pub const resolve_unexpected_res_change_ty_to_const_param_sugg:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_unexpected_res_change_ty_to_const_param_sugg"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_unexpected_res_use_at_op_in_slice_pat_with_range_sugg` from `resolve`"]
    pub const resolve_unexpected_res_use_at_op_in_slice_pat_with_range_sugg:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_unexpected_res_use_at_op_in_slice_pat_with_range_sugg"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_unknown_diagnostic_attribute` from `resolve`"]
    pub const resolve_unknown_diagnostic_attribute: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_unknown_diagnostic_attribute"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_unknown_diagnostic_attribute_typo_sugg` from `resolve`"]
    pub const resolve_unknown_diagnostic_attribute_typo_sugg:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_unknown_diagnostic_attribute_typo_sugg"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_unnamed_crate_root_import` from `resolve`"]
    pub const resolve_unnamed_crate_root_import: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_unnamed_crate_root_import"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_unreachable_label` from `resolve`"]
    pub const resolve_unreachable_label: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_unreachable_label"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_unreachable_label.label_definition_span` from `resolve`"]
    pub const resolve_label_definition_span: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("label_definition_span"));
    #[doc =
    "Constant referring to Fluent message `resolve_unreachable_label_similar_name_reachable` from `resolve`"]
    pub const resolve_unreachable_label_similar_name_reachable:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_unreachable_label_similar_name_reachable"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_unreachable_label_similar_name_unreachable` from `resolve`"]
    pub const resolve_unreachable_label_similar_name_unreachable:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_unreachable_label_similar_name_unreachable"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_unreachable_label_suggestion_use_similarly_named` from `resolve`"]
    pub const resolve_unreachable_label_suggestion_use_similarly_named:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_unreachable_label_suggestion_use_similarly_named"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_unreachable_label_with_similar_name_exists` from `resolve`"]
    pub const resolve_unreachable_label_with_similar_name_exists:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_unreachable_label_with_similar_name_exists"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_unused_extern_crate` from `resolve`"]
    pub const resolve_unused_extern_crate: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_unused_extern_crate"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_unused_label` from `resolve`"]
    pub const resolve_unused_label: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_unused_label"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_unused_macro_definition` from `resolve`"]
    pub const resolve_unused_macro_definition: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_unused_macro_definition"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_unused_macro_use` from `resolve`"]
    pub const resolve_unused_macro_use: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_unused_macro_use"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_variable_bound_with_different_mode` from `resolve`"]
    pub const resolve_variable_bound_with_different_mode:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_variable_bound_with_different_mode"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_variable_bound_with_different_mode.first_binding_span` from `resolve`"]
    pub const resolve_first_binding_span: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("first_binding_span"));
    #[doc =
    "Constant referring to Fluent message `resolve_variable_is_a_typo` from `resolve`"]
    pub const resolve_variable_is_a_typo: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_variable_is_a_typo"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_variable_is_not_bound_in_all_patterns` from `resolve`"]
    pub const resolve_variable_is_not_bound_in_all_patterns:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_variable_is_not_bound_in_all_patterns"),
            None);
    #[doc =
    "Constant referring to Fluent message `resolve_variable_not_in_all_patterns` from `resolve`"]
    pub const resolve_variable_not_in_all_patterns: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("resolve_variable_not_in_all_patterns"),
            None);
    #[doc =
    r" Constants expected to exist by the diagnostic derive macros to use as default Fluent"]
    #[doc = r" identifiers for different subdiagnostic kinds."]
    pub mod _subdiag {
        #[doc = r" Default for `#[help]`"]
        pub const help: rustc_errors::SubdiagMessage =
            rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("help"));
        #[doc = r" Default for `#[note]`"]
        pub const note: rustc_errors::SubdiagMessage =
            rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("note"));
        #[doc = r" Default for `#[warn]`"]
        pub const warn: rustc_errors::SubdiagMessage =
            rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("warn"));
        #[doc = r" Default for `#[label]`"]
        pub const label: rustc_errors::SubdiagMessage =
            rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("label"));
        #[doc = r" Default for `#[suggestion]`"]
        pub const suggestion: rustc_errors::SubdiagMessage =
            rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("suggestion"));
    }
}rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
102
103#[derive(#[automatically_derived]
impl ::core::marker::Copy for Determinacy { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Determinacy {
    #[inline]
    fn clone(&self) -> Determinacy { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Determinacy {
    #[inline]
    fn eq(&self, other: &Determinacy) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for Determinacy {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Determinacy::Determined => "Determined",
                Determinacy::Undetermined => "Undetermined",
            })
    }
}Debug)]
104enum Determinacy {
105    Determined,
106    Undetermined,
107}
108
109impl Determinacy {
110    fn determined(determined: bool) -> Determinacy {
111        if determined { Determinacy::Determined } else { Determinacy::Undetermined }
112    }
113}
114
115/// A specific scope in which a name can be looked up.
116#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for Scope<'ra> {
    #[inline]
    fn clone(&self) -> Scope<'ra> {
        let _: ::core::clone::AssertParamIsClone<LocalExpnId>;
        let _: ::core::clone::AssertParamIsClone<MacroRulesScopeRef<'ra>>;
        let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
        let _: ::core::clone::AssertParamIsClone<Option<NodeId>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for Scope<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for Scope<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Scope::DeriveHelpers(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "DeriveHelpers", &__self_0),
            Scope::DeriveHelpersCompat =>
                ::core::fmt::Formatter::write_str(f, "DeriveHelpersCompat"),
            Scope::MacroRules(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "MacroRules", &__self_0),
            Scope::Module(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Module",
                    __self_0, &__self_1),
            Scope::MacroUsePrelude =>
                ::core::fmt::Formatter::write_str(f, "MacroUsePrelude"),
            Scope::BuiltinAttrs =>
                ::core::fmt::Formatter::write_str(f, "BuiltinAttrs"),
            Scope::ExternPreludeItems =>
                ::core::fmt::Formatter::write_str(f, "ExternPreludeItems"),
            Scope::ExternPreludeFlags =>
                ::core::fmt::Formatter::write_str(f, "ExternPreludeFlags"),
            Scope::ToolPrelude =>
                ::core::fmt::Formatter::write_str(f, "ToolPrelude"),
            Scope::StdLibPrelude =>
                ::core::fmt::Formatter::write_str(f, "StdLibPrelude"),
            Scope::BuiltinTypes =>
                ::core::fmt::Formatter::write_str(f, "BuiltinTypes"),
        }
    }
}Debug)]
117enum Scope<'ra> {
118    /// Inert attributes registered by derive macros.
119    DeriveHelpers(LocalExpnId),
120    /// Inert attributes registered by derive macros, but used before they are actually declared.
121    /// This scope will exist until the compatibility lint `LEGACY_DERIVE_HELPERS`
122    /// is turned into a hard error.
123    DeriveHelpersCompat,
124    /// Textual `let`-like scopes introduced by `macro_rules!` items.
125    MacroRules(MacroRulesScopeRef<'ra>),
126    /// Names declared in the given module.
127    /// The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK`
128    /// lint if it should be reported.
129    Module(Module<'ra>, Option<NodeId>),
130    /// Names introduced by `#[macro_use]` attributes on `extern crate` items.
131    MacroUsePrelude,
132    /// Built-in attributes.
133    BuiltinAttrs,
134    /// Extern prelude names introduced by `extern crate` items.
135    ExternPreludeItems,
136    /// Extern prelude names introduced by `--extern` flags.
137    ExternPreludeFlags,
138    /// Tool modules introduced with `#![register_tool]`.
139    ToolPrelude,
140    /// Standard library prelude introduced with an internal `#[prelude_import]` import.
141    StdLibPrelude,
142    /// Built-in types.
143    BuiltinTypes,
144}
145
146/// Names from different contexts may want to visit different subsets of all specific scopes
147/// with different restrictions when looking up the resolution.
148#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for ScopeSet<'ra> {
    #[inline]
    fn clone(&self) -> ScopeSet<'ra> {
        let _: ::core::clone::AssertParamIsClone<Namespace>;
        let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
        let _: ::core::clone::AssertParamIsClone<MacroKind>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for ScopeSet<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for ScopeSet<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ScopeSet::All(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "All",
                    &__self_0),
            ScopeSet::ModuleAndExternPrelude(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "ModuleAndExternPrelude", __self_0, &__self_1),
            ScopeSet::ExternPrelude =>
                ::core::fmt::Formatter::write_str(f, "ExternPrelude"),
            ScopeSet::Macro(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Macro",
                    &__self_0),
        }
    }
}Debug)]
149enum ScopeSet<'ra> {
150    /// All scopes with the given namespace.
151    All(Namespace),
152    /// A module, then extern prelude (used for mixed 2015-2018 mode in macros).
153    ModuleAndExternPrelude(Namespace, Module<'ra>),
154    /// Just two extern prelude scopes.
155    ExternPrelude,
156    /// Same as `All(MacroNS)`, but with the given macro kind restriction.
157    Macro(MacroKind),
158}
159
160/// Everything you need to know about a name's location to resolve it.
161/// Serves as a starting point for the scope visitor.
162/// This struct is currently used only for early resolution (imports and macros),
163/// but not for late resolution yet.
164#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for ParentScope<'ra> {
    #[inline]
    fn clone(&self) -> ParentScope<'ra> {
        let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
        let _: ::core::clone::AssertParamIsClone<LocalExpnId>;
        let _: ::core::clone::AssertParamIsClone<MacroRulesScopeRef<'ra>>;
        let _: ::core::clone::AssertParamIsClone<&'ra [ast::Path]>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for ParentScope<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for ParentScope<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "ParentScope",
            "module", &self.module, "expansion", &self.expansion,
            "macro_rules", &self.macro_rules, "derives", &&self.derives)
    }
}Debug)]
165struct ParentScope<'ra> {
166    module: Module<'ra>,
167    expansion: LocalExpnId,
168    macro_rules: MacroRulesScopeRef<'ra>,
169    derives: &'ra [ast::Path],
170}
171
172impl<'ra> ParentScope<'ra> {
173    /// Creates a parent scope with the passed argument used as the module scope component,
174    /// and other scope components set to default empty values.
175    fn module(module: Module<'ra>, arenas: &'ra ResolverArenas<'ra>) -> ParentScope<'ra> {
176        ParentScope {
177            module,
178            expansion: LocalExpnId::ROOT,
179            macro_rules: arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
180            derives: &[],
181        }
182    }
183}
184
185#[derive(#[automatically_derived]
impl ::core::marker::Copy for InvocationParent { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for InvocationParent {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "InvocationParent", "parent_def", &self.parent_def,
            "impl_trait_context", &self.impl_trait_context, "in_attr",
            &&self.in_attr)
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for InvocationParent {
    #[inline]
    fn clone(&self) -> InvocationParent {
        let _: ::core::clone::AssertParamIsClone<LocalDefId>;
        let _: ::core::clone::AssertParamIsClone<ImplTraitContext>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone)]
186struct InvocationParent {
187    parent_def: LocalDefId,
188    impl_trait_context: ImplTraitContext,
189    in_attr: bool,
190}
191
192impl InvocationParent {
193    const ROOT: Self = Self {
194        parent_def: CRATE_DEF_ID,
195        impl_trait_context: ImplTraitContext::Existential,
196        in_attr: false,
197    };
198}
199
200#[derive(#[automatically_derived]
impl ::core::marker::Copy for ImplTraitContext { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for ImplTraitContext {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ImplTraitContext::Existential => "Existential",
                ImplTraitContext::Universal => "Universal",
                ImplTraitContext::InBinding => "InBinding",
            })
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for ImplTraitContext {
    #[inline]
    fn clone(&self) -> ImplTraitContext { *self }
}Clone)]
201enum ImplTraitContext {
202    Existential,
203    Universal,
204    InBinding,
205}
206
207/// Used for tracking import use types which will be used for redundant import checking.
208///
209/// ### Used::Scope Example
210///
211/// ```rust,compile_fail
212/// #![deny(redundant_imports)]
213/// use std::mem::drop;
214/// fn main() {
215///     let s = Box::new(32);
216///     drop(s);
217/// }
218/// ```
219///
220/// Used::Other is for other situations like module-relative uses.
221#[derive(#[automatically_derived]
impl ::core::clone::Clone for Used {
    #[inline]
    fn clone(&self) -> Used { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Used { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for Used {
    #[inline]
    fn eq(&self, other: &Used) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::PartialOrd for Used {
    #[inline]
    fn partial_cmp(&self, other: &Used)
        -> ::core::option::Option<::core::cmp::Ordering> {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        ::core::cmp::PartialOrd::partial_cmp(&__self_discr, &__arg1_discr)
    }
}PartialOrd, #[automatically_derived]
impl ::core::fmt::Debug for Used {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self { Used::Scope => "Scope", Used::Other => "Other", })
    }
}Debug)]
222enum Used {
223    Scope,
224    Other,
225}
226
227#[derive(#[automatically_derived]
impl ::core::fmt::Debug for BindingError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "BindingError",
            "name", &self.name, "origin", &self.origin, "target",
            &self.target, "could_be_path", &&self.could_be_path)
    }
}Debug)]
228struct BindingError {
229    name: Ident,
230    origin: Vec<(Span, ast::Pat)>,
231    target: Vec<ast::Pat>,
232    could_be_path: bool,
233}
234
235#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for ResolutionError<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ResolutionError::GenericParamsFromOuterItem {
                outer_res: __self_0,
                has_generic_params: __self_1,
                def_kind: __self_2,
                inner_item: __self_3,
                current_self_ty: __self_4 } =>
                ::core::fmt::Formatter::debug_struct_field5_finish(f,
                    "GenericParamsFromOuterItem", "outer_res", __self_0,
                    "has_generic_params", __self_1, "def_kind", __self_2,
                    "inner_item", __self_3, "current_self_ty", &__self_4),
            ResolutionError::NameAlreadyUsedInParameterList(__self_0,
                __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "NameAlreadyUsedInParameterList", __self_0, &__self_1),
            ResolutionError::MethodNotMemberOfTrait(__self_0, __self_1,
                __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "MethodNotMemberOfTrait", __self_0, __self_1, &__self_2),
            ResolutionError::TypeNotMemberOfTrait(__self_0, __self_1,
                __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "TypeNotMemberOfTrait", __self_0, __self_1, &__self_2),
            ResolutionError::ConstNotMemberOfTrait(__self_0, __self_1,
                __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "ConstNotMemberOfTrait", __self_0, __self_1, &__self_2),
            ResolutionError::VariableNotBoundInPattern(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "VariableNotBoundInPattern", __self_0, &__self_1),
            ResolutionError::VariableBoundWithDifferentMode(__self_0,
                __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "VariableBoundWithDifferentMode", __self_0, &__self_1),
            ResolutionError::IdentifierBoundMoreThanOnceInParameterList(__self_0)
                =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "IdentifierBoundMoreThanOnceInParameterList", &__self_0),
            ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(__self_0)
                =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "IdentifierBoundMoreThanOnceInSamePattern", &__self_0),
            ResolutionError::UndeclaredLabel {
                name: __self_0, suggestion: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "UndeclaredLabel", "name", __self_0, "suggestion",
                    &__self_1),
            ResolutionError::SelfImportsOnlyAllowedWithin {
                root: __self_0, span_with_rename: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "SelfImportsOnlyAllowedWithin", "root", __self_0,
                    "span_with_rename", &__self_1),
            ResolutionError::SelfImportCanOnlyAppearOnceInTheList =>
                ::core::fmt::Formatter::write_str(f,
                    "SelfImportCanOnlyAppearOnceInTheList"),
            ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix =>
                ::core::fmt::Formatter::write_str(f,
                    "SelfImportOnlyInImportListWithNonEmptyPrefix"),
            ResolutionError::FailedToResolve {
                segment: __self_0,
                label: __self_1,
                suggestion: __self_2,
                module: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "FailedToResolve", "segment", __self_0, "label", __self_1,
                    "suggestion", __self_2, "module", &__self_3),
            ResolutionError::CannotCaptureDynamicEnvironmentInFnItem =>
                ::core::fmt::Formatter::write_str(f,
                    "CannotCaptureDynamicEnvironmentInFnItem"),
            ResolutionError::AttemptToUseNonConstantValueInConstant {
                ident: __self_0,
                suggestion: __self_1,
                current: __self_2,
                type_span: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "AttemptToUseNonConstantValueInConstant", "ident", __self_0,
                    "suggestion", __self_1, "current", __self_2, "type_span",
                    &__self_3),
            ResolutionError::BindingShadowsSomethingUnacceptable {
                shadowing_binding: __self_0,
                name: __self_1,
                participle: __self_2,
                article: __self_3,
                shadowed_binding: __self_4,
                shadowed_binding_span: __self_5 } => {
                let names: &'static _ =
                    &["shadowing_binding", "name", "participle", "article",
                                "shadowed_binding", "shadowed_binding_span"];
                let values: &[&dyn ::core::fmt::Debug] =
                    &[__self_0, __self_1, __self_2, __self_3, __self_4,
                                &__self_5];
                ::core::fmt::Formatter::debug_struct_fields_finish(f,
                    "BindingShadowsSomethingUnacceptable", names, values)
            }
            ResolutionError::ForwardDeclaredGenericParam(__self_0, __self_1)
                =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "ForwardDeclaredGenericParam", __self_0, &__self_1),
            ResolutionError::ParamInTyOfConstParam { name: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ParamInTyOfConstParam", "name", &__self_0),
            ResolutionError::ParamInNonTrivialAnonConst {
                name: __self_0, param_kind: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "ParamInNonTrivialAnonConst", "name", __self_0,
                    "param_kind", &__self_1),
            ResolutionError::ParamInEnumDiscriminant {
                name: __self_0, param_kind: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "ParamInEnumDiscriminant", "name", __self_0, "param_kind",
                    &__self_1),
            ResolutionError::ForwardDeclaredSelf(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ForwardDeclaredSelf", &__self_0),
            ResolutionError::UnreachableLabel {
                name: __self_0,
                definition_span: __self_1,
                suggestion: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "UnreachableLabel", "name", __self_0, "definition_span",
                    __self_1, "suggestion", &__self_2),
            ResolutionError::TraitImplMismatch {
                name: __self_0,
                kind: __self_1,
                trait_path: __self_2,
                trait_item_span: __self_3,
                code: __self_4 } =>
                ::core::fmt::Formatter::debug_struct_field5_finish(f,
                    "TraitImplMismatch", "name", __self_0, "kind", __self_1,
                    "trait_path", __self_2, "trait_item_span", __self_3, "code",
                    &__self_4),
            ResolutionError::TraitImplDuplicate {
                name: __self_0, trait_item_span: __self_1, old_span: __self_2
                } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "TraitImplDuplicate", "name", __self_0, "trait_item_span",
                    __self_1, "old_span", &__self_2),
            ResolutionError::InvalidAsmSym =>
                ::core::fmt::Formatter::write_str(f, "InvalidAsmSym"),
            ResolutionError::LowercaseSelf =>
                ::core::fmt::Formatter::write_str(f, "LowercaseSelf"),
            ResolutionError::BindingInNeverPattern =>
                ::core::fmt::Formatter::write_str(f, "BindingInNeverPattern"),
        }
    }
}Debug)]
236enum ResolutionError<'ra> {
237    /// Error E0401: can't use type or const parameters from outer item.
238    GenericParamsFromOuterItem {
239        outer_res: Res,
240        has_generic_params: HasGenericParams,
241        def_kind: DefKind,
242        inner_item: Option<(Span, ast::ItemKind)>,
243        current_self_ty: Option<String>,
244    },
245    /// Error E0403: the name is already used for a type or const parameter in this generic
246    /// parameter list.
247    NameAlreadyUsedInParameterList(Ident, Span),
248    /// Error E0407: method is not a member of trait.
249    MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
250    /// Error E0437: type is not a member of trait.
251    TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
252    /// Error E0438: const is not a member of trait.
253    ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
254    /// Error E0408: variable `{}` is not bound in all patterns.
255    VariableNotBoundInPattern(BindingError, ParentScope<'ra>),
256    /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
257    VariableBoundWithDifferentMode(Ident, Span),
258    /// Error E0415: identifier is bound more than once in this parameter list.
259    IdentifierBoundMoreThanOnceInParameterList(Ident),
260    /// Error E0416: identifier is bound more than once in the same pattern.
261    IdentifierBoundMoreThanOnceInSamePattern(Ident),
262    /// Error E0426: use of undeclared label.
263    UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
264    /// Error E0429: `self` imports are only allowed within a `{ }` list.
265    SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
266    /// Error E0430: `self` import can only appear once in the list.
267    SelfImportCanOnlyAppearOnceInTheList,
268    /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
269    SelfImportOnlyInImportListWithNonEmptyPrefix,
270    /// Error E0433: failed to resolve.
271    FailedToResolve {
272        segment: Option<Symbol>,
273        label: String,
274        suggestion: Option<Suggestion>,
275        module: Option<ModuleOrUniformRoot<'ra>>,
276    },
277    /// Error E0434: can't capture dynamic environment in a fn item.
278    CannotCaptureDynamicEnvironmentInFnItem,
279    /// Error E0435: attempt to use a non-constant value in a constant.
280    AttemptToUseNonConstantValueInConstant {
281        ident: Ident,
282        suggestion: &'static str,
283        current: &'static str,
284        type_span: Option<Span>,
285    },
286    /// Error E0530: `X` bindings cannot shadow `Y`s.
287    BindingShadowsSomethingUnacceptable {
288        shadowing_binding: PatternSource,
289        name: Symbol,
290        participle: &'static str,
291        article: &'static str,
292        shadowed_binding: Res,
293        shadowed_binding_span: Span,
294    },
295    /// Error E0128: generic parameters with a default cannot use forward-declared identifiers.
296    ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
297    // FIXME(generic_const_parameter_types): This should give custom output specifying it's only
298    // problematic to use *forward declared* parameters when the feature is enabled.
299    /// ERROR E0770: the type of const parameters must not depend on other generic parameters.
300    ParamInTyOfConstParam { name: Symbol },
301    /// generic parameters must not be used inside const evaluations.
302    ///
303    /// This error is only emitted when using `min_const_generics`.
304    ParamInNonTrivialAnonConst { name: Symbol, param_kind: ParamKindInNonTrivialAnonConst },
305    /// generic parameters must not be used inside enum discriminants.
306    ///
307    /// This error is emitted even with `generic_const_exprs`.
308    ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },
309    /// Error E0735: generic parameters with a default cannot use `Self`
310    ForwardDeclaredSelf(ForwardGenericParamBanReason),
311    /// Error E0767: use of unreachable label
312    UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
313    /// Error E0323, E0324, E0325: mismatch between trait item and impl item.
314    TraitImplMismatch {
315        name: Ident,
316        kind: &'static str,
317        trait_path: String,
318        trait_item_span: Span,
319        code: ErrCode,
320    },
321    /// Error E0201: multiple impl items for the same trait item.
322    TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },
323    /// Inline asm `sym` operand must refer to a `fn` or `static`.
324    InvalidAsmSym,
325    /// `self` used instead of `Self` in a generic parameter
326    LowercaseSelf,
327    /// A never pattern has a binding.
328    BindingInNeverPattern,
329}
330
331enum VisResolutionError<'a> {
332    Relative2018(Span, &'a ast::Path),
333    AncestorOnly(Span),
334    FailedToResolve(Span, String, Option<Suggestion>),
335    ExpectedFound(Span, String, Res),
336    Indeterminate(Span),
337    ModuleOnly(Span),
338}
339
340/// A minimal representation of a path segment. We use this in resolve because we synthesize 'path
341/// segments' which don't have the rest of an AST or HIR `PathSegment`.
342#[derive(#[automatically_derived]
impl ::core::clone::Clone for Segment {
    #[inline]
    fn clone(&self) -> Segment {
        let _: ::core::clone::AssertParamIsClone<Ident>;
        let _: ::core::clone::AssertParamIsClone<Option<NodeId>>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Segment { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Segment {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f, "Segment",
            "ident", &self.ident, "id", &self.id, "has_generic_args",
            &self.has_generic_args, "has_lifetime_args",
            &self.has_lifetime_args, "args_span", &&self.args_span)
    }
}Debug)]
343struct Segment {
344    ident: Ident,
345    id: Option<NodeId>,
346    /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing
347    /// nonsensical suggestions.
348    has_generic_args: bool,
349    /// Signals whether this `PathSegment` has lifetime arguments.
350    has_lifetime_args: bool,
351    args_span: Span,
352}
353
354impl Segment {
355    fn from_path(path: &Path) -> Vec<Segment> {
356        path.segments.iter().map(|s| s.into()).collect()
357    }
358
359    fn from_ident(ident: Ident) -> Segment {
360        Segment {
361            ident,
362            id: None,
363            has_generic_args: false,
364            has_lifetime_args: false,
365            args_span: DUMMY_SP,
366        }
367    }
368
369    fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment {
370        Segment {
371            ident,
372            id: Some(id),
373            has_generic_args: false,
374            has_lifetime_args: false,
375            args_span: DUMMY_SP,
376        }
377    }
378
379    fn names_to_string(segments: &[Segment]) -> String {
380        names_to_string(segments.iter().map(|seg| seg.ident.name))
381    }
382}
383
384impl<'a> From<&'a ast::PathSegment> for Segment {
385    fn from(seg: &'a ast::PathSegment) -> Segment {
386        let has_generic_args = seg.args.is_some();
387        let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
388            match args {
389                GenericArgs::AngleBracketed(args) => {
390                    let found_lifetimes = args
391                        .args
392                        .iter()
393                        .any(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
    AngleBracketedArg::Arg(GenericArg::Lifetime(_)) => true,
    _ => false,
}matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
394                    (args.span, found_lifetimes)
395                }
396                GenericArgs::Parenthesized(args) => (args.span, true),
397                GenericArgs::ParenthesizedElided(span) => (*span, true),
398            }
399        } else {
400            (DUMMY_SP, false)
401        };
402        Segment {
403            ident: seg.ident,
404            id: Some(seg.id),
405            has_generic_args,
406            has_lifetime_args,
407            args_span,
408        }
409    }
410}
411
412/// An intermediate resolution result.
413///
414/// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
415/// items are visible in their whole block, while `Res`es only from the place they are defined
416/// forward.
417#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for LexicalScopeBinding<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LexicalScopeBinding::Item(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Item",
                    &__self_0),
            LexicalScopeBinding::Res(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Res",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'ra> ::core::marker::Copy for LexicalScopeBinding<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::clone::Clone for LexicalScopeBinding<'ra> {
    #[inline]
    fn clone(&self) -> LexicalScopeBinding<'ra> {
        let _: ::core::clone::AssertParamIsClone<NameBinding<'ra>>;
        let _: ::core::clone::AssertParamIsClone<Res>;
        *self
    }
}Clone)]
418enum LexicalScopeBinding<'ra> {
419    Item(NameBinding<'ra>),
420    Res(Res),
421}
422
423impl<'ra> LexicalScopeBinding<'ra> {
424    fn res(self) -> Res {
425        match self {
426            LexicalScopeBinding::Item(binding) => binding.res(),
427            LexicalScopeBinding::Res(res) => res,
428        }
429    }
430}
431
432#[derive(#[automatically_derived]
impl<'ra> ::core::marker::Copy for ModuleOrUniformRoot<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::clone::Clone for ModuleOrUniformRoot<'ra> {
    #[inline]
    fn clone(&self) -> ModuleOrUniformRoot<'ra> {
        let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
        let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for ModuleOrUniformRoot<'ra> {
    #[inline]
    fn eq(&self, other: &ModuleOrUniformRoot<'ra>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ModuleOrUniformRoot::Module(__self_0),
                    ModuleOrUniformRoot::Module(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (ModuleOrUniformRoot::ModuleAndExternPrelude(__self_0),
                    ModuleOrUniformRoot::ModuleAndExternPrelude(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for ModuleOrUniformRoot<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ModuleOrUniformRoot::Module(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Module",
                    &__self_0),
            ModuleOrUniformRoot::ModuleAndExternPrelude(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ModuleAndExternPrelude", &__self_0),
            ModuleOrUniformRoot::ExternPrelude =>
                ::core::fmt::Formatter::write_str(f, "ExternPrelude"),
            ModuleOrUniformRoot::CurrentScope =>
                ::core::fmt::Formatter::write_str(f, "CurrentScope"),
        }
    }
}Debug)]
433enum ModuleOrUniformRoot<'ra> {
434    /// Regular module.
435    Module(Module<'ra>),
436
437    /// Virtual module that denotes resolution in a module with fallback to extern prelude.
438    /// Used for paths starting with `::` coming from 2015 edition macros
439    /// used in 2018+ edition crates.
440    ModuleAndExternPrelude(Module<'ra>),
441
442    /// Virtual module that denotes resolution in extern prelude.
443    /// Used for paths starting with `::` on 2018 edition.
444    ExternPrelude,
445
446    /// Virtual module that denotes resolution in current scope.
447    /// Used only for resolving single-segment imports. The reason it exists is that import paths
448    /// are always split into two parts, the first of which should be some kind of module.
449    CurrentScope,
450}
451
452#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for PathResult<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            PathResult::Module(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Module",
                    &__self_0),
            PathResult::NonModule(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "NonModule", &__self_0),
            PathResult::Indeterminate =>
                ::core::fmt::Formatter::write_str(f, "Indeterminate"),
            PathResult::Failed {
                span: __self_0,
                label: __self_1,
                suggestion: __self_2,
                is_error_from_last_segment: __self_3,
                module: __self_4,
                segment_name: __self_5,
                error_implied_by_parse_error: __self_6 } => {
                let names: &'static _ =
                    &["span", "label", "suggestion",
                                "is_error_from_last_segment", "module", "segment_name",
                                "error_implied_by_parse_error"];
                let values: &[&dyn ::core::fmt::Debug] =
                    &[__self_0, __self_1, __self_2, __self_3, __self_4,
                                __self_5, &__self_6];
                ::core::fmt::Formatter::debug_struct_fields_finish(f,
                    "Failed", names, values)
            }
        }
    }
}Debug)]
453enum PathResult<'ra> {
454    Module(ModuleOrUniformRoot<'ra>),
455    NonModule(PartialRes),
456    Indeterminate,
457    Failed {
458        span: Span,
459        label: String,
460        suggestion: Option<Suggestion>,
461        is_error_from_last_segment: bool,
462        /// The final module being resolved, for instance:
463        ///
464        /// ```compile_fail
465        /// mod a {
466        ///     mod b {
467        ///         mod c {}
468        ///     }
469        /// }
470        ///
471        /// use a::not_exist::c;
472        /// ```
473        ///
474        /// In this case, `module` will point to `a`.
475        module: Option<ModuleOrUniformRoot<'ra>>,
476        /// The segment name of target
477        segment_name: Symbol,
478        error_implied_by_parse_error: bool,
479    },
480}
481
482impl<'ra> PathResult<'ra> {
483    fn failed(
484        ident: Ident,
485        is_error_from_last_segment: bool,
486        finalize: bool,
487        error_implied_by_parse_error: bool,
488        module: Option<ModuleOrUniformRoot<'ra>>,
489        label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
490    ) -> PathResult<'ra> {
491        let (label, suggestion) =
492            if finalize { label_and_suggestion() } else { (String::new(), None) };
493        PathResult::Failed {
494            span: ident.span,
495            segment_name: ident.name,
496            label,
497            suggestion,
498            is_error_from_last_segment,
499            module,
500            error_implied_by_parse_error,
501        }
502    }
503}
504
505#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ModuleKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ModuleKind::Block =>
                ::core::fmt::Formatter::write_str(f, "Block"),
            ModuleKind::Def(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f, "Def",
                    __self_0, __self_1, &__self_2),
        }
    }
}Debug)]
506enum ModuleKind {
507    /// An anonymous module; e.g., just a block.
508    ///
509    /// ```
510    /// fn main() {
511    ///     fn f() {} // (1)
512    ///     { // This is an anonymous module
513    ///         f(); // This resolves to (2) as we are inside the block.
514    ///         fn f() {} // (2)
515    ///     }
516    ///     f(); // Resolves to (1)
517    /// }
518    /// ```
519    Block,
520    /// Any module with a name.
521    ///
522    /// This could be:
523    ///
524    /// * A normal module – either `mod from_file;` or `mod from_block { }` –
525    ///   or the crate root (which is conceptually a top-level module).
526    ///   The crate root will have `None` for the symbol.
527    /// * A trait or an enum (it implicitly contains associated types, methods and variant
528    ///   constructors).
529    Def(DefKind, DefId, Option<Symbol>),
530}
531
532impl ModuleKind {
533    /// Get name of the module.
534    fn name(&self) -> Option<Symbol> {
535        match *self {
536            ModuleKind::Block => None,
537            ModuleKind::Def(.., name) => name,
538        }
539    }
540}
541
542/// A key that identifies a binding in a given `Module`.
543///
544/// Multiple bindings in the same module can have the same key (in a valid
545/// program) if all but one of them come from glob imports.
546#[derive(#[automatically_derived]
impl ::core::marker::Copy for BindingKey { }Copy, #[automatically_derived]
impl ::core::clone::Clone for BindingKey {
    #[inline]
    fn clone(&self) -> BindingKey {
        let _: ::core::clone::AssertParamIsClone<Macros20NormalizedIdent>;
        let _: ::core::clone::AssertParamIsClone<Namespace>;
        let _: ::core::clone::AssertParamIsClone<u32>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for BindingKey {
    #[inline]
    fn eq(&self, other: &BindingKey) -> bool {
        self.disambiguator == other.disambiguator && self.ident == other.ident
            && self.ns == other.ns
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for BindingKey {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<Macros20NormalizedIdent>;
        let _: ::core::cmp::AssertParamIsEq<Namespace>;
        let _: ::core::cmp::AssertParamIsEq<u32>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for BindingKey {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
        ::core::hash::Hash::hash(&self.ident, state);
        ::core::hash::Hash::hash(&self.ns, state);
        ::core::hash::Hash::hash(&self.disambiguator, state)
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for BindingKey {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "BindingKey",
            "ident", &self.ident, "ns", &self.ns, "disambiguator",
            &&self.disambiguator)
    }
}Debug)]
547struct BindingKey {
548    /// The identifier for the binding, always the `normalize_to_macros_2_0` version of the
549    /// identifier.
550    ident: Macros20NormalizedIdent,
551    ns: Namespace,
552    /// When we add an underscore binding (with ident `_`) to some module, this field has
553    /// a non-zero value that uniquely identifies this binding in that module.
554    /// For non-underscore bindings this field is zero.
555    /// When a key is constructed for name lookup (as opposed to name definition), this field is
556    /// also zero, even for underscore names, so for underscores the lookup will never succeed.
557    disambiguator: u32,
558}
559
560impl BindingKey {
561    fn new(ident: Ident, ns: Namespace) -> Self {
562        BindingKey { ident: Macros20NormalizedIdent::new(ident), ns, disambiguator: 0 }
563    }
564
565    fn new_disambiguated(
566        ident: Ident,
567        ns: Namespace,
568        disambiguator: impl FnOnce() -> u32,
569    ) -> BindingKey {
570        let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
571        BindingKey { ident: Macros20NormalizedIdent::new(ident), ns, disambiguator }
572    }
573}
574
575type Resolutions<'ra> = CmRefCell<FxIndexMap<BindingKey, &'ra CmRefCell<NameResolution<'ra>>>>;
576
577/// One node in the tree of modules.
578///
579/// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these:
580///
581/// * `mod`
582/// * crate root (aka, top-level anonymous module)
583/// * `enum`
584/// * `trait`
585/// * curly-braced block with statements
586///
587/// You can use [`ModuleData::kind`] to determine the kind of module this is.
588struct ModuleData<'ra> {
589    /// The direct parent module (it may not be a `mod`, however).
590    parent: Option<Module<'ra>>,
591    /// What kind of module this is, because this may not be a `mod`.
592    kind: ModuleKind,
593
594    /// Mapping between names and their (possibly in-progress) resolutions in this module.
595    /// Resolutions in modules from other crates are not populated until accessed.
596    lazy_resolutions: Resolutions<'ra>,
597    /// True if this is a module from other crate that needs to be populated on access.
598    populate_on_access: CacheCell<bool>,
599    /// Used to disambiguate underscore items (`const _: T = ...`) in the module.
600    underscore_disambiguator: CmCell<u32>,
601
602    /// Macro invocations that can expand into items in this module.
603    unexpanded_invocations: CmRefCell<FxHashSet<LocalExpnId>>,
604
605    /// Whether `#[no_implicit_prelude]` is active.
606    no_implicit_prelude: bool,
607
608    glob_importers: CmRefCell<Vec<Import<'ra>>>,
609    globs: CmRefCell<Vec<Import<'ra>>>,
610
611    /// Used to memoize the traits in this module for faster searches through all traits in scope.
612    traits:
613        CmRefCell<Option<Box<[(Macros20NormalizedIdent, NameBinding<'ra>, Option<Module<'ra>>)]>>>,
614
615    /// Span of the module itself. Used for error reporting.
616    span: Span,
617
618    expansion: ExpnId,
619
620    /// Binding for implicitly declared names that come with a module,
621    /// like `self` (not yet used), or `crate`/`$crate` (for root modules).
622    self_binding: Option<NameBinding<'ra>>,
623}
624
625/// All modules are unique and allocated on a same arena,
626/// so we can use referential equality to compare them.
627#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for Module<'ra> {
    #[inline]
    fn clone(&self) -> Module<'ra> {
        let _:
                ::core::clone::AssertParamIsClone<Interned<'ra,
                ModuleData<'ra>>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for Module<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for Module<'ra> {
    #[inline]
    fn eq(&self, other: &Module<'ra>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'ra> ::core::cmp::Eq for Module<'ra> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) -> () {
        let _: ::core::cmp::AssertParamIsEq<Interned<'ra, ModuleData<'ra>>>;
    }
}Eq, #[automatically_derived]
impl<'ra> ::core::hash::Hash for Module<'ra> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash)]
628#[rustc_pass_by_value]
629struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);
630
631// Allows us to use Interned without actually enforcing (via Hash/PartialEq/...) uniqueness of the
632// contained data.
633// FIXME: We may wish to actually have at least debug-level assertions that Interned's guarantees
634// are upheld.
635impl std::hash::Hash for ModuleData<'_> {
636    fn hash<H>(&self, _: &mut H)
637    where
638        H: std::hash::Hasher,
639    {
640        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
641    }
642}
643
644impl<'ra> ModuleData<'ra> {
645    fn new(
646        parent: Option<Module<'ra>>,
647        kind: ModuleKind,
648        expansion: ExpnId,
649        span: Span,
650        no_implicit_prelude: bool,
651        self_binding: Option<NameBinding<'ra>>,
652    ) -> Self {
653        let is_foreign = match kind {
654            ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
655            ModuleKind::Block => false,
656        };
657        ModuleData {
658            parent,
659            kind,
660            lazy_resolutions: Default::default(),
661            populate_on_access: CacheCell::new(is_foreign),
662            underscore_disambiguator: CmCell::new(0),
663            unexpanded_invocations: Default::default(),
664            no_implicit_prelude,
665            glob_importers: CmRefCell::new(Vec::new()),
666            globs: CmRefCell::new(Vec::new()),
667            traits: CmRefCell::new(None),
668            span,
669            expansion,
670            self_binding,
671        }
672    }
673}
674
675impl<'ra> Module<'ra> {
676    fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(
677        self,
678        resolver: &R,
679        mut f: impl FnMut(&R, Macros20NormalizedIdent, Namespace, NameBinding<'ra>),
680    ) {
681        for (key, name_resolution) in resolver.as_ref().resolutions(self).borrow().iter() {
682            if let Some(binding) = name_resolution.borrow().best_binding() {
683                f(resolver, key.ident, key.ns, binding);
684            }
685        }
686    }
687
688    fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(
689        self,
690        resolver: &mut R,
691        mut f: impl FnMut(&mut R, Macros20NormalizedIdent, Namespace, NameBinding<'ra>),
692    ) {
693        for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
694            if let Some(binding) = name_resolution.borrow().best_binding() {
695                f(resolver, key.ident, key.ns, binding);
696            }
697        }
698    }
699
700    /// This modifies `self` in place. The traits will be stored in `self.traits`.
701    fn ensure_traits<'tcx>(self, resolver: &impl AsRef<Resolver<'ra, 'tcx>>) {
702        let mut traits = self.traits.borrow_mut(resolver.as_ref());
703        if traits.is_none() {
704            let mut collected_traits = Vec::new();
705            self.for_each_child(resolver, |r, name, ns, binding| {
706                if ns != TypeNS {
707                    return;
708                }
709                if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = binding.res() {
710                    collected_traits.push((name, binding, r.as_ref().get_module(def_id)))
711                }
712            });
713            *traits = Some(collected_traits.into_boxed_slice());
714        }
715    }
716
717    fn res(self) -> Option<Res> {
718        match self.kind {
719            ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
720            _ => None,
721        }
722    }
723
724    fn def_id(self) -> DefId {
725        self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
726    }
727
728    fn opt_def_id(self) -> Option<DefId> {
729        match self.kind {
730            ModuleKind::Def(_, def_id, _) => Some(def_id),
731            _ => None,
732        }
733    }
734
735    // `self` resolves to the first module ancestor that `is_normal`.
736    fn is_normal(self) -> bool {
737        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    ModuleKind::Def(DefKind::Mod, _, _) => true,
    _ => false,
}matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
738    }
739
740    fn is_trait(self) -> bool {
741        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    ModuleKind::Def(DefKind::Trait, _, _) => true,
    _ => false,
}matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
742    }
743
744    fn nearest_item_scope(self) -> Module<'ra> {
745        match self.kind {
746            ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
747                self.parent.expect("enum or trait module without a parent")
748            }
749            _ => self,
750        }
751    }
752
753    /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module).
754    /// This may be the crate root.
755    fn nearest_parent_mod(self) -> DefId {
756        match self.kind {
757            ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
758            _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
759        }
760    }
761
762    fn is_ancestor_of(self, mut other: Self) -> bool {
763        while self != other {
764            if let Some(parent) = other.parent {
765                other = parent;
766            } else {
767                return false;
768            }
769        }
770        true
771    }
772}
773
774impl<'ra> std::ops::Deref for Module<'ra> {
775    type Target = ModuleData<'ra>;
776
777    fn deref(&self) -> &Self::Target {
778        &self.0
779    }
780}
781
782impl<'ra> fmt::Debug for Module<'ra> {
783    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
784        match self.kind {
785            ModuleKind::Block => f.write_fmt(format_args!("block"))write!(f, "block"),
786            ModuleKind::Def(..) => f.write_fmt(format_args!("{0:?}", self.res()))write!(f, "{:?}", self.res()),
787        }
788    }
789}
790
791/// Records a possibly-private value, type, or module definition.
792#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for NameBindingData<'ra> {
    #[inline]
    fn clone(&self) -> NameBindingData<'ra> {
        let _: ::core::clone::AssertParamIsClone<NameBindingKind<'ra>>;
        let _:
                ::core::clone::AssertParamIsClone<Option<(NameBinding<'ra>,
                AmbiguityKind)>>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<LocalExpnId>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<Visibility<DefId>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for NameBindingData<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for NameBindingData<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["kind", "ambiguity", "warn_ambiguity", "expansion", "span",
                        "vis"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.kind, &self.ambiguity, &self.warn_ambiguity,
                        &self.expansion, &self.span, &&self.vis];
        ::core::fmt::Formatter::debug_struct_fields_finish(f,
            "NameBindingData", names, values)
    }
}Debug)]
793struct NameBindingData<'ra> {
794    kind: NameBindingKind<'ra>,
795    ambiguity: Option<(NameBinding<'ra>, AmbiguityKind)>,
796    /// Produce a warning instead of an error when reporting ambiguities inside this binding.
797    /// May apply to indirect ambiguities under imports, so `ambiguity.is_some()` is not required.
798    warn_ambiguity: bool,
799    expansion: LocalExpnId,
800    span: Span,
801    vis: Visibility<DefId>,
802}
803
804/// All name bindings are unique and allocated on a same arena,
805/// so we can use referential equality to compare them.
806type NameBinding<'ra> = Interned<'ra, NameBindingData<'ra>>;
807
808// Allows us to use Interned without actually enforcing (via Hash/PartialEq/...) uniqueness of the
809// contained data.
810// FIXME: We may wish to actually have at least debug-level assertions that Interned's guarantees
811// are upheld.
812impl std::hash::Hash for NameBindingData<'_> {
813    fn hash<H>(&self, _: &mut H)
814    where
815        H: std::hash::Hasher,
816    {
817        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
818    }
819}
820
821#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for NameBindingKind<'ra> {
    #[inline]
    fn clone(&self) -> NameBindingKind<'ra> {
        let _: ::core::clone::AssertParamIsClone<Res>;
        let _: ::core::clone::AssertParamIsClone<NameBinding<'ra>>;
        let _: ::core::clone::AssertParamIsClone<Import<'ra>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for NameBindingKind<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for NameBindingKind<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            NameBindingKind::Res(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Res",
                    &__self_0),
            NameBindingKind::Import { binding: __self_0, import: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Import", "binding", __self_0, "import", &__self_1),
        }
    }
}Debug)]
822enum NameBindingKind<'ra> {
823    Res(Res),
824    Import { binding: NameBinding<'ra>, import: Import<'ra> },
825}
826
827impl<'ra> NameBindingKind<'ra> {
828    /// Is this a name binding of an import?
829    fn is_import(&self) -> bool {
830        #[allow(non_exhaustive_omitted_patterns)] match *self {
    NameBindingKind::Import { .. } => true,
    _ => false,
}matches!(*self, NameBindingKind::Import { .. })
831    }
832}
833
834#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for PrivacyError<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["ident", "binding", "dedup_span", "outermost_res",
                        "parent_scope", "single_nested", "source"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.ident, &self.binding, &self.dedup_span,
                        &self.outermost_res, &self.parent_scope,
                        &self.single_nested, &&self.source];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "PrivacyError",
            names, values)
    }
}Debug)]
835struct PrivacyError<'ra> {
836    ident: Ident,
837    binding: NameBinding<'ra>,
838    dedup_span: Span,
839    outermost_res: Option<(Res, Ident)>,
840    parent_scope: ParentScope<'ra>,
841    /// Is the format `use a::{b,c}`?
842    single_nested: bool,
843    source: Option<ast::Expr>,
844}
845
846#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for UseError<'a> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["err", "candidates", "def_id", "instead", "suggestion", "path",
                        "is_call"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.err, &self.candidates, &self.def_id, &self.instead,
                        &self.suggestion, &self.path, &&self.is_call];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "UseError",
            names, values)
    }
}Debug)]
847struct UseError<'a> {
848    err: Diag<'a>,
849    /// Candidates which user could `use` to access the missing type.
850    candidates: Vec<ImportSuggestion>,
851    /// The `DefId` of the module to place the use-statements in.
852    def_id: DefId,
853    /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`).
854    instead: bool,
855    /// Extra free-form suggestion.
856    suggestion: Option<(Span, &'static str, String, Applicability)>,
857    /// Path `Segment`s at the place of use that failed. Used for accurate suggestion after telling
858    /// the user to import the item directly.
859    path: Vec<Segment>,
860    /// Whether the expected source is a call
861    is_call: bool,
862}
863
864#[derive(#[automatically_derived]
impl ::core::clone::Clone for AmbiguityKind {
    #[inline]
    fn clone(&self) -> AmbiguityKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AmbiguityKind { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for AmbiguityKind {
    #[inline]
    fn eq(&self, other: &AmbiguityKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for AmbiguityKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AmbiguityKind::BuiltinAttr => "BuiltinAttr",
                AmbiguityKind::DeriveHelper => "DeriveHelper",
                AmbiguityKind::MacroRulesVsModularized =>
                    "MacroRulesVsModularized",
                AmbiguityKind::GlobVsOuter => "GlobVsOuter",
                AmbiguityKind::GlobVsGlob => "GlobVsGlob",
                AmbiguityKind::GlobVsExpanded => "GlobVsExpanded",
                AmbiguityKind::MoreExpandedVsOuter => "MoreExpandedVsOuter",
            })
    }
}Debug)]
865enum AmbiguityKind {
866    BuiltinAttr,
867    DeriveHelper,
868    MacroRulesVsModularized,
869    GlobVsOuter,
870    GlobVsGlob,
871    GlobVsExpanded,
872    MoreExpandedVsOuter,
873}
874
875impl AmbiguityKind {
876    fn descr(self) -> &'static str {
877        match self {
878            AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
879            AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
880            AmbiguityKind::MacroRulesVsModularized => {
881                "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
882            }
883            AmbiguityKind::GlobVsOuter => {
884                "a conflict between a name from a glob import and an outer scope during import or macro resolution"
885            }
886            AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
887            AmbiguityKind::GlobVsExpanded => {
888                "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
889            }
890            AmbiguityKind::MoreExpandedVsOuter => {
891                "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
892            }
893        }
894    }
895}
896
897/// Miscellaneous bits of metadata for better ambiguity error reporting.
898#[derive(#[automatically_derived]
impl ::core::clone::Clone for AmbiguityErrorMisc {
    #[inline]
    fn clone(&self) -> AmbiguityErrorMisc { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AmbiguityErrorMisc { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for AmbiguityErrorMisc {
    #[inline]
    fn eq(&self, other: &AmbiguityErrorMisc) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
899enum AmbiguityErrorMisc {
900    SuggestCrate,
901    SuggestSelf,
902    FromPrelude,
903    None,
904}
905
906struct AmbiguityError<'ra> {
907    kind: AmbiguityKind,
908    ident: Ident,
909    b1: NameBinding<'ra>,
910    b2: NameBinding<'ra>,
911    misc1: AmbiguityErrorMisc,
912    misc2: AmbiguityErrorMisc,
913    warning: bool,
914}
915
916impl<'ra> NameBindingData<'ra> {
917    fn res(&self) -> Res {
918        match self.kind {
919            NameBindingKind::Res(res) => res,
920            NameBindingKind::Import { binding, .. } => binding.res(),
921        }
922    }
923
924    fn import_source(&self) -> NameBinding<'ra> {
925        match self.kind {
926            NameBindingKind::Import { binding, .. } => binding,
927            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
928        }
929    }
930
931    fn descent_to_ambiguity(
932        self: NameBinding<'ra>,
933    ) -> Option<(NameBinding<'ra>, NameBinding<'ra>, AmbiguityKind)> {
934        match self.ambiguity {
935            Some((ambig_binding, ambig_kind)) => Some((self, ambig_binding, ambig_kind)),
936            None => match self.kind {
937                NameBindingKind::Import { binding, .. } => binding.descent_to_ambiguity(),
938                _ => None,
939            },
940        }
941    }
942
943    fn is_ambiguity_recursive(&self) -> bool {
944        self.ambiguity.is_some()
945            || match self.kind {
946                NameBindingKind::Import { binding, .. } => binding.is_ambiguity_recursive(),
947                _ => false,
948            }
949    }
950
951    fn warn_ambiguity_recursive(&self) -> bool {
952        self.warn_ambiguity
953            || match self.kind {
954                NameBindingKind::Import { binding, .. } => binding.warn_ambiguity_recursive(),
955                _ => false,
956            }
957    }
958
959    fn is_possibly_imported_variant(&self) -> bool {
960        match self.kind {
961            NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(),
962            NameBindingKind::Res(Res::Def(
963                DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..),
964                _,
965            )) => true,
966            NameBindingKind::Res(..) => false,
967        }
968    }
969
970    fn is_extern_crate(&self) -> bool {
971        match self.kind {
972            NameBindingKind::Import { import, .. } => {
973                #[allow(non_exhaustive_omitted_patterns)] match import.kind {
    ImportKind::ExternCrate { .. } => true,
    _ => false,
}matches!(import.kind, ImportKind::ExternCrate { .. })
974            }
975            NameBindingKind::Res(Res::Def(_, def_id)) => def_id.is_crate_root(),
976            _ => false,
977        }
978    }
979
980    fn is_import(&self) -> bool {
981        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    NameBindingKind::Import { .. } => true,
    _ => false,
}matches!(self.kind, NameBindingKind::Import { .. })
982    }
983
984    /// The binding introduced by `#[macro_export] macro_rules` is a public import, but it might
985    /// not be perceived as such by users, so treat it as a non-import in some diagnostics.
986    fn is_import_user_facing(&self) -> bool {
987        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    NameBindingKind::Import { import, .. } if
        !#[allow(non_exhaustive_omitted_patterns)] match import.kind {
                ImportKind::MacroExport => true,
                _ => false,
            } => true,
    _ => false,
}matches!(self.kind, NameBindingKind::Import { import, .. }
988            if !matches!(import.kind, ImportKind::MacroExport))
989    }
990
991    fn is_glob_import(&self) -> bool {
992        match self.kind {
993            NameBindingKind::Import { import, .. } => import.is_glob(),
994            _ => false,
995        }
996    }
997
998    fn is_assoc_item(&self) -> bool {
999        #[allow(non_exhaustive_omitted_patterns)] match self.res() {
    Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) =>
        true,
    _ => false,
}matches!(self.res(), Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _))
1000    }
1001
1002    fn macro_kinds(&self) -> Option<MacroKinds> {
1003        self.res().macro_kinds()
1004    }
1005
1006    fn reexport_chain(self: NameBinding<'ra>, r: &Resolver<'_, '_>) -> SmallVec<[Reexport; 2]> {
1007        let mut reexport_chain = SmallVec::new();
1008        let mut next_binding = self;
1009        while let NameBindingKind::Import { binding, import, .. } = next_binding.kind {
1010            reexport_chain.push(import.simplify(r));
1011            next_binding = binding;
1012        }
1013        reexport_chain
1014    }
1015
1016    // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
1017    // at some expansion round `max(invoc, binding)` when they both emerged from macros.
1018    // Then this function returns `true` if `self` may emerge from a macro *after* that
1019    // in some later round and screw up our previously found resolution.
1020    // See more detailed explanation in
1021    // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
1022    fn may_appear_after(
1023        &self,
1024        invoc_parent_expansion: LocalExpnId,
1025        binding: NameBinding<'_>,
1026    ) -> bool {
1027        // self > max(invoc, binding) => !(self <= invoc || self <= binding)
1028        // Expansions are partially ordered, so "may appear after" is an inversion of
1029        // "certainly appears before or simultaneously" and includes unordered cases.
1030        let self_parent_expansion = self.expansion;
1031        let other_parent_expansion = binding.expansion;
1032        let certainly_before_other_or_simultaneously =
1033            other_parent_expansion.is_descendant_of(self_parent_expansion);
1034        let certainly_before_invoc_or_simultaneously =
1035            invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1036        !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1037    }
1038
1039    // Its purpose is to postpone the determination of a single binding because
1040    // we can't predict whether it will be overwritten by recently expanded macros.
1041    // FIXME: How can we integrate it with the `update_resolution`?
1042    fn determined(&self) -> bool {
1043        match &self.kind {
1044            NameBindingKind::Import { binding, import, .. } if import.is_glob() => {
1045                import.parent_scope.module.unexpanded_invocations.borrow().is_empty()
1046                    && binding.determined()
1047            }
1048            _ => true,
1049        }
1050    }
1051}
1052
1053struct ExternPreludeEntry<'ra> {
1054    /// Binding from an `extern crate` item.
1055    /// The boolean flag is true is `item_binding` is non-redundant, happens either when
1056    /// `flag_binding` is `None`, or when `extern crate` introducing `item_binding` used renaming.
1057    item_binding: Option<(NameBinding<'ra>, /* introduced by item */ bool)>,
1058    /// Binding from an `--extern` flag, lazily populated on first use.
1059    flag_binding: Option<CacheCell<(PendingBinding<'ra>, /* finalized */ bool)>>,
1060}
1061
1062impl ExternPreludeEntry<'_> {
1063    fn introduced_by_item(&self) -> bool {
1064        #[allow(non_exhaustive_omitted_patterns)] match self.item_binding {
    Some((_, true)) => true,
    _ => false,
}matches!(self.item_binding, Some((_, true)))
1065    }
1066
1067    fn flag() -> Self {
1068        ExternPreludeEntry {
1069            item_binding: None,
1070            flag_binding: Some(CacheCell::new((PendingBinding::Pending, false))),
1071        }
1072    }
1073}
1074
1075struct DeriveData {
1076    resolutions: Vec<DeriveResolution>,
1077    helper_attrs: Vec<(usize, Ident)>,
1078    has_derive_copy: bool,
1079}
1080
1081struct MacroData {
1082    ext: Arc<SyntaxExtension>,
1083    nrules: usize,
1084    macro_rules: bool,
1085}
1086
1087impl MacroData {
1088    fn new(ext: Arc<SyntaxExtension>) -> MacroData {
1089        MacroData { ext, nrules: 0, macro_rules: false }
1090    }
1091}
1092
1093pub struct ResolverOutputs {
1094    pub global_ctxt: ResolverGlobalCtxt,
1095    pub ast_lowering: ResolverAstLowering,
1096}
1097
1098/// The main resolver class.
1099///
1100/// This is the visitor that walks the whole crate.
1101pub struct Resolver<'ra, 'tcx> {
1102    tcx: TyCtxt<'tcx>,
1103
1104    /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
1105    expn_that_defined: UnordMap<LocalDefId, ExpnId>,
1106
1107    graph_root: Module<'ra>,
1108
1109    /// Assert that we are in speculative resolution mode.
1110    assert_speculative: bool,
1111
1112    prelude: Option<Module<'ra>> = None,
1113    extern_prelude: FxIndexMap<Macros20NormalizedIdent, ExternPreludeEntry<'ra>>,
1114
1115    /// N.B., this is used only for better diagnostics, not name resolution itself.
1116    field_names: LocalDefIdMap<Vec<Ident>>,
1117    field_defaults: LocalDefIdMap<Vec<Symbol>>,
1118
1119    /// Span of the privacy modifier in fields of an item `DefId` accessible with dot syntax.
1120    /// Used for hints during error reporting.
1121    field_visibility_spans: FxHashMap<DefId, Vec<Span>>,
1122
1123    /// All imports known to succeed or fail.
1124    determined_imports: Vec<Import<'ra>> = Vec::new(),
1125
1126    /// All non-determined imports.
1127    indeterminate_imports: Vec<Import<'ra>> = Vec::new(),
1128
1129    // Spans for local variables found during pattern resolution.
1130    // Used for suggestions during error reporting.
1131    pat_span_map: NodeMap<Span>,
1132
1133    /// Resolutions for nodes that have a single resolution.
1134    partial_res_map: NodeMap<PartialRes>,
1135    /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
1136    import_res_map: NodeMap<PerNS<Option<Res>>>,
1137    /// An import will be inserted into this map if it has been used.
1138    import_use_map: FxHashMap<Import<'ra>, Used>,
1139    /// Resolutions for labels (node IDs of their corresponding blocks or loops).
1140    label_res_map: NodeMap<NodeId>,
1141    /// Resolutions for lifetimes.
1142    lifetimes_res_map: NodeMap<LifetimeRes>,
1143    /// Lifetime parameters that lowering will have to introduce.
1144    extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
1145
1146    /// `CrateNum` resolutions of `extern crate` items.
1147    extern_crate_map: UnordMap<LocalDefId, CrateNum>,
1148    module_children: LocalDefIdMap<Vec<ModChild>>,
1149    ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>>,
1150    trait_map: NodeMap<Vec<TraitCandidate>>,
1151
1152    /// A map from nodes to anonymous modules.
1153    /// Anonymous modules are pseudo-modules that are implicitly created around items
1154    /// contained within blocks.
1155    ///
1156    /// For example, if we have this:
1157    ///
1158    ///  fn f() {
1159    ///      fn g() {
1160    ///          ...
1161    ///      }
1162    ///  }
1163    ///
1164    /// There will be an anonymous module created around `g` with the ID of the
1165    /// entry block for `f`.
1166    block_map: NodeMap<Module<'ra>>,
1167    /// A fake module that contains no definition and no prelude. Used so that
1168    /// some AST passes can generate identifiers that only resolve to local or
1169    /// lang items.
1170    empty_module: Module<'ra>,
1171    /// All local modules, including blocks.
1172    local_modules: Vec<Module<'ra>>,
1173    /// Eagerly populated map of all local non-block modules.
1174    local_module_map: FxIndexMap<LocalDefId, Module<'ra>>,
1175    /// Lazily populated cache of modules loaded from external crates.
1176    extern_module_map: CacheRefCell<FxIndexMap<DefId, Module<'ra>>>,
1177    binding_parent_modules: FxHashMap<NameBinding<'ra>, Module<'ra>>,
1178
1179    /// Maps glob imports to the names of items actually imported.
1180    glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1181    glob_error: Option<ErrorGuaranteed> = None,
1182    visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1183    used_imports: FxHashSet<NodeId>,
1184    maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1185
1186    /// Privacy errors are delayed until the end in order to deduplicate them.
1187    privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1188    /// Ambiguity errors are delayed for deduplication.
1189    ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1190    issue_145575_hack_applied: bool = false,
1191    /// `use` injections are delayed for better placement and deduplication.
1192    use_injections: Vec<UseError<'tcx>> = Vec::new(),
1193    /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
1194    macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1195
1196    /// When a type is re-exported that has an inaccessible constructor because it has fields that
1197    /// are inaccessible from the import's scope, we mark that as the type won't be able to be built
1198    /// through the re-export. We use this information to extend the existing diagnostic.
1199    inaccessible_ctor_reexport: FxHashMap<Span, Span>,
1200
1201    arenas: &'ra ResolverArenas<'ra>,
1202    dummy_binding: NameBinding<'ra>,
1203    builtin_types_bindings: FxHashMap<Symbol, NameBinding<'ra>>,
1204    builtin_attrs_bindings: FxHashMap<Symbol, NameBinding<'ra>>,
1205    registered_tool_bindings: FxHashMap<Ident, NameBinding<'ra>>,
1206    macro_names: FxHashSet<Ident>,
1207    builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind>,
1208    registered_tools: &'tcx RegisteredTools,
1209    macro_use_prelude: FxIndexMap<Symbol, NameBinding<'ra>>,
1210    /// Eagerly populated map of all local macro definitions.
1211    local_macro_map: FxHashMap<LocalDefId, &'ra MacroData>,
1212    /// Lazily populated cache of macro definitions loaded from external crates.
1213    extern_macro_map: CacheRefCell<FxHashMap<DefId, &'ra MacroData>>,
1214    dummy_ext_bang: Arc<SyntaxExtension>,
1215    dummy_ext_derive: Arc<SyntaxExtension>,
1216    non_macro_attr: &'ra MacroData,
1217    local_macro_def_scopes: FxHashMap<LocalDefId, Module<'ra>>,
1218    ast_transform_scopes: FxHashMap<LocalExpnId, Module<'ra>>,
1219    unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1220    /// A map from the macro to all its potentially unused arms.
1221    unused_macro_rules: FxIndexMap<NodeId, DenseBitSet<usize>>,
1222    proc_macro_stubs: FxHashSet<LocalDefId>,
1223    /// Traces collected during macro resolution and validated when it's complete.
1224    single_segment_macro_resolutions:
1225        CmRefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<NameBinding<'ra>>, Option<Span>)>>,
1226    multi_segment_macro_resolutions:
1227        CmRefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1228    builtin_attrs: Vec<(Ident, ParentScope<'ra>)>,
1229    /// `derive(Copy)` marks items they are applied to so they are treated specially later.
1230    /// Derive macros cannot modify the item themselves and have to store the markers in the global
1231    /// context, so they attach the markers to derive container IDs using this resolver table.
1232    containers_deriving_copy: FxHashSet<LocalExpnId>,
1233    /// Parent scopes in which the macros were invoked.
1234    /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
1235    invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>>,
1236    /// `macro_rules` scopes *produced* by expanding the macro invocations,
1237    /// include all the `macro_rules` items and other invocations generated by them.
1238    output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>>,
1239    /// `macro_rules` scopes produced by `macro_rules` item definitions.
1240    macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>>,
1241    /// Helper attributes that are in scope for the given expansion.
1242    helper_attrs: FxHashMap<LocalExpnId, Vec<(Ident, NameBinding<'ra>)>>,
1243    /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute
1244    /// with the given `ExpnId`.
1245    derive_data: FxHashMap<LocalExpnId, DeriveData>,
1246
1247    /// Avoid duplicated errors for "name already defined".
1248    name_already_seen: FxHashMap<Symbol, Span>,
1249
1250    potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1251
1252    potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1253
1254    /// Table for mapping struct IDs into struct constructor IDs,
1255    /// it's not used during normal resolution, only for better error reporting.
1256    /// Also includes of list of each fields visibility
1257    struct_constructors: LocalDefIdMap<(Res, Visibility<DefId>, Vec<Visibility<DefId>>)>,
1258
1259    lint_buffer: LintBuffer,
1260
1261    next_node_id: NodeId = CRATE_NODE_ID,
1262
1263    node_id_to_def_id: NodeMap<Feed<'tcx, LocalDefId>>,
1264
1265    disambiguator: DisambiguatorState,
1266
1267    /// Indices of unnamed struct or variant fields with unresolved attributes.
1268    placeholder_field_indices: FxHashMap<NodeId, usize>,
1269    /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
1270    /// we know what parent node that fragment should be attached to thanks to this table,
1271    /// and how the `impl Trait` fragments were introduced.
1272    invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1273
1274    legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1275    /// Amount of lifetime parameters for each item in the crate.
1276    item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1277    delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
1278    delegation_sig_resolution_nodes: LocalDefIdMap<NodeId>,
1279
1280    main_def: Option<MainDefinition> = None,
1281    trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1282    /// A list of proc macro LocalDefIds, written out in the order in which
1283    /// they are declared in the static array generated by proc_macro_harness.
1284    proc_macros: Vec<LocalDefId> = Vec::new(),
1285    confused_type_with_std_module: FxIndexMap<Span, Span>,
1286    /// Whether lifetime elision was successful.
1287    lifetime_elision_allowed: FxHashSet<NodeId>,
1288
1289    /// Names of items that were stripped out via cfg with their corresponding cfg meta item.
1290    stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1291
1292    effective_visibilities: EffectiveVisibilities,
1293    doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
1294    doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
1295    all_macro_rules: UnordSet<Symbol>,
1296
1297    /// Invocation ids of all glob delegations.
1298    glob_delegation_invoc_ids: FxHashSet<LocalExpnId>,
1299    /// Analogue of module `unexpanded_invocations` but in trait impls, excluding glob delegations.
1300    /// Needed because glob delegations wait for all other neighboring macros to expand.
1301    impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>>,
1302    /// Simplified analogue of module `resolutions` but in trait impls, excluding glob delegations.
1303    /// Needed because glob delegations exclude explicitly defined names.
1304    impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>>,
1305
1306    /// This is the `Span` where an `extern crate foo;` suggestion would be inserted, if `foo`
1307    /// could be a crate that wasn't imported. For diagnostics use only.
1308    current_crate_outer_attr_insert_span: Span,
1309
1310    mods_with_parse_errors: FxHashSet<DefId>,
1311
1312    /// Whether `Resolver::register_macros_for_all_crates` has been called once already, as we
1313    /// don't need to run it more than once.
1314    all_crate_macros_already_registered: bool = false,
1315
1316    // Stores pre-expansion and pre-placeholder-fragment-insertion names for `impl Trait` types
1317    // that were encountered during resolution. These names are used to generate item names
1318    // for APITs, so we don't want to leak details of resolution into these names.
1319    impl_trait_names: FxHashMap<NodeId, Symbol>,
1320}
1321
1322/// This provides memory for the rest of the crate. The `'ra` lifetime that is
1323/// used by many types in this crate is an abbreviation of `ResolverArenas`.
1324#[derive(#[automatically_derived]
impl<'ra> ::core::default::Default for ResolverArenas<'ra> {
    #[inline]
    fn default() -> ResolverArenas<'ra> {
        ResolverArenas {
            modules: ::core::default::Default::default(),
            imports: ::core::default::Default::default(),
            name_resolutions: ::core::default::Default::default(),
            ast_paths: ::core::default::Default::default(),
            macros: ::core::default::Default::default(),
            dropless: ::core::default::Default::default(),
        }
    }
}Default)]
1325pub struct ResolverArenas<'ra> {
1326    modules: TypedArena<ModuleData<'ra>>,
1327    imports: TypedArena<ImportData<'ra>>,
1328    name_resolutions: TypedArena<CmRefCell<NameResolution<'ra>>>,
1329    ast_paths: TypedArena<ast::Path>,
1330    macros: TypedArena<MacroData>,
1331    dropless: DroplessArena,
1332}
1333
1334impl<'ra> ResolverArenas<'ra> {
1335    fn new_res_binding(
1336        &'ra self,
1337        res: Res,
1338        vis: Visibility<DefId>,
1339        span: Span,
1340        expansion: LocalExpnId,
1341    ) -> NameBinding<'ra> {
1342        self.alloc_name_binding(NameBindingData {
1343            kind: NameBindingKind::Res(res),
1344            ambiguity: None,
1345            warn_ambiguity: false,
1346            vis,
1347            span,
1348            expansion,
1349        })
1350    }
1351
1352    fn new_pub_res_binding(
1353        &'ra self,
1354        res: Res,
1355        span: Span,
1356        expn_id: LocalExpnId,
1357    ) -> NameBinding<'ra> {
1358        self.new_res_binding(res, Visibility::Public, span, expn_id)
1359    }
1360
1361    fn new_module(
1362        &'ra self,
1363        parent: Option<Module<'ra>>,
1364        kind: ModuleKind,
1365        expn_id: ExpnId,
1366        span: Span,
1367        no_implicit_prelude: bool,
1368    ) -> Module<'ra> {
1369        let self_binding = match kind {
1370            ModuleKind::Def(def_kind, def_id, _) => {
1371                Some(self.new_pub_res_binding(Res::Def(def_kind, def_id), span, LocalExpnId::ROOT))
1372            }
1373            ModuleKind::Block => None,
1374        };
1375        Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1376            parent,
1377            kind,
1378            expn_id,
1379            span,
1380            no_implicit_prelude,
1381            self_binding,
1382        ))))
1383    }
1384    fn alloc_name_binding(&'ra self, name_binding: NameBindingData<'ra>) -> NameBinding<'ra> {
1385        Interned::new_unchecked(self.dropless.alloc(name_binding))
1386    }
1387    fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1388        Interned::new_unchecked(self.imports.alloc(import))
1389    }
1390    fn alloc_name_resolution(&'ra self) -> &'ra CmRefCell<NameResolution<'ra>> {
1391        self.name_resolutions.alloc(Default::default())
1392    }
1393    fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1394        self.dropless.alloc(CacheCell::new(scope))
1395    }
1396    fn alloc_macro_rules_binding(
1397        &'ra self,
1398        binding: MacroRulesBinding<'ra>,
1399    ) -> &'ra MacroRulesBinding<'ra> {
1400        self.dropless.alloc(binding)
1401    }
1402    fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1403        self.ast_paths.alloc_from_iter(paths.iter().cloned())
1404    }
1405    fn alloc_macro(&'ra self, macro_data: MacroData) -> &'ra MacroData {
1406        self.macros.alloc(macro_data)
1407    }
1408    fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1409        self.dropless.alloc_from_iter(spans)
1410    }
1411}
1412
1413impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1414    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1415        self
1416    }
1417}
1418
1419impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1420    fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1421        self
1422    }
1423}
1424
1425impl<'tcx> Resolver<'_, 'tcx> {
1426    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1427        self.opt_feed(node).map(|f| f.key())
1428    }
1429
1430    fn local_def_id(&self, node: NodeId) -> LocalDefId {
1431        self.feed(node).key()
1432    }
1433
1434    fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1435        self.node_id_to_def_id.get(&node).copied()
1436    }
1437
1438    fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1439        self.opt_feed(node).unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("no entry for node id: `{0:?}`",
            node));
}panic!("no entry for node id: `{node:?}`"))
1440    }
1441
1442    fn local_def_kind(&self, node: NodeId) -> DefKind {
1443        self.tcx.def_kind(self.local_def_id(node))
1444    }
1445
1446    /// Adds a definition with a parent definition.
1447    fn create_def(
1448        &mut self,
1449        parent: LocalDefId,
1450        node_id: ast::NodeId,
1451        name: Option<Symbol>,
1452        def_kind: DefKind,
1453        expn_id: ExpnId,
1454        span: Span,
1455    ) -> TyCtxtFeed<'tcx, LocalDefId> {
1456        if !!self.node_id_to_def_id.contains_key(&node_id) {
    {
        ::core::panicking::panic_fmt(format_args!("adding a def for node-id {0:?}, name {1:?}, data {2:?} but a previous def exists: {3:?}",
                node_id, name, def_kind,
                self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key())));
    }
};assert!(
1457            !self.node_id_to_def_id.contains_key(&node_id),
1458            "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1459            node_id,
1460            name,
1461            def_kind,
1462            self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1463        );
1464
1465        // FIXME: remove `def_span` body, pass in the right spans here and call `tcx.at().create_def()`
1466        let feed = self.tcx.create_def(parent, name, def_kind, None, &mut self.disambiguator);
1467        let def_id = feed.def_id();
1468
1469        // Create the definition.
1470        if expn_id != ExpnId::root() {
1471            self.expn_that_defined.insert(def_id, expn_id);
1472        }
1473
1474        // A relative span's parent must be an absolute span.
1475        if true {
    match (&span.data_untracked().parent, &None) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(span.data_untracked().parent, None);
1476        let _id = self.tcx.untracked().source_span.push(span);
1477        if true {
    match (&_id, &def_id) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(_id, def_id);
1478
1479        // Some things for which we allocate `LocalDefId`s don't correspond to
1480        // anything in the AST, so they don't have a `NodeId`. For these cases
1481        // we don't need a mapping from `NodeId` to `LocalDefId`.
1482        if node_id != ast::DUMMY_NODE_ID {
1483            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:1483",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1483u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("create_def: def_id_to_node_id[{0:?}] <-> {1:?}",
                                                    def_id, node_id) as &dyn Value))])
            });
    } else { ; }
};debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1484            self.node_id_to_def_id.insert(node_id, feed.downgrade());
1485        }
1486
1487        feed
1488    }
1489
1490    fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1491        if let Some(def_id) = def_id.as_local() {
1492            self.item_generics_num_lifetimes[&def_id]
1493        } else {
1494            self.tcx.generics_of(def_id).own_counts().lifetimes
1495        }
1496    }
1497
1498    pub fn tcx(&self) -> TyCtxt<'tcx> {
1499        self.tcx
1500    }
1501
1502    /// This function is very slow, as it iterates over the entire
1503    /// [Resolver::node_id_to_def_id] map just to find the [NodeId]
1504    /// that corresponds to the given [LocalDefId]. Only use this in
1505    /// diagnostics code paths.
1506    fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1507        self.node_id_to_def_id
1508            .items()
1509            .filter(|(_, v)| v.key() == def_id)
1510            .map(|(k, _)| *k)
1511            .get_only()
1512            .unwrap()
1513    }
1514}
1515
1516impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1517    pub fn new(
1518        tcx: TyCtxt<'tcx>,
1519        attrs: &[ast::Attribute],
1520        crate_span: Span,
1521        current_crate_outer_attr_insert_span: Span,
1522        arenas: &'ra ResolverArenas<'ra>,
1523    ) -> Resolver<'ra, 'tcx> {
1524        let root_def_id = CRATE_DEF_ID.to_def_id();
1525        let graph_root = arenas.new_module(
1526            None,
1527            ModuleKind::Def(DefKind::Mod, root_def_id, None),
1528            ExpnId::root(),
1529            crate_span,
1530            attr::contains_name(attrs, sym::no_implicit_prelude),
1531        );
1532        let local_modules = <[_]>::into_vec(::alloc::boxed::box_new([graph_root]))vec![graph_root];
1533        let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);
1534        let empty_module = arenas.new_module(
1535            None,
1536            ModuleKind::Def(DefKind::Mod, root_def_id, None),
1537            ExpnId::root(),
1538            DUMMY_SP,
1539            true,
1540        );
1541
1542        let mut node_id_to_def_id = NodeMap::default();
1543        let crate_feed = tcx.create_local_crate_def_id(crate_span);
1544
1545        crate_feed.def_kind(DefKind::Mod);
1546        let crate_feed = crate_feed.downgrade();
1547        node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1548
1549        let mut invocation_parents = FxHashMap::default();
1550        invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1551
1552        let mut extern_prelude: FxIndexMap<_, _> = tcx
1553            .sess
1554            .opts
1555            .externs
1556            .iter()
1557            .filter_map(|(name, entry)| {
1558                // Make sure `self`, `super`, `_` etc do not get into extern prelude.
1559                // FIXME: reject `--extern self` and similar in option parsing instead.
1560                if entry.add_prelude
1561                    && let name = Symbol::intern(name)
1562                    && name.can_be_raw()
1563                {
1564                    let ident = Macros20NormalizedIdent::with_dummy_span(name);
1565                    Some((ident, ExternPreludeEntry::flag()))
1566                } else {
1567                    None
1568                }
1569            })
1570            .collect();
1571
1572        if !attr::contains_name(attrs, sym::no_core) {
1573            let ident = Macros20NormalizedIdent::with_dummy_span(sym::core);
1574            extern_prelude.insert(ident, ExternPreludeEntry::flag());
1575            if !attr::contains_name(attrs, sym::no_std) {
1576                let ident = Macros20NormalizedIdent::with_dummy_span(sym::std);
1577                extern_prelude.insert(ident, ExternPreludeEntry::flag());
1578            }
1579        }
1580
1581        let registered_tools = tcx.registered_tools(());
1582        let edition = tcx.sess.edition();
1583
1584        let mut resolver = Resolver {
1585            tcx,
1586
1587            expn_that_defined: Default::default(),
1588
1589            // The outermost module has def ID 0; this is not reflected in the
1590            // AST.
1591            graph_root,
1592            assert_speculative: false, // Only set/cleared in Resolver::resolve_imports for now
1593            prelude: None,
1594            extern_prelude,
1595
1596            field_names: Default::default(),
1597            field_defaults: Default::default(),
1598            field_visibility_spans: FxHashMap::default(),
1599
1600            pat_span_map: Default::default(),
1601            partial_res_map: Default::default(),
1602            import_res_map: Default::default(),
1603            import_use_map: Default::default(),
1604            label_res_map: Default::default(),
1605            lifetimes_res_map: Default::default(),
1606            extra_lifetime_params_map: Default::default(),
1607            extern_crate_map: Default::default(),
1608            module_children: Default::default(),
1609            ambig_module_children: Default::default(),
1610            trait_map: NodeMap::default(),
1611            empty_module,
1612            local_modules,
1613            local_module_map,
1614            extern_module_map: Default::default(),
1615            block_map: Default::default(),
1616            binding_parent_modules: FxHashMap::default(),
1617            ast_transform_scopes: FxHashMap::default(),
1618
1619            glob_map: Default::default(),
1620            used_imports: FxHashSet::default(),
1621            maybe_unused_trait_imports: Default::default(),
1622            inaccessible_ctor_reexport: Default::default(),
1623
1624            arenas,
1625            dummy_binding: arenas.new_pub_res_binding(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1626            builtin_types_bindings: PrimTy::ALL
1627                .iter()
1628                .map(|prim_ty| {
1629                    let res = Res::PrimTy(*prim_ty);
1630                    let binding = arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
1631                    (prim_ty.name(), binding)
1632                })
1633                .collect(),
1634            builtin_attrs_bindings: BUILTIN_ATTRIBUTES
1635                .iter()
1636                .map(|builtin_attr| {
1637                    let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1638                    let binding = arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
1639                    (builtin_attr.name, binding)
1640                })
1641                .collect(),
1642            registered_tool_bindings: registered_tools
1643                .iter()
1644                .map(|ident| {
1645                    let res = Res::ToolMod;
1646                    let binding = arenas.new_pub_res_binding(res, ident.span, LocalExpnId::ROOT);
1647                    (*ident, binding)
1648                })
1649                .collect(),
1650            macro_names: FxHashSet::default(),
1651            builtin_macros: Default::default(),
1652            registered_tools,
1653            macro_use_prelude: Default::default(),
1654            local_macro_map: Default::default(),
1655            extern_macro_map: Default::default(),
1656            dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1657            dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1658            non_macro_attr: arenas
1659                .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))),
1660            invocation_parent_scopes: Default::default(),
1661            output_macro_rules_scopes: Default::default(),
1662            macro_rules_scopes: Default::default(),
1663            helper_attrs: Default::default(),
1664            derive_data: Default::default(),
1665            local_macro_def_scopes: FxHashMap::default(),
1666            name_already_seen: FxHashMap::default(),
1667            struct_constructors: Default::default(),
1668            unused_macros: Default::default(),
1669            unused_macro_rules: Default::default(),
1670            proc_macro_stubs: Default::default(),
1671            single_segment_macro_resolutions: Default::default(),
1672            multi_segment_macro_resolutions: Default::default(),
1673            builtin_attrs: Default::default(),
1674            containers_deriving_copy: Default::default(),
1675            lint_buffer: LintBuffer::default(),
1676            node_id_to_def_id,
1677            disambiguator: DisambiguatorState::new(),
1678            placeholder_field_indices: Default::default(),
1679            legacy_const_generic_args: Default::default(),
1680            invocation_parents,
1681            item_generics_num_lifetimes: Default::default(),
1682            trait_impls: Default::default(),
1683            confused_type_with_std_module: Default::default(),
1684            lifetime_elision_allowed: Default::default(),
1685            stripped_cfg_items: Default::default(),
1686            effective_visibilities: Default::default(),
1687            doc_link_resolutions: Default::default(),
1688            doc_link_traits_in_scope: Default::default(),
1689            all_macro_rules: Default::default(),
1690            delegation_fn_sigs: Default::default(),
1691            glob_delegation_invoc_ids: Default::default(),
1692            impl_unexpanded_invocations: Default::default(),
1693            impl_binding_keys: Default::default(),
1694            current_crate_outer_attr_insert_span,
1695            mods_with_parse_errors: Default::default(),
1696            impl_trait_names: Default::default(),
1697            delegation_sig_resolution_nodes: Default::default(),
1698            ..
1699        };
1700
1701        let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1702        resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1703        resolver.feed_visibility(crate_feed, Visibility::Public);
1704
1705        resolver
1706    }
1707
1708    fn new_local_module(
1709        &mut self,
1710        parent: Option<Module<'ra>>,
1711        kind: ModuleKind,
1712        expn_id: ExpnId,
1713        span: Span,
1714        no_implicit_prelude: bool,
1715    ) -> Module<'ra> {
1716        let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1717        self.local_modules.push(module);
1718        if let Some(def_id) = module.opt_def_id() {
1719            self.local_module_map.insert(def_id.expect_local(), module);
1720        }
1721        module
1722    }
1723
1724    fn new_extern_module(
1725        &self,
1726        parent: Option<Module<'ra>>,
1727        kind: ModuleKind,
1728        expn_id: ExpnId,
1729        span: Span,
1730        no_implicit_prelude: bool,
1731    ) -> Module<'ra> {
1732        let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1733        self.extern_module_map.borrow_mut().insert(module.def_id(), module);
1734        module
1735    }
1736
1737    fn new_local_macro(&mut self, def_id: LocalDefId, macro_data: MacroData) -> &'ra MacroData {
1738        let mac = self.arenas.alloc_macro(macro_data);
1739        self.local_macro_map.insert(def_id, mac);
1740        mac
1741    }
1742
1743    fn next_node_id(&mut self) -> NodeId {
1744        let start = self.next_node_id;
1745        let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1746        self.next_node_id = ast::NodeId::from_u32(next);
1747        start
1748    }
1749
1750    fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1751        let start = self.next_node_id;
1752        let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1753        self.next_node_id = ast::NodeId::from_usize(end);
1754        start..self.next_node_id
1755    }
1756
1757    pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1758        &mut self.lint_buffer
1759    }
1760
1761    pub fn arenas() -> ResolverArenas<'ra> {
1762        Default::default()
1763    }
1764
1765    fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: Visibility) {
1766        let feed = feed.upgrade(self.tcx);
1767        feed.visibility(vis.to_def_id());
1768        self.visibilities_for_hashing.push((feed.def_id(), vis));
1769    }
1770
1771    pub fn into_outputs(self) -> ResolverOutputs {
1772        let proc_macros = self.proc_macros;
1773        let expn_that_defined = self.expn_that_defined;
1774        let extern_crate_map = self.extern_crate_map;
1775        let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1776        let glob_map = self.glob_map;
1777        let main_def = self.main_def;
1778        let confused_type_with_std_module = self.confused_type_with_std_module;
1779        let effective_visibilities = self.effective_visibilities;
1780
1781        let stripped_cfg_items = self
1782            .stripped_cfg_items
1783            .into_iter()
1784            .filter_map(|item| {
1785                let parent_module =
1786                    self.node_id_to_def_id.get(&item.parent_module)?.key().to_def_id();
1787                Some(StrippedCfgItem { parent_module, ident: item.ident, cfg: item.cfg })
1788            })
1789            .collect();
1790
1791        let global_ctxt = ResolverGlobalCtxt {
1792            expn_that_defined,
1793            visibilities_for_hashing: self.visibilities_for_hashing,
1794            effective_visibilities,
1795            extern_crate_map,
1796            module_children: self.module_children,
1797            ambig_module_children: self.ambig_module_children,
1798            glob_map,
1799            maybe_unused_trait_imports,
1800            main_def,
1801            trait_impls: self.trait_impls,
1802            proc_macros,
1803            confused_type_with_std_module,
1804            doc_link_resolutions: self.doc_link_resolutions,
1805            doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1806            all_macro_rules: self.all_macro_rules,
1807            stripped_cfg_items,
1808        };
1809        let ast_lowering = ty::ResolverAstLowering {
1810            legacy_const_generic_args: self.legacy_const_generic_args,
1811            partial_res_map: self.partial_res_map,
1812            import_res_map: self.import_res_map,
1813            label_res_map: self.label_res_map,
1814            lifetimes_res_map: self.lifetimes_res_map,
1815            extra_lifetime_params_map: self.extra_lifetime_params_map,
1816            next_node_id: self.next_node_id,
1817            node_id_to_def_id: self
1818                .node_id_to_def_id
1819                .into_items()
1820                .map(|(k, f)| (k, f.key()))
1821                .collect(),
1822            trait_map: self.trait_map,
1823            lifetime_elision_allowed: self.lifetime_elision_allowed,
1824            lint_buffer: Steal::new(self.lint_buffer),
1825            delegation_fn_sigs: self.delegation_fn_sigs,
1826            delegation_sig_resolution_nodes: self.delegation_sig_resolution_nodes,
1827        };
1828        ResolverOutputs { global_ctxt, ast_lowering }
1829    }
1830
1831    fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1832        StableHashingContext::new(self.tcx.sess, self.tcx.untracked())
1833    }
1834
1835    fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1836        CStore::from_tcx(self.tcx)
1837    }
1838
1839    fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
1840        CStore::from_tcx_mut(self.tcx)
1841    }
1842
1843    fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1844        match macro_kind {
1845            MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1846            MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1847            MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1848        }
1849    }
1850
1851    /// Returns a conditionally mutable resolver.
1852    ///
1853    /// Currently only dependent on `assert_speculative`, if `assert_speculative` is false,
1854    /// the resolver will allow mutation; otherwise, it will be immutable.
1855    fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
1856        CmResolver::new(self, !self.assert_speculative)
1857    }
1858
1859    /// Runs the function on each namespace.
1860    fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1861        f(self, TypeNS);
1862        f(self, ValueNS);
1863        f(self, MacroNS);
1864    }
1865
1866    fn per_ns_cm<'r, F: FnMut(&mut CmResolver<'r, 'ra, 'tcx>, Namespace)>(
1867        mut self: CmResolver<'r, 'ra, 'tcx>,
1868        mut f: F,
1869    ) {
1870        f(&mut self, TypeNS);
1871        f(&mut self, ValueNS);
1872        f(&mut self, MacroNS);
1873    }
1874
1875    fn is_builtin_macro(&self, res: Res) -> bool {
1876        self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1877    }
1878
1879    fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1880        loop {
1881            match ctxt.outer_expn_data().macro_def_id {
1882                Some(def_id) => return def_id,
1883                None => ctxt.remove_mark(),
1884            };
1885        }
1886    }
1887
1888    /// Entry point to crate resolution.
1889    pub fn resolve_crate(&mut self, krate: &Crate) {
1890        self.tcx.sess.time("resolve_crate", || {
1891            self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1892            let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1893                EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1894            });
1895            self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
1896            self.tcx
1897                .sess
1898                .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1899            self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1900            self.tcx.sess.time("resolve_main", || self.resolve_main());
1901            self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1902            self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1903            self.tcx
1904                .sess
1905                .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
1906        });
1907
1908        // Make sure we don't mutate the cstore from here on.
1909        self.tcx.untracked().cstore.freeze();
1910    }
1911
1912    fn traits_in_scope(
1913        &mut self,
1914        current_trait: Option<Module<'ra>>,
1915        parent_scope: &ParentScope<'ra>,
1916        ctxt: SyntaxContext,
1917        assoc_item: Option<(Symbol, Namespace)>,
1918    ) -> Vec<TraitCandidate> {
1919        let mut found_traits = Vec::new();
1920
1921        if let Some(module) = current_trait {
1922            if self.trait_may_have_item(Some(module), assoc_item) {
1923                let def_id = module.def_id();
1924                found_traits.push(TraitCandidate { def_id, import_ids: ::smallvec::SmallVec::new()smallvec![] });
1925            }
1926        }
1927
1928        let scope_set = ScopeSet::All(TypeNS);
1929        self.cm().visit_scopes(scope_set, parent_scope, ctxt, None, |this, scope, _, _| {
1930            match scope {
1931                Scope::Module(module, _) => {
1932                    this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1933                }
1934                Scope::StdLibPrelude => {
1935                    if let Some(module) = this.prelude {
1936                        this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1937                    }
1938                }
1939                Scope::ExternPreludeItems
1940                | Scope::ExternPreludeFlags
1941                | Scope::ToolPrelude
1942                | Scope::BuiltinTypes => {}
1943                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1944            }
1945            ControlFlow::<()>::Continue(())
1946        });
1947
1948        found_traits
1949    }
1950
1951    fn traits_in_module(
1952        &mut self,
1953        module: Module<'ra>,
1954        assoc_item: Option<(Symbol, Namespace)>,
1955        found_traits: &mut Vec<TraitCandidate>,
1956    ) {
1957        module.ensure_traits(self);
1958        let traits = module.traits.borrow();
1959        for &(trait_name, trait_binding, trait_module) in traits.as_ref().unwrap().iter() {
1960            if self.trait_may_have_item(trait_module, assoc_item) {
1961                let def_id = trait_binding.res().def_id();
1962                let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name.0);
1963                found_traits.push(TraitCandidate { def_id, import_ids });
1964            }
1965        }
1966    }
1967
1968    // List of traits in scope is pruned on best effort basis. We reject traits not having an
1969    // associated item with the given name and namespace (if specified). This is a conservative
1970    // optimization, proper hygienic type-based resolution of associated items is done in typeck.
1971    // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
1972    // associated items.
1973    fn trait_may_have_item(
1974        &self,
1975        trait_module: Option<Module<'ra>>,
1976        assoc_item: Option<(Symbol, Namespace)>,
1977    ) -> bool {
1978        match (trait_module, assoc_item) {
1979            (Some(trait_module), Some((name, ns))) => self
1980                .resolutions(trait_module)
1981                .borrow()
1982                .iter()
1983                .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
1984            _ => true,
1985        }
1986    }
1987
1988    fn find_transitive_imports(
1989        &mut self,
1990        mut kind: &NameBindingKind<'_>,
1991        trait_name: Ident,
1992    ) -> SmallVec<[LocalDefId; 1]> {
1993        let mut import_ids = ::smallvec::SmallVec::new()smallvec![];
1994        while let NameBindingKind::Import { import, binding, .. } = kind {
1995            if let Some(node_id) = import.id() {
1996                let def_id = self.local_def_id(node_id);
1997                self.maybe_unused_trait_imports.insert(def_id);
1998                import_ids.push(def_id);
1999            }
2000            self.add_to_glob_map(*import, trait_name);
2001            kind = &binding.kind;
2002        }
2003        import_ids
2004    }
2005
2006    fn resolutions(&self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
2007        if module.populate_on_access.get() {
2008            module.populate_on_access.set(false);
2009            self.build_reduced_graph_external(module);
2010        }
2011        &module.0.0.lazy_resolutions
2012    }
2013
2014    fn resolution(
2015        &self,
2016        module: Module<'ra>,
2017        key: BindingKey,
2018    ) -> Option<Ref<'ra, NameResolution<'ra>>> {
2019        self.resolutions(module).borrow().get(&key).map(|resolution| resolution.borrow())
2020    }
2021
2022    fn resolution_or_default(
2023        &self,
2024        module: Module<'ra>,
2025        key: BindingKey,
2026    ) -> &'ra CmRefCell<NameResolution<'ra>> {
2027        self.resolutions(module)
2028            .borrow_mut_unchecked()
2029            .entry(key)
2030            .or_insert_with(|| self.arenas.alloc_name_resolution())
2031    }
2032
2033    /// Test if AmbiguityError ambi is any identical to any one inside ambiguity_errors
2034    fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
2035        for ambiguity_error in &self.ambiguity_errors {
2036            // if the span location and ident as well as its span are the same
2037            if ambiguity_error.kind == ambi.kind
2038                && ambiguity_error.ident == ambi.ident
2039                && ambiguity_error.ident.span == ambi.ident.span
2040                && ambiguity_error.b1.span == ambi.b1.span
2041                && ambiguity_error.b2.span == ambi.b2.span
2042                && ambiguity_error.misc1 == ambi.misc1
2043                && ambiguity_error.misc2 == ambi.misc2
2044            {
2045                return true;
2046            }
2047        }
2048        false
2049    }
2050
2051    fn record_use(&mut self, ident: Ident, used_binding: NameBinding<'ra>, used: Used) {
2052        self.record_use_inner(ident, used_binding, used, used_binding.warn_ambiguity);
2053    }
2054
2055    fn record_use_inner(
2056        &mut self,
2057        ident: Ident,
2058        used_binding: NameBinding<'ra>,
2059        used: Used,
2060        warn_ambiguity: bool,
2061    ) {
2062        if let Some((b2, kind)) = used_binding.ambiguity {
2063            let ambiguity_error = AmbiguityError {
2064                kind,
2065                ident,
2066                b1: used_binding,
2067                b2,
2068                misc1: AmbiguityErrorMisc::None,
2069                misc2: AmbiguityErrorMisc::None,
2070                warning: warn_ambiguity,
2071            };
2072            if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2073                // avoid duplicated span information to be emit out
2074                self.ambiguity_errors.push(ambiguity_error);
2075            }
2076        }
2077        if let NameBindingKind::Import { import, binding } = used_binding.kind {
2078            if let ImportKind::MacroUse { warn_private: true } = import.kind {
2079                // Do not report the lint if the macro name resolves in stdlib prelude
2080                // even without the problematic `macro_use` import.
2081                let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2082                    let empty_module = self.empty_module;
2083                    let arenas = self.arenas;
2084                    self.cm()
2085                        .maybe_resolve_ident_in_module(
2086                            ModuleOrUniformRoot::Module(prelude),
2087                            ident,
2088                            MacroNS,
2089                            &ParentScope::module(empty_module, arenas),
2090                            None,
2091                        )
2092                        .is_ok()
2093                });
2094                if !found_in_stdlib_prelude {
2095                    self.lint_buffer().buffer_lint(
2096                        PRIVATE_MACRO_USE,
2097                        import.root_id,
2098                        ident.span,
2099                        errors::MacroIsPrivate { ident },
2100                    );
2101                }
2102            }
2103            // Avoid marking `extern crate` items that refer to a name from extern prelude,
2104            // but not introduce it, as used if they are accessed from lexical scope.
2105            if used == Used::Scope
2106                && let Some(entry) = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident))
2107                && entry.item_binding == Some((used_binding, false))
2108            {
2109                return;
2110            }
2111            let old_used = self.import_use_map.entry(import).or_insert(used);
2112            if *old_used < used {
2113                *old_used = used;
2114            }
2115            if let Some(id) = import.id() {
2116                self.used_imports.insert(id);
2117            }
2118            self.add_to_glob_map(import, ident);
2119            self.record_use_inner(
2120                ident,
2121                binding,
2122                Used::Other,
2123                warn_ambiguity || binding.warn_ambiguity,
2124            );
2125        }
2126    }
2127
2128    #[inline]
2129    fn add_to_glob_map(&mut self, import: Import<'_>, ident: Ident) {
2130        if let ImportKind::Glob { id, .. } = import.kind {
2131            let def_id = self.local_def_id(id);
2132            self.glob_map.entry(def_id).or_default().insert(ident.name);
2133        }
2134    }
2135
2136    fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2137        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2137",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2137u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root({0:?})",
                                                    ident) as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_crate_root({:?})", ident);
2138        let mut ctxt = ident.span.ctxt();
2139        let mark = if ident.name == kw::DollarCrate {
2140            // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2141            // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2142            // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
2143            // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2144            // definitions actually produced by `macro` and `macro` definitions produced by
2145            // `macro_rules!`, but at least such configurations are not stable yet.
2146            ctxt = ctxt.normalize_to_macro_rules();
2147            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2147",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2147u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: marks={0:?}",
                                                    ctxt.marks().into_iter().map(|(i, t)|
                                                                (i.expn_data(), t)).collect::<Vec<_>>()) as &dyn Value))])
            });
    } else { ; }
};debug!(
2148                "resolve_crate_root: marks={:?}",
2149                ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2150            );
2151            let mut iter = ctxt.marks().into_iter().rev().peekable();
2152            let mut result = None;
2153            // Find the last opaque mark from the end if it exists.
2154            while let Some(&(mark, transparency)) = iter.peek() {
2155                if transparency == Transparency::Opaque {
2156                    result = Some(mark);
2157                    iter.next();
2158                } else {
2159                    break;
2160                }
2161            }
2162            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2162",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2162u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: found opaque mark {0:?} {1:?}",
                                                    result, result.map(|r| r.expn_data())) as &dyn Value))])
            });
    } else { ; }
};debug!(
2163                "resolve_crate_root: found opaque mark {:?} {:?}",
2164                result,
2165                result.map(|r| r.expn_data())
2166            );
2167            // Then find the last semi-opaque mark from the end if it exists.
2168            for (mark, transparency) in iter {
2169                if transparency == Transparency::SemiOpaque {
2170                    result = Some(mark);
2171                } else {
2172                    break;
2173                }
2174            }
2175            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2175",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2175u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: found semi-opaque mark {0:?} {1:?}",
                                                    result, result.map(|r| r.expn_data())) as &dyn Value))])
            });
    } else { ; }
};debug!(
2176                "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2177                result,
2178                result.map(|r| r.expn_data())
2179            );
2180            result
2181        } else {
2182            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2182",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2182u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: not DollarCrate")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_crate_root: not DollarCrate");
2183            ctxt = ctxt.normalize_to_macros_2_0();
2184            ctxt.adjust(ExpnId::root())
2185        };
2186        let module = match mark {
2187            Some(def) => self.expn_def_scope(def),
2188            None => {
2189                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2189",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2189u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root({0:?}): found no mark (ident.span = {1:?})",
                                                    ident, ident.span) as &dyn Value))])
            });
    } else { ; }
};debug!(
2190                    "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2191                    ident, ident.span
2192                );
2193                return self.graph_root;
2194            }
2195        };
2196        let module = self.expect_module(
2197            module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2198        );
2199        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2199",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2199u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root({0:?}): got module {1:?} ({2:?}) (ident.span = {3:?})",
                                                    ident, module, module.kind.name(), ident.span) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
2200            "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2201            ident,
2202            module,
2203            module.kind.name(),
2204            ident.span
2205        );
2206        module
2207    }
2208
2209    fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2210        let mut module = self.expect_module(module.nearest_parent_mod());
2211        while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2212            let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2213            module = self.expect_module(parent.nearest_parent_mod());
2214        }
2215        module
2216    }
2217
2218    fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2219        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2219",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2219u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("(recording res) recording {0:?} for {1}",
                                                    resolution, node_id) as &dyn Value))])
            });
    } else { ; }
};debug!("(recording res) recording {:?} for {}", resolution, node_id);
2220        if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2221            {
    ::core::panicking::panic_fmt(format_args!("path resolved multiple times ({0:?} before, {1:?} now)",
            prev_res, resolution));
};panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
2222        }
2223    }
2224
2225    fn record_pat_span(&mut self, node: NodeId, span: Span) {
2226        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2226",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2226u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("(recording pat) recording {0:?} for {1:?}",
                                                    node, span) as &dyn Value))])
            });
    } else { ; }
};debug!("(recording pat) recording {:?} for {:?}", node, span);
2227        self.pat_span_map.insert(node, span);
2228    }
2229
2230    fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2231        vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2232    }
2233
2234    fn set_binding_parent_module(&mut self, binding: NameBinding<'ra>, module: Module<'ra>) {
2235        if let Some(old_module) = self.binding_parent_modules.insert(binding, module) {
2236            if module != old_module {
2237                ::rustc_middle::util::bug::span_bug_fmt(binding.span,
    format_args!("parent module is reset for binding"));span_bug!(binding.span, "parent module is reset for binding");
2238            }
2239        }
2240    }
2241
2242    fn disambiguate_macro_rules_vs_modularized(
2243        &self,
2244        macro_rules: NameBinding<'ra>,
2245        modularized: NameBinding<'ra>,
2246    ) -> bool {
2247        // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
2248        // is disambiguated to mitigate regressions from macro modularization.
2249        // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
2250        //
2251        // panic on index should be impossible, the only name_bindings passed in should be from
2252        // `resolve_ident_in_scope_set` which will always refer to a local binding from an
2253        // import or macro definition
2254        let macro_rules = &self.binding_parent_modules[&macro_rules];
2255        let modularized = &self.binding_parent_modules[&modularized];
2256        macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2257            && modularized.is_ancestor_of(*macro_rules)
2258    }
2259
2260    fn extern_prelude_get_item<'r>(
2261        mut self: CmResolver<'r, 'ra, 'tcx>,
2262        ident: Ident,
2263        finalize: bool,
2264    ) -> Option<NameBinding<'ra>> {
2265        let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2266        entry.and_then(|entry| entry.item_binding).map(|(binding, _)| {
2267            if finalize {
2268                self.get_mut().record_use(ident, binding, Used::Scope);
2269            }
2270            binding
2271        })
2272    }
2273
2274    fn extern_prelude_get_flag(&self, ident: Ident, finalize: bool) -> Option<NameBinding<'ra>> {
2275        let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2276        entry.and_then(|entry| entry.flag_binding.as_ref()).and_then(|flag_binding| {
2277            let (pending_binding, finalized) = flag_binding.get();
2278            let binding = match pending_binding {
2279                PendingBinding::Ready(binding) => {
2280                    if finalize && !finalized {
2281                        self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span);
2282                    }
2283                    binding
2284                }
2285                PendingBinding::Pending => {
2286                    if true {
    if !!finalized {
        ::core::panicking::panic("assertion failed: !finalized")
    };
};debug_assert!(!finalized);
2287                    let crate_id = if finalize {
2288                        self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span)
2289                    } else {
2290                        self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2291                    };
2292                    crate_id.map(|crate_id| {
2293                        let res = Res::Def(DefKind::Mod, crate_id.as_def_id());
2294                        self.arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT)
2295                    })
2296                }
2297            };
2298            flag_binding.set((PendingBinding::Ready(binding), finalize || finalized));
2299            binding.or_else(|| finalize.then_some(self.dummy_binding))
2300        })
2301    }
2302
2303    /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
2304    /// isn't something that can be returned because it can't be made to live that long,
2305    /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
2306    /// just that an error occurred.
2307    fn resolve_rustdoc_path(
2308        &mut self,
2309        path_str: &str,
2310        ns: Namespace,
2311        parent_scope: ParentScope<'ra>,
2312    ) -> Option<Res> {
2313        let segments: Result<Vec<_>, ()> = path_str
2314            .split("::")
2315            .enumerate()
2316            .map(|(i, s)| {
2317                let sym = if s.is_empty() {
2318                    if i == 0 {
2319                        // For a path like `::a::b`, use `kw::PathRoot` as the leading segment.
2320                        kw::PathRoot
2321                    } else {
2322                        return Err(()); // occurs in cases like `String::`
2323                    }
2324                } else {
2325                    Symbol::intern(s)
2326                };
2327                Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2328            })
2329            .collect();
2330        let Ok(segments) = segments else { return None };
2331
2332        match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2333            PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2334            PathResult::NonModule(path_res) => {
2335                path_res.full_res().filter(|res| !#[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Ctor(..), _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Ctor(..), _)))
2336            }
2337            PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2338                None
2339            }
2340            PathResult::Module(..) | PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2341        }
2342    }
2343
2344    /// Retrieves definition span of the given `DefId`.
2345    fn def_span(&self, def_id: DefId) -> Span {
2346        match def_id.as_local() {
2347            Some(def_id) => self.tcx.source_span(def_id),
2348            // Query `def_span` is not used because hashing its result span is expensive.
2349            None => self.cstore().def_span_untracked(self.tcx(), def_id),
2350        }
2351    }
2352
2353    fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2354        match def_id.as_local() {
2355            Some(def_id) => self.field_names.get(&def_id).cloned(),
2356            None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
    DefKind::Struct | DefKind::Union | DefKind::Variant => true,
    _ => false,
}matches!(
2357                self.tcx.def_kind(def_id),
2358                DefKind::Struct | DefKind::Union | DefKind::Variant
2359            ) =>
2360            {
2361                Some(
2362                    self.tcx
2363                        .associated_item_def_ids(def_id)
2364                        .iter()
2365                        .map(|&def_id| {
2366                            Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2367                        })
2368                        .collect(),
2369                )
2370            }
2371            _ => None,
2372        }
2373    }
2374
2375    fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2376        match def_id.as_local() {
2377            Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2378            None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
    DefKind::Struct | DefKind::Union | DefKind::Variant => true,
    _ => false,
}matches!(
2379                self.tcx.def_kind(def_id),
2380                DefKind::Struct | DefKind::Union | DefKind::Variant
2381            ) =>
2382            {
2383                Some(
2384                    self.tcx
2385                        .associated_item_def_ids(def_id)
2386                        .iter()
2387                        .filter_map(|&def_id| {
2388                            self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2389                        })
2390                        .collect(),
2391                )
2392            }
2393            _ => None,
2394        }
2395    }
2396
2397    /// Checks if an expression refers to a function marked with
2398    /// `#[rustc_legacy_const_generics]` and returns the argument index list
2399    /// from the attribute.
2400    fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2401        let ExprKind::Path(None, path) = &expr.kind else {
2402            return None;
2403        };
2404        // Don't perform legacy const generics rewriting if the path already
2405        // has generic arguments.
2406        if path.segments.last().unwrap().args.is_some() {
2407            return None;
2408        }
2409
2410        let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
2411
2412        // We only support cross-crate argument rewriting. Uses
2413        // within the same crate should be updated to use the new
2414        // const generics style.
2415        if def_id.is_local() {
2416            return None;
2417        }
2418
2419        let indexes = {
    'done:
        {
        for i in self.tcx.get_all_attrs(def_id) {
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(AttributeKind::RustcLegacyConstGenerics {
                    fn_indexes, .. }) => {
                    break 'done Some(fn_indexes);
                }
                _ => {}
            }
        }
        None
    }
}find_attr!(
2420            // we can use parsed attrs here since for other crates they're already available
2421            self.tcx.get_all_attrs(def_id),
2422            AttributeKind::RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
2423        )
2424        .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect());
2425
2426        self.legacy_const_generic_args.insert(def_id, indexes.clone());
2427        indexes
2428    }
2429
2430    fn resolve_main(&mut self) {
2431        let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
2432        // Don't try to resolve main unless it's an executable
2433        if !any_exe {
2434            return;
2435        }
2436
2437        let module = self.graph_root;
2438        let ident = Ident::with_dummy_span(sym::main);
2439        let parent_scope = &ParentScope::module(module, self.arenas);
2440
2441        let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2442            ModuleOrUniformRoot::Module(module),
2443            ident,
2444            ValueNS,
2445            parent_scope,
2446            None,
2447        ) else {
2448            return;
2449        };
2450
2451        let res = name_binding.res();
2452        let is_import = name_binding.is_import();
2453        let span = name_binding.span;
2454        if let Res::Def(DefKind::Fn, _) = res {
2455            self.record_use(ident, name_binding, Used::Other);
2456        }
2457        self.main_def = Some(MainDefinition { res, is_import, span });
2458    }
2459}
2460
2461fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2462    let mut result = String::new();
2463    for (i, name) in names.filter(|name| *name != kw::PathRoot).enumerate() {
2464        if i > 0 {
2465            result.push_str("::");
2466        }
2467        if Ident::with_dummy_span(name).is_raw_guess() {
2468            result.push_str("r#");
2469        }
2470        result.push_str(name.as_str());
2471    }
2472    result
2473}
2474
2475fn path_names_to_string(path: &Path) -> String {
2476    names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2477}
2478
2479/// A somewhat inefficient routine to obtain the name of a module.
2480fn module_to_string(mut module: Module<'_>) -> Option<String> {
2481    let mut names = Vec::new();
2482    loop {
2483        if let ModuleKind::Def(.., name) = module.kind {
2484            if let Some(parent) = module.parent {
2485                // `unwrap` is safe: the presence of a parent means it's not the crate root.
2486                names.push(name.unwrap());
2487                module = parent
2488            } else {
2489                break;
2490            }
2491        } else {
2492            names.push(sym::opaque_module_name_placeholder);
2493            let Some(parent) = module.parent else {
2494                return None;
2495            };
2496            module = parent;
2497        }
2498    }
2499    if names.is_empty() {
2500        return None;
2501    }
2502    Some(names_to_string(names.iter().rev().copied()))
2503}
2504
2505#[derive(#[automatically_derived]
impl ::core::marker::Copy for Stage { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Stage {
    #[inline]
    fn clone(&self) -> Stage { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Stage {
    #[inline]
    fn eq(&self, other: &Stage) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for Stage {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self { Stage::Early => "Early", Stage::Late => "Late", })
    }
}Debug)]
2506enum Stage {
2507    /// Resolving an import or a macro.
2508    /// Used when macro expansion is either not yet finished, or we are finalizing its results.
2509    /// Used by default as a more restrictive variant that can produce additional errors.
2510    Early,
2511    /// Resolving something in late resolution when all imports are resolved
2512    /// and all macros are expanded.
2513    Late,
2514}
2515
2516/// Invariant: if `Finalize` is used, expansion and import resolution must be complete.
2517#[derive(#[automatically_derived]
impl ::core::marker::Copy for Finalize { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Finalize {
    #[inline]
    fn clone(&self) -> Finalize {
        let _: ::core::clone::AssertParamIsClone<NodeId>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<Used>;
        let _: ::core::clone::AssertParamIsClone<Stage>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Finalize {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["node_id", "path_span", "root_span", "report_private", "used",
                        "stage"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.node_id, &self.path_span, &self.root_span,
                        &self.report_private, &self.used, &&self.stage];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "Finalize",
            names, values)
    }
}Debug)]
2518struct Finalize {
2519    /// Node ID for linting.
2520    node_id: NodeId,
2521    /// Span of the whole path or some its characteristic fragment.
2522    /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2523    path_span: Span,
2524    /// Span of the path start, suitable for prepending something to it.
2525    /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2526    root_span: Span,
2527    /// Whether to report privacy errors or silently return "no resolution" for them,
2528    /// similarly to speculative resolution.
2529    report_private: bool = true,
2530    /// Tracks whether an item is used in scope or used relatively to a module.
2531    used: Used = Used::Other,
2532    /// Finalizing early or late resolution.
2533    stage: Stage = Stage::Early,
2534}
2535
2536impl Finalize {
2537    fn new(node_id: NodeId, path_span: Span) -> Finalize {
2538        Finalize::with_root_span(node_id, path_span, path_span)
2539    }
2540
2541    fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2542        Finalize { node_id, path_span, root_span, .. }
2543    }
2544}
2545
2546pub fn provide(providers: &mut Providers) {
2547    providers.registered_tools = macros::registered_tools;
2548}
2549
2550/// A wrapper around `&mut Resolver` that may be mutable or immutable, depending on a conditions.
2551///
2552/// `Cm` stands for "conditionally mutable".
2553///
2554/// Prefer constructing it through [`Resolver::cm`] to ensure correctness.
2555type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2556
2557// FIXME: These are cells for caches that can be populated even during speculative resolution,
2558// and should be replaced with mutexes, atomics, or other synchronized data when migrating to
2559// parallel name resolution.
2560use std::cell::{Cell as CacheCell, RefCell as CacheRefCell};
2561
2562// FIXME: `*_unchecked` methods in the module below should be eliminated in the process
2563// of migration to parallel name resolution.
2564mod ref_mut {
2565    use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2566    use std::fmt;
2567    use std::ops::Deref;
2568
2569    use crate::Resolver;
2570
2571    /// A wrapper around a mutable reference that conditionally allows mutable access.
2572    pub(crate) struct RefOrMut<'a, T> {
2573        p: &'a mut T,
2574        mutable: bool,
2575    }
2576
2577    impl<'a, T> Deref for RefOrMut<'a, T> {
2578        type Target = T;
2579
2580        fn deref(&self) -> &Self::Target {
2581            self.p
2582        }
2583    }
2584
2585    impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2586        fn as_ref(&self) -> &T {
2587            self.p
2588        }
2589    }
2590
2591    impl<'a, T> RefOrMut<'a, T> {
2592        pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2593            RefOrMut { p, mutable }
2594        }
2595
2596        /// This is needed because this wraps a `&mut T` and is therefore not `Copy`.
2597        pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2598            RefOrMut { p: self.p, mutable: self.mutable }
2599        }
2600
2601        /// Returns a mutable reference to the inner value if allowed.
2602        ///
2603        /// # Panics
2604        /// Panics if the `mutable` flag is false.
2605        #[track_caller]
2606        pub(crate) fn get_mut(&mut self) -> &mut T {
2607            match self.mutable {
2608                false => {
    ::core::panicking::panic_fmt(format_args!("Can\'t mutably borrow speculative resolver"));
}panic!("Can't mutably borrow speculative resolver"),
2609                true => self.p,
2610            }
2611        }
2612
2613        /// Returns a mutable reference to the inner value without checking if
2614        /// it's in a mutable state.
2615        pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2616            self.p
2617        }
2618    }
2619
2620    /// A wrapper around a [`Cell`] that only allows mutation based on a condition in the resolver.
2621    #[derive(#[automatically_derived]
impl<T: ::core::default::Default> ::core::default::Default for CmCell<T> {
    #[inline]
    fn default() -> CmCell<T> { CmCell(::core::default::Default::default()) }
}Default)]
2622    pub(crate) struct CmCell<T>(Cell<T>);
2623
2624    impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2625        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2626            f.debug_tuple("CmCell").field(&self.get()).finish()
2627        }
2628    }
2629
2630    impl<T: Copy> Clone for CmCell<T> {
2631        fn clone(&self) -> CmCell<T> {
2632            CmCell::new(self.get())
2633        }
2634    }
2635
2636    impl<T: Copy> CmCell<T> {
2637        pub(crate) const fn get(&self) -> T {
2638            self.0.get()
2639        }
2640
2641        pub(crate) fn update_unchecked(&self, f: impl FnOnce(T) -> T)
2642        where
2643            T: Copy,
2644        {
2645            let old = self.get();
2646            self.set_unchecked(f(old));
2647        }
2648    }
2649
2650    impl<T> CmCell<T> {
2651        pub(crate) const fn new(value: T) -> CmCell<T> {
2652            CmCell(Cell::new(value))
2653        }
2654
2655        pub(crate) fn set_unchecked(&self, val: T) {
2656            self.0.set(val);
2657        }
2658
2659        pub(crate) fn into_inner(self) -> T {
2660            self.0.into_inner()
2661        }
2662    }
2663
2664    /// A wrapper around a [`RefCell`] that only allows mutable borrows based on a condition in the resolver.
2665    #[derive(#[automatically_derived]
impl<T: ::core::default::Default> ::core::default::Default for CmRefCell<T> {
    #[inline]
    fn default() -> CmRefCell<T> {
        CmRefCell(::core::default::Default::default())
    }
}Default)]
2666    pub(crate) struct CmRefCell<T>(RefCell<T>);
2667
2668    impl<T> CmRefCell<T> {
2669        pub(crate) const fn new(value: T) -> CmRefCell<T> {
2670            CmRefCell(RefCell::new(value))
2671        }
2672
2673        #[track_caller]
2674        pub(crate) fn borrow_mut_unchecked(&self) -> RefMut<'_, T> {
2675            self.0.borrow_mut()
2676        }
2677
2678        #[track_caller]
2679        pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
2680            if r.assert_speculative {
2681                {
    ::core::panicking::panic_fmt(format_args!("Not allowed to mutably borrow a CmRefCell during speculative resolution"));
};panic!("Not allowed to mutably borrow a CmRefCell during speculative resolution");
2682            }
2683            self.borrow_mut_unchecked()
2684        }
2685
2686        #[track_caller]
2687        pub(crate) fn try_borrow_mut_unchecked(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
2688            self.0.try_borrow_mut()
2689        }
2690
2691        #[track_caller]
2692        pub(crate) fn borrow(&self) -> Ref<'_, T> {
2693            self.0.borrow()
2694        }
2695    }
2696
2697    impl<T: Default> CmRefCell<T> {
2698        pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
2699            if r.assert_speculative {
2700                {
    ::core::panicking::panic_fmt(format_args!("Not allowed to mutate a CmRefCell during speculative resolution"));
};panic!("Not allowed to mutate a CmRefCell during speculative resolution");
2701            }
2702            self.0.take()
2703        }
2704    }
2705}