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#![cfg_attr(bootstrap, feature(if_let_guard))]
35#![feature(box_patterns)]
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::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
51use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId};
52use rustc_hir::definitions::{DefPathData, DisambiguatorState};
53use rustc_hir::lints::{AttributeLint, DelayedLint};
54use rustc_hir::{
55    self as hir, AngleBrackets, ConstArg, GenericArg, HirId, ItemLocalMap, LifetimeSource,
56    LifetimeSyntax, ParamName, Target, TraitCandidate, find_attr,
57};
58use rustc_index::{Idx, IndexSlice, IndexVec};
59use rustc_macros::extension;
60use rustc_middle::span_bug;
61use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
62use rustc_session::parse::add_feature_diagnostics;
63use rustc_span::symbol::{Ident, Symbol, kw, sym};
64use rustc_span::{DUMMY_SP, DesugaringKind, Span};
65use smallvec::SmallVec;
66use thin_vec::ThinVec;
67use tracing::{debug, instrument, trace};
68
69use crate::errors::{AssocTyParentheses, AssocTyParenthesesSub, MisplacedImplTrait};
70
71macro_rules! arena_vec {
72    ($this:expr; $($x:expr),*) => (
73        $this.arena.alloc_from_iter([$($x),*])
74    );
75}
76
77mod asm;
78mod block;
79mod contract;
80mod delegation;
81mod errors;
82mod expr;
83mod format;
84mod index;
85mod item;
86mod pat;
87mod path;
88pub mod stability;
89
90struct LoweringContext<'a, 'hir> {
91    tcx: TyCtxt<'hir>,
92    resolver: &'a mut ResolverAstLowering,
93    disambiguator: DisambiguatorState,
94
95    /// Used to allocate HIR nodes.
96    arena: &'hir hir::Arena<'hir>,
97
98    /// Bodies inside the owner being lowered.
99    bodies: Vec<(hir::ItemLocalId, &'hir hir::Body<'hir>)>,
100    /// `#[define_opaque]` attributes
101    define_opaque: Option<&'hir [(Span, LocalDefId)]>,
102    /// Attributes inside the owner being lowered.
103    attrs: SortedMap<hir::ItemLocalId, &'hir [hir::Attribute]>,
104    /// Collect items that were created by lowering the current owner.
105    children: Vec<(LocalDefId, hir::MaybeOwner<'hir>)>,
106
107    contract_ensures: Option<(Span, Ident, HirId)>,
108
109    coroutine_kind: Option<hir::CoroutineKind>,
110
111    /// When inside an `async` context, this is the `HirId` of the
112    /// `task_context` local bound to the resume argument of the coroutine.
113    task_context: Option<HirId>,
114
115    /// Used to get the current `fn`'s def span to point to when using `await`
116    /// outside of an `async fn`.
117    current_item: Option<Span>,
118
119    try_block_scope: TryBlockScope,
120    loop_scope: Option<HirId>,
121    is_in_loop_condition: bool,
122    is_in_dyn_type: bool,
123
124    current_hir_id_owner: hir::OwnerId,
125    item_local_id_counter: hir::ItemLocalId,
126    trait_map: ItemLocalMap<Box<[TraitCandidate]>>,
127
128    impl_trait_defs: Vec<hir::GenericParam<'hir>>,
129    impl_trait_bounds: Vec<hir::WherePredicate<'hir>>,
130
131    /// NodeIds of pattern identifiers and labelled nodes that are lowered inside the current HIR owner.
132    ident_and_label_to_local_id: NodeMap<hir::ItemLocalId>,
133    /// NodeIds that are lowered inside the current HIR owner. Only used for duplicate lowering check.
134    #[cfg(debug_assertions)]
135    node_id_to_local_id: NodeMap<hir::ItemLocalId>,
136
137    allow_contracts: Arc<[Symbol]>,
138    allow_try_trait: Arc<[Symbol]>,
139    allow_gen_future: Arc<[Symbol]>,
140    allow_pattern_type: Arc<[Symbol]>,
141    allow_async_gen: Arc<[Symbol]>,
142    allow_async_iterator: Arc<[Symbol]>,
143    allow_for_await: Arc<[Symbol]>,
144    allow_async_fn_traits: Arc<[Symbol]>,
145
146    delayed_lints: Vec<DelayedLint>,
147
148    attribute_parser: AttributeParser<'hir>,
149}
150
151impl<'a, 'hir> LoweringContext<'a, 'hir> {
152    fn new(tcx: TyCtxt<'hir>, resolver: &'a mut ResolverAstLowering) -> Self {
153        let registered_tools = tcx.registered_tools(()).iter().map(|x| x.name).collect();
154        Self {
155            // Pseudo-globals.
156            tcx,
157            resolver,
158            disambiguator: DisambiguatorState::new(),
159            arena: tcx.hir_arena,
160
161            // HirId handling.
162            bodies: Vec::new(),
163            define_opaque: None,
164            attrs: SortedMap::default(),
165            children: Vec::default(),
166            contract_ensures: None,
167            current_hir_id_owner: hir::CRATE_OWNER_ID,
168            item_local_id_counter: hir::ItemLocalId::ZERO,
169            ident_and_label_to_local_id: Default::default(),
170            #[cfg(debug_assertions)]
171            node_id_to_local_id: Default::default(),
172            trait_map: Default::default(),
173
174            // Lowering state.
175            try_block_scope: TryBlockScope::Function,
176            loop_scope: None,
177            is_in_loop_condition: false,
178            is_in_dyn_type: false,
179            coroutine_kind: None,
180            task_context: None,
181            current_item: None,
182            impl_trait_defs: Vec::new(),
183            impl_trait_bounds: Vec::new(),
184            allow_contracts: [sym::contracts_internals].into(),
185            allow_try_trait: [
186                sym::try_trait_v2,
187                sym::try_trait_v2_residual,
188                sym::yeet_desugar_details,
189            ]
190            .into(),
191            allow_pattern_type: [sym::pattern_types, sym::pattern_type_range_trait].into(),
192            allow_gen_future: if tcx.features().async_fn_track_caller() {
193                [sym::gen_future, sym::closure_track_caller].into()
194            } else {
195                [sym::gen_future].into()
196            },
197            allow_for_await: [sym::async_gen_internals, sym::async_iterator].into(),
198            allow_async_fn_traits: [sym::async_fn_traits].into(),
199            allow_async_gen: [sym::async_gen_internals].into(),
200            // FIXME(gen_blocks): how does `closure_track_caller`/`async_fn_track_caller`
201            // interact with `gen`/`async gen` blocks
202            allow_async_iterator: [sym::gen_future, sym::async_iterator].into(),
203
204            attribute_parser: AttributeParser::new(
205                tcx.sess,
206                tcx.features(),
207                registered_tools,
208                Late,
209            ),
210            delayed_lints: Vec::new(),
211        }
212    }
213
214    pub(crate) fn dcx(&self) -> DiagCtxtHandle<'hir> {
215        self.tcx.dcx()
216    }
217}
218
219struct SpanLowerer {
220    is_incremental: bool,
221    def_id: LocalDefId,
222}
223
224impl SpanLowerer {
225    fn lower(&self, span: Span) -> Span {
226        if self.is_incremental {
227            span.with_parent(Some(self.def_id))
228        } else {
229            // Do not make spans relative when not using incremental compilation.
230            span
231        }
232    }
233}
234
235impl 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; }
        {

                #[allow(deprecated)]
                {
                    {
                        'done:
                            {
                            for i in tcx.get_all_attrs(def_id) {
                                #[allow(unused_imports)]
                                use rustc_hir::attrs::AttributeKind::*;
                                let i: &rustc_hir::Attribute = i;
                                match i {
                                    rustc_hir::Attribute::Parsed(RustcLegacyConstGenerics {
                                        fn_indexes, .. }) => {
                                        break 'done Some(fn_indexes);
                                    }
                                    rustc_hir::Attribute::Unparsed(..) =>
                                        {}
                                        #[deny(unreachable_patterns)]
                                        _ => {}
                                }
                            }
                            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)]
236impl ResolverAstLowering {
237    fn legacy_const_generic_args(&self, expr: &Expr, tcx: TyCtxt<'_>) -> Option<Vec<usize>> {
238        let ExprKind::Path(None, path) = &expr.kind else {
239            return None;
240        };
241
242        // Don't perform legacy const generics rewriting if the path already
243        // has generic arguments.
244        if path.segments.last().unwrap().args.is_some() {
245            return None;
246        }
247
248        let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
249
250        // We only support cross-crate argument rewriting. Uses
251        // within the same crate should be updated to use the new
252        // const generics style.
253        if def_id.is_local() {
254            return None;
255        }
256
257        // we can use parsed attrs here since for other crates they're already available
258        find_attr!(
259            tcx, def_id,
260            RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
261        )
262        .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
263    }
264
265    fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
266        self.partial_res_map.get(&id).copied()
267    }
268
269    /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
270    fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
271        self.import_res_map.get(&id).copied().unwrap_or_default()
272    }
273
274    /// Obtains resolution for a label with the given `NodeId`.
275    fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
276        self.label_res_map.get(&id).copied()
277    }
278
279    /// Obtains resolution for a lifetime with the given `NodeId`.
280    fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
281        self.lifetimes_res_map.get(&id).copied()
282    }
283
284    /// Obtain the list of lifetimes parameters to add to an item.
285    ///
286    /// Extra lifetime parameters should only be added in places that can appear
287    /// as a `binder` in `LifetimeRes`.
288    ///
289    /// The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring
290    /// should appear at the enclosing `PolyTraitRef`.
291    fn extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> {
292        self.extra_lifetime_params_map.get(&id).cloned().unwrap_or_default()
293    }
294}
295
296/// How relaxed bounds `?Trait` should be treated.
297///
298/// Relaxed bounds should only be allowed in places where we later
299/// (namely during HIR ty lowering) perform *sized elaboration*.
300#[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)]
301enum RelaxedBoundPolicy<'a> {
302    Allowed,
303    AllowedIfOnTyParam(NodeId, &'a [ast::GenericParam]),
304    Forbidden(RelaxedBoundForbiddenReason),
305}
306
307#[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)]
308enum RelaxedBoundForbiddenReason {
309    TraitObjectTy,
310    SuperTrait,
311    TraitAlias,
312    AssocTyBounds,
313    LateBoundVarsInScope,
314}
315
316/// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
317/// and if so, what meaning it has.
318#[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 {
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<hir::OpaqueTyOrigin<LocalDefId>>;
        let _: ::core::cmp::AssertParamIsEq<ImplTraitPosition>;
        let _: ::core::cmp::AssertParamIsEq<Symbol>;
    }
}Eq)]
319enum ImplTraitContext {
320    /// Treat `impl Trait` as shorthand for a new universal generic parameter.
321    /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
322    /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
323    ///
324    /// Newly generated parameters should be inserted into the given `Vec`.
325    Universal,
326
327    /// Treat `impl Trait` as shorthand for a new opaque type.
328    /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
329    /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
330    ///
331    OpaqueTy { origin: hir::OpaqueTyOrigin<LocalDefId> },
332
333    /// Treat `impl Trait` as a "trait ascription", which is like a type
334    /// variable but that also enforces that a set of trait goals hold.
335    ///
336    /// This is useful to guide inference for unnameable types.
337    InBinding,
338
339    /// `impl Trait` is unstably accepted in this position.
340    FeatureGated(ImplTraitPosition, Symbol),
341    /// `impl Trait` is not accepted in this position.
342    Disallowed(ImplTraitPosition),
343}
344
345/// Position in which `impl Trait` is disallowed.
346#[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 {
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
347enum ImplTraitPosition {
348    Path,
349    Variable,
350    Trait,
351    Bound,
352    Generic,
353    ExternFnParam,
354    ClosureParam,
355    PointerParam,
356    FnTraitParam,
357    ExternFnReturn,
358    ClosureReturn,
359    PointerReturn,
360    FnTraitReturn,
361    GenericDefault,
362    ConstTy,
363    StaticTy,
364    AssocTy,
365    FieldTy,
366    Cast,
367    ImplSelf,
368    OffsetOf,
369}
370
371impl std::fmt::Display for ImplTraitPosition {
372    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373        let name = match self {
374            ImplTraitPosition::Path => "paths",
375            ImplTraitPosition::Variable => "the type of variable bindings",
376            ImplTraitPosition::Trait => "traits",
377            ImplTraitPosition::Bound => "bounds",
378            ImplTraitPosition::Generic => "generics",
379            ImplTraitPosition::ExternFnParam => "`extern fn` parameters",
380            ImplTraitPosition::ClosureParam => "closure parameters",
381            ImplTraitPosition::PointerParam => "`fn` pointer parameters",
382            ImplTraitPosition::FnTraitParam => "the parameters of `Fn` trait bounds",
383            ImplTraitPosition::ExternFnReturn => "`extern fn` return types",
384            ImplTraitPosition::ClosureReturn => "closure return types",
385            ImplTraitPosition::PointerReturn => "`fn` pointer return types",
386            ImplTraitPosition::FnTraitReturn => "the return type of `Fn` trait bounds",
387            ImplTraitPosition::GenericDefault => "generic parameter defaults",
388            ImplTraitPosition::ConstTy => "const types",
389            ImplTraitPosition::StaticTy => "static types",
390            ImplTraitPosition::AssocTy => "associated types",
391            ImplTraitPosition::FieldTy => "field types",
392            ImplTraitPosition::Cast => "cast expression types",
393            ImplTraitPosition::ImplSelf => "impl headers",
394            ImplTraitPosition::OffsetOf => "`offset_of!` parameters",
395        };
396
397        f.write_fmt(format_args!("{0}", name))write!(f, "{name}")
398    }
399}
400
401#[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 {
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
402enum FnDeclKind {
403    Fn,
404    Inherent,
405    ExternFn,
406    Closure,
407    Pointer,
408    Trait,
409    Impl,
410}
411
412#[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)]
413enum AstOwner<'a> {
414    NonOwner,
415    Crate(&'a ast::Crate),
416    Item(&'a ast::Item),
417    AssocItem(&'a ast::AssocItem, visit::AssocCtxt),
418    ForeignItem(&'a ast::ForeignItem),
419}
420
421#[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)]
422enum TryBlockScope {
423    /// There isn't a `try` block, so a `?` will use `return`.
424    Function,
425    /// We're inside a `try { … }` block, so a `?` will block-break
426    /// from that block using a type depending only on the argument.
427    Homogeneous(HirId),
428    /// We're inside a `try as _ { … }` block, so a `?` will block-break
429    /// from that block using the type specified.
430    Heterogeneous(HirId),
431}
432
433fn index_crate<'a>(
434    node_id_to_def_id: &NodeMap<LocalDefId>,
435    krate: &'a Crate,
436) -> IndexVec<LocalDefId, AstOwner<'a>> {
437    let mut indexer = Indexer { node_id_to_def_id, index: IndexVec::new() };
438    *indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner) =
439        AstOwner::Crate(krate);
440    visit::walk_crate(&mut indexer, krate);
441    return indexer.index;
442
443    struct Indexer<'s, 'a> {
444        node_id_to_def_id: &'s NodeMap<LocalDefId>,
445        index: IndexVec<LocalDefId, AstOwner<'a>>,
446    }
447
448    impl<'a> visit::Visitor<'a> for Indexer<'_, 'a> {
449        fn visit_attribute(&mut self, _: &'a Attribute) {
450            // We do not want to lower expressions that appear in attributes,
451            // as they are not accessible to the rest of the HIR.
452        }
453
454        fn visit_item(&mut self, item: &'a ast::Item) {
455            let def_id = self.node_id_to_def_id[&item.id];
456            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) = AstOwner::Item(item);
457            visit::walk_item(self, item)
458        }
459
460        fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) {
461            let def_id = self.node_id_to_def_id[&item.id];
462            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) =
463                AstOwner::AssocItem(item, ctxt);
464            visit::walk_assoc_item(self, item, ctxt);
465        }
466
467        fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) {
468            let def_id = self.node_id_to_def_id[&item.id];
469            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) =
470                AstOwner::ForeignItem(item);
471            visit::walk_item(self, item);
472        }
473    }
474}
475
476/// Compute the hash for the HIR of the full crate.
477/// This hash will then be part of the crate_hash which is stored in the metadata.
478fn compute_hir_hash(
479    tcx: TyCtxt<'_>,
480    owners: &IndexSlice<LocalDefId, hir::MaybeOwner<'_>>,
481) -> Fingerprint {
482    let mut hir_body_nodes: Vec<_> = owners
483        .iter_enumerated()
484        .filter_map(|(def_id, info)| {
485            let info = info.as_owner()?;
486            let def_path_hash = tcx.hir_def_path_hash(def_id);
487            Some((def_path_hash, info))
488        })
489        .collect();
490    hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
491
492    tcx.with_stable_hashing_context(|mut hcx| {
493        let mut stable_hasher = StableHasher::new();
494        hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher);
495        stable_hasher.finish()
496    })
497}
498
499pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> hir::Crate<'_> {
500    let sess = tcx.sess;
501    // Queries that borrow `resolver_for_lowering`.
502    tcx.ensure_done().output_filenames(());
503    tcx.ensure_done().early_lint_checks(());
504    tcx.ensure_done().debugger_visualizers(LOCAL_CRATE);
505    tcx.ensure_done().get_lang_items(());
506    let (mut resolver, krate) = tcx.resolver_for_lowering().steal();
507
508    let ast_index = index_crate(&resolver.node_id_to_def_id, &krate);
509    let mut owners = IndexVec::from_fn_n(
510        |_| hir::MaybeOwner::Phantom,
511        tcx.definitions_untracked().def_index_count(),
512    );
513
514    let mut lowerer = item::ItemLowerer {
515        tcx,
516        resolver: &mut resolver,
517        ast_index: &ast_index,
518        owners: &mut owners,
519    };
520    for def_id in ast_index.indices() {
521        lowerer.lower_node(def_id);
522    }
523
524    drop(ast_index);
525
526    // Drop AST to free memory. It can be expensive so try to drop it on a separate thread.
527    let prof = sess.prof.clone();
528    spawn(move || {
529        let _timer = prof.verbose_generic_activity("drop_ast");
530        drop(krate);
531    });
532
533    // Don't hash unless necessary, because it's expensive.
534    let opt_hir_hash =
535        if tcx.needs_crate_hash() { Some(compute_hir_hash(tcx, &owners)) } else { None };
536    hir::Crate { owners, opt_hir_hash }
537}
538
539#[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)]
540enum ParamMode {
541    /// Any path in a type context.
542    Explicit,
543    /// The `module::Type` in `module::Type::method` in an expression.
544    Optional,
545}
546
547#[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)]
548enum AllowReturnTypeNotation {
549    /// Only in types, since RTN is denied later during HIR lowering.
550    Yes,
551    /// All other positions (path expr, method, use tree).
552    No,
553}
554
555enum GenericArgsMode {
556    /// Allow paren sugar, don't allow RTN.
557    ParenSugar,
558    /// Allow RTN, don't allow paren sugar.
559    ReturnTypeNotation,
560    // Error if parenthesized generics or RTN are encountered.
561    Err,
562    /// Silence errors when lowering generics. Only used with `Res::Err`.
563    Silence,
564}
565
566impl<'a, 'hir> LoweringContext<'a, 'hir> {
567    fn create_def(
568        &mut self,
569        node_id: ast::NodeId,
570        name: Option<Symbol>,
571        def_kind: DefKind,
572        def_path_data: DefPathData,
573        span: Span,
574    ) -> LocalDefId {
575        let parent = self.current_hir_id_owner.def_id;
576        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);
577        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!(
578            self.opt_local_def_id(node_id).is_none(),
579            "adding a def'n for node-id {:?} and def kind {:?} but a previous def'n exists: {:?}",
580            node_id,
581            def_kind,
582            self.tcx.hir_def_key(self.local_def_id(node_id)),
583        );
584
585        let def_id = self
586            .tcx
587            .at(span)
588            .create_def(parent, name, def_kind, Some(def_path_data), &mut self.disambiguator)
589            .def_id();
590
591        {
    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:591",
                        "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(591u32),
                        ::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);
592        self.resolver.node_id_to_def_id.insert(node_id, def_id);
593
594        def_id
595    }
596
597    fn next_node_id(&mut self) -> NodeId {
598        let start = self.resolver.next_node_id;
599        let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
600        self.resolver.next_node_id = ast::NodeId::from_u32(next);
601        start
602    }
603
604    /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
605    /// resolver (if any).
606    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
607        self.resolver.node_id_to_def_id.get(&node).copied()
608    }
609
610    fn local_def_id(&self, node: NodeId) -> LocalDefId {
611        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:?}`"))
612    }
613
614    /// Given the id of an owner node in the AST, returns the corresponding `OwnerId`.
615    fn owner_id(&self, node: NodeId) -> hir::OwnerId {
616        hir::OwnerId { def_id: self.local_def_id(node) }
617    }
618
619    /// Freshen the `LoweringContext` and ready it to lower a nested item.
620    /// The lowered item is registered into `self.children`.
621    ///
622    /// This function sets up `HirId` lowering infrastructure,
623    /// and stashes the shared mutable state to avoid pollution by the closure.
624    #[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(624u32),
                                    ::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))]
625    fn with_hir_id_owner(
626        &mut self,
627        owner: NodeId,
628        f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
629    ) {
630        let owner_id = self.owner_id(owner);
631
632        let current_attrs = std::mem::take(&mut self.attrs);
633        let current_bodies = std::mem::take(&mut self.bodies);
634        let current_define_opaque = std::mem::take(&mut self.define_opaque);
635        let current_ident_and_label_to_local_id =
636            std::mem::take(&mut self.ident_and_label_to_local_id);
637
638        #[cfg(debug_assertions)]
639        let current_node_id_to_local_id = std::mem::take(&mut self.node_id_to_local_id);
640        let current_trait_map = std::mem::take(&mut self.trait_map);
641        let current_owner = std::mem::replace(&mut self.current_hir_id_owner, owner_id);
642        let current_local_counter =
643            std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
644        let current_impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
645        let current_impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
646        let current_delayed_lints = std::mem::take(&mut self.delayed_lints);
647
648        // Do not reset `next_node_id` and `node_id_to_def_id`:
649        // we want `f` to be able to refer to the `LocalDefId`s that the caller created.
650        // and the caller to refer to some of the subdefinitions' nodes' `LocalDefId`s.
651
652        // Always allocate the first `HirId` for the owner itself.
653        #[cfg(debug_assertions)]
654        {
655            let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::ZERO);
656            debug_assert_eq!(_old, None);
657        }
658
659        let item = f(self);
660        assert_eq!(owner_id, item.def_id());
661        // `f` should have consumed all the elements in these vectors when constructing `item`.
662        assert!(self.impl_trait_defs.is_empty());
663        assert!(self.impl_trait_bounds.is_empty());
664        let info = self.make_owner_info(item);
665
666        self.attrs = current_attrs;
667        self.bodies = current_bodies;
668        self.define_opaque = current_define_opaque;
669        self.ident_and_label_to_local_id = current_ident_and_label_to_local_id;
670
671        #[cfg(debug_assertions)]
672        {
673            self.node_id_to_local_id = current_node_id_to_local_id;
674        }
675        self.trait_map = current_trait_map;
676        self.current_hir_id_owner = current_owner;
677        self.item_local_id_counter = current_local_counter;
678        self.impl_trait_defs = current_impl_trait_defs;
679        self.impl_trait_bounds = current_impl_trait_bounds;
680        self.delayed_lints = current_delayed_lints;
681
682        debug_assert!(!self.children.iter().any(|(id, _)| id == &owner_id.def_id));
683        self.children.push((owner_id.def_id, hir::MaybeOwner::Owner(info)));
684    }
685
686    fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> {
687        let attrs = std::mem::take(&mut self.attrs);
688        let mut bodies = std::mem::take(&mut self.bodies);
689        let define_opaque = std::mem::take(&mut self.define_opaque);
690        let trait_map = std::mem::take(&mut self.trait_map);
691        let delayed_lints = std::mem::take(&mut self.delayed_lints).into_boxed_slice();
692
693        #[cfg(debug_assertions)]
694        for (id, attrs) in attrs.iter() {
695            // Verify that we do not store empty slices in the map.
696            if attrs.is_empty() {
697                {
    ::core::panicking::panic_fmt(format_args!("Stored empty attributes for {0:?}",
            id));
};panic!("Stored empty attributes for {:?}", id);
698            }
699        }
700
701        bodies.sort_by_key(|(k, _)| *k);
702        let bodies = SortedMap::from_presorted_elements(bodies);
703
704        // Don't hash unless necessary, because it's expensive.
705        let rustc_middle::hir::Hashes { opt_hash_including_bodies, attrs_hash, delayed_lints_hash } =
706            self.tcx.hash_owner_nodes(node, &bodies, &attrs, &delayed_lints, define_opaque);
707        let num_nodes = self.item_local_id_counter.as_usize();
708        let (nodes, parenting) = index::index_hir(self.tcx, node, &bodies, num_nodes);
709        let nodes = hir::OwnerNodes { opt_hash_including_bodies, nodes, bodies };
710        let attrs = hir::AttributeMap { map: attrs, opt_hash: attrs_hash, define_opaque };
711        let delayed_lints =
712            hir::lints::DelayedLints { lints: delayed_lints, opt_hash: delayed_lints_hash };
713
714        self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map, delayed_lints })
715    }
716
717    /// This method allocates a new `HirId` for the given `NodeId`.
718    /// Take care not to call this method if the resulting `HirId` is then not
719    /// actually used in the HIR, as that would trigger an assertion in the
720    /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
721    /// properly. Calling the method twice with the same `NodeId` is also forbidden.
722    x;#[instrument(level = "debug", skip(self), ret)]
723    fn lower_node_id(&mut self, ast_node_id: NodeId) -> HirId {
724        assert_ne!(ast_node_id, DUMMY_NODE_ID);
725
726        let owner = self.current_hir_id_owner;
727        let local_id = self.item_local_id_counter;
728        assert_ne!(local_id, hir::ItemLocalId::ZERO);
729        self.item_local_id_counter.increment_by(1);
730        let hir_id = HirId { owner, local_id };
731
732        if let Some(def_id) = self.opt_local_def_id(ast_node_id) {
733            self.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id)));
734        }
735
736        if let Some(traits) = self.resolver.trait_map.remove(&ast_node_id) {
737            self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice());
738        }
739
740        // Check whether the same `NodeId` is lowered more than once.
741        #[cfg(debug_assertions)]
742        {
743            let old = self.node_id_to_local_id.insert(ast_node_id, local_id);
744            assert_eq!(old, None);
745        }
746
747        hir_id
748    }
749
750    /// Generate a new `HirId` without a backing `NodeId`.
751    x;#[instrument(level = "debug", skip(self), ret)]
752    fn next_id(&mut self) -> HirId {
753        let owner = self.current_hir_id_owner;
754        let local_id = self.item_local_id_counter;
755        assert_ne!(local_id, hir::ItemLocalId::ZERO);
756        self.item_local_id_counter.increment_by(1);
757        HirId { owner, local_id }
758    }
759
760    #[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(760u32),
                                    ::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:767",
                                    "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(767u32),
                                    ::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))]
761    fn lower_res(&mut self, res: Res<NodeId>) -> Res {
762        let res: Result<Res, ()> = res.apply_id(|id| {
763            let owner = self.current_hir_id_owner;
764            let local_id = self.ident_and_label_to_local_id.get(&id).copied().ok_or(())?;
765            Ok(HirId { owner, local_id })
766        });
767        trace!(?res);
768
769        // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
770        // This can happen when trying to lower the return type `x` in erroneous code like
771        //   async fn foo(x: u8) -> x {}
772        // In that case, `x` is lowered as a function parameter, and the return type is lowered as
773        // an opaque type as a synthesized HIR owner.
774        res.unwrap_or(Res::Err)
775    }
776
777    fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
778        self.resolver.get_partial_res(id).map_or(Res::Err, |pr| pr.expect_full_res())
779    }
780
781    fn lower_import_res(&mut self, id: NodeId, span: Span) -> PerNS<Option<Res>> {
782        let per_ns = self.resolver.get_import_res(id);
783        let per_ns = per_ns.map(|res| res.map(|res| self.lower_res(res)));
784        if per_ns.is_empty() {
785            // Propagate the error to all namespaces, just to be sure.
786            self.dcx().span_delayed_bug(span, "no resolution for an import");
787            let err = Some(Res::Err);
788            return PerNS { type_ns: err, value_ns: err, macro_ns: err };
789        }
790        per_ns
791    }
792
793    fn make_lang_item_qpath(
794        &mut self,
795        lang_item: hir::LangItem,
796        span: Span,
797        args: Option<&'hir hir::GenericArgs<'hir>>,
798    ) -> hir::QPath<'hir> {
799        hir::QPath::Resolved(None, self.make_lang_item_path(lang_item, span, args))
800    }
801
802    fn make_lang_item_path(
803        &mut self,
804        lang_item: hir::LangItem,
805        span: Span,
806        args: Option<&'hir hir::GenericArgs<'hir>>,
807    ) -> &'hir hir::Path<'hir> {
808        let def_id = self.tcx.require_lang_item(lang_item, span);
809        let def_kind = self.tcx.def_kind(def_id);
810        let res = Res::Def(def_kind, def_id);
811        self.arena.alloc(hir::Path {
812            span,
813            res,
814            segments: self.arena.alloc_from_iter([hir::PathSegment {
815                ident: Ident::new(lang_item.name(), span),
816                hir_id: self.next_id(),
817                res,
818                args,
819                infer_args: args.is_none(),
820            }]),
821        })
822    }
823
824    /// Reuses the span but adds information like the kind of the desugaring and features that are
825    /// allowed inside this span.
826    fn mark_span_with_reason(
827        &self,
828        reason: DesugaringKind,
829        span: Span,
830        allow_internal_unstable: Option<Arc<[Symbol]>>,
831    ) -> Span {
832        self.tcx.with_stable_hashing_context(|hcx| {
833            span.mark_with_reason(allow_internal_unstable, reason, span.edition(), hcx)
834        })
835    }
836
837    fn span_lowerer(&self) -> SpanLowerer {
838        SpanLowerer {
839            is_incremental: self.tcx.sess.opts.incremental.is_some(),
840            def_id: self.current_hir_id_owner.def_id,
841        }
842    }
843
844    /// Intercept all spans entering HIR.
845    /// Mark a span as relative to the current owning item.
846    fn lower_span(&self, span: Span) -> Span {
847        self.span_lowerer().lower(span)
848    }
849
850    fn lower_ident(&self, ident: Ident) -> Ident {
851        Ident::new(ident.name, self.lower_span(ident.span))
852    }
853
854    /// Converts a lifetime into a new generic parameter.
855    #[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(855u32),
                                    ::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:876",
                                                "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(876u32),
                                                ::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))]
856    fn lifetime_res_to_generic_param(
857        &mut self,
858        ident: Ident,
859        node_id: NodeId,
860        res: LifetimeRes,
861        source: hir::GenericParamSource,
862    ) -> Option<hir::GenericParam<'hir>> {
863        let (name, kind) = match res {
864            LifetimeRes::Param { .. } => {
865                (hir::ParamName::Plain(ident), hir::LifetimeParamKind::Explicit)
866            }
867            LifetimeRes::Fresh { param, kind, .. } => {
868                // Late resolution delegates to us the creation of the `LocalDefId`.
869                let _def_id = self.create_def(
870                    param,
871                    Some(kw::UnderscoreLifetime),
872                    DefKind::LifetimeParam,
873                    DefPathData::DesugaredAnonymousLifetime,
874                    ident.span,
875                );
876                debug!(?_def_id);
877
878                (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided(kind))
879            }
880            LifetimeRes::Static { .. } | LifetimeRes::Error(..) => return None,
881            res => panic!(
882                "Unexpected lifetime resolution {:?} for {:?} at {:?}",
883                res, ident, ident.span
884            ),
885        };
886        let hir_id = self.lower_node_id(node_id);
887        let def_id = self.local_def_id(node_id);
888        Some(hir::GenericParam {
889            hir_id,
890            def_id,
891            name,
892            span: self.lower_span(ident.span),
893            pure_wrt_drop: false,
894            kind: hir::GenericParamKind::Lifetime { kind },
895            colon_span: None,
896            source,
897        })
898    }
899
900    /// Lowers a lifetime binder that defines `generic_params`, returning the corresponding HIR
901    /// nodes. The returned list includes any "extra" lifetime parameters that were added by the
902    /// name resolver owing to lifetime elision; this also populates the resolver's node-id->def-id
903    /// map, so that later calls to `opt_node_id_to_def_id` that refer to these extra lifetime
904    /// parameters will be successful.
905    x;#[instrument(level = "debug", skip(self), ret)]
906    #[inline]
907    fn lower_lifetime_binder(
908        &mut self,
909        binder: NodeId,
910        generic_params: &[GenericParam],
911    ) -> &'hir [hir::GenericParam<'hir>] {
912        // Start by creating params for extra lifetimes params, as this creates the definitions
913        // that may be referred to by the AST inside `generic_params`.
914        let extra_lifetimes = self.resolver.extra_lifetime_params(binder);
915        debug!(?extra_lifetimes);
916        let extra_lifetimes: Vec<_> = extra_lifetimes
917            .into_iter()
918            .filter_map(|(ident, node_id, res)| {
919                self.lifetime_res_to_generic_param(
920                    ident,
921                    node_id,
922                    res,
923                    hir::GenericParamSource::Binder,
924                )
925            })
926            .collect();
927        let arena = self.arena;
928        let explicit_generic_params =
929            self.lower_generic_params_mut(generic_params, hir::GenericParamSource::Binder);
930        arena.alloc_from_iter(explicit_generic_params.chain(extra_lifetimes.into_iter()))
931    }
932
933    fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
934        let was_in_dyn_type = self.is_in_dyn_type;
935        self.is_in_dyn_type = in_scope;
936
937        let result = f(self);
938
939        self.is_in_dyn_type = was_in_dyn_type;
940
941        result
942    }
943
944    fn with_new_scopes<T>(&mut self, scope_span: Span, f: impl FnOnce(&mut Self) -> T) -> T {
945        let current_item = self.current_item;
946        self.current_item = Some(scope_span);
947
948        let was_in_loop_condition = self.is_in_loop_condition;
949        self.is_in_loop_condition = false;
950
951        let old_contract = self.contract_ensures.take();
952
953        let try_block_scope = mem::replace(&mut self.try_block_scope, TryBlockScope::Function);
954        let loop_scope = self.loop_scope.take();
955        let ret = f(self);
956        self.try_block_scope = try_block_scope;
957        self.loop_scope = loop_scope;
958
959        self.contract_ensures = old_contract;
960
961        self.is_in_loop_condition = was_in_loop_condition;
962
963        self.current_item = current_item;
964
965        ret
966    }
967
968    fn lower_attrs(
969        &mut self,
970        id: HirId,
971        attrs: &[Attribute],
972        target_span: Span,
973        target: Target,
974    ) -> &'hir [hir::Attribute] {
975        self.lower_attrs_with_extra(id, attrs, target_span, target, &[])
976    }
977
978    fn lower_attrs_with_extra(
979        &mut self,
980        id: HirId,
981        attrs: &[Attribute],
982        target_span: Span,
983        target: Target,
984        extra_hir_attributes: &[hir::Attribute],
985    ) -> &'hir [hir::Attribute] {
986        if attrs.is_empty() && extra_hir_attributes.is_empty() {
987            &[]
988        } else {
989            let mut lowered_attrs =
990                self.lower_attrs_vec(attrs, self.lower_span(target_span), id, target);
991            lowered_attrs.extend(extra_hir_attributes.iter().cloned());
992
993            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);
994            let ret = self.arena.alloc_from_iter(lowered_attrs);
995
996            // this is possible if an item contained syntactical attribute,
997            // but none of them parse successfully or all of them were ignored
998            // for not being built-in attributes at all. They could be remaining
999            // unexpanded attributes used as markers in proc-macro derives for example.
1000            // This will have emitted some diagnostics for the misparse, but will then
1001            // not emit the attribute making the list empty.
1002            if ret.is_empty() {
1003                &[]
1004            } else {
1005                self.attrs.insert(id.local_id, ret);
1006                ret
1007            }
1008        }
1009    }
1010
1011    fn lower_attrs_vec(
1012        &mut self,
1013        attrs: &[Attribute],
1014        target_span: Span,
1015        target_hir_id: HirId,
1016        target: Target,
1017    ) -> Vec<hir::Attribute> {
1018        let l = self.span_lowerer();
1019        self.attribute_parser.parse_attribute_list(
1020            attrs,
1021            target_span,
1022            target,
1023            OmitDoc::Lower,
1024            |s| l.lower(s),
1025            |lint_id, span, kind| {
1026                self.delayed_lints.push(DelayedLint::AttributeParsing(AttributeLint {
1027                    lint_id,
1028                    id: target_hir_id,
1029                    span,
1030                    kind,
1031                }));
1032            },
1033        )
1034    }
1035
1036    fn alias_attrs(&mut self, id: HirId, target_id: HirId) {
1037        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);
1038        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);
1039        if let Some(&a) = self.attrs.get(&target_id.local_id) {
1040            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
1041            self.attrs.insert(id.local_id, a);
1042        }
1043    }
1044
1045    fn lower_delim_args(&self, args: &DelimArgs) -> DelimArgs {
1046        args.clone()
1047    }
1048
1049    /// Lower an associated item constraint.
1050    #[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(1050u32),
                                    ::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:1056",
                                    "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(1056u32),
                                    ::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)]
1051    fn lower_assoc_item_constraint(
1052        &mut self,
1053        constraint: &AssocItemConstraint,
1054        itctx: ImplTraitContext,
1055    ) -> hir::AssocItemConstraint<'hir> {
1056        debug!(?constraint, ?itctx);
1057        // Lower the generic arguments for the associated item.
1058        let gen_args = if let Some(gen_args) = &constraint.gen_args {
1059            let gen_args_ctor = match gen_args {
1060                GenericArgs::AngleBracketed(data) => {
1061                    self.lower_angle_bracketed_parameter_data(data, ParamMode::Explicit, itctx).0
1062                }
1063                GenericArgs::Parenthesized(data) => {
1064                    if let Some(first_char) = constraint.ident.as_str().chars().next()
1065                        && first_char.is_ascii_lowercase()
1066                    {
1067                        let err = match (&data.inputs[..], &data.output) {
1068                            ([_, ..], FnRetTy::Default(_)) => {
1069                                errors::BadReturnTypeNotation::Inputs { span: data.inputs_span }
1070                            }
1071                            ([], FnRetTy::Default(_)) => {
1072                                errors::BadReturnTypeNotation::NeedsDots { span: data.inputs_span }
1073                            }
1074                            // The case `T: Trait<method(..) -> Ret>` is handled in the parser.
1075                            (_, FnRetTy::Ty(ty)) => {
1076                                let span = data.inputs_span.shrink_to_hi().to(ty.span);
1077                                errors::BadReturnTypeNotation::Output {
1078                                    span,
1079                                    suggestion: errors::RTNSuggestion {
1080                                        output: span,
1081                                        input: data.inputs_span,
1082                                    },
1083                                }
1084                            }
1085                        };
1086                        let mut err = self.dcx().create_err(err);
1087                        if !self.tcx.features().return_type_notation()
1088                            && self.tcx.sess.is_nightly_build()
1089                        {
1090                            add_feature_diagnostics(
1091                                &mut err,
1092                                &self.tcx.sess,
1093                                sym::return_type_notation,
1094                            );
1095                        }
1096                        err.emit();
1097                        GenericArgsCtor {
1098                            args: Default::default(),
1099                            constraints: &[],
1100                            parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
1101                            span: data.span,
1102                        }
1103                    } else {
1104                        self.emit_bad_parenthesized_trait_in_assoc_ty(data);
1105                        // FIXME(return_type_notation): we could issue a feature error
1106                        // if the parens are empty and there's no return type.
1107                        self.lower_angle_bracketed_parameter_data(
1108                            &data.as_angle_bracketed_args(),
1109                            ParamMode::Explicit,
1110                            itctx,
1111                        )
1112                        .0
1113                    }
1114                }
1115                GenericArgs::ParenthesizedElided(span) => GenericArgsCtor {
1116                    args: Default::default(),
1117                    constraints: &[],
1118                    parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
1119                    span: *span,
1120                },
1121            };
1122            gen_args_ctor.into_generic_args(self)
1123        } else {
1124            self.arena.alloc(hir::GenericArgs::none())
1125        };
1126        let kind = match &constraint.kind {
1127            AssocItemConstraintKind::Equality { term } => {
1128                let term = match term {
1129                    Term::Ty(ty) => self.lower_ty_alloc(ty, itctx).into(),
1130                    Term::Const(c) => self.lower_anon_const_to_const_arg_and_alloc(c).into(),
1131                };
1132                hir::AssocItemConstraintKind::Equality { term }
1133            }
1134            AssocItemConstraintKind::Bound { bounds } => {
1135                // Disallow ATB in dyn types
1136                if self.is_in_dyn_type {
1137                    let suggestion = match itctx {
1138                        ImplTraitContext::OpaqueTy { .. } | ImplTraitContext::Universal => {
1139                            let bound_end_span = constraint
1140                                .gen_args
1141                                .as_ref()
1142                                .map_or(constraint.ident.span, |args| args.span());
1143                            if bound_end_span.eq_ctxt(constraint.span) {
1144                                Some(self.tcx.sess.source_map().next_point(bound_end_span))
1145                            } else {
1146                                None
1147                            }
1148                        }
1149                        _ => None,
1150                    };
1151
1152                    let guar = self.dcx().emit_err(errors::MisplacedAssocTyBinding {
1153                        span: constraint.span,
1154                        suggestion,
1155                    });
1156                    let err_ty =
1157                        &*self.arena.alloc(self.ty(constraint.span, hir::TyKind::Err(guar)));
1158                    hir::AssocItemConstraintKind::Equality { term: err_ty.into() }
1159                } else {
1160                    let bounds = self.lower_param_bounds(
1161                        bounds,
1162                        RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::AssocTyBounds),
1163                        itctx,
1164                    );
1165                    hir::AssocItemConstraintKind::Bound { bounds }
1166                }
1167            }
1168        };
1169
1170        hir::AssocItemConstraint {
1171            hir_id: self.lower_node_id(constraint.id),
1172            ident: self.lower_ident(constraint.ident),
1173            gen_args,
1174            kind,
1175            span: self.lower_span(constraint.span),
1176        }
1177    }
1178
1179    fn emit_bad_parenthesized_trait_in_assoc_ty(&self, data: &ParenthesizedArgs) {
1180        // Suggest removing empty parentheses: "Trait()" -> "Trait"
1181        let sub = if data.inputs.is_empty() {
1182            let parentheses_span =
1183                data.inputs_span.shrink_to_lo().to(data.inputs_span.shrink_to_hi());
1184            AssocTyParenthesesSub::Empty { parentheses_span }
1185        }
1186        // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
1187        else {
1188            // Start of parameters to the 1st argument
1189            let open_param = data.inputs_span.shrink_to_lo().to(data
1190                .inputs
1191                .first()
1192                .unwrap()
1193                .span
1194                .shrink_to_lo());
1195            // End of last argument to end of parameters
1196            let close_param =
1197                data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi());
1198            AssocTyParenthesesSub::NotEmpty { open_param, close_param }
1199        };
1200        self.dcx().emit_err(AssocTyParentheses { span: data.span, sub });
1201    }
1202
1203    #[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(1203u32),
                                    ::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:1241",
                                                            "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(1241u32),
                                                            ::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))]
1204    fn lower_generic_arg(
1205        &mut self,
1206        arg: &ast::GenericArg,
1207        itctx: ImplTraitContext,
1208    ) -> hir::GenericArg<'hir> {
1209        match arg {
1210            ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(
1211                lt,
1212                LifetimeSource::Path { angle_brackets: hir::AngleBrackets::Full },
1213                lt.ident.into(),
1214            )),
1215            ast::GenericArg::Type(ty) => {
1216                // We cannot just match on `TyKind::Infer` as `(_)` is represented as
1217                // `TyKind::Paren(TyKind::Infer)` and should also be lowered to `GenericArg::Infer`
1218                if ty.is_maybe_parenthesised_infer() {
1219                    return GenericArg::Infer(hir::InferArg {
1220                        hir_id: self.lower_node_id(ty.id),
1221                        span: self.lower_span(ty.span),
1222                    });
1223                }
1224
1225                match &ty.kind {
1226                    // We parse const arguments as path types as we cannot distinguish them during
1227                    // parsing. We try to resolve that ambiguity by attempting resolution in both the
1228                    // type and value namespaces. If we resolved the path in the value namespace, we
1229                    // transform it into a generic const argument.
1230                    //
1231                    // FIXME: Should we be handling `(PATH_TO_CONST)`?
1232                    TyKind::Path(None, path) => {
1233                        if let Some(res) = self
1234                            .resolver
1235                            .get_partial_res(ty.id)
1236                            .and_then(|partial_res| partial_res.full_res())
1237                        {
1238                            if !res.matches_ns(Namespace::TypeNS)
1239                                && path.is_potential_trivial_const_arg()
1240                            {
1241                                debug!(
1242                                    "lower_generic_arg: Lowering type argument as const argument: {:?}",
1243                                    ty,
1244                                );
1245
1246                                let ct =
1247                                    self.lower_const_path_to_const_arg(path, res, ty.id, ty.span);
1248                                return GenericArg::Const(ct.try_as_ambig_ct().unwrap());
1249                            }
1250                        }
1251                    }
1252                    _ => {}
1253                }
1254                GenericArg::Type(self.lower_ty_alloc(ty, itctx).try_as_ambig_ty().unwrap())
1255            }
1256            ast::GenericArg::Const(ct) => GenericArg::Const(
1257                self.lower_anon_const_to_const_arg_and_alloc(ct).try_as_ambig_ct().unwrap(),
1258            ),
1259        }
1260    }
1261
1262    #[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(1262u32),
                                    ::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))]
1263    fn lower_ty_alloc(&mut self, t: &Ty, itctx: ImplTraitContext) -> &'hir hir::Ty<'hir> {
1264        self.arena.alloc(self.lower_ty(t, itctx))
1265    }
1266
1267    fn lower_path_ty(
1268        &mut self,
1269        t: &Ty,
1270        qself: &Option<Box<QSelf>>,
1271        path: &Path,
1272        param_mode: ParamMode,
1273        itctx: ImplTraitContext,
1274    ) -> hir::Ty<'hir> {
1275        // Check whether we should interpret this as a bare trait object.
1276        // This check mirrors the one in late resolution. We only introduce this special case in
1277        // the rare occurrence we need to lower `Fresh` anonymous lifetimes.
1278        // The other cases when a qpath should be opportunistically made a trait object are handled
1279        // by `ty_path`.
1280        if qself.is_none()
1281            && let Some(partial_res) = self.resolver.get_partial_res(t.id)
1282            && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res()
1283        {
1284            let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1285                let bound = this.lower_poly_trait_ref(
1286                    &PolyTraitRef {
1287                        bound_generic_params: ThinVec::new(),
1288                        modifiers: TraitBoundModifiers::NONE,
1289                        trait_ref: TraitRef { path: path.clone(), ref_id: t.id },
1290                        span: t.span,
1291                        parens: ast::Parens::No,
1292                    },
1293                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitObjectTy),
1294                    itctx,
1295                );
1296                let bounds = this.arena.alloc_from_iter([bound]);
1297                let lifetime_bound = this.elided_dyn_bound(t.span);
1298                (bounds, lifetime_bound)
1299            });
1300            let kind = hir::TyKind::TraitObject(
1301                bounds,
1302                TaggedRef::new(lifetime_bound, TraitObjectSyntax::None),
1303            );
1304            return hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.next_id() };
1305        }
1306
1307        let id = self.lower_node_id(t.id);
1308        let qpath = self.lower_qpath(
1309            t.id,
1310            qself,
1311            path,
1312            param_mode,
1313            AllowReturnTypeNotation::Yes,
1314            itctx,
1315            None,
1316        );
1317        self.ty_path(id, t.span, qpath)
1318    }
1319
1320    fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1321        hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1322    }
1323
1324    fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1325        self.ty(span, hir::TyKind::Tup(tys))
1326    }
1327
1328    fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> hir::Ty<'hir> {
1329        let kind = match &t.kind {
1330            TyKind::Infer => hir::TyKind::Infer(()),
1331            TyKind::Err(guar) => hir::TyKind::Err(*guar),
1332            TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty_alloc(ty, itctx)),
1333            TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1334            TyKind::Ref(region, mt) => {
1335                let lifetime = self.lower_ty_direct_lifetime(t, *region);
1336                hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx))
1337            }
1338            TyKind::PinnedRef(region, mt) => {
1339                let lifetime = self.lower_ty_direct_lifetime(t, *region);
1340                let kind = hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx));
1341                let span = self.lower_span(t.span);
1342                let arg = hir::Ty { kind, span, hir_id: self.next_id() };
1343                let args = self.arena.alloc(hir::GenericArgs {
1344                    args: self.arena.alloc([hir::GenericArg::Type(self.arena.alloc(arg))]),
1345                    constraints: &[],
1346                    parenthesized: hir::GenericArgsParentheses::No,
1347                    span_ext: span,
1348                });
1349                let path = self.make_lang_item_qpath(hir::LangItem::Pin, span, Some(args));
1350                hir::TyKind::Path(path)
1351            }
1352            TyKind::FnPtr(f) => {
1353                let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1354                hir::TyKind::FnPtr(self.arena.alloc(hir::FnPtrTy {
1355                    generic_params,
1356                    safety: self.lower_safety(f.safety, hir::Safety::Safe),
1357                    abi: self.lower_extern(f.ext),
1358                    decl: self.lower_fn_decl(&f.decl, t.id, t.span, FnDeclKind::Pointer, None),
1359                    param_idents: self.lower_fn_params_to_idents(&f.decl),
1360                }))
1361            }
1362            TyKind::UnsafeBinder(f) => {
1363                let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1364                hir::TyKind::UnsafeBinder(self.arena.alloc(hir::UnsafeBinderTy {
1365                    generic_params,
1366                    inner_ty: self.lower_ty_alloc(&f.inner_ty, itctx),
1367                }))
1368            }
1369            TyKind::Never => hir::TyKind::Never,
1370            TyKind::Tup(tys) => hir::TyKind::Tup(
1371                self.arena.alloc_from_iter(tys.iter().map(|ty| self.lower_ty(ty, itctx))),
1372            ),
1373            TyKind::Paren(ty) => {
1374                return self.lower_ty(ty, itctx);
1375            }
1376            TyKind::Path(qself, path) => {
1377                return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1378            }
1379            TyKind::ImplicitSelf => {
1380                let hir_id = self.next_id();
1381                let res = self.expect_full_res(t.id);
1382                let res = self.lower_res(res);
1383                hir::TyKind::Path(hir::QPath::Resolved(
1384                    None,
1385                    self.arena.alloc(hir::Path {
1386                        res,
1387                        segments: self.arena.alloc_from_iter([hir::PathSegment::new(Ident::with_dummy_span(kw::SelfUpper),
                hir_id, res)])arena_vec![self; hir::PathSegment::new(
1388                            Ident::with_dummy_span(kw::SelfUpper),
1389                            hir_id,
1390                            res
1391                        )],
1392                        span: self.lower_span(t.span),
1393                    }),
1394                ))
1395            }
1396            TyKind::Array(ty, length) => hir::TyKind::Array(
1397                self.lower_ty_alloc(ty, itctx),
1398                self.lower_array_length_to_const_arg(length),
1399            ),
1400            TyKind::TraitObject(bounds, kind) => {
1401                let mut lifetime_bound = None;
1402                let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1403                    let bounds =
1404                        this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| match bound {
1405                            // We can safely ignore constness here since AST validation
1406                            // takes care of rejecting invalid modifier combinations and
1407                            // const trait bounds in trait object types.
1408                            GenericBound::Trait(ty) => {
1409                                let trait_ref = this.lower_poly_trait_ref(
1410                                    ty,
1411                                    RelaxedBoundPolicy::Forbidden(
1412                                        RelaxedBoundForbiddenReason::TraitObjectTy,
1413                                    ),
1414                                    itctx,
1415                                );
1416                                Some(trait_ref)
1417                            }
1418                            GenericBound::Outlives(lifetime) => {
1419                                if lifetime_bound.is_none() {
1420                                    lifetime_bound = Some(this.lower_lifetime(
1421                                        lifetime,
1422                                        LifetimeSource::Other,
1423                                        lifetime.ident.into(),
1424                                    ));
1425                                }
1426                                None
1427                            }
1428                            // Ignore `use` syntax since that is not valid in objects.
1429                            GenericBound::Use(_, span) => {
1430                                this.dcx()
1431                                    .span_delayed_bug(*span, "use<> not allowed in dyn types");
1432                                None
1433                            }
1434                        }));
1435                    let lifetime_bound =
1436                        lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1437                    (bounds, lifetime_bound)
1438                });
1439                hir::TyKind::TraitObject(bounds, TaggedRef::new(lifetime_bound, *kind))
1440            }
1441            TyKind::ImplTrait(def_node_id, bounds) => {
1442                let span = t.span;
1443                match itctx {
1444                    ImplTraitContext::OpaqueTy { origin } => {
1445                        self.lower_opaque_impl_trait(span, origin, *def_node_id, bounds, itctx)
1446                    }
1447                    ImplTraitContext::Universal => {
1448                        if let Some(span) = bounds.iter().find_map(|bound| match *bound {
1449                            ast::GenericBound::Use(_, span) => Some(span),
1450                            _ => None,
1451                        }) {
1452                            self.tcx.dcx().emit_err(errors::NoPreciseCapturesOnApit { span });
1453                        }
1454
1455                        let def_id = self.local_def_id(*def_node_id);
1456                        let name = self.tcx.item_name(def_id.to_def_id());
1457                        let ident = Ident::new(name, span);
1458                        let (param, bounds, path) = self.lower_universal_param_and_bounds(
1459                            *def_node_id,
1460                            span,
1461                            ident,
1462                            bounds,
1463                        );
1464                        self.impl_trait_defs.push(param);
1465                        if let Some(bounds) = bounds {
1466                            self.impl_trait_bounds.push(bounds);
1467                        }
1468                        path
1469                    }
1470                    ImplTraitContext::InBinding => hir::TyKind::TraitAscription(
1471                        self.lower_param_bounds(bounds, RelaxedBoundPolicy::Allowed, itctx),
1472                    ),
1473                    ImplTraitContext::FeatureGated(position, feature) => {
1474                        let guar = self
1475                            .tcx
1476                            .sess
1477                            .create_feature_err(
1478                                MisplacedImplTrait {
1479                                    span: t.span,
1480                                    position: DiagArgFromDisplay(&position),
1481                                },
1482                                feature,
1483                            )
1484                            .emit();
1485                        hir::TyKind::Err(guar)
1486                    }
1487                    ImplTraitContext::Disallowed(position) => {
1488                        let guar = self.dcx().emit_err(MisplacedImplTrait {
1489                            span: t.span,
1490                            position: DiagArgFromDisplay(&position),
1491                        });
1492                        hir::TyKind::Err(guar)
1493                    }
1494                }
1495            }
1496            TyKind::Pat(ty, pat) => {
1497                hir::TyKind::Pat(self.lower_ty_alloc(ty, itctx), self.lower_ty_pat(pat, ty.span))
1498            }
1499            TyKind::MacCall(_) => {
1500                ::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")
1501            }
1502            TyKind::CVarArgs => {
1503                let guar = self.dcx().span_delayed_bug(
1504                    t.span,
1505                    "`TyKind::CVarArgs` should have been handled elsewhere",
1506                );
1507                hir::TyKind::Err(guar)
1508            }
1509            TyKind::Dummy => {
    ::core::panicking::panic_fmt(format_args!("`TyKind::Dummy` should never be lowered"));
}panic!("`TyKind::Dummy` should never be lowered"),
1510        };
1511
1512        hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1513    }
1514
1515    fn lower_ty_direct_lifetime(
1516        &mut self,
1517        t: &Ty,
1518        region: Option<Lifetime>,
1519    ) -> &'hir hir::Lifetime {
1520        let (region, syntax) = match region {
1521            Some(region) => (region, region.ident.into()),
1522
1523            None => {
1524                let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1525                    self.resolver.get_lifetime_res(t.id)
1526                {
1527                    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);
1528                    start
1529                } else {
1530                    self.next_node_id()
1531                };
1532                let span = self.tcx.sess.source_map().start_point(t.span).shrink_to_hi();
1533                let region = Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id };
1534                (region, LifetimeSyntax::Implicit)
1535            }
1536        };
1537        self.lower_lifetime(&region, LifetimeSource::Reference, syntax)
1538    }
1539
1540    /// Lowers a `ReturnPositionOpaqueTy` (`-> impl Trait`) or a `TypeAliasesOpaqueTy` (`type F =
1541    /// impl Trait`): this creates the associated Opaque Type (TAIT) definition and then returns a
1542    /// HIR type that references the TAIT.
1543    ///
1544    /// Given a function definition like:
1545    ///
1546    /// ```rust
1547    /// use std::fmt::Debug;
1548    ///
1549    /// fn test<'a, T: Debug>(x: &'a T) -> impl Debug + 'a {
1550    ///     x
1551    /// }
1552    /// ```
1553    ///
1554    /// we will create a TAIT definition in the HIR like
1555    ///
1556    /// ```rust,ignore (pseudo-Rust)
1557    /// type TestReturn<'a, T, 'x> = impl Debug + 'x
1558    /// ```
1559    ///
1560    /// and return a type like `TestReturn<'static, T, 'a>`, so that the function looks like:
1561    ///
1562    /// ```rust,ignore (pseudo-Rust)
1563    /// fn test<'a, T: Debug>(x: &'a T) -> TestReturn<'static, T, 'a>
1564    /// ```
1565    ///
1566    /// Note the subtlety around type parameters! The new TAIT, `TestReturn`, inherits all the
1567    /// type parameters from the function `test` (this is implemented in the query layer, they aren't
1568    /// added explicitly in the HIR). But this includes all the lifetimes, and we only want to
1569    /// capture the lifetimes that are referenced in the bounds. Therefore, we add *extra* lifetime parameters
1570    /// for the lifetimes that get captured (`'x`, in our example above) and reference those.
1571    x;#[instrument(level = "debug", skip(self), ret)]
1572    fn lower_opaque_impl_trait(
1573        &mut self,
1574        span: Span,
1575        origin: hir::OpaqueTyOrigin<LocalDefId>,
1576        opaque_ty_node_id: NodeId,
1577        bounds: &GenericBounds,
1578        itctx: ImplTraitContext,
1579    ) -> hir::TyKind<'hir> {
1580        // Make sure we know that some funky desugaring has been going on here.
1581        // This is a first: there is code in other places like for loop
1582        // desugaring that explicitly states that we don't want to track that.
1583        // Not tracking it makes lints in rustc and clippy very fragile, as
1584        // frequently opened issues show.
1585        let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1586
1587        self.lower_opaque_inner(opaque_ty_node_id, origin, opaque_ty_span, |this| {
1588            this.lower_param_bounds(bounds, RelaxedBoundPolicy::Allowed, itctx)
1589        })
1590    }
1591
1592    fn lower_opaque_inner(
1593        &mut self,
1594        opaque_ty_node_id: NodeId,
1595        origin: hir::OpaqueTyOrigin<LocalDefId>,
1596        opaque_ty_span: Span,
1597        lower_item_bounds: impl FnOnce(&mut Self) -> &'hir [hir::GenericBound<'hir>],
1598    ) -> hir::TyKind<'hir> {
1599        let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id);
1600        let opaque_ty_hir_id = self.lower_node_id(opaque_ty_node_id);
1601        {
    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:1601",
                        "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(1601u32),
                        ::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);
