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};
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::errors::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())
    }
    #[doc = " Obtain the list of lifetimes parameters to add to an item."]
    #[doc = ""]
    #[doc =
    " Extra lifetime parameters should only be added in places that can appear"]
    #[doc = " as a `binder` in `LifetimeRes`."]
    #[doc = ""]
    #[doc =
    " The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring"]
    #[doc = " should appear at the enclosing `PolyTraitRef`."]
    fn extra_lifetime_params(&self, id: NodeId)
        -> &[(Ident, NodeId, MissingLifetimeKind)] {
        self.extra_lifetime_params_map.get(&id).map_or(&[], |v| &v[..])
    }
}#[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    /// Obtain the list of lifetimes parameters to add to an item.
356    ///
357    /// Extra lifetime parameters should only be added in places that can appear
358    /// as a `binder` in `LifetimeRes`.
359    ///
360    /// The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring
361    /// should appear at the enclosing `PolyTraitRef`.
362    fn extra_lifetime_params(&self, id: NodeId) -> &[(Ident, NodeId, MissingLifetimeKind)] {
363        self.extra_lifetime_params_map.get(&id).map_or(&[], |v| &v[..])
364    }
365}
366
367/// How relaxed bounds `?Trait` should be treated.
368///
369/// Relaxed bounds should only be allowed in places where we later
370/// (namely during HIR ty lowering) perform *sized elaboration*.
371#[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)]
372enum RelaxedBoundPolicy<'a> {
373    /// The `DefId` refers to the trait that is being relaxed.
374    Allowed(&'a mut FxIndexMap<DefId, Span>),
375    Forbidden(RelaxedBoundForbiddenReason),
376}
377impl RelaxedBoundPolicy<'_> {
378    fn reborrow(&mut self) -> RelaxedBoundPolicy<'_> {
379        match self {
380            RelaxedBoundPolicy::Allowed(m) => RelaxedBoundPolicy::Allowed(m),
381            RelaxedBoundPolicy::Forbidden(reason) => RelaxedBoundPolicy::Forbidden(*reason),
382        }
383    }
384}
385
386#[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)]
387enum RelaxedBoundForbiddenReason {
388    TraitObjectTy,
389    SuperTrait,
390    TraitAlias,
391    AssocTyBounds,
392    /// We do not allow where bounds doing relaxed bounds,
393    /// except if it's for generic parameters of the current item.
394    WhereBound,
395}
396
397/// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
398/// and if so, what meaning it has.
399#[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)]
400enum ImplTraitContext {
401    /// Treat `impl Trait` as shorthand for a new universal generic parameter.
402    /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
403    /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
404    ///
405    /// Newly generated parameters should be inserted into the given `Vec`.
406    Universal,
407
408    /// Treat `impl Trait` as shorthand for a new opaque type.
409    /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
410    /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
411    ///
412    OpaqueTy { origin: hir::OpaqueTyOrigin<LocalDefId> },
413
414    /// Treat `impl Trait` as a "trait ascription", which is like a type
415    /// variable but that also enforces that a set of trait goals hold.
416    ///
417    /// This is useful to guide inference for unnameable types.
418    InBinding,
419
420    /// `impl Trait` is unstably accepted in this position.
421    FeatureGated(ImplTraitPosition, Symbol),
422    /// `impl Trait` is not accepted in this position.
423    Disallowed(ImplTraitPosition),
424}
425
426/// Position in which `impl Trait` is disallowed.
427#[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)]
428enum ImplTraitPosition {
429    Path,
430    Variable,
431    Trait,
432    Bound,
433    Generic,
434    ExternFnParam,
435    ClosureParam,
436    PointerParam,
437    FnTraitParam,
438    ExternFnReturn,
439    ClosureReturn,
440    PointerReturn,
441    FnTraitReturn,
442    GenericDefault,
443    ConstTy,
444    StaticTy,
445    AssocTy,
446    FieldTy,
447    Cast,
448    ImplSelf,
449    OffsetOf,
450}
451
452impl std::fmt::Display for ImplTraitPosition {
453    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
454        let name = match self {
455            ImplTraitPosition::Path => "paths",
456            ImplTraitPosition::Variable => "the type of variable bindings",
457            ImplTraitPosition::Trait => "traits",
458            ImplTraitPosition::Bound => "bounds",
459            ImplTraitPosition::Generic => "generics",
460            ImplTraitPosition::ExternFnParam => "`extern fn` parameters",
461            ImplTraitPosition::ClosureParam => "closure parameters",
462            ImplTraitPosition::PointerParam => "`fn` pointer parameters",
463            ImplTraitPosition::FnTraitParam => "the parameters of `Fn` trait bounds",
464            ImplTraitPosition::ExternFnReturn => "`extern fn` return types",
465            ImplTraitPosition::ClosureReturn => "closure return types",
466            ImplTraitPosition::PointerReturn => "`fn` pointer return types",
467            ImplTraitPosition::FnTraitReturn => "the return type of `Fn` trait bounds",
468            ImplTraitPosition::GenericDefault => "generic parameter defaults",
469            ImplTraitPosition::ConstTy => "const types",
470            ImplTraitPosition::StaticTy => "static types",
471            ImplTraitPosition::AssocTy => "associated types",
472            ImplTraitPosition::FieldTy => "field types",
473            ImplTraitPosition::Cast => "cast expression types",
474            ImplTraitPosition::ImplSelf => "impl headers",
475            ImplTraitPosition::OffsetOf => "`offset_of!` parameters",
476        };
477
478        f.write_fmt(format_args!("{0}", name))write!(f, "{name}")
479    }
480}
481
482#[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)]
483enum FnDeclKind {
484    Fn,
485    Inherent,
486    ExternFn,
487    Closure,
488    Pointer,
489    Trait,
490    Impl,
491}
492
493#[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)]
494enum TryBlockScope {
495    /// There isn't a `try` block, so a `?` will use `return`.
496    Function,
497    /// We're inside a `try { … }` block, so a `?` will block-break
498    /// from that block using a type depending only on the argument.
499    Homogeneous(HirId),
500    /// We're inside a `try as _ { … }` block, so a `?` will block-break
501    /// from that block using the type specified.
502    Heterogeneous(HirId),
503}
504
505fn index_ast<'tcx>(
506    tcx: TyCtxt<'tcx>,
507    (): (),
508) -> IndexVec<LocalDefId, Steal<(Arc<ResolverAstLowering<'tcx>>, AstOwner)>> {
509    // Queries that borrow `resolver_for_lowering`.
510    tcx.ensure_done().output_filenames(());
511    tcx.ensure_done().early_lint_checks(());
512    tcx.ensure_done().get_lang_items(());
513    tcx.ensure_done().debugger_visualizers(LOCAL_CRATE);
514
515    let (resolver, krate) = tcx.resolver_for_lowering();
516    let mut resolver = resolver.steal();
517    let mut krate = krate.steal();
518
519    let mut indexer = Indexer {
520        owners: &resolver.owners,
521        index: IndexVec::new(),
522        next_node_id: resolver.next_node_id,
523    };
524    indexer.visit_crate(&mut krate);
525    indexer.insert(CRATE_NODE_ID, AstOwner::Crate(Box::new(krate)));
526    resolver.next_node_id = indexer.next_node_id;
527
528    let index = indexer.index;
529    let resolver = Arc::new(resolver);
530    let index = index.into_iter().map(|owner| Steal::new((Arc::clone(&resolver), owner))).collect();
531    return index;
532
533    struct Indexer<'s, 'hir> {
534        owners: &'s NodeMap<PerOwnerResolverData<'hir>>,
535        index: IndexVec<LocalDefId, AstOwner>,
536        next_node_id: NodeId,
537    }
538
539    impl Indexer<'_, '_> {
540        fn insert(&mut self, id: NodeId, node: AstOwner) {
541            let def_id = self.owners[&id].def_id;
542            self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner);
543            self.index[def_id] = node;
544        }
545
546        fn make_dummy<K>(
547            &mut self,
548            id: NodeId,
549            span: Span,
550            dummy: impl FnOnce(Box<MacCall>) -> K,
551        ) -> Box<Item<K>> {
552            use rustc_ast::token::Delimiter;
553            use rustc_ast::tokenstream::{DelimSpan, TokenStream};
554            use thin_vec::thin_vec;
555
556            Box::new(Item {
557                attrs: AttrVec::default(),
558                id,
559                span,
560                vis: Visibility { kind: VisibilityKind::Public, span },
561                // Lacking a better choice, we replace the contents with a macro call.
562                // Unexpanded macros should never reach lowering, so this is not confusing.
563                kind: dummy(Box::new(MacCall {
564                    path: Path { span, segments: ::thin_vec::ThinVec::new()thin_vec![] },
565                    args: Box::new(DelimArgs {
566                        dspan: DelimSpan::from_single(span),
567                        delim: Delimiter::Parenthesis,
568                        tokens: TokenStream::new(Vec::new()),
569                    }),
570                })),
571                tokens: None,
572            })
573        }
574
575        fn replace_with_dummy<K>(
576            &mut self,
577            item: &mut ast::Item<K>,
578            dummy: impl FnOnce(Box<MacCall>) -> K,
579            node: impl FnOnce(Box<Item<K>>) -> AstOwner,
580        ) {
581            let dummy = self.make_dummy(item.id, item.span, dummy);
582            let item = mem::replace(item, *dummy);
583            self.insert(item.id, node(Box::new(item)));
584        }
585
586        #[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(586u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["tree", "parent",
                                                    "items"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tree)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&items)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            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))]
587        fn visit_item_id_use_tree(
588            &mut self,
589            tree: &UseTree,
590            parent: LocalDefId,
591            items: &mut SmallVec<[Box<Item>; 1]>,
592        ) {
593            match tree.kind {
594                UseTreeKind::Glob(_) | UseTreeKind::Simple(_) => {}
595                UseTreeKind::Nested { items: ref nested_vec, span } => {
596                    for &(ref nested, id) in nested_vec {
597                        self.insert(id, AstOwner::NestedUseTree(parent));
598                        items.push(self.make_dummy(id, span, ItemKind::MacCall));
599
600                        let def_id = self.owners[&id].def_id;
601                        self.visit_item_id_use_tree(nested, def_id, items);
602                    }
603                }
604            }
605        }
606    }
607
608    impl MutVisitor for Indexer<'_, '_> {
609        fn visit_attribute(&mut self, _: &mut Attribute) {
610            // We do not want to lower expressions that appear in attributes,
611            // as they are not accessible to the rest of the HIR.
612        }
613
614        fn flat_map_item(&mut self, mut item: Box<Item>) -> SmallVec<[Box<Item>; 1]> {
615            let def_id = self.owners[&item.id].def_id;
616            mut_visit::walk_item(self, &mut *item);
617            let dummy = self.make_dummy(item.id, item.span, ItemKind::MacCall);
618            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];
619            if let ItemKind::Use(ref use_tree) = item.kind {
620                self.visit_item_id_use_tree(use_tree, def_id, &mut items);
621            }
622            self.insert(item.id, AstOwner::Item(item));
623            items
624        }
625
626        fn flat_map_stmt(&mut self, stmt: Stmt) -> SmallVec<[Stmt; 1]> {
627            let Stmt { id, span, kind } = stmt;
628            let mut id = Some(id);
629            mut_visit::walk_flat_map_stmt_kind(self, kind)
630                .into_iter()
631                .map(|kind| {
632                    // Expanding the current statement is a nested `use` item,
633                    // it is expanded into several flat `use` items.
634                    // Create new NodeIds for the corresponding statements
635                    // as two statements cannot have the same.
636                    let id = id.take().unwrap_or_else(|| {
637                        let next = self.next_node_id;
638                        self.next_node_id.increment_by(1);
639                        next
640                    });
641                    Stmt { id, kind, span }
642                })
643                .collect()
644        }
645
646        fn visit_assoc_item(&mut self, item: &mut AssocItem, ctxt: visit::AssocCtxt) {
647            mut_visit::walk_assoc_item(self, item, ctxt);
648            match ctxt {
649                visit::AssocCtxt::Trait => {
650                    self.replace_with_dummy(item, AssocItemKind::MacCall, AstOwner::TraitItem)
651                }
652                visit::AssocCtxt::Impl { .. } => {
653                    self.replace_with_dummy(item, AssocItemKind::MacCall, AstOwner::ImplItem)
654                }
655            }
656        }
657
658        fn visit_foreign_item(&mut self, item: &mut ForeignItem) {
659            mut_visit::walk_item(self, item);
660            self.replace_with_dummy(item, ForeignItemKind::MacCall, AstOwner::ForeignItem);
661        }
662    }
663}
664
665#[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(665u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::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))]
666fn lower_to_hir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> hir::MaybeOwner<'_> {
667    let ast_index = tcx.index_ast(());
668    let resolver_and_node = ast_index.get(def_id).map(Steal::steal);
669
670    let fallback_to_ancestor = |parent_id| {
671        // The item did not exist in the AST, it was created while lowering another item.
672        // `parent_id` may be different from the direct parent of `def_id`,
673        // for instance use-trees are lowered by the first sibling.
674        let mut parent_info = tcx.lower_to_hir(parent_id);
675        if let hir::MaybeOwner::NonOwner(hir_id) = parent_info {
676            // `parent_id` could also not be a owner either.
677            // For instance if `def_id` is an enum variant field,
678            // the direct parent is the enum variant.
679            // In that case `hir_id.owner` point to the actual HIR owner
680            // and skips all non-owner parents, so fetch the HIR associated to it.
681            parent_info = tcx.lower_to_hir(hir_id.owner);
682        }
683
684        let parent_info = parent_info.unwrap();
685        *parent_info.children.get(&def_id).unwrap_or_else(|| {
686            panic!(
687                "{:?} does not appear in children of {:?}",
688                def_id,
689                parent_info.nodes.node().def_id()
690            )
691        })
692    };
693
694    let Some((resolver, node)) = resolver_and_node else {
695        // `ast_index` does not contain all definitions, only up-to the highest
696        // `LocalDefId` which has a non-trivial `AstOwner`. Gracefully handle
697        // other definitions, in particular those nested inside this highest definition.
698        return fallback_to_ancestor(tcx.local_parent(def_id));
699    };
700
701    let mut item_lowerer = item::ItemLowerer { tcx, resolver: &*resolver };
702
703    let item = match &node {
704        // The item existed in the AST.
705        AstOwner::Crate(c) => item_lowerer.lower_crate(&c),
706        AstOwner::Item(item) => item_lowerer.lower_item(&item),
707        AstOwner::TraitItem(item) => item_lowerer.lower_trait_item(&item),
708        AstOwner::ImplItem(item) => item_lowerer.lower_impl_item(&item),
709        AstOwner::ForeignItem(item) => item_lowerer.lower_foreign_item(&item),
710        AstOwner::NestedUseTree(owner_id) => fallback_to_ancestor(*owner_id),
711        // The item existed in the AST, but is not a HIR owner.
712        // Fetch the correct information from its parent.
713        AstOwner::NonOwner => fallback_to_ancestor(tcx.local_parent(def_id)),
714    };
715
716    tcx.sess.time("drop_ast", || mem::drop(node));
717
718    item
719}
720
721#[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)]
722enum ParamMode {
723    /// Any path in a type context.
724    Explicit,
725    /// The `module::Type` in `module::Type::method` in an expression.
726    Optional,
727}
728
729#[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)]
730enum AllowReturnTypeNotation {
731    /// Only in types, since RTN is denied later during HIR lowering.
732    Yes,
733    /// All other positions (path expr, method, use tree).
734    No,
735}
736
737enum GenericArgsMode {
738    /// Allow paren sugar, don't allow RTN.
739    ParenSugar,
740    /// Allow RTN, don't allow paren sugar.
741    ReturnTypeNotation,
742    // Error if parenthesized generics or RTN are encountered.
743    Err,
744    /// Silence errors when lowering generics. Only used with `Res::Err`.
745    Silence,
746}
747
748impl<'hir> LoweringContext<'_, 'hir> {
749    fn create_def(
750        &mut self,
751        node_id: NodeId,
752        name: Option<Symbol>,
753        def_kind: DefKind,
754        span: Span,
755    ) -> LocalDefId {
756        let parent = self.current_hir_id_owner.def_id;
757        {
    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);
758        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!(
759            self.opt_local_def_id(node_id).is_none(),
760            "adding a def'n for node-id {:?} and def kind {:?} but a previous def'n exists: {:?}",
761            node_id,
762            def_kind,
763            self.tcx.hir_def_key(self.local_def_id(node_id)),
764        );
765
766        let def_id = self
767            .tcx
768            .at(span)
769            .create_def(parent, name, def_kind, None, &mut self.current_disambiguator)
770            .def_id();
771
772        {
    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:772",
                        "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(772u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("create_def: def_id_to_node_id[{0:?}] <-> {1:?}",
                                                    def_id, node_id) as &dyn Value))])
            });
    } else { ; }
};debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
773        self.node_id_to_def_id.insert(node_id, def_id);
774
775        def_id
776    }
777
778    fn next_node_id(&mut self) -> NodeId {
779        let start = self.next_node_id;
780        let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
781        self.next_node_id = NodeId::from_u32(next);
782        start
783    }
784
785    /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
786    /// resolver (if any).
787    x;#[instrument(level = "trace", skip(self), ret)]
788    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
789        self.node_id_to_def_id
790            .get(&node)
791            .or_else(|| self.owner.node_id_to_def_id.get(&node))
792            .copied()
793    }
794
795    fn local_def_id(&self, node: NodeId) -> LocalDefId {
796        self.opt_local_def_id(node).unwrap_or_else(|| {
797            self.resolver.owners.items().any(|(id, items)| {
798                items.node_id_to_def_id.items().any(|(node_id, def_id)| {
799                    if *node_id == node {
800                        let actual_owner = items.node_id_to_def_id.get(id);
801                        {
    ::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})",)
802                    }
803                    false
804                })
805            });
806            {
    ::core::panicking::panic_fmt(format_args!("no entry for node id: `{0:?}`",
            node));
};panic!("no entry for node id: `{node:?}`");
807        })
808    }
809
810    fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
811        match self.partial_res_overrides.get(&id) {
812            Some(self_param_id) => Some(PartialRes::new(Res::Local(*self_param_id))),
813            None => self.resolver.partial_res_map.get(&id).copied(),
814        }
815    }
816
817    /// Given the id of an owner node in the AST, returns the corresponding `OwnerId`.
818    fn owner_id(&self, node: NodeId) -> hir::OwnerId {
819        hir::OwnerId { def_id: self.resolver.owners[&node].def_id }
820    }
821
822    /// Freshen the `LoweringContext` and ready it to lower a nested item.
823    /// The lowered item is registered into `self.children`.
824    ///
825    /// This function sets up `HirId` lowering infrastructure,
826    /// and stashes the shared mutable state to avoid pollution by the closure.
827    #[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(827u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["owner"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&owner)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let owner_id = self.owner_id(owner);
            let 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))]
