Skip to main content

rustc_ast_lowering/
lib.rs

1//! Lowers the AST to the HIR.
2//!
3//! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
4//! much like a fold. Where lowering involves a bit more work things get more
5//! interesting and there are some invariants you should know about. These mostly
6//! concern spans and IDs.
7//!
8//! Spans are assigned to AST nodes during parsing and then are modified during
9//! expansion to indicate the origin of a node and the process it went through
10//! being expanded. IDs are assigned to AST nodes just before lowering.
11//!
12//! For the simpler lowering steps, IDs and spans should be preserved. Unlike
13//! expansion we do not preserve the process of lowering in the spans, so spans
14//! should not be modified here. When creating a new node (as opposed to
15//! "folding" an existing one), create a new ID using `next_id()`.
16//!
17//! You must ensure that IDs are unique. That means that you should only use the
18//! ID from an AST node in a single HIR node (you can assume that AST node-IDs
19//! are unique). Every new node must have a unique ID. Avoid cloning HIR nodes.
20//! If you do, you must then set the new node's ID to a fresh one.
21//!
22//! Spans are used for error messages and for tools to map semantics back to
23//! source code. It is therefore not as important with spans as IDs to be strict
24//! about use (you can't break the compiler by screwing up a span). Obviously, a
25//! HIR node can only have a single span. But multiple nodes can have the same
26//! span and spans don't need to be kept in order, etc. Where code is preserved
27//! by lowering, it should have the same span as in the AST. Where HIR nodes are
28//! new it is probably best to give a span for the whole AST node being lowered.
29//! All nodes should have real spans; don't use dummy spans. Tools are likely to
30//! get confused if the spans from leaf AST nodes occur in multiple places
31//! in the HIR, especially for multiple identifiers.
32
33// tidy-alphabetical-start
34#![feature(const_default)]
35#![feature(const_trait_impl)]
36#![feature(default_field_values)]
37#![feature(deref_patterns)]
38#![recursion_limit = "256"]
39// tidy-alphabetical-end
40
41use std::mem;
42use std::sync::Arc;
43
44use rustc_ast::mut_visit::{self, MutVisitor};
45use rustc_ast::node_id::NodeMap;
46use rustc_ast::visit::{self, Visitor};
47use rustc_ast::{self as ast, *};
48use rustc_attr_parsing::{AttributeParser, OmitDoc, Recovery, ShouldEmit};
49use rustc_data_structures::fx::FxIndexMap;
50use rustc_data_structures::sorted_map::SortedMap;
51use rustc_data_structures::stable_hash::{StableHash, StableHasher};
52use rustc_data_structures::steal::Steal;
53use rustc_data_structures::tagged_ptr::TaggedRef;
54use rustc_data_structures::unord::ExtendUnord;
55use rustc_errors::codes::*;
56use rustc_errors::{DiagArgFromDisplay, DiagCtxtHandle, ErrorGuaranteed};
57use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
58use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
59use rustc_hir::definitions::PerParentDisambiguatorState;
60use rustc_hir::lints::DelayedLint;
61use rustc_hir::{
62    self as hir, AngleBrackets, ConstArg, GenericArg, HirId, ItemLocalMap, LifetimeSource,
63    LifetimeSyntax, MissingLifetimeKind, ParamName, Target, TraitCandidate, find_attr,
64};
65use rustc_index::{Idx, IndexVec};
66use rustc_macros::extension;
67use rustc_middle::queries::Providers;
68use rustc_middle::span_bug;
69use rustc_middle::ty::{PerOwnerResolverData, ResolverAstLowering, TyCtxt};
70use rustc_session::diagnostics::add_feature_diagnostics;
71use rustc_span::symbol::{Ident, Symbol, kw, sym};
72use rustc_span::{DUMMY_SP, DesugaringKind, Span};
73use smallvec::{SmallVec, smallvec};
74use thin_vec::ThinVec;
75use tracing::{debug, instrument, trace};
76
77use crate::diagnostics::{AssocTyParentheses, AssocTyParenthesesSub, MisplacedImplTrait};
78
79macro_rules! arena_vec {
80    ($this:expr; $($x:expr),*) => (
81        $this.arena.alloc_from_iter([$($x),*])
82    );
83}
84
85mod asm;
86mod block;
87mod contract;
88mod delegation;
89mod diagnostics;
90mod expr;
91mod format;
92mod index;
93mod item;
94mod pat;
95mod path;
96pub mod stability;
97
98pub fn provide(providers: &mut Providers) {
99    providers.index_ast = index_ast;
100    providers.lower_to_hir = lower_to_hir;
101}
102
103#[cfg(debug_assertions)]
104pub(crate) mod re_lowering {
105    use rustc_ast::NodeId;
106    use rustc_ast::node_id::NodeMap;
107    use rustc_hir::{self as hir};
108
109    use crate::LoweringContext;
110
111    #[derive(#[automatically_derived]
impl ::core::fmt::Debug for ReloweringChecker {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ReloweringChecker", "node_id_to_local_id",
            &self.node_id_to_local_id, "can_relower", &&self.can_relower)
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for ReloweringChecker {
    #[inline]
    fn default() -> ReloweringChecker {
        ReloweringChecker {
            node_id_to_local_id: ::core::default::Default::default(),
            can_relower: ::core::default::Default::default(),
        }
    }
}Default)]
112    pub(crate) struct ReloweringChecker {
113        node_id_to_local_id: NodeMap<hir::ItemLocalId>,
114        can_relower: bool,
115    }
116
117    impl ReloweringChecker {
118        pub(crate) fn assert_node_is_not_relowered(
119            &mut self,
120            ast_node_id: NodeId,
121            local_id: hir::ItemLocalId,
122        ) {
123            if !self.can_relower {
124                let old = self.node_id_to_local_id.insert(ast_node_id, local_id);
125                {
    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);
            }
        }
    }
};assert_eq!(old, None);
126            }
127        }
128
129        pub(crate) fn allow_relowering<'a, 'hir, TRes>(
130            ctx: &mut LoweringContext<'a, 'hir>,
131            op: impl FnOnce(&mut LoweringContext<'a, 'hir>) -> TRes,
132        ) -> TRes {
133            if !!ctx.relowering_checker.can_relower {
    {
        ::core::panicking::panic_fmt(format_args!("reentrant relowering is not supported"));
    }
};assert!(!ctx.relowering_checker.can_relower, "reentrant relowering is not supported");
134
135            ctx.relowering_checker.can_relower = true;
136
137            let res = op(ctx);
138
139            ctx.relowering_checker.can_relower = false;
140
141            res
142        }
143    }
144}
145
146struct LoweringContext<'a, 'hir> {
147    tcx: TyCtxt<'hir>,
148    resolver: &'a ResolverAstLowering<'hir>,
149    current_disambiguator: PerParentDisambiguatorState,
150
151    /// Used to allocate HIR nodes.
152    arena: &'hir hir::Arena<'hir>,
153
154    /// Bodies inside the owner being lowered.
155    bodies: Vec<(hir::ItemLocalId, &'hir hir::Body<'hir>)>,
156    /// `#[define_opaque]` attributes
157    define_opaque: Option<&'hir [(Span, LocalDefId)]>,
158    /// Attributes inside the owner being lowered.
159    attrs: SortedMap<hir::ItemLocalId, &'hir [hir::Attribute]>,
160    /// Collect items that were created by lowering the current owner.
161    children: LocalDefIdMap<hir::MaybeOwner<'hir>>,
162
163    contract_ensures: Option<(Span, Ident, HirId)>,
164
165    coroutine_kind: Option<hir::CoroutineKind>,
166
167    /// When inside an `async` context, this is the `HirId` of the
168    /// `task_context` local bound to the resume argument of the coroutine.
169    task_context: Option<HirId>,
170
171    /// Used to get the current `fn`'s def span to point to when using `await`
172    /// outside of an `async fn`.
173    current_item: Option<Span>,
174
175    try_block_scope: TryBlockScope,
176    loop_scope: Option<HirId>,
177    is_in_loop_condition: bool,
178    is_in_dyn_type: bool,
179
180    current_hir_id_owner: hir::OwnerId,
181    owner: &'a PerOwnerResolverData<'hir>,
182    item_local_id_counter: hir::ItemLocalId,
183    trait_map: ItemLocalMap<&'hir [TraitCandidate<'hir>]>,
184
185    impl_trait_defs: Vec<hir::GenericParam<'hir>>,
186    impl_trait_bounds: Vec<hir::WherePredicate<'hir>>,
187
188    /// NodeIds of pattern identifiers and labelled nodes that are lowered inside the current HIR owner.
189    ident_and_label_to_local_id: NodeMap<hir::ItemLocalId>,
190    /// NodeIds that are lowered inside the current HIR owner. Only used for duplicate lowering check.
191    #[cfg(debug_assertions)]
192    relowering_checker: re_lowering::ReloweringChecker,
193    /// The `NodeId` space is split in two.
194    /// `0..resolver.next_node_id` are created by the resolver on the AST.
195    /// The higher part `resolver.next_node_id..next_node_id` are created during lowering.
196    next_node_id: NodeId,
197    /// Maps the `NodeId`s created during lowering to `LocalDefId`s.
198    node_id_to_def_id: NodeMap<LocalDefId>,
199    /// Overlay over resolver's `partial_res_map` used by delegation.
200    /// This only contains `PartialRes::new(Res::Local(self_param_id))`,
201    /// so we only store `self_param_id`.
202    partial_res_overrides: NodeMap<NodeId>,
203
204    allow_contracts: Arc<[Symbol]>,
205    allow_try_trait: Arc<[Symbol]>,
206    allow_gen_future: Arc<[Symbol]>,
207    allow_pattern_type: Arc<[Symbol]>,
208    allow_async_gen: Arc<[Symbol]>,
209    allow_async_iterator: Arc<[Symbol]>,
210    allow_for_await: Arc<[Symbol]>,
211    allow_async_fn_traits: Arc<[Symbol]>,
212
213    delayed_lints: Vec<DelayedLint>,
214
215    /// Stack of `move(...)` collection states. A plain closure body pushes
216    /// `Some`, so `move(...)` expressions can record the generated locals they
217    /// should lower to. Nested bodies that cannot use `move(...)` push `None`.
218    move_expr_bindings: Vec<Option<expr::MoveExprState<'hir>>>,
219
220    attribute_parser: AttributeParser<'hir>,
221}
222
223impl<'a, 'hir> LoweringContext<'a, 'hir> {
224    fn new(tcx: TyCtxt<'hir>, resolver: &'a ResolverAstLowering<'hir>, owner: NodeId) -> Self {
225        let current_ast_owner = &resolver.owners[&owner];
226        let current_hir_id_owner = hir::OwnerId { def_id: current_ast_owner.def_id };
227        let current_disambiguator = resolver
228            .disambiguators
229            .get(&current_hir_id_owner.def_id)
230            .map(|s| s.steal())
231            .unwrap_or_else(|| PerParentDisambiguatorState::new(current_hir_id_owner.def_id));
232
233        Self {
234            tcx,
235            resolver,
236            current_disambiguator,
237            owner: current_ast_owner,
238            arena: tcx.hir_arena,
239
240            // HirId handling.
241            bodies: Vec::new(),
242            define_opaque: None,
243            attrs: SortedMap::default(),
244            children: LocalDefIdMap::default(),
245            contract_ensures: None,
246            current_hir_id_owner,
247            // 0 corresponds to `owner` lowered as `current_hir_id_owner`,
248            // and we never call `lower_node_id(owner)`.
249            item_local_id_counter: hir::ItemLocalId::new(1),
250            ident_and_label_to_local_id: Default::default(),
251
252            #[cfg(debug_assertions)]
253            relowering_checker: Default::default(),
254
255            trait_map: Default::default(),
256            next_node_id: resolver.next_node_id,
257            node_id_to_def_id: NodeMap::default(),
258            partial_res_overrides: NodeMap::default(),
259
260            // Lowering state.
261            try_block_scope: TryBlockScope::Function,
262            loop_scope: None,
263            is_in_loop_condition: false,
264            is_in_dyn_type: false,
265            coroutine_kind: None,
266            task_context: None,
267            current_item: None,
268            impl_trait_defs: Vec::new(),
269            impl_trait_bounds: Vec::new(),
270            allow_contracts: [sym::contracts_internals].into(),
271            allow_try_trait: [
272                sym::try_trait_v2,
273                sym::try_trait_v2_residual,
274                sym::yeet_desugar_details,
275            ]
276            .into(),
277            allow_pattern_type: [sym::pattern_types, sym::pattern_type_range_trait].into(),
278            allow_gen_future: if tcx.features().async_fn_track_caller() {
279                [sym::gen_future, sym::closure_track_caller].into()
280            } else {
281                [sym::gen_future].into()
282            },
283            allow_for_await: [sym::async_gen_internals, sym::async_iterator].into(),
284            allow_async_fn_traits: [sym::async_fn_traits].into(),
285            allow_async_gen: [sym::async_gen_internals].into(),
286            // FIXME(gen_blocks): how does `closure_track_caller`/`async_fn_track_caller`
287            // interact with `gen`/`async gen` blocks
288            allow_async_iterator: [sym::gen_future, sym::async_iterator].into(),
289
290            move_expr_bindings: Vec::new(),
291            attribute_parser: AttributeParser::new(
292                tcx.sess,
293                tcx.features(),
294                tcx.registered_tools(()),
295                ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
296            ),
297            delayed_lints: Vec::new(),
298        }
299    }
300
301    pub(crate) fn dcx(&self) -> DiagCtxtHandle<'hir> {
302        self.tcx.dcx()
303    }
304}
305
306struct SpanLowerer {
307    is_incremental: bool,
308    def_id: LocalDefId,
309}
310
311impl SpanLowerer {
312    fn lower(&self, span: Span) -> Span {
313        if self.is_incremental {
314            span.with_parent(Some(self.def_id))
315        } else {
316            // Do not make spans relative when not using incremental compilation.
317            span
318        }
319    }
320}
321
322impl<'tcx> ResolverAstLoweringExt<'tcx> for ResolverAstLowering<'tcx> {
    fn legacy_const_generic_args(&self, expr: &Expr, tcx: TyCtxt<'tcx>)
        -> Option<Vec<usize>> {
        let ExprKind::Path(None, path) = &expr.kind else { return None; };
        if path.segments.last().unwrap().args.is_some() { return None; }
        let def_id =
            self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
        if def_id.is_local() { return None; }
        {
                {
                    'done:
                        {
                        for i in
                            ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
                            #[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())
    }
}#[extension(trait ResolverAstLoweringExt<'tcx>)]
323impl<'tcx> ResolverAstLowering<'tcx> {
324    fn legacy_const_generic_args(&self, expr: &Expr, tcx: TyCtxt<'tcx>) -> Option<Vec<usize>> {
325        let ExprKind::Path(None, path) = &expr.kind else {
326            return None;
327        };
328
329        // Don't perform legacy const generics rewriting if the path already
330        // has generic arguments.
331        if path.segments.last().unwrap().args.is_some() {
332            return None;
333        }
334
335        // We do not need to look at `partial_res_overrides`. That map only contains overrides for
336        // `self_param` locals. And here we are looking for the function definition that `expr`
337        // resolves to.
338        let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
339
340        // We only support cross-crate argument rewriting. Uses
341        // within the same crate should be updated to use the new
342        // const generics style.
343        if def_id.is_local() {
344            return None;
345        }
346
347        // we can use parsed attrs here since for other crates they're already available
348        find_attr!(
349            tcx, def_id,
350            RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
351        )
352        .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
353    }
354}
355
356/// How relaxed bounds `?Trait` should be treated.
357///
358/// Relaxed bounds should only be allowed in places where we later
359/// (namely during HIR ty lowering) perform *sized elaboration*.
360#[derive(#[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(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Allowed", &__self_0),
            RelaxedBoundPolicy::Forbidden(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Forbidden", &__self_0),
        }
    }
}Debug)]
361enum RelaxedBoundPolicy<'a> {
362    /// The `DefId` refers to the trait that is being relaxed.
363    Allowed(&'a mut FxIndexMap<DefId, Span>),
364    Forbidden(RelaxedBoundForbiddenReason),
365}
366impl RelaxedBoundPolicy<'_> {
367    fn reborrow(&mut self) -> RelaxedBoundPolicy<'_> {
368        match self {
369            RelaxedBoundPolicy::Allowed(m) => RelaxedBoundPolicy::Allowed(m),
370            RelaxedBoundPolicy::Forbidden(reason) => RelaxedBoundPolicy::Forbidden(*reason),
371        }
372    }
373}
374
375#[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::WhereBound => "WhereBound",
            })
    }
}Debug)]
376enum RelaxedBoundForbiddenReason {
377    TraitObjectTy,
378    SuperTrait,
379    TraitAlias,
380    AssocTyBounds,
381    /// We do not allow where bounds doing relaxed bounds,
382    /// except if it's for generic parameters of the current item.
383    WhereBound,
384}
385
386/// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
387/// and if so, what meaning it has.
388#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ImplTraitContext {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ImplTraitContext::Universal =>
                ::core::fmt::Formatter::write_str(f, "Universal"),
            ImplTraitContext::OpaqueTy { origin: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OpaqueTy", "origin", &__self_0),
            ImplTraitContext::InBinding =>
                ::core::fmt::Formatter::write_str(f, "InBinding"),
            ImplTraitContext::FeatureGated(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "FeatureGated", __self_0, &__self_1),
            ImplTraitContext::Disallowed(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Disallowed", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ImplTraitContext { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ImplTraitContext {
    #[inline]
    fn clone(&self) -> ImplTraitContext {
        let _:
                ::core::clone::AssertParamIsClone<hir::OpaqueTyOrigin<LocalDefId>>;
        let _: ::core::clone::AssertParamIsClone<ImplTraitPosition>;
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ImplTraitContext {
    #[inline]
    fn eq(&self, other: &ImplTraitContext) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ImplTraitContext::OpaqueTy { origin: __self_0 },
                    ImplTraitContext::OpaqueTy { origin: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                (ImplTraitContext::FeatureGated(__self_0, __self_1),
                    ImplTraitContext::FeatureGated(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (ImplTraitContext::Disallowed(__self_0),
                    ImplTraitContext::Disallowed(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ImplTraitContext {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<hir::OpaqueTyOrigin<LocalDefId>>;
        let _: ::core::cmp::AssertParamIsEq<ImplTraitPosition>;
        let _: ::core::cmp::AssertParamIsEq<Symbol>;
    }
}Eq)]
389enum ImplTraitContext {
390    /// Treat `impl Trait` as shorthand for a new universal generic parameter.
391    /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
392    /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
393    ///
394    /// Newly generated parameters should be inserted into the given `Vec`.
395    Universal,
396
397    /// Treat `impl Trait` as shorthand for a new opaque type.
398    /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
399    /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
400    ///
401    OpaqueTy { origin: hir::OpaqueTyOrigin<LocalDefId> },
402
403    /// Treat `impl Trait` as a "trait ascription", which is like a type
404    /// variable but that also enforces that a set of trait goals hold.
405    ///
406    /// This is useful to guide inference for unnameable types.
407    InBinding,
408
409    /// `impl Trait` is unstably accepted in this position.
410    FeatureGated(ImplTraitPosition, Symbol),
411    /// `impl Trait` is not accepted in this position.
412    Disallowed(ImplTraitPosition),
413}
414
415/// Position in which `impl Trait` is disallowed.
416#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ImplTraitPosition {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ImplTraitPosition::Path => "Path",
                ImplTraitPosition::Variable => "Variable",
                ImplTraitPosition::Trait => "Trait",
                ImplTraitPosition::Bound => "Bound",
                ImplTraitPosition::Generic => "Generic",
                ImplTraitPosition::ExternFnParam => "ExternFnParam",
                ImplTraitPosition::ClosureParam => "ClosureParam",
                ImplTraitPosition::PointerParam => "PointerParam",
                ImplTraitPosition::FnTraitParam => "FnTraitParam",
                ImplTraitPosition::ExternFnReturn => "ExternFnReturn",
                ImplTraitPosition::ClosureReturn => "ClosureReturn",
                ImplTraitPosition::PointerReturn => "PointerReturn",
                ImplTraitPosition::FnTraitReturn => "FnTraitReturn",
                ImplTraitPosition::GenericDefault => "GenericDefault",
                ImplTraitPosition::ConstTy => "ConstTy",
                ImplTraitPosition::StaticTy => "StaticTy",
                ImplTraitPosition::AssocTy => "AssocTy",
                ImplTraitPosition::FieldTy => "FieldTy",
                ImplTraitPosition::Cast => "Cast",
                ImplTraitPosition::ImplSelf => "ImplSelf",
                ImplTraitPosition::OffsetOf => "OffsetOf",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ImplTraitPosition { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ImplTraitPosition {
    #[inline]
    fn clone(&self) -> ImplTraitPosition { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ImplTraitPosition {
    #[inline]
    fn eq(&self, other: &ImplTraitPosition) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ImplTraitPosition {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
417enum ImplTraitPosition {
418    Path,
419    Variable,
420    Trait,
421    Bound,
422    Generic,
423    ExternFnParam,
424    ClosureParam,
425    PointerParam,
426    FnTraitParam,
427    ExternFnReturn,
428    ClosureReturn,
429    PointerReturn,
430    FnTraitReturn,
431    GenericDefault,
432    ConstTy,
433    StaticTy,
434    AssocTy,
435    FieldTy,
436    Cast,
437    ImplSelf,
438    OffsetOf,
439}
440
441impl std::fmt::Display for ImplTraitPosition {
442    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
443        let name = match self {
444            ImplTraitPosition::Path => "paths",
445            ImplTraitPosition::Variable => "the type of variable bindings",
446            ImplTraitPosition::Trait => "traits",
447            ImplTraitPosition::Bound => "bounds",
448            ImplTraitPosition::Generic => "generics",
449            ImplTraitPosition::ExternFnParam => "`extern fn` parameters",
450            ImplTraitPosition::ClosureParam => "closure parameters",
451            ImplTraitPosition::PointerParam => "`fn` pointer parameters",
452            ImplTraitPosition::FnTraitParam => "the parameters of `Fn` trait bounds",
453            ImplTraitPosition::ExternFnReturn => "`extern fn` return types",
454            ImplTraitPosition::ClosureReturn => "closure return types",
455            ImplTraitPosition::PointerReturn => "`fn` pointer return types",
456            ImplTraitPosition::FnTraitReturn => "the return type of `Fn` trait bounds",
457            ImplTraitPosition::GenericDefault => "generic parameter defaults",
458            ImplTraitPosition::ConstTy => "const types",
459            ImplTraitPosition::StaticTy => "static types",
460            ImplTraitPosition::AssocTy => "associated types",
461            ImplTraitPosition::FieldTy => "field types",
462            ImplTraitPosition::Cast => "cast expression types",
463            ImplTraitPosition::ImplSelf => "impl headers",
464            ImplTraitPosition::OffsetOf => "`offset_of!` parameters",
465        };
466
467        f.write_fmt(format_args!("{0}", name))write!(f, "{name}")
468    }
469}
470
471#[derive(#[automatically_derived]
impl ::core::marker::Copy for FnDeclKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for FnDeclKind {
    #[inline]
    fn clone(&self) -> FnDeclKind { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for FnDeclKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                FnDeclKind::Fn => "Fn",
                FnDeclKind::Inherent => "Inherent",
                FnDeclKind::ExternFn => "ExternFn",
                FnDeclKind::Closure => "Closure",
                FnDeclKind::Pointer => "Pointer",
                FnDeclKind::Trait => "Trait",
                FnDeclKind::Impl => "Impl",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for FnDeclKind {
    #[inline]
    fn eq(&self, other: &FnDeclKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for FnDeclKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
472enum FnDeclKind {
473    Fn,
474    Inherent,
475    ExternFn,
476    Closure,
477    Pointer,
478    Trait,
479    Impl,
480}
481
482#[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)]
483enum TryBlockScope {
484    /// There isn't a `try` block, so a `?` will use `return`.
485    Function,
486    /// We're inside a `try { … }` block, so a `?` will block-break
487    /// from that block using a type depending only on the argument.
488    Homogeneous(HirId),
489    /// We're inside a `try as _ { … }` block, so a `?` will block-break
490    /// from that block using the type specified.
491    Heterogeneous(HirId),
492}
493
494fn index_ast<'tcx>(
495    tcx: TyCtxt<'tcx>,
496    (): (),
497) -> IndexVec<LocalDefId, Steal<(Arc<ResolverAstLowering<'tcx>>, AstOwner)>> {
498    // Queries that borrow `resolver_for_lowering`.
499    tcx.ensure_done().output_filenames(());
500    tcx.ensure_done().early_lint_checks(());
501    tcx.ensure_done().get_lang_items(());
502    tcx.ensure_done().debugger_visualizers(LOCAL_CRATE);
503
504    let (resolver, krate) = tcx.resolver_for_lowering();
505    let mut resolver = resolver.steal();
506    let mut krate = krate.steal();
507
508    let mut indexer = Indexer {
509        owners: &resolver.owners,
510        index: IndexVec::new(),
511        next_node_id: resolver.next_node_id,
512    };
513    indexer.visit_crate(&mut krate);
514    indexer.insert(CRATE_NODE_ID, AstOwner::Crate(Box::new(krate)));
515    resolver.next_node_id = indexer.next_node_id;
516
517    let index = indexer.index;
518    let resolver = Arc::new(resolver);
519    let index = index.into_iter().map(|owner| Steal::new((Arc::clone(&resolver), owner))).collect();
520    return index;
521
522    struct Indexer<'s, 'hir> {
523        owners: &'s NodeMap<PerOwnerResolverData<'hir>>,
524        index: IndexVec<LocalDefId, AstOwner>,
525        next_node_id: NodeId,
526    }
527
528    impl Indexer<'_, '_> {
529        fn insert(&mut self, id: NodeId, node: AstOwner) {
530            let def_id = self.owners[&id].def_id;
531            self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
532            self.index[def_id] = node;
533        }
534
535        fn make_dummy<K>(
536            &mut self,
537            id: NodeId,
538            span: Span,
539            dummy: impl FnOnce(Box<MacCall>) -> K,
540        ) -> Box<Item<K>> {
541            use rustc_ast::token::Delimiter;
542            use rustc_ast::tokenstream::{DelimSpan, TokenStream};
543            use thin_vec::thin_vec;
544
545            Box::new(Item {
546                attrs: AttrVec::default(),
547                id,
548                span,
549                vis: Visibility { kind: VisibilityKind::Public, span },
550                // Lacking a better choice, we replace the contents with a macro call.
551                // Unexpanded macros should never reach lowering, so this is not confusing.
552                kind: dummy(Box::new(MacCall {
553                    path: Path { span, segments: ::thin_vec::ThinVec::new()thin_vec![] },
554                    args: Box::new(DelimArgs {
555                        dspan: DelimSpan::from_single(span),
556                        delim: Delimiter::Parenthesis,
557                        tokens: TokenStream::new(Vec::new()),
558                    }),
559                })),
560                tokens: None,
561            })
562        }
563
564        fn replace_with_dummy<K>(
565            &mut self,
566            item: &mut ast::Item<K>,
567            dummy: impl FnOnce(Box<MacCall>) -> K,
568            node: impl FnOnce(Box<Item<K>>) -> AstOwner,
569        ) {
570            let dummy = self.make_dummy(item.id, item.span, dummy);
571            let item = mem::replace(item, *dummy);
572            self.insert(item.id, node(Box::new(item)));
573        }
574
575        #[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("visit_item_id_use_tree",
                                    "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(575u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("tree")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("tree");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("parent")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("parent");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("items")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("items");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tree)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&items)
                                                            as &dyn ::tracing::field::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;
        }
        {
            match tree.kind {
                UseTreeKind::Glob(_) | UseTreeKind::Simple(_) => {}
                UseTreeKind::Nested { items: ref nested_vec, span } => {
                    for &(ref nested, id) in nested_vec {
                        self.insert(id, AstOwner::NestedUseTree(parent));
                        items.push(self.make_dummy(id, span, ItemKind::MacCall));
                        let def_id = self.owners[&id].def_id;
                        self.visit_item_id_use_tree(nested, def_id, items);
                    }
                }
            }
        }
    }
}#[tracing::instrument(level = "trace", skip(self))]
576        fn visit_item_id_use_tree(
577            &mut self,
578            tree: &UseTree,
579            parent: LocalDefId,
580            items: &mut SmallVec<[Box<Item>; 1]>,
581        ) {
582            match tree.kind {
583                UseTreeKind::Glob(_) | UseTreeKind::Simple(_) => {}
584                UseTreeKind::Nested { items: ref nested_vec, span } => {
585                    for &(ref nested, id) in nested_vec {
586                        self.insert(id, AstOwner::NestedUseTree(parent));
587                        items.push(self.make_dummy(id, span, ItemKind::MacCall));
588
589                        let def_id = self.owners[&id].def_id;
590                        self.visit_item_id_use_tree(nested, def_id, items);
591                    }
592                }
593            }
594        }
595    }
596
597    impl MutVisitor for Indexer<'_, '_> {
598        fn visit_attribute(&mut self, _: &mut Attribute) {
599            // We do not want to lower expressions that appear in attributes,
600            // as they are not accessible to the rest of the HIR.
601        }
602
603        fn flat_map_item(&mut self, mut item: Box<Item>) -> SmallVec<[Box<Item>; 1]> {
604            let def_id = self.owners[&item.id].def_id;
605            mut_visit::walk_item(self, &mut *item);
606            let dummy = self.make_dummy(item.id, item.span, ItemKind::MacCall);
607            let mut items = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(dummy);
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [dummy])))
    }
}smallvec![dummy];
608            if let ItemKind::Use(ref use_tree) = item.kind {
609                self.visit_item_id_use_tree(use_tree, def_id, &mut items);
610            }
611            self.insert(item.id, AstOwner::Item(item));
612            items
613        }
614
615        fn flat_map_stmt(&mut self, stmt: Stmt) -> SmallVec<[Stmt; 1]> {
616            let Stmt { id, span, kind } = stmt;
617            let mut id = Some(id);
618            mut_visit::walk_flat_map_stmt_kind(self, kind)
619                .into_iter()
620                .map(|kind| {
621                    // Expanding the current statement is a nested `use` item,
622                    // it is expanded into several flat `use` items.
623                    // Create new NodeIds for the corresponding statements
624                    // as two statements cannot have the same.
625                    let id = id.take().unwrap_or_else(|| {
626                        let next = self.next_node_id;
627                        self.next_node_id.increment_by(1);
628                        next
629                    });
630                    Stmt { id, kind, span }
631                })
632                .collect()
633        }
634
635        fn visit_assoc_item(&mut self, item: &mut AssocItem, ctxt: visit::AssocCtxt) {
636            mut_visit::walk_assoc_item(self, item, ctxt);
637            match ctxt {
638                visit::AssocCtxt::Trait => {
639                    self.replace_with_dummy(item, AssocItemKind::MacCall, AstOwner::TraitItem)
640                }
641                visit::AssocCtxt::Impl { .. } => {
642                    self.replace_with_dummy(item, AssocItemKind::MacCall, AstOwner::ImplItem)
643                }
644            }
645        }
646
647        fn visit_foreign_item(&mut self, item: &mut ForeignItem) {
648            mut_visit::walk_item(self, item);
649            self.replace_with_dummy(item, ForeignItemKind::MacCall, AstOwner::ForeignItem);
650        }
651    }
652}
653
654#[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_to_hir",
                                    "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(654u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::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::MaybeOwner<'_> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ast_index = tcx.index_ast(());
            let resolver_and_node = ast_index.get(def_id).map(Steal::steal);
            let fallback_to_ancestor =
                |parent_id|
                    {
                        let mut parent_info = tcx.lower_to_hir(parent_id);
                        if let hir::MaybeOwner::NonOwner(hir_id) = parent_info {
                            parent_info = tcx.lower_to_hir(hir_id.owner);
                        }
                        let parent_info = parent_info.unwrap();
                        *parent_info.children.get(&def_id).unwrap_or_else(||
                                    {
                                        {
                                            ::core::panicking::panic_fmt(format_args!("{0:?} does not appear in children of {1:?}",
                                                    def_id, parent_info.nodes.node().def_id()));
                                        }
                                    })
                    };
            let Some((resolver, node)) =
                resolver_and_node else {
                    return fallback_to_ancestor(tcx.local_parent(def_id));
                };
            let mut item_lowerer =
                item::ItemLowerer { tcx, resolver: &*resolver };
            let item =
                match &node {
                    AstOwner::Crate(c) => item_lowerer.lower_crate(&c),
                    AstOwner::Item(item) => item_lowerer.lower_item(&item),
                    AstOwner::TraitItem(item) =>
                        item_lowerer.lower_trait_item(&item),
                    AstOwner::ImplItem(item) =>
                        item_lowerer.lower_impl_item(&item),
                    AstOwner::ForeignItem(item) =>
                        item_lowerer.lower_foreign_item(&item),
                    AstOwner::NestedUseTree(owner_id) =>
                        fallback_to_ancestor(*owner_id),
                    AstOwner::NonOwner =>
                        fallback_to_ancestor(tcx.local_parent(def_id)),
                };
            tcx.sess.time("drop_ast", || mem::drop(node));
            item
        }
    }
}#[instrument(level = "trace", skip(tcx))]
655fn lower_to_hir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> hir::MaybeOwner<'_> {
656    let ast_index = tcx.index_ast(());
657    let resolver_and_node = ast_index.get(def_id).map(Steal::steal);
658
659    let fallback_to_ancestor = |parent_id| {
660        // The item did not exist in the AST, it was created while lowering another item.
661        // `parent_id` may be different from the direct parent of `def_id`,
662        // for instance use-trees are lowered by the first sibling.
663        let mut parent_info = tcx.lower_to_hir(parent_id);
664        if let hir::MaybeOwner::NonOwner(hir_id) = parent_info {
665            // `parent_id` could also not be a owner either.
666            // For instance if `def_id` is an enum variant field,
667            // the direct parent is the enum variant.
668            // In that case `hir_id.owner` point to the actual HIR owner
669            // and skips all non-owner parents, so fetch the HIR associated to it.
670            parent_info = tcx.lower_to_hir(hir_id.owner);
671        }
672
673        let parent_info = parent_info.unwrap();
674        *parent_info.children.get(&def_id).unwrap_or_else(|| {
675            panic!(
676                "{:?} does not appear in children of {:?}",
677                def_id,
678                parent_info.nodes.node().def_id()
679            )
680        })
681    };
682
683    let Some((resolver, node)) = resolver_and_node else {
684        // `ast_index` does not contain all definitions, only up-to the highest
685        // `LocalDefId` which has a non-trivial `AstOwner`. Gracefully handle
686        // other definitions, in particular those nested inside this highest definition.
687        return fallback_to_ancestor(tcx.local_parent(def_id));
688    };
689
690    let mut item_lowerer = item::ItemLowerer { tcx, resolver: &*resolver };
691
692    let item = match &node {
693        // The item existed in the AST.
694        AstOwner::Crate(c) => item_lowerer.lower_crate(&c),
695        AstOwner::Item(item) => item_lowerer.lower_item(&item),
696        AstOwner::TraitItem(item) => item_lowerer.lower_trait_item(&item),
697        AstOwner::ImplItem(item) => item_lowerer.lower_impl_item(&item),
698        AstOwner::ForeignItem(item) => item_lowerer.lower_foreign_item(&item),
699        AstOwner::NestedUseTree(owner_id) => fallback_to_ancestor(*owner_id),
700        // The item existed in the AST, but is not a HIR owner.
701        // Fetch the correct information from its parent.
702        AstOwner::NonOwner => fallback_to_ancestor(tcx.local_parent(def_id)),
703    };
704
705    tcx.sess.time("drop_ast", || mem::drop(node));
706
707    item
708}
709
710#[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)]
711enum ParamMode {
712    /// Any path in a type context.
713    Explicit,
714    /// The `module::Type` in `module::Type::method` in an expression.
715    Optional,
716}
717
718#[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)]
719enum AllowReturnTypeNotation {
720    /// Only in types, since RTN is denied later during HIR lowering.
721    Yes,
722    /// All other positions (path expr, method, use tree).
723    No,
724}
725
726enum GenericArgsMode {
727    /// Allow paren sugar, don't allow RTN.
728    ParenSugar,
729    /// Allow RTN, don't allow paren sugar.
730    ReturnTypeNotation,
731    // Error if parenthesized generics or RTN are encountered.
732    Err,
733    /// Silence errors when lowering generics. Only used with `Res::Err`.
734    Silence,
735}
736
737impl<'hir> LoweringContext<'_, 'hir> {
738    fn create_def(
739        &mut self,
740        node_id: NodeId,
741        name: Option<Symbol>,
742        def_kind: DefKind,
743        span: Span,
744    ) -> LocalDefId {
745        let parent = self.current_hir_id_owner.def_id;
746        {
    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);
747        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!(
748            self.opt_local_def_id(node_id).is_none(),
749            "adding a def'n for node-id {:?} and def kind {:?} but a previous def'n exists: {:?}",
750            node_id,
751            def_kind,
752            self.tcx.hir_def_key(self.local_def_id(node_id)),
753        );
754
755        let def_id = self
756            .tcx
757            .at(span)
758            .create_def(parent, name, def_kind, None, &mut self.current_disambiguator)
759            .def_id();
760
761        {
    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:761",
                        "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(761u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("create_def: def_id_to_node_id[{0:?}] <-> {1:?}",
                                                    def_id, node_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
762        self.node_id_to_def_id.insert(node_id, def_id);
763
764        def_id
765    }
766
767    fn next_node_id(&mut self) -> NodeId {
768        let start = self.next_node_id;
769        let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
770        self.next_node_id = NodeId::from_u32(next);
771        start
772    }
773
774    /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
775    /// resolver (if any).
776    x;#[instrument(level = "trace", skip(self), ret)]
777    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
778        self.node_id_to_def_id
779            .get(&node)
780            .or_else(|| self.owner.node_id_to_def_id.get(&node))
781            .copied()
782    }
783
784    fn local_def_id(&self, node: NodeId) -> LocalDefId {
785        self.opt_local_def_id(node).unwrap_or_else(|| {
786            self.resolver.owners.items().any(|(id, items)| {
787                items.node_id_to_def_id.items().any(|(node_id, def_id)| {
788                    if *node_id == node {
789                        let actual_owner = items.node_id_to_def_id.get(id);
790                        {
    ::core::panicking::panic_fmt(format_args!("{0:?} ({1}) was found in {2:?} ({3})",
            def_id, node_id, actual_owner, id));
}panic!("{def_id:?} ({node_id}) was found in {actual_owner:?} ({id})",)
791                    }
792                    false
793                })
794            });
795            {
    ::core::panicking::panic_fmt(format_args!("no entry for node id: `{0:?}`",
            node));
};panic!("no entry for node id: `{node:?}`");
796        })
797    }
798
799    fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
800        match self.partial_res_overrides.get(&id) {
801            Some(self_param_id) => Some(PartialRes::new(Res::Local(*self_param_id))),
802            None => self.resolver.partial_res_map.get(&id).copied(),
803        }
804    }
805
806    /// Given the id of an owner node in the AST, returns the corresponding `OwnerId`.
807    fn owner_id(&self, node: NodeId) -> hir::OwnerId {
808        hir::OwnerId { def_id: self.resolver.owners[&node].def_id }
809    }
810
811    /// Freshen the `LoweringContext` and ready it to lower a nested item.
812    /// The lowered item is registered into `self.children`.
813    ///
814    /// This function sets up `HirId` lowering infrastructure,
815    /// and stashes the shared mutable state to avoid pollution by the closure.
816    #[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(816u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("owner")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("owner");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&owner)
                                                            as &dyn ::tracing::field::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 def_id = owner_id.def_id;
            let new_disambig =
                self.resolver.disambiguators.get(&def_id).map(|s|
                            s.steal()).unwrap_or_else(||
                        PerParentDisambiguatorState::new(def_id));
            let disambiguator =
                mem::replace(&mut self.current_disambiguator, new_disambig);
            let current_ast_owner =
                mem::replace(&mut self.owner, &self.resolver.owners[&owner]);
            let current_attrs = mem::take(&mut self.attrs);
            let current_bodies = mem::take(&mut self.bodies);
            let current_define_opaque = mem::take(&mut self.define_opaque);
            let current_ident_and_label_to_local_id =
                mem::take(&mut self.ident_and_label_to_local_id);
            let current_relowering_checker =
                mem::take(&mut self.relowering_checker);
            let current_trait_map = mem::take(&mut self.trait_map);
            let current_owner =
                mem::replace(&mut self.current_hir_id_owner, owner_id);
            let current_local_counter =
                mem::replace(&mut self.item_local_id_counter,
                    hir::ItemLocalId::new(1));
            let current_impl_trait_defs =
                mem::take(&mut self.impl_trait_defs);
            let current_impl_trait_bounds =
                mem::take(&mut self.impl_trait_bounds);
            let current_delayed_lints = mem::take(&mut self.delayed_lints);
            let current_children = mem::take(&mut self.children);
            self.relowering_checker.assert_node_is_not_relowered(owner,
                hir::ItemLocalId::ZERO);
            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.current_disambiguator = disambiguator;
            self.owner = current_ast_owner;
            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.relowering_checker = current_relowering_checker; }
            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;
            self.children = current_children;
            self.children.extend_unord(info.children.items().map(|(&def_id,
                            &info)| (def_id, info)));
            if true {
                if !!self.children.contains_key(&owner_id.def_id) {
                    ::core::panicking::panic("assertion failed: !self.children.contains_key(&owner_id.def_id)")
                };
            };
            self.children.insert(owner_id.def_id,
                hir::MaybeOwner::Owner(info));
        }
    }
}#[instrument(level = "debug", skip(self, f))]
817    fn with_hir_id_owner(
818        &mut self,
819        owner: NodeId,
820        f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
821    ) {
822        let owner_id = self.owner_id(owner);
823        let def_id = owner_id.def_id;
824
825        let new_disambig = self
826            .resolver
827            .disambiguators
828            .get(&def_id)
829            .map(|s| s.steal())
830            .unwrap_or_else(|| PerParentDisambiguatorState::new(def_id));
831
832        let disambiguator = mem::replace(&mut self.current_disambiguator, new_disambig);
833        let current_ast_owner = mem::replace(&mut self.owner, &self.resolver.owners[&owner]);
834        let current_attrs = mem::take(&mut self.attrs);
835        let current_bodies = mem::take(&mut self.bodies);
836        let current_define_opaque = mem::take(&mut self.define_opaque);
837        let current_ident_and_label_to_local_id = mem::take(&mut self.ident_and_label_to_local_id);
838
839        #[cfg(debug_assertions)]
840        let current_relowering_checker = mem::take(&mut self.relowering_checker);
841        let current_trait_map = mem::take(&mut self.trait_map);
842        let current_owner = mem::replace(&mut self.current_hir_id_owner, owner_id);
843        let current_local_counter =
844            mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
845        let current_impl_trait_defs = mem::take(&mut self.impl_trait_defs);
846        let current_impl_trait_bounds = mem::take(&mut self.impl_trait_bounds);
847        let current_delayed_lints = mem::take(&mut self.delayed_lints);
848        let current_children = mem::take(&mut self.children);
849
850        // Do not reset `next_node_id` and `node_id_to_def_id`:
851        // we want `f` to be able to refer to the `LocalDefId`s that the caller created.
852        // and the caller to refer to some of the subdefinitions' nodes' `LocalDefId`s.
853
854        // Always allocate the first `HirId` for the owner itself.
855        #[cfg(debug_assertions)]
856        self.relowering_checker.assert_node_is_not_relowered(owner, hir::ItemLocalId::ZERO);
857
858        let item = f(self);
859        assert_eq!(owner_id, item.def_id());
860        // `f` should have consumed all the elements in these vectors when constructing `item`.
861        assert!(self.impl_trait_defs.is_empty());
862        assert!(self.impl_trait_bounds.is_empty());
863        let info = self.make_owner_info(item);
864
865        self.current_disambiguator = disambiguator;
866        self.owner = current_ast_owner;
867        self.attrs = current_attrs;
868        self.bodies = current_bodies;
869        self.define_opaque = current_define_opaque;
870        self.ident_and_label_to_local_id = current_ident_and_label_to_local_id;
871
872        #[cfg(debug_assertions)]
873        {
874            self.relowering_checker = current_relowering_checker;
875        }
876        self.trait_map = current_trait_map;
877        self.current_hir_id_owner = current_owner;
878        self.item_local_id_counter = current_local_counter;
879        self.impl_trait_defs = current_impl_trait_defs;
880        self.impl_trait_bounds = current_impl_trait_bounds;
881        self.delayed_lints = current_delayed_lints;
882        self.children = current_children;
883        self.children.extend_unord(info.children.items().map(|(&def_id, &info)| (def_id, info)));
884
885        debug_assert!(!self.children.contains_key(&owner_id.def_id));
886        self.children.insert(owner_id.def_id, hir::MaybeOwner::Owner(info));
887    }
888
889    fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> {
890        let attrs = mem::take(&mut self.attrs);
891        let mut bodies = mem::take(&mut self.bodies);
892        let define_opaque = mem::take(&mut self.define_opaque);
893        let trait_map = mem::take(&mut self.trait_map);
894        let delayed_lints = Steal::new(mem::take(&mut self.delayed_lints).into_boxed_slice());
895        let children = mem::take(&mut self.children);
896
897        #[cfg(debug_assertions)]
898        for (id, attrs) in attrs.iter() {
899            // Verify that we do not store empty slices in the map.
900            if attrs.is_empty() {
901                {
    ::core::panicking::panic_fmt(format_args!("Stored empty attributes for {0:?}",
            id));
};panic!("Stored empty attributes for {:?}", id);
902            }
903        }
904
905        bodies.sort_by_key(|(k, _)| *k);
906        let bodies = SortedMap::from_presorted_elements(bodies);
907
908        // Don't hash unless necessary, because it's expensive.
909        let rustc_middle::hir::Hashes { bodies_hash, attrs_hash } =
910            self.tcx.hash_owner_nodes(node, &bodies, &attrs, define_opaque);
911        let num_nodes = self.item_local_id_counter.as_usize();
912        let (nodes, parenting) = index::index_hir(self.tcx, node, &bodies, num_nodes);
913        let nodes = hir::OwnerNodes { opt_hash: bodies_hash, nodes, bodies };
914        let attrs = hir::AttributeMap { map: attrs, opt_hash: attrs_hash, define_opaque };
915
916        let opt_hash = self.tcx.needs_hir_hash().then(|| {
917            self.tcx.with_stable_hashing_context(|mut hcx| {
918                let mut stable_hasher = StableHasher::new();
919                bodies_hash.unwrap().stable_hash(&mut hcx, &mut stable_hasher);
920                attrs_hash.unwrap().stable_hash(&mut hcx, &mut stable_hasher);
921                // Do not hash delayed_lints.
922                parenting.stable_hash(&mut hcx, &mut stable_hasher);
923                trait_map.stable_hash(&mut hcx, &mut stable_hasher);
924                children.stable_hash(&mut hcx, &mut stable_hasher);
925                stable_hasher.finish()
926            })
927        });
928
929        self.arena.alloc(hir::OwnerInfo {
930            opt_hash,
931            nodes,
932            parenting,
933            attrs,
934            trait_map,
935            delayed_lints,
936            children,
937        })
938    }
939
940    /// This method allocates a new `HirId` for the given `NodeId`.
941    /// Take care not to call this method if the resulting `HirId` is then not
942    /// actually used in the HIR, as that would trigger an assertion in the
943    /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
944    /// properly. Calling the method twice with the same `NodeId` is also forbidden.
945    x;#[instrument(level = "debug", skip(self), ret)]
946    fn lower_node_id(&mut self, ast_node_id: NodeId) -> HirId {
947        assert_ne!(ast_node_id, DUMMY_NODE_ID);
948
949        let owner = self.current_hir_id_owner;
950        let local_id = self.item_local_id_counter;
951        assert_ne!(local_id, hir::ItemLocalId::ZERO);
952        self.item_local_id_counter.increment_by(1);
953        let hir_id = HirId { owner, local_id };
954
955        if let Some(def_id) = self.opt_local_def_id(ast_node_id) {
956            self.children.insert(def_id, hir::MaybeOwner::NonOwner(hir_id));
957        }
958
959        if let Some(traits) = self.owner.trait_map.get(&ast_node_id) {
960            self.trait_map.insert(hir_id.local_id, *traits);
961        }
962
963        // Check whether the same `NodeId` is lowered more than once.
964        #[cfg(debug_assertions)]
965        self.relowering_checker.assert_node_is_not_relowered(ast_node_id, local_id);
966
967        hir_id
968    }
969
970    /// Generate a new `HirId` without a backing `NodeId`.
971    x;#[instrument(level = "debug", skip(self), ret)]
972    fn next_id(&mut self) -> HirId {
973        let owner = self.current_hir_id_owner;
974        let local_id = self.item_local_id_counter;
975        assert_ne!(local_id, hir::ItemLocalId::ZERO);
976        self.item_local_id_counter.increment_by(1);
977        HirId { owner, local_id }
978    }
979
980    #[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(980u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("res");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn ::tracing::field::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:987",
                                    "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(987u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("res");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            res.unwrap_or(Res::Err)
        }
    }
}#[instrument(level = "trace", skip(self))]
981    fn lower_res(&mut self, res: Res<NodeId>) -> Res {
982        let res: Result<Res, ()> = res.apply_id(|id| {
983            let owner = self.current_hir_id_owner;
984            let local_id = self.ident_and_label_to_local_id.get(&id).copied().ok_or(())?;
985            Ok(HirId { owner, local_id })
986        });
987        trace!(?res);
988
989        // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
990        // This can happen when trying to lower the return type `x` in erroneous code like
991        //   async fn foo(x: u8) -> x {}
992        // In that case, `x` is lowered as a function parameter, and the return type is lowered as
993        // an opaque type as a synthesized HIR owner.
994        res.unwrap_or(Res::Err)
995    }
996
997    fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
998        self.get_partial_res(id).map_or(Res::Err, |pr| pr.expect_full_res())
999    }
1000
1001    fn lower_import_res(&mut self, id: NodeId, span: Span) -> PerNS<Option<Res>> {
1002        if true {
    {
        match (&id, &self.owner.id) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(id, self.owner.id);
1003        let per_ns = self.owner.import_res.map(|res| res.map(|res| self.lower_res(res)));
1004        if per_ns.is_empty() {
1005            // Propagate the error to all namespaces, just to be sure.
1006            self.dcx().span_delayed_bug(span, "no resolution for an import");
1007            let err = Some(Res::Err);
1008            return PerNS { type_ns: err, value_ns: err, macro_ns: err };
1009        }
1010        per_ns
1011    }
1012
1013    fn make_lang_item_qpath(
1014        &mut self,
1015        lang_item: hir::LangItem,
1016        span: Span,
1017        args: Option<&'hir hir::GenericArgs<'hir>>,
1018    ) -> hir::QPath<'hir> {
1019        hir::QPath::Resolved(None, self.make_lang_item_path(lang_item, span, args))
1020    }
1021
1022    fn make_lang_item_path(
1023        &mut self,
1024        lang_item: hir::LangItem,
1025        span: Span,
1026        args: Option<&'hir hir::GenericArgs<'hir>>,
1027    ) -> &'hir hir::Path<'hir> {
1028        let def_id = self.tcx.require_lang_item(lang_item, span);
1029        let def_kind = self.tcx.def_kind(def_id);
1030        let res = Res::Def(def_kind, def_id);
1031        self.arena.alloc(hir::Path {
1032            span,
1033            res,
1034            segments: self.arena.alloc_from_iter([hir::PathSegment {
1035                ident: Ident::new(lang_item.name(), span),
1036                hir_id: self.next_id(),
1037                res,
1038                args,
1039                infer_args: args.is_none(),
1040                delegation_child_segment: false,
1041            }]),
1042        })
1043    }
1044
1045    /// Reuses the span but adds information like the kind of the desugaring and features that are
1046    /// allowed inside this span.
1047    fn mark_span_with_reason(
1048        &self,
1049        reason: DesugaringKind,
1050        span: Span,
1051        allow_internal_unstable: Option<Arc<[Symbol]>>,
1052    ) -> Span {
1053        self.tcx.with_stable_hashing_context(|hcx| {
1054            span.mark_with_reason(allow_internal_unstable, reason, span.edition(), hcx)
1055        })
1056    }
1057
1058    fn span_lowerer(&self) -> SpanLowerer {
1059        SpanLowerer {
1060            is_incremental: self.tcx.sess.opts.incremental.is_some(),
1061            def_id: self.current_hir_id_owner.def_id,
1062        }
1063    }
1064
1065    /// Intercept all spans entering HIR.
1066    /// Mark a span as relative to the current owning item.
1067    fn lower_span(&self, span: Span) -> Span {
1068        self.span_lowerer().lower(span)
1069    }
1070
1071    fn lower_ident(&self, ident: Ident) -> Ident {
1072        Ident::new(ident.name, self.lower_span(ident.span))
1073    }
1074
1075    /// Converts a lifetime into a new generic parameter.
1076    #[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(1076u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ident")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ident");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("node_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("node_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("kind")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("kind");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn ::tracing::field::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 _def_id =
                self.create_def(node_id, Some(kw::UnderscoreLifetime),
                    DefKind::LifetimeParam, 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:1091",
                                    "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(1091u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("_def_id");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&_def_id)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let hir_id = self.lower_node_id(node_id);
            let def_id = self.local_def_id(node_id);
            hir::GenericParam {
                hir_id,
                def_id,
                name: hir::ParamName::Fresh,
                span: self.lower_span(ident.span),
                pure_wrt_drop: false,
                kind: hir::GenericParamKind::Lifetime {
                    kind: hir::LifetimeParamKind::Elided(kind),
                },
                colon_span: None,
                source,
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1077    fn lifetime_res_to_generic_param(
1078        &mut self,
1079        ident: Ident,
1080        node_id: NodeId,
1081        kind: MissingLifetimeKind,
1082        source: hir::GenericParamSource,
1083    ) -> hir::GenericParam<'hir> {
1084        // Late resolution delegates to us the creation of the `LocalDefId`.
1085        let _def_id = self.create_def(
1086            node_id,
1087            Some(kw::UnderscoreLifetime),
1088            DefKind::LifetimeParam,
1089            ident.span,
1090        );
1091        debug!(?_def_id);
1092
1093        let hir_id = self.lower_node_id(node_id);
1094        let def_id = self.local_def_id(node_id);
1095        hir::GenericParam {
1096            hir_id,
1097            def_id,
1098            name: hir::ParamName::Fresh,
1099            span: self.lower_span(ident.span),
1100            pure_wrt_drop: false,
1101            kind: hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided(kind) },
1102            colon_span: None,
1103            source,
1104        }
1105    }
1106
1107    /// Lowers a lifetime binder that defines `generic_params`, returning the corresponding HIR
1108    /// nodes. The returned list includes any "extra" lifetime parameters that were added by the
1109    /// name resolver owing to lifetime elision; this also populates the resolver's node-id->def-id
1110    /// map, so that later calls to `opt_node_id_to_def_id` that refer to these extra lifetime
1111    /// parameters will be successful.
1112    x;#[instrument(level = "debug", skip(self), ret)]
1113    #[inline]
1114    fn lower_lifetime_binder(
1115        &mut self,
1116        binder: NodeId,
1117        generic_params: &[GenericParam],
1118    ) -> &'hir [hir::GenericParam<'hir>] {
1119        // Start by creating params for extra lifetimes params, as this creates the definitions
1120        // that may be referred to by the AST inside `generic_params`.
1121        let extra_lifetimes = self.owner.extra_lifetime_params(binder);
1122        debug!(?extra_lifetimes);
1123        let extra_lifetimes: Vec<_> = extra_lifetimes
1124            .iter()
1125            .map(|&(ident, node_id, res)| {
1126                self.lifetime_res_to_generic_param(
1127                    ident,
1128                    node_id,
1129                    res,
1130                    hir::GenericParamSource::Binder,
1131                )
1132            })
1133            .collect();
1134        let arena = self.arena;
1135        let explicit_generic_params =
1136            self.lower_generic_params_mut(generic_params, hir::GenericParamSource::Binder);
1137        arena.alloc_from_iter(explicit_generic_params.chain(extra_lifetimes.into_iter()))
1138    }
1139
1140    fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
1141        let was_in_dyn_type = self.is_in_dyn_type;
1142        self.is_in_dyn_type = in_scope;
1143
1144        let result = f(self);
1145
1146        self.is_in_dyn_type = was_in_dyn_type;
1147
1148        result
1149    }
1150
1151    fn with_new_scopes<T>(&mut self, scope_span: Span, f: impl FnOnce(&mut Self) -> T) -> T {
1152        let current_item = self.current_item;
1153        self.current_item = Some(scope_span);
1154
1155        let was_in_loop_condition = self.is_in_loop_condition;
1156        self.is_in_loop_condition = false;
1157
1158        let old_contract = self.contract_ensures.take();
1159
1160        let try_block_scope = mem::replace(&mut self.try_block_scope, TryBlockScope::Function);
1161        let loop_scope = self.loop_scope.take();
1162        let ret = f(self);
1163        self.try_block_scope = try_block_scope;
1164        self.loop_scope = loop_scope;
1165
1166        self.contract_ensures = old_contract;
1167
1168        self.is_in_loop_condition = was_in_loop_condition;
1169
1170        self.current_item = current_item;
1171
1172        ret
1173    }
1174
1175    fn lower_attrs(
1176        &mut self,
1177        id: HirId,
1178        attrs: &[Attribute],
1179        target_span: Span,
1180        target: Target,
1181    ) -> &'hir [hir::Attribute] {
1182        self.lower_attrs_with_extra(id, attrs, target_span, target, &[])
1183    }
1184
1185    fn lower_attrs_with_extra(
1186        &mut self,
1187        id: HirId,
1188        attrs: &[Attribute],
1189        target_span: Span,
1190        target: Target,
1191        extra_hir_attributes: &[hir::Attribute],
1192    ) -> &'hir [hir::Attribute] {
1193        if attrs.is_empty() && extra_hir_attributes.is_empty() {
1194            &[]
1195        } else {
1196            let mut lowered_attrs =
1197                self.lower_attrs_vec(attrs, self.lower_span(target_span), id, target);
1198            lowered_attrs.extend(extra_hir_attributes.iter().cloned());
1199
1200            {
    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);
1201            let ret = self.arena.alloc_from_iter(lowered_attrs);
1202
1203            // this is possible if an item contained syntactical attribute,
1204            // but none of them parse successfully or all of them were ignored
1205            // for not being built-in attributes at all. They could be remaining
1206            // unexpanded attributes used as markers in proc-macro derives for example.
1207            // This will have emitted some diagnostics for the misparse, but will then
1208            // not emit the attribute making the list empty.
1209            if ret.is_empty() {
1210                &[]
1211            } else {
1212                self.attrs.insert(id.local_id, ret);
1213                ret
1214            }
1215        }
1216    }
1217
1218    fn lower_attrs_vec(
1219        &mut self,
1220        attrs: &[Attribute],
1221        target_span: Span,
1222        target_hir_id: HirId,
1223        target: Target,
1224    ) -> Vec<hir::Attribute> {
1225        let l = self.span_lowerer();
1226        self.attribute_parser.parse_attribute_list(
1227            attrs,
1228            target_span,
1229            target,
1230            OmitDoc::Lower,
1231            |s| l.lower(s),
1232            |lint_id, span, kind| {
1233                self.delayed_lints.push(DelayedLint {
1234                    lint_id,
1235                    id: target_hir_id,
1236                    span,
1237                    callback: Box::new(move |dcx, level, sess: &dyn std::any::Any| {
1238                        let sess = sess
1239                            .downcast_ref::<rustc_session::Session>()
1240                            .expect("expected `Session`");
1241                        (kind.0)(dcx, level, sess)
1242                    }),
1243                });
1244            },
1245        )
1246    }
1247
1248    fn alias_attrs(&mut self, id: HirId, target_id: HirId) {
1249        {
    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);
1250        {
    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);
1251        if let Some(&a) = self.attrs.get(&target_id.local_id) {
1252            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
1253            self.attrs.insert(id.local_id, a);
1254        }
1255    }
1256
1257    fn lower_delim_args(&self, args: &DelimArgs) -> DelimArgs {
1258        args.clone()
1259    }
1260
1261    /// Lower an associated item constraint.
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_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(1262u32),
                                    ::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_all(&[]) })
                } 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:1268",
                                    "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(1268u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("constraint")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("constraint");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("itctx")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("itctx");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constraint)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                        as &dyn ::tracing::field::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(_)) => {
                                                diagnostics::BadReturnTypeNotation::Inputs {
                                                    span: data.inputs_span,
                                                }
                                            }
                                            ([], FnRetTy::Default(_)) => {
                                                diagnostics::BadReturnTypeNotation::NeedsDots {
                                                    span: data.inputs_span,
                                                }
                                            }
                                            (_, FnRetTy::Ty(ty)) => {
                                                let span = data.inputs_span.shrink_to_hi().to(ty.span);
                                                diagnostics::BadReturnTypeNotation::Output {
                                                    span,
                                                    suggestion: diagnostics::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 { 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(diagnostics::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)]
1263    fn lower_assoc_item_constraint(
1264        &mut self,
1265        constraint: &AssocItemConstraint,
1266        itctx: ImplTraitContext,
1267    ) -> hir::AssocItemConstraint<'hir> {
1268        debug!(?constraint, ?itctx);
1269        // Lower the generic arguments for the associated item.
1270        let gen_args = if let Some(gen_args) = &constraint.gen_args {
1271            let gen_args_ctor = match gen_args {
1272                GenericArgs::AngleBracketed(data) => {
1273                    self.lower_angle_bracketed_parameter_data(data, ParamMode::Explicit, itctx).0
1274                }
1275                GenericArgs::Parenthesized(data) => {
1276                    if let Some(first_char) = constraint.ident.as_str().chars().next()
1277                        && first_char.is_ascii_lowercase()
1278                    {
1279                        let err = match (&data.inputs[..], &data.output) {
1280                            ([_, ..], FnRetTy::Default(_)) => {
1281                                diagnostics::BadReturnTypeNotation::Inputs {
1282                                    span: data.inputs_span,
1283                                }
1284                            }
1285                            ([], FnRetTy::Default(_)) => {
1286                                diagnostics::BadReturnTypeNotation::NeedsDots {
1287                                    span: data.inputs_span,
1288                                }
1289                            }
1290                            // The case `T: Trait<method(..) -> Ret>` is handled in the parser.
1291                            (_, FnRetTy::Ty(ty)) => {
1292                                let span = data.inputs_span.shrink_to_hi().to(ty.span);
1293                                diagnostics::BadReturnTypeNotation::Output {
1294                                    span,
1295                                    suggestion: diagnostics::RTNSuggestion {
1296                                        output: span,
1297                                        input: data.inputs_span,
1298                                    },
1299                                }
1300                            }
1301                        };
1302                        let mut err = self.dcx().create_err(err);
1303                        if !self.tcx.features().return_type_notation()
1304                            && self.tcx.sess.is_nightly_build()
1305                        {
1306                            add_feature_diagnostics(
1307                                &mut err,
1308                                &self.tcx.sess,
1309                                sym::return_type_notation,
1310                            );
1311                        }
1312                        err.emit();
1313                        GenericArgsCtor {
1314                            args: Default::default(),
1315                            constraints: &[],
1316                            parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
1317                            span: data.span,
1318                        }
1319                    } else {
1320                        self.emit_bad_parenthesized_trait_in_assoc_ty(data);
1321                        self.lower_angle_bracketed_parameter_data(
1322                            &data.as_angle_bracketed_args(),
1323                            ParamMode::Explicit,
1324                            itctx,
1325                        )
1326                        .0
1327                    }
1328                }
1329                GenericArgs::ParenthesizedElided(span) => GenericArgsCtor {
1330                    args: Default::default(),
1331                    constraints: &[],
1332                    parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
1333                    span: *span,
1334                },
1335            };
1336            gen_args_ctor.into_generic_args(self)
1337        } else {
1338            hir::GenericArgs::NONE
1339        };
1340        let kind = match &constraint.kind {
1341            AssocItemConstraintKind::Equality { term } => {
1342                let term = match term {
1343                    Term::Ty(ty) => self.lower_ty_alloc(ty, itctx).into(),
1344                    Term::Const(c) => self.lower_anon_const_to_const_arg_and_alloc(c).into(),
1345                };
1346                hir::AssocItemConstraintKind::Equality { term }
1347            }
1348            AssocItemConstraintKind::Bound { bounds } => {
1349                // Disallow ATB in dyn types
1350                if self.is_in_dyn_type {
1351                    let suggestion = match itctx {
1352                        ImplTraitContext::OpaqueTy { .. } | ImplTraitContext::Universal => {
1353                            let bound_end_span = constraint
1354                                .gen_args
1355                                .as_ref()
1356                                .map_or(constraint.ident.span, |args| args.span());
1357                            if bound_end_span.eq_ctxt(constraint.span) {
1358                                Some(self.tcx.sess.source_map().next_point(bound_end_span))
1359                            } else {
1360                                None
1361                            }
1362                        }
1363                        _ => None,
1364                    };
1365
1366                    let guar = self.dcx().emit_err(diagnostics::MisplacedAssocTyBinding {
1367                        span: constraint.span,
1368                        suggestion,
1369                    });
1370                    let err_ty =
1371                        &*self.arena.alloc(self.ty(constraint.span, hir::TyKind::Err(guar)));
1372                    hir::AssocItemConstraintKind::Equality { term: err_ty.into() }
1373                } else {
1374                    let bounds = self.lower_param_bounds(
1375                        bounds,
1376                        RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::AssocTyBounds),
1377                        itctx,
1378                    );
1379                    hir::AssocItemConstraintKind::Bound { bounds }
1380                }
1381            }
1382        };
1383
1384        hir::AssocItemConstraint {
1385            hir_id: self.lower_node_id(constraint.id),
1386            ident: self.lower_ident(constraint.ident),
1387            gen_args,
1388            kind,
1389            span: self.lower_span(constraint.span),
1390        }
1391    }
1392
1393    fn emit_bad_parenthesized_trait_in_assoc_ty(&self, data: &ParenthesizedArgs) {
1394        // Suggest removing empty parentheses: "Trait()" -> "Trait"
1395        let sub = if data.inputs.is_empty() {
1396            let parentheses_span =
1397                data.inputs_span.shrink_to_lo().to(data.inputs_span.shrink_to_hi());
1398            AssocTyParenthesesSub::Empty { parentheses_span }
1399        }
1400        // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
1401        else {
1402            // Start of parameters to the 1st argument
1403            let open_param = data.inputs_span.shrink_to_lo().to(data
1404                .inputs
1405                .first()
1406                .unwrap()
1407                .span
1408                .shrink_to_lo());
1409            // End of last argument to end of parameters
1410            let close_param =
1411                data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi());
1412            AssocTyParenthesesSub::NotEmpty { open_param, close_param }
1413        };
1414        self.dcx().emit_err(AssocTyParentheses { span: data.span, sub });
1415    }
1416
1417    #[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(1417u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("arg")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("arg");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("itctx")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("itctx");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arg)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn ::tracing::field::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.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:1454",
                                                            "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(1454u32),
                                                            ::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};
                                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("lower_generic_arg: Lowering type argument as const argument: {0:?}",
                                                                                        ty) as &dyn ::tracing::field::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());
                                }
                            }
                        }
                        TyKind::DirectConstArg(expr) if
                            self.tcx.features().min_generic_const_args() => {
                            let ct =
                                match self.can_lower_expr_to_const_arg_direct(expr) {
                                    Ok(()) => self.lower_expr_to_const_arg_direct(expr, None),
                                    Err(e) => e.emit(self),
                                };
                            let ct = self.arena.alloc(ct);
                            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) => {
                    let ct = self.lower_anon_const_to_const_arg_and_alloc(ct);
                    match ct.try_as_ambig_ct() {
                        Some(ct) => GenericArg::Const(ct),
                        None =>
                            GenericArg::Infer(hir::InferArg {
                                    hir_id: ct.hir_id,
                                    span: ct.span,
                                }),
                    }
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1418    fn lower_generic_arg(
1419        &mut self,
1420        arg: &ast::GenericArg,
1421        itctx: ImplTraitContext,
1422    ) -> hir::GenericArg<'hir> {
1423        match arg {
1424            ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(
1425                lt,
1426                LifetimeSource::Path { angle_brackets: hir::AngleBrackets::Full },
1427                lt.ident.into(),
1428            )),
1429            ast::GenericArg::Type(ty) => {
1430                // We cannot just match on `TyKind::Infer` as `(_)` is represented as
1431                // `TyKind::Paren(TyKind::Infer)` and should also be lowered to `GenericArg::Infer`
1432                if ty.is_maybe_parenthesised_infer() {
1433                    return GenericArg::Infer(hir::InferArg {
1434                        hir_id: self.lower_node_id(ty.id),
1435                        span: self.lower_span(ty.span),
1436                    });
1437                }
1438
1439                match &ty.kind {
1440                    // We parse const arguments as path types as we cannot distinguish them during
1441                    // parsing. We try to resolve that ambiguity by attempting resolution in both the
1442                    // type and value namespaces. If we resolved the path in the value namespace, we
1443                    // transform it into a generic const argument.
1444                    //
1445                    // FIXME: Should we be handling `(PATH_TO_CONST)`?
1446                    TyKind::Path(None, path) => {
1447                        if let Some(res) = self
1448                            .get_partial_res(ty.id)
1449                            .and_then(|partial_res| partial_res.full_res())
1450                        {
1451                            if !res.matches_ns(Namespace::TypeNS)
1452                                && path.is_potential_trivial_const_arg()
1453                            {
1454                                debug!(
1455                                    "lower_generic_arg: Lowering type argument as const argument: {:?}",
1456                                    ty,
1457                                );
1458
1459                                let ct =
1460                                    self.lower_const_path_to_const_arg(path, res, ty.id, ty.span);
1461                                return GenericArg::Const(ct.try_as_ambig_ct().unwrap());
1462                            }
1463                        }
1464                    }
1465                    TyKind::DirectConstArg(expr)
1466                        if self.tcx.features().min_generic_const_args() =>
1467                    {
1468                        let ct = match self.can_lower_expr_to_const_arg_direct(expr) {
1469                            Ok(()) => self.lower_expr_to_const_arg_direct(expr, None),
1470                            Err(e) => e.emit(self),
1471                        };
1472                        let ct = self.arena.alloc(ct);
1473                        return GenericArg::Const(ct.try_as_ambig_ct().unwrap());
1474                    }
1475                    _ => {}
1476                }
1477                GenericArg::Type(self.lower_ty_alloc(ty, itctx).try_as_ambig_ty().unwrap())
1478            }
1479            ast::GenericArg::Const(ct) => {
1480                let ct = self.lower_anon_const_to_const_arg_and_alloc(ct);
1481                match ct.try_as_ambig_ct() {
1482                    Some(ct) => GenericArg::Const(ct),
1483                    None => GenericArg::Infer(hir::InferArg { hir_id: ct.hir_id, span: ct.span }),
1484                }
1485            }
1486        }
1487    }
1488
1489    #[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(1489u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("t")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("t");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("itctx")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("itctx");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&t)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn ::tracing::field::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))]
1490    fn lower_ty_alloc(&mut self, t: &Ty, itctx: ImplTraitContext) -> &'hir hir::Ty<'hir> {
1491        self.arena.alloc(self.lower_ty(t, itctx))
1492    }
1493
1494    fn lower_path_ty(
1495        &mut self,
1496        t: &Ty,
1497        qself: &Option<Box<QSelf>>,
1498        path: &Path,
1499        param_mode: ParamMode,
1500        itctx: ImplTraitContext,
1501    ) -> hir::Ty<'hir> {
1502        // Check whether we should interpret this as a bare trait object.
1503        // This check mirrors the one in late resolution. We only introduce this special case in
1504        // the rare occurrence we need to lower `Fresh` anonymous lifetimes.
1505        // The other cases when a qpath should be opportunistically made a trait object are handled
1506        // by `ty_path`.
1507        if qself.is_none()
1508            && let Some(partial_res) = self.get_partial_res(t.id)
1509            && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res()
1510        {
1511            let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1512                let bound = this.lower_poly_trait_ref(
1513                    &PolyTraitRef {
1514                        bound_generic_params: ThinVec::new(),
1515                        modifiers: TraitBoundModifiers::NONE,
1516                        trait_ref: TraitRef { path: path.clone(), ref_id: t.id },
1517                        span: t.span,
1518                        parens: ast::Parens::No,
1519                    },
1520                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitObjectTy),
1521                    itctx,
1522                );
1523                let bounds = this.arena.alloc_from_iter([bound]);
1524                let lifetime_bound = this.elided_dyn_bound(t.span);
1525                (bounds, lifetime_bound)
1526            });
1527            let kind = hir::TyKind::TraitObject(
1528                bounds,
1529                TaggedRef::new(lifetime_bound, TraitObjectSyntax::None),
1530            );
1531            return hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.next_id() };
1532        }
1533
1534        let id = self.lower_node_id(t.id);
1535        let qpath = self.lower_qpath(
1536            t.id,
1537            qself,
1538            path,
1539            param_mode,
1540            AllowReturnTypeNotation::Yes,
1541            itctx,
1542            None,
1543        );
1544        self.ty_path(id, t.span, qpath)
1545    }
1546
1547    fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1548        hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1549    }
1550
1551    fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1552        self.ty(span, hir::TyKind::Tup(tys))
1553    }
1554
1555    fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> hir::Ty<'hir> {
1556        let kind = match &t.kind {
1557            TyKind::Infer => hir::TyKind::Infer(()),
1558            TyKind::Err(guar) => hir::TyKind::Err(*guar),
1559            TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty_alloc(ty, itctx)),
1560            TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1561            TyKind::Ref(region, mt) => {
1562                let lifetime = self.lower_ty_direct_lifetime(t, *region);
1563                hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx))
1564            }
1565            TyKind::PinnedRef(region, mt) => {
1566                let lifetime = self.lower_ty_direct_lifetime(t, *region);
1567                let kind = hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx));
1568                let span = self.lower_span(t.span);
1569                let arg = hir::Ty { kind, span, hir_id: self.next_id() };
1570                let args = self.arena.alloc(hir::GenericArgs {
1571                    args: self.arena.alloc([hir::GenericArg::Type(self.arena.alloc(arg))]),
1572                    constraints: &[],
1573                    parenthesized: hir::GenericArgsParentheses::No,
1574                    span_ext: span,
1575                });
1576                let path = self.make_lang_item_qpath(hir::LangItem::Pin, span, Some(args));
1577                hir::TyKind::Path(path)
1578            }
1579            TyKind::FnPtr(f) => {
1580                let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1581                hir::TyKind::FnPtr(self.arena.alloc(hir::FnPtrTy {
1582                    generic_params,
1583                    safety: self.lower_safety(f.safety, hir::Safety::Safe),
1584                    abi: self.lower_extern(f.ext),
1585                    decl: self.lower_fn_decl(&f.decl, t.id, t.span, FnDeclKind::Pointer, None),
1586                    param_idents: self.lower_fn_params_to_idents(&f.decl),
1587                }))
1588            }
1589            TyKind::UnsafeBinder(f) => {
1590                let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1591                hir::TyKind::UnsafeBinder(self.arena.alloc(hir::UnsafeBinderTy {
1592                    generic_params,
1593                    inner_ty: self.lower_ty_alloc(&f.inner_ty, itctx),
1594                }))
1595            }
1596            TyKind::Never => hir::TyKind::Never,
1597            TyKind::Tup(tys) => hir::TyKind::Tup(
1598                self.arena.alloc_from_iter(tys.iter().map(|ty| self.lower_ty(ty, itctx))),
1599            ),
1600            TyKind::Paren(ty) => {
1601                return self.lower_ty(ty, itctx);
1602            }
1603            TyKind::Path(qself, path) => {
1604                return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1605            }
1606            TyKind::ImplicitSelf => {
1607                let hir_id = self.next_id();
1608                let res = self.expect_full_res(t.id);
1609                let res = self.lower_res(res);
1610                hir::TyKind::Path(hir::QPath::Resolved(
1611                    None,
1612                    self.arena.alloc(hir::Path {
1613                        res,
1614                        segments: self.arena.alloc_from_iter([hir::PathSegment::new(Ident::with_dummy_span(kw::SelfUpper),
                hir_id, res)])arena_vec![self; hir::PathSegment::new(
1615                            Ident::with_dummy_span(kw::SelfUpper),
1616                            hir_id,
1617                            res
1618                        )],
1619                        span: self.lower_span(t.span),
1620                    }),
1621                ))
1622            }
1623            TyKind::Array(ty, length) => hir::TyKind::Array(
1624                self.lower_ty_alloc(ty, itctx),
1625                self.lower_array_length_to_const_arg(length),
1626            ),
1627            TyKind::TraitObject(bounds, kind) => {
1628                let mut lifetime_bound = None;
1629                let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1630                    let bounds =
1631                        this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| match bound {
1632                            // We can safely ignore constness here since AST validation
1633                            // takes care of rejecting invalid modifier combinations and
1634                            // const trait bounds in trait object types.
1635                            GenericBound::Trait(ty) => {
1636                                let trait_ref = this.lower_poly_trait_ref(
1637                                    ty,
1638                                    RelaxedBoundPolicy::Forbidden(
1639                                        RelaxedBoundForbiddenReason::TraitObjectTy,
1640                                    ),
1641                                    itctx,
1642                                );
1643                                Some(trait_ref)
1644                            }
1645                            GenericBound::Outlives(lifetime) => {
1646                                if lifetime_bound.is_none() {
1647                                    lifetime_bound = Some(this.lower_lifetime(
1648                                        lifetime,
1649                                        LifetimeSource::Other,
1650                                        lifetime.ident.into(),
1651                                    ));
1652                                }
1653                                None
1654                            }
1655                            // Ignore `use` syntax since that is not valid in objects.
1656                            GenericBound::Use(_, span) => {
1657                                this.dcx()
1658                                    .span_delayed_bug(*span, "use<> not allowed in dyn types");
1659                                None
1660                            }
1661                        }));
1662                    let lifetime_bound =
1663                        lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1664                    (bounds, lifetime_bound)
1665                });
1666                hir::TyKind::TraitObject(bounds, TaggedRef::new(lifetime_bound, *kind))
1667            }
1668            TyKind::ImplTrait(def_node_id, bounds) => {
1669                let span = t.span;
1670                match itctx {
1671                    ImplTraitContext::OpaqueTy { origin } => {
1672                        self.lower_opaque_impl_trait(span, origin, *def_node_id, bounds, itctx)
1673                    }
1674                    ImplTraitContext::Universal => {
1675                        if let Some(span) = bounds.iter().find_map(|bound| match *bound {
1676                            ast::GenericBound::Use(_, span) => Some(span),
1677                            _ => None,
1678                        }) {
1679                            self.tcx.dcx().emit_err(diagnostics::NoPreciseCapturesOnApit { span });
1680                        }
1681
1682                        let def_id = self.local_def_id(*def_node_id);
1683                        let name = self.tcx.item_name(def_id.to_def_id());
1684                        let ident = Ident::new(name, span);
1685                        let (param, bounds, path) = self.lower_universal_param_and_bounds(
1686                            *def_node_id,
1687                            span,
1688                            ident,
1689                            bounds,
1690                        );
1691                        self.impl_trait_defs.push(param);
1692                        if let Some(bounds) = bounds {
1693                            self.impl_trait_bounds.push(bounds);
1694                        }
1695                        path
1696                    }
1697                    ImplTraitContext::InBinding => {
1698                        hir::TyKind::TraitAscription(self.lower_param_bounds(
1699                            bounds,
1700                            RelaxedBoundPolicy::Allowed(&mut Default::default()),
1701                            itctx,
1702                        ))
1703                    }
1704                    ImplTraitContext::FeatureGated(position, feature) => {
1705                        let guar = self
1706                            .tcx
1707                            .sess
1708                            .create_feature_err(
1709                                MisplacedImplTrait {
1710                                    span: t.span,
1711                                    position: DiagArgFromDisplay(&position),
1712                                },
1713                                feature,
1714                            )
1715                            .emit();
1716                        hir::TyKind::Err(guar)
1717                    }
1718                    ImplTraitContext::Disallowed(position) => {
1719                        let guar = self.dcx().emit_err(MisplacedImplTrait {
1720                            span: t.span,
1721                            position: DiagArgFromDisplay(&position),
1722                        });
1723                        hir::TyKind::Err(guar)
1724                    }
1725                }
1726            }
1727            TyKind::Pat(ty, pat) => {
1728                hir::TyKind::Pat(self.lower_ty_alloc(ty, itctx), self.lower_ty_pat(pat, ty.span))
1729            }
1730            TyKind::FieldOf(ty, variant, field) => hir::TyKind::FieldOf(
1731                self.lower_ty_alloc(ty, itctx),
1732                self.arena.alloc(hir::TyFieldPath {
1733                    variant: variant.map(|variant| self.lower_ident(variant)),
1734                    field: self.lower_ident(*field),
1735                }),
1736            ),
1737            TyKind::MacCall(_) => {
1738                ::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")
1739            }
1740            TyKind::CVarArgs => {
1741                let guar = self.dcx().span_delayed_bug(
1742                    t.span,
1743                    "`TyKind::CVarArgs` should have been handled elsewhere",
1744                );
1745                hir::TyKind::Err(guar)
1746            }
1747            TyKind::View(ty, fields) => {
1748                let ty = self.lower_ty_alloc(ty, itctx);
1749                let fields = self.arena.alloc_slice(fields);
1750                hir::TyKind::View(ty, fields)
1751            }
1752            TyKind::DirectConstArg(expr) => {
1753                let e = self.emit_bad_direct_const_arg(t.span, expr, "type");
1754                hir::TyKind::Err(e)
1755            }
1756            TyKind::Dummy => {
    ::core::panicking::panic_fmt(format_args!("`TyKind::Dummy` should never be lowered"));
}panic!("`TyKind::Dummy` should never be lowered"),
1757        };
1758
1759        hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1760    }
1761
1762    pub(crate) fn emit_bad_direct_const_arg(
1763        &mut self,
1764        span: Span,
1765        expr: &Expr,
1766        expected: &'static str,
1767    ) -> ErrorGuaranteed {
1768        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found `direct_const_arg!()` constant",
                expected))
    })format!("expected {expected}, found `direct_const_arg!()` constant");