1602
1603        let bounds = lower_item_bounds(self);
1604        let opaque_ty_def = hir::OpaqueTy {
1605            hir_id: opaque_ty_hir_id,
1606            def_id: opaque_ty_def_id,
1607            bounds,
1608            origin,
1609            span: self.lower_span(opaque_ty_span),
1610        };
1611        let opaque_ty_def = self.arena.alloc(opaque_ty_def);
1612
1613        hir::TyKind::OpaqueDef(opaque_ty_def)
1614    }
1615
1616    fn lower_precise_capturing_args(
1617        &mut self,
1618        precise_capturing_args: &[PreciseCapturingArg],
1619    ) -> &'hir [hir::PreciseCapturingArg<'hir>] {
1620        self.arena.alloc_from_iter(precise_capturing_args.iter().map(|arg| match arg {
1621            PreciseCapturingArg::Lifetime(lt) => hir::PreciseCapturingArg::Lifetime(
1622                self.lower_lifetime(lt, LifetimeSource::PreciseCapturing, lt.ident.into()),
1623            ),
1624            PreciseCapturingArg::Arg(path, id) => {
1625                let [segment] = path.segments.as_slice() else {
1626                    ::core::panicking::panic("explicit panic");panic!();
1627                };
1628                let res = self.resolver.get_partial_res(*id).map_or(Res::Err, |partial_res| {
1629                    partial_res.full_res().expect("no partial res expected for precise capture arg")
1630                });
1631                hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
1632                    hir_id: self.lower_node_id(*id),
1633                    ident: self.lower_ident(segment.ident),
1634                    res: self.lower_res(res),
1635                })
1636            }
1637        }))
1638    }
1639
1640    fn lower_fn_params_to_idents(&mut self, decl: &FnDecl) -> &'hir [Option<Ident>] {
1641        self.arena.alloc_from_iter(decl.inputs.iter().map(|param| match param.pat.kind {
1642            PatKind::Missing => None,
1643            PatKind::Ident(_, ident, _) => Some(self.lower_ident(ident)),
1644            PatKind::Wild => Some(Ident::new(kw::Underscore, self.lower_span(param.pat.span))),
1645            _ => {
1646                self.dcx().span_delayed_bug(
1647                    param.pat.span,
1648                    "non-missing/ident/wild param pat must trigger an error",
1649                );
1650                None
1651            }
1652        }))
1653    }
1654
1655    /// Lowers a function declaration.
1656    ///
1657    /// `decl`: the unlowered (AST) function declaration.
1658    ///
1659    /// `fn_node_id`: `impl Trait` arguments are lowered into generic parameters on the given
1660    /// `NodeId`.
1661    ///
1662    /// `transform_return_type`: if `Some`, applies some conversion to the return type, such as is
1663    /// needed for `async fn` and `gen fn`. See [`CoroutineKind`] for more details.
1664    #[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(1664u32),
                                    ::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))]
