Skip to main content

rustc_ast_lowering/
lib.rs

1//! Lowers the AST to the HIR.
2//!
3//! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
4//! much like a fold. Where lowering involves a bit more work things get more
5//! interesting and there are some invariants you should know about. These mostly
6//! concern spans and IDs.
7//!
8//! Spans are assigned to AST nodes during parsing and then are modified during
9//! expansion to indicate the origin of a node and the process it went through
10//! being expanded. IDs are assigned to AST nodes just before lowering.
11//!
12//! For the simpler lowering steps, IDs and spans should be preserved. Unlike
13//! expansion we do not preserve the process of lowering in the spans, so spans
14//! should not be modified here. When creating a new node (as opposed to
15//! "folding" an existing one), create a new ID using `next_id()`.
16//!
17//! You must ensure that IDs are unique. That means that you should only use the
18//! ID from an AST node in a single HIR node (you can assume that AST node-IDs
19//! are unique). Every new node must have a unique ID. Avoid cloning HIR nodes.
20//! If you do, you must then set the new node's ID to a fresh one.
21//!
22//! Spans are used for error messages and for tools to map semantics back to
23//! source code. It is therefore not as important with spans as IDs to be strict
24//! about use (you can't break the compiler by screwing up a span). Obviously, a
25//! HIR node can only have a single span. But multiple nodes can have the same
26//! span and spans don't need to be kept in order, etc. Where code is preserved
27//! by lowering, it should have the same span as in the AST. Where HIR nodes are
28//! new it is probably best to give a span for the whole AST node being lowered.
29//! All nodes should have real spans; don't use dummy spans. Tools are likely to
30//! get confused if the spans from leaf AST nodes occur in multiple places
31//! in the HIR, especially for multiple identifiers.
32
33// tidy-alphabetical-start
34#![feature(box_patterns)]
35#![feature(if_let_guard)]
36// tidy-alphabetical-end
37
38use std::mem;
39use std::sync::Arc;
40
41use rustc_ast::node_id::NodeMap;
42use rustc_ast::{self as ast, *};
43use rustc_attr_parsing::{AttributeParser, Late, OmitDoc};
44use rustc_data_structures::fingerprint::Fingerprint;
45use rustc_data_structures::sorted_map::SortedMap;
46use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
47use rustc_data_structures::sync::spawn;
48use rustc_data_structures::tagged_ptr::TaggedRef;
49use rustc_errors::{DiagArgFromDisplay, DiagCtxtHandle};
50use rustc_hir::attrs::AttributeKind;
51use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
52use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId};
53use rustc_hir::definitions::{DefPathData, DisambiguatorState};
54use rustc_hir::lints::{AttributeLint, DelayedLint};
55use rustc_hir::{
56    self as hir, AngleBrackets, ConstArg, GenericArg, HirId, ItemLocalMap, LifetimeSource,
57    LifetimeSyntax, ParamName, Target, TraitCandidate, find_attr,
58};
59use rustc_index::{Idx, IndexSlice, IndexVec};
60use rustc_macros::extension;
61use rustc_middle::span_bug;
62use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
63use rustc_session::parse::add_feature_diagnostics;
64use rustc_span::symbol::{Ident, Symbol, kw, sym};
65use rustc_span::{DUMMY_SP, DesugaringKind, Span};
66use smallvec::SmallVec;
67use thin_vec::ThinVec;
68use tracing::{debug, instrument, trace};
69
70use crate::errors::{AssocTyParentheses, AssocTyParenthesesSub, MisplacedImplTrait};
71
72macro_rules! arena_vec {
73    ($this:expr; $($x:expr),*) => (
74        $this.arena.alloc_from_iter([$($x),*])
75    );
76}
77
78mod asm;
79mod block;
80mod contract;
81mod delegation;
82mod errors;
83mod expr;
84mod format;
85mod index;
86mod item;
87mod pat;
88mod path;
89pub mod stability;
90
91#[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 `ast_lowering_abi_specified_multiple_times` from `ast_lowering`"]
    pub const ast_lowering_abi_specified_multiple_times:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_abi_specified_multiple_times"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_abi_specified_multiple_times.label` from `ast_lowering`"]
    pub const ast_lowering_label: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("label"));
    #[doc =
    "Constant referring to Fluent message `ast_lowering_abi_specified_multiple_times.note` from `ast_lowering`"]
    pub const ast_lowering_note: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("note"));
    #[doc =
    "Constant referring to Fluent message `ast_lowering_arbitrary_expression_in_pattern` from `ast_lowering`"]
    pub const ast_lowering_arbitrary_expression_in_pattern:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_arbitrary_expression_in_pattern"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_arbitrary_expression_in_pattern.pattern_from_macro_note` from `ast_lowering`"]
    pub const ast_lowering_pattern_from_macro_note:
        rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("pattern_from_macro_note"));
    #[doc =
    "Constant referring to Fluent message `ast_lowering_arbitrary_expression_in_pattern.const_block_in_pattern_help` from `ast_lowering`"]
    pub const ast_lowering_const_block_in_pattern_help:
        rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("const_block_in_pattern_help"));
    #[doc =
    "Constant referring to Fluent message `ast_lowering_argument` from `ast_lowering`"]
    pub const ast_lowering_argument: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_argument"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_assoc_ty_binding_in_dyn` from `ast_lowering`"]
    pub const ast_lowering_assoc_ty_binding_in_dyn: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_assoc_ty_binding_in_dyn"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_assoc_ty_binding_in_dyn.suggestion` from `ast_lowering`"]
    pub const ast_lowering_suggestion: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("suggestion"));
    #[doc =
    "Constant referring to Fluent message `ast_lowering_assoc_ty_parentheses` from `ast_lowering`"]
    pub const ast_lowering_assoc_ty_parentheses: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_assoc_ty_parentheses"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_async_bound_not_on_trait` from `ast_lowering`"]
    pub const ast_lowering_async_bound_not_on_trait: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_async_bound_not_on_trait"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_async_bound_only_for_fn_traits` from `ast_lowering`"]
    pub const ast_lowering_async_bound_only_for_fn_traits:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_async_bound_only_for_fn_traits"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_async_coroutines_not_supported` from `ast_lowering`"]
    pub const ast_lowering_async_coroutines_not_supported:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_async_coroutines_not_supported"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_att_syntax_only_x86` from `ast_lowering`"]
    pub const ast_lowering_att_syntax_only_x86: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_att_syntax_only_x86"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_await_only_in_async_fn_and_blocks` from `ast_lowering`"]
    pub const ast_lowering_await_only_in_async_fn_and_blocks:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_await_only_in_async_fn_and_blocks"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_bad_return_type_notation_inputs` from `ast_lowering`"]
    pub const ast_lowering_bad_return_type_notation_inputs:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_bad_return_type_notation_inputs"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_bad_return_type_notation_needs_dots` from `ast_lowering`"]
    pub const ast_lowering_bad_return_type_notation_needs_dots:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_bad_return_type_notation_needs_dots"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_bad_return_type_notation_output` from `ast_lowering`"]
    pub const ast_lowering_bad_return_type_notation_output:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_bad_return_type_notation_output"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_bad_return_type_notation_output_suggestion` from `ast_lowering`"]
    pub const ast_lowering_bad_return_type_notation_output_suggestion:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_bad_return_type_notation_output_suggestion"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_bad_return_type_notation_position` from `ast_lowering`"]
    pub const ast_lowering_bad_return_type_notation_position:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_bad_return_type_notation_position"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_clobber_abi_not_supported` from `ast_lowering`"]
    pub const ast_lowering_clobber_abi_not_supported:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_clobber_abi_not_supported"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_closure_cannot_be_static` from `ast_lowering`"]
    pub const ast_lowering_closure_cannot_be_static: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_closure_cannot_be_static"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_coroutine_too_many_parameters` from `ast_lowering`"]
    pub const ast_lowering_coroutine_too_many_parameters:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_coroutine_too_many_parameters"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_default_field_in_tuple` from `ast_lowering`"]
    pub const ast_lowering_default_field_in_tuple: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_default_field_in_tuple"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_delegation_cycle_in_signature_resolution` from `ast_lowering`"]
    pub const ast_lowering_delegation_cycle_in_signature_resolution:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_delegation_cycle_in_signature_resolution"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_delegation_unresolved_callee` from `ast_lowering`"]
    pub const ast_lowering_delegation_unresolved_callee:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_delegation_unresolved_callee"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_does_not_support_modifiers` from `ast_lowering`"]
    pub const ast_lowering_does_not_support_modifiers:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_does_not_support_modifiers"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_extra_double_dot` from `ast_lowering`"]
    pub const ast_lowering_extra_double_dot: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_extra_double_dot"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_functional_record_update_destructuring_assignment` from `ast_lowering`"]
    pub const ast_lowering_functional_record_update_destructuring_assignment:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_functional_record_update_destructuring_assignment"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_generic_param_default_in_binder` from `ast_lowering`"]
    pub const ast_lowering_generic_param_default_in_binder:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_generic_param_default_in_binder"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_generic_type_with_parentheses` from `ast_lowering`"]
    pub const ast_lowering_generic_type_with_parentheses:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_generic_type_with_parentheses"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_inclusive_range_with_no_end` from `ast_lowering`"]
    pub const ast_lowering_inclusive_range_with_no_end:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_inclusive_range_with_no_end"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_inline_asm_unsupported_target` from `ast_lowering`"]
    pub const ast_lowering_inline_asm_unsupported_target:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_inline_asm_unsupported_target"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_invalid_abi` from `ast_lowering`"]
    pub const ast_lowering_invalid_abi: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_invalid_abi"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_invalid_abi_clobber_abi` from `ast_lowering`"]
    pub const ast_lowering_invalid_abi_clobber_abi: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_invalid_abi_clobber_abi"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_invalid_abi_suggestion` from `ast_lowering`"]
    pub const ast_lowering_invalid_abi_suggestion: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_invalid_abi_suggestion"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_invalid_asm_template_modifier_const` from `ast_lowering`"]
    pub const ast_lowering_invalid_asm_template_modifier_const:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_invalid_asm_template_modifier_const"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_invalid_asm_template_modifier_label` from `ast_lowering`"]
    pub const ast_lowering_invalid_asm_template_modifier_label:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_invalid_asm_template_modifier_label"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_invalid_asm_template_modifier_reg_class` from `ast_lowering`"]
    pub const ast_lowering_invalid_asm_template_modifier_reg_class:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_invalid_asm_template_modifier_reg_class"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_invalid_asm_template_modifier_sym` from `ast_lowering`"]
    pub const ast_lowering_invalid_asm_template_modifier_sym:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_invalid_asm_template_modifier_sym"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_invalid_legacy_const_generic_arg` from `ast_lowering`"]
    pub const ast_lowering_invalid_legacy_const_generic_arg:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_invalid_legacy_const_generic_arg"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_invalid_legacy_const_generic_arg_suggestion` from `ast_lowering`"]
    pub const ast_lowering_invalid_legacy_const_generic_arg_suggestion:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_invalid_legacy_const_generic_arg_suggestion"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_invalid_register` from `ast_lowering`"]
    pub const ast_lowering_invalid_register: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_invalid_register"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_invalid_register_class` from `ast_lowering`"]
    pub const ast_lowering_invalid_register_class: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_invalid_register_class"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_match_arm_with_no_body` from `ast_lowering`"]
    pub const ast_lowering_match_arm_with_no_body: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_match_arm_with_no_body"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_misplaced_double_dot` from `ast_lowering`"]
    pub const ast_lowering_misplaced_double_dot: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_misplaced_double_dot"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_misplaced_impl_trait` from `ast_lowering`"]
    pub const ast_lowering_misplaced_impl_trait: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_misplaced_impl_trait"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_never_pattern_with_body` from `ast_lowering`"]
    pub const ast_lowering_never_pattern_with_body: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_never_pattern_with_body"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_never_pattern_with_guard` from `ast_lowering`"]
    pub const ast_lowering_never_pattern_with_guard: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_never_pattern_with_guard"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_no_precise_captures_on_apit` from `ast_lowering`"]
    pub const ast_lowering_no_precise_captures_on_apit:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_no_precise_captures_on_apit"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_previously_used_here` from `ast_lowering`"]
    pub const ast_lowering_previously_used_here: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_previously_used_here"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_register1` from `ast_lowering`"]
    pub const ast_lowering_register1: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_register1"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_register2` from `ast_lowering`"]
    pub const ast_lowering_register2: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_register2"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_register_class_only_clobber` from `ast_lowering`"]
    pub const ast_lowering_register_class_only_clobber:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_register_class_only_clobber"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_register_class_only_clobber_stable` from `ast_lowering`"]
    pub const ast_lowering_register_class_only_clobber_stable:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_register_class_only_clobber_stable"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_register_conflict` from `ast_lowering`"]
    pub const ast_lowering_register_conflict: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_register_conflict"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_register_conflict.help` from `ast_lowering`"]
    pub const ast_lowering_help: rustc_errors::SubdiagMessage =
        rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("help"));
    #[doc =
    "Constant referring to Fluent message `ast_lowering_remove_parentheses` from `ast_lowering`"]
    pub const ast_lowering_remove_parentheses: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_remove_parentheses"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_sub_tuple_binding` from `ast_lowering`"]
    pub const ast_lowering_sub_tuple_binding: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_sub_tuple_binding"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_sub_tuple_binding_suggestion` from `ast_lowering`"]
    pub const ast_lowering_sub_tuple_binding_suggestion:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_sub_tuple_binding_suggestion"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_support_modifiers` from `ast_lowering`"]
    pub const ast_lowering_support_modifiers: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_support_modifiers"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_template_modifier` from `ast_lowering`"]
    pub const ast_lowering_template_modifier: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_template_modifier"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_this_not_async` from `ast_lowering`"]
    pub const ast_lowering_this_not_async: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_this_not_async"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_underscore_expr_lhs_assign` from `ast_lowering`"]
    pub const ast_lowering_underscore_expr_lhs_assign:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_underscore_expr_lhs_assign"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_union_default_field_values` from `ast_lowering`"]
    pub const ast_lowering_union_default_field_values:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_union_default_field_values"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_unstable_inline_assembly` from `ast_lowering`"]
    pub const ast_lowering_unstable_inline_assembly: rustc_errors::DiagMessage
        =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_unstable_inline_assembly"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_unstable_inline_assembly_label_operand_with_outputs` from `ast_lowering`"]
    pub const
        ast_lowering_unstable_inline_assembly_label_operand_with_outputs:
        rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_unstable_inline_assembly_label_operand_with_outputs"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_unstable_may_unwind` from `ast_lowering`"]
    pub const ast_lowering_unstable_may_unwind: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_unstable_may_unwind"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_use_angle_brackets` from `ast_lowering`"]
    pub const ast_lowering_use_angle_brackets: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_use_angle_brackets"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_yield` from `ast_lowering`"]
    pub const ast_lowering_yield: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_yield"),
            None);
    #[doc =
    "Constant referring to Fluent message `ast_lowering_yield_in_closure` from `ast_lowering`"]
    pub const ast_lowering_yield_in_closure: rustc_errors::DiagMessage =
        rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("ast_lowering_yield_in_closure"),
            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" }
