Skip to main content

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