1665    fn lower_fn_decl(
1666        &mut self,
1667        decl: &FnDecl,
1668        fn_node_id: NodeId,
1669        fn_span: Span,
1670        kind: FnDeclKind,
1671        coro: Option<CoroutineKind>,
1672    ) -> &'hir hir::FnDecl<'hir> {
1673        let c_variadic = decl.c_variadic();
1674
1675        // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1676        // as they are not explicit in HIR/Ty function signatures.
1677        // (instead, the `c_variadic` flag is set to `true`)
1678        let mut inputs = &decl.inputs[..];
1679        if c_variadic {
1680            inputs = &inputs[..inputs.len() - 1];
1681        }
1682        let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1683            let itctx = match kind {
1684                FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait => {
1685                    ImplTraitContext::Universal
1686                }
1687                FnDeclKind::ExternFn => {
1688                    ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnParam)
1689                }
1690                FnDeclKind::Closure => {
1691                    ImplTraitContext::Disallowed(ImplTraitPosition::ClosureParam)
1692                }
1693                FnDeclKind::Pointer => {
1694                    ImplTraitContext::Disallowed(ImplTraitPosition::PointerParam)
1695                }
1696            };
1697            self.lower_ty(&param.ty, itctx)
1698        }));
1699
1700        let output = match coro {
1701            Some(coro) => {
1702                let fn_def_id = self.local_def_id(fn_node_id);
1703                self.lower_coroutine_fn_ret_ty(&decl.output, fn_def_id, coro, kind)
1704            }
1705            None => match &decl.output {
1706                FnRetTy::Ty(ty) => {
1707                    let itctx = match kind {
1708                        FnDeclKind::Fn | FnDeclKind::Inherent => ImplTraitContext::OpaqueTy {
1709                            origin: hir::OpaqueTyOrigin::FnReturn {
1710                                parent: self.local_def_id(fn_node_id),
1711                                in_trait_or_impl: None,
1712                            },
1713                        },
1714                        FnDeclKind::Trait => ImplTraitContext::OpaqueTy {
1715                            origin: hir::OpaqueTyOrigin::FnReturn {
1716                                parent: self.local_def_id(fn_node_id),
1717                                in_trait_or_impl: Some(hir::RpitContext::Trait),
1718                            },
1719                        },
1720                        FnDeclKind::Impl => ImplTraitContext::OpaqueTy {
1721                            origin: hir::OpaqueTyOrigin::FnReturn {
1722                                parent: self.local_def_id(fn_node_id),
1723                                in_trait_or_impl: Some(hir::RpitContext::TraitImpl),
1724                            },
1725                        },
1726                        FnDeclKind::ExternFn => {
1727                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnReturn)
1728                        }
1729                        FnDeclKind::Closure => {
1730                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureReturn)
1731                        }
1732                        FnDeclKind::Pointer => {
1733                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerReturn)
1734                        }
1735                    };
1736                    hir::FnRetTy::Return(self.lower_ty_alloc(ty, itctx))
1737                }
1738                FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(*span)),
1739            },
1740        };
1741
1742        self.arena.alloc(hir::FnDecl {
1743            inputs,
1744            output,
1745            c_variadic,
1746            lifetime_elision_allowed: self.resolver.lifetime_elision_allowed.contains(&fn_node_id),
1747            implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1748                let is_mutable_pat = matches!(
1749                    arg.pat.kind,
1750                    PatKind::Ident(hir::BindingMode(_, Mutability::Mut), ..)
1751                );
1752
1753                match &arg.ty.kind {
1754                    TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1755                    TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1756                    // Given we are only considering `ImplicitSelf` types, we needn't consider
1757                    // the case where we have a mutable pattern to a reference as that would
1758                    // no longer be an `ImplicitSelf`.
1759                    TyKind::Ref(_, mt) | TyKind::PinnedRef(_, mt)
1760                        if mt.ty.kind.is_implicit_self() =>
1761                    {
1762                        match mt.mutbl {
1763                            hir::Mutability::Not => hir::ImplicitSelfKind::RefImm,
1764                            hir::Mutability::Mut => hir::ImplicitSelfKind::RefMut,
1765                        }
1766                    }
1767                    _ => hir::ImplicitSelfKind::None,
1768                }
1769            }),
1770        })
1771    }
1772
1773    // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1774    // combined with the following definition of `OpaqueTy`:
1775    //
1776    //     type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1777    //
1778    // `output`: unlowered output type (`T` in `-> T`)
1779    // `fn_node_id`: `NodeId` of the parent function (used to create child impl trait definition)
1780    // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1781    #[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(1781u32),
                                    ::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))]