828    fn with_hir_id_owner(
829        &mut self,
830        owner: NodeId,
831        f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
832    ) {
833        let owner_id = self.owner_id(owner);
834        let def_id = owner_id.def_id;
835
836        let new_disambig = self
837            .resolver
838            .disambiguators
839            .get(&def_id)
840            .map(|s| s.steal())
841            .unwrap_or_else(|| PerParentDisambiguatorState::new(def_id));
842
843        let disambiguator = mem::replace(&mut self.current_disambiguator, new_disambig);
844        let current_ast_owner = mem::replace(&mut self.owner, &self.resolver.owners[&owner]);
845        let current_attrs = mem::take(&mut self.attrs);
846        let current_bodies = mem::take(&mut self.bodies);
847        let current_define_opaque = mem::take(&mut self.define_opaque);
848        let current_ident_and_label_to_local_id = mem::take(&mut self.ident_and_label_to_local_id);
849
850        #[cfg(debug_assertions)]
851        let current_relowering_checker = mem::take(&mut self.relowering_checker);
852        let current_trait_map = mem::take(&mut self.trait_map);
853        let current_owner = mem::replace(&mut self.current_hir_id_owner, owner_id);
854        let current_local_counter =
855            mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
856        let current_impl_trait_defs = mem::take(&mut self.impl_trait_defs);
857        let current_impl_trait_bounds = mem::take(&mut self.impl_trait_bounds);
858        let current_delayed_lints = mem::take(&mut self.delayed_lints);
859        let current_children = mem::take(&mut self.children);
860
861        // Do not reset `next_node_id` and `node_id_to_def_id`:
862        // we want `f` to be able to refer to the `LocalDefId`s that the caller created.
863        // and the caller to refer to some of the subdefinitions' nodes' `LocalDefId`s.
864
865        // Always allocate the first `HirId` for the owner itself.
866        #[cfg(debug_assertions)]
867        self.relowering_checker.assert_node_is_not_relowered(owner, hir::ItemLocalId::ZERO);
868
869        let item = f(self);
870        assert_eq!(owner_id, item.def_id());
871        // `f` should have consumed all the elements in these vectors when constructing `item`.
872        assert!(self.impl_trait_defs.is_empty());
873        assert!(self.impl_trait_bounds.is_empty());
874        let info = self.make_owner_info(item);
875
876        self.current_disambiguator = disambiguator;
877        self.owner = current_ast_owner;
878        self.attrs = current_attrs;
879        self.bodies = current_bodies;
880        self.define_opaque = current_define_opaque;
881        self.ident_and_label_to_local_id = current_ident_and_label_to_local_id;
882
883        #[cfg(debug_assertions)]
884        {
885            self.relowering_checker = current_relowering_checker;
886        }
887        self.trait_map = current_trait_map;
888        self.current_hir_id_owner = current_owner;
889        self.item_local_id_counter = current_local_counter;
890        self.impl_trait_defs = current_impl_trait_defs;
891        self.impl_trait_bounds = current_impl_trait_bounds;
892        self.delayed_lints = current_delayed_lints;
893        self.children = current_children;
894        self.children.extend_unord(info.children.items().map(|(&def_id, &info)| (def_id, info)));
895
896        debug_assert!(!self.children.contains_key(&owner_id.def_id));
897        self.children.insert(owner_id.def_id, hir::MaybeOwner::Owner(info));
898    }
899
900    fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> {
901        let attrs = mem::take(&mut self.attrs);
902        let mut bodies = mem::take(&mut self.bodies);
903        let define_opaque = mem::take(&mut self.define_opaque);
904        let trait_map = mem::take(&mut self.trait_map);
905        let delayed_lints = Steal::new(mem::take(&mut self.delayed_lints).into_boxed_slice());
906        let children = mem::take(&mut self.children);
907
908        #[cfg(debug_assertions)]
909        for (id, attrs) in attrs.iter() {
910            // Verify that we do not store empty slices in the map.
911            if attrs.is_empty() {
912                {
    ::core::panicking::panic_fmt(format_args!("Stored empty attributes for {0:?}",
            id));
};panic!("Stored empty attributes for {:?}", id);
913            }
914        }
915
916        bodies.sort_by_key(|(k, _)| *k);
917        let bodies = SortedMap::from_presorted_elements(bodies);
918
919        // Don't hash unless necessary, because it's expensive.
920        let rustc_middle::hir::Hashes { bodies_hash, attrs_hash } =
921            self.tcx.hash_owner_nodes(node, &bodies, &attrs, define_opaque);
922        let num_nodes = self.item_local_id_counter.as_usize();
923        let (nodes, parenting) = index::index_hir(self.tcx, node, &bodies, num_nodes);
924        let nodes = hir::OwnerNodes { opt_hash: bodies_hash, nodes, bodies };
925        let attrs = hir::AttributeMap { map: attrs, opt_hash: attrs_hash, define_opaque };
926
927        let opt_hash = self.tcx.needs_hir_hash().then(|| {
928            self.tcx.with_stable_hashing_context(|mut hcx| {
929                let mut stable_hasher = StableHasher::new();
930                bodies_hash.unwrap().stable_hash(&mut hcx, &mut stable_hasher);
931                attrs_hash.unwrap().stable_hash(&mut hcx, &mut stable_hasher);
932                // Do not hash delayed_lints.
933                parenting.stable_hash(&mut hcx, &mut stable_hasher);
934                trait_map.stable_hash(&mut hcx, &mut stable_hasher);
935                children.stable_hash(&mut hcx, &mut stable_hasher);
936                stable_hasher.finish()
937            })
938        });
939
940        self.arena.alloc(hir::OwnerInfo {
941            opt_hash,
942            nodes,
943            parenting,
944            attrs,
945            trait_map,
946            delayed_lints,
947            children,
948        })
949    }
950
951    /// This method allocates a new `HirId` for the given `NodeId`.
952    /// Take care not to call this method if the resulting `HirId` is then not
953    /// actually used in the HIR, as that would trigger an assertion in the
954    /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
955    /// properly. Calling the method twice with the same `NodeId` is also forbidden.
956    x;#[instrument(level = "debug", skip(self), ret)]
957    fn lower_node_id(&mut self, ast_node_id: NodeId) -> HirId {
958        assert_ne!(ast_node_id, DUMMY_NODE_ID);
959
960        let owner = self.current_hir_id_owner;
961        let local_id = self.item_local_id_counter;
962        assert_ne!(local_id, hir::ItemLocalId::ZERO);
963        self.item_local_id_counter.increment_by(1);
964        let hir_id = HirId { owner, local_id };
965
966        if let Some(def_id) = self.opt_local_def_id(ast_node_id) {
967            self.children.insert(def_id, hir::MaybeOwner::NonOwner(hir_id));
968        }
969
970        if let Some(traits) = self.owner.trait_map.get(&ast_node_id) {
971            self.trait_map.insert(hir_id.local_id, *traits);
972        }
973
974        // Check whether the same `NodeId` is lowered more than once.
975        #[cfg(debug_assertions)]
976        self.relowering_checker.assert_node_is_not_relowered(ast_node_id, local_id);
977
978        hir_id
979    }
980
981    /// Generate a new `HirId` without a backing `NodeId`.
982    x;#[instrument(level = "debug", skip(self), ret)]
983    fn next_id(&mut self) -> HirId {
984        let owner = self.current_hir_id_owner;
985        let local_id = self.item_local_id_counter;
986        assert_ne!(local_id, hir::ItemLocalId::ZERO);
987        self.item_local_id_counter.increment_by(1);
988        HirId { owner, local_id }
989    }
990
991    #[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(991u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["res"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Res = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let res: Result<Res, ()> =
                res.apply_id(|id|
                        {
                            let owner = self.current_hir_id_owner;
                            let local_id =
                                self.ident_and_label_to_local_id.get(&id).copied().ok_or(())?;
                            Ok(HirId { owner, local_id })
                        });
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:998",
                                    "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(998u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["res"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&res) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            res.unwrap_or(Res::Err)
        }
    }
}#[instrument(level = "trace", skip(self))]
992    fn lower_res(&mut self, res: Res<NodeId>) -> Res {
993        let res: Result<Res, ()> = res.apply_id(|id| {
994            let owner = self.current_hir_id_owner;
995            let local_id = self.ident_and_label_to_local_id.get(&id).copied().ok_or(())?;
996            Ok(HirId { owner, local_id })
997        });
998        trace!(?res);
999
1000        // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
1001        // This can happen when trying to lower the return type `x` in erroneous code like
1002        //   async fn foo(x: u8) -> x {}
1003        // In that case, `x` is lowered as a function parameter, and the return type is lowered as
1004        // an opaque type as a synthesized HIR owner.
1005        res.unwrap_or(Res::Err)
1006    }
1007
1008    fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
1009        self.get_partial_res(id).map_or(Res::Err, |pr| pr.expect_full_res())
1010    }
1011
1012    fn lower_import_res(&mut self, id: NodeId, span: Span) -> PerNS<Option<Res>> {
1013        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);
1014        let per_ns = self.owner.import_res.map(|res| res.map(|res| self.lower_res(res)));
1015        if per_ns.is_empty() {
1016            // Propagate the error to all namespaces, just to be sure.
1017            self.dcx().span_delayed_bug(span, "no resolution for an import");
1018            let err = Some(Res::Err);
1019            return PerNS { type_ns: err, value_ns: err, macro_ns: err };
1020        }
1021        per_ns
1022    }
1023
1024    fn make_lang_item_qpath(
1025        &mut self,
1026        lang_item: hir::LangItem,
1027        span: Span,
1028        args: Option<&'hir hir::GenericArgs<'hir>>,
1029    ) -> hir::QPath<'hir> {
1030        hir::QPath::Resolved(None, self.make_lang_item_path(lang_item, span, args))
1031    }
1032
1033    fn make_lang_item_path(
1034        &mut self,
1035        lang_item: hir::LangItem,
1036        span: Span,
1037        args: Option<&'hir hir::GenericArgs<'hir>>,
1038    ) -> &'hir hir::Path<'hir> {
1039        let def_id = self.tcx.require_lang_item(lang_item, span);
1040        let def_kind = self.tcx.def_kind(def_id);
1041        let res = Res::Def(def_kind, def_id);
1042        self.arena.alloc(hir::Path {
1043            span,
1044            res,
1045            segments: self.arena.alloc_from_iter([hir::PathSegment {
1046                ident: Ident::new(lang_item.name(), span),
1047                hir_id: self.next_id(),
1048                res,
1049                args,
1050                infer_args: args.is_none(),
1051                delegation_child_segment: false,
1052            }]),
1053        })
1054    }
1055
1056    /// Reuses the span but adds information like the kind of the desugaring and features that are
1057    /// allowed inside this span.
1058    fn mark_span_with_reason(
1059        &self,
1060        reason: DesugaringKind,
1061        span: Span,
1062        allow_internal_unstable: Option<Arc<[Symbol]>>,
1063    ) -> Span {
1064        self.tcx.with_stable_hashing_context(|hcx| {
1065            span.mark_with_reason(allow_internal_unstable, reason, span.edition(), hcx)
1066        })
1067    }
1068
1069    fn span_lowerer(&self) -> SpanLowerer {
1070        SpanLowerer {
1071            is_incremental: self.tcx.sess.opts.incremental.is_some(),
1072            def_id: self.current_hir_id_owner.def_id,
1073        }
1074    }
1075
1076    /// Intercept all spans entering HIR.
1077    /// Mark a span as relative to the current owning item.
1078    fn lower_span(&self, span: Span) -> Span {
1079        self.span_lowerer().lower(span)
1080    }
1081
1082    fn lower_ident(&self, ident: Ident) -> Ident {
1083        Ident::new(ident.name, self.lower_span(ident.span))
1084    }
1085
1086    /// Converts a lifetime into a new generic parameter.
1087    #[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(1087u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["ident", "node_id",
                                                    "kind", "source"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::GenericParam<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let _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:1102",
                                    "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(1102u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["_def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&_def_id) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            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))]