92
93struct LoweringContext<'a, 'hir> {
94    tcx: TyCtxt<'hir>,
95    resolver: &'a mut ResolverAstLowering,
96    disambiguator: DisambiguatorState,
97
98    /// Used to allocate HIR nodes.
99    arena: &'hir hir::Arena<'hir>,
100
101    /// Bodies inside the owner being lowered.
102    bodies: Vec<(hir::ItemLocalId, &'hir hir::Body<'hir>)>,
103    /// `#[define_opaque]` attributes
104    define_opaque: Option<&'hir [(Span, LocalDefId)]>,
105    /// Attributes inside the owner being lowered.
106    attrs: SortedMap<hir::ItemLocalId, &'hir [hir::Attribute]>,
107    /// Collect items that were created by lowering the current owner.
108    children: Vec<(LocalDefId, hir::MaybeOwner<'hir>)>,
109
110    contract_ensures: Option<(Span, Ident, HirId)>,
111
112    coroutine_kind: Option<hir::CoroutineKind>,
113
114    /// When inside an `async` context, this is the `HirId` of the
115    /// `task_context` local bound to the resume argument of the coroutine.
116    task_context: Option<HirId>,
117
118    /// Used to get the current `fn`'s def span to point to when using `await`
119    /// outside of an `async fn`.
120    current_item: Option<Span>,
121
122    try_block_scope: TryBlockScope,
123    loop_scope: Option<HirId>,
124    is_in_loop_condition: bool,
125    is_in_dyn_type: bool,
126
127    current_hir_id_owner: hir::OwnerId,
128    item_local_id_counter: hir::ItemLocalId,
129    trait_map: ItemLocalMap<Box<[TraitCandidate]>>,
130
131    impl_trait_defs: Vec<hir::GenericParam<'hir>>,
132    impl_trait_bounds: Vec<hir::WherePredicate<'hir>>,
133
134    /// NodeIds of pattern identifiers and labelled nodes that are lowered inside the current HIR owner.
135    ident_and_label_to_local_id: NodeMap<hir::ItemLocalId>,
136    /// NodeIds that are lowered inside the current HIR owner. Only used for duplicate lowering check.
137    #[cfg(debug_assertions)]
138    node_id_to_local_id: NodeMap<hir::ItemLocalId>,
139
140    allow_contracts: Arc<[Symbol]>,
141    allow_try_trait: Arc<[Symbol]>,
142    allow_gen_future: Arc<[Symbol]>,
143    allow_pattern_type: Arc<[Symbol]>,
144    allow_async_gen: Arc<[Symbol]>,
145    allow_async_iterator: Arc<[Symbol]>,
146    allow_for_await: Arc<[Symbol]>,
147    allow_async_fn_traits: Arc<[Symbol]>,
148
149    delayed_lints: Vec<DelayedLint>,
150
151    attribute_parser: AttributeParser<'hir>,
152}
153
154impl<'a, 'hir> LoweringContext<'a, 'hir> {
155    fn new(tcx: TyCtxt<'hir>, resolver: &'a mut ResolverAstLowering) -> Self {
156        let registered_tools = tcx.registered_tools(()).iter().map(|x| x.name).collect();
157        Self {
158            // Pseudo-globals.
159            tcx,
160            resolver,
161            disambiguator: DisambiguatorState::new(),
162            arena: tcx.hir_arena,
163
164            // HirId handling.
165            bodies: Vec::new(),
166            define_opaque: None,
167            attrs: SortedMap::default(),
168            children: Vec::default(),
169            contract_ensures: None,
170            current_hir_id_owner: hir::CRATE_OWNER_ID,
171            item_local_id_counter: hir::ItemLocalId::ZERO,
172            ident_and_label_to_local_id: Default::default(),
173            #[cfg(debug_assertions)]
174            node_id_to_local_id: Default::default(),
175            trait_map: Default::default(),
176
177            // Lowering state.
178            try_block_scope: TryBlockScope::Function,
179            loop_scope: None,
180            is_in_loop_condition: false,
181            is_in_dyn_type: false,
182            coroutine_kind: None,
183            task_context: None,
184            current_item: None,
185            impl_trait_defs: Vec::new(),
186            impl_trait_bounds: Vec::new(),
187            allow_contracts: [sym::contracts_internals].into(),
188            allow_try_trait: [
189                sym::try_trait_v2,
190                sym::try_trait_v2_residual,
191                sym::yeet_desugar_details,
192            ]
193            .into(),
194            allow_pattern_type: [sym::pattern_types, sym::pattern_type_range_trait].into(),
195            allow_gen_future: if tcx.features().async_fn_track_caller() {
196                [sym::gen_future, sym::closure_track_caller].into()
197            } else {
198                [sym::gen_future].into()
199            },
200            allow_for_await: [sym::async_gen_internals, sym::async_iterator].into(),
201            allow_async_fn_traits: [sym::async_fn_traits].into(),
202            allow_async_gen: [sym::async_gen_internals].into(),
203            // FIXME(gen_blocks): how does `closure_track_caller`/`async_fn_track_caller`
204            // interact with `gen`/`async gen` blocks
205            allow_async_iterator: [sym::gen_future, sym::async_iterator].into(),
206
207            attribute_parser: AttributeParser::new(
208                tcx.sess,
209                tcx.features(),
210                registered_tools,
211                Late,
212            ),
213            delayed_lints: Vec::new(),
214        }
215    }
216
217    pub(crate) fn dcx(&self) -> DiagCtxtHandle<'hir> {
218        self.tcx.dcx()
219    }
220}
221
222struct SpanLowerer {
223    is_incremental: bool,
224    def_id: LocalDefId,
225}
226
227impl SpanLowerer {
228    fn lower(&self, span: Span) -> Span {
229        if self.is_incremental {
230            span.with_parent(Some(self.def_id))
231        } else {
232            // Do not make spans relative when not using incremental compilation.
233            span
234        }
235    }
236}
237
238impl ResolverAstLoweringExt for ResolverAstLowering {
    fn legacy_const_generic_args(&self, expr: &Expr, tcx: TyCtxt<'_>)
        -> Option<Vec<usize>> {
        let ExprKind::Path(None, path) = &expr.kind else { return None; };
        if path.segments.last().unwrap().args.is_some() { return None; }
        let def_id =
            self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
        if def_id.is_local() { return None; }
        {
                'done:
                    {
                    for i in 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
                }
            }.map(|fn_indexes|
                fn_indexes.iter().map(|(num, _)| *num).collect())
    }
    fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
        self.partial_res_map.get(&id).copied()
    }
    #[doc =
    " Obtains per-namespace resolutions for `use` statement with the given `NodeId`."]
    fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
        self.import_res_map.get(&id).copied().unwrap_or_default()
    }
    #[doc = " Obtains resolution for a label with the given `NodeId`."]
    fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
        self.label_res_map.get(&id).copied()
    }
    #[doc = " Obtains resolution for a lifetime with the given `NodeId`."]
    fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
        self.lifetimes_res_map.get(&id).copied()
    }
    #[doc = " Obtain the list of lifetimes parameters to add to an item."]
    #[doc = ""]
    #[doc =
    " Extra lifetime parameters should only be added in places that can appear"]
    #[doc = " as a `binder` in `LifetimeRes`."]
    #[doc = ""]
    #[doc =
    " The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring"]
    #[doc = " should appear at the enclosing `PolyTraitRef`."]
    fn extra_lifetime_params(&mut self, id: NodeId)
        -> Vec<(Ident, NodeId, LifetimeRes)> {
        self.extra_lifetime_params_map.get(&id).cloned().unwrap_or_default()
    }
}#[extension(trait ResolverAstLoweringExt)]
239impl ResolverAstLowering {
240    fn legacy_const_generic_args(&self, expr: &Expr, tcx: TyCtxt<'_>) -> Option<Vec<usize>> {
241        let ExprKind::Path(None, path) = &expr.kind else {
242            return None;
243        };
244
245        // Don't perform legacy const generics rewriting if the path already
246        // has generic arguments.
247        if path.segments.last().unwrap().args.is_some() {
248            return None;
249        }
250
251        let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
252
253        // We only support cross-crate argument rewriting. Uses
254        // within the same crate should be updated to use the new
255        // const generics style.
256        if def_id.is_local() {
257            return None;
258        }
259
260        find_attr!(
261            // we can use parsed attrs here since for other crates they're already available
262            tcx.get_all_attrs(def_id),
263            AttributeKind::RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
264        )
265        .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
266    }
267
268    fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
269        self.partial_res_map.get(&id).copied()
270    }
271
272    /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
273    fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
274        self.import_res_map.get(&id).copied().unwrap_or_default()
275    }
276
277    /// Obtains resolution for a label with the given `NodeId`.
278    fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
279        self.label_res_map.get(&id).copied()
280    }
281
282    /// Obtains resolution for a lifetime with the given `NodeId`.
283    fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
284        self.lifetimes_res_map.get(&id).copied()
285    }
286
287    /// Obtain the list of lifetimes parameters to add to an item.
288    ///
289    /// Extra lifetime parameters should only be added in places that can appear
290    /// as a `binder` in `LifetimeRes`.
291    ///
292    /// The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring
293    /// should appear at the enclosing `PolyTraitRef`.
294    fn extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> {
295        self.extra_lifetime_params_map.get(&id).cloned().unwrap_or_default()
296    }
297}
298
299/// How relaxed bounds `?Trait` should be treated.
300///
301/// Relaxed bounds should only be allowed in places where we later
302/// (namely during HIR ty lowering) perform *sized elaboration*.
303#[derive(#[automatically_derived]
impl<'a> ::core::clone::Clone for RelaxedBoundPolicy<'a> {
    #[inline]
    fn clone(&self) -> RelaxedBoundPolicy<'a> {
        let _: ::core::clone::AssertParamIsClone<NodeId>;
        let _: ::core::clone::AssertParamIsClone<&'a [ast::GenericParam]>;
        let _: ::core::clone::AssertParamIsClone<RelaxedBoundForbiddenReason>;
        *self
    }
}Clone, #[automatically_derived]
impl<'a> ::core::marker::Copy for RelaxedBoundPolicy<'a> { }Copy, #[automatically_derived]
impl<'a> ::core::fmt::Debug for RelaxedBoundPolicy<'a> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            RelaxedBoundPolicy::Allowed =>
                ::core::fmt::Formatter::write_str(f, "Allowed"),
            RelaxedBoundPolicy::AllowedIfOnTyParam(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "AllowedIfOnTyParam", __self_0, &__self_1),
            RelaxedBoundPolicy::Forbidden(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Forbidden", &__self_0),
        }
    }
}Debug)]
304enum RelaxedBoundPolicy<'a> {
305    Allowed,
306    AllowedIfOnTyParam(NodeId, &'a [ast::GenericParam]),
307    Forbidden(RelaxedBoundForbiddenReason),
308}
309
310#[derive(#[automatically_derived]
impl ::core::clone::Clone for RelaxedBoundForbiddenReason {
    #[inline]
    fn clone(&self) -> RelaxedBoundForbiddenReason { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for RelaxedBoundForbiddenReason { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for RelaxedBoundForbiddenReason {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                RelaxedBoundForbiddenReason::TraitObjectTy => "TraitObjectTy",
                RelaxedBoundForbiddenReason::SuperTrait => "SuperTrait",
                RelaxedBoundForbiddenReason::TraitAlias => "TraitAlias",
                RelaxedBoundForbiddenReason::AssocTyBounds => "AssocTyBounds",
                RelaxedBoundForbiddenReason::LateBoundVarsInScope =>
                    "LateBoundVarsInScope",
            })
    }
}Debug)]
311enum RelaxedBoundForbiddenReason {
312    TraitObjectTy,
313    SuperTrait,
314    TraitAlias,
315    AssocTyBounds,
316    LateBoundVarsInScope,
317}
318
319/// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
320/// and if so, what meaning it has.
321#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ImplTraitContext {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ImplTraitContext::Universal =>
                ::core::fmt::Formatter::write_str(f, "Universal"),
            ImplTraitContext::OpaqueTy { origin: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OpaqueTy", "origin", &__self_0),
            ImplTraitContext::InBinding =>
                ::core::fmt::Formatter::write_str(f, "InBinding"),
            ImplTraitContext::FeatureGated(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "FeatureGated", __self_0, &__self_1),
            ImplTraitContext::Disallowed(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Disallowed", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ImplTraitContext { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ImplTraitContext {
    #[inline]
    fn clone(&self) -> ImplTraitContext {
        let _:
                ::core::clone::AssertParamIsClone<hir::OpaqueTyOrigin<LocalDefId>>;
        let _: ::core::clone::AssertParamIsClone<ImplTraitPosition>;
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ImplTraitContext {
    #[inline]
    fn eq(&self, other: &ImplTraitContext) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ImplTraitContext::OpaqueTy { origin: __self_0 },
                    ImplTraitContext::OpaqueTy { origin: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                (ImplTraitContext::FeatureGated(__self_0, __self_1),
                    ImplTraitContext::FeatureGated(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (ImplTraitContext::Disallowed(__self_0),
                    ImplTraitContext::Disallowed(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ImplTraitContext {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<hir::OpaqueTyOrigin<LocalDefId>>;
        let _: ::core::cmp::AssertParamIsEq<ImplTraitPosition>;
        let _: ::core::cmp::AssertParamIsEq<Symbol>;
    }
}Eq)]
322enum ImplTraitContext {
323    /// Treat `impl Trait` as shorthand for a new universal generic parameter.
324    /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
325    /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
326    ///
327    /// Newly generated parameters should be inserted into the given `Vec`.
328    Universal,
329
330    /// Treat `impl Trait` as shorthand for a new opaque type.
331    /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
332    /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
333    ///
334    OpaqueTy { origin: hir::OpaqueTyOrigin<LocalDefId> },
335
336    /// Treat `impl Trait` as a "trait ascription", which is like a type
337    /// variable but that also enforces that a set of trait goals hold.
338    ///
339    /// This is useful to guide inference for unnameable types.
340    InBinding,
341
342    /// `impl Trait` is unstably accepted in this position.
343    FeatureGated(ImplTraitPosition, Symbol),
344    /// `impl Trait` is not accepted in this position.
345    Disallowed(ImplTraitPosition),
346}
347
348/// Position in which `impl Trait` is disallowed.
349#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ImplTraitPosition {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ImplTraitPosition::Path => "Path",
                ImplTraitPosition::Variable => "Variable",
                ImplTraitPosition::Trait => "Trait",
                ImplTraitPosition::Bound => "Bound",
                ImplTraitPosition::Generic => "Generic",
                ImplTraitPosition::ExternFnParam => "ExternFnParam",
                ImplTraitPosition::ClosureParam => "ClosureParam",
                ImplTraitPosition::PointerParam => "PointerParam",
                ImplTraitPosition::FnTraitParam => "FnTraitParam",
                ImplTraitPosition::ExternFnReturn => "ExternFnReturn",
                ImplTraitPosition::ClosureReturn => "ClosureReturn",
                ImplTraitPosition::PointerReturn => "PointerReturn",
                ImplTraitPosition::FnTraitReturn => "FnTraitReturn",
                ImplTraitPosition::GenericDefault => "GenericDefault",
                ImplTraitPosition::ConstTy => "ConstTy",
                ImplTraitPosition::StaticTy => "StaticTy",
                ImplTraitPosition::AssocTy => "AssocTy",
                ImplTraitPosition::FieldTy => "FieldTy",
                ImplTraitPosition::Cast => "Cast",
                ImplTraitPosition::ImplSelf => "ImplSelf",
                ImplTraitPosition::OffsetOf => "OffsetOf",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ImplTraitPosition { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ImplTraitPosition {
    #[inline]
    fn clone(&self) -> ImplTraitPosition { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ImplTraitPosition {
    #[inline]
    fn eq(&self, other: &ImplTraitPosition) -> 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::Eq for ImplTraitPosition {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {}
}Eq)]
350enum ImplTraitPosition {
351    Path,
352    Variable,
353    Trait,
354    Bound,
355    Generic,
356    ExternFnParam,
357    ClosureParam,
358    PointerParam,
359    FnTraitParam,
360    ExternFnReturn,
361    ClosureReturn,
362    PointerReturn,
363    FnTraitReturn,
364    GenericDefault,
365    ConstTy,
366    StaticTy,
367    AssocTy,
368    FieldTy,
369    Cast,
370    ImplSelf,
371    OffsetOf,
372}
373
374impl std::fmt::Display for ImplTraitPosition {
375    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
376        let name = match self {
377            ImplTraitPosition::Path => "paths",
378            ImplTraitPosition::Variable => "the type of variable bindings",
379            ImplTraitPosition::Trait => "traits",
380            ImplTraitPosition::Bound => "bounds",
381            ImplTraitPosition::Generic => "generics",
382            ImplTraitPosition::ExternFnParam => "`extern fn` parameters",
383            ImplTraitPosition::ClosureParam => "closure parameters",
384            ImplTraitPosition::PointerParam => "`fn` pointer parameters",
385            ImplTraitPosition::FnTraitParam => "the parameters of `Fn` trait bounds",
386            ImplTraitPosition::ExternFnReturn => "`extern fn` return types",
387            ImplTraitPosition::ClosureReturn => "closure return types",
388            ImplTraitPosition::PointerReturn => "`fn` pointer return types",
389            ImplTraitPosition::FnTraitReturn => "the return type of `Fn` trait bounds",
390            ImplTraitPosition::GenericDefault => "generic parameter defaults",
391            ImplTraitPosition::ConstTy => "const types",
392            ImplTraitPosition::StaticTy => "static types",
393            ImplTraitPosition::AssocTy => "associated types",
394            ImplTraitPosition::FieldTy => "field types",
395            ImplTraitPosition::Cast => "cast expression types",
396            ImplTraitPosition::ImplSelf => "impl headers",
397            ImplTraitPosition::OffsetOf => "`offset_of!` parameters",
398        };
399
400        f.write_fmt(format_args!("{0}", name))write!(f, "{name}")
401    }
402}
403
404#[derive(#[automatically_derived]
impl ::core::marker::Copy for FnDeclKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for FnDeclKind {
    #[inline]
    fn clone(&self) -> FnDeclKind { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for FnDeclKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                FnDeclKind::Fn => "Fn",
                FnDeclKind::Inherent => "Inherent",
                FnDeclKind::ExternFn => "ExternFn",
                FnDeclKind::Closure => "Closure",
                FnDeclKind::Pointer => "Pointer",
                FnDeclKind::Trait => "Trait",
                FnDeclKind::Impl => "Impl",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for FnDeclKind {
    #[inline]
    fn eq(&self, other: &FnDeclKind) -> 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::Eq for FnDeclKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {}
}Eq)]
405enum FnDeclKind {
406    Fn,
407    Inherent,
408    ExternFn,
409    Closure,
410    Pointer,
411    Trait,
412    Impl,
413}
414
415#[derive(#[automatically_derived]
impl<'a> ::core::marker::Copy for AstOwner<'a> { }Copy, #[automatically_derived]
impl<'a> ::core::clone::Clone for AstOwner<'a> {
    #[inline]
    fn clone(&self) -> AstOwner<'a> {
        let _: ::core::clone::AssertParamIsClone<&'a ast::Crate>;
        let _: ::core::clone::AssertParamIsClone<&'a ast::Item>;
        let _: ::core::clone::AssertParamIsClone<&'a ast::AssocItem>;
        let _: ::core::clone::AssertParamIsClone<visit::AssocCtxt>;
        let _: ::core::clone::AssertParamIsClone<&'a ast::ForeignItem>;
        *self
    }
}Clone)]
416enum AstOwner<'a> {
417    NonOwner,
418    Crate(&'a ast::Crate),
419    Item(&'a ast::Item),
420    AssocItem(&'a ast::AssocItem, visit::AssocCtxt),
421    ForeignItem(&'a ast::ForeignItem),
422}
423
424#[derive(#[automatically_derived]
impl ::core::marker::Copy for TryBlockScope { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TryBlockScope {
    #[inline]
    fn clone(&self) -> TryBlockScope {
        let _: ::core::clone::AssertParamIsClone<HirId>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for TryBlockScope {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TryBlockScope::Function =>
                ::core::fmt::Formatter::write_str(f, "Function"),
            TryBlockScope::Homogeneous(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Homogeneous", &__self_0),
            TryBlockScope::Heterogeneous(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Heterogeneous", &__self_0),
        }
    }
}Debug)]
425enum TryBlockScope {
426    /// There isn't a `try` block, so a `?` will use `return`.
427    Function,
428    /// We're inside a `try { … }` block, so a `?` will block-break
429    /// from that block using a type depending only on the argument.
430    Homogeneous(HirId),
431    /// We're inside a `try as _ { … }` block, so a `?` will block-break
432    /// from that block using the type specified.
433    Heterogeneous(HirId),
434}
435
436fn index_crate<'a>(
437    node_id_to_def_id: &NodeMap<LocalDefId>,
438    krate: &'a Crate,
439) -> IndexVec<LocalDefId, AstOwner<'a>> {
440    let mut indexer = Indexer { node_id_to_def_id, index: IndexVec::new() };
441    *indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner) =
442        AstOwner::Crate(krate);
443    visit::walk_crate(&mut indexer, krate);
444    return indexer.index;
445
446    struct Indexer<'s, 'a> {
447        node_id_to_def_id: &'s NodeMap<LocalDefId>,
448        index: IndexVec<LocalDefId, AstOwner<'a>>,
449    }
450
451    impl<'a> visit::Visitor<'a> for Indexer<'_, 'a> {
452        fn visit_attribute(&mut self, _: &'a Attribute) {
453            // We do not want to lower expressions that appear in attributes,
454            // as they are not accessible to the rest of the HIR.
455        }
456
457        fn visit_item(&mut self, item: &'a ast::Item) {
458            let def_id = self.node_id_to_def_id[&item.id];
459            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) = AstOwner::Item(item);
460            visit::walk_item(self, item)
461        }
462
463        fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) {
464            let def_id = self.node_id_to_def_id[&item.id];
465            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) =
466                AstOwner::AssocItem(item, ctxt);
467            visit::walk_assoc_item(self, item, ctxt);
468        }
469
470        fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) {
471            let def_id = self.node_id_to_def_id[&item.id];
472            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) =
473                AstOwner::ForeignItem(item);
474            visit::walk_item(self, item);
475        }
476    }
477}
478
479/// Compute the hash for the HIR of the full crate.
480/// This hash will then be part of the crate_hash which is stored in the metadata.
481fn compute_hir_hash(
482    tcx: TyCtxt<'_>,
483    owners: &IndexSlice<LocalDefId, hir::MaybeOwner<'_>>,
484) -> Fingerprint {
485    let mut hir_body_nodes: Vec<_> = owners
486        .iter_enumerated()
487        .filter_map(|(def_id, info)| {
488            let info = info.as_owner()?;
489            let def_path_hash = tcx.hir_def_path_hash(def_id);
490            Some((def_path_hash, info))
491        })
492        .collect();
493    hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
494
495    tcx.with_stable_hashing_context(|mut hcx| {
496        let mut stable_hasher = StableHasher::new();
497        hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher);
498        stable_hasher.finish()
499    })
500}
501
502pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> hir::Crate<'_> {
503    let sess = tcx.sess;
504    // Queries that borrow `resolver_for_lowering`.
505    tcx.ensure_done().output_filenames(());
506    tcx.ensure_done().early_lint_checks(());
507    tcx.ensure_done().debugger_visualizers(LOCAL_CRATE);
508    tcx.ensure_done().get_lang_items(());
509    let (mut resolver, krate) = tcx.resolver_for_lowering().steal();
510
511    let ast_index = index_crate(&resolver.node_id_to_def_id, &krate);
512    let mut owners = IndexVec::from_fn_n(
513        |_| hir::MaybeOwner::Phantom,
514        tcx.definitions_untracked().def_index_count(),
515    );
516
517    let mut lowerer = item::ItemLowerer {
518        tcx,
519        resolver: &mut resolver,
520        ast_index: &ast_index,
521        owners: &mut owners,
522    };
523    for def_id in ast_index.indices() {
524        lowerer.lower_node(def_id);
525    }
526
527    drop(ast_index);
528
529    // Drop AST to free memory. It can be expensive so try to drop it on a separate thread.
530    let prof = sess.prof.clone();
531    spawn(move || {
532        let _timer = prof.verbose_generic_activity("drop_ast");
533        drop(krate);
534    });
535
536    // Don't hash unless necessary, because it's expensive.
537    let opt_hir_hash =
538        if tcx.needs_crate_hash() { Some(compute_hir_hash(tcx, &owners)) } else { None };
539    hir::Crate { owners, opt_hir_hash }
540}
541
542#[derive(#[automatically_derived]
impl ::core::marker::Copy for ParamMode { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ParamMode {
    #[inline]
    fn clone(&self) -> ParamMode { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ParamMode {
    #[inline]
    fn eq(&self, other: &ParamMode) -> 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 ParamMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ParamMode::Explicit => "Explicit",
                ParamMode::Optional => "Optional",
            })
    }
}Debug)]
543enum ParamMode {
544    /// Any path in a type context.
545    Explicit,
546    /// The `module::Type` in `module::Type::method` in an expression.
547    Optional,
548}
549
550#[derive(#[automatically_derived]
impl ::core::marker::Copy for AllowReturnTypeNotation { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AllowReturnTypeNotation {
    #[inline]
    fn clone(&self) -> AllowReturnTypeNotation { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AllowReturnTypeNotation {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AllowReturnTypeNotation::Yes => "Yes",
                AllowReturnTypeNotation::No => "No",
            })
    }
}Debug)]
551enum AllowReturnTypeNotation {
552    /// Only in types, since RTN is denied later during HIR lowering.
553    Yes,
554    /// All other positions (path expr, method, use tree).
555    No,
556}
557
558enum GenericArgsMode {
559    /// Allow paren sugar, don't allow RTN.
560    ParenSugar,
561    /// Allow RTN, don't allow paren sugar.
562    ReturnTypeNotation,
563    // Error if parenthesized generics or RTN are encountered.
564    Err,
565    /// Silence errors when lowering generics. Only used with `Res::Err`.
566    Silence,
567}
568
569impl<'a, 'hir> LoweringContext<'a, 'hir> {
570    fn create_def(
571        &mut self,
572        node_id: ast::NodeId,
573        name: Option<Symbol>,
574        def_kind: DefKind,
575        def_path_data: DefPathData,
576        span: Span,
577    ) -> LocalDefId {
578        let parent = self.current_hir_id_owner.def_id;
579        match (&node_id, &ast::DUMMY_NODE_ID) {
    (left_val, right_val) => {
        if *left_val == *right_val {
            let kind = ::core::panicking::AssertKind::Ne;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_ne!(node_id, ast::DUMMY_NODE_ID);
580        if !self.opt_local_def_id(node_id).is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("adding a def\'n for node-id {0:?} and def kind {1:?} but a previous def\'n exists: {2:?}",
                node_id, def_kind,
                self.tcx.hir_def_key(self.local_def_id(node_id))));
    }
};assert!(
581            self.opt_local_def_id(node_id).is_none(),
582            "adding a def'n for node-id {:?} and def kind {:?} but a previous def'n exists: {:?}",
583            node_id,
584            def_kind,
585            self.tcx.hir_def_key(self.local_def_id(node_id)),
586        );
587
588        let def_id = self
589            .tcx
590            .at(span)
591            .create_def(parent, name, def_kind, Some(def_path_data), &mut self.disambiguator)
592            .def_id();
593
594        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:594",
                        "rustc_ast_lowering", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(594u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                        ::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);
595        self.resolver.node_id_to_def_id.insert(node_id, def_id);
596
597        def_id
598    }
599
600    fn next_node_id(&mut self) -> NodeId {
601        let start = self.resolver.next_node_id;
602        let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
603        self.resolver.next_node_id = ast::NodeId::from_u32(next);
604        start
605    }
606
607    /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
608    /// resolver (if any).
609    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
610        self.resolver.node_id_to_def_id.get(&node).copied()
611    }
612
613    fn local_def_id(&self, node: NodeId) -> LocalDefId {
614        self.opt_local_def_id(node).unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("no entry for node id: `{0:?}`",
            node));
}panic!("no entry for node id: `{node:?}`"))
615    }
616
617    /// Given the id of an owner node in the AST, returns the corresponding `OwnerId`.
618    fn owner_id(&self, node: NodeId) -> hir::OwnerId {
619        hir::OwnerId { def_id: self.local_def_id(node) }
620    }
621
622    /// Freshen the `LoweringContext` and ready it to lower a nested item.
623    /// The lowered item is registered into `self.children`.
624    ///
625    /// This function sets up `HirId` lowering infrastructure,
626    /// and stashes the shared mutable state to avoid pollution by the closure.
627    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("with_hir_id_owner",
                                    "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(627u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["owner"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&owner)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let owner_id = self.owner_id(owner);
            let current_attrs = std::mem::take(&mut self.attrs);
            let current_bodies = std::mem::take(&mut self.bodies);
            let current_define_opaque =
                std::mem::take(&mut self.define_opaque);
            let current_ident_and_label_to_local_id =
                std::mem::take(&mut self.ident_and_label_to_local_id);
            let current_node_id_to_local_id =
                std::mem::take(&mut self.node_id_to_local_id);
            let current_trait_map = std::mem::take(&mut self.trait_map);
            let current_owner =
                std::mem::replace(&mut self.current_hir_id_owner, owner_id);
            let current_local_counter =
                std::mem::replace(&mut self.item_local_id_counter,
                    hir::ItemLocalId::new(1));
            let current_impl_trait_defs =
                std::mem::take(&mut self.impl_trait_defs);
            let current_impl_trait_bounds =
                std::mem::take(&mut self.impl_trait_bounds);
            let current_delayed_lints =
                std::mem::take(&mut self.delayed_lints);
            {
                let _old =
                    self.node_id_to_local_id.insert(owner,
                        hir::ItemLocalId::ZERO);
                if true {
                    match (&_old, &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);
                            }
                        }
                    };
                };
            }
            let item = f(self);
            match (&owner_id, &item.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);
                    }
                }
            };
            if !self.impl_trait_defs.is_empty() {
                ::core::panicking::panic("assertion failed: self.impl_trait_defs.is_empty()")
            };
            if !self.impl_trait_bounds.is_empty() {
                ::core::panicking::panic("assertion failed: self.impl_trait_bounds.is_empty()")
            };
            let info = self.make_owner_info(item);
            self.attrs = current_attrs;
            self.bodies = current_bodies;
            self.define_opaque = current_define_opaque;
            self.ident_and_label_to_local_id =
                current_ident_and_label_to_local_id;
            { self.node_id_to_local_id = current_node_id_to_local_id; }
            self.trait_map = current_trait_map;
            self.current_hir_id_owner = current_owner;
            self.item_local_id_counter = current_local_counter;
            self.impl_trait_defs = current_impl_trait_defs;
            self.impl_trait_bounds = current_impl_trait_bounds;
            self.delayed_lints = current_delayed_lints;
            if true {
                if !!self.children.iter().any(|(id, _)|
                                    id == &owner_id.def_id) {
                    ::core::panicking::panic("assertion failed: !self.children.iter().any(|(id, _)| id == &owner_id.def_id)")
                };
            };
            self.children.push((owner_id.def_id,
                    hir::MaybeOwner::Owner(info)));
        }
    }
}#[instrument(level = "debug", skip(self, f))]
628    fn with_hir_id_owner(
629        &mut self,
630        owner: NodeId,
631        f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
632    ) {
633        let owner_id = self.owner_id(owner);
634
635        let current_attrs = std::mem::take(&mut self.attrs);
636        let current_bodies = std::mem::take(&mut self.bodies);
637        let current_define_opaque = std::mem::take(&mut self.define_opaque);
638        let current_ident_and_label_to_local_id =
639            std::mem::take(&mut self.ident_and_label_to_local_id);
640
641        #[cfg(debug_assertions)]
642        let current_node_id_to_local_id = std::mem::take(&mut self.node_id_to_local_id);
643        let current_trait_map = std::mem::take(&mut self.trait_map);
644        let current_owner = std::mem::replace(&mut self.current_hir_id_owner, owner_id);
645        let current_local_counter =
646            std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
647        let current_impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
648        let current_impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
649        let current_delayed_lints = std::mem::take(&mut self.delayed_lints);
650
651        // Do not reset `next_node_id` and `node_id_to_def_id`:
652        // we want `f` to be able to refer to the `LocalDefId`s that the caller created.
653        // and the caller to refer to some of the subdefinitions' nodes' `LocalDefId`s.
654
655        // Always allocate the first `HirId` for the owner itself.
656        #[cfg(debug_assertions)]
657        {
658            let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::ZERO);
659            debug_assert_eq!(_old, None);
660        }
661
662        let item = f(self);
663        assert_eq!(owner_id, item.def_id());
664        // `f` should have consumed all the elements in these vectors when constructing `item`.
665        assert!(self.impl_trait_defs.is_empty());
666        assert!(self.impl_trait_bounds.is_empty());
667        let info = self.make_owner_info(item);
668
669        self.attrs = current_attrs;
670        self.bodies = current_bodies;
671        self.define_opaque = current_define_opaque;
672        self.ident_and_label_to_local_id = current_ident_and_label_to_local_id;
673
674        #[cfg(debug_assertions)]
675        {
676            self.node_id_to_local_id = current_node_id_to_local_id;
677        }
678        self.trait_map = current_trait_map;
679        self.current_hir_id_owner = current_owner;
680        self.item_local_id_counter = current_local_counter;
681        self.impl_trait_defs = current_impl_trait_defs;
682        self.impl_trait_bounds = current_impl_trait_bounds;
683        self.delayed_lints = current_delayed_lints;
684
685        debug_assert!(!self.children.iter().any(|(id, _)| id == &owner_id.def_id));
686        self.children.push((owner_id.def_id, hir::MaybeOwner::Owner(info)));
687    }
688
689    fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> {
690        let attrs = std::mem::take(&mut self.attrs);
691        let mut bodies = std::mem::take(&mut self.bodies);
692        let define_opaque = std::mem::take(&mut self.define_opaque);
693        let trait_map = std::mem::take(&mut self.trait_map);
694        let delayed_lints = std::mem::take(&mut self.delayed_lints).into_boxed_slice();
695
696        #[cfg(debug_assertions)]
697        for (id, attrs) in attrs.iter() {
698            // Verify that we do not store empty slices in the map.
699            if attrs.is_empty() {
700                {
    ::core::panicking::panic_fmt(format_args!("Stored empty attributes for {0:?}",
            id));
};panic!("Stored empty attributes for {:?}", id);
701            }
702        }
703
704        bodies.sort_by_key(|(k, _)| *k);
705        let bodies = SortedMap::from_presorted_elements(bodies);
706
707        // Don't hash unless necessary, because it's expensive.
708        let rustc_middle::hir::Hashes { opt_hash_including_bodies, attrs_hash, delayed_lints_hash } =
709            self.tcx.hash_owner_nodes(node, &bodies, &attrs, &delayed_lints, define_opaque);
710        let num_nodes = self.item_local_id_counter.as_usize();
711        let (nodes, parenting) = index::index_hir(self.tcx, node, &bodies, num_nodes);
712        let nodes = hir::OwnerNodes { opt_hash_including_bodies, nodes, bodies };
713        let attrs = hir::AttributeMap { map: attrs, opt_hash: attrs_hash, define_opaque };
714        let delayed_lints =
715            hir::lints::DelayedLints { lints: delayed_lints, opt_hash: delayed_lints_hash };
716
717        self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map, delayed_lints })
718    }
719
720    /// This method allocates a new `HirId` for the given `NodeId`.
721    /// Take care not to call this method if the resulting `HirId` is then not
722    /// actually used in the HIR, as that would trigger an assertion in the
723    /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
724    /// properly. Calling the method twice with the same `NodeId` is also forbidden.
725    x;#[instrument(level = "debug", skip(self), ret)]
726    fn lower_node_id(&mut self, ast_node_id: NodeId) -> HirId {
727        assert_ne!(ast_node_id, DUMMY_NODE_ID);
728
729        let owner = self.current_hir_id_owner;
730        let local_id = self.item_local_id_counter;
731        assert_ne!(local_id, hir::ItemLocalId::ZERO);
732        self.item_local_id_counter.increment_by(1);
733        let hir_id = HirId { owner, local_id };
734
735        if let Some(def_id) = self.opt_local_def_id(ast_node_id) {
736            self.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id)));
737        }
738
739        if let Some(traits) = self.resolver.trait_map.remove(&ast_node_id) {
740            self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice());
741        }
742
743        // Check whether the same `NodeId` is lowered more than once.
744        #[cfg(debug_assertions)]
745        {
746            let old = self.node_id_to_local_id.insert(ast_node_id, local_id);
747            assert_eq!(old, None);
748        }
749
750        hir_id
751    }
752
753    /// Generate a new `HirId` without a backing `NodeId`.
754    x;#[instrument(level = "debug", skip(self), ret)]
755    fn next_id(&mut self) -> HirId {
756        let owner = self.current_hir_id_owner;
757        let local_id = self.item_local_id_counter;
758        assert_ne!(local_id, hir::ItemLocalId::ZERO);
759        self.item_local_id_counter.increment_by(1);
760        HirId { owner, local_id }
761    }
762
763    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_res",
                                    "rustc_ast_lowering", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(763u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["res"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Res = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let res: Result<Res, ()> =
                res.apply_id(|id|
                        {
                            let owner = self.current_hir_id_owner;
                            let local_id =
                                self.ident_and_label_to_local_id.get(&id).copied().ok_or(())?;
                            Ok(HirId { owner, local_id })
                        });
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:770",
                                    "rustc_ast_lowering", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(770u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["res"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::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(&debug(&res) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            res.unwrap_or(Res::Err)
        }
    }
}#[instrument(level = "trace", skip(self))]
764    fn lower_res(&mut self, res: Res<NodeId>) -> Res {
765        let res: Result<Res, ()> = res.apply_id(|id| {
766            let owner = self.current_hir_id_owner;
767            let local_id = self.ident_and_label_to_local_id.get(&id).copied().ok_or(())?;
768            Ok(HirId { owner, local_id })
769        });
770        trace!(?res);
771
772        // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
773        // This can happen when trying to lower the return type `x` in erroneous code like
774        //   async fn foo(x: u8) -> x {}
775        // In that case, `x` is lowered as a function parameter, and the return type is lowered as
776        // an opaque type as a synthesized HIR owner.
777        res.unwrap_or(Res::Err)
778    }
779
780    fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
781        self.resolver.get_partial_res(id).map_or(Res::Err, |pr| pr.expect_full_res())
782    }
783
784    fn lower_import_res(&mut self, id: NodeId, span: Span) -> PerNS<Option<Res>> {
785        let per_ns = self.resolver.get_import_res(id);
786        let per_ns = per_ns.map(|res| res.map(|res| self.lower_res(res)));
787        if per_ns.is_empty() {
788            // Propagate the error to all namespaces, just to be sure.
789            self.dcx().span_delayed_bug(span, "no resolution for an import");
790            let err = Some(Res::Err);
791            return PerNS { type_ns: err, value_ns: err, macro_ns: err };
792        }
793        per_ns
794    }
795
796    fn make_lang_item_qpath(
797        &mut self,
798        lang_item: hir::LangItem,
799        span: Span,
800        args: Option<&'hir hir::GenericArgs<'hir>>,
801    ) -> hir::QPath<'hir> {
802        hir::QPath::Resolved(None, self.make_lang_item_path(lang_item, span, args))
803    }
804
805    fn make_lang_item_path(
806        &mut self,
807        lang_item: hir::LangItem,
808        span: Span,
809        args: Option<&'hir hir::GenericArgs<'hir>>,
810    ) -> &'hir hir::Path<'hir> {
811        let def_id = self.tcx.require_lang_item(lang_item, span);
812        let def_kind = self.tcx.def_kind(def_id);
813        let res = Res::Def(def_kind, def_id);
814        self.arena.alloc(hir::Path {
815            span,
816            res,
817            segments: self.arena.alloc_from_iter([hir::PathSegment {
818                ident: Ident::new(lang_item.name(), span),
819                hir_id: self.next_id(),
820                res,
821                args,
822                infer_args: args.is_none(),
823            }]),
824        })
825    }
826
827    /// Reuses the span but adds information like the kind of the desugaring and features that are
828    /// allowed inside this span.
829    fn mark_span_with_reason(
830        &self,
831        reason: DesugaringKind,
832        span: Span,
833        allow_internal_unstable: Option<Arc<[Symbol]>>,
834    ) -> Span {
835        self.tcx.with_stable_hashing_context(|hcx| {
836            span.mark_with_reason(allow_internal_unstable, reason, span.edition(), hcx)
837        })
838    }
839
840    fn span_lowerer(&self) -> SpanLowerer {
841        SpanLowerer {
842            is_incremental: self.tcx.sess.opts.incremental.is_some(),
843            def_id: self.current_hir_id_owner.def_id,
844        }
845    }
846
847    /// Intercept all spans entering HIR.
848    /// Mark a span as relative to the current owning item.
849    fn lower_span(&self, span: Span) -> Span {
850        self.span_lowerer().lower(span)
851    }
852
853    fn lower_ident(&self, ident: Ident) -> Ident {
854        Ident::new(ident.name, self.lower_span(ident.span))
855    }
856
857    /// Converts a lifetime into a new generic parameter.
858    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lifetime_res_to_generic_param",
                                    "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(858u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["ident", "node_id",
                                                    "res", "source"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<hir::GenericParam<'hir>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (name, kind) =
                match res {
                    LifetimeRes::Param { .. } => {
                        (hir::ParamName::Plain(ident),
                            hir::LifetimeParamKind::Explicit)
                    }
                    LifetimeRes::Fresh { param, kind, .. } => {
                        let _def_id =
                            self.create_def(param, Some(kw::UnderscoreLifetime),
                                DefKind::LifetimeParam,
                                DefPathData::DesugaredAnonymousLifetime, ident.span);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:879",
                                                "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                                ::tracing_core::__macro_support::Option::Some(879u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                                ::tracing_core::field::FieldSet::new(&["_def_id"],
                                                    ::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(&debug(&_def_id) as
                                                                    &dyn Value))])
                                    });
                            } else { ; }
                        };
                        (hir::ParamName::Fresh,
                            hir::LifetimeParamKind::Elided(kind))
                    }
                    LifetimeRes::Static { .. } | LifetimeRes::Error =>
                        return None,
                    res => {
                        ::core::panicking::panic_fmt(format_args!("Unexpected lifetime resolution {0:?} for {1:?} at {2:?}",
                                res, ident, ident.span));
                    }
                };
            let hir_id = self.lower_node_id(node_id);
            let def_id = self.local_def_id(node_id);
            Some(hir::GenericParam {
                    hir_id,
                    def_id,
                    name,
                    span: self.lower_span(ident.span),
                    pure_wrt_drop: false,
                    kind: hir::GenericParamKind::Lifetime { kind },
                    colon_span: None,
                    source,
                })
        }
    }
}#[instrument(level = "debug", skip(self))]
859    fn lifetime_res_to_generic_param(
860        &mut self,
861        ident: Ident,
862        node_id: NodeId,
863        res: LifetimeRes,
864        source: hir::GenericParamSource,
865    ) -> Option<hir::GenericParam<'hir>> {
866        let (name, kind) = match res {
867            LifetimeRes::Param { .. } => {
868                (hir::ParamName::Plain(ident), hir::LifetimeParamKind::Explicit)
869            }
870            LifetimeRes::Fresh { param, kind, .. } => {
871                // Late resolution delegates to us the creation of the `LocalDefId`.
872                let _def_id = self.create_def(
873                    param,
874                    Some(kw::UnderscoreLifetime),
875                    DefKind::LifetimeParam,
876                    DefPathData::DesugaredAnonymousLifetime,
877                    ident.span,
878                );
879                debug!(?_def_id);
880
881                (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided(kind))
882            }
883            LifetimeRes::Static { .. } | LifetimeRes::Error => return None,
884            res => panic!(
885                "Unexpected lifetime resolution {:?} for {:?} at {:?}",
886                res, ident, ident.span
887            ),
888        };
889        let hir_id = self.lower_node_id(node_id);
890        let def_id = self.local_def_id(node_id);
891        Some(hir::GenericParam {
892            hir_id,
893            def_id,
894            name,
895            span: self.lower_span(ident.span),
896            pure_wrt_drop: false,
897            kind: hir::GenericParamKind::Lifetime { kind },
898            colon_span: None,
899            source,
900        })
901    }
902
903    /// Lowers a lifetime binder that defines `generic_params`, returning the corresponding HIR
904    /// nodes. The returned list includes any "extra" lifetime parameters that were added by the
905    /// name resolver owing to lifetime elision; this also populates the resolver's node-id->def-id
906    /// map, so that later calls to `opt_node_id_to_def_id` that refer to these extra lifetime
907    /// parameters will be successful.
908    x;#[instrument(level = "debug", skip(self), ret)]
909    #[inline]
910    fn lower_lifetime_binder(
911        &mut self,
912        binder: NodeId,
913        generic_params: &[GenericParam],
914    ) -> &'hir [hir::GenericParam<'hir>] {
915        // Start by creating params for extra lifetimes params, as this creates the definitions
916        // that may be referred to by the AST inside `generic_params`.
917        let extra_lifetimes = self.resolver.extra_lifetime_params(binder);
918        debug!(?extra_lifetimes);
919        let extra_lifetimes: Vec<_> = extra_lifetimes
920            .into_iter()
921            .filter_map(|(ident, node_id, res)| {
922                self.lifetime_res_to_generic_param(
923                    ident,
924                    node_id,
925                    res,
926                    hir::GenericParamSource::Binder,
927                )
928            })
929            .collect();
930        let arena = self.arena;
931        let explicit_generic_params =
932            self.lower_generic_params_mut(generic_params, hir::GenericParamSource::Binder);
933        arena.alloc_from_iter(explicit_generic_params.chain(extra_lifetimes.into_iter()))
934    }
935
936    fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
937        let was_in_dyn_type = self.is_in_dyn_type;
938        self.is_in_dyn_type = in_scope;
939
940        let result = f(self);
941
942        self.is_in_dyn_type = was_in_dyn_type;
943
944        result
945    }
946
947    fn with_new_scopes<T>(&mut self, scope_span: Span, f: impl FnOnce(&mut Self) -> T) -> T {
948        let current_item = self.current_item;
949        self.current_item = Some(scope_span);
950
951        let was_in_loop_condition = self.is_in_loop_condition;
952        self.is_in_loop_condition = false;
953
954        let old_contract = self.contract_ensures.take();
955
956        let try_block_scope = mem::replace(&mut self.try_block_scope, TryBlockScope::Function);
957        let loop_scope = self.loop_scope.take();
958        let ret = f(self);
959        self.try_block_scope = try_block_scope;
960        self.loop_scope = loop_scope;
961
962        self.contract_ensures = old_contract;
963
964        self.is_in_loop_condition = was_in_loop_condition;
965
966        self.current_item = current_item;
967
968        ret
969    }
970
971    fn lower_attrs(
972        &mut self,
973        id: HirId,
974        attrs: &[Attribute],
975        target_span: Span,
976        target: Target,
977    ) -> &'hir [hir::Attribute] {
978        self.lower_attrs_with_extra(id, attrs, target_span, target, &[])
979    }
980
981    fn lower_attrs_with_extra(
982        &mut self,
983        id: HirId,
984        attrs: &[Attribute],
985        target_span: Span,
986        target: Target,
987        extra_hir_attributes: &[hir::Attribute],
988    ) -> &'hir [hir::Attribute] {
989        if attrs.is_empty() && extra_hir_attributes.is_empty() {
990            &[]
991        } else {
992            let mut lowered_attrs =
993                self.lower_attrs_vec(attrs, self.lower_span(target_span), id, target);
994            lowered_attrs.extend(extra_hir_attributes.iter().cloned());
995
996            match (&id.owner, &self.current_hir_id_owner) {
    (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);
        }
    }
};assert_eq!(id.owner, self.current_hir_id_owner);
997            let ret = self.arena.alloc_from_iter(lowered_attrs);
998
999            // this is possible if an item contained syntactical attribute,
1000            // but none of them parse successfully or all of them were ignored
1001            // for not being built-in attributes at all. They could be remaining
1002            // unexpanded attributes used as markers in proc-macro derives for example.
1003            // This will have emitted some diagnostics for the misparse, but will then
1004            // not emit the attribute making the list empty.
1005            if ret.is_empty() {
1006                &[]
1007            } else {
1008                self.attrs.insert(id.local_id, ret);
1009                ret
1010            }
1011        }
1012    }
1013
1014    fn lower_attrs_vec(
1015        &mut self,
1016        attrs: &[Attribute],
1017        target_span: Span,
1018        target_hir_id: HirId,
1019        target: Target,
1020    ) -> Vec<hir::Attribute> {
1021        let l = self.span_lowerer();
1022        self.attribute_parser.parse_attribute_list(
1023            attrs,
1024            target_span,
1025            target,
1026            OmitDoc::Lower,
1027            |s| l.lower(s),
1028            |lint_id, span, kind| {
1029                self.delayed_lints.push(DelayedLint::AttributeParsing(AttributeLint {
1030                    lint_id,
1031                    id: target_hir_id,
1032                    span,
1033                    kind,
1034                }));
1035            },
1036        )
1037    }
1038
1039    fn alias_attrs(&mut self, id: HirId, target_id: HirId) {
1040        match (&id.owner, &self.current_hir_id_owner) {
    (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);
        }
    }
};assert_eq!(id.owner, self.current_hir_id_owner);
1041        match (&target_id.owner, &self.current_hir_id_owner) {
    (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);
        }
    }
};assert_eq!(target_id.owner, self.current_hir_id_owner);
1042        if let Some(&a) = self.attrs.get(&target_id.local_id) {
1043            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
1044            self.attrs.insert(id.local_id, a);
1045        }
1046    }
1047
1048    fn lower_delim_args(&self, args: &DelimArgs) -> DelimArgs {
1049        args.clone()
1050    }
1051
1052    /// Lower an associated item constraint.
1053    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_assoc_item_constraint",
                                    "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1053u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::AssocItemConstraint<'hir> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:1059",
                                    "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1059u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["constraint",
                                                    "itctx"],
                                        ::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(&debug(&constraint)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&itctx) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            let gen_args =
                if let Some(gen_args) = &constraint.gen_args {
                    let gen_args_ctor =
                        match gen_args {
                            GenericArgs::AngleBracketed(data) => {
                                self.lower_angle_bracketed_parameter_data(data,
                                        ParamMode::Explicit, itctx).0
                            }
                            GenericArgs::Parenthesized(data) => {
                                if let Some(first_char) =
                                            constraint.ident.as_str().chars().next() &&
                                        first_char.is_ascii_lowercase() {
                                    let err =
                                        match (&data.inputs[..], &data.output) {
                                            ([_, ..], FnRetTy::Default(_)) => {
                                                errors::BadReturnTypeNotation::Inputs {
                                                    span: data.inputs_span,
                                                }
                                            }
                                            ([], FnRetTy::Default(_)) => {
                                                errors::BadReturnTypeNotation::NeedsDots {
                                                    span: data.inputs_span,
                                                }
                                            }
                                            (_, FnRetTy::Ty(ty)) => {
                                                let span = data.inputs_span.shrink_to_hi().to(ty.span);
                                                errors::BadReturnTypeNotation::Output {
                                                    span,
                                                    suggestion: errors::RTNSuggestion {
                                                        output: span,
                                                        input: data.inputs_span,
                                                    },
                                                }
                                            }
                                        };
                                    let mut err = self.dcx().create_err(err);
                                    if !self.tcx.features().return_type_notation() &&
                                            self.tcx.sess.is_nightly_build() {
                                        add_feature_diagnostics(&mut err, &self.tcx.sess,
                                            sym::return_type_notation);
                                    }
                                    err.emit();
                                    GenericArgsCtor {
                                        args: Default::default(),
                                        constraints: &[],
                                        parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
                                        span: data.span,
                                    }
                                } else {
                                    self.emit_bad_parenthesized_trait_in_assoc_ty(data);
                                    self.lower_angle_bracketed_parameter_data(&data.as_angle_bracketed_args(),
                                            ParamMode::Explicit, itctx).0
                                }
                            }
                            GenericArgs::ParenthesizedElided(span) =>
                                GenericArgsCtor {
                                    args: Default::default(),
                                    constraints: &[],
                                    parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
                                    span: *span,
                                },
                        };
                    gen_args_ctor.into_generic_args(self)
                } else { self.arena.alloc(hir::GenericArgs::none()) };
            let kind =
                match &constraint.kind {
                    AssocItemConstraintKind::Equality { term } => {
                        let term =
                            match term {
                                Term::Ty(ty) => self.lower_ty_alloc(ty, itctx).into(),
                                Term::Const(c) =>
                                    self.lower_anon_const_to_const_arg_and_alloc(c).into(),
                            };
                        hir::AssocItemConstraintKind::Equality { term }
                    }
                    AssocItemConstraintKind::Bound { bounds } => {
                        if self.is_in_dyn_type {
                            let suggestion =
                                match itctx {
                                    ImplTraitContext::OpaqueTy { .. } |
                                        ImplTraitContext::Universal => {
                                        let bound_end_span =
                                            constraint.gen_args.as_ref().map_or(constraint.ident.span,
                                                |args| args.span());
                                        if bound_end_span.eq_ctxt(constraint.span) {
                                            Some(self.tcx.sess.source_map().next_point(bound_end_span))
                                        } else { None }
                                    }
                                    _ => None,
                                };
                            let guar =
                                self.dcx().emit_err(errors::MisplacedAssocTyBinding {
                                        span: constraint.span,
                                        suggestion,
                                    });
                            let err_ty =
                                &*self.arena.alloc(self.ty(constraint.span,
                                                hir::TyKind::Err(guar)));
                            hir::AssocItemConstraintKind::Equality {
                                term: err_ty.into(),
                            }
                        } else {
                            let bounds =
                                self.lower_param_bounds(bounds,
                                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::AssocTyBounds),
                                    itctx);
                            hir::AssocItemConstraintKind::Bound { bounds }
                        }
                    }
                };
            hir::AssocItemConstraint {
                hir_id: self.lower_node_id(constraint.id),
                ident: self.lower_ident(constraint.ident),
                gen_args,
                kind,
                span: self.lower_span(constraint.span),
            }
        }
    }
}#[instrument(level = "debug", skip_all)]
1054    fn lower_assoc_item_constraint(
1055        &mut self,
1056        constraint: &AssocItemConstraint,
1057        itctx: ImplTraitContext,
1058    ) -> hir::AssocItemConstraint<'hir> {
1059        debug!(?constraint, ?itctx);
1060        // Lower the generic arguments for the associated item.
1061        let gen_args = if let Some(gen_args) = &constraint.gen_args {
1062            let gen_args_ctor = match gen_args {
1063                GenericArgs::AngleBracketed(data) => {
1064                    self.lower_angle_bracketed_parameter_data(data, ParamMode::Explicit, itctx).0
1065                }
1066                GenericArgs::Parenthesized(data) => {
1067                    if let Some(first_char) = constraint.ident.as_str().chars().next()
1068                        && first_char.is_ascii_lowercase()
1069                    {
1070                        let err = match (&data.inputs[..], &data.output) {
1071                            ([_, ..], FnRetTy::Default(_)) => {
1072                                errors::BadReturnTypeNotation::Inputs { span: data.inputs_span }
1073                            }
1074                            ([], FnRetTy::Default(_)) => {
1075                                errors::BadReturnTypeNotation::NeedsDots { span: data.inputs_span }
1076                            }
1077                            // The case `T: Trait<method(..) -> Ret>` is handled in the parser.
1078                            (_, FnRetTy::Ty(ty)) => {
1079                                let span = data.inputs_span.shrink_to_hi().to(ty.span);
1080                                errors::BadReturnTypeNotation::Output {
1081                                    span,
1082                                    suggestion: errors::RTNSuggestion {
1083                                        output: span,
1084                                        input: data.inputs_span,
1085                                    },
1086                                }
1087                            }
1088                        };
1089                        let mut err = self.dcx().create_err(err);
1090                        if !self.tcx.features().return_type_notation()
1091                            && self.tcx.sess.is_nightly_build()
1092                        {
1093                            add_feature_diagnostics(
1094                                &mut err,
1095                                &self.tcx.sess,
1096                                sym::return_type_notation,
1097                            );
1098                        }
1099                        err.emit();
1100                        GenericArgsCtor {
1101                            args: Default::default(),
1102                            constraints: &[],
1103                            parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
1104                            span: data.span,
1105                        }
1106                    } else {
1107                        self.emit_bad_parenthesized_trait_in_assoc_ty(data);
1108                        // FIXME(return_type_notation): we could issue a feature error
1109                        // if the parens are empty and there's no return type.
1110                        self.lower_angle_bracketed_parameter_data(
1111                            &data.as_angle_bracketed_args(),
1112                            ParamMode::Explicit,
1113                            itctx,
1114                        )
1115                        .0
1116                    }
1117                }
1118                GenericArgs::ParenthesizedElided(span) => GenericArgsCtor {
1119                    args: Default::default(),
1120                    constraints: &[],
1121                    parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
1122                    span: *span,
1123                },
1124            };
1125            gen_args_ctor.into_generic_args(self)
1126        } else {
1127            self.arena.alloc(hir::GenericArgs::none())
1128        };
1129        let kind = match &constraint.kind {
1130            AssocItemConstraintKind::Equality { term } => {
1131                let term = match term {
1132                    Term::Ty(ty) => self.lower_ty_alloc(ty, itctx).into(),
1133                    Term::Const(c) => self.lower_anon_const_to_const_arg_and_alloc(c).into(),
1134                };
1135                hir::AssocItemConstraintKind::Equality { term }
1136            }
1137            AssocItemConstraintKind::Bound { bounds } => {
1138                // Disallow ATB in dyn types
1139                if self.is_in_dyn_type {
1140                    let suggestion = match itctx {
1141                        ImplTraitContext::OpaqueTy { .. } | ImplTraitContext::Universal => {
1142                            let bound_end_span = constraint
1143                                .gen_args
1144                                .as_ref()
1145                                .map_or(constraint.ident.span, |args| args.span());
1146                            if bound_end_span.eq_ctxt(constraint.span) {
1147                                Some(self.tcx.sess.source_map().next_point(bound_end_span))
1148                            } else {
1149                                None
1150                            }
1151                        }
1152                        _ => None,
1153                    };
1154
1155                    let guar = self.dcx().emit_err(errors::MisplacedAssocTyBinding {
1156                        span: constraint.span,
1157                        suggestion,
1158                    });
1159                    let err_ty =
1160                        &*self.arena.alloc(self.ty(constraint.span, hir::TyKind::Err(guar)));
1161                    hir::AssocItemConstraintKind::Equality { term: err_ty.into() }
1162                } else {
1163                    let bounds = self.lower_param_bounds(
1164                        bounds,
1165                        RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::AssocTyBounds),
1166                        itctx,
1167                    );
1168                    hir::AssocItemConstraintKind::Bound { bounds }
1169                }
1170            }
1171        };
1172
1173        hir::AssocItemConstraint {
1174            hir_id: self.lower_node_id(constraint.id),
1175            ident: self.lower_ident(constraint.ident),
1176            gen_args,
1177            kind,
1178            span: self.lower_span(constraint.span),
1179        }
1180    }
1181
1182    fn emit_bad_parenthesized_trait_in_assoc_ty(&self, data: &ParenthesizedArgs) {
1183        // Suggest removing empty parentheses: "Trait()" -> "Trait"
1184        let sub = if data.inputs.is_empty() {
1185            let parentheses_span =
1186                data.inputs_span.shrink_to_lo().to(data.inputs_span.shrink_to_hi());
1187            AssocTyParenthesesSub::Empty { parentheses_span }
1188        }
1189        // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
1190        else {
1191            // Start of parameters to the 1st argument
1192            let open_param = data.inputs_span.shrink_to_lo().to(data
1193                .inputs
1194                .first()
1195                .unwrap()
1196                .span
1197                .shrink_to_lo());
1198            // End of last argument to end of parameters
1199            let close_param =
1200                data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi());
1201            AssocTyParenthesesSub::NotEmpty { open_param, close_param }
1202        };
1203        self.dcx().emit_err(AssocTyParentheses { span: data.span, sub });
1204    }
1205
1206    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_generic_arg",
                                    "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1206u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["arg", "itctx"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arg)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::GenericArg<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match arg {
                ast::GenericArg::Lifetime(lt) =>
                    GenericArg::Lifetime(self.lower_lifetime(lt,
                            LifetimeSource::Path {
                                angle_brackets: hir::AngleBrackets::Full,
                            }, lt.ident.into())),
                ast::GenericArg::Type(ty) => {
                    if ty.is_maybe_parenthesised_infer() {
                        return GenericArg::Infer(hir::InferArg {
                                    hir_id: self.lower_node_id(ty.id),
                                    span: self.lower_span(ty.span),
                                });
                    }
                    match &ty.kind {
                        TyKind::Path(None, path) => {
                            if let Some(res) =
                                    self.resolver.get_partial_res(ty.id).and_then(|partial_res|
                                            partial_res.full_res()) {
                                if !res.matches_ns(Namespace::TypeNS) &&
                                        path.is_potential_trivial_const_arg() {
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:1244",
                                                            "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(1244u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                                            ::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!("lower_generic_arg: Lowering type argument as const argument: {0:?}",
                                                                                        ty) as &dyn Value))])
                                                });
                                        } else { ; }
                                    };
                                    let ct =
                                        self.lower_const_path_to_const_arg(path, res, ty.id,
                                            ty.span);
                                    return GenericArg::Const(ct.try_as_ambig_ct().unwrap());
                                }
                            }
                        }
                        _ => {}
                    }
                    GenericArg::Type(self.lower_ty_alloc(ty,
                                    itctx).try_as_ambig_ty().unwrap())
                }
                ast::GenericArg::Const(ct) =>
                    GenericArg::Const(self.lower_anon_const_to_const_arg_and_alloc(ct).try_as_ambig_ct().unwrap()),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1207    fn lower_generic_arg(
1208        &mut self,
1209        arg: &ast::GenericArg,
1210        itctx: ImplTraitContext,
1211    ) -> hir::GenericArg<'hir> {
1212        match arg {
1213            ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(
1214                lt,
1215                LifetimeSource::Path { angle_brackets: hir::AngleBrackets::Full },
1216                lt.ident.into(),
1217            )),
1218            ast::GenericArg::Type(ty) => {
1219                // We cannot just match on `TyKind::Infer` as `(_)` is represented as
1220                // `TyKind::Paren(TyKind::Infer)` and should also be lowered to `GenericArg::Infer`
1221                if ty.is_maybe_parenthesised_infer() {
1222                    return GenericArg::Infer(hir::InferArg {
1223                        hir_id: self.lower_node_id(ty.id),
1224                        span: self.lower_span(ty.span),
1225                    });
1226                }
1227
1228                match &ty.kind {
1229                    // We parse const arguments as path types as we cannot distinguish them during
1230                    // parsing. We try to resolve that ambiguity by attempting resolution in both the
1231                    // type and value namespaces. If we resolved the path in the value namespace, we
1232                    // transform it into a generic const argument.
1233                    //
1234                    // FIXME: Should we be handling `(PATH_TO_CONST)`?
1235                    TyKind::Path(None, path) => {
1236                        if let Some(res) = self
1237                            .resolver
1238                            .get_partial_res(ty.id)
1239                            .and_then(|partial_res| partial_res.full_res())
1240                        {
1241                            if !res.matches_ns(Namespace::TypeNS)
1242                                && path.is_potential_trivial_const_arg()
1243                            {
1244                                debug!(
1245                                    "lower_generic_arg: Lowering type argument as const argument: {:?}",
1246                                    ty,
1247                                );
1248
1249                                let ct =
1250                                    self.lower_const_path_to_const_arg(path, res, ty.id, ty.span);
1251                                return GenericArg::Const(ct.try_as_ambig_ct().unwrap());
1252                            }
1253                        }
1254                    }
1255                    _ => {}
1256                }
1257                GenericArg::Type(self.lower_ty_alloc(ty, itctx).try_as_ambig_ty().unwrap())
1258            }
1259            ast::GenericArg::Const(ct) => GenericArg::Const(
1260                self.lower_anon_const_to_const_arg_and_alloc(ct).try_as_ambig_ct().unwrap(),
1261            ),
1262        }
1263    }
1264
1265    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_ty_alloc",
                                    "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1265u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["t", "itctx"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&t)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'hir hir::Ty<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        { self.arena.alloc(self.lower_ty(t, itctx)) }
    }
}#[instrument(level = "debug", skip(self))]
1266    fn lower_ty_alloc(&mut self, t: &Ty, itctx: ImplTraitContext) -> &'hir hir::Ty<'hir> {
1267        self.arena.alloc(self.lower_ty(t, itctx))
1268    }
1269
1270    fn lower_path_ty(
1271        &mut self,
1272        t: &Ty,
1273        qself: &Option<Box<QSelf>>,
1274        path: &Path,
1275        param_mode: ParamMode,
1276        itctx: ImplTraitContext,
1277    ) -> hir::Ty<'hir> {
1278        // Check whether we should interpret this as a bare trait object.
1279        // This check mirrors the one in late resolution. We only introduce this special case in
1280        // the rare occurrence we need to lower `Fresh` anonymous lifetimes.
1281        // The other cases when a qpath should be opportunistically made a trait object are handled
1282        // by `ty_path`.
1283        if qself.is_none()
1284            && let Some(partial_res) = self.resolver.get_partial_res(t.id)
1285            && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res()
1286        {
1287            let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1288                let bound = this.lower_poly_trait_ref(
1289                    &PolyTraitRef {
1290                        bound_generic_params: ThinVec::new(),
1291                        modifiers: TraitBoundModifiers::NONE,
1292                        trait_ref: TraitRef { path: path.clone(), ref_id: t.id },
1293                        span: t.span,
1294                        parens: ast::Parens::No,
1295                    },
1296                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitObjectTy),
1297                    itctx,
1298                );
1299                let bounds = this.arena.alloc_from_iter([bound]);
1300                let lifetime_bound = this.elided_dyn_bound(t.span);
1301                (bounds, lifetime_bound)
1302            });
1303            let kind = hir::TyKind::TraitObject(
1304                bounds,
1305                TaggedRef::new(lifetime_bound, TraitObjectSyntax::None),
1306            );
1307            return hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.next_id() };
1308        }
1309
1310        let id = self.lower_node_id(t.id);
1311        let qpath = self.lower_qpath(
1312            t.id,
1313            qself,
1314            path,
1315            param_mode,
1316            AllowReturnTypeNotation::Yes,
1317            itctx,
1318            None,
1319        );
1320        self.ty_path(id, t.span, qpath)
1321    }
1322
1323    fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1324        hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1325    }
1326
1327    fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1328        self.ty(span, hir::TyKind::Tup(tys))
1329    }
1330
1331    fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> hir::Ty<'hir> {
1332        let kind = match &t.kind {
1333            TyKind::Infer => hir::TyKind::Infer(()),
1334            TyKind::Err(guar) => hir::TyKind::Err(*guar),
1335            TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty_alloc(ty, itctx)),
1336            TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1337            TyKind::Ref(region, mt) => {
1338                let lifetime = self.lower_ty_direct_lifetime(t, *region);
1339                hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx))
1340            }
1341            TyKind::PinnedRef(region, mt) => {
1342                let lifetime = self.lower_ty_direct_lifetime(t, *region);
1343                let kind = hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx));
1344                let span = self.lower_span(t.span);
1345                let arg = hir::Ty { kind, span, hir_id: self.next_id() };
1346                let args = self.arena.alloc(hir::GenericArgs {
1347                    args: self.arena.alloc([hir::GenericArg::Type(self.arena.alloc(arg))]),
1348                    constraints: &[],
1349                    parenthesized: hir::GenericArgsParentheses::No,
1350                    span_ext: span,
1351                });
1352                let path = self.make_lang_item_qpath(hir::LangItem::Pin, span, Some(args));
1353                hir::TyKind::Path(path)
1354            }
1355            TyKind::FnPtr(f) => {
1356                let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1357                hir::TyKind::FnPtr(self.arena.alloc(hir::FnPtrTy {
1358                    generic_params,
1359                    safety: self.lower_safety(f.safety, hir::Safety::Safe),
1360                    abi: self.lower_extern(f.ext),
1361                    decl: self.lower_fn_decl(&f.decl, t.id, t.span, FnDeclKind::Pointer, None),
1362                    param_idents: self.lower_fn_params_to_idents(&f.decl),
1363                }))
1364            }
1365            TyKind::UnsafeBinder(f) => {
1366                let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1367                hir::TyKind::UnsafeBinder(self.arena.alloc(hir::UnsafeBinderTy {
1368                    generic_params,
1369                    inner_ty: self.lower_ty_alloc(&f.inner_ty, itctx),
1370                }))
1371            }
1372            TyKind::Never => hir::TyKind::Never,
1373            TyKind::Tup(tys) => hir::TyKind::Tup(
1374                self.arena.alloc_from_iter(tys.iter().map(|ty| self.lower_ty(ty, itctx))),
1375            ),
1376            TyKind::Paren(ty) => {
1377                return self.lower_ty(ty, itctx);
1378            }
1379            TyKind::Path(qself, path) => {
1380                return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1381            }
1382            TyKind::ImplicitSelf => {
1383                let hir_id = self.next_id();
1384                let res = self.expect_full_res(t.id);
1385                let res = self.lower_res(res);
1386                hir::TyKind::Path(hir::QPath::Resolved(
1387                    None,
1388                    self.arena.alloc(hir::Path {
1389                        res,
1390                        segments: self.arena.alloc_from_iter([hir::PathSegment::new(Ident::with_dummy_span(kw::SelfUpper),
                hir_id, res)])arena_vec![self; hir::PathSegment::new(
1391                            Ident::with_dummy_span(kw::SelfUpper),
1392                            hir_id,
1393                            res
1394                        )],
1395                        span: self.lower_span(t.span),
1396                    }),
1397                ))
1398            }
1399            TyKind::Array(ty, length) => hir::TyKind::Array(
1400                self.lower_ty_alloc(ty, itctx),
1401                self.lower_array_length_to_const_arg(length),
1402            ),
1403            TyKind::TraitObject(bounds, kind) => {
1404                let mut lifetime_bound = None;
1405                let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1406                    let bounds =
1407                        this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| match bound {
1408                            // We can safely ignore constness here since AST validation
1409                            // takes care of rejecting invalid modifier combinations and
1410                            // const trait bounds in trait object types.
1411                            GenericBound::Trait(ty) => {
1412                                let trait_ref = this.lower_poly_trait_ref(
1413                                    ty,
1414                                    RelaxedBoundPolicy::Forbidden(
1415                                        RelaxedBoundForbiddenReason::TraitObjectTy,
1416                                    ),
1417                                    itctx,
1418                                );
1419                                Some(trait_ref)
1420                            }
1421                            GenericBound::Outlives(lifetime) => {
1422                                if lifetime_bound.is_none() {
1423                                    lifetime_bound = Some(this.lower_lifetime(
1424                                        lifetime,
1425                                        LifetimeSource::Other,
1426                                        lifetime.ident.into(),
1427                                    ));
1428                                }
1429                                None
1430                            }
1431                            // Ignore `use` syntax since that is not valid in objects.
1432                            GenericBound::Use(_, span) => {
1433                                this.dcx()
1434                                    .span_delayed_bug(*span, "use<> not allowed in dyn types");
1435                                None
1436                            }
1437                        }));
1438                    let lifetime_bound =
1439                        lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1440                    (bounds, lifetime_bound)
1441                });
1442                hir::TyKind::TraitObject(bounds, TaggedRef::new(lifetime_bound, *kind))
1443            }
1444            TyKind::ImplTrait(def_node_id, bounds) => {
1445                let span = t.span;
1446                match itctx {
1447                    ImplTraitContext::OpaqueTy { origin } => {
1448                        self.lower_opaque_impl_trait(span, origin, *def_node_id, bounds, itctx)
1449                    }
1450                    ImplTraitContext::Universal => {
1451                        if let Some(span) = bounds.iter().find_map(|bound| match *bound {
1452                            ast::GenericBound::Use(_, span) => Some(span),
1453                            _ => None,
1454                        }) {
1455                            self.tcx.dcx().emit_err(errors::NoPreciseCapturesOnApit { span });
1456                        }
1457
1458                        let def_id = self.local_def_id(*def_node_id);
1459                        let name = self.tcx.item_name(def_id.to_def_id());
1460                        let ident = Ident::new(name, span);
1461                        let (param, bounds, path) = self.lower_universal_param_and_bounds(
1462                            *def_node_id,
1463                            span,
1464                            ident,
1465                            bounds,
1466                        );
1467                        self.impl_trait_defs.push(param);
1468                        if let Some(bounds) = bounds {
1469                            self.impl_trait_bounds.push(bounds);
1470                        }
1471                        path
1472                    }
1473                    ImplTraitContext::InBinding => hir::TyKind::TraitAscription(
1474                        self.lower_param_bounds(bounds, RelaxedBoundPolicy::Allowed, itctx),
1475                    ),
1476                    ImplTraitContext::FeatureGated(position, feature) => {
1477                        let guar = self
1478                            .tcx
1479                            .sess
1480                            .create_feature_err(
1481                                MisplacedImplTrait {
1482                                    span: t.span,
1483                                    position: DiagArgFromDisplay(&position),
1484                                },
1485                                feature,
1486                            )
1487                            .emit();
1488                        hir::TyKind::Err(guar)
1489                    }
1490                    ImplTraitContext::Disallowed(position) => {
1491                        let guar = self.dcx().emit_err(MisplacedImplTrait {
1492                            span: t.span,
1493                            position: DiagArgFromDisplay(&position),
1494                        });
1495                        hir::TyKind::Err(guar)
1496                    }
1497                }
1498            }
1499            TyKind::Pat(ty, pat) => {
1500                hir::TyKind::Pat(self.lower_ty_alloc(ty, itctx), self.lower_ty_pat(pat, ty.span))
1501            }
1502            TyKind::MacCall(_) => {
1503                ::rustc_middle::util::bug::span_bug_fmt(t.span,
    format_args!("`TyKind::MacCall` should have been expanded by now"))span_bug!(t.span, "`TyKind::MacCall` should have been expanded by now")
1504            }
1505            TyKind::CVarArgs => {
1506                let guar = self.dcx().span_delayed_bug(
1507                    t.span,
1508                    "`TyKind::CVarArgs` should have been handled elsewhere",
1509                );
1510                hir::TyKind::Err(guar)
1511            }
1512            TyKind::Dummy => {
    ::core::panicking::panic_fmt(format_args!("`TyKind::Dummy` should never be lowered"));
}panic!("`TyKind::Dummy` should never be lowered"),
1513        };
1514
1515        hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1516    }
1517
1518    fn lower_ty_direct_lifetime(
1519        &mut self,
1520        t: &Ty,
1521        region: Option<Lifetime>,
1522    ) -> &'hir hir::Lifetime {
1523        let (region, syntax) = match region {
1524            Some(region) => (region, region.ident.into()),
1525
1526            None => {
1527                let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1528                    self.resolver.get_lifetime_res(t.id)
1529                {
1530                    match (&start.plus(1), &end) {
    (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);
        }
    }
};assert_eq!(start.plus(1), end);
1531                    start
1532                } else {
1533                    self.next_node_id()
1534                };
1535                let span = self.tcx.sess.source_map().start_point(t.span).shrink_to_hi();
1536                let region = Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id };
1537                (region, LifetimeSyntax::Implicit)
1538            }
1539        };
1540        self.lower_lifetime(&region, LifetimeSource::Reference, syntax)
1541    }
1542
1543    /// Lowers a `ReturnPositionOpaqueTy` (`-> impl Trait`) or a `TypeAliasesOpaqueTy` (`type F =
1544    /// impl Trait`): this creates the associated Opaque Type (TAIT) definition and then returns a
1545    /// HIR type that references the TAIT.
1546    ///
1547    /// Given a function definition like:
1548    ///
1549    /// ```rust
1550    /// use std::fmt::Debug;
1551    ///
1552    /// fn test<'a, T: Debug>(x: &'a T) -> impl Debug + 'a {
1553    ///     x
1554    /// }
1555    /// ```
1556    ///
1557    /// we will create a TAIT definition in the HIR like
1558    ///
1559    /// ```rust,ignore (pseudo-Rust)
1560    /// type TestReturn<'a, T, 'x> = impl Debug + 'x
1561    /// ```
1562    ///
1563    /// and return a type like `TestReturn<'static, T, 'a>`, so that the function looks like:
1564    ///
1565    /// ```rust,ignore (pseudo-Rust)
1566    /// fn test<'a, T: Debug>(x: &'a T) -> TestReturn<'static, T, 'a>
1567    /// ```
1568    ///
1569    /// Note the subtlety around type parameters! The new TAIT, `TestReturn`, inherits all the
1570    /// type parameters from the function `test` (this is implemented in the query layer, they aren't
1571    /// added explicitly in the HIR). But this includes all the lifetimes, and we only want to
1572    /// capture the lifetimes that are referenced in the bounds. Therefore, we add *extra* lifetime parameters
1573    /// for the lifetimes that get captured (`'x`, in our example above) and reference those.
1574    x;#[instrument(level = "debug", skip(self), ret)]
1575    fn lower_opaque_impl_trait(
1576        &mut self,
1577        span: Span,
1578        origin: hir::OpaqueTyOrigin<LocalDefId>,
1579        opaque_ty_node_id: NodeId,
1580        bounds: &GenericBounds,
1581        itctx: ImplTraitContext,
1582    ) -> hir::TyKind<'hir> {
1583        // Make sure we know that some funky desugaring has been going on here.
1584        // This is a first: there is code in other places like for loop
1585        // desugaring that explicitly states that we don't want to track that.
1586        // Not tracking it makes lints in rustc and clippy very fragile, as
1587        // frequently opened issues show.
1588        let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1589
1590        self.lower_opaque_inner(opaque_ty_node_id, origin, opaque_ty_span, |this| {
1591            this.lower_param_bounds(bounds, RelaxedBoundPolicy::Allowed, itctx)
1592        })
1593    }
1594
1595    fn lower_opaque_inner(
1596        &mut self,
1597        opaque_ty_node_id: NodeId,
1598        origin: hir::OpaqueTyOrigin<LocalDefId>,
1599        opaque_ty_span: Span,
1600        lower_item_bounds: impl FnOnce(&mut Self) -> &'hir [hir::GenericBound<'hir>],
1601    ) -> hir::TyKind<'hir> {
1602        let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id);
1603        let opaque_ty_hir_id = self.lower_node_id(opaque_ty_node_id);
1604        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:1604",
                        "rustc_ast_lowering", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1604u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                        ::tracing_core::field::FieldSet::new(&["opaque_ty_def_id",
                                        "opaque_ty_hir_id"],
                            ::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(&debug(&opaque_ty_def_id)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&opaque_ty_hir_id)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?opaque_ty_def_id, ?opaque_ty_hir_id);