1782    fn lower_coroutine_fn_ret_ty(
1783        &mut self,
1784        output: &FnRetTy,
1785        fn_def_id: LocalDefId,
1786        coro: CoroutineKind,
1787        fn_kind: FnDeclKind,
1788    ) -> hir::FnRetTy<'hir> {
1789        let span = self.lower_span(output.span());
1790
1791        let (opaque_ty_node_id, allowed_features) = match coro {
1792            CoroutineKind::Async { return_impl_trait_id, .. } => (return_impl_trait_id, None),
1793            CoroutineKind::Gen { return_impl_trait_id, .. } => (return_impl_trait_id, None),
1794            CoroutineKind::AsyncGen { return_impl_trait_id, .. } => {
1795                (return_impl_trait_id, Some(Arc::clone(&self.allow_async_iterator)))
1796            }
1797        };
1798
1799        let opaque_ty_span =
1800            self.mark_span_with_reason(DesugaringKind::Async, span, allowed_features);
1801
1802        let in_trait_or_impl = match fn_kind {
1803            FnDeclKind::Trait => Some(hir::RpitContext::Trait),
1804            FnDeclKind::Impl => Some(hir::RpitContext::TraitImpl),
1805            FnDeclKind::Fn | FnDeclKind::Inherent => None,
1806            FnDeclKind::ExternFn | FnDeclKind::Closure | FnDeclKind::Pointer => unreachable!(),
1807        };
1808
1809        let opaque_ty_ref = self.lower_opaque_inner(
1810            opaque_ty_node_id,
1811            hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, in_trait_or_impl },
1812            opaque_ty_span,
1813            |this| {
1814                let bound = this.lower_coroutine_fn_output_type_to_bound(
1815                    output,
1816                    coro,
1817                    opaque_ty_span,
1818                    ImplTraitContext::OpaqueTy {
1819                        origin: hir::OpaqueTyOrigin::FnReturn {
1820                            parent: fn_def_id,
1821                            in_trait_or_impl,
1822                        },
1823                    },
1824                );
1825                arena_vec![this; bound]
1826            },
1827        );
1828
1829        let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1830        hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
1831    }
1832
1833    /// Transforms `-> T` into `Future<Output = T>`.
1834    fn lower_coroutine_fn_output_type_to_bound(
1835        &mut self,
1836        output: &FnRetTy,
1837        coro: CoroutineKind,
1838        opaque_ty_span: Span,
1839        itctx: ImplTraitContext,
1840    ) -> hir::GenericBound<'hir> {
1841        // Compute the `T` in `Future<Output = T>` from the return type.
1842        let output_ty = match output {
1843            FnRetTy::Ty(ty) => {
1844                // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1845                // `impl Future` opaque type that `async fn` implicitly
1846                // generates.
1847                self.lower_ty_alloc(ty, itctx)
1848            }
1849            FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1850        };
1851
1852        // "<$assoc_ty_name = T>"
1853        let (assoc_ty_name, trait_lang_item) = match coro {
1854            CoroutineKind::Async { .. } => (sym::Output, hir::LangItem::Future),
1855            CoroutineKind::Gen { .. } => (sym::Item, hir::LangItem::Iterator),
1856            CoroutineKind::AsyncGen { .. } => (sym::Item, hir::LangItem::AsyncIterator),
1857        };
1858
1859        let bound_args = self.arena.alloc(hir::GenericArgs {
1860            args: &[],
1861            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)],
1862            parenthesized: hir::GenericArgsParentheses::No,
1863            span_ext: DUMMY_SP,
1864        });
1865
1866        hir::GenericBound::Trait(hir::PolyTraitRef {
1867            bound_generic_params: &[],
1868            modifiers: hir::TraitBoundModifiers::NONE,
1869            trait_ref: hir::TraitRef {
1870                path: self.make_lang_item_path(trait_lang_item, opaque_ty_span, Some(bound_args)),
1871                hir_ref_id: self.next_id(),
1872            },
1873            span: opaque_ty_span,
1874        })
1875    }
1876
1877    #[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(1877u32),
                                    ::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))]