1088    fn lifetime_res_to_generic_param(
1089        &mut self,
1090        ident: Ident,
1091        node_id: NodeId,
1092        kind: MissingLifetimeKind,
1093        source: hir::GenericParamSource,
1094    ) -> hir::GenericParam<'hir> {
1095        // Late resolution delegates to us the creation of the `LocalDefId`.
1096        let _def_id = self.create_def(
1097            node_id,
1098            Some(kw::UnderscoreLifetime),
1099            DefKind::LifetimeParam,
1100            ident.span,
1101        );
1102        debug!(?_def_id);
1103
1104        let hir_id = self.lower_node_id(node_id);
1105        let def_id = self.local_def_id(node_id);
1106        hir::GenericParam {
1107            hir_id,
1108            def_id,
1109            name: hir::ParamName::Fresh,
1110            span: self.lower_span(ident.span),
1111            pure_wrt_drop: false,
1112            kind: hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided(kind) },
1113            colon_span: None,
1114            source,
1115        }
1116    }
1117
1118    /// Lowers a lifetime binder that defines `generic_params`, returning the corresponding HIR
1119    /// nodes. The returned list includes any "extra" lifetime parameters that were added by the
1120    /// name resolver owing to lifetime elision; this also populates the resolver's node-id->def-id
1121    /// map, so that later calls to `opt_node_id_to_def_id` that refer to these extra lifetime
1122    /// parameters will be successful.
1123    x;#[instrument(level = "debug", skip(self), ret)]
1124    #[inline]
1125    fn lower_lifetime_binder(
1126        &mut self,
1127        binder: NodeId,
1128        generic_params: &[GenericParam],
1129    ) -> &'hir [hir::GenericParam<'hir>] {
1130        // Start by creating params for extra lifetimes params, as this creates the definitions
1131        // that may be referred to by the AST inside `generic_params`.
1132        let extra_lifetimes = self.resolver.extra_lifetime_params(binder);
1133        debug!(?extra_lifetimes);
1134        let extra_lifetimes: Vec<_> = extra_lifetimes
1135            .iter()
1136            .map(|&(ident, node_id, res)| {
1137                self.lifetime_res_to_generic_param(
1138                    ident,
1139                    node_id,
1140                    res,
1141                    hir::GenericParamSource::Binder,
1142                )
1143            })
1144            .collect();
1145        let arena = self.arena;
1146        let explicit_generic_params =
1147            self.lower_generic_params_mut(generic_params, hir::GenericParamSource::Binder);
1148        arena.alloc_from_iter(explicit_generic_params.chain(extra_lifetimes.into_iter()))
1149    }
1150
1151    fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
1152        let was_in_dyn_type = self.is_in_dyn_type;
1153        self.is_in_dyn_type = in_scope;
1154
1155        let result = f(self);
1156
1157        self.is_in_dyn_type = was_in_dyn_type;
1158
1159        result
1160    }
1161
1162    fn with_new_scopes<T>(&mut self, scope_span: Span, f: impl FnOnce(&mut Self) -> T) -> T {
1163        let current_item = self.current_item;
1164        self.current_item = Some(scope_span);
1165
1166        let was_in_loop_condition = self.is_in_loop_condition;
1167        self.is_in_loop_condition = false;
1168
1169        let old_contract = self.contract_ensures.take();
1170
1171        let try_block_scope = mem::replace(&mut self.try_block_scope, TryBlockScope::Function);
1172        let loop_scope = self.loop_scope.take();
1173        let ret = f(self);
1174        self.try_block_scope = try_block_scope;
1175        self.loop_scope = loop_scope;
1176
1177        self.contract_ensures = old_contract;
1178
1179        self.is_in_loop_condition = was_in_loop_condition;
1180
1181        self.current_item = current_item;
1182
1183        ret
1184    }
1185
1186    fn lower_attrs(
1187        &mut self,
1188        id: HirId,
1189        attrs: &[Attribute],
1190        target_span: Span,
1191        target: Target,
1192    ) -> &'hir [hir::Attribute] {
1193        self.lower_attrs_with_extra(id, attrs, target_span, target, &[])
1194    }
1195
1196    fn lower_attrs_with_extra(
1197        &mut self,
1198        id: HirId,
1199        attrs: &[Attribute],
1200        target_span: Span,
1201        target: Target,
1202        extra_hir_attributes: &[hir::Attribute],
1203    ) -> &'hir [hir::Attribute] {
1204        if attrs.is_empty() && extra_hir_attributes.is_empty() {
1205            &[]
1206        } else {
1207            let mut lowered_attrs =
1208                self.lower_attrs_vec(attrs, self.lower_span(target_span), id, target);
1209            lowered_attrs.extend(extra_hir_attributes.iter().cloned());
1210
1211            {
    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);
1212            let ret = self.arena.alloc_from_iter(lowered_attrs);
1213
1214            // this is possible if an item contained syntactical attribute,
1215            // but none of them parse successfully or all of them were ignored
1216            // for not being built-in attributes at all. They could be remaining
1217            // unexpanded attributes used as markers in proc-macro derives for example.
1218            // This will have emitted some diagnostics for the misparse, but will then
1219            // not emit the attribute making the list empty.
1220            if ret.is_empty() {
1221                &[]
1222            } else {
1223                self.attrs.insert(id.local_id, ret);
1224                ret
1225            }
1226        }
1227    }
1228
1229    fn lower_attrs_vec(
1230        &mut self,
1231        attrs: &[Attribute],
1232        target_span: Span,
1233        target_hir_id: HirId,
1234        target: Target,
1235    ) -> Vec<hir::Attribute> {
1236        let l = self.span_lowerer();
1237        self.attribute_parser.parse_attribute_list(
1238            attrs,
1239            target_span,
1240            target,
1241            OmitDoc::Lower,
1242            |s| l.lower(s),
1243            |lint_id, span, kind| {
1244                self.delayed_lints.push(DelayedLint {
1245                    lint_id,
1246                    id: target_hir_id,
1247                    span,
1248                    callback: Box::new(move |dcx, level, sess: &dyn std::any::Any| {
1249                        let sess = sess
1250                            .downcast_ref::<rustc_session::Session>()
1251                            .expect("expected `Session`");
1252                        (kind.0)(dcx, level, sess)
1253                    }),
1254                });
1255            },
1256        )
1257    }
1258
1259    fn alias_attrs(&mut self, id: HirId, target_id: HirId) {
1260        {
    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);
1261        {
    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);
1262        if let Some(&a) = self.attrs.get(&target_id.local_id) {
1263            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
1264            self.attrs.insert(id.local_id, a);
1265        }
1266    }
1267
1268    fn lower_delim_args(&self, args: &DelimArgs) -> DelimArgs {
1269        args.clone()
1270    }
1271
1272    /// Lower an associated item constraint.
1273    #[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(1273u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::AssocItemConstraint<'hir> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:1279",
                                    "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(1279u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["constraint",
                                                    "itctx"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&constraint)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&itctx) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            let gen_args =
                if let Some(gen_args) = &constraint.gen_args {
                    let gen_args_ctor =
                        match gen_args {
                            GenericArgs::AngleBracketed(data) => {
                                self.lower_angle_bracketed_parameter_data(data,
                                        ParamMode::Explicit, itctx).0
                            }
                            GenericArgs::Parenthesized(data) => {
                                if let Some(first_char) =
                                            constraint.ident.as_str().chars().next() &&
                                        first_char.is_ascii_lowercase() {
                                    let err =
                                        match (&data.inputs[..], &data.output) {
                                            ([_, ..], FnRetTy::Default(_)) => {
                                                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)]
1274    fn lower_assoc_item_constraint(
1275        &mut self,
1276        constraint: &AssocItemConstraint,
1277        itctx: ImplTraitContext,
1278    ) -> hir::AssocItemConstraint<'hir> {
1279        debug!(?constraint, ?itctx);
1280        // Lower the generic arguments for the associated item.
1281        let gen_args = if let Some(gen_args) = &constraint.gen_args {
1282            let gen_args_ctor = match gen_args {
1283                GenericArgs::AngleBracketed(data) => {
1284                    self.lower_angle_bracketed_parameter_data(data, ParamMode::Explicit, itctx).0
1285                }
1286                GenericArgs::Parenthesized(data) => {
1287                    if let Some(first_char) = constraint.ident.as_str().chars().next()
1288                        && first_char.is_ascii_lowercase()
1289                    {
1290                        let err = match (&data.inputs[..], &data.output) {
1291                            ([_, ..], FnRetTy::Default(_)) => {
1292                                diagnostics::BadReturnTypeNotation::Inputs {
1293                                    span: data.inputs_span,
1294                                }
1295                            }
1296                            ([], FnRetTy::Default(_)) => {
1297                                diagnostics::BadReturnTypeNotation::NeedsDots {
1298                                    span: data.inputs_span,
1299                                }
1300                            }
1301                            // The case `T: Trait<method(..) -> Ret>` is handled in the parser.
1302                            (_, FnRetTy::Ty(ty)) => {
1303                                let span = data.inputs_span.shrink_to_hi().to(ty.span);
1304                                diagnostics::BadReturnTypeNotation::Output {
1305                                    span,
1306                                    suggestion: diagnostics::RTNSuggestion {
1307                                        output: span,
1308                                        input: data.inputs_span,
1309                                    },
1310                                }
1311                            }
1312                        };
1313                        let mut err = self.dcx().create_err(err);
1314                        if !self.tcx.features().return_type_notation()
1315                            && self.tcx.sess.is_nightly_build()
1316                        {
1317                            add_feature_diagnostics(
1318                                &mut err,
1319                                &self.tcx.sess,
1320                                sym::return_type_notation,
1321                            );
1322                        }
1323                        err.emit();
1324                        GenericArgsCtor {
1325                            args: Default::default(),
1326                            constraints: &[],
1327                            parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
1328                            span: data.span,
1329                        }
1330                    } else {
1331                        self.emit_bad_parenthesized_trait_in_assoc_ty(data);
1332                        self.lower_angle_bracketed_parameter_data(
1333                            &data.as_angle_bracketed_args(),
1334                            ParamMode::Explicit,
1335                            itctx,
1336                        )
1337                        .0
1338                    }
1339                }
1340                GenericArgs::ParenthesizedElided(span) => GenericArgsCtor {
1341                    args: Default::default(),
1342                    constraints: &[],
1343                    parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
1344                    span: *span,
1345                },
1346            };
1347            gen_args_ctor.into_generic_args(self)
1348        } else {
1349            hir::GenericArgs::NONE
1350        };
1351        let kind = match &constraint.kind {
1352            AssocItemConstraintKind::Equality { term } => {
1353                let term = match term {
1354                    Term::Ty(ty) => self.lower_ty_alloc(ty, itctx).into(),
1355                    Term::Const(c) => self.lower_anon_const_to_const_arg_and_alloc(c).into(),
1356                };
1357                hir::AssocItemConstraintKind::Equality { term }
1358            }
1359            AssocItemConstraintKind::Bound { bounds } => {
1360                // Disallow ATB in dyn types
1361                if self.is_in_dyn_type {
1362                    let suggestion = match itctx {
1363                        ImplTraitContext::OpaqueTy { .. } | ImplTraitContext::Universal => {
1364                            let bound_end_span = constraint
1365                                .gen_args
1366                                .as_ref()
1367                                .map_or(constraint.ident.span, |args| args.span());
1368                            if bound_end_span.eq_ctxt(constraint.span) {
1369                                Some(self.tcx.sess.source_map().next_point(bound_end_span))
1370                            } else {
1371                                None
1372                            }
1373                        }
1374                        _ => None,
1375                    };
1376
1377                    let guar = self.dcx().emit_err(diagnostics::MisplacedAssocTyBinding {
1378                        span: constraint.span,
1379                        suggestion,
1380                    });
1381                    let err_ty =
1382                        &*self.arena.alloc(self.ty(constraint.span, hir::TyKind::Err(guar)));
1383                    hir::AssocItemConstraintKind::Equality { term: err_ty.into() }
1384                } else {
1385                    let bounds = self.lower_param_bounds(
1386                        bounds,
1387                        RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::AssocTyBounds),
1388                        itctx,
1389                    );
1390                    hir::AssocItemConstraintKind::Bound { bounds }
1391                }
1392            }
1393        };
1394
1395        hir::AssocItemConstraint {
1396            hir_id: self.lower_node_id(constraint.id),
1397            ident: self.lower_ident(constraint.ident),
1398            gen_args,
1399            kind,
1400            span: self.lower_span(constraint.span),
1401        }
1402    }
1403
1404    fn emit_bad_parenthesized_trait_in_assoc_ty(&self, data: &ParenthesizedArgs) {
1405        // Suggest removing empty parentheses: "Trait()" -> "Trait"
1406        let sub = if data.inputs.is_empty() {
1407            let parentheses_span =
1408                data.inputs_span.shrink_to_lo().to(data.inputs_span.shrink_to_hi());
1409            AssocTyParenthesesSub::Empty { parentheses_span }
1410        }
1411        // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
1412        else {
1413            // Start of parameters to the 1st argument
1414            let open_param = data.inputs_span.shrink_to_lo().to(data
1415                .inputs
1416                .first()
1417                .unwrap()
1418                .span
1419                .shrink_to_lo());
1420            // End of last argument to end of parameters
1421            let close_param =
1422                data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi());
1423            AssocTyParenthesesSub::NotEmpty { open_param, close_param }
1424        };
1425        self.dcx().emit_err(AssocTyParentheses { span: data.span, sub });
1426    }
1427
1428    #[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(1428u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["arg", "itctx"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arg)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::GenericArg<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match arg {
                ast::GenericArg::Lifetime(lt) =>
                    GenericArg::Lifetime(self.lower_lifetime(lt,
                            LifetimeSource::Path {
                                angle_brackets: hir::AngleBrackets::Full,
                            }, lt.ident.into())),
                ast::GenericArg::Type(ty) => {
                    if ty.is_maybe_parenthesised_infer() {
                        return GenericArg::Infer(hir::InferArg {
                                    hir_id: self.lower_node_id(ty.id),
                                    span: self.lower_span(ty.span),
                                });
                    }
                    match &ty.kind {
                        TyKind::Path(None, path) => {
                            if let Some(res) =
                                    self.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:1465",
                                                            "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(1465u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                        ::tracing::__macro_support::Option::Some(&format_args!("lower_generic_arg: Lowering type argument as const argument: {0:?}",
                                                                                        ty) as &dyn Value))])
                                                });
                                        } else { ; }
                                    };
                                    let ct =
                                        self.lower_const_path_to_const_arg(path, res, ty.id,
                                            ty.span);
                                    return GenericArg::Const(ct.try_as_ambig_ct().unwrap());
                                }
                            }
                        }
                        TyKind::DirectConstArg(expr) if
                            self.tcx.features().min_generic_const_args() => {
                            let ct =
                                match self.can_lower_expr_to_const_arg_direct(expr) {
                                    Ok(()) => self.lower_expr_to_const_arg_direct(expr, None),
                                    Err(e) => e.emit(self),
                                };
                            let ct = self.arena.alloc(ct);
                            return GenericArg::Const(ct.try_as_ambig_ct().unwrap());
                        }
                        _ => {}
                    }
                    GenericArg::Type(self.lower_ty_alloc(ty,
                                    itctx).try_as_ambig_ty().unwrap())
                }
                ast::GenericArg::Const(ct) => {
                    let ct = self.lower_anon_const_to_const_arg_and_alloc(ct);
                    match ct.try_as_ambig_ct() {
                        Some(ct) => GenericArg::Const(ct),
                        None =>
                            GenericArg::Infer(hir::InferArg {
                                    hir_id: ct.hir_id,
                                    span: ct.span,
                                }),
                    }
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1429    fn lower_generic_arg(
1430        &mut self,
1431        arg: &ast::GenericArg,
1432        itctx: ImplTraitContext,
1433    ) -> hir::GenericArg<'hir> {
1434        match arg {
1435            ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(
1436                lt,
1437                LifetimeSource::Path { angle_brackets: hir::AngleBrackets::Full },
1438                lt.ident.into(),
1439            )),
1440            ast::GenericArg::Type(ty) => {
1441                // We cannot just match on `TyKind::Infer` as `(_)` is represented as
1442                // `TyKind::Paren(TyKind::Infer)` and should also be lowered to `GenericArg::Infer`
1443                if ty.is_maybe_parenthesised_infer() {
1444                    return GenericArg::Infer(hir::InferArg {
1445                        hir_id: self.lower_node_id(ty.id),
1446                        span: self.lower_span(ty.span),
1447                    });
1448                }
1449
1450                match &ty.kind {
1451                    // We parse const arguments as path types as we cannot distinguish them during
1452                    // parsing. We try to resolve that ambiguity by attempting resolution in both the
1453                    // type and value namespaces. If we resolved the path in the value namespace, we
1454                    // transform it into a generic const argument.
1455                    //
1456                    // FIXME: Should we be handling `(PATH_TO_CONST)`?
1457                    TyKind::Path(None, path) => {
1458                        if let Some(res) = self
1459                            .get_partial_res(ty.id)
1460                            .and_then(|partial_res| partial_res.full_res())
1461                        {
1462                            if !res.matches_ns(Namespace::TypeNS)
1463                                && path.is_potential_trivial_const_arg()
1464                            {
1465                                debug!(
1466                                    "lower_generic_arg: Lowering type argument as const argument: {:?}",
1467                                    ty,
1468                                );
1469
1470                                let ct =
1471                                    self.lower_const_path_to_const_arg(path, res, ty.id, ty.span);
1472                                return GenericArg::Const(ct.try_as_ambig_ct().unwrap());
1473                            }
1474                        }
1475                    }
1476                    TyKind::DirectConstArg(expr)
1477                        if self.tcx.features().min_generic_const_args() =>
1478                    {
1479                        let ct = match self.can_lower_expr_to_const_arg_direct(expr) {
1480                            Ok(()) => self.lower_expr_to_const_arg_direct(expr, None),
1481                            Err(e) => e.emit(self),
1482                        };
1483                        let ct = self.arena.alloc(ct);
1484                        return GenericArg::Const(ct.try_as_ambig_ct().unwrap());
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(&["t", "itctx"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&t)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'hir hir::Ty<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        { self.arena.alloc(self.lower_ty(t, itctx)) }
    }
}#[instrument(level = "debug", skip(self))]
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(_) => {
1764                let e = self
1765                    .tcx
1766                    .dcx()
1767                    .struct_span_err(t.span, "expected type, found `direct_const_arg!()` constant")
1768                    .emit();
1769                hir::TyKind::Err(e)
1770            }
1771            TyKind::Dummy => {
    ::core::panicking::panic_fmt(format_args!("`TyKind::Dummy` should never be lowered"));
}panic!("`TyKind::Dummy` should never be lowered"),
1772        };
1773
1774        hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1775    }
1776
1777    fn lower_ty_direct_lifetime(
1778        &mut self,
1779        t: &Ty,
1780        region: Option<Lifetime>,
1781    ) -> &'hir hir::Lifetime {
1782        let (region, syntax) = match region {
1783            Some(region) => (region, region.ident.into()),
1784
1785            None => {
1786                let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1787                    self.owner.get_lifetime_res(t.id)
1788                {
1789                    {
    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);
1790                    start
1791                } else {
1792                    self.next_node_id()
1793                };
1794                let span = self.tcx.sess.source_map().start_point(t.span).shrink_to_hi();
1795                let region = Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id };
1796                (region, LifetimeSyntax::Implicit)
1797            }
1798        };
1799        self.lower_lifetime(&region, LifetimeSource::Reference, syntax)
1800    }
1801
1802    /// Lowers a `ReturnPositionOpaqueTy` (`-> impl Trait`) or a `TypeAliasesOpaqueTy` (`type F =
1803    /// impl Trait`): this creates the associated Opaque Type (TAIT) definition and then returns a
1804    /// HIR type that references the TAIT.
1805    ///
1806    /// Given a function definition like:
1807    ///
1808    /// ```rust
1809    /// use std::fmt::Debug;
1810    ///
1811    /// fn test<'a, T: Debug>(x: &'a T) -> impl Debug + 'a {
1812    ///     x
1813    /// }
1814    /// ```
1815    ///
1816    /// we will create a TAIT definition in the HIR like
1817    ///
1818    /// ```rust,ignore (pseudo-Rust)
1819    /// type TestReturn<'a, T, 'x> = impl Debug + 'x
1820    /// ```
1821    ///
1822    /// and return a type like `TestReturn<'static, T, 'a>`, so that the function looks like:
1823    ///
1824    /// ```rust,ignore (pseudo-Rust)
1825    /// fn test<'a, T: Debug>(x: &'a T) -> TestReturn<'static, T, 'a>
1826    /// ```
1827    ///
1828    /// Note the subtlety around type parameters! The new TAIT, `TestReturn`, inherits all the
1829    /// type parameters from the function `test` (this is implemented in the query layer, they aren't
1830    /// added explicitly in the HIR). But this includes all the lifetimes, and we only want to
1831    /// capture the lifetimes that are referenced in the bounds. Therefore, we add *extra* lifetime parameters
1832    /// for the lifetimes that get captured (`'x`, in our example above) and reference those.
1833    x;#[instrument(level = "debug", skip(self), ret)]
1834    fn lower_opaque_impl_trait(
1835        &mut self,
1836        span: Span,
1837        origin: hir::OpaqueTyOrigin<LocalDefId>,
1838        opaque_ty_node_id: NodeId,
1839        bounds: &GenericBounds,
1840        itctx: ImplTraitContext,
1841    ) -> hir::TyKind<'hir> {
1842        // Make sure we know that some funky desugaring has been going on here.
1843        // This is a first: there is code in other places like for loop
1844        // desugaring that explicitly states that we don't want to track that.
1845        // Not tracking it makes lints in rustc and clippy very fragile, as
1846        // frequently opened issues show.
1847        let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1848
1849        self.lower_opaque_inner(opaque_ty_node_id, origin, opaque_ty_span, |this| {
1850            this.lower_param_bounds(
1851                bounds,
1852                RelaxedBoundPolicy::Allowed(&mut Default::default()),
1853                itctx,
1854            )
1855        })
1856    }
1857
1858    fn lower_opaque_inner(
1859        &mut self,
1860        opaque_ty_node_id: NodeId,
1861        origin: hir::OpaqueTyOrigin<LocalDefId>,
1862        opaque_ty_span: Span,
1863        lower_item_bounds: impl FnOnce(&mut Self) -> &'hir [hir::GenericBound<'hir>],
1864    ) -> hir::TyKind<'hir> {
1865        let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id);
1866        let opaque_ty_hir_id = self.lower_node_id(opaque_ty_node_id);
1867        {
    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:1867",
                        "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(1867u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                        ::tracing_core::field::FieldSet::new(&["opaque_ty_def_id",
                                        "opaque_ty_hir_id"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&opaque_ty_def_id)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&opaque_ty_hir_id)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?opaque_ty_def_id, ?opaque_ty_hir_id);
