rustc_resolve/
lib.rs

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