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,
                                        DirectConstArgContext::MacrolessMinGenericConstArgs) {
                                    Ok(()) => self.lower_expr_to_const_arg_direct(expr, None),
                                    Err(e) => e.emit(self),
                                };
                            let ct = self.arena.alloc(ct);
                            return match ct.try_as_ambig_ct() {
                                    Some(ct) => GenericArg::Const(ct),
                                    None =>
                                        GenericArg::Infer(hir::InferArg {
                                                hir_id: ct.hir_id,
                                                span: ct.span,
                                            }),
                                };
                        }
                        _ => {}
                    }
                    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(
1469                            expr,
1470                            DirectConstArgContext::MacrolessMinGenericConstArgs,
1471                        ) {
1472                            Ok(()) => self.lower_expr_to_const_arg_direct(expr, None),
1473                            Err(e) => e.emit(self),
1474                        };
1475                        let ct = self.arena.alloc(ct);
1476                        // note: this allows direct_const_arg!(_) to be inferred to a type. a little
1477                        // wonky.
1478                        return match ct.try_as_ambig_ct() {
1479                            Some(ct) => GenericArg::Const(ct),
1480                            None => GenericArg::Infer(hir::InferArg {
1481                                hir_id: ct.hir_id,
1482                                span: ct.span,
1483                            }),
1484                        };
1485                    }
1486                    _ => {}
1487                }
1488                GenericArg::Type(self.lower_ty_alloc(ty, itctx).try_as_ambig_ty().unwrap())
1489            }
1490            ast::GenericArg::Const(ct) => {
1491                let ct = self.lower_anon_const_to_const_arg_and_alloc(ct);
1492                match ct.try_as_ambig_ct() {
1493                    Some(ct) => GenericArg::Const(ct),
1494                    None => GenericArg::Infer(hir::InferArg { hir_id: ct.hir_id, span: ct.span }),
1495                }
1496            }
1497        }
1498    }
1499
1500    #[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(1500u32),
                                    ::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))]