1769        if expr::WillCreateDefIdsVisitor.visit_expr(expr).is_break() {
1770            // FIXME(mgca): make this non-fatal once we have a better way to handle
1771            // nested items in invalid `direct_const_arg!()` arguments.
1772            self.dcx().struct_span_fatal(span, msg).emit()
1773        } else {
1774            self.dcx().struct_span_err(span, msg).emit()
1775        }
1776    }
1777
1778    fn lower_ty_direct_lifetime(
1779        &mut self,
1780        t: &Ty,
1781        region: Option<Lifetime>,
1782    ) -> &'hir hir::Lifetime {
1783        let (region, syntax) = match region {
1784            Some(region) => (region, region.ident.into()),
1785
1786            None => {
1787                let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1788                    self.owner.get_lifetime_res(t.id)
1789                {
1790                    {
    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);
1791                    start
1792                } else {
1793                    self.next_node_id()
1794                };
1795                let span = self.tcx.sess.source_map().start_point(t.span).shrink_to_hi();
1796                let region = Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id };
1797                (region, LifetimeSyntax::Implicit)
1798            }
1799        };
1800        self.lower_lifetime(&region, LifetimeSource::Reference, syntax)
1801    }
1802
1803    /// Lowers a `ReturnPositionOpaqueTy` (`-> impl Trait`) or a `TypeAliasesOpaqueTy` (`type F =
1804    /// impl Trait`): this creates the associated Opaque Type (TAIT) definition and then returns a
1805    /// HIR type that references the TAIT.
1806    ///
1807    /// Given a function definition like:
1808    ///
1809    /// ```rust
1810    /// use std::fmt::Debug;
1811    ///
1812    /// fn test<'a, T: Debug>(x: &'a T) -> impl Debug + 'a {
1813    ///     x
1814    /// }
1815    /// ```
1816    ///
1817    /// we will create a TAIT definition in the HIR like
1818    ///
1819    /// ```rust,ignore (pseudo-Rust)
1820    /// type TestReturn<'a, T, 'x> = impl Debug + 'x
1821    /// ```
1822    ///
1823    /// and return a type like `TestReturn<'static, T, 'a>`, so that the function looks like:
1824    ///
1825    /// ```rust,ignore (pseudo-Rust)
1826    /// fn test<'a, T: Debug>(x: &'a T) -> TestReturn<'static, T, 'a>
1827    /// ```
1828    ///
1829    /// Note the subtlety around type parameters! The new TAIT, `TestReturn`, inherits all the
1830    /// type parameters from the function `test` (this is implemented in the query layer, they aren't
1831    /// added explicitly in the HIR). But this includes all the lifetimes, and we only want to
1832    /// capture the lifetimes that are referenced in the bounds. Therefore, we add *extra* lifetime parameters
1833    /// for the lifetimes that get captured (`'x`, in our example above) and reference those.
1834    x;#[instrument(level = "debug", skip(self), ret)]
1835    fn lower_opaque_impl_trait(
1836        &mut self,
1837        span: Span,
1838        origin: hir::OpaqueTyOrigin<LocalDefId>,
1839        opaque_ty_node_id: NodeId,
1840        bounds: &GenericBounds,
1841        itctx: ImplTraitContext,
1842    ) -> hir::TyKind<'hir> {
1843        // Make sure we know that some funky desugaring has been going on here.
1844        // This is a first: there is code in other places like for loop
1845        // desugaring that explicitly states that we don't want to track that.
1846        // Not tracking it makes lints in rustc and clippy very fragile, as
1847        // frequently opened issues show.
1848        let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1849
1850        self.lower_opaque_inner(opaque_ty_node_id, origin, opaque_ty_span, |this| {
1851            this.lower_param_bounds(
1852                bounds,
1853                RelaxedBoundPolicy::Allowed(&mut Default::default()),
1854                itctx,
1855            )
1856        })
1857    }
1858
1859    fn lower_opaque_inner(
1860        &mut self,
1861        opaque_ty_node_id: NodeId,
1862        origin: hir::OpaqueTyOrigin<LocalDefId>,
1863        opaque_ty_span: Span,
1864        lower_item_bounds: impl FnOnce(&mut Self) -> &'hir [hir::GenericBound<'hir>],
1865    ) -> hir::TyKind<'hir> {
1866        let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id);
1867        let opaque_ty_hir_id = self.lower_node_id(opaque_ty_node_id);
1868        {
    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:1868",
                        "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(1868u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("opaque_ty_def_id")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("opaque_ty_def_id");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("opaque_ty_hir_id")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("opaque_ty_hir_id");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opaque_ty_def_id)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opaque_ty_hir_id)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?opaque_ty_def_id, ?opaque_ty_hir_id);
1869
1870        let bounds = lower_item_bounds(self);
1871        let opaque_ty_def = hir::OpaqueTy {
1872            hir_id: opaque_ty_hir_id,
1873            def_id: opaque_ty_def_id,
1874            bounds,
1875            origin,
1876            span: self.lower_span(opaque_ty_span),
1877        };
1878        let opaque_ty_def = self.arena.alloc(opaque_ty_def);
1879
1880        hir::TyKind::OpaqueDef(opaque_ty_def)
1881    }
1882
1883    fn lower_precise_capturing_args(
1884        &mut self,
1885        precise_capturing_args: &[PreciseCapturingArg],
1886    ) -> &'hir [hir::PreciseCapturingArg<'hir>] {
1887        self.arena.alloc_from_iter(precise_capturing_args.iter().map(|arg| match arg {
1888            PreciseCapturingArg::Lifetime(lt) => hir::PreciseCapturingArg::Lifetime(
1889                self.lower_lifetime(lt, LifetimeSource::PreciseCapturing, lt.ident.into()),
1890            ),
1891            PreciseCapturingArg::Arg(path, id) => {
1892                let [segment] = path.segments.as_slice() else {
1893                    ::core::panicking::panic("explicit panic");panic!();
1894                };
1895                let res = self.get_partial_res(*id).map_or(Res::Err, |partial_res| {
1896                    partial_res.full_res().expect("no partial res expected for precise capture arg")
1897                });
1898                hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
1899                    hir_id: self.lower_node_id(*id),
1900                    ident: self.lower_ident(segment.ident),
1901                    res: self.lower_res(res),
1902                })
1903            }
1904        }))
1905    }
1906
1907    fn lower_fn_params_to_idents(&mut self, decl: &FnDecl) -> &'hir [Option<Ident>] {
1908        self.arena.alloc_from_iter(decl.inputs.iter().map(|param| match param.pat.kind {
1909            PatKind::Missing => None,
1910            PatKind::Ident(_, ident, _) => Some(self.lower_ident(ident)),
1911            PatKind::Wild => Some(Ident::new(kw::Underscore, self.lower_span(param.pat.span))),
1912            _ => {
1913                self.dcx().span_delayed_bug(
1914                    param.pat.span,
1915                    "non-missing/ident/wild param pat must trigger an error",
1916                );
1917                None
1918            }
1919        }))
1920    }
1921
1922    /// Lowers a function declaration.
1923    ///
1924    /// `decl`: the unlowered (AST) function declaration.
1925    ///
1926    /// `fn_node_id`: `impl Trait` arguments are lowered into generic parameters on the given
1927    /// `NodeId`.
1928    ///
1929    /// `transform_return_type`: if `Some`, applies some conversion to the return type, such as is
1930    /// needed for `async fn` and `gen fn`. See [`CoroutineKind`] for more details.
1931    #[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(1931u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("decl")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("decl");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_node_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_node_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("kind")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("kind");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("coro")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("coro");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&decl)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_node_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coro)
                                                            as &dyn ::tracing::field::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 splatted = decl.splatted();
            let mut inputs = &decl.inputs[..];
            if decl.c_variadic() {
                splatted = None;
                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.owner.def_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.owner.def_id,
                                                    in_trait_or_impl: None,
                                                },
                                            },
                                        FnDeclKind::Trait =>
                                            ImplTraitContext::OpaqueTy {
                                                origin: hir::OpaqueTyOrigin::FnReturn {
                                                    parent: self.owner.def_id,
                                                    in_trait_or_impl: Some(hir::RpitContext::Trait),
                                                },
                                            },
                                        FnDeclKind::Impl =>
                                            ImplTraitContext::OpaqueTy {
                                                origin: hir::OpaqueTyOrigin::FnReturn {
                                                    parent: self.owner.def_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)),
                        },
                };
            let fn_decl_kind =
                hir::FnDeclFlags::default().set_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,
                                                }
                                            })).set_lifetime_elision_allowed(self.owner.id == fn_node_id
                                    &&
                                    self.owner.lifetime_elision_allowed).set_c_variadic(c_variadic).set_splatted(splatted,
                        inputs.len()).unwrap();
            self.arena.alloc(hir::FnDecl { inputs, output, fn_decl_kind })
        }
    }
}#[instrument(level = "debug", skip(self))]
1932    fn lower_fn_decl(
1933        &mut self,
1934        decl: &FnDecl,
1935        fn_node_id: NodeId,
1936        fn_span: Span,
1937        kind: FnDeclKind,
1938        coro: Option<CoroutineKind>,
1939    ) -> &'hir hir::FnDecl<'hir> {
1940        let c_variadic = decl.c_variadic();
1941        let mut splatted = decl.splatted();
1942
1943        // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1944        // as they are not explicit in HIR/Ty function signatures.
1945        // (instead, the `c_variadic` flag is set to `true`)
1946        let mut inputs = &decl.inputs[..];
1947        if decl.c_variadic() {
1948            // Splat + variadic errors in AST validation, so just ignore one of them here.
1949            splatted = None;
1950            inputs = &inputs[..inputs.len() - 1];
1951        }
1952        let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1953            let itctx = match kind {
1954                FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait => {
1955                    ImplTraitContext::Universal
1956                }
1957                FnDeclKind::ExternFn => {
1958                    ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnParam)
1959                }
1960                FnDeclKind::Closure => {
1961                    ImplTraitContext::Disallowed(ImplTraitPosition::ClosureParam)
1962                }
1963                FnDeclKind::Pointer => {
1964                    ImplTraitContext::Disallowed(ImplTraitPosition::PointerParam)
1965                }
1966            };
1967            self.lower_ty(&param.ty, itctx)
1968        }));
1969
1970        let output = match coro {
1971            Some(coro) => {
1972                let fn_def_id = self.owner.def_id;
1973                self.lower_coroutine_fn_ret_ty(&decl.output, fn_def_id, coro, kind)
1974            }
1975            None => match &decl.output {
1976                FnRetTy::Ty(ty) => {
1977                    let itctx = match kind {
1978                        FnDeclKind::Fn | FnDeclKind::Inherent => ImplTraitContext::OpaqueTy {
1979                            origin: hir::OpaqueTyOrigin::FnReturn {
1980                                parent: self.owner.def_id,
1981                                in_trait_or_impl: None,
1982                            },
1983                        },
1984                        FnDeclKind::Trait => ImplTraitContext::OpaqueTy {
1985                            origin: hir::OpaqueTyOrigin::FnReturn {
1986                                parent: self.owner.def_id,
1987                                in_trait_or_impl: Some(hir::RpitContext::Trait),
1988                            },
1989                        },
1990                        FnDeclKind::Impl => ImplTraitContext::OpaqueTy {
1991                            origin: hir::OpaqueTyOrigin::FnReturn {
1992                                parent: self.owner.def_id,
1993                                in_trait_or_impl: Some(hir::RpitContext::TraitImpl),
1994                            },
1995                        },
1996                        FnDeclKind::ExternFn => {
1997                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnReturn)
1998                        }
1999                        FnDeclKind::Closure => {
2000                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureReturn)
2001                        }
2002                        FnDeclKind::Pointer => {
2003                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerReturn)
2004                        }
2005                    };
2006                    hir::FnRetTy::Return(self.lower_ty_alloc(ty, itctx))
2007                }
2008                FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(*span)),
2009            },
2010        };
2011
2012        let fn_decl_kind = hir::FnDeclFlags::default()
2013            .set_implicit_self(decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
2014                let is_mutable_pat = matches!(
2015                    arg.pat.kind,
2016                    PatKind::Ident(hir::BindingMode(_, Mutability::Mut), ..)
2017                );
2018
2019                match &arg.ty.kind {
2020                    TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2021                    TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2022                    // Given we are only considering `ImplicitSelf` types, we needn't consider
2023                    // the case where we have a mutable pattern to a reference as that would
2024                    // no longer be an `ImplicitSelf`.
2025                    TyKind::Ref(_, mt) | TyKind::PinnedRef(_, mt)
2026                        if mt.ty.kind.is_implicit_self() =>
2027                    {
2028                        match mt.mutbl {
2029                            hir::Mutability::Not => hir::ImplicitSelfKind::RefImm,
2030                            hir::Mutability::Mut => hir::ImplicitSelfKind::RefMut,
2031                        }
2032                    }
2033                    _ => hir::ImplicitSelfKind::None,
2034                }
2035            }))
2036            .set_lifetime_elision_allowed(
2037                self.owner.id == fn_node_id && self.owner.lifetime_elision_allowed,
2038            )
2039            .set_c_variadic(c_variadic)
2040            .set_splatted(splatted, inputs.len())
2041            .unwrap();
2042
2043        self.arena.alloc(hir::FnDecl { inputs, output, fn_decl_kind })
2044    }
2045
2046    // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
2047    // combined with the following definition of `OpaqueTy`:
2048    //
2049    //     type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
2050    //
2051    // `output`: unlowered output type (`T` in `-> T`)
2052    // `fn_node_id`: `NodeId` of the parent function (used to create child impl trait definition)
2053    // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
2054    #[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(2054u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("output")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("output");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("coro")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("coro");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_kind")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_kind");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&output)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coro)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_kind)
                                                            as &dyn ::tracing::field::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))]