1605
1606        let bounds = lower_item_bounds(self);
1607        let opaque_ty_def = hir::OpaqueTy {
1608            hir_id: opaque_ty_hir_id,
1609            def_id: opaque_ty_def_id,
1610            bounds,
1611            origin,
1612            span: self.lower_span(opaque_ty_span),
1613        };
1614        let opaque_ty_def = self.arena.alloc(opaque_ty_def);
1615
1616        hir::TyKind::OpaqueDef(opaque_ty_def)
1617    }
1618
1619    fn lower_precise_capturing_args(
1620        &mut self,
1621        precise_capturing_args: &[PreciseCapturingArg],
1622    ) -> &'hir [hir::PreciseCapturingArg<'hir>] {
1623        self.arena.alloc_from_iter(precise_capturing_args.iter().map(|arg| match arg {
1624            PreciseCapturingArg::Lifetime(lt) => hir::PreciseCapturingArg::Lifetime(
1625                self.lower_lifetime(lt, LifetimeSource::PreciseCapturing, lt.ident.into()),
1626            ),
1627            PreciseCapturingArg::Arg(path, id) => {
1628                let [segment] = path.segments.as_slice() else {
1629                    ::core::panicking::panic("explicit panic");panic!();
1630                };
1631                let res = self.resolver.get_partial_res(*id).map_or(Res::Err, |partial_res| {
1632                    partial_res.full_res().expect("no partial res expected for precise capture arg")
1633                });
1634                hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
1635                    hir_id: self.lower_node_id(*id),
1636                    ident: self.lower_ident(segment.ident),
1637                    res: self.lower_res(res),
1638                })
1639            }
1640        }))
1641    }
1642
1643    fn lower_fn_params_to_idents(&mut self, decl: &FnDecl) -> &'hir [Option<Ident>] {
1644        self.arena.alloc_from_iter(decl.inputs.iter().map(|param| match param.pat.kind {
1645            PatKind::Missing => None,
1646            PatKind::Ident(_, ident, _) => Some(self.lower_ident(ident)),
1647            PatKind::Wild => Some(Ident::new(kw::Underscore, self.lower_span(param.pat.span))),
1648            _ => {
1649                self.dcx().span_delayed_bug(
1650                    param.pat.span,
1651                    "non-missing/ident/wild param pat must trigger an error",
1652                );
1653                None
1654            }
1655        }))
1656    }
1657
1658    /// Lowers a function declaration.
1659    ///
1660    /// `decl`: the unlowered (AST) function declaration.
1661    ///
1662    /// `fn_node_id`: `impl Trait` arguments are lowered into generic parameters on the given
1663    /// `NodeId`.
1664    ///
1665    /// `transform_return_type`: if `Some`, applies some conversion to the return type, such as is
1666    /// needed for `async fn` and `gen fn`. See [`CoroutineKind`] for more details.
1667    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_fn_decl",
                                    "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1667u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["decl", "fn_node_id",
                                                    "fn_span", "kind", "coro"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&decl)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_node_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coro)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'hir hir::FnDecl<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let c_variadic = decl.c_variadic();
            let mut inputs = &decl.inputs[..];
            if c_variadic { inputs = &inputs[..inputs.len() - 1]; }
            let inputs =
                self.arena.alloc_from_iter(inputs.iter().map(|param|
                            {
                                let itctx =
                                    match kind {
                                        FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl |
                                            FnDeclKind::Trait => {
                                            ImplTraitContext::Universal
                                        }
                                        FnDeclKind::ExternFn => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnParam)
                                        }
                                        FnDeclKind::Closure => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureParam)
                                        }
                                        FnDeclKind::Pointer => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerParam)
                                        }
                                    };
                                self.lower_ty(&param.ty, itctx)
                            }));
            let output =
                match coro {
                    Some(coro) => {
                        let fn_def_id = self.local_def_id(fn_node_id);
                        self.lower_coroutine_fn_ret_ty(&decl.output, fn_def_id,
                            coro, kind)
                    }
                    None =>
                        match &decl.output {
                            FnRetTy::Ty(ty) => {
                                let itctx =
                                    match kind {
                                        FnDeclKind::Fn | FnDeclKind::Inherent =>
                                            ImplTraitContext::OpaqueTy {
                                                origin: hir::OpaqueTyOrigin::FnReturn {
                                                    parent: self.local_def_id(fn_node_id),
                                                    in_trait_or_impl: None,
                                                },
                                            },
                                        FnDeclKind::Trait =>
                                            ImplTraitContext::OpaqueTy {
                                                origin: hir::OpaqueTyOrigin::FnReturn {
                                                    parent: self.local_def_id(fn_node_id),
                                                    in_trait_or_impl: Some(hir::RpitContext::Trait),
                                                },
                                            },
                                        FnDeclKind::Impl =>
                                            ImplTraitContext::OpaqueTy {
                                                origin: hir::OpaqueTyOrigin::FnReturn {
                                                    parent: self.local_def_id(fn_node_id),
                                                    in_trait_or_impl: Some(hir::RpitContext::TraitImpl),
                                                },
                                            },
                                        FnDeclKind::ExternFn => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnReturn)
                                        }
                                        FnDeclKind::Closure => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureReturn)
                                        }
                                        FnDeclKind::Pointer => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerReturn)
                                        }
                                    };
                                hir::FnRetTy::Return(self.lower_ty_alloc(ty, itctx))
                            }
                            FnRetTy::Default(span) =>
                                hir::FnRetTy::DefaultReturn(self.lower_span(*span)),
                        },
                };
            self.arena.alloc(hir::FnDecl {
                    inputs,
                    output,
                    c_variadic,
                    lifetime_elision_allowed: self.resolver.lifetime_elision_allowed.contains(&fn_node_id),
                    implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None,
                        |arg|
                            {
                                let is_mutable_pat =
                                    #[allow(non_exhaustive_omitted_patterns)] match arg.pat.kind
                                        {
                                        PatKind::Ident(hir::BindingMode(_, Mutability::Mut), ..) =>
                                            true,
                                        _ => false,
                                    };
                                match &arg.ty.kind {
                                    TyKind::ImplicitSelf if is_mutable_pat =>
                                        hir::ImplicitSelfKind::Mut,
                                    TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
                                    TyKind::Ref(_, mt) | TyKind::PinnedRef(_, mt) if
                                        mt.ty.kind.is_implicit_self() => {
                                        match mt.mutbl {
                                            hir::Mutability::Not => hir::ImplicitSelfKind::RefImm,
                                            hir::Mutability::Mut => hir::ImplicitSelfKind::RefMut,
                                        }
                                    }
                                    _ => hir::ImplicitSelfKind::None,
                                }
                            }),
                })
        }
    }
}#[instrument(level = "debug", skip(self))]
1668    fn lower_fn_decl(
1669        &mut self,
1670        decl: &FnDecl,
1671        fn_node_id: NodeId,
1672        fn_span: Span,
1673        kind: FnDeclKind,
1674        coro: Option<CoroutineKind>,
1675    ) -> &'hir hir::FnDecl<'hir> {
1676        let c_variadic = decl.c_variadic();
1677
1678        // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1679        // as they are not explicit in HIR/Ty function signatures.
1680        // (instead, the `c_variadic` flag is set to `true`)
1681        let mut inputs = &decl.inputs[..];
1682        if c_variadic {
1683            inputs = &inputs[..inputs.len() - 1];
1684        }
1685        let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1686            let itctx = match kind {
1687                FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait => {
1688                    ImplTraitContext::Universal
1689                }
1690                FnDeclKind::ExternFn => {
1691                    ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnParam)
1692                }
1693                FnDeclKind::Closure => {
1694                    ImplTraitContext::Disallowed(ImplTraitPosition::ClosureParam)
1695                }
1696                FnDeclKind::Pointer => {
1697                    ImplTraitContext::Disallowed(ImplTraitPosition::PointerParam)
1698                }
1699            };
1700            self.lower_ty(&param.ty, itctx)
1701        }));
1702
1703        let output = match coro {
1704            Some(coro) => {
1705                let fn_def_id = self.local_def_id(fn_node_id);
1706                self.lower_coroutine_fn_ret_ty(&decl.output, fn_def_id, coro, kind)
1707            }
1708            None => match &decl.output {
1709                FnRetTy::Ty(ty) => {
1710                    let itctx = match kind {
1711                        FnDeclKind::Fn | FnDeclKind::Inherent => ImplTraitContext::OpaqueTy {
1712                            origin: hir::OpaqueTyOrigin::FnReturn {
1713                                parent: self.local_def_id(fn_node_id),
1714                                in_trait_or_impl: None,
1715                            },
1716                        },
1717                        FnDeclKind::Trait => ImplTraitContext::OpaqueTy {
1718                            origin: hir::OpaqueTyOrigin::FnReturn {
1719                                parent: self.local_def_id(fn_node_id),
1720                                in_trait_or_impl: Some(hir::RpitContext::Trait),
1721                            },
1722                        },
1723                        FnDeclKind::Impl => ImplTraitContext::OpaqueTy {
1724                            origin: hir::OpaqueTyOrigin::FnReturn {
1725                                parent: self.local_def_id(fn_node_id),
1726                                in_trait_or_impl: Some(hir::RpitContext::TraitImpl),
1727                            },
1728                        },
1729                        FnDeclKind::ExternFn => {
1730                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnReturn)
1731                        }
1732                        FnDeclKind::Closure => {
1733                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureReturn)
1734                        }
1735                        FnDeclKind::Pointer => {
1736                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerReturn)
1737                        }
1738                    };
1739                    hir::FnRetTy::Return(self.lower_ty_alloc(ty, itctx))
1740                }
1741                FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(*span)),
1742            },
1743        };
1744
1745        self.arena.alloc(hir::FnDecl {
1746            inputs,
1747            output,
1748            c_variadic,
1749            lifetime_elision_allowed: self.resolver.lifetime_elision_allowed.contains(&fn_node_id),
1750            implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1751                let is_mutable_pat = matches!(
1752                    arg.pat.kind,
1753                    PatKind::Ident(hir::BindingMode(_, Mutability::Mut), ..)
1754                );
1755
1756                match &arg.ty.kind {
1757                    TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1758                    TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1759                    // Given we are only considering `ImplicitSelf` types, we needn't consider
1760                    // the case where we have a mutable pattern to a reference as that would
1761                    // no longer be an `ImplicitSelf`.
1762                    TyKind::Ref(_, mt) | TyKind::PinnedRef(_, mt)
1763                        if mt.ty.kind.is_implicit_self() =>
1764                    {
1765                        match mt.mutbl {
1766                            hir::Mutability::Not => hir::ImplicitSelfKind::RefImm,
1767                            hir::Mutability::Mut => hir::ImplicitSelfKind::RefMut,
1768                        }
1769                    }
1770                    _ => hir::ImplicitSelfKind::None,
1771                }
1772            }),
1773        })
1774    }
1775
1776    // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1777    // combined with the following definition of `OpaqueTy`:
1778    //
1779    //     type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1780    //
1781    // `output`: unlowered output type (`T` in `-> T`)
1782    // `fn_node_id`: `NodeId` of the parent function (used to create child impl trait definition)
1783    // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1784    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_coroutine_fn_ret_ty",
                                    "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1784u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["output",
                                                    "fn_def_id", "coro", "fn_kind"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&output)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coro)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_kind)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::FnRetTy<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let span = self.lower_span(output.span());
            let (opaque_ty_node_id, allowed_features) =
                match coro {
                    CoroutineKind::Async { return_impl_trait_id, .. } =>
                        (return_impl_trait_id, None),
                    CoroutineKind::Gen { return_impl_trait_id, .. } =>
                        (return_impl_trait_id, None),
                    CoroutineKind::AsyncGen { return_impl_trait_id, .. } => {
                        (return_impl_trait_id,
                            Some(Arc::clone(&self.allow_async_iterator)))
                    }
                };
            let opaque_ty_span =
                self.mark_span_with_reason(DesugaringKind::Async, span,
                    allowed_features);
            let in_trait_or_impl =
                match fn_kind {
                    FnDeclKind::Trait => Some(hir::RpitContext::Trait),
                    FnDeclKind::Impl => Some(hir::RpitContext::TraitImpl),
                    FnDeclKind::Fn | FnDeclKind::Inherent => None,
                    FnDeclKind::ExternFn | FnDeclKind::Closure |
                        FnDeclKind::Pointer =>
                        ::core::panicking::panic("internal error: entered unreachable code"),
                };
            let opaque_ty_ref =
                self.lower_opaque_inner(opaque_ty_node_id,
                    hir::OpaqueTyOrigin::AsyncFn {
                        parent: fn_def_id,
                        in_trait_or_impl,
                    }, opaque_ty_span,
                    |this|
                        {
                            let bound =
                                this.lower_coroutine_fn_output_type_to_bound(output, coro,
                                    opaque_ty_span,
                                    ImplTraitContext::OpaqueTy {
                                        origin: hir::OpaqueTyOrigin::FnReturn {
                                            parent: fn_def_id,
                                            in_trait_or_impl,
                                        },
                                    });
                            this.arena.alloc_from_iter([bound])
                        });
            let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
            hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
        }
    }
}#[instrument(level = "debug", skip(self))]
1785    fn lower_coroutine_fn_ret_ty(
1786        &mut self,
1787        output: &FnRetTy,
1788        fn_def_id: LocalDefId,
1789        coro: CoroutineKind,
1790        fn_kind: FnDeclKind,
1791    ) -> hir::FnRetTy<'hir> {
1792        let span = self.lower_span(output.span());
1793
1794        let (opaque_ty_node_id, allowed_features) = match coro {
1795            CoroutineKind::Async { return_impl_trait_id, .. } => (return_impl_trait_id, None),
1796            CoroutineKind::Gen { return_impl_trait_id, .. } => (return_impl_trait_id, None),
1797            CoroutineKind::AsyncGen { return_impl_trait_id, .. } => {
1798                (return_impl_trait_id, Some(Arc::clone(&self.allow_async_iterator)))
1799            }
1800        };
1801
1802        let opaque_ty_span =
1803            self.mark_span_with_reason(DesugaringKind::Async, span, allowed_features);
1804
1805        let in_trait_or_impl = match fn_kind {
1806            FnDeclKind::Trait => Some(hir::RpitContext::Trait),
1807            FnDeclKind::Impl => Some(hir::RpitContext::TraitImpl),
1808            FnDeclKind::Fn | FnDeclKind::Inherent => None,
1809            FnDeclKind::ExternFn | FnDeclKind::Closure | FnDeclKind::Pointer => unreachable!(),
1810        };
1811
1812        let opaque_ty_ref = self.lower_opaque_inner(
1813            opaque_ty_node_id,
1814            hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, in_trait_or_impl },
1815            opaque_ty_span,
1816            |this| {
1817                let bound = this.lower_coroutine_fn_output_type_to_bound(
1818                    output,
1819                    coro,
1820                    opaque_ty_span,
1821                    ImplTraitContext::OpaqueTy {
1822                        origin: hir::OpaqueTyOrigin::FnReturn {
1823                            parent: fn_def_id,
1824                            in_trait_or_impl,
1825                        },
1826                    },
1827                );
1828                arena_vec![this; bound]
1829            },
1830        );
1831
1832        let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1833        hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
1834    }
1835
1836    /// Transforms `-> T` into `Future<Output = T>`.
1837    fn lower_coroutine_fn_output_type_to_bound(
1838        &mut self,
1839        output: &FnRetTy,
1840        coro: CoroutineKind,
1841        opaque_ty_span: Span,
1842        itctx: ImplTraitContext,
1843    ) -> hir::GenericBound<'hir> {
1844        // Compute the `T` in `Future<Output = T>` from the return type.
1845        let output_ty = match output {
1846            FnRetTy::Ty(ty) => {
1847                // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1848                // `impl Future` opaque type that `async fn` implicitly
1849                // generates.
1850                self.lower_ty_alloc(ty, itctx)
1851            }
1852            FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1853        };
1854
1855        // "<$assoc_ty_name = T>"
1856        let (assoc_ty_name, trait_lang_item) = match coro {
1857            CoroutineKind::Async { .. } => (sym::Output, hir::LangItem::Future),
1858            CoroutineKind::Gen { .. } => (sym::Item, hir::LangItem::Iterator),
1859            CoroutineKind::AsyncGen { .. } => (sym::Item, hir::LangItem::AsyncIterator),
1860        };
1861
1862        let bound_args = self.arena.alloc(hir::GenericArgs {
1863            args: &[],
1864            constraints: self.arena.alloc_from_iter([self.assoc_ty_binding(assoc_ty_name,
                opaque_ty_span, output_ty)])arena_vec![self; self.assoc_ty_binding(assoc_ty_name, opaque_ty_span, output_ty)],
1865            parenthesized: hir::GenericArgsParentheses::No,
1866            span_ext: DUMMY_SP,
1867        });
1868
1869        hir::GenericBound::Trait(hir::PolyTraitRef {
1870            bound_generic_params: &[],
1871            modifiers: hir::TraitBoundModifiers::NONE,
1872            trait_ref: hir::TraitRef {
1873                path: self.make_lang_item_path(trait_lang_item, opaque_ty_span, Some(bound_args)),
1874                hir_ref_id: self.next_id(),
1875            },
1876            span: opaque_ty_span,
1877        })
1878    }
1879
1880    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_param_bound",
                                    "rustc_ast_lowering", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1880u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["tpb", "rbp",
                                                    "itctx"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tpb)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rbp)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::GenericBound<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match tpb {
                GenericBound::Trait(p) => {
                    hir::GenericBound::Trait(self.lower_poly_trait_ref(p, rbp,
                            itctx))
                }
                GenericBound::Outlives(lifetime) =>
                    hir::GenericBound::Outlives(self.lower_lifetime(lifetime,
                            LifetimeSource::OutlivesBound, lifetime.ident.into())),
                GenericBound::Use(args, span) =>
                    hir::GenericBound::Use(self.lower_precise_capturing_args(args),
                        self.lower_span(*span)),
            }
        }
    }
}#[instrument(level = "trace", skip(self))]
1881    fn lower_param_bound(
1882        &mut self,
1883        tpb: &GenericBound,
1884        rbp: RelaxedBoundPolicy<'_>,
1885        itctx: ImplTraitContext,
1886    ) -> hir::GenericBound<'hir> {
1887        match tpb {
1888            GenericBound::Trait(p) => {
1889                hir::GenericBound::Trait(self.lower_poly_trait_ref(p, rbp, itctx))
1890            }
1891            GenericBound::Outlives(lifetime) => hir::GenericBound::Outlives(self.lower_lifetime(
1892                lifetime,
1893                LifetimeSource::OutlivesBound,
1894                lifetime.ident.into(),
1895            )),
1896            GenericBound::Use(args, span) => hir::GenericBound::Use(
1897                self.lower_precise_capturing_args(args),
1898                self.lower_span(*span),
1899            ),
1900        }
1901    }
1902
1903    fn lower_lifetime(
1904        &mut self,
1905        l: &Lifetime,
1906        source: LifetimeSource,
1907        syntax: LifetimeSyntax,
1908    ) -> &'hir hir::Lifetime {
1909        self.new_named_lifetime(l.id, l.id, l.ident, source, syntax)
1910    }
1911
1912    fn lower_lifetime_hidden_in_path(
1913        &mut self,
1914        id: NodeId,
1915        span: Span,
1916        angle_brackets: AngleBrackets,
1917    ) -> &'hir hir::Lifetime {
1918        self.new_named_lifetime(
1919            id,
1920            id,
1921            Ident::new(kw::UnderscoreLifetime, span),
1922            LifetimeSource::Path { angle_brackets },
1923            LifetimeSyntax::Implicit,
1924        )
1925    }
1926
1927    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("new_named_lifetime",
                                    "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1927u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["id", "new_id",
                                                    "ident", "source", "syntax"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&new_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&syntax)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'hir hir::Lifetime = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let res =
                self.resolver.get_lifetime_res(id).unwrap_or(LifetimeRes::Error);
            let res =
                match res {
                    LifetimeRes::Param { param, .. } =>
                        hir::LifetimeKind::Param(param),
                    LifetimeRes::Fresh { param, .. } => {
                        match (&ident.name, &kw::UnderscoreLifetime) {
                            (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);
                                }
                            }
                        };
                        let param = self.local_def_id(param);
                        hir::LifetimeKind::Param(param)
                    }
                    LifetimeRes::Infer => {
                        match (&ident.name, &kw::UnderscoreLifetime) {
                            (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);
                                }
                            }
                        };
                        hir::LifetimeKind::Infer
                    }
                    LifetimeRes::Static { .. } => {
                        if !#[allow(non_exhaustive_omitted_patterns)] match ident.name
                                    {
                                    kw::StaticLifetime | kw::UnderscoreLifetime => true,
                                    _ => false,
                                } {
                            ::core::panicking::panic("assertion failed: matches!(ident.name, kw::StaticLifetime | kw::UnderscoreLifetime)")
                        };
                        hir::LifetimeKind::Static
                    }
                    LifetimeRes::Error => hir::LifetimeKind::Error,
                    LifetimeRes::ElidedAnchor { .. } => {
                        {
                            ::core::panicking::panic_fmt(format_args!("Unexpected `ElidedAnchar` {0:?} at {1:?}",
                                    ident, ident.span));
                        };
                    }
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:1958",
                                    "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1958u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["res"],
                                        ::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(&debug(&res) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            self.arena.alloc(hir::Lifetime::new(self.lower_node_id(new_id),
                    self.lower_ident(ident), res, source, syntax))
        }
    }
}#[instrument(level = "debug", skip(self))]
1928    fn new_named_lifetime(
1929        &mut self,
1930        id: NodeId,
1931        new_id: NodeId,
1932        ident: Ident,
1933        source: LifetimeSource,
1934        syntax: LifetimeSyntax,
1935    ) -> &'hir hir::Lifetime {
1936        let res = self.resolver.get_lifetime_res(id).unwrap_or(LifetimeRes::Error);
1937        let res = match res {
1938            LifetimeRes::Param { param, .. } => hir::LifetimeKind::Param(param),
1939            LifetimeRes::Fresh { param, .. } => {
1940                assert_eq!(ident.name, kw::UnderscoreLifetime);
1941                let param = self.local_def_id(param);
1942                hir::LifetimeKind::Param(param)
1943            }
1944            LifetimeRes::Infer => {
1945                assert_eq!(ident.name, kw::UnderscoreLifetime);
1946                hir::LifetimeKind::Infer
1947            }
1948            LifetimeRes::Static { .. } => {
1949                assert!(matches!(ident.name, kw::StaticLifetime | kw::UnderscoreLifetime));
1950                hir::LifetimeKind::Static
1951            }
1952            LifetimeRes::Error => hir::LifetimeKind::Error,
1953            LifetimeRes::ElidedAnchor { .. } => {
1954                panic!("Unexpected `ElidedAnchar` {:?} at {:?}", ident, ident.span);
1955            }
1956        };
1957
1958        debug!(?res);
1959        self.arena.alloc(hir::Lifetime::new(
1960            self.lower_node_id(new_id),
1961            self.lower_ident(ident),
1962            res,
1963            source,
1964            syntax,
1965        ))
1966    }
1967
1968    fn lower_generic_params_mut(
1969        &mut self,
1970        params: &[GenericParam],
1971        source: hir::GenericParamSource,
1972    ) -> impl Iterator<Item = hir::GenericParam<'hir>> {
1973        params.iter().map(move |param| self.lower_generic_param(param, source))
1974    }
1975
1976    fn lower_generic_params(
1977        &mut self,
1978        params: &[GenericParam],
1979        source: hir::GenericParamSource,
1980    ) -> &'hir [hir::GenericParam<'hir>] {
1981        self.arena.alloc_from_iter(self.lower_generic_params_mut(params, source))
1982    }
1983
1984    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_generic_param",
                                    "rustc_ast_lowering", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1984u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["param", "source"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::GenericParam<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (name, kind) = self.lower_generic_param_kind(param, source);
            let hir_id = self.lower_node_id(param.id);
            let param_attrs = &param.attrs;
            let param_span = param.span();
            let param =
                hir::GenericParam {
                    hir_id,
                    def_id: self.local_def_id(param.id),
                    name,
                    span: self.lower_span(param.span()),
                    pure_wrt_drop: attr::contains_name(&param.attrs,
                        sym::may_dangle),
                    kind,
                    colon_span: param.colon_span.map(|s| self.lower_span(s)),
                    source,
                };
            self.lower_attrs(hir_id, param_attrs, param_span,
                Target::from_generic_param(&param));
            param
        }
    }
}#[instrument(level = "trace", skip(self))]
1985    fn lower_generic_param(
1986        &mut self,
1987        param: &GenericParam,
1988        source: hir::GenericParamSource,
1989    ) -> hir::GenericParam<'hir> {
1990        let (name, kind) = self.lower_generic_param_kind(param, source);
1991
1992        let hir_id = self.lower_node_id(param.id);
1993        let param_attrs = &param.attrs;
1994        let param_span = param.span();
1995        let param = hir::GenericParam {
1996            hir_id,
1997            def_id: self.local_def_id(param.id),
1998            name,
1999            span: self.lower_span(param.span()),
2000            pure_wrt_drop: attr::contains_name(&param.attrs, sym::may_dangle),
2001            kind,
2002            colon_span: param.colon_span.map(|s| self.lower_span(s)),
2003            source,
2004        };
2005        self.lower_attrs(hir_id, param_attrs, param_span, Target::from_generic_param(&param));
2006        param
2007    }
2008
2009    fn lower_generic_param_kind(
2010        &mut self,
2011        param: &GenericParam,
2012        source: hir::GenericParamSource,
2013    ) -> (hir::ParamName, hir::GenericParamKind<'hir>) {
2014        match &param.kind {
2015            GenericParamKind::Lifetime => {
2016                // AST resolution emitted an error on those parameters, so we lower them using
2017                // `ParamName::Error`.
2018                let ident = self.lower_ident(param.ident);
2019                let param_name =
2020                    if let Some(LifetimeRes::Error) = self.resolver.get_lifetime_res(param.id) {
2021                        ParamName::Error(ident)
2022                    } else {
2023                        ParamName::Plain(ident)
2024                    };
2025                let kind =
2026                    hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2027
2028                (param_name, kind)
2029            }
2030            GenericParamKind::Type { default, .. } => {
2031                // Not only do we deny type param defaults in binders but we also map them to `None`
2032                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2033                let default = default
2034                    .as_ref()
2035                    .filter(|_| match source {
2036                        hir::GenericParamSource::Generics => true,
2037                        hir::GenericParamSource::Binder => {
2038                            self.dcx().emit_err(errors::GenericParamDefaultInBinder {
2039                                span: param.span(),
2040                            });
2041
2042                            false
2043                        }
2044                    })
2045                    .map(|def| {
2046                        self.lower_ty_alloc(
2047                            def,
2048                            ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2049                        )
2050                    });
2051
2052                let kind = hir::GenericParamKind::Type { default, synthetic: false };
2053
2054                (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2055            }
2056            GenericParamKind::Const { ty, span: _, default } => {
2057                let ty = self.lower_ty_alloc(
2058                    ty,
2059                    ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2060                );
2061
2062                // Not only do we deny const param defaults in binders but we also map them to `None`
2063                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2064                let default = default
2065                    .as_ref()
2066                    .filter(|_| match source {
2067                        hir::GenericParamSource::Generics => true,
2068                        hir::GenericParamSource::Binder => {
2069                            self.dcx().emit_err(errors::GenericParamDefaultInBinder {
2070                                span: param.span(),
2071                            });
2072
2073                            false
2074                        }
2075                    })
2076                    .map(|def| self.lower_anon_const_to_const_arg_and_alloc(def));
2077
2078                (
2079                    hir::ParamName::Plain(self.lower_ident(param.ident)),
2080                    hir::GenericParamKind::Const { ty, default },
2081                )
2082            }
2083        }
2084    }
2085
2086    fn lower_trait_ref(
2087        &mut self,
2088        modifiers: ast::TraitBoundModifiers,
2089        p: &TraitRef,
2090        itctx: ImplTraitContext,
2091    ) -> hir::TraitRef<'hir> {
2092        let path = match self.lower_qpath(
2093            p.ref_id,
2094            &None,
2095            &p.path,
2096            ParamMode::Explicit,
2097            AllowReturnTypeNotation::No,
2098            itctx,
2099            Some(modifiers),
2100        ) {
2101            hir::QPath::Resolved(None, path) => path,
2102            qpath => {
    ::core::panicking::panic_fmt(format_args!("lower_trait_ref: unexpected QPath `{0:?}`",
            qpath));
}panic!("lower_trait_ref: unexpected QPath `{qpath:?}`"),
2103        };
2104        hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2105    }
2106
2107    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_poly_trait_ref",
                                    "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2107u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["bound_generic_params",
                                                    "modifiers", "trait_ref", "span", "rbp", "itctx"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_generic_params)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&modifiers)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rbp)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::PolyTraitRef<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let bound_generic_params =
                self.lower_lifetime_binder(trait_ref.ref_id,
                    bound_generic_params);
            let trait_ref =
                self.lower_trait_ref(*modifiers, trait_ref, itctx);
            let modifiers = self.lower_trait_bound_modifiers(*modifiers);
            if let ast::BoundPolarity::Maybe(_) = modifiers.polarity {
                self.validate_relaxed_bound(trait_ref, *span, rbp);
            }
            hir::PolyTraitRef {
                bound_generic_params,
                modifiers,
                trait_ref,
                span: self.lower_span(*span),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2108    fn lower_poly_trait_ref(
2109        &mut self,
2110        PolyTraitRef { bound_generic_params, modifiers, trait_ref, span, parens: _ }: &PolyTraitRef,
2111        rbp: RelaxedBoundPolicy<'_>,
2112        itctx: ImplTraitContext,
2113    ) -> hir::PolyTraitRef<'hir> {
2114        let bound_generic_params =
2115            self.lower_lifetime_binder(trait_ref.ref_id, bound_generic_params);
2116        let trait_ref = self.lower_trait_ref(*modifiers, trait_ref, itctx);
2117        let modifiers = self.lower_trait_bound_modifiers(*modifiers);
2118
2119        if let ast::BoundPolarity::Maybe(_) = modifiers.polarity {
2120            self.validate_relaxed_bound(trait_ref, *span, rbp);
2121        }
2122
2123        hir::PolyTraitRef {
2124            bound_generic_params,
2125            modifiers,
2126            trait_ref,
2127            span: self.lower_span(*span),
2128        }
2129    }
2130
2131    fn validate_relaxed_bound(
2132        &self,
2133        trait_ref: hir::TraitRef<'_>,
2134        span: Span,
2135        rbp: RelaxedBoundPolicy<'_>,
2136    ) {
2137        // Even though feature `more_maybe_bounds` enables the user to relax all default bounds
2138        // other than `Sized` in a lot more positions (thereby bypassing the given policy), we don't
2139        // want to advertise it to the user (via a feature gate error) since it's super internal.
2140        //
2141        // FIXME(more_maybe_bounds): Moreover, if we actually were to add proper default traits
2142        // (like a hypothetical `Move` or `Leak`) we would want to validate the location according
2143        // to default trait elaboration in HIR ty lowering (which depends on the specific trait in
2144        // question: E.g., `?Sized` & `?Move` most likely won't be allowed in all the same places).
2145
2146        match rbp {
2147            RelaxedBoundPolicy::Allowed => return,
2148            RelaxedBoundPolicy::AllowedIfOnTyParam(id, params) => {
2149                if let Some(res) = self.resolver.get_partial_res(id).and_then(|r| r.full_res())
2150                    && let Res::Def(DefKind::TyParam, def_id) = res
2151                    && params.iter().any(|p| def_id == self.local_def_id(p.id).to_def_id())
2152                {
2153                    return;
2154                }
2155            }
2156            RelaxedBoundPolicy::Forbidden(reason) => {
2157                let gate = |context, subject| {
2158                    let extended = self.tcx.features().more_maybe_bounds();
2159                    let is_sized = trait_ref
2160                        .trait_def_id()
2161                        .is_some_and(|def_id| self.tcx.is_lang_item(def_id, hir::LangItem::Sized));
2162
2163                    if extended && !is_sized {
2164                        return;
2165                    }
2166
2167                    let prefix = if extended { "`Sized` " } else { "" };
2168                    let mut diag = self.dcx().struct_span_err(
2169                        span,
2170                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("relaxed {0}bounds are not permitted in {1}",
                prefix, context))
    })format!("relaxed {prefix}bounds are not permitted in {context}"),
2171                    );
2172                    if is_sized {
2173                        diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} are not implicitly bounded by `Sized`, so there is nothing to relax",
                subject))
    })format!(
2174                            "{subject} are not implicitly bounded by `Sized`, \
2175                             so there is nothing to relax"
2176                        ));
2177                    }
2178                    diag.emit();
2179                };
2180
2181                match reason {
2182                    RelaxedBoundForbiddenReason::TraitObjectTy => {
2183                        gate("trait object types", "trait object types");
2184                        return;
2185                    }
2186                    RelaxedBoundForbiddenReason::SuperTrait => {
2187                        gate("supertrait bounds", "traits");
2188                        return;
2189                    }
2190                    RelaxedBoundForbiddenReason::TraitAlias => {
2191                        gate("trait alias bounds", "trait aliases");
2192                        return;
2193                    }
2194                    RelaxedBoundForbiddenReason::AssocTyBounds
2195                    | RelaxedBoundForbiddenReason::LateBoundVarsInScope => {}
2196                };
2197            }
2198        }
2199
2200        self.dcx()
2201            .struct_span_err(span, "this relaxed bound is not permitted here")
2202            .with_note(
2203                "in this context, relaxed bounds are only allowed on \
2204                 type parameters defined on the closest item",
2205            )
2206            .emit();
2207    }
2208
2209    fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy<'hir> {
2210        hir::MutTy { ty: self.lower_ty_alloc(&mt.ty, itctx), mutbl: mt.mutbl }
2211    }
2212
2213    x;#[instrument(level = "debug", skip(self), ret)]
2214    fn lower_param_bounds(
2215        &mut self,
2216        bounds: &[GenericBound],
2217        rbp: RelaxedBoundPolicy<'_>,
2218        itctx: ImplTraitContext,
2219    ) -> hir::GenericBounds<'hir> {
2220        self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, rbp, itctx))
2221    }
2222
2223    fn lower_param_bounds_mut(
2224        &mut self,
2225        bounds: &[GenericBound],
2226        rbp: RelaxedBoundPolicy<'_>,
2227        itctx: ImplTraitContext,
2228    ) -> impl Iterator<Item = hir::GenericBound<'hir>> {
2229        bounds.iter().map(move |bound| self.lower_param_bound(bound, rbp, itctx))
2230    }
2231
2232    x;#[instrument(level = "debug", skip(self), ret)]
2233    fn lower_universal_param_and_bounds(
2234        &mut self,
2235        node_id: NodeId,
2236        span: Span,
2237        ident: Ident,
2238        bounds: &[GenericBound],
2239    ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2240        // Add a definition for the in-band `Param`.
2241        let def_id = self.local_def_id(node_id);
2242        let span = self.lower_span(span);
2243
2244        // Set the name to `impl Bound1 + Bound2`.
2245        let param = hir::GenericParam {
2246            hir_id: self.lower_node_id(node_id),
2247            def_id,
2248            name: ParamName::Plain(self.lower_ident(ident)),
2249            pure_wrt_drop: false,
2250            span,
2251            kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2252            colon_span: None,
2253            source: hir::GenericParamSource::Generics,
2254        };
2255
2256        let preds = self.lower_generic_bound_predicate(
2257            ident,
2258            node_id,
2259            &GenericParamKind::Type { default: None },
2260            bounds,
2261            /* colon_span */ None,
2262            span,
2263            RelaxedBoundPolicy::Allowed,
2264            ImplTraitContext::Universal,
2265            hir::PredicateOrigin::ImplTrait,
2266        );
2267
2268        let hir_id = self.next_id();
2269        let res = Res::Def(DefKind::TyParam, def_id.to_def_id());
2270        let ty = hir::TyKind::Path(hir::QPath::Resolved(
2271            None,
2272            self.arena.alloc(hir::Path {
2273                span,
2274                res,
2275                segments:
2276                    arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2277            }),
2278        ));
2279
2280        (param, preds, ty)
2281    }
2282
2283    /// Lowers a block directly to an expression, presuming that it
2284    /// has no attributes and is not targeted by a `break`.
2285    fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2286        let block = self.lower_block(b, false);
2287        self.expr_block(block)
2288    }
2289
2290    fn lower_array_length_to_const_arg(&mut self, c: &AnonConst) -> &'hir hir::ConstArg<'hir> {
2291        // We cannot just match on `ExprKind::Underscore` as `(_)` is represented as
2292        // `ExprKind::Paren(ExprKind::Underscore)` and should also be lowered to `GenericArg::Infer`
2293        match c.value.peel_parens().kind {
2294            ExprKind::Underscore => {
2295                let ct_kind = hir::ConstArgKind::Infer(());
2296                self.arena.alloc(hir::ConstArg {
2297                    hir_id: self.lower_node_id(c.id),
2298                    kind: ct_kind,
2299                    span: self.lower_span(c.value.span),
2300                })
2301            }
2302            _ => self.lower_anon_const_to_const_arg_and_alloc(c),
2303        }
2304    }
2305
2306    /// Used when lowering a type argument that turned out to actually be a const argument.
2307    ///
2308    /// Only use for that purpose since otherwise it will create a duplicate def.
2309    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_const_path_to_const_arg",
                                    "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2309u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["path", "res",
                                                    "ty_id", "span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'hir hir::ConstArg<'hir> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            let is_trivial_path =
                path.is_potential_trivial_const_arg() &&
                    #[allow(non_exhaustive_omitted_patterns)] match res {
                        Res::Def(DefKind::ConstParam, _) => true,
                        _ => false,
                    };
            let ct_kind =
                if is_trivial_path || tcx.features().min_generic_const_args()
                    {
                    let qpath =
                        self.lower_qpath(ty_id, &None, path, ParamMode::Explicit,
                            AllowReturnTypeNotation::No,
                            ImplTraitContext::Disallowed(ImplTraitPosition::Path),
                            None);
                    hir::ConstArgKind::Path(qpath)
                } else {
                    let node_id = self.next_node_id();
                    let span = self.lower_span(span);
                    let def_id =
                        self.create_def(node_id, None, DefKind::AnonConst,
                            DefPathData::LateAnonConst, span);
                    let hir_id = self.lower_node_id(node_id);
                    let path_expr =
                        Expr {
                            id: ty_id,
                            kind: ExprKind::Path(None, path.clone()),
                            span,
                            attrs: AttrVec::new(),
                            tokens: None,
                        };
                    let ct =
                        self.with_new_scopes(span,
                            |this|
                                {
                                    self.arena.alloc(hir::AnonConst {
                                            def_id,
                                            hir_id,
                                            body: this.lower_const_body(path_expr.span,
                                                Some(&path_expr)),
                                            span,
                                        })
                                });
                    hir::ConstArgKind::Anon(ct)
                };
            self.arena.alloc(hir::ConstArg {
                    hir_id: self.next_id(),
                    kind: ct_kind,
                    span: self.lower_span(span),
                })
        }
    }
}#[instrument(level = "debug", skip(self))]
2310    fn lower_const_path_to_const_arg(
2311        &mut self,
2312        path: &Path,
2313        res: Res<NodeId>,
2314        ty_id: NodeId,
2315        span: Span,
2316    ) -> &'hir hir::ConstArg<'hir> {
2317        let tcx = self.tcx;
2318
2319        let is_trivial_path = path.is_potential_trivial_const_arg()
2320            && matches!(res, Res::Def(DefKind::ConstParam, _));
2321        let ct_kind = if is_trivial_path || tcx.features().min_generic_const_args() {
2322            let qpath = self.lower_qpath(
2323                ty_id,
2324                &None,
2325                path,
2326                ParamMode::Explicit,
2327                AllowReturnTypeNotation::No,
2328                // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2329                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2330                None,
2331            );
2332            hir::ConstArgKind::Path(qpath)
2333        } else {
2334            // Construct an AnonConst where the expr is the "ty"'s path.
2335            let node_id = self.next_node_id();
2336            let span = self.lower_span(span);
2337
2338            // Add a definition for the in-band const def.
2339            // We're lowering a const argument that was originally thought to be a type argument,
2340            // so the def collector didn't create the def ahead of time. That's why we have to do
2341            // it here.
2342            let def_id = self.create_def(
2343                node_id,
2344                None,
2345                DefKind::AnonConst,
2346                DefPathData::LateAnonConst,
2347                span,
2348            );
2349            let hir_id = self.lower_node_id(node_id);
2350
2351            let path_expr = Expr {
2352                id: ty_id,
2353                kind: ExprKind::Path(None, path.clone()),
2354                span,
2355                attrs: AttrVec::new(),
2356                tokens: None,
2357            };
2358
2359            let ct = self.with_new_scopes(span, |this| {
2360                self.arena.alloc(hir::AnonConst {
2361                    def_id,
2362                    hir_id,
2363                    body: this.lower_const_body(path_expr.span, Some(&path_expr)),
2364                    span,
2365                })
2366            });
2367            hir::ConstArgKind::Anon(ct)
2368        };
2369
2370        self.arena.alloc(hir::ConstArg {
2371            hir_id: self.next_id(),
2372            kind: ct_kind,
2373            span: self.lower_span(span),
2374        })
2375    }
2376
2377    fn lower_const_item_rhs(
2378        &mut self,
2379        attrs: &[hir::Attribute],
2380        rhs: Option<&ConstItemRhs>,
2381        span: Span,
2382    ) -> hir::ConstItemRhs<'hir> {
2383        match rhs {
2384            Some(ConstItemRhs::TypeConst(anon)) => {
2385                hir::ConstItemRhs::TypeConst(self.lower_anon_const_to_const_arg_and_alloc(anon))
2386            }
2387            None if {
    {
            'done:
                {
                for i in attrs {
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(AttributeKind::TypeConst(_)) =>
                            {
                            break 'done Some(());
                        }
                        _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, AttributeKind::TypeConst(_)) => {
2388                let const_arg = ConstArg {
2389                    hir_id: self.next_id(),
2390                    kind: hir::ConstArgKind::Error(
2391                        self.dcx().span_delayed_bug(DUMMY_SP, "no block"),
2392                    ),
2393                    span: DUMMY_SP,
2394                };
2395                hir::ConstItemRhs::TypeConst(self.arena.alloc(const_arg))
2396            }
2397            Some(ConstItemRhs::Body(body)) => {
2398                hir::ConstItemRhs::Body(self.lower_const_body(span, Some(body)))
2399            }
2400            None => hir::ConstItemRhs::Body(self.lower_const_body(span, None)),
2401        }
2402    }
2403
2404    x;#[instrument(level = "debug", skip(self), ret)]
2405    fn lower_expr_to_const_arg_direct(&mut self, expr: &Expr) -> hir::ConstArg<'hir> {
2406        let span = self.lower_span(expr.span);
2407
2408        let overly_complex_const = |this: &mut Self| {
2409            let e = this.dcx().struct_span_err(
2410                expr.span,
2411                "complex const arguments must be placed inside of a `const` block",
2412            );
2413
2414            ConstArg { hir_id: this.next_id(), kind: hir::ConstArgKind::Error(e.emit()), span }
2415        };
2416
2417        match &expr.kind {
2418            ExprKind::Call(func, args) if let ExprKind::Path(qself, path) = &func.kind => {
2419                let qpath = self.lower_qpath(
2420                    func.id,
2421                    qself,
2422                    path,
2423                    ParamMode::Explicit,
2424                    AllowReturnTypeNotation::No,
2425                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2426                    None,
2427                );
2428
2429                let lowered_args = self.arena.alloc_from_iter(args.iter().map(|arg| {
2430                    let const_arg = if let ExprKind::ConstBlock(anon_const) = &arg.kind {
2431                        let def_id = self.local_def_id(anon_const.id);
2432                        let def_kind = self.tcx.def_kind(def_id);
2433                        assert_eq!(DefKind::AnonConst, def_kind);
2434                        self.lower_anon_const_to_const_arg(anon_const)
2435                    } else {
2436                        self.lower_expr_to_const_arg_direct(arg)
2437                    };
2438
2439                    &*self.arena.alloc(const_arg)
2440                }));
2441
2442                ConstArg {
2443                    hir_id: self.next_id(),
2444                    kind: hir::ConstArgKind::TupleCall(qpath, lowered_args),
2445                    span,
2446                }
2447            }
2448            ExprKind::Tup(exprs) => {
2449                let exprs = self.arena.alloc_from_iter(exprs.iter().map(|expr| {
2450                    let expr = if let ExprKind::ConstBlock(anon_const) = &expr.kind {
2451                        let def_id = self.local_def_id(anon_const.id);
2452                        let def_kind = self.tcx.def_kind(def_id);
2453                        assert_eq!(DefKind::AnonConst, def_kind);
2454
2455                        self.lower_anon_const_to_const_arg(anon_const)
2456                    } else {
2457                        self.lower_expr_to_const_arg_direct(&expr)
2458                    };
2459
2460                    &*self.arena.alloc(expr)
2461                }));
2462
2463                ConstArg { hir_id: self.next_id(), kind: hir::ConstArgKind::Tup(exprs), span }
2464            }
2465            ExprKind::Path(qself, path) => {
2466                let qpath = self.lower_qpath(
2467                    expr.id,
2468                    qself,
2469                    path,
2470                    ParamMode::Explicit,
2471                    AllowReturnTypeNotation::No,
2472                    // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2473                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2474                    None,
2475                );
2476
2477                ConstArg { hir_id: self.next_id(), kind: hir::ConstArgKind::Path(qpath), span }
2478            }
2479            ExprKind::Struct(se) => {
2480                let path = self.lower_qpath(
2481                    expr.id,
2482                    &se.qself,
2483                    &se.path,
2484                    // FIXME(mgca): we may want this to be `Optional` instead, but
2485                    // we would also need to make sure that HIR ty lowering errors
2486                    // when these paths wind up in signatures.
2487                    ParamMode::Explicit,
2488                    AllowReturnTypeNotation::No,
2489                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2490                    None,
2491                );
2492
2493                let fields = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
2494                    let hir_id = self.lower_node_id(f.id);
2495                    // FIXME(mgca): This might result in lowering attributes that
2496                    // then go unused as the `Target::ExprField` is not actually
2497                    // corresponding to `Node::ExprField`.
2498                    self.lower_attrs(hir_id, &f.attrs, f.span, Target::ExprField);
2499
2500                    let expr = if let ExprKind::ConstBlock(anon_const) = &f.expr.kind {
2501                        let def_id = self.local_def_id(anon_const.id);
2502                        let def_kind = self.tcx.def_kind(def_id);
2503                        assert_eq!(DefKind::AnonConst, def_kind);
2504
2505                        self.lower_anon_const_to_const_arg(anon_const)
2506                    } else {
2507                        self.lower_expr_to_const_arg_direct(&f.expr)
2508                    };
2509
2510                    &*self.arena.alloc(hir::ConstArgExprField {
2511                        hir_id,
2512                        field: self.lower_ident(f.ident),
2513                        expr: self.arena.alloc(expr),
2514                        span: self.lower_span(f.span),
2515                    })
2516                }));
2517
2518                ConstArg {
2519                    hir_id: self.next_id(),
2520                    kind: hir::ConstArgKind::Struct(path, fields),
2521                    span,
2522                }
2523            }
2524            ExprKind::Array(elements) => {
2525                let lowered_elems = self.arena.alloc_from_iter(elements.iter().map(|element| {
2526                    let const_arg = if let ExprKind::ConstBlock(anon_const) = &element.kind {
2527                        let def_id = self.local_def_id(anon_const.id);
2528                        assert_eq!(DefKind::AnonConst, self.tcx.def_kind(def_id));
2529                        self.lower_anon_const_to_const_arg(anon_const)
2530                    } else {
2531                        self.lower_expr_to_const_arg_direct(element)
2532                    };
2533                    &*self.arena.alloc(const_arg)
2534                }));
2535                let array_expr = self.arena.alloc(hir::ConstArgArrayExpr {
2536                    span: self.lower_span(expr.span),
2537                    elems: lowered_elems,
2538                });
2539
2540                ConstArg {
2541                    hir_id: self.next_id(),
2542                    kind: hir::ConstArgKind::Array(array_expr),
2543                    span,
2544                }
2545            }
2546            ExprKind::Underscore => ConstArg {
2547                hir_id: self.lower_node_id(expr.id),
2548                kind: hir::ConstArgKind::Infer(()),
2549                span,
2550            },
2551            ExprKind::Block(block, _) => {
2552                if let [stmt] = block.stmts.as_slice()
2553                    && let StmtKind::Expr(expr) = &stmt.kind
2554                    && matches!(
2555                        expr.kind,
2556                        ExprKind::Block(..)
2557                            | ExprKind::Path(..)
2558                            | ExprKind::Struct(..)
2559                            | ExprKind::Call(..)
2560                            | ExprKind::Tup(..)
2561                            | ExprKind::Array(..)
2562                    )
2563                {
2564                    return self.lower_expr_to_const_arg_direct(expr);
2565                }
2566
2567                overly_complex_const(self)
2568            }
2569            ExprKind::Lit(literal) => {
2570                let span = expr.span;
2571                let literal = self.lower_lit(literal, span);
2572
2573                ConstArg {
2574                    hir_id: self.lower_node_id(expr.id),
2575                    kind: hir::ConstArgKind::Literal(literal.node),
2576                    span,
2577                }
2578            }
2579            _ => overly_complex_const(self),
2580        }
2581    }
2582
2583    /// See [`hir::ConstArg`] for when to use this function vs
2584    /// [`Self::lower_anon_const_to_anon_const`].
2585    fn lower_anon_const_to_const_arg_and_alloc(
2586        &mut self,
2587        anon: &AnonConst,
2588    ) -> &'hir hir::ConstArg<'hir> {
2589        self.arena.alloc(self.lower_anon_const_to_const_arg(anon))
2590    }
2591
2592    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_anon_const_to_const_arg",
                                    "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2592u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["anon"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&anon)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::ConstArg<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            if tcx.features().min_generic_const_args() {
                return match anon.mgca_disambiguation {
                        MgcaDisambiguation::AnonConst => {
                            let lowered_anon =
                                self.lower_anon_const_to_anon_const(anon);
                            ConstArg {
                                hir_id: self.next_id(),
                                kind: hir::ConstArgKind::Anon(lowered_anon),
                                span: lowered_anon.span,
                            }
                        }
                        MgcaDisambiguation::Direct =>
                            self.lower_expr_to_const_arg_direct(&anon.value),
                    };
            }
            let expr =
                if let ExprKind::Block(block, _) = &anon.value.kind &&
                                let [stmt] = block.stmts.as_slice() &&
                            let StmtKind::Expr(expr) = &stmt.kind &&
                        let ExprKind::Path(..) = &expr.kind {
                    expr
                } else { &anon.value };
            let maybe_res =
                self.resolver.get_partial_res(expr.id).and_then(|partial_res|
                        partial_res.full_res());
            if let ExprKind::Path(qself, path) = &expr.kind &&
                        path.is_potential_trivial_const_arg() &&
                    #[allow(non_exhaustive_omitted_patterns)] match maybe_res {
                        Some(Res::Def(DefKind::ConstParam, _)) => true,
                        _ => false,
                    } {
                let qpath =
                    self.lower_qpath(expr.id, qself, path, ParamMode::Explicit,
                        AllowReturnTypeNotation::No,
                        ImplTraitContext::Disallowed(ImplTraitPosition::Path),
                        None);
                return ConstArg {
                        hir_id: self.lower_node_id(anon.id),
                        kind: hir::ConstArgKind::Path(qpath),
                        span: self.lower_span(expr.span),
                    };
            }
            let lowered_anon = self.lower_anon_const_to_anon_const(anon);
            ConstArg {
                hir_id: self.next_id(),
                kind: hir::ConstArgKind::Anon(lowered_anon),
                span: self.lower_span(expr.span),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2593    fn lower_anon_const_to_const_arg(&mut self, anon: &AnonConst) -> hir::ConstArg<'hir> {
2594        let tcx = self.tcx;
2595
2596        // We cannot change parsing depending on feature gates available,
2597        // we can only require feature gates to be active as a delayed check.
2598        // Thus we just parse anon consts generally and make the real decision
2599        // making in ast lowering.
2600        // FIXME(min_generic_const_args): revisit once stable
2601        if tcx.features().min_generic_const_args() {
2602            return match anon.mgca_disambiguation {
2603                MgcaDisambiguation::AnonConst => {
2604                    let lowered_anon = self.lower_anon_const_to_anon_const(anon);
2605                    ConstArg {
2606                        hir_id: self.next_id(),
2607                        kind: hir::ConstArgKind::Anon(lowered_anon),
2608                        span: lowered_anon.span,
2609                    }
2610                }
2611                MgcaDisambiguation::Direct => self.lower_expr_to_const_arg_direct(&anon.value),
2612            };
2613        }
2614
2615        // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2616        // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2617        let expr = if let ExprKind::Block(block, _) = &anon.value.kind
2618            && let [stmt] = block.stmts.as_slice()
2619            && let StmtKind::Expr(expr) = &stmt.kind
2620            && let ExprKind::Path(..) = &expr.kind
2621        {
2622            expr
2623        } else {
2624            &anon.value
2625        };
2626
2627        let maybe_res =
2628            self.resolver.get_partial_res(expr.id).and_then(|partial_res| partial_res.full_res());
2629        if let ExprKind::Path(qself, path) = &expr.kind
2630            && path.is_potential_trivial_const_arg()
2631            && matches!(maybe_res, Some(Res::Def(DefKind::ConstParam, _)))
2632        {
2633            let qpath = self.lower_qpath(
2634                expr.id,
2635                qself,
2636                path,
2637                ParamMode::Explicit,
2638                AllowReturnTypeNotation::No,
2639                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2640                None,
2641            );
2642
2643            return ConstArg {
2644                hir_id: self.lower_node_id(anon.id),
2645                kind: hir::ConstArgKind::Path(qpath),
2646                span: self.lower_span(expr.span),
2647            };
2648        }
2649
2650        let lowered_anon = self.lower_anon_const_to_anon_const(anon);
2651        ConstArg {
2652            hir_id: self.next_id(),
2653            kind: hir::ConstArgKind::Anon(lowered_anon),
2654            span: self.lower_span(expr.span),
2655        }
2656    }
2657
2658    /// See [`hir::ConstArg`] for when to use this function vs
2659    /// [`Self::lower_anon_const_to_const_arg`].
2660    fn lower_anon_const_to_anon_const(&mut self, c: &AnonConst) -> &'hir hir::AnonConst {
2661        self.arena.alloc(self.with_new_scopes(c.value.span, |this| {
2662            let def_id = this.local_def_id(c.id);
2663            let hir_id = this.lower_node_id(c.id);
2664            hir::AnonConst {
2665                def_id,
2666                hir_id,
2667                body: this.lower_const_body(c.value.span, Some(&c.value)),
2668                span: this.lower_span(c.value.span),
2669            }
2670        }))
2671    }
2672
2673    fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2674        match u {
2675            CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2676            UserProvided => hir::UnsafeSource::UserProvided,
2677        }
2678    }
2679
2680    fn lower_trait_bound_modifiers(
2681        &mut self,
2682        modifiers: TraitBoundModifiers,
2683    ) -> hir::TraitBoundModifiers {
2684        let constness = match modifiers.constness {
2685            BoundConstness::Never => BoundConstness::Never,
2686            BoundConstness::Always(span) => BoundConstness::Always(self.lower_span(span)),
2687            BoundConstness::Maybe(span) => BoundConstness::Maybe(self.lower_span(span)),
2688        };
2689        let polarity = match modifiers.polarity {
2690            BoundPolarity::Positive => BoundPolarity::Positive,
2691            BoundPolarity::Negative(span) => BoundPolarity::Negative(self.lower_span(span)),
2692            BoundPolarity::Maybe(span) => BoundPolarity::Maybe(self.lower_span(span)),
2693        };
2694        hir::TraitBoundModifiers { constness, polarity }
2695    }
2696
2697    // Helper methods for building HIR.
2698
2699    fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2700        hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2701    }
2702
2703    fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2704        self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2705    }
2706
2707    fn stmt_let_pat(
2708        &mut self,
2709        attrs: Option<&'hir [hir::Attribute]>,
2710        span: Span,
2711        init: Option<&'hir hir::Expr<'hir>>,
2712        pat: &'hir hir::Pat<'hir>,
2713        source: hir::LocalSource,
2714    ) -> hir::Stmt<'hir> {
2715        let hir_id = self.next_id();
2716        if let Some(a) = attrs {
2717            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
2718            self.attrs.insert(hir_id.local_id, a);
2719        }
2720        let local = hir::LetStmt {
2721            super_: None,
2722            hir_id,
2723            init,
2724            pat,
2725            els: None,
2726            source,
2727            span: self.lower_span(span),
2728            ty: None,
2729        };
2730        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
2731    }
2732
2733    fn stmt_super_let_pat(
2734        &mut self,
2735        span: Span,
2736        pat: &'hir hir::Pat<'hir>,
2737        init: Option<&'hir hir::Expr<'hir>>,
2738    ) -> hir::Stmt<'hir> {
2739        let hir_id = self.next_id();
2740        let span = self.lower_span(span);
2741        let local = hir::LetStmt {
2742            super_: Some(span),
2743            hir_id,
2744            init,
2745            pat,
2746            els: None,
2747            source: hir::LocalSource::Normal,
2748            span,
2749            ty: None,
2750        };
2751        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
2752    }
2753
2754    fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2755        self.block_all(expr.span, &[], Some(expr))
2756    }
2757
2758    fn block_all(
2759        &mut self,
2760        span: Span,
2761        stmts: &'hir [hir::Stmt<'hir>],
2762        expr: Option<&'hir hir::Expr<'hir>>,
2763    ) -> &'hir hir::Block<'hir> {
2764        let blk = hir::Block {
2765            stmts,
2766            expr,
2767            hir_id: self.next_id(),
2768            rules: hir::BlockCheckMode::DefaultBlock,
2769            span: self.lower_span(span),
2770            targeted_by_break: false,
2771        };
2772        self.arena.alloc(blk)
2773    }
2774
2775    fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2776        let field = self.single_pat_field(span, pat);
2777        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field)
2778    }
2779
2780    fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2781        let field = self.single_pat_field(span, pat);
2782        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field)
2783    }
2784
2785    fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2786        let field = self.single_pat_field(span, pat);
2787        self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field)
2788    }
2789
2790    fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2791        self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[])
2792    }
2793
2794    fn single_pat_field(
2795        &mut self,
2796        span: Span,
2797        pat: &'hir hir::Pat<'hir>,
2798    ) -> &'hir [hir::PatField<'hir>] {
2799        let field = hir::PatField {
2800            hir_id: self.next_id(),
2801            ident: Ident::new(sym::integer(0), self.lower_span(span)),
2802            is_shorthand: false,
2803            pat,
2804            span: self.lower_span(span),
2805        };
2806        self.arena.alloc_from_iter([field])arena_vec![self; field]
2807    }
2808
2809    fn pat_lang_item_variant(
2810        &mut self,
2811        span: Span,
2812        lang_item: hir::LangItem,
2813        fields: &'hir [hir::PatField<'hir>],
2814    ) -> &'hir hir::Pat<'hir> {
2815        let path = self.make_lang_item_qpath(lang_item, self.lower_span(span), None);
2816        self.pat(span, hir::PatKind::Struct(path, fields, None))
2817    }
2818
2819    fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, HirId) {
2820        self.pat_ident_binding_mode(span, ident, hir::BindingMode::NONE)
2821    }
2822
2823    fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, HirId) {
2824        self.pat_ident_binding_mode_mut(span, ident, hir::BindingMode::NONE)
2825    }
2826
2827    fn pat_ident_binding_mode(
2828        &mut self,
2829        span: Span,
2830        ident: Ident,
2831        bm: hir::BindingMode,
2832    ) -> (&'hir hir::Pat<'hir>, HirId) {
2833        let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2834        (self.arena.alloc(pat), hir_id)
2835    }
2836
2837    fn pat_ident_binding_mode_mut(
2838        &mut self,
2839        span: Span,
2840        ident: Ident,
2841        bm: hir::BindingMode,
2842    ) -> (hir::Pat<'hir>, HirId) {
2843        let hir_id = self.next_id();
2844
2845        (
2846            hir::Pat {
2847                hir_id,
2848                kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2849                span: self.lower_span(span),
2850                default_binding_modes: true,
2851            },
2852            hir_id,
2853        )
2854    }
2855
2856    fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2857        self.arena.alloc(hir::Pat {
2858            hir_id: self.next_id(),
2859            kind,
2860            span: self.lower_span(span),
2861            default_binding_modes: true,
2862        })
2863    }
2864
2865    fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2866        hir::Pat {
2867            hir_id: self.next_id(),
2868            kind,
2869            span: self.lower_span(span),
2870            default_binding_modes: false,
2871        }
2872    }
2873
2874    fn ty_path(&mut self, mut hir_id: HirId, span: Span, qpath: hir::QPath<'hir>) -> hir::Ty<'hir> {
2875        let kind = match qpath {
2876            hir::QPath::Resolved(None, path) => {
2877                // Turn trait object paths into `TyKind::TraitObject` instead.
2878                match path.res {
2879                    Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2880                        let principal = hir::PolyTraitRef {
2881                            bound_generic_params: &[],
2882                            modifiers: hir::TraitBoundModifiers::NONE,
2883                            trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2884                            span: self.lower_span(span),
2885                        };
2886
2887                        // The original ID is taken by the `PolyTraitRef`,
2888                        // so the `Ty` itself needs a different one.
2889                        hir_id = self.next_id();
2890                        hir::TyKind::TraitObject(
2891                            self.arena.alloc_from_iter([principal])arena_vec![self; principal],
2892                            TaggedRef::new(self.elided_dyn_bound(span), TraitObjectSyntax::None),
2893                        )
2894                    }
2895                    _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2896                }
2897            }
2898            _ => hir::TyKind::Path(qpath),
2899        };
2900
2901        hir::Ty { hir_id, kind, span: self.lower_span(span) }
2902    }
2903
2904    /// Invoked to create the lifetime argument(s) for an elided trait object
2905    /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2906    /// when the bound is written, even if it is written with `'_` like in
2907    /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2908    fn elided_dyn_bound(&mut self, span: Span) -> &'hir hir::Lifetime {
2909        let r = hir::Lifetime::new(
2910            self.next_id(),
2911            Ident::new(kw::UnderscoreLifetime, self.lower_span(span)),
2912            hir::LifetimeKind::ImplicitObjectLifetimeDefault,
2913            LifetimeSource::Other,
2914            LifetimeSyntax::Implicit,
2915        );
2916        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:2916",
                        "rustc_ast_lowering", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2916u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                        ::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!("elided_dyn_bound: r={0:?}",
                                                    r) as &dyn Value))])
            });
    } else { ; }
};debug!("elided_dyn_bound: r={:?}", r);
2917        self.arena.alloc(r)
2918    }
2919}
2920
2921/// Helper struct for the delayed construction of [`hir::GenericArgs`].
2922struct GenericArgsCtor<'hir> {
2923    args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2924    constraints: &'hir [hir::AssocItemConstraint<'hir>],
2925    parenthesized: hir::GenericArgsParentheses,
2926    span: Span,
2927}
2928
2929impl<'hir> GenericArgsCtor<'hir> {
2930    fn is_empty(&self) -> bool {
2931        self.args.is_empty()
2932            && self.constraints.is_empty()
2933            && self.parenthesized == hir::GenericArgsParentheses::No
2934    }
2935
2936    fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2937        let ga = hir::GenericArgs {
2938            args: this.arena.alloc_from_iter(self.args),
2939            constraints: self.constraints,
2940            parenthesized: self.parenthesized,
2941            span_ext: this.lower_span(self.span),
2942        };
2943        this.arena.alloc(ga)
2944    }
2945}