1501    fn lower_ty_alloc(&mut self, t: &Ty, itctx: ImplTraitContext) -> &'hir hir::Ty<'hir> {
1502        self.arena.alloc(self.lower_ty(t, itctx))
1503    }
1504
1505    fn lower_path_ty(
1506        &mut self,
1507        t: &Ty,
1508        qself: &Option<Box<QSelf>>,
1509        path: &Path,
1510        param_mode: ParamMode,
1511        itctx: ImplTraitContext,
1512    ) -> hir::Ty<'hir> {
1513        // Check whether we should interpret this as a bare trait object.
1514        // This check mirrors the one in late resolution. We only introduce this special case in
1515        // the rare occurrence we need to lower `Fresh` anonymous lifetimes.
1516        // The other cases when a qpath should be opportunistically made a trait object are handled
1517        // by `ty_path`.
1518        if qself.is_none()
1519            && let Some(partial_res) = self.get_partial_res(t.id)
1520            && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res()
1521        {
1522            let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1523                let bound = this.lower_poly_trait_ref(
1524                    &PolyTraitRef {
1525                        bound_generic_params: ThinVec::new(),
1526                        modifiers: TraitBoundModifiers::NONE,
1527                        trait_ref: TraitRef { path: path.clone(), ref_id: t.id },
1528                        span: t.span,
1529                        parens: ast::Parens::No,
1530                    },
1531                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitObjectTy),
1532                    itctx,
1533                );
1534                let bounds = this.arena.alloc_from_iter([bound]);
1535                let lifetime_bound = this.elided_dyn_bound(t.span);
1536                (bounds, lifetime_bound)
1537            });
1538            let kind = hir::TyKind::TraitObject(
1539                bounds,
1540                TaggedRef::new(lifetime_bound, TraitObjectSyntax::None),
1541            );
1542            return hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.next_id() };
1543        }
1544
1545        let id = self.lower_node_id(t.id);
1546        let qpath = self.lower_qpath(
1547            t.id,
1548            qself,
1549            path,
1550            param_mode,
1551            AllowReturnTypeNotation::Yes,
1552            itctx,
1553            None,
1554        );
1555        self.ty_path(id, t.span, qpath)
1556    }
1557
1558    fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1559        hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1560    }
1561
1562    fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1563        self.ty(span, hir::TyKind::Tup(tys))
1564    }
1565
1566    fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> hir::Ty<'hir> {
1567        let kind = match &t.kind {
1568            TyKind::Infer => hir::TyKind::Infer(()),
1569            TyKind::Err(guar) => hir::TyKind::Err(*guar),
1570            TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty_alloc(ty, itctx)),
1571            TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1572            TyKind::Ref(region, mt) => {
1573                let lifetime = self.lower_ty_direct_lifetime(t, *region);
1574                hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx))
1575            }
1576            TyKind::PinnedRef(region, mt) => {
1577                let lifetime = self.lower_ty_direct_lifetime(t, *region);
1578                let kind = hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx));
1579                let span = self.lower_span(t.span);
1580                let arg = hir::Ty { kind, span, hir_id: self.next_id() };
1581                let args = self.arena.alloc(hir::GenericArgs {
1582                    args: self.arena.alloc([hir::GenericArg::Type(self.arena.alloc(arg))]),
1583                    constraints: &[],
1584                    parenthesized: hir::GenericArgsParentheses::No,
1585                    span_ext: span,
1586                });
1587                let path = self.make_lang_item_qpath(hir::LangItem::Pin, span, Some(args));
1588                hir::TyKind::Path(path)
1589            }
1590            TyKind::FnPtr(f) => {
1591                let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1592                hir::TyKind::FnPtr(self.arena.alloc(hir::FnPtrTy {
1593                    generic_params,
1594                    safety: self.lower_safety(f.safety, hir::Safety::Safe),
1595                    abi: self.lower_extern(f.ext),
1596                    decl: self.lower_fn_decl(&f.decl, t.id, t.span, FnDeclKind::Pointer, None),
1597                    param_idents: self.lower_fn_params_to_idents(&f.decl),
1598                }))
1599            }
1600            TyKind::UnsafeBinder(f) => {
1601                let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1602                hir::TyKind::UnsafeBinder(self.arena.alloc(hir::UnsafeBinderTy {
1603                    generic_params,
1604                    inner_ty: self.lower_ty_alloc(&f.inner_ty, itctx),
1605                }))
1606            }
1607            TyKind::Never => hir::TyKind::Never,
1608            TyKind::Tup(tys) => hir::TyKind::Tup(
1609                self.arena.alloc_from_iter(tys.iter().map(|ty| self.lower_ty(ty, itctx))),
1610            ),
1611            TyKind::Paren(ty) => {
1612                return self.lower_ty(ty, itctx);
1613            }
1614            TyKind::Path(qself, path) => {
1615                return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1616            }
1617            TyKind::ImplicitSelf => {
1618                let hir_id = self.next_id();
1619                let res = self.expect_full_res(t.id);
1620                let res = self.lower_res(res);
1621                hir::TyKind::Path(hir::QPath::Resolved(
1622                    None,
1623                    self.arena.alloc(hir::Path {
1624                        res,
1625                        segments: self.arena.alloc_from_iter([hir::PathSegment::new(Ident::with_dummy_span(kw::SelfUpper),
                hir_id, res)])arena_vec![self; hir::PathSegment::new(
1626                            Ident::with_dummy_span(kw::SelfUpper),
1627                            hir_id,
1628                            res
1629                        )],
1630                        span: self.lower_span(t.span),
1631                    }),
1632                ))
1633            }
1634            TyKind::Array(ty, length) => hir::TyKind::Array(
1635                self.lower_ty_alloc(ty, itctx),
1636                self.lower_array_length_to_const_arg(length),
1637            ),
1638            TyKind::TraitObject(bounds, kind) => {
1639                let mut lifetime_bound = None;
1640                let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1641                    let bounds =
1642                        this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| match bound {
1643                            // We can safely ignore constness here since AST validation
1644                            // takes care of rejecting invalid modifier combinations and
1645                            // const trait bounds in trait object types.
1646                            GenericBound::Trait(ty) => {
1647                                let trait_ref = this.lower_poly_trait_ref(
1648                                    ty,
1649                                    RelaxedBoundPolicy::Forbidden(
1650                                        RelaxedBoundForbiddenReason::TraitObjectTy,
1651                                    ),
1652                                    itctx,
1653                                );
1654                                Some(trait_ref)
1655                            }
1656                            GenericBound::Outlives(lifetime) => {
1657                                if lifetime_bound.is_none() {
1658                                    lifetime_bound = Some(this.lower_lifetime(
1659                                        lifetime,
1660                                        LifetimeSource::Other,
1661                                        lifetime.ident.into(),
1662                                    ));
1663                                }
1664                                None
1665                            }
1666                            // Ignore `use` syntax since that is not valid in objects.
1667                            GenericBound::Use(_, span) => {
1668                                this.dcx()
1669                                    .span_delayed_bug(*span, "use<> not allowed in dyn types");
1670                                None
1671                            }
1672                        }));
1673                    let lifetime_bound =
1674                        lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1675                    (bounds, lifetime_bound)
1676                });
1677                hir::TyKind::TraitObject(bounds, TaggedRef::new(lifetime_bound, *kind))
1678            }
1679            TyKind::ImplTrait(def_node_id, bounds) => {
1680                let span = t.span;
1681                match itctx {
1682                    ImplTraitContext::OpaqueTy { origin } => {
1683                        self.lower_opaque_impl_trait(span, origin, *def_node_id, bounds, itctx)
1684                    }
1685                    ImplTraitContext::Universal => {
1686                        if let Some(span) = bounds.iter().find_map(|bound| match *bound {
1687                            ast::GenericBound::Use(_, span) => Some(span),
1688                            _ => None,
1689                        }) {
1690                            self.tcx.dcx().emit_err(diagnostics::NoPreciseCapturesOnApit { span });
1691                        }
1692
1693                        let def_id = self.local_def_id(*def_node_id);
1694                        let name = self.tcx.item_name(def_id.to_def_id());
1695                        let ident = Ident::new(name, span);
1696                        let (param, bounds, path) = self.lower_universal_param_and_bounds(
1697                            *def_node_id,
1698                            span,
1699                            ident,
1700                            bounds,
1701                        );
1702                        self.impl_trait_defs.push(param);
1703                        if let Some(bounds) = bounds {
1704                            self.impl_trait_bounds.push(bounds);
1705                        }
1706                        path
1707                    }
1708                    ImplTraitContext::InBinding => {
1709                        hir::TyKind::TraitAscription(self.lower_param_bounds(
1710                            bounds,
1711                            RelaxedBoundPolicy::Allowed(&mut Default::default()),
1712                            itctx,
1713                        ))
1714                    }
1715                    ImplTraitContext::FeatureGated(position, feature) => {
1716                        let guar = self
1717                            .tcx
1718                            .sess
1719                            .create_feature_err(
1720                                MisplacedImplTrait {
1721                                    span: t.span,
1722                                    position: DiagArgFromDisplay(&position),
1723                                },
1724                                feature,
1725                            )
1726                            .emit();
1727                        hir::TyKind::Err(guar)
1728                    }
1729                    ImplTraitContext::Disallowed(position) => {
1730                        let guar = self.dcx().emit_err(MisplacedImplTrait {
1731                            span: t.span,
1732                            position: DiagArgFromDisplay(&position),
1733                        });
1734                        hir::TyKind::Err(guar)
1735                    }
1736                }
1737            }
1738            TyKind::Pat(ty, pat) => {
1739                hir::TyKind::Pat(self.lower_ty_alloc(ty, itctx), self.lower_ty_pat(pat, ty.span))
1740            }
1741            TyKind::FieldOf(ty, variant, field) => hir::TyKind::FieldOf(
1742                self.lower_ty_alloc(ty, itctx),
1743                self.arena.alloc(hir::TyFieldPath {
1744                    variant: variant.map(|variant| self.lower_ident(variant)),
1745                    field: self.lower_ident(*field),
1746                }),
1747            ),
1748            TyKind::MacCall(_) => {
1749                ::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")
1750            }
1751            TyKind::CVarArgs => {
1752                let guar = self.dcx().span_delayed_bug(
1753                    t.span,
1754                    "`TyKind::CVarArgs` should have been handled elsewhere",
1755                );
1756                hir::TyKind::Err(guar)
1757            }
1758            TyKind::View(ty, fields) => {
1759                let ty = self.lower_ty_alloc(ty, itctx);
1760                let fields = self.arena.alloc_slice(fields);
1761                hir::TyKind::View(ty, fields)
1762            }
1763            TyKind::DirectConstArg(expr) => {
1764                let e = self.emit_bad_direct_const_arg(t.span, expr, "type");
1765                hir::TyKind::Err(e)
1766            }
1767            TyKind::Dummy => {
    ::core::panicking::panic_fmt(format_args!("`TyKind::Dummy` should never be lowered"));
}panic!("`TyKind::Dummy` should never be lowered"),
1768        };
1769
1770        hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1771    }
1772
1773    pub(crate) fn emit_bad_direct_const_arg(
1774        &mut self,
1775        span: Span,
1776        expr: &Expr,
1777        expected: &'static str,
1778    ) -> ErrorGuaranteed {
1779        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");
1780        if expr::WillCreateDefIdsVisitor.visit_expr(expr).is_break() {
1781            // FIXME(mgca): make this non-fatal once we have a better way to handle
1782            // nested items in invalid `direct_const_arg!()` arguments.
1783            self.dcx().struct_span_fatal(span, msg).emit()
1784        } else {
1785            self.dcx().struct_span_err(span, msg).emit()
1786        }
1787    }
1788
1789    fn lower_ty_direct_lifetime(
1790        &mut self,
1791        t: &Ty,
1792        region: Option<Lifetime>,
1793    ) -> &'hir hir::Lifetime {
1794        let (region, syntax) = match region {
1795            Some(region) => (region, region.ident.into()),
1796
1797            None => {
1798                let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1799                    self.owner.get_lifetime_res(t.id)
1800                {
1801                    {
    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);
1802                    start
1803                } else {
1804                    self.next_node_id()
1805                };
1806                let span = self.tcx.sess.source_map().start_point(t.span).shrink_to_hi();
1807                let region = Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id };
1808                (region, LifetimeSyntax::Implicit)
1809            }
1810        };
1811        self.lower_lifetime(&region, LifetimeSource::Reference, syntax)
1812    }
1813
1814    /// Lowers a `ReturnPositionOpaqueTy` (`-> impl Trait`) or a `TypeAliasesOpaqueTy` (`type F =
1815    /// impl Trait`): this creates the associated Opaque Type (TAIT) definition and then returns a
1816    /// HIR type that references the TAIT.
1817    ///
1818    /// Given a function definition like:
1819    ///
1820    /// ```rust
1821    /// use std::fmt::Debug;
1822    ///
1823    /// fn test<'a, T: Debug>(x: &'a T) -> impl Debug + 'a {
1824    ///     x
1825    /// }
1826    /// ```
1827    ///
1828    /// we will create a TAIT definition in the HIR like
1829    ///
1830    /// ```rust,ignore (pseudo-Rust)
1831    /// type TestReturn<'a, T, 'x> = impl Debug + 'x
1832    /// ```
1833    ///
1834    /// and return a type like `TestReturn<'static, T, 'a>`, so that the function looks like:
1835    ///
1836    /// ```rust,ignore (pseudo-Rust)
1837    /// fn test<'a, T: Debug>(x: &'a T) -> TestReturn<'static, T, 'a>
1838    /// ```
1839    ///
1840    /// Note the subtlety around type parameters! The new TAIT, `TestReturn`, inherits all the
1841    /// type parameters from the function `test` (this is implemented in the query layer, they aren't
1842    /// added explicitly in the HIR). But this includes all the lifetimes, and we only want to
1843    /// capture the lifetimes that are referenced in the bounds. Therefore, we add *extra* lifetime parameters
1844    /// for the lifetimes that get captured (`'x`, in our example above) and reference those.
1845    x;#[instrument(level = "debug", skip(self), ret)]
1846    fn lower_opaque_impl_trait(
1847        &mut self,
1848        span: Span,
1849        origin: hir::OpaqueTyOrigin<LocalDefId>,
1850        opaque_ty_node_id: NodeId,
1851        bounds: &GenericBounds,
1852        itctx: ImplTraitContext,
1853    ) -> hir::TyKind<'hir> {
1854        // Make sure we know that some funky desugaring has been going on here.
1855        // This is a first: there is code in other places like for loop
1856        // desugaring that explicitly states that we don't want to track that.
1857        // Not tracking it makes lints in rustc and clippy very fragile, as
1858        // frequently opened issues show.
1859        let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1860
1861        self.lower_opaque_inner(opaque_ty_node_id, origin, opaque_ty_span, |this| {
1862            this.lower_param_bounds(
1863                bounds,
1864                RelaxedBoundPolicy::Allowed(&mut Default::default()),
1865                itctx,
1866            )
1867        })
1868    }
1869
1870    fn lower_opaque_inner(
1871        &mut self,
1872        opaque_ty_node_id: NodeId,
1873        origin: hir::OpaqueTyOrigin<LocalDefId>,
1874        opaque_ty_span: Span,
1875        lower_item_bounds: impl FnOnce(&mut Self) -> &'hir [hir::GenericBound<'hir>],
1876    ) -> hir::TyKind<'hir> {
1877        let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id);
1878        let opaque_ty_hir_id = self.lower_node_id(opaque_ty_node_id);
1879        {
    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:1879",
                        "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(1879u32),
                        ::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);