2055    fn lower_coroutine_fn_ret_ty(
2056        &mut self,
2057        output: &FnRetTy,
2058        fn_def_id: LocalDefId,
2059        coro: CoroutineKind,
2060        fn_kind: FnDeclKind,
2061    ) -> hir::FnRetTy<'hir> {
2062        let span = self.lower_span(output.span());
2063
2064        let (opaque_ty_node_id, allowed_features) = match coro {
2065            CoroutineKind::Async { return_impl_trait_id, .. } => (return_impl_trait_id, None),
2066            CoroutineKind::Gen { return_impl_trait_id, .. } => (return_impl_trait_id, None),
2067            CoroutineKind::AsyncGen { return_impl_trait_id, .. } => {
2068                (return_impl_trait_id, Some(Arc::clone(&self.allow_async_iterator)))
2069            }
2070        };
2071
2072        let opaque_ty_span =
2073            self.mark_span_with_reason(DesugaringKind::Async, span, allowed_features);
2074
2075        let in_trait_or_impl = match fn_kind {
2076            FnDeclKind::Trait => Some(hir::RpitContext::Trait),
2077            FnDeclKind::Impl => Some(hir::RpitContext::TraitImpl),
2078            FnDeclKind::Fn | FnDeclKind::Inherent => None,
2079            FnDeclKind::ExternFn | FnDeclKind::Closure | FnDeclKind::Pointer => unreachable!(),
2080        };
2081
2082        let opaque_ty_ref = self.lower_opaque_inner(
2083            opaque_ty_node_id,
2084            hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, in_trait_or_impl },
2085            opaque_ty_span,
2086            |this| {
2087                let bound = this.lower_coroutine_fn_output_type_to_bound(
2088                    output,
2089                    coro,
2090                    opaque_ty_span,
2091                    ImplTraitContext::OpaqueTy {
2092                        origin: hir::OpaqueTyOrigin::FnReturn {
2093                            parent: fn_def_id,
2094                            in_trait_or_impl,
2095                        },
2096                    },
2097                );
2098                arena_vec![this; bound]
2099            },
2100        );
2101
2102        let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2103        hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
2104    }
2105
2106    /// Transforms `-> T` into `Future<Output = T>`.
2107    fn lower_coroutine_fn_output_type_to_bound(
2108        &mut self,
2109        output: &FnRetTy,
2110        coro: CoroutineKind,
2111        opaque_ty_span: Span,
2112        itctx: ImplTraitContext,
2113    ) -> hir::GenericBound<'hir> {
2114        // Compute the `T` in `Future<Output = T>` from the return type.
2115        let output_ty = match output {
2116            FnRetTy::Ty(ty) => {
2117                // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
2118                // `impl Future` opaque type that `async fn` implicitly
2119                // generates.
2120                self.lower_ty_alloc(ty, itctx)
2121            }
2122            FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
2123        };
2124
2125        // "<$assoc_ty_name = T>"
2126        let (assoc_ty_name, trait_lang_item) = match coro {
2127            CoroutineKind::Async { .. } => (sym::Output, hir::LangItem::Future),
2128            CoroutineKind::Gen { .. } => (sym::Item, hir::LangItem::Iterator),
2129            CoroutineKind::AsyncGen { .. } => (sym::Item, hir::LangItem::AsyncIterator),
2130        };
2131
2132        let bound_args = self.arena.alloc(hir::GenericArgs {
2133            args: &[],
2134            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)],
2135            parenthesized: hir::GenericArgsParentheses::No,
2136            span_ext: DUMMY_SP,
2137        });
2138
2139        hir::GenericBound::Trait(hir::PolyTraitRef {
2140            bound_generic_params: &[],
2141            modifiers: hir::TraitBoundModifiers::NONE,
2142            trait_ref: hir::TraitRef {
2143                path: self.make_lang_item_path(trait_lang_item, opaque_ty_span, Some(bound_args)),
2144                hir_ref_id: self.next_id(),
2145            },
2146            span: opaque_ty_span,
2147        })
2148    }
2149
2150    #[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(2150u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("tpb")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("tpb");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("rbp")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("rbp");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("itctx")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("itctx");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tpb)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rbp)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn ::tracing::field::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))]
2151    fn lower_param_bound(
2152        &mut self,
2153        tpb: &GenericBound,
2154        rbp: RelaxedBoundPolicy<'_>,
2155        itctx: ImplTraitContext,
2156    ) -> hir::GenericBound<'hir> {
2157        match tpb {
2158            GenericBound::Trait(p) => {
2159                hir::GenericBound::Trait(self.lower_poly_trait_ref(p, rbp, itctx))
2160            }
2161            GenericBound::Outlives(lifetime) => hir::GenericBound::Outlives(self.lower_lifetime(
2162                lifetime,
2163                LifetimeSource::OutlivesBound,
2164                lifetime.ident.into(),
2165            )),
2166            GenericBound::Use(args, span) => hir::GenericBound::Use(
2167                self.lower_precise_capturing_args(args),
2168                self.lower_span(*span),
2169            ),
2170        }
2171    }
2172
2173    fn lower_lifetime(
2174        &mut self,
2175        l: &Lifetime,
2176        source: LifetimeSource,
2177        syntax: LifetimeSyntax,
2178    ) -> &'hir hir::Lifetime {
2179        self.new_named_lifetime(l.id, l.id, l.ident, source, syntax)
2180    }
2181
2182    fn lower_lifetime_hidden_in_path(
2183        &mut self,
2184        id: NodeId,
2185        span: Span,
2186        angle_brackets: AngleBrackets,
2187    ) -> &'hir hir::Lifetime {
2188        self.new_named_lifetime(
2189            id,
2190            id,
2191            Ident::new(kw::UnderscoreLifetime, span),
2192            LifetimeSource::Path { angle_brackets },
2193            LifetimeSyntax::Implicit,
2194        )
2195    }
2196
2197    #[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(2197u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("new_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("new_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ident")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ident");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("syntax")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("syntax");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&new_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&syntax)
                                                            as &dyn ::tracing::field::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.owner.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:2231",
                                    "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(2231u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("res");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                        as &dyn ::tracing::field::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))]