1878    fn lower_param_bound(
1879        &mut self,
1880        tpb: &GenericBound,
1881        rbp: RelaxedBoundPolicy<'_>,
1882        itctx: ImplTraitContext,
1883    ) -> hir::GenericBound<'hir> {
1884        match tpb {
1885            GenericBound::Trait(p) => {
1886                hir::GenericBound::Trait(self.lower_poly_trait_ref(p, rbp, itctx))
1887            }
1888            GenericBound::Outlives(lifetime) => hir::GenericBound::Outlives(self.lower_lifetime(
1889                lifetime,
1890                LifetimeSource::OutlivesBound,
1891                lifetime.ident.into(),
1892            )),
1893            GenericBound::Use(args, span) => hir::GenericBound::Use(
1894                self.lower_precise_capturing_args(args),
1895                self.lower_span(*span),
1896            ),
1897        }
1898    }
1899
1900    fn lower_lifetime(
1901        &mut self,
1902        l: &Lifetime,
1903        source: LifetimeSource,
1904        syntax: LifetimeSyntax,
1905    ) -> &'hir hir::Lifetime {
1906        self.new_named_lifetime(l.id, l.id, l.ident, source, syntax)
1907    }
1908
1909    fn lower_lifetime_hidden_in_path(
1910        &mut self,
1911        id: NodeId,
1912        span: Span,
1913        angle_brackets: AngleBrackets,
1914    ) -> &'hir hir::Lifetime {
1915        self.new_named_lifetime(
1916            id,
1917            id,
1918            Ident::new(kw::UnderscoreLifetime, span),
1919            LifetimeSource::Path { angle_brackets },
1920            LifetimeSyntax::Implicit,
1921        )
1922    }
1923
1924    #[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(1924u32),
                                    ::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 =
                if let Some(res) = self.resolver.get_lifetime_res(id) {
                    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(guar) => hir::LifetimeKind::Error(guar),
                        LifetimeRes::ElidedAnchor { .. } => {
                            {
                                ::core::panicking::panic_fmt(format_args!("Unexpected `ElidedAnchar` {0:?} at {1:?}",
                                        ident, ident.span));
                            };
                        }
                    }
                } else {
                    hir::LifetimeKind::Error(self.dcx().span_delayed_bug(ident.span,
                            "unresolved lifetime"))
                };
            {
                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))]