1880
1881        let bounds = lower_item_bounds(self);
1882        let opaque_ty_def = hir::OpaqueTy {
1883            hir_id: opaque_ty_hir_id,
1884            def_id: opaque_ty_def_id,
1885            bounds,
1886            origin,
1887            span: self.lower_span(opaque_ty_span),
1888        };
1889        let opaque_ty_def = self.arena.alloc(opaque_ty_def);
1890
1891        hir::TyKind::OpaqueDef(opaque_ty_def)
1892    }
1893
1894    fn lower_precise_capturing_args(
1895        &mut self,
1896        precise_capturing_args: &[PreciseCapturingArg],
1897    ) -> &'hir [hir::PreciseCapturingArg<'hir>] {
1898        self.arena.alloc_from_iter(precise_capturing_args.iter().map(|arg| match arg {
1899            PreciseCapturingArg::Lifetime(lt) => hir::PreciseCapturingArg::Lifetime(
1900                self.lower_lifetime(lt, LifetimeSource::PreciseCapturing, lt.ident.into()),
1901            ),
1902            PreciseCapturingArg::Arg(path, id) => {
1903                let [segment] = path.segments.as_slice() else {
1904                    ::core::panicking::panic("explicit panic");panic!();
1905                };
1906                let res = self.get_partial_res(*id).map_or(Res::Err, |partial_res| {
1907                    partial_res.full_res().expect("no partial res expected for precise capture arg")
1908                });
1909                hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
1910                    hir_id: self.lower_node_id(*id),
1911                    ident: self.lower_ident(segment.ident),
1912                    res: self.lower_res(res),
1913                })
1914            }
1915        }))
1916    }
1917
1918    fn lower_fn_params_to_idents(&mut self, decl: &FnDecl) -> &'hir [Option<Ident>] {
1919        self.arena.alloc_from_iter(decl.inputs.iter().map(|param| match param.pat.kind {
1920            PatKind::Missing => None,
1921            PatKind::Ident(_, ident, _) => Some(self.lower_ident(ident)),
1922            PatKind::Wild => Some(Ident::new(kw::Underscore, self.lower_span(param.pat.span))),
1923            _ => {
1924                self.dcx().span_delayed_bug(
1925                    param.pat.span,
1926                    "non-missing/ident/wild param pat must trigger an error",
1927                );
1928                None
1929            }
1930        }))
1931    }
1932
1933    /// Lowers a function declaration.
1934    ///
1935    /// `decl`: the unlowered (AST) function declaration.
1936    ///
1937    /// `fn_node_id`: `impl Trait` arguments are lowered into generic parameters on the given
1938    /// `NodeId`.
1939    ///
1940    /// `transform_return_type`: if `Some`, applies some conversion to the return type, such as is
1941    /// needed for `async fn` and `gen fn`. See [`CoroutineKind`] for more details.
1942    #[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(1942u32),
                                    ::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))]
1943    fn lower_fn_decl(
1944        &mut self,
1945        decl: &FnDecl,
1946        fn_node_id: NodeId,
1947        fn_span: Span,
1948        kind: FnDeclKind,
1949        coro: Option<CoroutineKind>,
1950    ) -> &'hir hir::FnDecl<'hir> {
1951        let c_variadic = decl.c_variadic();
1952        let mut splatted = decl.splatted();
1953
1954        // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1955        // as they are not explicit in HIR/Ty function signatures.
1956        // (instead, the `c_variadic` flag is set to `true`)
1957        let mut inputs = &decl.inputs[..];
1958        if decl.c_variadic() {
1959            // Splat + variadic errors in AST validation, so just ignore one of them here.
1960            splatted = None;
1961            inputs = &inputs[..inputs.len() - 1];
1962        }
1963        let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1964            let itctx = match kind {
1965                FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait => {
1966                    ImplTraitContext::Universal
1967                }
1968                FnDeclKind::ExternFn => {
1969                    ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnParam)
1970                }
1971                FnDeclKind::Closure => {
1972                    ImplTraitContext::Disallowed(ImplTraitPosition::ClosureParam)
1973                }
1974                FnDeclKind::Pointer => {
1975                    ImplTraitContext::Disallowed(ImplTraitPosition::PointerParam)
1976                }
1977            };
1978            self.lower_ty(&param.ty, itctx)
1979        }));
1980
1981        let output = match coro {
1982            Some(coro) => {
1983                let fn_def_id = self.owner.def_id;
1984                self.lower_coroutine_fn_ret_ty(&decl.output, fn_def_id, coro, kind)
1985            }
1986            None => match &decl.output {
1987                FnRetTy::Ty(ty) => {
1988                    let itctx = match kind {
1989                        FnDeclKind::Fn | FnDeclKind::Inherent => ImplTraitContext::OpaqueTy {
1990                            origin: hir::OpaqueTyOrigin::FnReturn {
1991                                parent: self.owner.def_id,
1992                                in_trait_or_impl: None,
1993                            },
1994                        },
1995                        FnDeclKind::Trait => ImplTraitContext::OpaqueTy {
1996                            origin: hir::OpaqueTyOrigin::FnReturn {
1997                                parent: self.owner.def_id,
1998                                in_trait_or_impl: Some(hir::RpitContext::Trait),
1999                            },
2000                        },
2001                        FnDeclKind::Impl => ImplTraitContext::OpaqueTy {
2002                            origin: hir::OpaqueTyOrigin::FnReturn {
2003                                parent: self.owner.def_id,
2004                                in_trait_or_impl: Some(hir::RpitContext::TraitImpl),
2005                            },
2006                        },
2007                        FnDeclKind::ExternFn => {
2008                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnReturn)
2009                        }
2010                        FnDeclKind::Closure => {
2011                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureReturn)
2012                        }
2013                        FnDeclKind::Pointer => {
2014                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerReturn)
2015                        }
2016                    };
2017                    hir::FnRetTy::Return(self.lower_ty_alloc(ty, itctx))
2018                }
2019                FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(*span)),
2020            },
2021        };
2022
2023        let fn_decl_kind = hir::FnDeclFlags::default()
2024            .set_implicit_self(decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
2025                let is_mutable_pat = matches!(
2026                    arg.pat.kind,
2027                    PatKind::Ident(hir::BindingMode(_, Mutability::Mut), ..)
2028                );
2029
2030                match &arg.ty.kind {
2031                    TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2032                    TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2033                    // Given we are only considering `ImplicitSelf` types, we needn't consider
2034                    // the case where we have a mutable pattern to a reference as that would
2035                    // no longer be an `ImplicitSelf`.
2036                    TyKind::Ref(_, mt) | TyKind::PinnedRef(_, mt)
2037                        if mt.ty.kind.is_implicit_self() =>
2038                    {
2039                        match mt.mutbl {
2040                            hir::Mutability::Not => hir::ImplicitSelfKind::RefImm,
2041                            hir::Mutability::Mut => hir::ImplicitSelfKind::RefMut,
2042                        }
2043                    }
2044                    _ => hir::ImplicitSelfKind::None,
2045                }
2046            }))
2047            .set_lifetime_elision_allowed(
2048                self.owner.id == fn_node_id && self.owner.lifetime_elision_allowed,
2049            )
2050            .set_c_variadic(c_variadic)
2051            .set_splatted(splatted, inputs.len())
2052            .unwrap();
2053
2054        self.arena.alloc(hir::FnDecl { inputs, output, fn_decl_kind })
2055    }
2056
2057    // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
2058    // combined with the following definition of `OpaqueTy`:
2059    //
2060    //     type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
2061    //
2062    // `output`: unlowered output type (`T` in `-> T`)
2063    // `fn_node_id`: `NodeId` of the parent function (used to create child impl trait definition)
2064    // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
2065    #[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(2065u32),
                                    ::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))]
2066    fn lower_coroutine_fn_ret_ty(
2067        &mut self,
2068        output: &FnRetTy,
2069        fn_def_id: LocalDefId,
2070        coro: CoroutineKind,
2071        fn_kind: FnDeclKind,
2072    ) -> hir::FnRetTy<'hir> {
2073        let span = self.lower_span(output.span());
2074
2075        let (opaque_ty_node_id, allowed_features) = match coro {
2076            CoroutineKind::Async { return_impl_trait_id, .. } => (return_impl_trait_id, None),
2077            CoroutineKind::Gen { return_impl_trait_id, .. } => (return_impl_trait_id, None),
2078            CoroutineKind::AsyncGen { return_impl_trait_id, .. } => {
2079                (return_impl_trait_id, Some(Arc::clone(&self.allow_async_iterator)))
2080            }
2081        };
2082
2083        let opaque_ty_span =
2084            self.mark_span_with_reason(DesugaringKind::Async, span, allowed_features);
2085
2086        let in_trait_or_impl = match fn_kind {
2087            FnDeclKind::Trait => Some(hir::RpitContext::Trait),
2088            FnDeclKind::Impl => Some(hir::RpitContext::TraitImpl),
2089            FnDeclKind::Fn | FnDeclKind::Inherent => None,
2090            FnDeclKind::ExternFn | FnDeclKind::Closure | FnDeclKind::Pointer => unreachable!(),
2091        };
2092
2093        let opaque_ty_ref = self.lower_opaque_inner(
2094            opaque_ty_node_id,
2095            hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, in_trait_or_impl },
2096            opaque_ty_span,
2097            |this| {
2098                let bound = this.lower_coroutine_fn_output_type_to_bound(
2099                    output,
2100                    coro,
2101                    opaque_ty_span,
2102                    ImplTraitContext::OpaqueTy {
2103                        origin: hir::OpaqueTyOrigin::FnReturn {
2104                            parent: fn_def_id,
2105                            in_trait_or_impl,
2106                        },
2107                    },
2108                );
2109                arena_vec![this; bound]
2110            },
2111        );
2112
2113        let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2114        hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
2115    }
2116
2117    /// Transforms `-> T` into `Future<Output = T>`.
2118    fn lower_coroutine_fn_output_type_to_bound(
2119        &mut self,
2120        output: &FnRetTy,
2121        coro: CoroutineKind,
2122        opaque_ty_span: Span,
2123        itctx: ImplTraitContext,
2124    ) -> hir::GenericBound<'hir> {
2125        // Compute the `T` in `Future<Output = T>` from the return type.
2126        let output_ty = match output {
2127            FnRetTy::Ty(ty) => {
2128                // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
2129                // `impl Future` opaque type that `async fn` implicitly
2130                // generates.
2131                self.lower_ty_alloc(ty, itctx)
2132            }
2133            FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
2134        };
2135
2136        // "<$assoc_ty_name = T>"
2137        let (assoc_ty_name, trait_lang_item) = match coro {
2138            CoroutineKind::Async { .. } => (sym::Output, hir::LangItem::Future),
2139            CoroutineKind::Gen { .. } => (sym::Item, hir::LangItem::Iterator),
2140            CoroutineKind::AsyncGen { .. } => (sym::Item, hir::LangItem::AsyncIterator),
2141        };
2142
2143        let bound_args = self.arena.alloc(hir::GenericArgs {
2144            args: &[],
2145            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)],
2146            parenthesized: hir::GenericArgsParentheses::No,
2147            span_ext: DUMMY_SP,
2148        });
2149
2150        hir::GenericBound::Trait(hir::PolyTraitRef {
2151            bound_generic_params: &[],
2152            modifiers: hir::TraitBoundModifiers::NONE,
2153            trait_ref: hir::TraitRef {
2154                path: self.make_lang_item_path(trait_lang_item, opaque_ty_span, Some(bound_args)),
2155                hir_ref_id: self.next_id(),
2156            },
2157            span: opaque_ty_span,
2158        })
2159    }
2160
2161    #[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(2161u32),
                                    ::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))]