1868
1869        let bounds = lower_item_bounds(self);
1870        let opaque_ty_def = hir::OpaqueTy {
1871            hir_id: opaque_ty_hir_id,
1872            def_id: opaque_ty_def_id,
1873            bounds,
1874            origin,
1875            span: self.lower_span(opaque_ty_span),
1876        };
1877        let opaque_ty_def = self.arena.alloc(opaque_ty_def);
1878
1879        hir::TyKind::OpaqueDef(opaque_ty_def)
1880    }
1881
1882    fn lower_precise_capturing_args(
1883        &mut self,
1884        precise_capturing_args: &[PreciseCapturingArg],
1885    ) -> &'hir [hir::PreciseCapturingArg<'hir>] {
1886        self.arena.alloc_from_iter(precise_capturing_args.iter().map(|arg| match arg {
1887            PreciseCapturingArg::Lifetime(lt) => hir::PreciseCapturingArg::Lifetime(
1888                self.lower_lifetime(lt, LifetimeSource::PreciseCapturing, lt.ident.into()),
1889            ),
1890            PreciseCapturingArg::Arg(path, id) => {
1891                let [segment] = path.segments.as_slice() else {
1892                    ::core::panicking::panic("explicit panic");panic!();
1893                };
1894                let res = self.get_partial_res(*id).map_or(Res::Err, |partial_res| {
1895                    partial_res.full_res().expect("no partial res expected for precise capture arg")
1896                });
1897                hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
1898                    hir_id: self.lower_node_id(*id),
1899                    ident: self.lower_ident(segment.ident),
1900                    res: self.lower_res(res),
1901                })
1902            }
1903        }))
1904    }
1905
1906    fn lower_fn_params_to_idents(&mut self, decl: &FnDecl) -> &'hir [Option<Ident>] {
1907        self.arena.alloc_from_iter(decl.inputs.iter().map(|param| match param.pat.kind {
1908            PatKind::Missing => None,
1909            PatKind::Ident(_, ident, _) => Some(self.lower_ident(ident)),
1910            PatKind::Wild => Some(Ident::new(kw::Underscore, self.lower_span(param.pat.span))),
1911            _ => {
1912                self.dcx().span_delayed_bug(
1913                    param.pat.span,
1914                    "non-missing/ident/wild param pat must trigger an error",
1915                );
1916                None
1917            }
1918        }))
1919    }
1920
1921    /// Lowers a function declaration.
1922    ///
1923    /// `decl`: the unlowered (AST) function declaration.
1924    ///
1925    /// `fn_node_id`: `impl Trait` arguments are lowered into generic parameters on the given
1926    /// `NodeId`.
1927    ///
1928    /// `transform_return_type`: if `Some`, applies some conversion to the return type, such as is
1929    /// needed for `async fn` and `gen fn`. See [`CoroutineKind`] for more details.
1930    #[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(1930u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["decl", "fn_node_id",
                                                    "fn_span", "kind", "coro"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&decl)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_node_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coro)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'hir hir::FnDecl<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let c_variadic = decl.c_variadic();
            let mut 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))]