1925    fn new_named_lifetime(
1926        &mut self,
1927        id: NodeId,
1928        new_id: NodeId,
1929        ident: Ident,
1930        source: LifetimeSource,
1931        syntax: LifetimeSyntax,
1932    ) -> &'hir hir::Lifetime {
1933        let res = if let Some(res) = self.resolver.get_lifetime_res(id) {
1934            match res {
1935                LifetimeRes::Param { param, .. } => hir::LifetimeKind::Param(param),
1936                LifetimeRes::Fresh { param, .. } => {
1937                    assert_eq!(ident.name, kw::UnderscoreLifetime);
1938                    let param = self.local_def_id(param);
1939                    hir::LifetimeKind::Param(param)
1940                }
1941                LifetimeRes::Infer => {
1942                    assert_eq!(ident.name, kw::UnderscoreLifetime);
1943                    hir::LifetimeKind::Infer
1944                }
1945                LifetimeRes::Static { .. } => {
1946                    assert!(matches!(ident.name, kw::StaticLifetime | kw::UnderscoreLifetime));
1947                    hir::LifetimeKind::Static
1948                }
1949                LifetimeRes::Error(guar) => hir::LifetimeKind::Error(guar),
1950                LifetimeRes::ElidedAnchor { .. } => {
1951                    panic!("Unexpected `ElidedAnchar` {:?} at {:?}", ident, ident.span);
1952                }
1953            }
1954        } else {
1955            hir::LifetimeKind::Error(self.dcx().span_delayed_bug(ident.span, "unresolved lifetime"))
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 = if let Some(LifetimeRes::Error(..)) =
2020                    self.resolver.get_lifetime_res(param.id)
2021                {
2022                    ParamName::Error(ident)
2023                } else {
2024                    ParamName::Plain(ident)
2025                };
2026                let kind =
2027                    hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2028
2029                (param_name, kind)
2030            }
2031            GenericParamKind::Type { default, .. } => {
2032                // Not only do we deny type param defaults in binders but we also map them to `None`
2033                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2034                let default = default
2035                    .as_ref()
2036                    .filter(|_| match source {
2037                        hir::GenericParamSource::Generics => true,
2038                        hir::GenericParamSource::Binder => {
2039                            self.dcx().emit_err(errors::GenericParamDefaultInBinder {
2040                                span: param.span(),
2041                            });
2042
2043                            false
2044                        }
2045                    })
2046                    .map(|def| {
2047                        self.lower_ty_alloc(
2048                            def,
2049                            ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2050                        )
2051                    });
2052
2053                let kind = hir::GenericParamKind::Type { default, synthetic: false };
2054
2055                (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2056            }
2057            GenericParamKind::Const { ty, span: _, default } => {
2058                let ty = self.lower_ty_alloc(
2059                    ty,
2060                    ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2061                );
2062
2063                // Not only do we deny const param defaults in binders but we also map them to `None`
2064                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2065                let default = default
2066                    .as_ref()
2067                    .filter(|_| match source {
2068                        hir::GenericParamSource::Generics => true,
2069                        hir::GenericParamSource::Binder => {
2070                            self.dcx().emit_err(errors::GenericParamDefaultInBinder {
2071                                span: param.span(),
2072                            });
2073
2074                            false
2075                        }
2076                    })
2077                    .map(|def| self.lower_anon_const_to_const_arg_and_alloc(def));
2078
2079                (
2080                    hir::ParamName::Plain(self.lower_ident(param.ident)),
2081                    hir::GenericParamKind::Const { ty, default },
2082                )
2083            }
2084        }
2085    }
2086
2087    fn lower_trait_ref(
2088        &mut self,
2089        modifiers: ast::TraitBoundModifiers,
2090        p: &TraitRef,
2091        itctx: ImplTraitContext,
2092    ) -> hir::TraitRef<'hir> {
2093        let path = match self.lower_qpath(
2094            p.ref_id,
2095            &None,
2096            &p.path,
2097            ParamMode::Explicit,
2098            AllowReturnTypeNotation::No,
2099            itctx,
2100            Some(modifiers),
2101        ) {
2102            hir::QPath::Resolved(None, path) => path,
2103            qpath => {
    ::core::panicking::panic_fmt(format_args!("lower_trait_ref: unexpected QPath `{0:?}`",
            qpath));
}panic!("lower_trait_ref: unexpected QPath `{qpath:?}`"),
2104        };
2105        hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2106    }
2107
2108    #[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(2108u32),
                                    ::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))]