2162    fn lower_param_bound(
2163        &mut self,
2164        tpb: &GenericBound,
2165        rbp: RelaxedBoundPolicy<'_>,
2166        itctx: ImplTraitContext,
2167    ) -> hir::GenericBound<'hir> {
2168        match tpb {
2169            GenericBound::Trait(p) => {
2170                hir::GenericBound::Trait(self.lower_poly_trait_ref(p, rbp, itctx))
2171            }
2172            GenericBound::Outlives(lifetime) => hir::GenericBound::Outlives(self.lower_lifetime(
2173                lifetime,
2174                LifetimeSource::OutlivesBound,
2175                lifetime.ident.into(),
2176            )),
2177            GenericBound::Use(args, span) => hir::GenericBound::Use(
2178                self.lower_precise_capturing_args(args),
2179                self.lower_span(*span),
2180            ),
2181        }
2182    }
2183
2184    fn lower_lifetime(
2185        &mut self,
2186        l: &Lifetime,
2187        source: LifetimeSource,
2188        syntax: LifetimeSyntax,
2189    ) -> &'hir hir::Lifetime {
2190        self.new_named_lifetime(l.id, l.id, l.ident, source, syntax)
2191    }
2192
2193    fn lower_lifetime_hidden_in_path(
2194        &mut self,
2195        id: NodeId,
2196        span: Span,
2197        angle_brackets: AngleBrackets,
2198    ) -> &'hir hir::Lifetime {
2199        self.new_named_lifetime(
2200            id,
2201            id,
2202            Ident::new(kw::UnderscoreLifetime, span),
2203            LifetimeSource::Path { angle_brackets },
2204            LifetimeSyntax::Implicit,
2205        )
2206    }
2207
2208    #[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(2208u32),
                                    ::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:2242",
                                    "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(2242u32),
                                    ::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))]
2209    fn new_named_lifetime(
2210        &mut self,
2211        id: NodeId,
2212        new_id: NodeId,
2213        ident: Ident,
2214        source: LifetimeSource,
2215        syntax: LifetimeSyntax,
2216    ) -> &'hir hir::Lifetime {
2217        let res = if let Some(res) = self.owner.get_lifetime_res(id) {
2218            match res {
2219                LifetimeRes::Param { param, .. } => hir::LifetimeKind::Param(param),
2220                LifetimeRes::Fresh { param, .. } => {
2221                    assert_eq!(ident.name, kw::UnderscoreLifetime);
2222                    let param = self.local_def_id(param);
2223                    hir::LifetimeKind::Param(param)
2224                }
2225                LifetimeRes::Infer => {
2226                    assert_eq!(ident.name, kw::UnderscoreLifetime);
2227                    hir::LifetimeKind::Infer
2228                }
2229                LifetimeRes::Static { .. } => {
2230                    assert!(matches!(ident.name, kw::StaticLifetime | kw::UnderscoreLifetime));
2231                    hir::LifetimeKind::Static
2232                }
2233                LifetimeRes::Error(guar) => hir::LifetimeKind::Error(guar),
2234                LifetimeRes::ElidedAnchor { .. } => {
2235                    panic!("Unexpected `ElidedAnchar` {:?} at {:?}", ident, ident.span);
2236                }
2237            }
2238        } else {
2239            hir::LifetimeKind::Error(self.dcx().span_delayed_bug(ident.span, "unresolved lifetime"))
2240        };
2241
2242        debug!(?res);
2243        self.arena.alloc(hir::Lifetime::new(
2244            self.lower_node_id(new_id),
2245            self.lower_ident(ident),
2246            res,
2247            source,
2248            syntax,
2249        ))
2250    }
2251
2252    fn lower_generic_params_mut(
2253        &mut self,
2254        params: &[GenericParam],
2255        source: hir::GenericParamSource,
2256    ) -> impl Iterator<Item = hir::GenericParam<'hir>> {
2257        params.iter().map(move |param| self.lower_generic_param(param, source))
2258    }
2259
2260    fn lower_generic_params(
2261        &mut self,
2262        params: &[GenericParam],
2263        source: hir::GenericParamSource,
2264    ) -> &'hir [hir::GenericParam<'hir>] {
2265        self.arena.alloc_from_iter(self.lower_generic_params_mut(params, source))
2266    }
2267
2268    #[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(2268u32),
                                    ::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))]
2269    fn lower_generic_param(
2270        &mut self,
2271        param: &GenericParam,
2272        source: hir::GenericParamSource,
2273    ) -> hir::GenericParam<'hir> {
2274        let (name, kind) = self.lower_generic_param_kind(param, source);
2275
2276        let hir_id = self.lower_node_id(param.id);
2277        let param_attrs = &param.attrs;
2278        let param_span = param.span();
2279        let param = hir::GenericParam {
2280            hir_id,
2281            def_id: self.local_def_id(param.id),
2282            name,
2283            span: self.lower_span(param.span()),
2284            pure_wrt_drop: attr::contains_name(&param.attrs, sym::may_dangle),
2285            kind,
2286            colon_span: param.colon_span.map(|s| self.lower_span(s)),
2287            source,
2288        };
2289        self.lower_attrs(hir_id, param_attrs, param_span, Target::from_generic_param(&param));
2290        param
2291    }
2292
2293    fn lower_generic_param_kind(
2294        &mut self,
2295        param: &GenericParam,
2296        source: hir::GenericParamSource,
2297    ) -> (hir::ParamName, hir::GenericParamKind<'hir>) {
2298        match &param.kind {
2299            GenericParamKind::Lifetime => {
2300                // AST resolution emitted an error on those parameters, so we lower them using
2301                // `ParamName::Error`.
2302                let ident = self.lower_ident(param.ident);
2303                let param_name =
2304                    if let Some(LifetimeRes::Error(..)) = self.owner.get_lifetime_res(param.id) {
2305                        ParamName::Error(ident)
2306                    } else {
2307                        ParamName::Plain(ident)
2308                    };
2309                let kind =
2310                    hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2311
2312                (param_name, kind)
2313            }
2314            GenericParamKind::Type { default, .. } => {
2315                // Not only do we deny type param defaults in binders but we also map them to `None`
2316                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2317                let default = default
2318                    .as_ref()
2319                    .filter(|_| match source {
2320                        hir::GenericParamSource::Generics => true,
2321                        hir::GenericParamSource::Binder => {
2322                            self.dcx().emit_err(diagnostics::GenericParamDefaultInBinder {
2323                                span: param.span(),
2324                            });
2325
2326                            false
2327                        }
2328                    })
2329                    .map(|def| {
2330                        self.lower_ty_alloc(
2331                            def,
2332                            ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2333                        )
2334                    });
2335
2336                let kind = hir::GenericParamKind::Type { default, synthetic: false };
2337
2338                (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2339            }
2340            GenericParamKind::Const { ty, span: _, default } => {
2341                let ty = self.lower_ty_alloc(
2342                    ty,
2343                    ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2344                );
2345
2346                // Not only do we deny const param defaults in binders but we also map them to `None`
2347                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2348                let default = default
2349                    .as_ref()
2350                    .filter(|anon_const| match source {
2351                        hir::GenericParamSource::Generics => true,
2352                        hir::GenericParamSource::Binder => {
2353                            let err =
2354                                diagnostics::GenericParamDefaultInBinder { span: param.span() };
2355                            if expr::WillCreateDefIdsVisitor
2356                                .visit_expr(&anon_const.value)
2357                                .is_break()
2358                            {
2359                                // FIXME(mgca): make this non-fatal once we have a better way
2360                                // to handle nested items in anno const from binder
2361                                // Issue: https://github.com/rust-lang/rust/issues/123629
2362                                self.dcx().emit_fatal(err)
2363                            } else {
2364                                self.dcx().emit_err(err);
2365                                false
2366                            }
2367                        }
2368                    })
2369                    .map(|def| self.lower_anon_const_to_const_arg_and_alloc(def));
2370
2371                (
2372                    hir::ParamName::Plain(self.lower_ident(param.ident)),
2373                    hir::GenericParamKind::Const { ty, default },
2374                )
2375            }
2376        }
2377    }
2378
2379    fn lower_trait_ref(
2380        &mut self,
2381        modifiers: ast::TraitBoundModifiers,
2382        p: &TraitRef,
2383        itctx: ImplTraitContext,
2384    ) -> hir::TraitRef<'hir> {
2385        let path = match self.lower_qpath(
2386            p.ref_id,
2387            &None,
2388            &p.path,
2389            ParamMode::Explicit,
2390            AllowReturnTypeNotation::No,
2391            itctx,
2392            Some(modifiers),
2393        ) {
2394            hir::QPath::Resolved(None, path) => path,
2395            qpath => {
    ::core::panicking::panic_fmt(format_args!("lower_trait_ref: unexpected QPath `{0:?}`",
            qpath));
}panic!("lower_trait_ref: unexpected QPath `{qpath:?}`"),
2396        };
2397        hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2398    }
2399
2400    #[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(2400u32),
                                    ::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))]