2198    fn new_named_lifetime(
2199        &mut self,
2200        id: NodeId,
2201        new_id: NodeId,
2202        ident: Ident,
2203        source: LifetimeSource,
2204        syntax: LifetimeSyntax,
2205    ) -> &'hir hir::Lifetime {
2206        let res = if let Some(res) = self.owner.get_lifetime_res(id) {
2207            match res {
2208                LifetimeRes::Param { param, .. } => hir::LifetimeKind::Param(param),
2209                LifetimeRes::Fresh { param, .. } => {
2210                    assert_eq!(ident.name, kw::UnderscoreLifetime);
2211                    let param = self.local_def_id(param);
2212                    hir::LifetimeKind::Param(param)
2213                }
2214                LifetimeRes::Infer => {
2215                    assert_eq!(ident.name, kw::UnderscoreLifetime);
2216                    hir::LifetimeKind::Infer
2217                }
2218                LifetimeRes::Static { .. } => {
2219                    assert!(matches!(ident.name, kw::StaticLifetime | kw::UnderscoreLifetime));
2220                    hir::LifetimeKind::Static
2221                }
2222                LifetimeRes::Error(guar) => hir::LifetimeKind::Error(guar),
2223                LifetimeRes::ElidedAnchor { .. } => {
2224                    panic!("Unexpected `ElidedAnchar` {:?} at {:?}", ident, ident.span);
2225                }
2226            }
2227        } else {
2228            hir::LifetimeKind::Error(self.dcx().span_delayed_bug(ident.span, "unresolved lifetime"))
2229        };
2230
2231        debug!(?res);
2232        self.arena.alloc(hir::Lifetime::new(
2233            self.lower_node_id(new_id),
2234            self.lower_ident(ident),
2235            res,
2236            source,
2237            syntax,
2238        ))
2239    }
2240
2241    fn lower_generic_params_mut(
2242        &mut self,
2243        params: &[GenericParam],
2244        source: hir::GenericParamSource,
2245    ) -> impl Iterator<Item = hir::GenericParam<'hir>> {
2246        params.iter().map(move |param| self.lower_generic_param(param, source))
2247    }
2248
2249    fn lower_generic_params(
2250        &mut self,
2251        params: &[GenericParam],
2252        source: hir::GenericParamSource,
2253    ) -> &'hir [hir::GenericParam<'hir>] {
2254        self.arena.alloc_from_iter(self.lower_generic_params_mut(params, source))
2255    }
2256
2257    #[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(2257u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("param")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("param");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn ::tracing::field::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))]
2258    fn lower_generic_param(
2259        &mut self,
2260        param: &GenericParam,
2261        source: hir::GenericParamSource,
2262    ) -> hir::GenericParam<'hir> {
2263        let (name, kind) = self.lower_generic_param_kind(param, source);
2264
2265        let hir_id = self.lower_node_id(param.id);
2266        let param_attrs = &param.attrs;
2267        let param_span = param.span();
2268        let param = hir::GenericParam {
2269            hir_id,
2270            def_id: self.local_def_id(param.id),
2271            name,
2272            span: self.lower_span(param.span()),
2273            pure_wrt_drop: attr::contains_name(&param.attrs, sym::may_dangle),
2274            kind,
2275            colon_span: param.colon_span.map(|s| self.lower_span(s)),
2276            source,
2277        };
2278        self.lower_attrs(hir_id, param_attrs, param_span, Target::from_generic_param(&param));
2279        param
2280    }
2281
2282    fn lower_generic_param_kind(
2283        &mut self,
2284        param: &GenericParam,
2285        source: hir::GenericParamSource,
2286    ) -> (hir::ParamName, hir::GenericParamKind<'hir>) {
2287        match &param.kind {
2288            GenericParamKind::Lifetime => {
2289                // AST resolution emitted an error on those parameters, so we lower them using
2290                // `ParamName::Error`.
2291                let ident = self.lower_ident(param.ident);
2292                let param_name =
2293                    if let Some(LifetimeRes::Error(..)) = self.owner.get_lifetime_res(param.id) {
2294                        ParamName::Error(ident)
2295                    } else {
2296                        ParamName::Plain(ident)
2297                    };
2298                let kind =
2299                    hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2300
2301                (param_name, kind)
2302            }
2303            GenericParamKind::Type { default, .. } => {
2304                // Not only do we deny type param defaults in binders but we also map them to `None`
2305                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2306                let default = default
2307                    .as_ref()
2308                    .filter(|_| match source {
2309                        hir::GenericParamSource::Generics => true,
2310                        hir::GenericParamSource::Binder => {
2311                            self.dcx().emit_err(diagnostics::GenericParamDefaultInBinder {
2312                                span: param.span(),
2313                            });
2314
2315                            false
2316                        }
2317                    })
2318                    .map(|def| {
2319                        self.lower_ty_alloc(
2320                            def,
2321                            ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2322                        )
2323                    });
2324
2325                let kind = hir::GenericParamKind::Type { default, synthetic: false };
2326
2327                (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2328            }
2329            GenericParamKind::Const { ty, span: _, default } => {
2330                let ty = self.lower_ty_alloc(
2331                    ty,
2332                    ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2333                );
2334
2335                // Not only do we deny const param defaults in binders but we also map them to `None`
2336                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2337                let default = default
2338                    .as_ref()
2339                    .filter(|anon_const| match source {
2340                        hir::GenericParamSource::Generics => true,
2341                        hir::GenericParamSource::Binder => {
2342                            let err =
2343                                diagnostics::GenericParamDefaultInBinder { span: param.span() };
2344                            if expr::WillCreateDefIdsVisitor
2345                                .visit_expr(&anon_const.value)
2346                                .is_break()
2347                            {
2348                                // FIXME(mgca): make this non-fatal once we have a better way
2349                                // to handle nested items in anno const from binder
2350                                // Issue: https://github.com/rust-lang/rust/issues/123629
2351                                self.dcx().emit_fatal(err)
2352                            } else {
2353                                self.dcx().emit_err(err);
2354                                false
2355                            }
2356                        }
2357                    })
2358                    .map(|def| self.lower_anon_const_to_const_arg_and_alloc(def));
2359
2360                (
2361                    hir::ParamName::Plain(self.lower_ident(param.ident)),
2362                    hir::GenericParamKind::Const { ty, default },
2363                )
2364            }
2365        }
2366    }
2367
2368    fn lower_trait_ref(
2369        &mut self,
2370        modifiers: ast::TraitBoundModifiers,
2371        p: &TraitRef,
2372        itctx: ImplTraitContext,
2373    ) -> hir::TraitRef<'hir> {
2374        let path = match self.lower_qpath(
2375            p.ref_id,
2376            &None,
2377            &p.path,
2378            ParamMode::Explicit,
2379            AllowReturnTypeNotation::No,
2380            itctx,
2381            Some(modifiers),
2382        ) {
2383            hir::QPath::Resolved(None, path) => path,
2384            qpath => {
    ::core::panicking::panic_fmt(format_args!("lower_trait_ref: unexpected QPath `{0:?}`",
            qpath));
}panic!("lower_trait_ref: unexpected QPath `{qpath:?}`"),
2385        };
2386        hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2387    }
2388
2389    #[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(2389u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("bound_generic_params")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("bound_generic_params");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("modifiers")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("modifiers");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("trait_ref")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("trait_ref");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("rbp")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("rbp");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("itctx")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("itctx");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_generic_params)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&modifiers)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rbp)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn ::tracing::field::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))]
2390    fn lower_poly_trait_ref(
2391        &mut self,
2392        PolyTraitRef { bound_generic_params, modifiers, trait_ref, span, parens: _ }: &PolyTraitRef,
2393        rbp: RelaxedBoundPolicy<'_>,
2394        itctx: ImplTraitContext,
2395    ) -> hir::PolyTraitRef<'hir> {
2396        let bound_generic_params =
2397            self.lower_lifetime_binder(trait_ref.ref_id, bound_generic_params);
2398        let trait_ref = self.lower_trait_ref(*modifiers, trait_ref, itctx);
2399        let modifiers = self.lower_trait_bound_modifiers(*modifiers);
2400
2401        if let ast::BoundPolarity::Maybe(_) = modifiers.polarity {
2402            self.validate_relaxed_bound(trait_ref, *span, rbp);
2403        }
2404
2405        hir::PolyTraitRef {
2406            bound_generic_params,
2407            modifiers,
2408            trait_ref,
2409            span: self.lower_span(*span),
2410        }
2411    }
2412
2413    fn validate_relaxed_bound(
2414        &self,
2415        trait_ref: hir::TraitRef<'_>,
2416        span: Span,
2417        rbp: RelaxedBoundPolicy<'_>,
2418    ) {
2419        // Even though feature `more_maybe_bounds` enables the user to relax all default bounds
2420        // other than `Sized` in a lot more positions (thereby bypassing the given policy), we don't
2421        // want to advertise it to the user (via a feature gate error) since it's super internal.
2422        //
2423        // FIXME(more_maybe_bounds): Moreover, if we actually were to add proper default traits
2424        // (like a hypothetical `Move` or `Leak`) we would want to validate the location according
2425        // to default trait elaboration in HIR ty lowering (which depends on the specific trait in
2426        // question: E.g., `?Sized` & `?Move` most likely won't be allowed in all the same places).
2427
2428        match rbp {
2429            RelaxedBoundPolicy::Allowed(dedup_map) => {
2430                // `trait_def_id` only returns `None` for errors during resolution.
2431                let Some(trait_def_id) = trait_ref.trait_def_id() else { return };
2432                let tcx = self.tcx;
2433                let err = |s| {
2434                    let name = tcx.item_name(trait_def_id);
2435                    tcx.dcx()
2436                        .struct_span_err(
2437                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [span, s]))vec![span, s],
2438                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("duplicate relaxed `{0}` bounds",
                name))
    })format!("duplicate relaxed `{name}` bounds"),