2109    fn lower_poly_trait_ref(
2110        &mut self,
2111        PolyTraitRef { bound_generic_params, modifiers, trait_ref, span, parens: _ }: &PolyTraitRef,
2112        rbp: RelaxedBoundPolicy<'_>,
2113        itctx: ImplTraitContext,
2114    ) -> hir::PolyTraitRef<'hir> {
2115        let bound_generic_params =
2116            self.lower_lifetime_binder(trait_ref.ref_id, bound_generic_params);
2117        let trait_ref = self.lower_trait_ref(*modifiers, trait_ref, itctx);
2118        let modifiers = self.lower_trait_bound_modifiers(*modifiers);
2119
2120        if let ast::BoundPolarity::Maybe(_) = modifiers.polarity {
2121            self.validate_relaxed_bound(trait_ref, *span, rbp);
2122        }
2123
2124        hir::PolyTraitRef {
2125            bound_generic_params,
2126            modifiers,
2127            trait_ref,
2128            span: self.lower_span(*span),
2129        }
2130    }
2131
2132    fn validate_relaxed_bound(
2133        &self,
2134        trait_ref: hir::TraitRef<'_>,
2135        span: Span,
2136        rbp: RelaxedBoundPolicy<'_>,
2137    ) {
2138        // Even though feature `more_maybe_bounds` enables the user to relax all default bounds
2139        // other than `Sized` in a lot more positions (thereby bypassing the given policy), we don't
2140        // want to advertise it to the user (via a feature gate error) since it's super internal.
2141        //
2142        // FIXME(more_maybe_bounds): Moreover, if we actually were to add proper default traits
2143        // (like a hypothetical `Move` or `Leak`) we would want to validate the location according
2144        // to default trait elaboration in HIR ty lowering (which depends on the specific trait in
2145        // question: E.g., `?Sized` & `?Move` most likely won't be allowed in all the same places).
2146
2147        match rbp {
2148            RelaxedBoundPolicy::Allowed => return,
2149            RelaxedBoundPolicy::AllowedIfOnTyParam(id, params) => {
2150                if let Some(res) = self.resolver.get_partial_res(id).and_then(|r| r.full_res())
2151                    && let Res::Def(DefKind::TyParam, def_id) = res
2152                    && params.iter().any(|p| def_id == self.local_def_id(p.id).to_def_id())
2153                {
2154                    return;
2155                }
2156            }
2157            RelaxedBoundPolicy::Forbidden(reason) => {
2158                let gate = |context, subject| {
2159                    let extended = self.tcx.features().more_maybe_bounds();
2160                    let is_sized = trait_ref
2161                        .trait_def_id()
2162                        .is_some_and(|def_id| self.tcx.is_lang_item(def_id, hir::LangItem::Sized));
2163
2164                    if extended && !is_sized {
2165                        return;
2166                    }
2167
2168                    let prefix = if extended { "`Sized` " } else { "" };
2169                    let mut diag = self.dcx().struct_span_err(
2170                        span,
2171                        ::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}"),
2172                    );
2173                    if is_sized {
2174                        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!(
2175                            "{subject} are not implicitly bounded by `Sized`, \
2176                             so there is nothing to relax"
2177                        ));
2178                    }
2179                    diag.emit();
2180                };
2181
2182                match reason {
2183                    RelaxedBoundForbiddenReason::TraitObjectTy => {
2184                        gate("trait object types", "trait object types");
2185                        return;
2186                    }
2187                    RelaxedBoundForbiddenReason::SuperTrait => {
2188                        gate("supertrait bounds", "traits");
2189                        return;
2190                    }
2191                    RelaxedBoundForbiddenReason::TraitAlias => {
2192                        gate("trait alias bounds", "trait aliases");
2193                        return;
2194                    }
2195                    RelaxedBoundForbiddenReason::AssocTyBounds
2196                    | RelaxedBoundForbiddenReason::LateBoundVarsInScope => {}
2197                };
2198            }
2199        }
2200
2201        self.dcx()
2202            .struct_span_err(span, "this relaxed bound is not permitted here")
2203            .with_note(
2204                "in this context, relaxed bounds are only allowed on \
2205                 type parameters defined on the closest item",
2206            )
2207            .emit();
2208    }
2209
2210    fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy<'hir> {
2211        hir::MutTy { ty: self.lower_ty_alloc(&mt.ty, itctx), mutbl: mt.mutbl }
2212    }
2213
2214    x;#[instrument(level = "debug", skip(self), ret)]
2215    fn lower_param_bounds(
2216        &mut self,
2217        bounds: &[GenericBound],
2218        rbp: RelaxedBoundPolicy<'_>,
2219        itctx: ImplTraitContext,
2220    ) -> hir::GenericBounds<'hir> {
2221        self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, rbp, itctx))
2222    }
2223
2224    fn lower_param_bounds_mut(
2225        &mut self,
2226        bounds: &[GenericBound],
2227        rbp: RelaxedBoundPolicy<'_>,
2228        itctx: ImplTraitContext,
2229    ) -> impl Iterator<Item = hir::GenericBound<'hir>> {
2230        bounds.iter().map(move |bound| self.lower_param_bound(bound, rbp, itctx))
2231    }
2232
2233    x;#[instrument(level = "debug", skip(self), ret)]
2234    fn lower_universal_param_and_bounds(
2235        &mut self,
2236        node_id: NodeId,
2237        span: Span,
2238        ident: Ident,
2239        bounds: &[GenericBound],
2240    ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2241        // Add a definition for the in-band `Param`.
2242        let def_id = self.local_def_id(node_id);
2243        let span = self.lower_span(span);
2244
2245        // Set the name to `impl Bound1 + Bound2`.
2246        let param = hir::GenericParam {
2247            hir_id: self.lower_node_id(node_id),
2248            def_id,
2249            name: ParamName::Plain(self.lower_ident(ident)),
2250            pure_wrt_drop: false,
2251            span,
2252            kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2253            colon_span: None,
2254            source: hir::GenericParamSource::Generics,
2255        };
2256
2257        let preds = self.lower_generic_bound_predicate(
2258            ident,
2259            node_id,
2260            &GenericParamKind::Type { default: None },
2261            bounds,
2262            /* colon_span */ None,
2263            span,
2264            RelaxedBoundPolicy::Allowed,
2265            ImplTraitContext::Universal,
2266            hir::PredicateOrigin::ImplTrait,
2267        );
2268
2269        let hir_id = self.next_id();
2270        let res = Res::Def(DefKind::TyParam, def_id.to_def_id());
2271        let ty = hir::TyKind::Path(hir::QPath::Resolved(
2272            None,
2273            self.arena.alloc(hir::Path {
2274                span,
2275                res,
2276                segments:
2277                    arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2278            }),
2279        ));
2280
2281        (param, preds, ty)
2282    }
2283
2284    /// Lowers a block directly to an expression, presuming that it
2285    /// has no attributes and is not targeted by a `break`.
2286    fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2287        let block = self.lower_block(b, false);
2288        self.expr_block(block)
2289    }
2290
2291    fn lower_array_length_to_const_arg(&mut self, c: &AnonConst) -> &'hir hir::ConstArg<'hir> {
2292        // We cannot just match on `ExprKind::Underscore` as `(_)` is represented as
2293        // `ExprKind::Paren(ExprKind::Underscore)` and should also be lowered to `GenericArg::Infer`
2294        match c.value.peel_parens().kind {
2295            ExprKind::Underscore => {
2296                let ct_kind = hir::ConstArgKind::Infer(());
2297                self.arena.alloc(hir::ConstArg {
2298                    hir_id: self.lower_node_id(c.id),
2299                    kind: ct_kind,
2300                    span: self.lower_span(c.value.span),
2301                })
2302            }
2303            _ => self.lower_anon_const_to_const_arg_and_alloc(c),
2304        }
2305    }
2306
2307    /// Used when lowering a type argument that turned out to actually be a const argument.
2308    ///
2309    /// Only use for that purpose since otherwise it will create a duplicate def.
2310    #[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(2310u32),
                                    ::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))]