2401    fn lower_poly_trait_ref(
2402        &mut self,
2403        PolyTraitRef { bound_generic_params, modifiers, trait_ref, span, parens: _ }: &PolyTraitRef,
2404        rbp: RelaxedBoundPolicy<'_>,
2405        itctx: ImplTraitContext,
2406    ) -> hir::PolyTraitRef<'hir> {
2407        let bound_generic_params =
2408            self.lower_lifetime_binder(trait_ref.ref_id, bound_generic_params);
2409        let trait_ref = self.lower_trait_ref(*modifiers, trait_ref, itctx);
2410        let modifiers = self.lower_trait_bound_modifiers(*modifiers);
2411
2412        if let ast::BoundPolarity::Maybe(_) = modifiers.polarity {
2413            self.validate_relaxed_bound(trait_ref, *span, rbp);
2414        }
2415
2416        hir::PolyTraitRef {
2417            bound_generic_params,
2418            modifiers,
2419            trait_ref,
2420            span: self.lower_span(*span),
2421        }
2422    }
2423
2424    fn validate_relaxed_bound(
2425        &self,
2426        trait_ref: hir::TraitRef<'_>,
2427        span: Span,
2428        rbp: RelaxedBoundPolicy<'_>,
2429    ) {
2430        // Even though feature `more_maybe_bounds` enables the user to relax all default bounds
2431        // other than `Sized` in a lot more positions (thereby bypassing the given policy), we don't
2432        // want to advertise it to the user (via a feature gate error) since it's super internal.
2433        //
2434        // FIXME(more_maybe_bounds): Moreover, if we actually were to add proper default traits
2435        // (like a hypothetical `Move` or `Leak`) we would want to validate the location according
2436        // to default trait elaboration in HIR ty lowering (which depends on the specific trait in
2437        // question: E.g., `?Sized` & `?Move` most likely won't be allowed in all the same places).
2438
2439        match rbp {
2440            RelaxedBoundPolicy::Allowed(dedup_map) => {
2441                // `trait_def_id` only returns `None` for errors during resolution.
2442                let Some(trait_def_id) = trait_ref.trait_def_id() else { return };
2443                let tcx = self.tcx;
2444                let err = |s| {
2445                    let name = tcx.item_name(trait_def_id);
2446                    tcx.dcx()
2447                        .struct_span_err(
2448                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [span, s]))vec![span, s],
2449                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("duplicate relaxed `{0}` bounds",
                name))
    })format!("duplicate relaxed `{name}` bounds"),
2450                        )
2451                        .with_code(E0203)
2452                        .emit();
2453                };
2454                dedup_map.entry(trait_def_id).and_modify(|&mut s| err(s)).or_insert(span);
2455                return;
2456            }
2457            RelaxedBoundPolicy::Forbidden(reason) => {
2458                let gate = |context, subject| {
2459                    let extended = self.tcx.features().more_maybe_bounds();
2460                    let is_sized = trait_ref
2461                        .trait_def_id()
2462                        .is_some_and(|def_id| self.tcx.is_lang_item(def_id, hir::LangItem::Sized));
2463
2464                    if extended && !is_sized {
2465                        return;
2466                    }
2467
2468                    let prefix = if extended { "`Sized` " } else { "" };
2469                    let mut diag = self.dcx().struct_span_err(
2470                        span,
2471                        ::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}"),
2472                    );
2473                    if is_sized {
2474                        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!(
2475                            "{subject} are not implicitly bounded by `Sized`, \
2476                             so there is nothing to relax"
2477                        ));
2478                    }
2479                    diag.emit();
2480                };
2481
2482                match reason {
2483                    RelaxedBoundForbiddenReason::TraitObjectTy => {
2484                        gate("trait object types", "trait object types");
2485                        return;
2486                    }
2487                    RelaxedBoundForbiddenReason::SuperTrait => {
2488                        gate("supertrait bounds", "traits");
2489                        return;
2490                    }
2491                    RelaxedBoundForbiddenReason::TraitAlias => {
2492                        gate("trait alias bounds", "trait aliases");
2493                        return;
2494                    }
2495                    RelaxedBoundForbiddenReason::AssocTyBounds
2496                    | RelaxedBoundForbiddenReason::WhereBound => {}
2497                };
2498            }
2499        }
2500
2501        self.dcx()
2502            .struct_span_err(span, "this relaxed bound is not permitted here")
2503            .with_note(
2504                "in this context, relaxed bounds are only allowed on \
2505                 type parameters defined on the closest item",
2506            )
2507            .emit();
2508    }
2509
2510    fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy<'hir> {
2511        hir::MutTy { ty: self.lower_ty_alloc(&mt.ty, itctx), mutbl: mt.mutbl }
2512    }
2513
2514    x;#[instrument(level = "debug", skip(self), ret)]
2515    fn lower_param_bounds(
2516        &mut self,
2517        bounds: &[GenericBound],
2518        rbp: RelaxedBoundPolicy<'_>,
2519        itctx: ImplTraitContext,
2520    ) -> hir::GenericBounds<'hir> {
2521        self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, rbp, itctx))
2522    }
2523
2524    fn lower_param_bounds_mut(
2525        &mut self,
2526        bounds: &[GenericBound],
2527        mut rbp: RelaxedBoundPolicy<'_>,
2528        itctx: ImplTraitContext,
2529    ) -> impl Iterator<Item = hir::GenericBound<'hir>> {
2530        bounds.iter().map(move |bound| self.lower_param_bound(bound, rbp.reborrow(), itctx))
2531    }
2532
2533    x;#[instrument(level = "debug", skip(self), ret)]
2534    fn lower_universal_param_and_bounds(
2535        &mut self,
2536        node_id: NodeId,
2537        span: Span,
2538        ident: Ident,
2539        bounds: &[GenericBound],
2540    ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2541        // Add a definition for the in-band `Param`.
2542        let def_id = self.local_def_id(node_id);
2543        let span = self.lower_span(span);
2544
2545        // Set the name to `impl Bound1 + Bound2`.
2546        let param = hir::GenericParam {
2547            hir_id: self.lower_node_id(node_id),
2548            def_id,
2549            name: ParamName::Plain(self.lower_ident(ident)),
2550            pure_wrt_drop: false,
2551            span,
2552            kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2553            colon_span: None,
2554            source: hir::GenericParamSource::Generics,
2555        };
2556
2557        let preds = self.lower_generic_bound_predicate(
2558            ident,
2559            node_id,
2560            &GenericParamKind::Type { default: None },
2561            bounds,
2562            /* colon_span */ None,
2563            span,
2564            RelaxedBoundPolicy::Allowed(&mut Default::default()),
2565            ImplTraitContext::Universal,
2566            hir::PredicateOrigin::ImplTrait,
2567        );
2568
2569        let hir_id = self.next_id();
2570        let res = Res::Def(DefKind::TyParam, def_id.to_def_id());
2571        let ty = hir::TyKind::Path(hir::QPath::Resolved(
2572            None,
2573            self.arena.alloc(hir::Path {
2574                span,
2575                res,
2576                segments:
2577                    arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2578            }),
2579        ));
2580
2581        (param, preds, ty)
2582    }
2583
2584    /// Lowers a block directly to an expression, presuming that it
2585    /// has no attributes and is not targeted by a `break`.
2586    fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2587        let block = self.lower_block(b, false);
2588        self.expr_block(block)
2589    }
2590
2591    fn lower_array_length_to_const_arg(&mut self, c: &AnonConst) -> &'hir hir::ConstArg<'hir> {
2592        // We cannot just match on `ExprKind::Underscore` as `(_)` is represented as
2593        // `ExprKind::Paren(ExprKind::Underscore)` and should also be lowered to `GenericArg::Infer`
2594        match c.value.peel_parens().kind {
2595            ExprKind::Underscore => {
2596                let ct_kind = hir::ConstArgKind::Infer(());
2597                self.arena.alloc(hir::ConstArg {
2598                    hir_id: self.lower_node_id(c.id),
2599                    kind: ct_kind,
2600                    span: self.lower_span(c.value.span),
2601                })
2602            }
2603            _ => self.lower_anon_const_to_const_arg_and_alloc(c),
2604        }
2605    }
2606
2607    /// Used when lowering a type argument that turned out to actually be a const argument.
2608    ///
2609    /// Only use for that purpose since otherwise it will create a duplicate def.
2610    #[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(2610u32),
                                    ::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().macroless_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))]