1931    fn lower_fn_decl(
1932        &mut self,
1933        decl: &FnDecl,
1934        fn_node_id: NodeId,
1935        fn_span: Span,
1936        kind: FnDeclKind,
1937        coro: Option<CoroutineKind>,
1938    ) -> &'hir hir::FnDecl<'hir> {
1939        let c_variadic = decl.c_variadic();
1940        let mut splatted = decl.splatted();
1941
1942        // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1943        // as they are not explicit in HIR/Ty function signatures.
1944        // (instead, the `c_variadic` flag is set to `true`)
1945        let mut inputs = &decl.inputs[..];
1946        if decl.c_variadic() {
1947            // Splat + variadic errors in AST validation, so just ignore one of them here.
1948            splatted = None;
1949            inputs = &inputs[..inputs.len() - 1];
1950        }
1951        let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1952            let itctx = match kind {
1953                FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait => {
1954                    ImplTraitContext::Universal
1955                }
1956                FnDeclKind::ExternFn => {
1957                    ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnParam)
1958                }
1959                FnDeclKind::Closure => {
1960                    ImplTraitContext::Disallowed(ImplTraitPosition::ClosureParam)
1961                }
1962                FnDeclKind::Pointer => {
1963                    ImplTraitContext::Disallowed(ImplTraitPosition::PointerParam)
1964                }
1965            };
1966            self.lower_ty(&param.ty, itctx)
1967        }));
1968
1969        let output = match coro {
1970            Some(coro) => {
1971                let fn_def_id = self.owner.def_id;
1972                self.lower_coroutine_fn_ret_ty(&decl.output, fn_def_id, coro, kind)
1973            }
1974            None => match &decl.output {
1975                FnRetTy::Ty(ty) => {
1976                    let itctx = match kind {
1977                        FnDeclKind::Fn | FnDeclKind::Inherent => ImplTraitContext::OpaqueTy {
1978                            origin: hir::OpaqueTyOrigin::FnReturn {
1979                                parent: self.owner.def_id,
1980                                in_trait_or_impl: None,
1981                            },
1982                        },
1983                        FnDeclKind::Trait => ImplTraitContext::OpaqueTy {
1984                            origin: hir::OpaqueTyOrigin::FnReturn {
1985                                parent: self.owner.def_id,
1986                                in_trait_or_impl: Some(hir::RpitContext::Trait),
1987                            },
1988                        },
1989                        FnDeclKind::Impl => ImplTraitContext::OpaqueTy {
1990                            origin: hir::OpaqueTyOrigin::FnReturn {
1991                                parent: self.owner.def_id,
1992                                in_trait_or_impl: Some(hir::RpitContext::TraitImpl),
1993                            },
1994                        },
1995                        FnDeclKind::ExternFn => {
1996                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnReturn)
1997                        }
1998                        FnDeclKind::Closure => {
1999                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureReturn)
2000                        }
2001                        FnDeclKind::Pointer => {
2002                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerReturn)
2003                        }
2004                    };
2005                    hir::FnRetTy::Return(self.lower_ty_alloc(ty, itctx))
2006                }
2007                FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(*span)),
2008            },
2009        };
2010
2011        let fn_decl_kind = hir::FnDeclFlags::default()
2012            .set_implicit_self(decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
2013                let is_mutable_pat = matches!(
2014                    arg.pat.kind,
2015                    PatKind::Ident(hir::BindingMode(_, Mutability::Mut), ..)
2016                );
2017
2018                match &arg.ty.kind {
2019                    TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
2020                    TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
2021                    // Given we are only considering `ImplicitSelf` types, we needn't consider
2022                    // the case where we have a mutable pattern to a reference as that would
2023                    // no longer be an `ImplicitSelf`.
2024                    TyKind::Ref(_, mt) | TyKind::PinnedRef(_, mt)
2025                        if mt.ty.kind.is_implicit_self() =>
2026                    {
2027                        match mt.mutbl {
2028                            hir::Mutability::Not => hir::ImplicitSelfKind::RefImm,
2029                            hir::Mutability::Mut => hir::ImplicitSelfKind::RefMut,
2030                        }
2031                    }
2032                    _ => hir::ImplicitSelfKind::None,
2033                }
2034            }))
2035            .set_lifetime_elision_allowed(
2036                self.owner.id == fn_node_id && self.owner.lifetime_elision_allowed,
2037            )
2038            .set_c_variadic(c_variadic)
2039            .set_splatted(splatted, inputs.len())
2040            .unwrap();
2041
2042        self.arena.alloc(hir::FnDecl { inputs, output, fn_decl_kind })
2043    }
2044
2045    // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
2046    // combined with the following definition of `OpaqueTy`:
2047    //
2048    //     type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
2049    //
2050    // `output`: unlowered output type (`T` in `-> T`)
2051    // `fn_node_id`: `NodeId` of the parent function (used to create child impl trait definition)
2052    // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
2053    #[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(2053u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["output",
                                                    "fn_def_id", "coro", "fn_kind"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&output)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coro)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_kind)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::FnRetTy<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let span = self.lower_span(output.span());
            let (opaque_ty_node_id, allowed_features) =
                match coro {
                    CoroutineKind::Async { return_impl_trait_id, .. } =>
                        (return_impl_trait_id, None),
                    CoroutineKind::Gen { return_impl_trait_id, .. } =>
                        (return_impl_trait_id, None),
                    CoroutineKind::AsyncGen { return_impl_trait_id, .. } => {
                        (return_impl_trait_id,
                            Some(Arc::clone(&self.allow_async_iterator)))
                    }
                };
            let opaque_ty_span =
                self.mark_span_with_reason(DesugaringKind::Async, span,
                    allowed_features);
            let in_trait_or_impl =
                match fn_kind {
                    FnDeclKind::Trait => Some(hir::RpitContext::Trait),
                    FnDeclKind::Impl => Some(hir::RpitContext::TraitImpl),
                    FnDeclKind::Fn | FnDeclKind::Inherent => None,
                    FnDeclKind::ExternFn | FnDeclKind::Closure |
                        FnDeclKind::Pointer =>
                        ::core::panicking::panic("internal error: entered unreachable code"),
                };
            let opaque_ty_ref =
                self.lower_opaque_inner(opaque_ty_node_id,
                    hir::OpaqueTyOrigin::AsyncFn {
                        parent: fn_def_id,
                        in_trait_or_impl,
                    }, opaque_ty_span,
                    |this|
                        {
                            let bound =
                                this.lower_coroutine_fn_output_type_to_bound(output, coro,
                                    opaque_ty_span,
                                    ImplTraitContext::OpaqueTy {
                                        origin: hir::OpaqueTyOrigin::FnReturn {
                                            parent: fn_def_id,
                                            in_trait_or_impl,
                                        },
                                    });
                            this.arena.alloc_from_iter([bound])
                        });
            let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
            hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
        }
    }
}#[instrument(level = "debug", skip(self))]
2054    fn lower_coroutine_fn_ret_ty(
2055        &mut self,
2056        output: &FnRetTy,
2057        fn_def_id: LocalDefId,
2058        coro: CoroutineKind,
2059        fn_kind: FnDeclKind,
2060    ) -> hir::FnRetTy<'hir> {
2061        let span = self.lower_span(output.span());
2062
2063        let (opaque_ty_node_id, allowed_features) = match coro {
2064            CoroutineKind::Async { return_impl_trait_id, .. } => (return_impl_trait_id, None),
2065            CoroutineKind::Gen { return_impl_trait_id, .. } => (return_impl_trait_id, None),
2066            CoroutineKind::AsyncGen { return_impl_trait_id, .. } => {
2067                (return_impl_trait_id, Some(Arc::clone(&self.allow_async_iterator)))
2068            }
2069        };
2070
2071        let opaque_ty_span =
2072            self.mark_span_with_reason(DesugaringKind::Async, span, allowed_features);
2073
2074        let in_trait_or_impl = match fn_kind {
2075            FnDeclKind::Trait => Some(hir::RpitContext::Trait),
2076            FnDeclKind::Impl => Some(hir::RpitContext::TraitImpl),
2077            FnDeclKind::Fn | FnDeclKind::Inherent => None,
2078            FnDeclKind::ExternFn | FnDeclKind::Closure | FnDeclKind::Pointer => unreachable!(),
2079        };
2080
2081        let opaque_ty_ref = self.lower_opaque_inner(
2082            opaque_ty_node_id,
2083            hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, in_trait_or_impl },
2084            opaque_ty_span,
2085            |this| {
2086                let bound = this.lower_coroutine_fn_output_type_to_bound(
2087                    output,
2088                    coro,
2089                    opaque_ty_span,
2090                    ImplTraitContext::OpaqueTy {
2091                        origin: hir::OpaqueTyOrigin::FnReturn {
2092                            parent: fn_def_id,
2093                            in_trait_or_impl,
2094                        },
2095                    },
2096                );
2097                arena_vec![this; bound]
2098            },
2099        );
2100
2101        let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2102        hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
2103    }
2104
2105    /// Transforms `-> T` into `Future<Output = T>`.
2106    fn lower_coroutine_fn_output_type_to_bound(
2107        &mut self,
2108        output: &FnRetTy,
2109        coro: CoroutineKind,
2110        opaque_ty_span: Span,
2111        itctx: ImplTraitContext,
2112    ) -> hir::GenericBound<'hir> {
2113        // Compute the `T` in `Future<Output = T>` from the return type.
2114        let output_ty = match output {
2115            FnRetTy::Ty(ty) => {
2116                // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
2117                // `impl Future` opaque type that `async fn` implicitly
2118                // generates.
2119                self.lower_ty_alloc(ty, itctx)
2120            }
2121            FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
2122        };
2123
2124        // "<$assoc_ty_name = T>"
2125        let (assoc_ty_name, trait_lang_item) = match coro {
2126            CoroutineKind::Async { .. } => (sym::Output, hir::LangItem::Future),
2127            CoroutineKind::Gen { .. } => (sym::Item, hir::LangItem::Iterator),
2128            CoroutineKind::AsyncGen { .. } => (sym::Item, hir::LangItem::AsyncIterator),
2129        };
2130
2131        let bound_args = self.arena.alloc(hir::GenericArgs {
2132            args: &[],
2133            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)],
2134            parenthesized: hir::GenericArgsParentheses::No,
2135            span_ext: DUMMY_SP,
2136        });
2137
2138        hir::GenericBound::Trait(hir::PolyTraitRef {
2139            bound_generic_params: &[],
2140            modifiers: hir::TraitBoundModifiers::NONE,
2141            trait_ref: hir::TraitRef {
2142                path: self.make_lang_item_path(trait_lang_item, opaque_ty_span, Some(bound_args)),
2143                hir_ref_id: self.next_id(),
2144            },
2145            span: opaque_ty_span,
2146        })
2147    }
2148
2149    #[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(2149u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["tpb", "rbp",
                                                    "itctx"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tpb)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rbp)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::GenericBound<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match tpb {
                GenericBound::Trait(p) => {
                    hir::GenericBound::Trait(self.lower_poly_trait_ref(p, rbp,
                            itctx))
                }
                GenericBound::Outlives(lifetime) =>
                    hir::GenericBound::Outlives(self.lower_lifetime(lifetime,
                            LifetimeSource::OutlivesBound, lifetime.ident.into())),
                GenericBound::Use(args, span) =>
                    hir::GenericBound::Use(self.lower_precise_capturing_args(args),
                        self.lower_span(*span)),
            }
        }
    }
}#[instrument(level = "trace", skip(self))]
2150    fn lower_param_bound(
2151        &mut self,
2152        tpb: &GenericBound,
2153        rbp: RelaxedBoundPolicy<'_>,
2154        itctx: ImplTraitContext,
2155    ) -> hir::GenericBound<'hir> {
2156        match tpb {
2157            GenericBound::Trait(p) => {
2158                hir::GenericBound::Trait(self.lower_poly_trait_ref(p, rbp, itctx))
2159            }
2160            GenericBound::Outlives(lifetime) => hir::GenericBound::Outlives(self.lower_lifetime(
2161                lifetime,
2162                LifetimeSource::OutlivesBound,
2163                lifetime.ident.into(),
2164            )),
2165            GenericBound::Use(args, span) => hir::GenericBound::Use(
2166                self.lower_precise_capturing_args(args),
2167                self.lower_span(*span),
2168            ),
2169        }
2170    }
2171
2172    fn lower_lifetime(
2173        &mut self,
2174        l: &Lifetime,
2175        source: LifetimeSource,
2176        syntax: LifetimeSyntax,
2177    ) -> &'hir hir::Lifetime {
2178        self.new_named_lifetime(l.id, l.id, l.ident, source, syntax)
2179    }
2180
2181    fn lower_lifetime_hidden_in_path(
2182        &mut self,
2183        id: NodeId,
2184        span: Span,
2185        angle_brackets: AngleBrackets,
2186    ) -> &'hir hir::Lifetime {
2187        self.new_named_lifetime(
2188            id,
2189            id,
2190            Ident::new(kw::UnderscoreLifetime, span),
2191            LifetimeSource::Path { angle_brackets },
2192            LifetimeSyntax::Implicit,
2193        )
2194    }
2195
2196    #[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(2196u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["id", "new_id",
                                                    "ident", "source", "syntax"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&new_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&syntax)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'hir hir::Lifetime = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let res =
                if let Some(res) = self.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:2230",
                                    "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(2230u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["res"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&res) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            self.arena.alloc(hir::Lifetime::new(self.lower_node_id(new_id),
                    self.lower_ident(ident), res, source, syntax))
        }
    }
}#[instrument(level = "debug", skip(self))]
2197    fn new_named_lifetime(
2198        &mut self,
2199        id: NodeId,
2200        new_id: NodeId,
2201        ident: Ident,
2202        source: LifetimeSource,
2203        syntax: LifetimeSyntax,
2204    ) -> &'hir hir::Lifetime {
2205        let res = if let Some(res) = self.owner.get_lifetime_res(id) {
2206            match res {
2207                LifetimeRes::Param { param, .. } => hir::LifetimeKind::Param(param),
2208                LifetimeRes::Fresh { param, .. } => {
2209                    assert_eq!(ident.name, kw::UnderscoreLifetime);
2210                    let param = self.local_def_id(param);
2211                    hir::LifetimeKind::Param(param)
2212                }
2213                LifetimeRes::Infer => {
2214                    assert_eq!(ident.name, kw::UnderscoreLifetime);
2215                    hir::LifetimeKind::Infer
2216                }
2217                LifetimeRes::Static { .. } => {
2218                    assert!(matches!(ident.name, kw::StaticLifetime | kw::UnderscoreLifetime));
2219                    hir::LifetimeKind::Static
2220                }
2221                LifetimeRes::Error(guar) => hir::LifetimeKind::Error(guar),
2222                LifetimeRes::ElidedAnchor { .. } => {
2223                    panic!("Unexpected `ElidedAnchar` {:?} at {:?}", ident, ident.span);
2224                }
2225            }
2226        } else {
2227            hir::LifetimeKind::Error(self.dcx().span_delayed_bug(ident.span, "unresolved lifetime"))
2228        };
2229
2230        debug!(?res);
2231        self.arena.alloc(hir::Lifetime::new(
2232            self.lower_node_id(new_id),
2233            self.lower_ident(ident),
2234            res,
2235            source,
2236            syntax,
2237        ))
2238    }
2239
2240    fn lower_generic_params_mut(
2241        &mut self,
2242        params: &[GenericParam],
2243        source: hir::GenericParamSource,
2244    ) -> impl Iterator<Item = hir::GenericParam<'hir>> {
2245        params.iter().map(move |param| self.lower_generic_param(param, source))
2246    }
2247
2248    fn lower_generic_params(
2249        &mut self,
2250        params: &[GenericParam],
2251        source: hir::GenericParamSource,
2252    ) -> &'hir [hir::GenericParam<'hir>] {
2253        self.arena.alloc_from_iter(self.lower_generic_params_mut(params, source))
2254    }
2255
2256    #[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(2256u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["param", "source"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::GenericParam<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (name, kind) = self.lower_generic_param_kind(param, source);
            let hir_id = self.lower_node_id(param.id);
            let param_attrs = &param.attrs;
            let param_span = param.span();
            let param =
                hir::GenericParam {
                    hir_id,
                    def_id: self.local_def_id(param.id),
                    name,
                    span: self.lower_span(param.span()),
                    pure_wrt_drop: attr::contains_name(&param.attrs,
                        sym::may_dangle),
                    kind,
                    colon_span: param.colon_span.map(|s| self.lower_span(s)),
                    source,
                };
            self.lower_attrs(hir_id, param_attrs, param_span,
                Target::from_generic_param(&param));
            param
        }
    }
}#[instrument(level = "trace", skip(self))]
2257    fn lower_generic_param(
2258        &mut self,
2259        param: &GenericParam,
2260        source: hir::GenericParamSource,
2261    ) -> hir::GenericParam<'hir> {
2262        let (name, kind) = self.lower_generic_param_kind(param, source);
2263
2264        let hir_id = self.lower_node_id(param.id);
2265        let param_attrs = &param.attrs;
2266        let param_span = param.span();
2267        let param = hir::GenericParam {
2268            hir_id,
2269            def_id: self.local_def_id(param.id),
2270            name,
2271            span: self.lower_span(param.span()),
2272            pure_wrt_drop: attr::contains_name(&param.attrs, sym::may_dangle),
2273            kind,
2274            colon_span: param.colon_span.map(|s| self.lower_span(s)),
2275            source,
2276        };
2277        self.lower_attrs(hir_id, param_attrs, param_span, Target::from_generic_param(&param));
2278        param
2279    }
2280
2281    fn lower_generic_param_kind(
2282        &mut self,
2283        param: &GenericParam,
2284        source: hir::GenericParamSource,
2285    ) -> (hir::ParamName, hir::GenericParamKind<'hir>) {
2286        match &param.kind {
2287            GenericParamKind::Lifetime => {
2288                // AST resolution emitted an error on those parameters, so we lower them using
2289                // `ParamName::Error`.
2290                let ident = self.lower_ident(param.ident);
2291                let param_name =
2292                    if let Some(LifetimeRes::Error(..)) = self.owner.get_lifetime_res(param.id) {
2293                        ParamName::Error(ident)
2294                    } else {
2295                        ParamName::Plain(ident)
2296                    };
2297                let kind =
2298                    hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2299
2300                (param_name, kind)
2301            }
2302            GenericParamKind::Type { default, .. } => {
2303                // Not only do we deny type param defaults in binders but we also map them to `None`
2304                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2305                let default = default
2306                    .as_ref()
2307                    .filter(|_| match source {
2308                        hir::GenericParamSource::Generics => true,
2309                        hir::GenericParamSource::Binder => {
2310                            self.dcx().emit_err(diagnostics::GenericParamDefaultInBinder {
2311                                span: param.span(),
2312                            });
2313
2314                            false
2315                        }
2316                    })
2317                    .map(|def| {
2318                        self.lower_ty_alloc(
2319                            def,
2320                            ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2321                        )
2322                    });
2323
2324                let kind = hir::GenericParamKind::Type { default, synthetic: false };
2325
2326                (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2327            }
2328            GenericParamKind::Const { ty, span: _, default } => {
2329                let ty = self.lower_ty_alloc(
2330                    ty,
2331                    ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2332                );
2333
2334                // Not only do we deny const param defaults in binders but we also map them to `None`
2335                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2336                let default = default
2337                    .as_ref()
2338                    .filter(|anon_const| match source {
2339                        hir::GenericParamSource::Generics => true,
2340                        hir::GenericParamSource::Binder => {
2341                            let err =
2342                                diagnostics::GenericParamDefaultInBinder { span: param.span() };
2343                            if expr::WillCreateDefIdsVisitor
2344                                .visit_expr(&anon_const.value)
2345                                .is_break()
2346                            {
2347                                // FIXME(mgca): make this non-fatal once we have a better way
2348                                // to handle nested items in anno const from binder
2349                                // Issue: https://github.com/rust-lang/rust/issues/123629
2350                                self.dcx().emit_fatal(err)
2351                            } else {
2352                                self.dcx().emit_err(err);
2353                                false
2354                            }
2355                        }
2356                    })
2357                    .map(|def| self.lower_anon_const_to_const_arg_and_alloc(def));
2358
2359                (
2360                    hir::ParamName::Plain(self.lower_ident(param.ident)),
2361                    hir::GenericParamKind::Const { ty, default },
2362                )
2363            }
2364        }
2365    }
2366
2367    fn lower_trait_ref(
2368        &mut self,
2369        modifiers: ast::TraitBoundModifiers,
2370        p: &TraitRef,
2371        itctx: ImplTraitContext,
2372    ) -> hir::TraitRef<'hir> {
2373        let path = match self.lower_qpath(
2374            p.ref_id,
2375            &None,
2376            &p.path,
2377            ParamMode::Explicit,
2378            AllowReturnTypeNotation::No,
2379            itctx,
2380            Some(modifiers),
2381        ) {
2382            hir::QPath::Resolved(None, path) => path,
2383            qpath => {
    ::core::panicking::panic_fmt(format_args!("lower_trait_ref: unexpected QPath `{0:?}`",
            qpath));
}panic!("lower_trait_ref: unexpected QPath `{qpath:?}`"),
2384        };
2385        hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2386    }
2387
2388    #[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(2388u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["bound_generic_params",
                                                    "modifiers", "trait_ref", "span", "rbp", "itctx"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_generic_params)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&modifiers)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rbp)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::PolyTraitRef<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let bound_generic_params =
                self.lower_lifetime_binder(trait_ref.ref_id,
                    bound_generic_params);
            let trait_ref =
                self.lower_trait_ref(*modifiers, trait_ref, itctx);
            let modifiers = self.lower_trait_bound_modifiers(*modifiers);
            if let ast::BoundPolarity::Maybe(_) = modifiers.polarity {
                self.validate_relaxed_bound(trait_ref, *span, rbp);
            }
            hir::PolyTraitRef {
                bound_generic_params,
                modifiers,
                trait_ref,
                span: self.lower_span(*span),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2389    fn lower_poly_trait_ref(
2390        &mut self,
2391        PolyTraitRef { bound_generic_params, modifiers, trait_ref, span, parens: _ }: &PolyTraitRef,
2392        rbp: RelaxedBoundPolicy<'_>,
2393        itctx: ImplTraitContext,
2394    ) -> hir::PolyTraitRef<'hir> {
2395        let bound_generic_params =
2396            self.lower_lifetime_binder(trait_ref.ref_id, bound_generic_params);
2397        let trait_ref = self.lower_trait_ref(*modifiers, trait_ref, itctx);
2398        let modifiers = self.lower_trait_bound_modifiers(*modifiers);
2399
2400        if let ast::BoundPolarity::Maybe(_) = modifiers.polarity {
2401            self.validate_relaxed_bound(trait_ref, *span, rbp);
2402        }
2403
2404        hir::PolyTraitRef {
2405            bound_generic_params,
2406            modifiers,
2407            trait_ref,
2408            span: self.lower_span(*span),
2409        }
2410    }
2411
2412    fn validate_relaxed_bound(
2413        &self,
2414        trait_ref: hir::TraitRef<'_>,
2415        span: Span,
2416        rbp: RelaxedBoundPolicy<'_>,
2417    ) {
2418        // Even though feature `more_maybe_bounds` enables the user to relax all default bounds
2419        // other than `Sized` in a lot more positions (thereby bypassing the given policy), we don't
2420        // want to advertise it to the user (via a feature gate error) since it's super internal.
2421        //
2422        // FIXME(more_maybe_bounds): Moreover, if we actually were to add proper default traits
2423        // (like a hypothetical `Move` or `Leak`) we would want to validate the location according
2424        // to default trait elaboration in HIR ty lowering (which depends on the specific trait in
2425        // question: E.g., `?Sized` & `?Move` most likely won't be allowed in all the same places).
2426
2427        match rbp {
2428            RelaxedBoundPolicy::Allowed(dedup_map) => {
2429                // `trait_def_id` only returns `None` for errors during resolution.
2430                let Some(trait_def_id) = trait_ref.trait_def_id() else { return };
2431                let tcx = self.tcx;
2432                let err = |s| {
2433                    let name = tcx.item_name(trait_def_id);
2434                    tcx.dcx()
2435                        .struct_span_err(
2436                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [span, s]))vec![span, s],
2437                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("duplicate relaxed `{0}` bounds",
                name))
    })format!("duplicate relaxed `{name}` bounds"),