2439                        )
2440                        .with_code(E0203)
2441                        .emit();
2442                };
2443                dedup_map.entry(trait_def_id).and_modify(|&mut s| err(s)).or_insert(span);
2444                return;
2445            }
2446            RelaxedBoundPolicy::Forbidden(reason) => {
2447                let gate = |context, subject| {
2448                    let extended = self.tcx.features().more_maybe_bounds();
2449                    let is_sized = trait_ref
2450                        .trait_def_id()
2451                        .is_some_and(|def_id| self.tcx.is_lang_item(def_id, hir::LangItem::Sized));
2452
2453                    if extended && !is_sized {
2454                        return;
2455                    }
2456
2457                    let prefix = if extended { "`Sized` " } else { "" };
2458                    let mut diag = self.dcx().struct_span_err(
2459                        span,
2460                        ::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}"),
2461                    );
2462                    if is_sized {
2463                        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!(
2464                            "{subject} are not implicitly bounded by `Sized`, \
2465                             so there is nothing to relax"
2466                        ));
2467                    }
2468                    diag.emit();
2469                };
2470
2471                match reason {
2472                    RelaxedBoundForbiddenReason::TraitObjectTy => {
2473                        gate("trait object types", "trait object types");
2474                        return;
2475                    }
2476                    RelaxedBoundForbiddenReason::SuperTrait => {
2477                        gate("supertrait bounds", "traits");
2478                        return;
2479                    }
2480                    RelaxedBoundForbiddenReason::TraitAlias => {
2481                        gate("trait alias bounds", "trait aliases");
2482                        return;
2483                    }
2484                    RelaxedBoundForbiddenReason::AssocTyBounds
2485                    | RelaxedBoundForbiddenReason::WhereBound => {}
2486                };
2487            }
2488        }
2489
2490        self.dcx()
2491            .struct_span_err(span, "this relaxed bound is not permitted here")
2492            .with_note(
2493                "in this context, relaxed bounds are only allowed on \
2494                 type parameters defined on the closest item",
2495            )
2496            .emit();
2497    }
2498
2499    fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy<'hir> {
2500        hir::MutTy { ty: self.lower_ty_alloc(&mt.ty, itctx), mutbl: mt.mutbl }
2501    }
2502
2503    x;#[instrument(level = "debug", skip(self), ret)]
2504    fn lower_param_bounds(
2505        &mut self,
2506        bounds: &[GenericBound],
2507        rbp: RelaxedBoundPolicy<'_>,
2508        itctx: ImplTraitContext,
2509    ) -> hir::GenericBounds<'hir> {
2510        self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, rbp, itctx))
2511    }
2512
2513    fn lower_param_bounds_mut(
2514        &mut self,
2515        bounds: &[GenericBound],
2516        mut rbp: RelaxedBoundPolicy<'_>,
2517        itctx: ImplTraitContext,
2518    ) -> impl Iterator<Item = hir::GenericBound<'hir>> {
2519        bounds.iter().map(move |bound| self.lower_param_bound(bound, rbp.reborrow(), itctx))
2520    }
2521
2522    x;#[instrument(level = "debug", skip(self), ret)]
2523    fn lower_universal_param_and_bounds(
2524        &mut self,
2525        node_id: NodeId,
2526        span: Span,
2527        ident: Ident,
2528        bounds: &[GenericBound],
2529    ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2530        // Add a definition for the in-band `Param`.
2531        let def_id = self.local_def_id(node_id);
2532        let span = self.lower_span(span);
2533
2534        // Set the name to `impl Bound1 + Bound2`.
2535        let param = hir::GenericParam {
2536            hir_id: self.lower_node_id(node_id),
2537            def_id,
2538            name: ParamName::Plain(self.lower_ident(ident)),
2539            pure_wrt_drop: false,
2540            span,
2541            kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2542            colon_span: None,
2543            source: hir::GenericParamSource::Generics,
2544        };
2545
2546        let preds = self.lower_generic_bound_predicate(
2547            ident,
2548            node_id,
2549            &GenericParamKind::Type { default: None },
2550            bounds,
2551            /* colon_span */ None,
2552            span,
2553            RelaxedBoundPolicy::Allowed(&mut Default::default()),
2554            ImplTraitContext::Universal,
2555            hir::PredicateOrigin::ImplTrait,
2556        );
2557
2558        let hir_id = self.next_id();
2559        let res = Res::Def(DefKind::TyParam, def_id.to_def_id());
2560        let ty = hir::TyKind::Path(hir::QPath::Resolved(
2561            None,
2562            self.arena.alloc(hir::Path {
2563                span,
2564                res,
2565                segments:
2566                    arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2567            }),
2568        ));
2569
2570        (param, preds, ty)
2571    }
2572
2573    /// Lowers a block directly to an expression, presuming that it
2574    /// has no attributes and is not targeted by a `break`.
2575    fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2576        let block = self.lower_block(b, false);
2577        self.expr_block(block)
2578    }
2579
2580    fn lower_array_length_to_const_arg(&mut self, c: &AnonConst) -> &'hir hir::ConstArg<'hir> {
2581        // We cannot just match on `ExprKind::Underscore` as `(_)` is represented as
2582        // `ExprKind::Paren(ExprKind::Underscore)` and should also be lowered to `GenericArg::Infer`
2583        match c.value.peel_parens().kind {
2584            ExprKind::Underscore => {
2585                let ct_kind = hir::ConstArgKind::Infer(());
2586                self.arena.alloc(hir::ConstArg {
2587                    hir_id: self.lower_node_id(c.id),
2588                    kind: ct_kind,
2589                    span: self.lower_span(c.value.span),
2590                })
2591            }
2592            _ => self.lower_anon_const_to_const_arg_and_alloc(c),
2593        }
2594    }
2595
2596    /// Used when lowering a type argument that turned out to actually be a const argument.
2597    ///
2598    /// Only use for that purpose since otherwise it will create a duplicate def.
2599    #[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(2599u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("res");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ty_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ty_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::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, 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))]
2600    fn lower_const_path_to_const_arg(
2601        &mut self,
2602        path: &Path,
2603        res: Res<NodeId>,
2604        ty_id: NodeId,
2605        span: Span,
2606    ) -> &'hir hir::ConstArg<'hir> {
2607        let tcx = self.tcx;
2608
2609        let is_trivial_path = path.is_potential_trivial_const_arg()
2610            && matches!(res, Res::Def(DefKind::ConstParam, _));
2611        let ct_kind = if is_trivial_path || tcx.features().min_generic_const_args() {
2612            let qpath = self.lower_qpath(
2613                ty_id,
2614                &None,
2615                path,
2616                ParamMode::Explicit,
2617                AllowReturnTypeNotation::No,
2618                // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2619                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2620                None,
2621            );
2622            hir::ConstArgKind::Path(qpath)
2623        } else {
2624            // Construct an AnonConst where the expr is the "ty"'s path.
2625            let node_id = self.next_node_id();
2626            let span = self.lower_span(span);
2627
2628            // Add a definition for the in-band const def.
2629            // We're lowering a const argument that was originally thought to be a type argument,
2630            // so the def collector didn't create the def ahead of time. That's why we have to do
2631            // it here.
2632            let def_id = self.create_def(node_id, None, DefKind::AnonConst, span);
2633            let hir_id = self.lower_node_id(node_id);
2634
2635            let path_expr = Expr {
2636                id: ty_id,
2637                kind: ExprKind::Path(None, path.clone()),
2638                span,
2639                attrs: AttrVec::new(),
2640                tokens: None,
2641            };
2642
2643            let ct = self.with_new_scopes(span, |this| {
2644                self.arena.alloc(hir::AnonConst {
2645                    def_id,
2646                    hir_id,
2647                    body: this.lower_const_body(path_expr.span, Some(&path_expr)),
2648                    span,
2649                })
2650            });
2651            hir::ConstArgKind::Anon(ct)
2652        };
2653
2654        self.arena.alloc(hir::ConstArg {
2655            hir_id: self.next_id(),
2656            kind: ct_kind,
2657            span: self.lower_span(span),
2658        })
2659    }
2660
2661    fn lower_const_item_rhs(
2662        &mut self,
2663        rhs_kind: &ConstItemRhsKind,
2664        span: Span,
2665    ) -> hir::ConstItemRhs<'hir> {
2666        match rhs_kind {
2667            ConstItemRhsKind::Body { rhs: Some(body) } => {
2668                hir::ConstItemRhs::Body(self.lower_const_body(span, Some(body)))
2669            }
2670            ConstItemRhsKind::Body { rhs: None } => {
2671                hir::ConstItemRhs::Body(self.lower_const_body(span, None))
2672            }
2673            ConstItemRhsKind::TypeConst { rhs: Some(anon) } => {
2674                hir::ConstItemRhs::TypeConst(self.lower_anon_const_to_const_arg_and_alloc(anon))
2675            }
2676            ConstItemRhsKind::TypeConst { rhs: None } => {
2677                let const_arg = ConstArg {
2678                    hir_id: self.next_id(),
2679                    kind: hir::ConstArgKind::Error(
2680                        self.dcx().span_delayed_bug(DUMMY_SP, "no block"),
2681                    ),
2682                    span: DUMMY_SP,
2683                };
2684                hir::ConstItemRhs::TypeConst(self.arena.alloc(const_arg))
2685            }
2686        }
2687    }
2688
2689    x;#[instrument(level = "debug", skip(self), ret)]
2690    fn can_lower_expr_to_const_arg_direct(
2691        &mut self,
2692        expr: &Expr,
2693    ) -> Result<(), UnrepresentableConstArgError> {
2694        let is_mgca = self.tcx.features().min_generic_const_args();
2695        // Note the only stable case is currently ExprKind::Path. All others have an is_mgca guard.
2696        match &expr.kind {
2697            ExprKind::Call(func, args)
2698                if is_mgca && let ExprKind::Path(_qself, _path) = &func.kind =>
2699            {
2700                for arg in args {
2701                    self.can_lower_expr_to_const_arg_direct(arg)?;
2702                }
2703                Ok(())
2704            }
2705            ExprKind::Tup(exprs) if is_mgca => {
2706                for expr in exprs {
2707                    self.can_lower_expr_to_const_arg_direct(expr)?;
2708                }
2709                Ok(())
2710            }
2711            ExprKind::Path(qself, path)
2712                if is_mgca
2713                    || path.is_potential_trivial_const_arg()
2714                        && matches!(
2715                            self.get_partial_res(expr.id)
2716                                .and_then(|partial_res| partial_res.full_res()),
2717                            Some(Res::Def(DefKind::ConstParam, _))
2718                        ) =>
2719            {
2720                Ok(())
2721            }
2722            ExprKind::Struct(se) if is_mgca => {
2723                for f in &se.fields {
2724                    self.can_lower_expr_to_const_arg_direct(&f.expr)?;
2725                }
2726                Ok(())
2727            }
2728            ExprKind::Array(elements) if is_mgca => {
2729                for element in elements {
2730                    self.can_lower_expr_to_const_arg_direct(element)?;
2731                }
2732                Ok(())
2733            }
2734            ExprKind::Underscore if is_mgca => Ok(()),
2735            ExprKind::Block(block, _)
2736                if is_mgca
2737                    && let [stmt] = block.stmts.as_slice()
2738                    && let StmtKind::Expr(expr) = &stmt.kind =>
2739            {
2740                self.can_lower_expr_to_const_arg_direct(expr)
2741            }
2742            ExprKind::Lit(literal) if is_mgca => Ok(()),
2743            ExprKind::Unary(UnOp::Neg, inner_expr)
2744                if is_mgca && let ExprKind::Lit(_) = &inner_expr.kind =>
2745            {
2746                Ok(())
2747            }
2748            ExprKind::ConstBlock(anon) if is_mgca => Ok(()),
2749            ExprKind::DirectConstArg(expr) if is_mgca => {
2750                // Always report this as able to be represented directly. If it turns out not to be,
2751                // `lower_expr_to_const_arg_direct` will report an error.
2752                Ok(())
2753            }
2754            _ => Err(UnrepresentableConstArgError::new(expr)),
2755        }
2756    }
2757
2758    /// It is not allowed to call this function without checking can_lower_expr_to_const_arg_direct
2759    /// first, as we assume all feature gates/etc. have been checked already.
2760    x;#[instrument(level = "debug", skip(self), ret)]
2761    fn lower_expr_to_const_arg_direct(
2762        &mut self,
2763        expr: &Expr,
2764        id_override: Option<NodeId>,
2765    ) -> hir::ConstArg<'hir> {
2766        debug_assert!(self.can_lower_expr_to_const_arg_direct(expr).is_ok());
2767
2768        let span = self.lower_span(expr.span);
2769        let node_id = id_override.unwrap_or(expr.id);
2770        match &expr.kind {
2771            ExprKind::Call(func, args) if let ExprKind::Path(qself, path) = &func.kind => {
2772                let qpath = self.lower_qpath(
2773                    func.id,
2774                    qself,
2775                    path,
2776                    ParamMode::Explicit,
2777                    AllowReturnTypeNotation::No,
2778                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2779                    None,
2780                );
2781
2782                let lowered_args = self.arena.alloc_from_iter(args.iter().map(|arg| {
2783                    let const_arg = self.lower_expr_to_const_arg_direct(arg, None);
2784                    &*self.arena.alloc(const_arg)
2785                }));
2786
2787                ConstArg {
2788                    hir_id: self.lower_node_id(node_id),
2789                    kind: hir::ConstArgKind::TupleCall(qpath, lowered_args),
2790                    span,
2791                }
2792            }
2793            ExprKind::Tup(exprs) => {
2794                let exprs = self.arena.alloc_from_iter(exprs.iter().map(|expr| {
2795                    let expr = self.lower_expr_to_const_arg_direct(expr, None);
2796                    &*self.arena.alloc(expr)
2797                }));
2798
2799                ConstArg {
2800                    hir_id: self.lower_node_id(node_id),
2801                    kind: hir::ConstArgKind::Tup(exprs),
2802                    span,
2803                }
2804            }
2805            ExprKind::Path(qself, path) => {
2806                let qpath = self.lower_qpath(
2807                    expr.id,
2808                    qself,
2809                    path,
2810                    ParamMode::Explicit,
2811                    AllowReturnTypeNotation::No,
2812                    // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2813                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2814                    None,
2815                );
2816
2817                ConstArg {
2818                    hir_id: self.lower_node_id(node_id),
2819                    kind: hir::ConstArgKind::Path(qpath),
2820                    span,
2821                }
2822            }
2823            ExprKind::Struct(se) => {
2824                let path = self.lower_qpath(
2825                    expr.id,
2826                    &se.qself,
2827                    &se.path,
2828                    // FIXME(mgca): we may want this to be `Optional` instead, but
2829                    // we would also need to make sure that HIR ty lowering errors
2830                    // when these paths wind up in signatures.
2831                    ParamMode::Explicit,
2832                    AllowReturnTypeNotation::No,
2833                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2834                    None,
2835                );
2836
2837                let fields = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
2838                    let hir_id = self.lower_node_id(f.id);
2839                    // FIXME(mgca): This might result in lowering attributes that
2840                    // then go unused as the `Target::ExprField` is not actually
2841                    // corresponding to `Node::ExprField`.
2842                    self.lower_attrs(hir_id, &f.attrs, f.span, Target::ExprField);
2843                    let expr = self.lower_expr_to_const_arg_direct(&f.expr, None);
2844
2845                    &*self.arena.alloc(hir::ConstArgExprField {
2846                        hir_id,
2847                        field: self.lower_ident(f.ident),
2848                        expr: self.arena.alloc(expr),
2849                        span: self.lower_span(f.span),
2850                    })
2851                }));
2852
2853                ConstArg {
2854                    hir_id: self.lower_node_id(node_id),
2855                    kind: hir::ConstArgKind::Struct(path, fields),
2856                    span,
2857                }
2858            }
2859            ExprKind::Array(elements) => {
2860                let lowered_elems = self.arena.alloc_from_iter(elements.iter().map(|element| {
2861                    let const_arg = self.lower_expr_to_const_arg_direct(element, None);
2862                    &*self.arena.alloc(const_arg)
2863                }));
2864                let array_expr = self.arena.alloc(hir::ConstArgArrayExpr {
2865                    span: self.lower_span(expr.span),
2866                    elems: lowered_elems,
2867                });
2868
2869                ConstArg {
2870                    hir_id: self.lower_node_id(node_id),
2871                    kind: hir::ConstArgKind::Array(array_expr),
2872                    span,
2873                }
2874            }
2875            ExprKind::Underscore => ConstArg {
2876                hir_id: self.lower_node_id(node_id),
2877                kind: hir::ConstArgKind::Infer(()),
2878                span,
2879            },
2880            ExprKind::Block(block, _)
2881                if let [stmt] = block.stmts.as_slice()
2882                    && let StmtKind::Expr(expr) = &stmt.kind =>
2883            {
2884                return self.lower_expr_to_const_arg_direct(expr, id_override);
2885            }
2886            ExprKind::Lit(literal) => {
2887                let span = self.lower_span(expr.span);
2888                let literal = self.lower_lit(literal, span);
2889
2890                ConstArg {
2891                    hir_id: self.lower_node_id(node_id),
2892                    kind: hir::ConstArgKind::Literal { lit: literal.node, negated: false },
2893                    span,
2894                }
2895            }
2896            ExprKind::Unary(UnOp::Neg, inner_expr)
2897                if let ExprKind::Lit(literal) = &inner_expr.kind =>
2898            {
2899                let span = self.lower_span(expr.span);
2900                let literal = self.lower_lit(literal, span);
2901
2902                let kind = if !matches!(literal.node, LitKind::Int(..)) {
2903                    let err =
2904                        self.dcx().struct_span_err(expr.span, "negated literal must be an integer");
2905                    hir::ConstArgKind::Error(err.emit())
2906                } else {
2907                    hir::ConstArgKind::Literal { lit: literal.node, negated: true }
2908                };
2909                ConstArg { hir_id: self.lower_node_id(node_id), kind, span }
2910            }
2911            ExprKind::ConstBlock(anon_const) => {
2912                // Do not use lower_anon_const_to_const_arg, as that attempts to represent the body
2913                // directly. Instead, force an anon const.
2914                let def_id = self.local_def_id(anon_const.id);
2915                assert_eq!(DefKind::AnonConst, self.tcx.def_kind(def_id));
2916                let lowered_anon = self.lower_anon_const_to_anon_const(anon_const, span);
2917                ConstArg {
2918                    hir_id: self.lower_node_id(node_id),
2919                    kind: hir::ConstArgKind::Anon(lowered_anon),
2920                    span,
2921                }
2922            }
2923            ExprKind::DirectConstArg(expr) => {
2924                // `can_lower_expr_to_const_arg_direct` always returns success upon encountering a
2925                // ExprKind::DirectConstArg, which effectively forces the expression to be lowered
2926                // as a direct arg. If it actually turns out to not be possible, emit an error
2927                // instead.
2928                match self.can_lower_expr_to_const_arg_direct(expr) {
2929                    Ok(()) => self.lower_expr_to_const_arg_direct(expr, id_override),
2930                    Err(err) => err.emit(self),
2931                }
2932            }
2933            _ => {
2934                span_bug!(
2935                    expr.span,
2936                    "lower_expr_to_const_arg_direct encountered an unlowerable expression, either \
2937                    can_lower_expr_to_const_arg_direct returned Ok() on something it shouldn't \
2938                    have, or you forgot to check can_lower_expr_to_const_arg_direct first"
2939                );
2940            }
2941        }
2942    }
2943
2944    /// See [`hir::ConstArg`] for when to use this function vs
2945    /// [`Self::lower_anon_const_to_anon_const`].
2946    fn lower_anon_const_to_const_arg_and_alloc(
2947        &mut self,
2948        anon: &AnonConst,
2949    ) -> &'hir hir::ConstArg<'hir> {
2950        self.arena.alloc(self.lower_anon_const_to_const_arg(anon, anon.value.span))
2951    }
2952
2953    #[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(2953u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("anon")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("anon");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&anon)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::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 expr =
                if self.tcx.features().min_generic_const_args() {
                    &anon.value
                } else { anon.value.maybe_unwrap_block() };
            if self.can_lower_expr_to_const_arg_direct(expr).is_ok() {
                return self.lower_expr_to_const_arg_direct(expr,
                        Some(anon.id));
            }
            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(anon.value.span),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2954    fn lower_anon_const_to_const_arg(
2955        &mut self,
2956        anon: &AnonConst,
2957        span: Span,
2958    ) -> hir::ConstArg<'hir> {
2959        // Stable only allows one nesting of blocks for directly represented paths. mGCA allows
2960        // arbitrarily many, and are handled inside lower_expr_to_const_arg_direct for consistency.
2961        let expr = if self.tcx.features().min_generic_const_args() {
2962            &anon.value
2963        } else {
2964            anon.value.maybe_unwrap_block()
2965        };
2966
2967        if self.can_lower_expr_to_const_arg_direct(expr).is_ok() {
2968            return self.lower_expr_to_const_arg_direct(expr, Some(anon.id));
2969        }
2970
2971        let lowered_anon = self.lower_anon_const_to_anon_const(anon, anon.value.span);
2972        ConstArg {
2973            hir_id: self.next_id(),
2974            kind: hir::ConstArgKind::Anon(lowered_anon),
2975            span: self.lower_span(anon.value.span),
2976        }
2977    }
2978
2979    /// See [`hir::ConstArg`] for when to use this function vs
2980    /// [`Self::lower_anon_const_to_const_arg`].
2981    fn lower_anon_const_to_anon_const(
2982        &mut self,
2983        c: &AnonConst,
2984        span: Span,
2985    ) -> &'hir hir::AnonConst {
2986        self.arena.alloc(self.with_new_scopes(c.value.span, |this| {
2987            let def_id = this.local_def_id(c.id);
2988            let hir_id = this.lower_node_id(c.id);
2989            hir::AnonConst {
2990                def_id,
2991                hir_id,
2992                body: this.lower_const_body(c.value.span, Some(&c.value)),
2993                span: this.lower_span(span),
2994            }
2995        }))
2996    }
2997
2998    fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2999        match u {
3000            CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
3001            UserProvided => hir::UnsafeSource::UserProvided,
3002        }
3003    }
3004
3005    fn lower_trait_bound_modifiers(
3006        &mut self,
3007        modifiers: TraitBoundModifiers,
3008    ) -> hir::TraitBoundModifiers {
3009        let constness = match modifiers.constness {
3010            BoundConstness::Never => BoundConstness::Never,
3011            BoundConstness::Always(span) => BoundConstness::Always(self.lower_span(span)),
3012            BoundConstness::Maybe(span) => BoundConstness::Maybe(self.lower_span(span)),
3013        };
3014        let polarity = match modifiers.polarity {
3015            BoundPolarity::Positive => BoundPolarity::Positive,
3016            BoundPolarity::Negative(span) => BoundPolarity::Negative(self.lower_span(span)),
3017            BoundPolarity::Maybe(span) => BoundPolarity::Maybe(self.lower_span(span)),
3018        };
3019        hir::TraitBoundModifiers { constness, polarity }
3020    }
3021
3022    // Helper methods for building HIR.
3023
3024    fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
3025        hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
3026    }
3027
3028    fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
3029        self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
3030    }
3031
3032    fn stmt_let_pat(
3033        &mut self,
3034        attrs: Option<&'hir [hir::Attribute]>,
3035        span: Span,
3036        init: Option<&'hir hir::Expr<'hir>>,
3037        pat: &'hir hir::Pat<'hir>,
3038        source: hir::LocalSource,
3039    ) -> hir::Stmt<'hir> {
3040        let hir_id = self.next_id();
3041        if let Some(a) = attrs {
3042            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
3043            self.attrs.insert(hir_id.local_id, a);
3044        }
3045        let local = hir::LetStmt {
3046            super_: None,
3047            hir_id,
3048            init,
3049            pat,
3050            els: None,
3051            source,
3052            span: self.lower_span(span),
3053            ty: None,
3054        };
3055        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
3056    }
3057
3058    fn stmt_super_let_pat(
3059        &mut self,
3060        span: Span,
3061        pat: &'hir hir::Pat<'hir>,
3062        init: Option<&'hir hir::Expr<'hir>>,
3063    ) -> hir::Stmt<'hir> {
3064        let hir_id = self.next_id();
3065        let span = self.lower_span(span);
3066        let local = hir::LetStmt {
3067            super_: Some(span),
3068            hir_id,
3069            init,
3070            pat,
3071            els: None,
3072            source: hir::LocalSource::Normal,
3073            span,
3074            ty: None,
3075        };
3076        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
3077    }
3078
3079    fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
3080        self.block_all(expr.span, &[], Some(expr))
3081    }
3082
3083    fn block_all(
3084        &mut self,
3085        span: Span,
3086        stmts: &'hir [hir::Stmt<'hir>],
3087        expr: Option<&'hir hir::Expr<'hir>>,
3088    ) -> &'hir hir::Block<'hir> {
3089        let blk = hir::Block {
3090            stmts,
3091            expr,
3092            hir_id: self.next_id(),
3093            rules: hir::BlockCheckMode::DefaultBlock,
3094            span: self.lower_span(span),
3095            targeted_by_break: false,
3096        };
3097        self.arena.alloc(blk)
3098    }
3099
3100    fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
3101        let field = self.single_pat_field(span, pat);
3102        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field)
3103    }
3104
3105    fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
3106        let field = self.single_pat_field(span, pat);
3107        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field)
3108    }
3109
3110    fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
3111        let field = self.single_pat_field(span, pat);
3112        self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field)
3113    }
3114
3115    fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
3116        self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[])
3117    }
3118
3119    fn single_pat_field(
3120        &mut self,
3121        span: Span,
3122        pat: &'hir hir::Pat<'hir>,
3123    ) -> &'hir [hir::PatField<'hir>] {
3124        let field = hir::PatField {
3125            hir_id: self.next_id(),
3126            ident: Ident::new(sym::integer(0), self.lower_span(span)),
3127            is_shorthand: false,
3128            pat,
3129            span: self.lower_span(span),
3130        };
3131        self.arena.alloc_from_iter([field])arena_vec![self; field]
3132    }
3133
3134    fn pat_lang_item_variant(
3135        &mut self,
3136        span: Span,
3137        lang_item: hir::LangItem,
3138        fields: &'hir [hir::PatField<'hir>],
3139    ) -> &'hir hir::Pat<'hir> {
3140        let path = self.make_lang_item_qpath(lang_item, self.lower_span(span), None);
3141        self.pat(span, hir::PatKind::Struct(path, fields, None))
3142    }
3143
3144    fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, HirId) {
3145        self.pat_ident_binding_mode(span, ident, hir::BindingMode::NONE)
3146    }
3147
3148    fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, HirId) {
3149        self.pat_ident_binding_mode_mut(span, ident, hir::BindingMode::NONE)
3150    }
3151
3152    fn pat_ident_binding_mode(
3153        &mut self,
3154        span: Span,
3155        ident: Ident,
3156        bm: hir::BindingMode,
3157    ) -> (&'hir hir::Pat<'hir>, HirId) {
3158        let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
3159        (self.arena.alloc(pat), hir_id)
3160    }
3161
3162    fn pat_ident_binding_mode_mut(
3163        &mut self,
3164        span: Span,
3165        ident: Ident,
3166        bm: hir::BindingMode,
3167    ) -> (hir::Pat<'hir>, HirId) {
3168        let hir_id = self.next_id();
3169
3170        (
3171            hir::Pat {
3172                hir_id,
3173                kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
3174                span: self.lower_span(span),
3175                default_binding_modes: true,
3176            },
3177            hir_id,
3178        )
3179    }
3180
3181    fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
3182        self.arena.alloc(hir::Pat {
3183            hir_id: self.next_id(),
3184            kind,
3185            span: self.lower_span(span),
3186            default_binding_modes: true,
3187        })
3188    }
3189
3190    fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
3191        hir::Pat {
3192            hir_id: self.next_id(),
3193            kind,
3194            span: self.lower_span(span),
3195            default_binding_modes: false,
3196        }
3197    }
3198
3199    fn ty_path(&mut self, mut hir_id: HirId, span: Span, qpath: hir::QPath<'hir>) -> hir::Ty<'hir> {
3200        let kind = match qpath {
3201            hir::QPath::Resolved(None, path) => {
3202                // Turn trait object paths into `TyKind::TraitObject` instead.
3203                match path.res {
3204                    Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
3205                        let principal = hir::PolyTraitRef {
3206                            bound_generic_params: &[],
3207                            modifiers: hir::TraitBoundModifiers::NONE,
3208                            trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
3209                            span: self.lower_span(span),
3210                        };
3211
3212                        // The original ID is taken by the `PolyTraitRef`,
3213                        // so the `Ty` itself needs a different one.
3214                        hir_id = self.next_id();
3215                        hir::TyKind::TraitObject(
3216                            self.arena.alloc_from_iter([principal])arena_vec![self; principal],
3217                            TaggedRef::new(self.elided_dyn_bound(span), TraitObjectSyntax::None),
3218                        )
3219                    }
3220                    _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
3221                }
3222            }
3223            _ => hir::TyKind::Path(qpath),
3224        };
3225
3226        hir::Ty { hir_id, kind, span: self.lower_span(span) }
3227    }
3228
3229    /// Invoked to create the lifetime argument(s) for an elided trait object
3230    /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
3231    /// when the bound is written, even if it is written with `'_` like in
3232    /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
3233    fn elided_dyn_bound(&mut self, span: Span) -> &'hir hir::Lifetime {
3234        let r = hir::Lifetime::new(
3235            self.next_id(),
3236            Ident::new(kw::UnderscoreLifetime, self.lower_span(span)),
3237            hir::LifetimeKind::ImplicitObjectLifetimeDefault,
3238            LifetimeSource::Other,
3239            LifetimeSyntax::Implicit,
3240        );
3241        {
    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:3241",
                        "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(3241u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("elided_dyn_bound: r={0:?}",
                                                    r) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("elided_dyn_bound: r={:?}", r);