2611    fn lower_const_path_to_const_arg(
2612        &mut self,
2613        path: &Path,
2614        res: Res<NodeId>,
2615        ty_id: NodeId,
2616        span: Span,
2617    ) -> &'hir hir::ConstArg<'hir> {
2618        let tcx = self.tcx;
2619
2620        let is_trivial_path = path.is_potential_trivial_const_arg()
2621            && matches!(res, Res::Def(DefKind::ConstParam, _));
2622        let ct_kind = if is_trivial_path || tcx.features().macroless_generic_const_args() {
2623            let qpath = self.lower_qpath(
2624                ty_id,
2625                &None,
2626                path,
2627                ParamMode::Explicit,
2628                AllowReturnTypeNotation::No,
2629                // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2630                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2631                None,
2632            );
2633            hir::ConstArgKind::Path(qpath)
2634        } else {
2635            // Construct an AnonConst where the expr is the "ty"'s path.
2636            let node_id = self.next_node_id();
2637            let span = self.lower_span(span);
2638
2639            // Add a definition for the in-band const def.
2640            // We're lowering a const argument that was originally thought to be a type argument,
2641            // so the def collector didn't create the def ahead of time. That's why we have to do
2642            // it here.
2643            let def_id = self.create_def(node_id, None, DefKind::AnonConst, span);
2644            let hir_id = self.lower_node_id(node_id);
2645
2646            let path_expr = Expr {
2647                id: ty_id,
2648                kind: ExprKind::Path(None, path.clone()),
2649                span,
2650                attrs: AttrVec::new(),
2651                tokens: None,
2652            };
2653
2654            let ct = self.with_new_scopes(span, |this| {
2655                self.arena.alloc(hir::AnonConst {
2656                    def_id,
2657                    hir_id,
2658                    body: this.lower_const_body(path_expr.span, Some(&path_expr)),
2659                    span,
2660                })
2661            });
2662            hir::ConstArgKind::Anon(ct)
2663        };
2664
2665        self.arena.alloc(hir::ConstArg {
2666            hir_id: self.next_id(),
2667            kind: ct_kind,
2668            span: self.lower_span(span),
2669        })
2670    }
2671
2672    fn lower_const_item_rhs(
2673        &mut self,
2674        body: &Option<Box<Expr>>,
2675        kind: ConstItemKind,
2676        span: Span,
2677    ) -> hir::ConstItemRhs<'hir> {
2678        match (body, kind) {
2679            (body, ConstItemKind::Body) => {
2680                hir::ConstItemRhs::Body(self.lower_const_body(span, body.as_deref()))
2681            }
2682            (Some(body), ConstItemKind::TypeConst) => {
2683                hir::ConstItemRhs::TypeConst(self.arena.alloc(
2684                    match self.can_lower_expr_to_const_arg_direct(
2685                        &body,
2686                        DirectConstArgContext::MacrolessMinGenericConstArgs,
2687                    ) {
2688                        Ok(()) => self.lower_expr_to_const_arg_direct(&body, None),
2689                        Err(err) => err.emit(self),
2690                    },
2691                ))
2692            }
2693            (None, ConstItemKind::TypeConst) => {
2694                let const_arg = ConstArg {
2695                    hir_id: self.next_id(),
2696                    kind: hir::ConstArgKind::Error(
2697                        self.dcx().span_delayed_bug(DUMMY_SP, "no block"),
2698                    ),
2699                    span: DUMMY_SP,
2700                };
2701                hir::ConstItemRhs::TypeConst(self.arena.alloc(const_arg))
2702            }
2703        }
2704    }
2705
2706    x;#[instrument(level = "debug", skip(self), ret)]
2707    fn can_lower_expr_to_const_arg_direct(
2708        &mut self,
2709        expr: &Expr,
2710        context: DirectConstArgContext,
2711    ) -> Result<(), UnrepresentableConstArgError> {
2712        use DirectConstArgContext::*;
2713        // Note the only stable case is currently ExprKind::Path
2714        match (&expr.kind, context) {
2715            (
2716                ExprKind::Call(Expr { kind: ExprKind::Path(_, _), .. }, args),
2717                MacrolessMinGenericConstArgs,
2718            ) => {
2719                for arg in args {
2720                    self.can_lower_expr_to_const_arg_direct(arg, context)?;
2721                }
2722                Ok(())
2723            }
2724            (ExprKind::Tup(exprs), MacrolessMinGenericConstArgs) => {
2725                for expr in exprs {
2726                    self.can_lower_expr_to_const_arg_direct(expr, context)?;
2727                }
2728                Ok(())
2729            }
2730            (ExprKind::Path(_, _), MacrolessMinGenericConstArgs) => Ok(()),
2731            (ExprKind::Path(_, path), _) => {
2732                if path.is_potential_trivial_const_arg()
2733                    && matches!(
2734                        self.get_partial_res(expr.id)
2735                            .and_then(|partial_res| partial_res.full_res()),
2736                        Some(Res::Def(DefKind::ConstParam, _))
2737                    )
2738                {
2739                    Ok(())
2740                } else {
2741                    Err(UnrepresentableConstArgError::new(expr))
2742                }
2743            }
2744            (ExprKind::Struct(se), MacrolessMinGenericConstArgs) => {
2745                for f in &se.fields {
2746                    self.can_lower_expr_to_const_arg_direct(&f.expr, context)?;
2747                }
2748                Ok(())
2749            }
2750            (ExprKind::Array(elements), MacrolessMinGenericConstArgs) => {
2751                for element in elements {
2752                    self.can_lower_expr_to_const_arg_direct(element, context)?;
2753                }
2754                Ok(())
2755            }
2756            (ExprKind::Underscore, MacrolessMinGenericConstArgs) => Ok(()),
2757            (ExprKind::Block(block, _), MacrolessMinGenericConstArgs)
2758                if let [stmt] = block.stmts.as_slice()
2759                    && let StmtKind::Expr(expr) = &stmt.kind =>
2760            {
2761                self.can_lower_expr_to_const_arg_direct(expr, context)
2762            }
2763            (ExprKind::Lit(_), MacrolessMinGenericConstArgs) => Ok(()),
2764            (ExprKind::Unary(UnOp::Neg, inner_expr), MacrolessMinGenericConstArgs)
2765                if let ExprKind::Lit(_) = &inner_expr.kind =>
2766            {
2767                Ok(())
2768            }
2769            (ExprKind::ConstBlock(_), MacrolessMinGenericConstArgs) => Ok(()),
2770            (ExprKind::DirectConstArg(_), MacrolessMinGenericConstArgs | MinGenericConstArgs) => {
2771                // Always report this as able to be represented directly. If it turns out not to be,
2772                // `lower_expr_to_const_arg_direct` will report an error.
2773                Ok(())
2774            }
2775            _ => Err(UnrepresentableConstArgError::new(expr)),
2776        }
2777    }
2778
2779    /// It is not allowed to call this function without checking can_lower_expr_to_const_arg_direct
2780    /// first, as we assume all feature gates/etc. have been checked already.
2781    x;#[instrument(level = "debug", skip(self), ret)]
2782    fn lower_expr_to_const_arg_direct(
2783        &mut self,
2784        expr: &Expr,
2785        id_override: Option<NodeId>,
2786    ) -> hir::ConstArg<'hir> {
2787        let span = self.lower_span(expr.span);
2788        let node_id = id_override.unwrap_or(expr.id);
2789        match &expr.kind {
2790            ExprKind::Call(func, args) if let ExprKind::Path(qself, path) = &func.kind => {
2791                let qpath = self.lower_qpath(
2792                    func.id,
2793                    qself,
2794                    path,
2795                    ParamMode::Explicit,
2796                    AllowReturnTypeNotation::No,
2797                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2798                    None,
2799                );
2800
2801                let lowered_args = self.arena.alloc_from_iter(args.iter().map(|arg| {
2802                    let const_arg = self.lower_expr_to_const_arg_direct(arg, None);
2803                    &*self.arena.alloc(const_arg)
2804                }));
2805
2806                ConstArg {
2807                    hir_id: self.lower_node_id(node_id),
2808                    kind: hir::ConstArgKind::TupleCall(qpath, lowered_args),
2809                    span,
2810                }
2811            }
2812            ExprKind::Tup(exprs) => {
2813                let exprs = self.arena.alloc_from_iter(exprs.iter().map(|expr| {
2814                    let expr = self.lower_expr_to_const_arg_direct(expr, None);
2815                    &*self.arena.alloc(expr)
2816                }));
2817
2818                ConstArg {
2819                    hir_id: self.lower_node_id(node_id),
2820                    kind: hir::ConstArgKind::Tup(exprs),
2821                    span,
2822                }
2823            }
2824            ExprKind::Path(qself, path) => {
2825                let qpath = self.lower_qpath(
2826                    expr.id,
2827                    qself,
2828                    path,
2829                    ParamMode::Explicit,
2830                    AllowReturnTypeNotation::No,
2831                    // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2832                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2833                    None,
2834                );
2835
2836                ConstArg {
2837                    hir_id: self.lower_node_id(node_id),
2838                    kind: hir::ConstArgKind::Path(qpath),
2839                    span,
2840                }
2841            }
2842            ExprKind::Struct(se) => {
2843                let path = self.lower_qpath(
2844                    expr.id,
2845                    &se.qself,
2846                    &se.path,
2847                    // FIXME(mgca): we may want this to be `Optional` instead, but
2848                    // we would also need to make sure that HIR ty lowering errors
2849                    // when these paths wind up in signatures.
2850                    ParamMode::Explicit,
2851                    AllowReturnTypeNotation::No,
2852                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2853                    None,
2854                );
2855
2856                let fields = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
2857                    let hir_id = self.lower_node_id(f.id);
2858                    // FIXME(mgca): This might result in lowering attributes that
2859                    // then go unused as the `Target::ExprField` is not actually
2860                    // corresponding to `Node::ExprField`.
2861                    self.lower_attrs(hir_id, &f.attrs, f.span, Target::ExprField);
2862                    let expr = self.lower_expr_to_const_arg_direct(&f.expr, None);
2863
2864                    &*self.arena.alloc(hir::ConstArgExprField {
2865                        hir_id,
2866                        field: self.lower_ident(f.ident),
2867                        expr: self.arena.alloc(expr),
2868                        span: self.lower_span(f.span),
2869                    })
2870                }));
2871
2872                ConstArg {
2873                    hir_id: self.lower_node_id(node_id),
2874                    kind: hir::ConstArgKind::Struct(path, fields),
2875                    span,
2876                }
2877            }
2878            ExprKind::Array(elements) => {
2879                let lowered_elems = self.arena.alloc_from_iter(elements.iter().map(|element| {
2880                    let const_arg = self.lower_expr_to_const_arg_direct(element, None);
2881                    &*self.arena.alloc(const_arg)
2882                }));
2883                let array_expr = self.arena.alloc(hir::ConstArgArrayExpr {
2884                    span: self.lower_span(expr.span),
2885                    elems: lowered_elems,
2886                });
2887
2888                ConstArg {
2889                    hir_id: self.lower_node_id(node_id),
2890                    kind: hir::ConstArgKind::Array(array_expr),
2891                    span,
2892                }
2893            }
2894            ExprKind::Underscore => ConstArg {
2895                hir_id: self.lower_node_id(node_id),
2896                kind: hir::ConstArgKind::Infer(()),
2897                span,
2898            },
2899            ExprKind::Block(block, _)
2900                if let [stmt] = block.stmts.as_slice()
2901                    && let StmtKind::Expr(expr) = &stmt.kind =>
2902            {
2903                return self.lower_expr_to_const_arg_direct(expr, id_override);
2904            }
2905            ExprKind::Lit(literal) => {
2906                let span = self.lower_span(expr.span);
2907                let literal = self.lower_lit(literal, span);
2908
2909                ConstArg {
2910                    hir_id: self.lower_node_id(node_id),
2911                    kind: hir::ConstArgKind::Literal { lit: literal.node, negated: false },
2912                    span,
2913                }
2914            }
2915            ExprKind::Unary(UnOp::Neg, inner_expr)
2916                if let ExprKind::Lit(literal) = &inner_expr.kind =>
2917            {
2918                let span = self.lower_span(expr.span);
2919                let literal = self.lower_lit(literal, span);
2920
2921                let kind = if !matches!(literal.node, LitKind::Int(..)) {
2922                    let err =
2923                        self.dcx().struct_span_err(expr.span, "negated literal must be an integer");
2924                    hir::ConstArgKind::Error(err.emit())
2925                } else {
2926                    hir::ConstArgKind::Literal { lit: literal.node, negated: true }
2927                };
2928                ConstArg { hir_id: self.lower_node_id(node_id), kind, span }
2929            }
2930            ExprKind::ConstBlock(anon_const) => {
2931                // Do not use lower_anon_const_to_const_arg, as that attempts to represent the body
2932                // directly. Instead, force an anon const.
2933                let def_id = self.local_def_id(anon_const.id);
2934                assert_eq!(DefKind::AnonConst, self.tcx.def_kind(def_id));
2935                let lowered_anon = self.lower_anon_const_to_anon_const(anon_const, span);
2936                ConstArg {
2937                    hir_id: self.lower_node_id(node_id),
2938                    kind: hir::ConstArgKind::Anon(lowered_anon),
2939                    span,
2940                }
2941            }
2942            ExprKind::DirectConstArg(expr) => {
2943                // `can_lower_expr_to_const_arg_direct` always returns success upon encountering a
2944                // ExprKind::DirectConstArg, which effectively forces the expression to be lowered
2945                // as a direct arg. If it actually turns out to not be possible, emit an error
2946                // instead.
2947                // Always use MacrolessMinGenericConstArgs, even if we're under regular GCA, because
2948                // that's what the macro means: to enter a context that is like macroless GCA.
2949                match self.can_lower_expr_to_const_arg_direct(
2950                    expr,
2951                    DirectConstArgContext::MacrolessMinGenericConstArgs,
2952                ) {
2953                    Ok(()) => self.lower_expr_to_const_arg_direct(expr, id_override),
2954                    Err(err) => err.emit(self),
2955                }
2956            }
2957            _ => {
2958                span_bug!(
2959                    expr.span,
2960                    "lower_expr_to_const_arg_direct encountered an unlowerable expression, either \
2961                    can_lower_expr_to_const_arg_direct returned Ok() on something it shouldn't \
2962                    have, or you forgot to check can_lower_expr_to_const_arg_direct first"
2963                );
2964            }
2965        }
2966    }
2967
2968    /// See [`hir::ConstArg`] for when to use this function vs
2969    /// [`Self::lower_anon_const_to_anon_const`].
2970    fn lower_anon_const_to_const_arg_and_alloc(
2971        &mut self,
2972        anon: &AnonConst,
2973    ) -> &'hir hir::ConstArg<'hir> {
2974        self.arena.alloc(self.lower_anon_const_to_const_arg(anon))
2975    }
2976
2977    #[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(2977u32),
                                    ::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()
                                                    }], ::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))])
                            })
                } 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().macroless_generic_const_args() {
                    &anon.value
                } else { anon.value.maybe_unwrap_block() };
            let context =
                if self.tcx.features().macroless_generic_const_args() {
                    DirectConstArgContext::MacrolessMinGenericConstArgs
                } else if self.tcx.features().min_generic_const_args() {
                    DirectConstArgContext::MinGenericConstArgs
                } else { DirectConstArgContext::Stable };
            if self.can_lower_expr_to_const_arg_direct(expr, context).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))]