2311    fn lower_const_path_to_const_arg(
2312        &mut self,
2313        path: &Path,
2314        res: Res<NodeId>,
2315        ty_id: NodeId,
2316        span: Span,
2317    ) -> &'hir hir::ConstArg<'hir> {
2318        let tcx = self.tcx;
2319
2320        let is_trivial_path = path.is_potential_trivial_const_arg()
2321            && matches!(res, Res::Def(DefKind::ConstParam, _));
2322        let ct_kind = if is_trivial_path || tcx.features().min_generic_const_args() {
2323            let qpath = self.lower_qpath(
2324                ty_id,
2325                &None,
2326                path,
2327                ParamMode::Explicit,
2328                AllowReturnTypeNotation::No,
2329                // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2330                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2331                None,
2332            );
2333            hir::ConstArgKind::Path(qpath)
2334        } else {
2335            // Construct an AnonConst where the expr is the "ty"'s path.
2336            let node_id = self.next_node_id();
2337            let span = self.lower_span(span);
2338
2339            // Add a definition for the in-band const def.
2340            // We're lowering a const argument that was originally thought to be a type argument,
2341            // so the def collector didn't create the def ahead of time. That's why we have to do
2342            // it here.
2343            let def_id = self.create_def(
2344                node_id,
2345                None,
2346                DefKind::AnonConst,
2347                DefPathData::LateAnonConst,
2348                span,
2349            );
2350            let hir_id = self.lower_node_id(node_id);
2351
2352            let path_expr = Expr {
2353                id: ty_id,
2354                kind: ExprKind::Path(None, path.clone()),
2355                span,
2356                attrs: AttrVec::new(),
2357                tokens: None,
2358            };
2359
2360            let ct = self.with_new_scopes(span, |this| {
2361                self.arena.alloc(hir::AnonConst {
2362                    def_id,
2363                    hir_id,
2364                    body: this.lower_const_body(path_expr.span, Some(&path_expr)),
2365                    span,
2366                })
2367            });
2368            hir::ConstArgKind::Anon(ct)
2369        };
2370
2371        self.arena.alloc(hir::ConstArg {
2372            hir_id: self.next_id(),
2373            kind: ct_kind,
2374            span: self.lower_span(span),
2375        })
2376    }
2377
2378    fn lower_const_item_rhs(
2379        &mut self,
2380        rhs_kind: &ConstItemRhsKind,
2381        span: Span,
2382    ) -> hir::ConstItemRhs<'hir> {
2383        match rhs_kind {
2384            ConstItemRhsKind::Body { rhs: Some(body) } => {
2385                hir::ConstItemRhs::Body(self.lower_const_body(span, Some(body)))
2386            }
2387            ConstItemRhsKind::Body { rhs: None } => {
2388                hir::ConstItemRhs::Body(self.lower_const_body(span, None))
2389            }
2390            ConstItemRhsKind::TypeConst { rhs: Some(anon) } => {
2391                hir::ConstItemRhs::TypeConst(self.lower_anon_const_to_const_arg_and_alloc(anon))
2392            }
2393            ConstItemRhsKind::TypeConst { rhs: None } => {
2394                let const_arg = ConstArg {
2395                    hir_id: self.next_id(),
2396                    kind: hir::ConstArgKind::Error(
2397                        self.dcx().span_delayed_bug(DUMMY_SP, "no block"),
2398                    ),
2399                    span: DUMMY_SP,
2400                };
2401                hir::ConstItemRhs::TypeConst(self.arena.alloc(const_arg))
2402            }
2403        }
2404    }
2405
2406    x;#[instrument(level = "debug", skip(self), ret)]
2407    fn lower_expr_to_const_arg_direct(&mut self, expr: &Expr) -> hir::ConstArg<'hir> {
2408        let span = self.lower_span(expr.span);
2409
2410        let overly_complex_const = |this: &mut Self| {
2411            let e = this.dcx().struct_span_err(
2412                expr.span,
2413                "complex const arguments must be placed inside of a `const` block",
2414            );
2415
2416            ConstArg { hir_id: this.next_id(), kind: hir::ConstArgKind::Error(e.emit()), span }
2417        };
2418
2419        match &expr.kind {
2420            ExprKind::Call(func, args) if let ExprKind::Path(qself, path) = &func.kind => {
2421                let qpath = self.lower_qpath(
2422                    func.id,
2423                    qself,
2424                    path,
2425                    ParamMode::Explicit,
2426                    AllowReturnTypeNotation::No,
2427                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2428                    None,
2429                );
2430
2431                let lowered_args = self.arena.alloc_from_iter(args.iter().map(|arg| {
2432                    let const_arg = self.lower_expr_to_const_arg_direct(arg);
2433                    &*self.arena.alloc(const_arg)
2434                }));
2435
2436                ConstArg {
2437                    hir_id: self.next_id(),
2438                    kind: hir::ConstArgKind::TupleCall(qpath, lowered_args),
2439                    span,
2440                }
2441            }
2442            ExprKind::Tup(exprs) => {
2443                let exprs = self.arena.alloc_from_iter(exprs.iter().map(|expr| {
2444                    let expr = self.lower_expr_to_const_arg_direct(&expr);
2445                    &*self.arena.alloc(expr)
2446                }));
2447
2448                ConstArg { hir_id: self.next_id(), kind: hir::ConstArgKind::Tup(exprs), span }
2449            }
2450            ExprKind::Path(qself, path) => {
2451                let qpath = self.lower_qpath(
2452                    expr.id,
2453                    qself,
2454                    path,
2455                    ParamMode::Explicit,
2456                    AllowReturnTypeNotation::No,
2457                    // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2458                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2459                    None,
2460                );
2461
2462                ConstArg { hir_id: self.next_id(), kind: hir::ConstArgKind::Path(qpath), span }
2463            }
2464            ExprKind::Struct(se) => {
2465                let path = self.lower_qpath(
2466                    expr.id,
2467                    &se.qself,
2468                    &se.path,
2469                    // FIXME(mgca): we may want this to be `Optional` instead, but
2470                    // we would also need to make sure that HIR ty lowering errors
2471                    // when these paths wind up in signatures.
2472                    ParamMode::Explicit,
2473                    AllowReturnTypeNotation::No,
2474                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2475                    None,
2476                );
2477
2478                let fields = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
2479                    let hir_id = self.lower_node_id(f.id);
2480                    // FIXME(mgca): This might result in lowering attributes that
2481                    // then go unused as the `Target::ExprField` is not actually
2482                    // corresponding to `Node::ExprField`.
2483                    self.lower_attrs(hir_id, &f.attrs, f.span, Target::ExprField);
2484                    let expr = self.lower_expr_to_const_arg_direct(&f.expr);
2485
2486                    &*self.arena.alloc(hir::ConstArgExprField {
2487                        hir_id,
2488                        field: self.lower_ident(f.ident),
2489                        expr: self.arena.alloc(expr),
2490                        span: self.lower_span(f.span),
2491                    })
2492                }));
2493
2494                ConstArg {
2495                    hir_id: self.next_id(),
2496                    kind: hir::ConstArgKind::Struct(path, fields),
2497                    span,
2498                }
2499            }
2500            ExprKind::Array(elements) => {
2501                let lowered_elems = self.arena.alloc_from_iter(elements.iter().map(|element| {
2502                    let const_arg = self.lower_expr_to_const_arg_direct(element);
2503                    &*self.arena.alloc(const_arg)
2504                }));
2505                let array_expr = self.arena.alloc(hir::ConstArgArrayExpr {
2506                    span: self.lower_span(expr.span),
2507                    elems: lowered_elems,
2508                });
2509
2510                ConstArg {
2511                    hir_id: self.next_id(),
2512                    kind: hir::ConstArgKind::Array(array_expr),
2513                    span,
2514                }
2515            }
2516            ExprKind::Underscore => ConstArg {
2517                hir_id: self.lower_node_id(expr.id),
2518                kind: hir::ConstArgKind::Infer(()),
2519                span,
2520            },
2521            ExprKind::Block(block, _) => {
2522                if let [stmt] = block.stmts.as_slice()
2523                    && let StmtKind::Expr(expr) = &stmt.kind
2524                {
2525                    return self.lower_expr_to_const_arg_direct(expr);
2526                }
2527
2528                overly_complex_const(self)
2529            }
2530            ExprKind::Lit(literal) => {
2531                let span = expr.span;
2532                let literal = self.lower_lit(literal, span);
2533
2534                ConstArg {
2535                    hir_id: self.lower_node_id(expr.id),
2536                    kind: hir::ConstArgKind::Literal { lit: literal.node, negated: false },
2537                    span,
2538                }
2539            }
2540            ExprKind::Unary(UnOp::Neg, inner_expr)
2541                if let ExprKind::Lit(literal) = &inner_expr.kind =>
2542            {
2543                let span = expr.span;
2544                let literal = self.lower_lit(literal, span);
2545
2546                if !matches!(literal.node, LitKind::Int(..)) {
2547                    let err =
2548                        self.dcx().struct_span_err(expr.span, "negated literal must be an integer");
2549
2550                    return ConstArg {
2551                        hir_id: self.next_id(),
2552                        kind: hir::ConstArgKind::Error(err.emit()),
2553                        span,
2554                    };
2555                }
2556
2557                ConstArg {
2558                    hir_id: self.lower_node_id(expr.id),
2559                    kind: hir::ConstArgKind::Literal { lit: literal.node, negated: true },
2560                    span,
2561                }
2562            }
2563            ExprKind::ConstBlock(anon_const) => {
2564                let def_id = self.local_def_id(anon_const.id);
2565                assert_eq!(DefKind::AnonConst, self.tcx.def_kind(def_id));
2566                self.lower_anon_const_to_const_arg(anon_const, span)
2567            }
2568            _ => overly_complex_const(self),
2569        }
2570    }
2571
2572    /// See [`hir::ConstArg`] for when to use this function vs
2573    /// [`Self::lower_anon_const_to_anon_const`].
2574    fn lower_anon_const_to_const_arg_and_alloc(
2575        &mut self,
2576        anon: &AnonConst,
2577    ) -> &'hir hir::ConstArg<'hir> {
2578        self.arena.alloc(self.lower_anon_const_to_const_arg(anon, anon.value.span))
2579    }
2580
2581    #[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(2581u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["anon", "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(&anon)
                                                            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::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, span);
                            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, anon.value.span);
            ConstArg {
                hir_id: self.next_id(),
                kind: hir::ConstArgKind::Anon(lowered_anon),
                span: self.lower_span(expr.span),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2582    fn lower_anon_const_to_const_arg(
2583        &mut self,
2584        anon: &AnonConst,
2585        span: Span,
2586    ) -> hir::ConstArg<'hir> {
2587        let tcx = self.tcx;
2588
2589        // We cannot change parsing depending on feature gates available,
2590        // we can only require feature gates to be active as a delayed check.
2591        // Thus we just parse anon consts generally and make the real decision
2592        // making in ast lowering.
2593        // FIXME(min_generic_const_args): revisit once stable
2594        if tcx.features().min_generic_const_args() {
2595            return match anon.mgca_disambiguation {
2596                MgcaDisambiguation::AnonConst => {
2597                    let lowered_anon = self.lower_anon_const_to_anon_const(anon, span);
2598                    ConstArg {
2599                        hir_id: self.next_id(),
2600                        kind: hir::ConstArgKind::Anon(lowered_anon),
2601                        span: lowered_anon.span,
2602                    }
2603                }
2604                MgcaDisambiguation::Direct => self.lower_expr_to_const_arg_direct(&anon.value),
2605            };
2606        }
2607
2608        // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2609        // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2610        let expr = if let ExprKind::Block(block, _) = &anon.value.kind
2611            && let [stmt] = block.stmts.as_slice()
2612            && let StmtKind::Expr(expr) = &stmt.kind
2613            && let ExprKind::Path(..) = &expr.kind
2614        {
2615            expr
2616        } else {
2617            &anon.value
2618        };
2619
2620        let maybe_res =
2621            self.resolver.get_partial_res(expr.id).and_then(|partial_res| partial_res.full_res());
2622        if let ExprKind::Path(qself, path) = &expr.kind
2623            && path.is_potential_trivial_const_arg()
2624            && matches!(maybe_res, Some(Res::Def(DefKind::ConstParam, _)))
2625        {
2626            let qpath = self.lower_qpath(
2627                expr.id,
2628                qself,
2629                path,
2630                ParamMode::Explicit,
2631                AllowReturnTypeNotation::No,
2632                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2633                None,
2634            );
2635
2636            return ConstArg {
2637                hir_id: self.lower_node_id(anon.id),
2638                kind: hir::ConstArgKind::Path(qpath),
2639                span: self.lower_span(expr.span),
2640            };
2641        }
2642
2643        let lowered_anon = self.lower_anon_const_to_anon_const(anon, anon.value.span);
2644        ConstArg {
2645            hir_id: self.next_id(),
2646            kind: hir::ConstArgKind::Anon(lowered_anon),
2647            span: self.lower_span(expr.span),
2648        }
2649    }
2650
2651    /// See [`hir::ConstArg`] for when to use this function vs
2652    /// [`Self::lower_anon_const_to_const_arg`].
2653    fn lower_anon_const_to_anon_const(
2654        &mut self,
2655        c: &AnonConst,
2656        span: Span,
2657    ) -> &'hir hir::AnonConst {
2658        self.arena.alloc(self.with_new_scopes(c.value.span, |this| {
2659            let def_id = this.local_def_id(c.id);
2660            let hir_id = this.lower_node_id(c.id);
2661            hir::AnonConst {
2662                def_id,
2663                hir_id,
2664                body: this.lower_const_body(c.value.span, Some(&c.value)),
2665                span: this.lower_span(span),
2666            }
2667        }))
2668    }
2669
2670    fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2671        match u {
2672            CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2673            UserProvided => hir::UnsafeSource::UserProvided,
2674        }
2675    }
2676
2677    fn lower_trait_bound_modifiers(
2678        &mut self,
2679        modifiers: TraitBoundModifiers,
2680    ) -> hir::TraitBoundModifiers {
2681        let constness = match modifiers.constness {
2682            BoundConstness::Never => BoundConstness::Never,
2683            BoundConstness::Always(span) => BoundConstness::Always(self.lower_span(span)),
2684            BoundConstness::Maybe(span) => BoundConstness::Maybe(self.lower_span(span)),
2685        };
2686        let polarity = match modifiers.polarity {
2687            BoundPolarity::Positive => BoundPolarity::Positive,
2688            BoundPolarity::Negative(span) => BoundPolarity::Negative(self.lower_span(span)),
2689            BoundPolarity::Maybe(span) => BoundPolarity::Maybe(self.lower_span(span)),
2690        };
2691        hir::TraitBoundModifiers { constness, polarity }
2692    }
2693
2694    // Helper methods for building HIR.
2695
2696    fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2697        hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2698    }
2699
2700    fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2701        self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2702    }
2703
2704    fn stmt_let_pat(
2705        &mut self,
2706        attrs: Option<&'hir [hir::Attribute]>,
2707        span: Span,
2708        init: Option<&'hir hir::Expr<'hir>>,
2709        pat: &'hir hir::Pat<'hir>,
2710        source: hir::LocalSource,
2711    ) -> hir::Stmt<'hir> {
2712        let hir_id = self.next_id();
2713        if let Some(a) = attrs {
2714            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
2715            self.attrs.insert(hir_id.local_id, a);
2716        }
2717        let local = hir::LetStmt {
2718            super_: None,
2719            hir_id,
2720            init,
2721            pat,
2722            els: None,
2723            source,
2724            span: self.lower_span(span),
2725            ty: None,
2726        };
2727        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
2728    }
2729
2730    fn stmt_super_let_pat(
2731        &mut self,
2732        span: Span,
2733        pat: &'hir hir::Pat<'hir>,
2734        init: Option<&'hir hir::Expr<'hir>>,
2735    ) -> hir::Stmt<'hir> {
2736        let hir_id = self.next_id();
2737        let span = self.lower_span(span);
2738        let local = hir::LetStmt {
2739            super_: Some(span),
2740            hir_id,
2741            init,
2742            pat,
2743            els: None,
2744            source: hir::LocalSource::Normal,
2745            span,
2746            ty: None,
2747        };
2748        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
2749    }
2750
2751    fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2752        self.block_all(expr.span, &[], Some(expr))
2753    }
2754
2755    fn block_all(
2756        &mut self,
2757        span: Span,
2758        stmts: &'hir [hir::Stmt<'hir>],
2759        expr: Option<&'hir hir::Expr<'hir>>,
2760    ) -> &'hir hir::Block<'hir> {
2761        let blk = hir::Block {
2762            stmts,
2763            expr,
2764            hir_id: self.next_id(),
2765            rules: hir::BlockCheckMode::DefaultBlock,
2766            span: self.lower_span(span),
2767            targeted_by_break: false,
2768        };
2769        self.arena.alloc(blk)
2770    }
2771
2772    fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2773        let field = self.single_pat_field(span, pat);
2774        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field)
2775    }
2776
2777    fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2778        let field = self.single_pat_field(span, pat);
2779        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field)
2780    }
2781
2782    fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2783        let field = self.single_pat_field(span, pat);
2784        self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field)
2785    }
2786
2787    fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2788        self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[])
2789    }
2790
2791    fn single_pat_field(
2792        &mut self,
2793        span: Span,
2794        pat: &'hir hir::Pat<'hir>,
2795    ) -> &'hir [hir::PatField<'hir>] {
2796        let field = hir::PatField {
2797            hir_id: self.next_id(),
2798            ident: Ident::new(sym::integer(0), self.lower_span(span)),
2799            is_shorthand: false,
2800            pat,
2801            span: self.lower_span(span),
2802        };
2803        self.arena.alloc_from_iter([field])arena_vec![self; field]
2804    }
2805
2806    fn pat_lang_item_variant(
2807        &mut self,
2808        span: Span,
2809        lang_item: hir::LangItem,
2810        fields: &'hir [hir::PatField<'hir>],
2811    ) -> &'hir hir::Pat<'hir> {
2812        let path = self.make_lang_item_qpath(lang_item, self.lower_span(span), None);
2813        self.pat(span, hir::PatKind::Struct(path, fields, None))
2814    }
2815
2816    fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, HirId) {
2817        self.pat_ident_binding_mode(span, ident, hir::BindingMode::NONE)
2818    }
2819
2820    fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, HirId) {
2821        self.pat_ident_binding_mode_mut(span, ident, hir::BindingMode::NONE)
2822    }
2823
2824    fn pat_ident_binding_mode(
2825        &mut self,
2826        span: Span,
2827        ident: Ident,
2828        bm: hir::BindingMode,
2829    ) -> (&'hir hir::Pat<'hir>, HirId) {
2830        let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2831        (self.arena.alloc(pat), hir_id)
2832    }
2833
2834    fn pat_ident_binding_mode_mut(
2835        &mut self,
2836        span: Span,
2837        ident: Ident,
2838        bm: hir::BindingMode,
2839    ) -> (hir::Pat<'hir>, HirId) {
2840        let hir_id = self.next_id();
2841
2842        (
2843            hir::Pat {
2844                hir_id,
2845                kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2846                span: self.lower_span(span),
2847                default_binding_modes: true,
2848            },
2849            hir_id,
2850        )
2851    }
2852
2853    fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2854        self.arena.alloc(hir::Pat {
2855            hir_id: self.next_id(),
2856            kind,
2857            span: self.lower_span(span),
2858            default_binding_modes: true,
2859        })
2860    }
2861
2862    fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2863        hir::Pat {
2864            hir_id: self.next_id(),
2865            kind,
2866            span: self.lower_span(span),
2867            default_binding_modes: false,
2868        }
2869    }
2870
2871    fn ty_path(&mut self, mut hir_id: HirId, span: Span, qpath: hir::QPath<'hir>) -> hir::Ty<'hir> {
2872        let kind = match qpath {
2873            hir::QPath::Resolved(None, path) => {
2874                // Turn trait object paths into `TyKind::TraitObject` instead.
2875                match path.res {
2876                    Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2877                        let principal = hir::PolyTraitRef {
2878                            bound_generic_params: &[],
2879                            modifiers: hir::TraitBoundModifiers::NONE,
2880                            trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2881                            span: self.lower_span(span),
2882                        };
2883
2884                        // The original ID is taken by the `PolyTraitRef`,
2885                        // so the `Ty` itself needs a different one.
2886                        hir_id = self.next_id();
2887                        hir::TyKind::TraitObject(
2888                            self.arena.alloc_from_iter([principal])arena_vec![self; principal],
2889                            TaggedRef::new(self.elided_dyn_bound(span), TraitObjectSyntax::None),
2890                        )
2891                    }
2892                    _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2893                }
2894            }
2895            _ => hir::TyKind::Path(qpath),
2896        };
2897
2898        hir::Ty { hir_id, kind, span: self.lower_span(span) }
2899    }
2900
2901    /// Invoked to create the lifetime argument(s) for an elided trait object
2902    /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2903    /// when the bound is written, even if it is written with `'_` like in
2904    /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2905    fn elided_dyn_bound(&mut self, span: Span) -> &'hir hir::Lifetime {
2906        let r = hir::Lifetime::new(
2907            self.next_id(),
2908            Ident::new(kw::UnderscoreLifetime, self.lower_span(span)),
2909            hir::LifetimeKind::ImplicitObjectLifetimeDefault,
2910            LifetimeSource::Other,
2911            LifetimeSyntax::Implicit,
2912        );
2913        {
    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:2913",
                        "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(2913u32),
                        ::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);
2914        self.arena.alloc(r)
2915    }
2916}
2917
2918/// Helper struct for the delayed construction of [`hir::GenericArgs`].
2919struct GenericArgsCtor<'hir> {
2920    args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2921    constraints: &'hir [hir::AssocItemConstraint<'hir>],
2922    parenthesized: hir::GenericArgsParentheses,
2923    span: Span,
2924}
2925
2926impl<'hir> GenericArgsCtor<'hir> {
2927    fn is_empty(&self) -> bool {
2928        self.args.is_empty()
2929            && self.constraints.is_empty()
2930            && self.parenthesized == hir::GenericArgsParentheses::No
2931    }
2932
2933    fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2934        let ga = hir::GenericArgs {
2935            args: this.arena.alloc_from_iter(self.args),
2936            constraints: self.constraints,
2937            parenthesized: self.parenthesized,
2938            span_ext: this.lower_span(self.span),
2939        };
2940        this.arena.alloc(ga)
2941    }
2942}