3242        self.arena.alloc(r)
3243    }
3244}
3245
3246/// Helper struct for the delayed construction of [`hir::GenericArgs`].
3247struct GenericArgsCtor<'hir> {
3248    args: SmallVec<[hir::GenericArg<'hir>; 4]>,
3249    constraints: &'hir [hir::AssocItemConstraint<'hir>],
3250    parenthesized: hir::GenericArgsParentheses,
3251    span: Span,
3252}
3253
3254impl<'hir> GenericArgsCtor<'hir> {
3255    fn is_empty(&self) -> bool {
3256        self.args.is_empty()
3257            && self.constraints.is_empty()
3258            && self.parenthesized == hir::GenericArgsParentheses::No
3259    }
3260
3261    fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
3262        let ga = hir::GenericArgs {
3263            args: this.arena.alloc_from_iter(self.args),
3264            constraints: self.constraints,
3265            parenthesized: self.parenthesized,
3266            span_ext: this.lower_span(self.span),
3267        };
3268        this.arena.alloc(ga)
3269    }
3270}
3271
3272#[derive(#[automatically_derived]
impl ::core::fmt::Debug for UnrepresentableConstArgError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "UnrepresentableConstArgError", "span", &self.span,
            "will_create_def_ids", &&self.will_create_def_ids)
    }
}Debug)]
3273struct UnrepresentableConstArgError {
3274    span: Span,
3275    will_create_def_ids: bool,
3276}
3277
3278impl UnrepresentableConstArgError {
3279    fn new(expr: &Expr) -> Self {
3280        Self {
3281            span: expr.span,
3282            will_create_def_ids: expr::WillCreateDefIdsVisitor.visit_expr(expr).is_break(),
3283        }
3284    }
3285
3286    fn emit<'hir>(self, lowering_context: &mut LoweringContext<'_, 'hir>) -> ConstArg<'hir> {
3287        let msg = "complex const arguments must be placed inside of a `const` block";
3288        let e = if self.will_create_def_ids {
3289            // FIXME(mgca): make this non-fatal once we have a better way to handle
3290            // nested items in const args
3291            // Issue: https://github.com/rust-lang/rust/issues/154539
3292            lowering_context.dcx().struct_span_fatal(self.span, msg).emit()
3293        } else {
3294            lowering_context.dcx().struct_span_err(self.span, msg).emit()
3295        };
3296
3297        ConstArg {
3298            hir_id: lowering_context.next_id(),
3299            kind: hir::ConstArgKind::Error(e),
3300            span: self.span,
3301        }
3302    }
3303}