2978    fn lower_anon_const_to_const_arg(&mut self, anon: &AnonConst) -> hir::ConstArg<'hir> {
2979        // Stable only allows one nesting of blocks for directly represented paths. mGCA allows
2980        // arbitrarily many, and are handled inside lower_expr_to_const_arg_direct for consistency.
2981        let expr = if self.tcx.features().macroless_generic_const_args() {
2982            &anon.value
2983        } else {
2984            anon.value.maybe_unwrap_block()
2985        };
2986
2987        let context = if self.tcx.features().macroless_generic_const_args() {
2988            DirectConstArgContext::MacrolessMinGenericConstArgs
2989        } else if self.tcx.features().min_generic_const_args() {
2990            DirectConstArgContext::MinGenericConstArgs
2991        } else {
2992            DirectConstArgContext::Stable
2993        };
2994
2995        if self.can_lower_expr_to_const_arg_direct(expr, context).is_ok() {
2996            return self.lower_expr_to_const_arg_direct(expr, Some(anon.id));
2997        }
2998
2999        let lowered_anon = self.lower_anon_const_to_anon_const(anon, anon.value.span);
3000        ConstArg {
3001            hir_id: self.next_id(),
3002            kind: hir::ConstArgKind::Anon(lowered_anon),
3003            span: self.lower_span(anon.value.span),
3004        }
3005    }
3006
3007    /// See [`hir::ConstArg`] for when to use this function vs
3008    /// [`Self::lower_anon_const_to_const_arg`].
3009    fn lower_anon_const_to_anon_const(
3010        &mut self,
3011        c: &AnonConst,
3012        span: Span,
3013    ) -> &'hir hir::AnonConst {
3014        self.arena.alloc(self.with_new_scopes(c.value.span, |this| {
3015            let def_id = this.local_def_id(c.id);
3016            let hir_id = this.lower_node_id(c.id);
3017            hir::AnonConst {
3018                def_id,
3019                hir_id,
3020                body: this.lower_const_body(c.value.span, Some(&c.value)),
3021                span: this.lower_span(span),
3022            }
3023        }))
3024    }
3025
3026    fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
3027        match u {
3028            CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
3029            UserProvided => hir::UnsafeSource::UserProvided,
3030        }
3031    }
3032
3033    fn lower_trait_bound_modifiers(
3034        &mut self,
3035        modifiers: TraitBoundModifiers,
3036    ) -> hir::TraitBoundModifiers {
3037        let constness = match modifiers.constness {
3038            BoundConstness::Never => BoundConstness::Never,
3039            BoundConstness::Always(span) => BoundConstness::Always(self.lower_span(span)),
3040            BoundConstness::Maybe(span) => BoundConstness::Maybe(self.lower_span(span)),
3041        };
3042        let polarity = match modifiers.polarity {
3043            BoundPolarity::Positive => BoundPolarity::Positive,
3044            BoundPolarity::Negative(span) => BoundPolarity::Negative(self.lower_span(span)),
3045            BoundPolarity::Maybe(span) => BoundPolarity::Maybe(self.lower_span(span)),
3046        };
3047        hir::TraitBoundModifiers { constness, polarity }
3048    }
3049
3050    // Helper methods for building HIR.
3051
3052    fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
3053        hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
3054    }
3055
3056    fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
3057        self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
3058    }
3059
3060    fn stmt_let_pat(
3061        &mut self,
3062        attrs: Option<&'hir [hir::Attribute]>,
3063        span: Span,
3064        init: Option<&'hir hir::Expr<'hir>>,
3065        pat: &'hir hir::Pat<'hir>,
3066        source: hir::LocalSource,
3067    ) -> hir::Stmt<'hir> {
3068        let hir_id = self.next_id();
3069        if let Some(a) = attrs {
3070            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
3071            self.attrs.insert(hir_id.local_id, a);
3072        }
3073        let local = hir::LetStmt {
3074            super_: None,
3075            hir_id,
3076            init,
3077            pat,
3078            els: None,
3079            source,
3080            span: self.lower_span(span),
3081            ty: None,
3082        };
3083        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
3084    }
3085
3086    fn stmt_super_let_pat(
3087        &mut self,
3088        span: Span,
3089        pat: &'hir hir::Pat<'hir>,
3090        init: Option<&'hir hir::Expr<'hir>>,
3091    ) -> hir::Stmt<'hir> {
3092        let hir_id = self.next_id();
3093        let span = self.lower_span(span);
3094        let local = hir::LetStmt {
3095            super_: Some(span),
3096            hir_id,
3097            init,
3098            pat,
3099            els: None,
3100            source: hir::LocalSource::Normal,
3101            span,
3102            ty: None,
3103        };
3104        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
3105    }
3106
3107    fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
3108        self.block_all(expr.span, &[], Some(expr))
3109    }
3110
3111    fn block_all(
3112        &mut self,
3113        span: Span,
3114        stmts: &'hir [hir::Stmt<'hir>],
3115        expr: Option<&'hir hir::Expr<'hir>>,
3116    ) -> &'hir hir::Block<'hir> {
3117        let blk = hir::Block {
3118            stmts,
3119            expr,
3120            hir_id: self.next_id(),
3121            rules: hir::BlockCheckMode::DefaultBlock,
3122            span: self.lower_span(span),
3123            targeted_by_break: false,
3124        };
3125        self.arena.alloc(blk)
3126    }
3127
3128    fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
3129        let field = self.single_pat_field(span, pat);
3130        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field)
3131    }
3132
3133    fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
3134        let field = self.single_pat_field(span, pat);
3135        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field)
3136    }
3137
3138    fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
3139        let field = self.single_pat_field(span, pat);
3140        self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field)
3141    }
3142
3143    fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
3144        self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[])
3145    }
3146
3147    fn single_pat_field(
3148        &mut self,
3149        span: Span,
3150        pat: &'hir hir::Pat<'hir>,
3151    ) -> &'hir [hir::PatField<'hir>] {
3152        let field = hir::PatField {
3153            hir_id: self.next_id(),
3154            ident: Ident::new(sym::integer(0), self.lower_span(span)),
3155            is_shorthand: false,
3156            pat,
3157            span: self.lower_span(span),
3158        };
3159        self.arena.alloc_from_iter([field])arena_vec![self; field]
3160    }
3161
3162    fn pat_lang_item_variant(
3163        &mut self,
3164        span: Span,
3165        lang_item: hir::LangItem,
3166        fields: &'hir [hir::PatField<'hir>],
3167    ) -> &'hir hir::Pat<'hir> {
3168        let path = self.make_lang_item_qpath(lang_item, self.lower_span(span), None);
3169        self.pat(span, hir::PatKind::Struct(path, fields, None))
3170    }
3171
3172    fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, HirId) {
3173        self.pat_ident_binding_mode(span, ident, hir::BindingMode::NONE)
3174    }
3175
3176    fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, HirId) {
3177        self.pat_ident_binding_mode_mut(span, ident, hir::BindingMode::NONE)
3178    }
3179
3180    fn pat_ident_binding_mode(
3181        &mut self,
3182        span: Span,
3183        ident: Ident,
3184        bm: hir::BindingMode,
3185    ) -> (&'hir hir::Pat<'hir>, HirId) {
3186        let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
3187        (self.arena.alloc(pat), hir_id)
3188    }
3189
3190    fn pat_ident_binding_mode_mut(
3191        &mut self,
3192        span: Span,
3193        ident: Ident,
3194        bm: hir::BindingMode,
3195    ) -> (hir::Pat<'hir>, HirId) {
3196        let hir_id = self.next_id();
3197
3198        (
3199            hir::Pat {
3200                hir_id,
3201                kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
3202                span: self.lower_span(span),
3203                default_binding_modes: true,
3204            },
3205            hir_id,
3206        )
3207    }
3208
3209    fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
3210        self.arena.alloc(hir::Pat {
3211            hir_id: self.next_id(),
3212            kind,
3213            span: self.lower_span(span),
3214            default_binding_modes: true,
3215        })
3216    }
3217
3218    fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
3219        hir::Pat {
3220            hir_id: self.next_id(),
3221            kind,
3222            span: self.lower_span(span),
3223            default_binding_modes: false,
3224        }
3225    }
3226
3227    fn ty_path(&mut self, mut hir_id: HirId, span: Span, qpath: hir::QPath<'hir>) -> hir::Ty<'hir> {
3228        let kind = match qpath {
3229            hir::QPath::Resolved(None, path) => {
3230                // Turn trait object paths into `TyKind::TraitObject` instead.
3231                match path.res {
3232                    Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
3233                        let principal = hir::PolyTraitRef {
3234                            bound_generic_params: &[],
3235                            modifiers: hir::TraitBoundModifiers::NONE,
3236                            trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
3237                            span: self.lower_span(span),
3238                        };
3239
3240                        // The original ID is taken by the `PolyTraitRef`,
3241                        // so the `Ty` itself needs a different one.
3242                        hir_id = self.next_id();
3243                        hir::TyKind::TraitObject(
3244                            self.arena.alloc_from_iter([principal])arena_vec![self; principal],
3245                            TaggedRef::new(self.elided_dyn_bound(span), TraitObjectSyntax::None),
3246                        )
3247                    }
3248                    _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
3249                }
3250            }
3251            _ => hir::TyKind::Path(qpath),
3252        };
3253
3254        hir::Ty { hir_id, kind, span: self.lower_span(span) }
3255    }
3256
3257    /// Invoked to create the lifetime argument(s) for an elided trait object
3258    /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
3259    /// when the bound is written, even if it is written with `'_` like in
3260    /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
3261    fn elided_dyn_bound(&mut self, span: Span) -> &'hir hir::Lifetime {
3262        let r = hir::Lifetime::new(
3263            self.next_id(),
3264            Ident::new(kw::UnderscoreLifetime, self.lower_span(span)),
3265            hir::LifetimeKind::ImplicitObjectLifetimeDefault,
3266            LifetimeSource::Other,
3267            LifetimeSyntax::Implicit,
3268        );
3269        {
    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:3269",
                        "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(3269u32),
                        ::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);