2438                        )
2439                        .with_code(E0203)
2440                        .emit();
2441                };
2442                dedup_map.entry(trait_def_id).and_modify(|&mut s| err(s)).or_insert(span);
2443                return;
2444            }
2445            RelaxedBoundPolicy::Forbidden(reason) => {
2446                let gate = |context, subject| {
2447                    let extended = self.tcx.features().more_maybe_bounds();
2448                    let is_sized = trait_ref
2449                        .trait_def_id()
2450                        .is_some_and(|def_id| self.tcx.is_lang_item(def_id, hir::LangItem::Sized));
2451
2452                    if extended && !is_sized {
2453                        return;
2454                    }
2455
2456                    let prefix = if extended { "`Sized` " } else { "" };
2457                    let mut diag = self.dcx().struct_span_err(
2458                        span,
2459                        ::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}"),
2460                    );
2461                    if is_sized {
2462                        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!(
2463                            "{subject} are not implicitly bounded by `Sized`, \
2464                             so there is nothing to relax"
2465                        ));
2466                    }
2467                    diag.emit();
2468                };
2469
2470                match reason {
2471                    RelaxedBoundForbiddenReason::TraitObjectTy => {
2472                        gate("trait object types", "trait object types");
2473                        return;
2474                    }
2475                    RelaxedBoundForbiddenReason::SuperTrait => {
2476                        gate("supertrait bounds", "traits");
2477                        return;
2478                    }
2479                    RelaxedBoundForbiddenReason::TraitAlias => {
2480                        gate("trait alias bounds", "trait aliases");
2481                        return;
2482                    }
2483                    RelaxedBoundForbiddenReason::AssocTyBounds
2484                    | RelaxedBoundForbiddenReason::WhereBound => {}
2485                };
2486            }
2487        }
2488
2489        self.dcx()
2490            .struct_span_err(span, "this relaxed bound is not permitted here")
2491            .with_note(
2492                "in this context, relaxed bounds are only allowed on \
2493                 type parameters defined on the closest item",
2494            )
2495            .emit();
2496    }
2497
2498    fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy<'hir> {
2499        hir::MutTy { ty: self.lower_ty_alloc(&mt.ty, itctx), mutbl: mt.mutbl }
2500    }
2501
2502    x;#[instrument(level = "debug", skip(self), ret)]
2503    fn lower_param_bounds(
2504        &mut self,
2505        bounds: &[GenericBound],
2506        rbp: RelaxedBoundPolicy<'_>,
2507        itctx: ImplTraitContext,
2508    ) -> hir::GenericBounds<'hir> {
2509        self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, rbp, itctx))
2510    }
2511
2512    fn lower_param_bounds_mut(
2513        &mut self,
2514        bounds: &[GenericBound],
2515        mut rbp: RelaxedBoundPolicy<'_>,
2516        itctx: ImplTraitContext,
2517    ) -> impl Iterator<Item = hir::GenericBound<'hir>> {
2518        bounds.iter().map(move |bound| self.lower_param_bound(bound, rbp.reborrow(), itctx))
2519    }
2520
2521    x;#[instrument(level = "debug", skip(self), ret)]
2522    fn lower_universal_param_and_bounds(
2523        &mut self,
2524        node_id: NodeId,
2525        span: Span,
2526        ident: Ident,
2527        bounds: &[GenericBound],
2528    ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2529        // Add a definition for the in-band `Param`.
2530        let def_id = self.local_def_id(node_id);
2531        let span = self.lower_span(span);
2532
2533        // Set the name to `impl Bound1 + Bound2`.
2534        let param = hir::GenericParam {
2535            hir_id: self.lower_node_id(node_id),
2536            def_id,
2537            name: ParamName::Plain(self.lower_ident(ident)),
2538            pure_wrt_drop: false,
2539            span,
2540            kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2541            colon_span: None,
2542            source: hir::GenericParamSource::Generics,
2543        };
2544
2545        let preds = self.lower_generic_bound_predicate(
2546            ident,
2547            node_id,
2548            &GenericParamKind::Type { default: None },
2549            bounds,
2550            /* colon_span */ None,
2551            span,
2552            RelaxedBoundPolicy::Allowed(&mut Default::default()),
2553            ImplTraitContext::Universal,
2554            hir::PredicateOrigin::ImplTrait,
2555        );
2556
2557        let hir_id = self.next_id();
2558        let res = Res::Def(DefKind::TyParam, def_id.to_def_id());
2559        let ty = hir::TyKind::Path(hir::QPath::Resolved(
2560            None,
2561            self.arena.alloc(hir::Path {
2562                span,
2563                res,
2564                segments:
2565                    arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2566            }),
2567        ));
2568
2569        (param, preds, ty)
2570    }
2571
2572    /// Lowers a block directly to an expression, presuming that it
2573    /// has no attributes and is not targeted by a `break`.
2574    fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2575        let block = self.lower_block(b, false);
2576        self.expr_block(block)
2577    }
2578
2579    fn lower_array_length_to_const_arg(&mut self, c: &AnonConst) -> &'hir hir::ConstArg<'hir> {
2580        // We cannot just match on `ExprKind::Underscore` as `(_)` is represented as
2581        // `ExprKind::Paren(ExprKind::Underscore)` and should also be lowered to `GenericArg::Infer`
2582        match c.value.peel_parens().kind {
2583            ExprKind::Underscore => {
2584                let ct_kind = hir::ConstArgKind::Infer(());
2585                self.arena.alloc(hir::ConstArg {
2586                    hir_id: self.lower_node_id(c.id),
2587                    kind: ct_kind,
2588                    span: self.lower_span(c.value.span),
2589                })
2590            }
2591            _ => self.lower_anon_const_to_const_arg_and_alloc(c),
2592        }
2593    }
2594
2595    /// Used when lowering a type argument that turned out to actually be a const argument.
2596    ///
2597    /// Only use for that purpose since otherwise it will create a duplicate def.
2598    #[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(2598u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["path", "res",
                                                    "ty_id", "span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'hir hir::ConstArg<'hir> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            let is_trivial_path =
                path.is_potential_trivial_const_arg() &&
                    #[allow(non_exhaustive_omitted_patterns)] match res {
                        Res::Def(DefKind::ConstParam, _) => true,
                        _ => false,
                    };
            let ct_kind =
                if is_trivial_path || tcx.features().min_generic_const_args()
                    {
                    let qpath =
                        self.lower_qpath(ty_id, &None, path, ParamMode::Explicit,
                            AllowReturnTypeNotation::No,
                            ImplTraitContext::Disallowed(ImplTraitPosition::Path),
                            None);
                    hir::ConstArgKind::Path(qpath)
                } else {
                    let node_id = self.next_node_id();
                    let span = self.lower_span(span);
                    let def_id =
                        self.create_def(node_id, None, DefKind::AnonConst, 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))]
2599    fn lower_const_path_to_const_arg(
2600        &mut self,
2601        path: &Path,
2602        res: Res<NodeId>,
2603        ty_id: NodeId,
2604        span: Span,
2605    ) -> &'hir hir::ConstArg<'hir> {
2606        let tcx = self.tcx;
2607
2608        let is_trivial_path = path.is_potential_trivial_const_arg()
2609            && matches!(res, Res::Def(DefKind::ConstParam, _));
2610        let ct_kind = if is_trivial_path || tcx.features().min_generic_const_args() {
2611            let qpath = self.lower_qpath(
2612                ty_id,
2613                &None,
2614                path,
2615                ParamMode::Explicit,
2616                AllowReturnTypeNotation::No,
2617                // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2618                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2619                None,
2620            );
2621            hir::ConstArgKind::Path(qpath)
2622        } else {
2623            // Construct an AnonConst where the expr is the "ty"'s path.
2624            let node_id = self.next_node_id();
2625            let span = self.lower_span(span);
2626
2627            // Add a definition for the in-band const def.
2628            // We're lowering a const argument that was originally thought to be a type argument,
2629            // so the def collector didn't create the def ahead of time. That's why we have to do
2630            // it here.
2631            let def_id = self.create_def(node_id, None, DefKind::AnonConst, span);
2632            let hir_id = self.lower_node_id(node_id);
2633
2634            let path_expr = Expr {
2635                id: ty_id,
2636                kind: ExprKind::Path(None, path.clone()),
2637                span,
2638                attrs: AttrVec::new(),
2639                tokens: None,
2640            };
2641
2642            let ct = self.with_new_scopes(span, |this| {
2643                self.arena.alloc(hir::AnonConst {
2644                    def_id,
2645                    hir_id,
2646                    body: this.lower_const_body(path_expr.span, Some(&path_expr)),
2647                    span,
2648                })
2649            });
2650            hir::ConstArgKind::Anon(ct)
2651        };
2652
2653        self.arena.alloc(hir::ConstArg {
2654            hir_id: self.next_id(),
2655            kind: ct_kind,
2656            span: self.lower_span(span),
2657        })
2658    }
2659
2660    fn lower_const_item_rhs(
2661        &mut self,
2662        rhs_kind: &ConstItemRhsKind,
2663        span: Span,
2664    ) -> hir::ConstItemRhs<'hir> {
2665        match rhs_kind {
2666            ConstItemRhsKind::Body { rhs: Some(body) } => {
2667                hir::ConstItemRhs::Body(self.lower_const_body(span, Some(body)))
2668            }
2669            ConstItemRhsKind::Body { rhs: None } => {
2670                hir::ConstItemRhs::Body(self.lower_const_body(span, None))
2671            }
2672            ConstItemRhsKind::TypeConst { rhs: Some(anon) } => {
2673                hir::ConstItemRhs::TypeConst(self.lower_anon_const_to_const_arg_and_alloc(anon))
2674            }
2675            ConstItemRhsKind::TypeConst { rhs: None } => {
2676                let const_arg = ConstArg {
2677                    hir_id: self.next_id(),
2678                    kind: hir::ConstArgKind::Error(
2679                        self.dcx().span_delayed_bug(DUMMY_SP, "no block"),
2680                    ),
2681                    span: DUMMY_SP,
2682                };
2683                hir::ConstItemRhs::TypeConst(self.arena.alloc(const_arg))
2684            }
2685        }
2686    }
2687
2688    x;#[instrument(level = "debug", skip(self), ret)]
2689    fn can_lower_expr_to_const_arg_direct(
2690        &mut self,
2691        expr: &Expr,
2692    ) -> Result<(), UnrepresentableConstArgError> {
2693        let is_mgca = self.tcx.features().min_generic_const_args();
2694        // Note the only stable case is currently ExprKind::Path. All others have an is_mgca guard.
2695        match &expr.kind {
2696            ExprKind::Call(func, args)
2697                if is_mgca && let ExprKind::Path(_qself, _path) = &func.kind =>
2698            {
2699                for arg in args {
2700                    self.can_lower_expr_to_const_arg_direct(arg)?;
2701                }
2702                Ok(())
2703            }
2704            ExprKind::Tup(exprs) if is_mgca => {
2705                for expr in exprs {
2706                    self.can_lower_expr_to_const_arg_direct(expr)?;
2707                }
2708                Ok(())
2709            }
2710            ExprKind::Path(qself, path)
2711                if is_mgca
2712                    || path.is_potential_trivial_const_arg()
2713                        && matches!(
2714                            self.get_partial_res(expr.id)
2715                                .and_then(|partial_res| partial_res.full_res()),
2716                            Some(Res::Def(DefKind::ConstParam, _))
2717                        ) =>
2718            {
2719                Ok(())
2720            }
2721            ExprKind::Struct(se) if is_mgca => {
2722                for f in &se.fields {
2723                    self.can_lower_expr_to_const_arg_direct(&f.expr)?;
2724                }
2725                Ok(())
2726            }
2727            ExprKind::Array(elements) if is_mgca => {
2728                for element in elements {
2729                    self.can_lower_expr_to_const_arg_direct(element)?;
2730                }
2731                Ok(())
2732            }
2733            ExprKind::Underscore if is_mgca => Ok(()),
2734            ExprKind::Block(block, _)
2735                if is_mgca
2736                    && let [stmt] = block.stmts.as_slice()
2737                    && let StmtKind::Expr(expr) = &stmt.kind =>
2738            {
2739                self.can_lower_expr_to_const_arg_direct(expr)
2740            }
2741            ExprKind::Lit(literal) if is_mgca => Ok(()),
2742            ExprKind::Unary(UnOp::Neg, inner_expr)
2743                if is_mgca && let ExprKind::Lit(_) = &inner_expr.kind =>
2744            {
2745                Ok(())
2746            }
2747            ExprKind::ConstBlock(anon) if is_mgca => Ok(()),
2748            ExprKind::DirectConstArg(expr) if is_mgca => {
2749                // Always report this as able to be represented directly. If it turns out not to be,
2750                // `lower_expr_to_const_arg_direct` will report an error.
2751                Ok(())
2752            }
2753            _ => Err(UnrepresentableConstArgError::new(expr)),
2754        }
2755    }
2756
2757    /// It is not allowed to call this function without checking can_lower_expr_to_const_arg_direct
2758    /// first, as we assume all feature gates/etc. have been checked already.
2759    x;#[instrument(level = "debug", skip(self), ret)]
2760    fn lower_expr_to_const_arg_direct(
2761        &mut self,
2762        expr: &Expr,
2763        id_override: Option<NodeId>,
2764    ) -> hir::ConstArg<'hir> {
2765        debug_assert!(self.can_lower_expr_to_const_arg_direct(expr).is_ok());
2766
2767        let span = self.lower_span(expr.span);
2768        let node_id = id_override.unwrap_or(expr.id);
2769        match &expr.kind {
2770            ExprKind::Call(func, args) if let ExprKind::Path(qself, path) = &func.kind => {
2771                let qpath = self.lower_qpath(
2772                    func.id,
2773                    qself,
2774                    path,
2775                    ParamMode::Explicit,
2776                    AllowReturnTypeNotation::No,
2777                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2778                    None,
2779                );
2780
2781                let lowered_args = self.arena.alloc_from_iter(args.iter().map(|arg| {
2782                    let const_arg = self.lower_expr_to_const_arg_direct(arg, None);
2783                    &*self.arena.alloc(const_arg)
2784                }));
2785
2786                ConstArg {
2787                    hir_id: self.lower_node_id(node_id),
2788                    kind: hir::ConstArgKind::TupleCall(qpath, lowered_args),
2789                    span,
2790                }
2791            }
2792            ExprKind::Tup(exprs) => {
2793                let exprs = self.arena.alloc_from_iter(exprs.iter().map(|expr| {
2794                    let expr = self.lower_expr_to_const_arg_direct(expr, None);
2795                    &*self.arena.alloc(expr)
2796                }));
2797
2798                ConstArg {
2799                    hir_id: self.lower_node_id(node_id),
2800                    kind: hir::ConstArgKind::Tup(exprs),
2801                    span,
2802                }
2803            }
2804            ExprKind::Path(qself, path) => {
2805                let qpath = self.lower_qpath(
2806                    expr.id,
2807                    qself,
2808                    path,
2809                    ParamMode::Explicit,
2810                    AllowReturnTypeNotation::No,
2811                    // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2812                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2813                    None,
2814                );
2815
2816                ConstArg {
2817                    hir_id: self.lower_node_id(node_id),
2818                    kind: hir::ConstArgKind::Path(qpath),
2819                    span,
2820                }
2821            }
2822            ExprKind::Struct(se) => {
2823                let path = self.lower_qpath(
2824                    expr.id,
2825                    &se.qself,
2826                    &se.path,
2827                    // FIXME(mgca): we may want this to be `Optional` instead, but
2828                    // we would also need to make sure that HIR ty lowering errors
2829                    // when these paths wind up in signatures.
2830                    ParamMode::Explicit,
2831                    AllowReturnTypeNotation::No,
2832                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2833                    None,
2834                );
2835
2836                let fields = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
2837                    let hir_id = self.lower_node_id(f.id);
2838                    // FIXME(mgca): This might result in lowering attributes that
2839                    // then go unused as the `Target::ExprField` is not actually
2840                    // corresponding to `Node::ExprField`.
2841                    self.lower_attrs(hir_id, &f.attrs, f.span, Target::ExprField);
2842                    let expr = self.lower_expr_to_const_arg_direct(&f.expr, None);
2843
2844                    &*self.arena.alloc(hir::ConstArgExprField {
2845                        hir_id,
2846                        field: self.lower_ident(f.ident),
2847                        expr: self.arena.alloc(expr),
2848                        span: self.lower_span(f.span),
2849                    })
2850                }));
2851
2852                ConstArg {
2853                    hir_id: self.lower_node_id(node_id),
2854                    kind: hir::ConstArgKind::Struct(path, fields),
2855                    span,
2856                }
2857            }
2858            ExprKind::Array(elements) => {
2859                let lowered_elems = self.arena.alloc_from_iter(elements.iter().map(|element| {
2860                    let const_arg = self.lower_expr_to_const_arg_direct(element, None);
2861                    &*self.arena.alloc(const_arg)
2862                }));
2863                let array_expr = self.arena.alloc(hir::ConstArgArrayExpr {
2864                    span: self.lower_span(expr.span),
2865                    elems: lowered_elems,
2866                });
2867
2868                ConstArg {
2869                    hir_id: self.lower_node_id(node_id),
2870                    kind: hir::ConstArgKind::Array(array_expr),
2871                    span,
2872                }
2873            }
2874            ExprKind::Underscore => ConstArg {
2875                hir_id: self.lower_node_id(node_id),
2876                kind: hir::ConstArgKind::Infer(()),
2877                span,
2878            },
2879            ExprKind::Block(block, _)
2880                if let [stmt] = block.stmts.as_slice()
2881                    && let StmtKind::Expr(expr) = &stmt.kind =>
2882            {
2883                return self.lower_expr_to_const_arg_direct(expr, id_override);
2884            }
2885            ExprKind::Lit(literal) => {
2886                let span = self.lower_span(expr.span);
2887                let literal = self.lower_lit(literal, span);
2888
2889                ConstArg {
2890                    hir_id: self.lower_node_id(node_id),
2891                    kind: hir::ConstArgKind::Literal { lit: literal.node, negated: false },
2892                    span,
2893                }
2894            }
2895            ExprKind::Unary(UnOp::Neg, inner_expr)
2896                if let ExprKind::Lit(literal) = &inner_expr.kind =>
2897            {
2898                let span = self.lower_span(expr.span);
2899                let literal = self.lower_lit(literal, span);
2900
2901                let kind = if !matches!(literal.node, LitKind::Int(..)) {
2902                    let err =
2903                        self.dcx().struct_span_err(expr.span, "negated literal must be an integer");
2904                    hir::ConstArgKind::Error(err.emit())
2905                } else {
2906                    hir::ConstArgKind::Literal { lit: literal.node, negated: true }
2907                };
2908                ConstArg { hir_id: self.lower_node_id(node_id), kind, span }
2909            }
2910            ExprKind::ConstBlock(anon_const) => {
2911                // Do not use lower_anon_const_to_const_arg, as that attempts to represent the body
2912                // directly. Instead, force an anon const.
2913                let def_id = self.local_def_id(anon_const.id);
2914                assert_eq!(DefKind::AnonConst, self.tcx.def_kind(def_id));
2915                let lowered_anon = self.lower_anon_const_to_anon_const(anon_const, span);
2916                ConstArg {
2917                    hir_id: self.lower_node_id(node_id),
2918                    kind: hir::ConstArgKind::Anon(lowered_anon),
2919                    span,
2920                }
2921            }
2922            ExprKind::DirectConstArg(expr) => {
2923                // `can_lower_expr_to_const_arg_direct` always returns success upon encountering a
2924                // ExprKind::DirectConstArg, which effectively forces the expression to be lowered
2925                // as a direct arg. If it actually turns out to not be possible, emit an error
2926                // instead.
2927                match self.can_lower_expr_to_const_arg_direct(expr) {
2928                    Ok(()) => self.lower_expr_to_const_arg_direct(expr, id_override),
2929                    Err(err) => err.emit(self),
2930                }
2931            }
2932            _ => {
2933                span_bug!(
2934                    expr.span,
2935                    "lower_expr_to_const_arg_direct encountered an unlowerable expression, either \
2936                    can_lower_expr_to_const_arg_direct returned Ok() on something it shouldn't \
2937                    have, or you forgot to check can_lower_expr_to_const_arg_direct first"
2938                );
2939            }
2940        }
2941    }
2942
2943    /// See [`hir::ConstArg`] for when to use this function vs
2944    /// [`Self::lower_anon_const_to_anon_const`].
2945    fn lower_anon_const_to_const_arg_and_alloc(
2946        &mut self,
2947        anon: &AnonConst,
2948    ) -> &'hir hir::ConstArg<'hir> {
2949        self.arena.alloc(self.lower_anon_const_to_const_arg(anon, anon.value.span))
2950    }
2951
2952    #[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(2952u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["anon", "span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&anon)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::ConstArg<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let expr =
                if self.tcx.features().min_generic_const_args() {
                    &anon.value
                } else { anon.value.maybe_unwrap_block() };
            if self.can_lower_expr_to_const_arg_direct(expr).is_ok() {
                return self.lower_expr_to_const_arg_direct(expr,
                        Some(anon.id));
            }
            let lowered_anon =
                self.lower_anon_const_to_anon_const(anon, anon.value.span);
            ConstArg {
                hir_id: self.next_id(),
                kind: hir::ConstArgKind::Anon(lowered_anon),
                span: self.lower_span(anon.value.span),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2953    fn lower_anon_const_to_const_arg(
2954        &mut self,
2955        anon: &AnonConst,
2956        span: Span,
2957    ) -> hir::ConstArg<'hir> {
2958        // Stable only allows one nesting of blocks for directly represented paths. mGCA allows
2959        // arbitrarily many, and are handled inside lower_expr_to_const_arg_direct for consistency.
2960        let expr = if self.tcx.features().min_generic_const_args() {
2961            &anon.value
2962        } else {
2963            anon.value.maybe_unwrap_block()
2964        };
2965
2966        if self.can_lower_expr_to_const_arg_direct(expr).is_ok() {
2967            return self.lower_expr_to_const_arg_direct(expr, Some(anon.id));
2968        }
2969
2970        let lowered_anon = self.lower_anon_const_to_anon_const(anon, anon.value.span);
2971        ConstArg {
2972            hir_id: self.next_id(),
2973            kind: hir::ConstArgKind::Anon(lowered_anon),
2974            span: self.lower_span(anon.value.span),
2975        }
2976    }
2977
2978    /// See [`hir::ConstArg`] for when to use this function vs
2979    /// [`Self::lower_anon_const_to_const_arg`].
2980    fn lower_anon_const_to_anon_const(
2981        &mut self,
2982        c: &AnonConst,
2983        span: Span,
2984    ) -> &'hir hir::AnonConst {
2985        self.arena.alloc(self.with_new_scopes(c.value.span, |this| {
2986            let def_id = this.local_def_id(c.id);
2987            let hir_id = this.lower_node_id(c.id);
2988            hir::AnonConst {
2989                def_id,
2990                hir_id,
2991                body: this.lower_const_body(c.value.span, Some(&c.value)),
2992                span: this.lower_span(span),
2993            }
2994        }))
2995    }
2996
2997    fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2998        match u {
2999            CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
3000            UserProvided => hir::UnsafeSource::UserProvided,
3001        }
3002    }
3003
3004    fn lower_trait_bound_modifiers(
3005        &mut self,
3006        modifiers: TraitBoundModifiers,
3007    ) -> hir::TraitBoundModifiers {
3008        let constness = match modifiers.constness {
3009            BoundConstness::Never => BoundConstness::Never,
3010            BoundConstness::Always(span) => BoundConstness::Always(self.lower_span(span)),
3011            BoundConstness::Maybe(span) => BoundConstness::Maybe(self.lower_span(span)),
3012        };
3013        let polarity = match modifiers.polarity {
3014            BoundPolarity::Positive => BoundPolarity::Positive,
3015            BoundPolarity::Negative(span) => BoundPolarity::Negative(self.lower_span(span)),
3016            BoundPolarity::Maybe(span) => BoundPolarity::Maybe(self.lower_span(span)),
3017        };
3018        hir::TraitBoundModifiers { constness, polarity }
3019    }
3020
3021    // Helper methods for building HIR.
3022
3023    fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
3024        hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
3025    }
3026
3027    fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
3028        self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
3029    }
3030
3031    fn stmt_let_pat(
3032        &mut self,
3033        attrs: Option<&'hir [hir::Attribute]>,
3034        span: Span,
3035        init: Option<&'hir hir::Expr<'hir>>,
3036        pat: &'hir hir::Pat<'hir>,
3037        source: hir::LocalSource,
3038    ) -> hir::Stmt<'hir> {
3039        let hir_id = self.next_id();
3040        if let Some(a) = attrs {
3041            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
3042            self.attrs.insert(hir_id.local_id, a);
3043        }
3044        let local = hir::LetStmt {
3045            super_: None,
3046            hir_id,
3047            init,
3048            pat,
3049            els: None,
3050            source,
3051            span: self.lower_span(span),
3052            ty: None,
3053        };
3054        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
3055    }
3056
3057    fn stmt_super_let_pat(
3058        &mut self,
3059        span: Span,
3060        pat: &'hir hir::Pat<'hir>,
3061        init: Option<&'hir hir::Expr<'hir>>,
3062    ) -> hir::Stmt<'hir> {
3063        let hir_id = self.next_id();
3064        let span = self.lower_span(span);
3065        let local = hir::LetStmt {
3066            super_: Some(span),
3067            hir_id,
3068            init,
3069            pat,
3070            els: None,
3071            source: hir::LocalSource::Normal,
3072            span,
3073            ty: None,
3074        };
3075        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
3076    }
3077
3078    fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
3079        self.block_all(expr.span, &[], Some(expr))
3080    }
3081
3082    fn block_all(
3083        &mut self,
3084        span: Span,
3085        stmts: &'hir [hir::Stmt<'hir>],
3086        expr: Option<&'hir hir::Expr<'hir>>,
3087    ) -> &'hir hir::Block<'hir> {
3088        let blk = hir::Block {
3089            stmts,
3090            expr,
3091            hir_id: self.next_id(),
3092            rules: hir::BlockCheckMode::DefaultBlock,
3093            span: self.lower_span(span),
3094            targeted_by_break: false,
3095        };
3096        self.arena.alloc(blk)
3097    }
3098
3099    fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
3100        let field = self.single_pat_field(span, pat);
3101        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field)
3102    }
3103
3104    fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
3105        let field = self.single_pat_field(span, pat);
3106        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field)
3107    }
3108
3109    fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
3110        let field = self.single_pat_field(span, pat);
3111        self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field)
3112    }
3113
3114    fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
3115        self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[])
3116    }
3117
3118    fn single_pat_field(
3119        &mut self,
3120        span: Span,
3121        pat: &'hir hir::Pat<'hir>,
3122    ) -> &'hir [hir::PatField<'hir>] {
3123        let field = hir::PatField {
3124            hir_id: self.next_id(),
3125            ident: Ident::new(sym::integer(0), self.lower_span(span)),
3126            is_shorthand: false,
3127            pat,
3128            span: self.lower_span(span),
3129        };
3130        self.arena.alloc_from_iter([field])arena_vec![self; field]
3131    }
3132
3133    fn pat_lang_item_variant(
3134        &mut self,
3135        span: Span,
3136        lang_item: hir::LangItem,
3137        fields: &'hir [hir::PatField<'hir>],
3138    ) -> &'hir hir::Pat<'hir> {
3139        let path = self.make_lang_item_qpath(lang_item, self.lower_span(span), None);
3140        self.pat(span, hir::PatKind::Struct(path, fields, None))
3141    }
3142
3143    fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, HirId) {
3144        self.pat_ident_binding_mode(span, ident, hir::BindingMode::NONE)
3145    }
3146
3147    fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, HirId) {
3148        self.pat_ident_binding_mode_mut(span, ident, hir::BindingMode::NONE)
3149    }
3150
3151    fn pat_ident_binding_mode(
3152        &mut self,
3153        span: Span,
3154        ident: Ident,
3155        bm: hir::BindingMode,
3156    ) -> (&'hir hir::Pat<'hir>, HirId) {
3157        let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
3158        (self.arena.alloc(pat), hir_id)
3159    }
3160
3161    fn pat_ident_binding_mode_mut(
3162        &mut self,
3163        span: Span,
3164        ident: Ident,
3165        bm: hir::BindingMode,
3166    ) -> (hir::Pat<'hir>, HirId) {
3167        let hir_id = self.next_id();
3168
3169        (
3170            hir::Pat {
3171                hir_id,
3172                kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
3173                span: self.lower_span(span),
3174                default_binding_modes: true,
3175            },
3176            hir_id,
3177        )
3178    }
3179
3180    fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
3181        self.arena.alloc(hir::Pat {
3182            hir_id: self.next_id(),
3183            kind,
3184            span: self.lower_span(span),
3185            default_binding_modes: true,
3186        })
3187    }
3188
3189    fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
3190        hir::Pat {
3191            hir_id: self.next_id(),
3192            kind,
3193            span: self.lower_span(span),
3194            default_binding_modes: false,
3195        }
3196    }
3197
3198    fn ty_path(&mut self, mut hir_id: HirId, span: Span, qpath: hir::QPath<'hir>) -> hir::Ty<'hir> {
3199        let kind = match qpath {
3200            hir::QPath::Resolved(None, path) => {
3201                // Turn trait object paths into `TyKind::TraitObject` instead.
3202                match path.res {
3203                    Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
3204                        let principal = hir::PolyTraitRef {
3205                            bound_generic_params: &[],
3206                            modifiers: hir::TraitBoundModifiers::NONE,
3207                            trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
3208                            span: self.lower_span(span),
3209                        };
3210
3211                        // The original ID is taken by the `PolyTraitRef`,
3212                        // so the `Ty` itself needs a different one.
3213                        hir_id = self.next_id();
3214                        hir::TyKind::TraitObject(
3215                            self.arena.alloc_from_iter([principal])arena_vec![self; principal],
3216                            TaggedRef::new(self.elided_dyn_bound(span), TraitObjectSyntax::None),
3217                        )
3218                    }
3219                    _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
3220                }
3221            }
3222            _ => hir::TyKind::Path(qpath),
3223        };
3224
3225        hir::Ty { hir_id, kind, span: self.lower_span(span) }
3226    }
3227
3228    /// Invoked to create the lifetime argument(s) for an elided trait object
3229    /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
3230    /// when the bound is written, even if it is written with `'_` like in
3231    /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
3232    fn elided_dyn_bound(&mut self, span: Span) -> &'hir hir::Lifetime {
3233        let r = hir::Lifetime::new(
3234            self.next_id(),
3235            Ident::new(kw::UnderscoreLifetime, self.lower_span(span)),
3236            hir::LifetimeKind::ImplicitObjectLifetimeDefault,
3237            LifetimeSource::Other,
3238            LifetimeSyntax::Implicit,
3239        );
3240        {
    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:3240",
                        "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(3240u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("elided_dyn_bound: r={0:?}",
                                                    r) as &dyn Value))])
            });
    } else { ; }
};debug!("elided_dyn_bound: r={:?}", r);
3241        self.arena.alloc(r)
3242    }
3243}
3244
3245/// Helper struct for the delayed construction of [`hir::GenericArgs`].
3246struct GenericArgsCtor<'hir> {
3247    args: SmallVec<[hir::GenericArg<'hir>; 4]>,
3248    constraints: &'hir [hir::AssocItemConstraint<'hir>],
3249    parenthesized: hir::GenericArgsParentheses,
3250    span: Span,
3251}
3252
3253impl<'hir> GenericArgsCtor<'hir> {
3254    fn is_empty(&self) -> bool {
3255        self.args.is_empty()
3256            && self.constraints.is_empty()
3257            && self.parenthesized == hir::GenericArgsParentheses::No
3258    }
3259
3260    fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
3261        let ga = hir::GenericArgs {
3262            args: this.arena.alloc_from_iter(self.args),
3263            constraints: self.constraints,
3264            parenthesized: self.parenthesized,
3265            span_ext: this.lower_span(self.span),
3266        };
3267        this.arena.alloc(ga)
3268    }
3269}
3270
3271#[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)]
3272struct UnrepresentableConstArgError {
3273    span: Span,
3274    will_create_def_ids: bool,
3275}
3276
3277impl UnrepresentableConstArgError {
3278    fn new(expr: &Expr) -> Self {
3279        Self {
3280            span: expr.span,
3281            will_create_def_ids: expr::WillCreateDefIdsVisitor.visit_expr(expr).is_break(),
3282        }
3283    }
3284
3285    fn emit<'hir>(self, lowering_context: &mut LoweringContext<'_, 'hir>) -> ConstArg<'hir> {
3286        let msg = "complex const arguments must be placed inside of a `const` block";
3287        let e = if self.will_create_def_ids {
3288            // FIXME(mgca): make this non-fatal once we have a better way to handle
3289            // nested items in const args
3290            // Issue: https://github.com/rust-lang/rust/issues/154539
3291            lowering_context.dcx().struct_span_fatal(self.span, msg).emit()
3292        } else {
3293            lowering_context.dcx().struct_span_err(self.span, msg).emit()
3294        };
3295
3296        ConstArg {
3297            hir_id: lowering_context.next_id(),
3298            kind: hir::ConstArgKind::Error(e),
3299            span: self.span,
3300        }
3301    }
3302}