3270        self.arena.alloc(r)
3271    }
3272}
3273
3274/// Helper struct for the delayed construction of [`hir::GenericArgs`].
3275struct GenericArgsCtor<'hir> {
3276    args: SmallVec<[hir::GenericArg<'hir>; 4]>,
3277    constraints: &'hir [hir::AssocItemConstraint<'hir>],
3278    parenthesized: hir::GenericArgsParentheses,
3279    span: Span,
3280}
3281
3282impl<'hir> GenericArgsCtor<'hir> {
3283    fn is_empty(&self) -> bool {
3284        self.args.is_empty()
3285            && self.constraints.is_empty()
3286            && self.parenthesized == hir::GenericArgsParentheses::No
3287    }
3288
3289    fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
3290        let ga = hir::GenericArgs {
3291            args: this.arena.alloc_from_iter(self.args),
3292            constraints: self.constraints,
3293            parenthesized: self.parenthesized,
3294            span_ext: this.lower_span(self.span),
3295        };
3296        this.arena.alloc(ga)
3297    }
3298}
3299
3300#[derive(#[automatically_derived]
impl ::core::marker::Copy for DirectConstArgContext { }Copy, #[automatically_derived]
impl ::core::clone::Clone for DirectConstArgContext {
    #[inline]
    fn clone(&self) -> DirectConstArgContext { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for DirectConstArgContext {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                DirectConstArgContext::Stable => "Stable",
                DirectConstArgContext::MinGenericConstArgs =>
                    "MinGenericConstArgs",
                DirectConstArgContext::MacrolessMinGenericConstArgs =>
                    "MacrolessMinGenericConstArgs",
            })
    }
}Debug)]
3301enum DirectConstArgContext {
3302    /// The only allowed direct const arg representation is simple paths that nameres to generic
3303    /// const parameters.
3304    Stable,
3305    /// The allowed representations are what is allowed on stable, plus the `direct_const_arg!` macro.
3306    MinGenericConstArgs,
3307    /// Expressions attempt to be lowered directly, and if that fails, the expression falls back to
3308    /// being represented as an anon const.
3309    ///
3310    /// This context is also used under MinGenericConstArgs inside a `direct_const_arg!` macro, for
3311    /// simplicity, as they allow the same code.
3312    MacrolessMinGenericConstArgs,
3313}
3314
3315#[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)]
3316struct UnrepresentableConstArgError {
3317    span: Span,
3318    will_create_def_ids: bool,
3319}
3320
3321impl UnrepresentableConstArgError {
3322    fn new(expr: &Expr) -> Self {
3323        Self {
3324            span: expr.span,
3325            will_create_def_ids: expr::WillCreateDefIdsVisitor.visit_expr(expr).is_break(),
3326        }
3327    }
3328
3329    fn emit<'hir>(self, lowering_context: &mut LoweringContext<'_, 'hir>) -> ConstArg<'hir> {
3330        let msg = "complex const arguments must be placed inside of a `const` block";
3331        let e = if self.will_create_def_ids {
3332            // FIXME(mgca): make this non-fatal once we have a better way to handle
3333            // nested items in const args
3334            // Issue: https://github.com/rust-lang/rust/issues/154539
3335            lowering_context.dcx().struct_span_fatal(self.span, msg).emit()
3336        } else {
3337            lowering_context.dcx().struct_span_err(self.span, msg).emit()
3338        };
3339
3340        ConstArg {
3341            hir_id: lowering_context.next_id(),
3342            kind: hir::ConstArgKind::Error(e),
3343            span: self.span,
3344        }
3345    }
3346}