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(deref_patterns)]
35#![recursion_limit = "256"]
36// tidy-alphabetical-end
37
38use std::mem;
39use std::sync::Arc;
40
41use rustc_ast::node_id::NodeMap;
42use rustc_ast::visit::Visitor;
43use rustc_ast::{self as ast, *};
44use rustc_attr_parsing::{AttributeParser, OmitDoc, Recovery, ShouldEmit};
45use rustc_data_structures::fingerprint::Fingerprint;
46use rustc_data_structures::fx::FxIndexSet;
47use rustc_data_structures::sorted_map::SortedMap;
48use rustc_data_structures::stable_hash::{StableHash, StableHasher};
49use rustc_data_structures::steal::Steal;
50use rustc_data_structures::tagged_ptr::TaggedRef;
51use rustc_errors::{DiagArgFromDisplay, DiagCtxtHandle};
52use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
53use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId};
54use rustc_hir::definitions::PerParentDisambiguatorState;
55use rustc_hir::lints::DelayedLint;
56use rustc_hir::{
57    self as hir, AngleBrackets, ConstArg, GenericArg, HirId, ItemLocalMap, LifetimeSource,
58    LifetimeSyntax, ParamName, Target, TraitCandidate, find_attr,
59};
60use rustc_index::{Idx, IndexSlice, IndexVec};
61use rustc_macros::extension;
62use rustc_middle::hir::{self as mid_hir};
63use rustc_middle::span_bug;
64use rustc_middle::ty::{DelegationInfo, PerOwnerResolverData, ResolverAstLowering, TyCtxt};
65use rustc_session::errors::add_feature_diagnostics;
66use rustc_span::symbol::{Ident, Symbol, kw, sym};
67use rustc_span::{DUMMY_SP, DesugaringKind, Span};
68use smallvec::SmallVec;
69use thin_vec::ThinVec;
70use tracing::{debug, instrument, trace};
71
72use crate::errors::{AssocTyParentheses, AssocTyParenthesesSub, MisplacedImplTrait};
73use crate::item::Owners;
74
75macro_rules! arena_vec {
76    ($this:expr; $($x:expr),*) => (
77        $this.arena.alloc_from_iter([$($x),*])
78    );
79}
80
81mod asm;
82mod block;
83mod contract;
84mod delegation;
85mod errors;
86mod expr;
87mod format;
88mod index;
89mod item;
90mod pat;
91mod path;
92pub mod stability;
93
94struct LoweringContext<'a, 'hir> {
95    tcx: TyCtxt<'hir>,
96    resolver: &'a ResolverAstLowering<'hir>,
97    current_disambiguator: PerParentDisambiguatorState,
98
99    /// Used to allocate HIR nodes.
100    arena: &'hir hir::Arena<'hir>,
101
102    /// Bodies inside the owner being lowered.
103    bodies: Vec<(hir::ItemLocalId, &'hir hir::Body<'hir>)>,
104    /// `#[define_opaque]` attributes
105    define_opaque: Option<&'hir [(Span, LocalDefId)]>,
106    /// Attributes inside the owner being lowered.
107    attrs: SortedMap<hir::ItemLocalId, &'hir [hir::Attribute]>,
108    /// Collect items that were created by lowering the current owner.
109    children: Vec<(LocalDefId, hir::MaybeOwner<'hir>)>,
110
111    contract_ensures: Option<(Span, Ident, HirId)>,
112
113    coroutine_kind: Option<hir::CoroutineKind>,
114
115    /// When inside an `async` context, this is the `HirId` of the
116    /// `task_context` local bound to the resume argument of the coroutine.
117    task_context: Option<HirId>,
118
119    /// Used to get the current `fn`'s def span to point to when using `await`
120    /// outside of an `async fn`.
121    current_item: Option<Span>,
122
123    try_block_scope: TryBlockScope,
124    loop_scope: Option<HirId>,
125    is_in_loop_condition: bool,
126    is_in_dyn_type: bool,
127
128    current_hir_id_owner: hir::OwnerId,
129    owner: &'a PerOwnerResolverData,
130    item_local_id_counter: hir::ItemLocalId,
131    trait_map: ItemLocalMap<&'hir [TraitCandidate<'hir>]>,
132
133    impl_trait_defs: Vec<hir::GenericParam<'hir>>,
134    impl_trait_bounds: Vec<hir::WherePredicate<'hir>>,
135
136    /// NodeIds of pattern identifiers and labelled nodes that are lowered inside the current HIR owner.
137    ident_and_label_to_local_id: NodeMap<hir::ItemLocalId>,
138    /// NodeIds that are lowered inside the current HIR owner. Only used for duplicate lowering check.
139    #[cfg(debug_assertions)]
140    node_id_to_local_id: NodeMap<hir::ItemLocalId>,
141    /// The `NodeId` space is split in two.
142    /// `0..resolver.next_node_id` are created by the resolver on the AST.
143    /// The higher part `resolver.next_node_id..next_node_id` are created during lowering.
144    next_node_id: NodeId,
145    /// Maps the `NodeId`s created during lowering to `LocalDefId`s.
146    node_id_to_def_id: NodeMap<LocalDefId>,
147    /// Overlay over resolver's `partial_res_map` used by delegation.
148    /// This only contains `PartialRes::new(Res::Local(self_param_id))`,
149    /// so we only store `self_param_id`.
150    partial_res_overrides: NodeMap<NodeId>,
151
152    allow_contracts: Arc<[Symbol]>,
153    allow_try_trait: Arc<[Symbol]>,
154    allow_gen_future: Arc<[Symbol]>,
155    allow_pattern_type: Arc<[Symbol]>,
156    allow_async_gen: Arc<[Symbol]>,
157    allow_async_iterator: Arc<[Symbol]>,
158    allow_for_await: Arc<[Symbol]>,
159    allow_async_fn_traits: Arc<[Symbol]>,
160
161    delayed_lints: Vec<DelayedLint>,
162
163    /// Stack of `move(...)` collection states. A plain closure body pushes
164    /// `Some`, so `move(...)` expressions can record the generated locals they
165    /// should lower to. Nested bodies that cannot use `move(...)` push `None`.
166    move_expr_bindings: Vec<Option<expr::MoveExprState<'hir>>>,
167
168    attribute_parser: AttributeParser<'hir>,
169}
170
171impl<'a, 'hir> LoweringContext<'a, 'hir> {
172    fn new(tcx: TyCtxt<'hir>, resolver: &'a ResolverAstLowering<'hir>) -> Self {
173        Self {
174            tcx,
175            resolver,
176            current_disambiguator: Default::default(),
177            owner: &resolver.owners[&CRATE_NODE_ID],
178            arena: tcx.hir_arena,
179
180            // HirId handling.
181            bodies: Vec::new(),
182            define_opaque: None,
183            attrs: SortedMap::default(),
184            children: Vec::default(),
185            contract_ensures: None,
186            current_hir_id_owner: hir::CRATE_OWNER_ID,
187            item_local_id_counter: hir::ItemLocalId::ZERO,
188            ident_and_label_to_local_id: Default::default(),
189            #[cfg(debug_assertions)]
190            node_id_to_local_id: Default::default(),
191            trait_map: Default::default(),
192            next_node_id: resolver.next_node_id,
193            node_id_to_def_id: NodeMap::default(),
194            partial_res_overrides: NodeMap::default(),
195
196            // Lowering state.
197            try_block_scope: TryBlockScope::Function,
198            loop_scope: None,
199            is_in_loop_condition: false,
200            is_in_dyn_type: false,
201            coroutine_kind: None,
202            task_context: None,
203            current_item: None,
204            impl_trait_defs: Vec::new(),
205            impl_trait_bounds: Vec::new(),
206            allow_contracts: [sym::contracts_internals].into(),
207            allow_try_trait: [
208                sym::try_trait_v2,
209                sym::try_trait_v2_residual,
210                sym::yeet_desugar_details,
211            ]
212            .into(),
213            allow_pattern_type: [sym::pattern_types, sym::pattern_type_range_trait].into(),
214            allow_gen_future: if tcx.features().async_fn_track_caller() {
215                [sym::gen_future, sym::closure_track_caller].into()
216            } else {
217                [sym::gen_future].into()
218            },
219            allow_for_await: [sym::async_gen_internals, sym::async_iterator].into(),
220            allow_async_fn_traits: [sym::async_fn_traits].into(),
221            allow_async_gen: [sym::async_gen_internals].into(),
222            // FIXME(gen_blocks): how does `closure_track_caller`/`async_fn_track_caller`
223            // interact with `gen`/`async gen` blocks
224            allow_async_iterator: [sym::gen_future, sym::async_iterator].into(),
225
226            move_expr_bindings: Vec::new(),
227            attribute_parser: AttributeParser::new(
228                tcx.sess,
229                tcx.features(),
230                tcx.registered_tools(()),
231                ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
232            ),
233            delayed_lints: Vec::new(),
234        }
235    }
236
237    pub(crate) fn dcx(&self) -> DiagCtxtHandle<'hir> {
238        self.tcx.dcx()
239    }
240}
241
242struct SpanLowerer {
243    is_incremental: bool,
244    def_id: LocalDefId,
245}
246
247impl SpanLowerer {
248    fn lower(&self, span: Span) -> Span {
249        if self.is_incremental {
250            span.with_parent(Some(self.def_id))
251        } else {
252            // Do not make spans relative when not using incremental compilation.
253            span
254        }
255    }
256}
257
258impl<'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 =
    " Obtains per-namespace resolutions for `use` statement with the given `NodeId`."]
    fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
        self.import_res_map.get(&id).copied().unwrap_or_default()
    }
    #[doc = " Obtains resolution for a label with the given `NodeId`."]
    fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
        self.label_res_map.get(&id).copied()
    }
    #[doc = " Obtains resolution for a lifetime with the given `NodeId`."]
    fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
        self.lifetimes_res_map.get(&id).copied()
    }
    #[doc = " Obtain the list of lifetimes parameters to add to an item."]
    #[doc = ""]
    #[doc =
    " Extra lifetime parameters should only be added in places that can appear"]
    #[doc = " as a `binder` in `LifetimeRes`."]
    #[doc = ""]
    #[doc =
    " The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring"]
    #[doc = " should appear at the enclosing `PolyTraitRef`."]
    fn extra_lifetime_params(&self, id: NodeId)
        -> &[(Ident, NodeId, LifetimeRes)] {
        self.extra_lifetime_params_map.get(&id).map_or(&[], |v| &v[..])
    }
    fn delegation_info(&self, id: LocalDefId) -> Option<&DelegationInfo> {
        self.delegation_infos.get(&id)
    }
    fn owner_def_id(&self, id: NodeId) -> LocalDefId {
        self.owners[&id].def_id
    }
    fn lifetime_elision_allowed(&self, id: NodeId) -> bool {
        self.lifetime_elision_allowed.contains(&id)
    }
}#[extension(trait ResolverAstLoweringExt<'tcx>)]
259impl<'tcx> ResolverAstLowering<'tcx> {
260    fn legacy_const_generic_args(&self, expr: &Expr, tcx: TyCtxt<'tcx>) -> Option<Vec<usize>> {
261        let ExprKind::Path(None, path) = &expr.kind else {
262            return None;
263        };
264
265        // Don't perform legacy const generics rewriting if the path already
266        // has generic arguments.
267        if path.segments.last().unwrap().args.is_some() {
268            return None;
269        }
270
271        // We do not need to look at `partial_res_overrides`. That map only contains overrides for
272        // `self_param` locals. And here we are looking for the function definition that `expr`
273        // resolves to.
274        let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
275
276        // We only support cross-crate argument rewriting. Uses
277        // within the same crate should be updated to use the new
278        // const generics style.
279        if def_id.is_local() {
280            return None;
281        }
282
283        // we can use parsed attrs here since for other crates they're already available
284        find_attr!(
285            tcx, def_id,
286            RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
287        )
288        .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
289    }
290
291    /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
292    fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
293        self.import_res_map.get(&id).copied().unwrap_or_default()
294    }
295
296    /// Obtains resolution for a label with the given `NodeId`.
297    fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
298        self.label_res_map.get(&id).copied()
299    }
300
301    /// Obtains resolution for a lifetime with the given `NodeId`.
302    fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
303        self.lifetimes_res_map.get(&id).copied()
304    }
305
306    /// Obtain the list of lifetimes parameters to add to an item.
307    ///
308    /// Extra lifetime parameters should only be added in places that can appear
309    /// as a `binder` in `LifetimeRes`.
310    ///
311    /// The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring
312    /// should appear at the enclosing `PolyTraitRef`.
313    fn extra_lifetime_params(&self, id: NodeId) -> &[(Ident, NodeId, LifetimeRes)] {
314        self.extra_lifetime_params_map.get(&id).map_or(&[], |v| &v[..])
315    }
316
317    fn delegation_info(&self, id: LocalDefId) -> Option<&DelegationInfo> {
318        self.delegation_infos.get(&id)
319    }
320
321    fn owner_def_id(&self, id: NodeId) -> LocalDefId {
322        self.owners[&id].def_id
323    }
324
325    fn lifetime_elision_allowed(&self, id: NodeId) -> bool {
326        self.lifetime_elision_allowed.contains(&id)
327    }
328}
329
330/// How relaxed bounds `?Trait` should be treated.
331///
332/// Relaxed bounds should only be allowed in places where we later
333/// (namely during HIR ty lowering) perform *sized elaboration*.
334#[derive(#[automatically_derived]
impl<'a> ::core::clone::Clone for RelaxedBoundPolicy<'a> {
    #[inline]
    fn clone(&self) -> RelaxedBoundPolicy<'a> {
        let _: ::core::clone::AssertParamIsClone<NodeId>;
        let _: ::core::clone::AssertParamIsClone<&'a [ast::GenericParam]>;
        let _: ::core::clone::AssertParamIsClone<RelaxedBoundForbiddenReason>;
        *self
    }
}Clone, #[automatically_derived]
impl<'a> ::core::marker::Copy for RelaxedBoundPolicy<'a> { }Copy, #[automatically_derived]
impl<'a> ::core::fmt::Debug for RelaxedBoundPolicy<'a> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            RelaxedBoundPolicy::Allowed =>
                ::core::fmt::Formatter::write_str(f, "Allowed"),
            RelaxedBoundPolicy::AllowedIfOnTyParam(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "AllowedIfOnTyParam", __self_0, &__self_1),
            RelaxedBoundPolicy::Forbidden(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Forbidden", &__self_0),
        }
    }
}Debug)]
335enum RelaxedBoundPolicy<'a> {
336    Allowed,
337    AllowedIfOnTyParam(NodeId, &'a [ast::GenericParam]),
338    Forbidden(RelaxedBoundForbiddenReason),
339}
340
341#[derive(#[automatically_derived]
impl ::core::clone::Clone for RelaxedBoundForbiddenReason {
    #[inline]
    fn clone(&self) -> RelaxedBoundForbiddenReason { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for RelaxedBoundForbiddenReason { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for RelaxedBoundForbiddenReason {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                RelaxedBoundForbiddenReason::TraitObjectTy => "TraitObjectTy",
                RelaxedBoundForbiddenReason::SuperTrait => "SuperTrait",
                RelaxedBoundForbiddenReason::TraitAlias => "TraitAlias",
                RelaxedBoundForbiddenReason::AssocTyBounds => "AssocTyBounds",
                RelaxedBoundForbiddenReason::LateBoundVarsInScope =>
                    "LateBoundVarsInScope",
            })
    }
}Debug)]
342enum RelaxedBoundForbiddenReason {
343    TraitObjectTy,
344    SuperTrait,
345    TraitAlias,
346    AssocTyBounds,
347    LateBoundVarsInScope,
348}
349
350/// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
351/// and if so, what meaning it has.
352#[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)]
353enum ImplTraitContext {
354    /// Treat `impl Trait` as shorthand for a new universal generic parameter.
355    /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
356    /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
357    ///
358    /// Newly generated parameters should be inserted into the given `Vec`.
359    Universal,
360
361    /// Treat `impl Trait` as shorthand for a new opaque type.
362    /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
363    /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
364    ///
365    OpaqueTy { origin: hir::OpaqueTyOrigin<LocalDefId> },
366
367    /// Treat `impl Trait` as a "trait ascription", which is like a type
368    /// variable but that also enforces that a set of trait goals hold.
369    ///
370    /// This is useful to guide inference for unnameable types.
371    InBinding,
372
373    /// `impl Trait` is unstably accepted in this position.
374    FeatureGated(ImplTraitPosition, Symbol),
375    /// `impl Trait` is not accepted in this position.
376    Disallowed(ImplTraitPosition),
377}
378
379/// Position in which `impl Trait` is disallowed.
380#[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)]
381enum ImplTraitPosition {
382    Path,
383    Variable,
384    Trait,
385    Bound,
386    Generic,
387    ExternFnParam,
388    ClosureParam,
389    PointerParam,
390    FnTraitParam,
391    ExternFnReturn,
392    ClosureReturn,
393    PointerReturn,
394    FnTraitReturn,
395    GenericDefault,
396    ConstTy,
397    StaticTy,
398    AssocTy,
399    FieldTy,
400    Cast,
401    ImplSelf,
402    OffsetOf,
403}
404
405impl std::fmt::Display for ImplTraitPosition {
406    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407        let name = match self {
408            ImplTraitPosition::Path => "paths",
409            ImplTraitPosition::Variable => "the type of variable bindings",
410            ImplTraitPosition::Trait => "traits",
411            ImplTraitPosition::Bound => "bounds",
412            ImplTraitPosition::Generic => "generics",
413            ImplTraitPosition::ExternFnParam => "`extern fn` parameters",
414            ImplTraitPosition::ClosureParam => "closure parameters",
415            ImplTraitPosition::PointerParam => "`fn` pointer parameters",
416            ImplTraitPosition::FnTraitParam => "the parameters of `Fn` trait bounds",
417            ImplTraitPosition::ExternFnReturn => "`extern fn` return types",
418            ImplTraitPosition::ClosureReturn => "closure return types",
419            ImplTraitPosition::PointerReturn => "`fn` pointer return types",
420            ImplTraitPosition::FnTraitReturn => "the return type of `Fn` trait bounds",
421            ImplTraitPosition::GenericDefault => "generic parameter defaults",
422            ImplTraitPosition::ConstTy => "const types",
423            ImplTraitPosition::StaticTy => "static types",
424            ImplTraitPosition::AssocTy => "associated types",
425            ImplTraitPosition::FieldTy => "field types",
426            ImplTraitPosition::Cast => "cast expression types",
427            ImplTraitPosition::ImplSelf => "impl headers",
428            ImplTraitPosition::OffsetOf => "`offset_of!` parameters",
429        };
430
431        f.write_fmt(format_args!("{0}", name))write!(f, "{name}")
432    }
433}
434
435#[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)]
436enum FnDeclKind {
437    Fn,
438    Inherent,
439    ExternFn,
440    Closure,
441    Pointer,
442    Trait,
443    Impl,
444}
445
446#[derive(#[automatically_derived]
impl<'a> ::core::marker::Copy for AstOwner<'a> { }Copy, #[automatically_derived]
impl<'a> ::core::clone::Clone for AstOwner<'a> {
    #[inline]
    fn clone(&self) -> AstOwner<'a> {
        let _: ::core::clone::AssertParamIsClone<&'a ast::Crate>;
        let _: ::core::clone::AssertParamIsClone<&'a ast::Item>;
        let _: ::core::clone::AssertParamIsClone<&'a ast::AssocItem>;
        let _: ::core::clone::AssertParamIsClone<visit::AssocCtxt>;
        let _: ::core::clone::AssertParamIsClone<&'a ast::ForeignItem>;
        *self
    }
}Clone)]
447enum AstOwner<'a> {
448    NonOwner,
449    Crate(&'a ast::Crate),
450    Item(&'a ast::Item),
451    AssocItem(&'a ast::AssocItem, visit::AssocCtxt),
452    ForeignItem(&'a ast::ForeignItem),
453}
454
455#[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)]
456enum TryBlockScope {
457    /// There isn't a `try` block, so a `?` will use `return`.
458    Function,
459    /// We're inside a `try { … }` block, so a `?` will block-break
460    /// from that block using a type depending only on the argument.
461    Homogeneous(HirId),
462    /// We're inside a `try as _ { … }` block, so a `?` will block-break
463    /// from that block using the type specified.
464    Heterogeneous(HirId),
465}
466
467fn index_crate<'a, 'b>(
468    resolver: &'b ResolverAstLowering<'b>,
469    krate: &'a Crate,
470) -> IndexVec<LocalDefId, AstOwner<'a>> {
471    let mut indexer = Indexer { resolver, index: IndexVec::new() };
472    *indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner) =
473        AstOwner::Crate(krate);
474    visit::walk_crate(&mut indexer, krate);
475
476    return indexer.index;
477
478    struct Indexer<'a, 'b> {
479        resolver: &'b ResolverAstLowering<'b>,
480        index: IndexVec<LocalDefId, AstOwner<'a>>,
481    }
482
483    impl<'a, 'b> visit::Visitor<'a> for Indexer<'a, 'b> {
484        fn visit_attribute(&mut self, _: &'a Attribute) {
485            // We do not want to lower expressions that appear in attributes,
486            // as they are not accessible to the rest of the HIR.
487        }
488
489        fn visit_item(&mut self, item: &'a ast::Item) {
490            let def_id = self.resolver.owner_def_id(item.id);
491            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) = AstOwner::Item(item);
492            visit::walk_item(self, item)
493        }
494
495        fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) {
496            let def_id = self.resolver.owner_def_id(item.id);
497            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) =
498                AstOwner::AssocItem(item, ctxt);
499            visit::walk_assoc_item(self, item, ctxt);
500        }
501
502        fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) {
503            let def_id = self.resolver.owner_def_id(item.id);
504            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) =
505                AstOwner::ForeignItem(item);
506            visit::walk_item(self, item);
507        }
508    }
509}
510
511/// Compute the hash for the HIR of the full crate.
512/// This hash will then be part of the crate_hash which is stored in the metadata.
513fn compute_hir_hash(
514    tcx: TyCtxt<'_>,
515    owners: &IndexSlice<LocalDefId, hir::MaybeOwner<'_>>,
516) -> Fingerprint {
517    let mut hir_body_nodes: Vec<_> = owners
518        .iter_enumerated()
519        .filter_map(|(def_id, info)| {
520            let info = info.as_owner()?;
521            let def_path_hash = tcx.hir_def_path_hash(def_id);
522            Some((def_path_hash, info))
523        })
524        .collect();
525    hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
526
527    tcx.with_stable_hashing_context(|mut hcx| {
528        let mut stable_hasher = StableHasher::new();
529        hir_body_nodes.stable_hash(&mut hcx, &mut stable_hasher);
530        stable_hasher.finish()
531    })
532}
533
534pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
535    // Queries that borrow `resolver_for_lowering`.
536    tcx.ensure_done().output_filenames(());
537    tcx.ensure_done().early_lint_checks(());
538    tcx.ensure_done().debugger_visualizers(LOCAL_CRATE);
539    tcx.ensure_done().get_lang_items(());
540    let (resolver, krate) = tcx.resolver_for_lowering().steal();
541
542    let ast_index = index_crate(&resolver, &krate);
543    let mut owners = IndexVec::from_fn_n(
544        |_| hir::MaybeOwner::Phantom,
545        tcx.definitions_untracked().def_index_count(),
546    );
547
548    let mut lowerer = item::ItemLowerer {
549        tcx,
550        resolver: &resolver,
551        ast_index: &ast_index,
552        owners: Owners::IndexVec(&mut owners),
553    };
554
555    let mut delayed_ids: FxIndexSet<LocalDefId> = Default::default();
556
557    for def_id in ast_index.indices() {
558        match &ast_index[def_id] {
559            AstOwner::Item(Item { kind: ItemKind::Delegation { .. }, .. })
560            | AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation { .. }, .. }, _) => {
561                delayed_ids.insert(def_id);
562            }
563            _ => lowerer.lower_node(def_id),
564        };
565    }
566
567    // Don't hash unless necessary, because it's expensive.
568    let opt_hir_hash =
569        if tcx.needs_hir_hash() { Some(compute_hir_hash(tcx, &owners)) } else { None };
570
571    let delayed_resolver = Steal::new((resolver, krate));
572    mid_hir::Crate::new(owners, delayed_ids, delayed_resolver, opt_hir_hash)
573}
574
575/// Lowers an AST owner corresponding to `def_id`, now only delegations are lowered this way.
576pub fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
577    let krate = tcx.hir_crate(());
578
579    let (resolver, krate) = &*krate.delayed_resolver.borrow();
580
581    // FIXME!!!(fn_delegation): make ast index lifetime same as resolver,
582    // as it is too bad to reindex whole crate on each delegation lowering.
583    let ast_index = index_crate(resolver, krate);
584
585    let mut map = Default::default();
586    let mut lowerer = item::ItemLowerer {
587        tcx,
588        resolver: &resolver,
589        ast_index: &ast_index,
590        owners: Owners::Map(&mut map),
591    };
592
593    lowerer.lower_node(def_id);
594
595    for (child_def_id, owner) in map {
596        tcx.feed_delayed_owner(child_def_id, owner);
597    }
598}
599
600#[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)]
601enum ParamMode {
602    /// Any path in a type context.
603    Explicit,
604    /// The `module::Type` in `module::Type::method` in an expression.
605    Optional,
606}
607
608#[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)]
609enum AllowReturnTypeNotation {
610    /// Only in types, since RTN is denied later during HIR lowering.
611    Yes,
612    /// All other positions (path expr, method, use tree).
613    No,
614}
615
616enum GenericArgsMode {
617    /// Allow paren sugar, don't allow RTN.
618    ParenSugar,
619    /// Allow RTN, don't allow paren sugar.
620    ReturnTypeNotation,
621    // Error if parenthesized generics or RTN are encountered.
622    Err,
623    /// Silence errors when lowering generics. Only used with `Res::Err`.
624    Silence,
625}
626
627impl<'hir> LoweringContext<'_, 'hir> {
628    fn create_def(
629        &mut self,
630        node_id: NodeId,
631        name: Option<Symbol>,
632        def_kind: DefKind,
633        span: Span,
634    ) -> LocalDefId {
635        let parent = self.current_hir_id_owner.def_id;
636        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);
637        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!(
638            self.opt_local_def_id(node_id).is_none(),
639            "adding a def'n for node-id {:?} and def kind {:?} but a previous def'n exists: {:?}",
640            node_id,
641            def_kind,
642            self.tcx.hir_def_key(self.local_def_id(node_id)),
643        );
644
645        let def_id = self
646            .tcx
647            .at(span)
648            .create_def(parent, name, def_kind, None, &mut self.current_disambiguator)
649            .def_id();
650
651        {
    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:651",
                        "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(651u32),
                        ::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);
652        self.node_id_to_def_id.insert(node_id, def_id);
653
654        def_id
655    }
656
657    fn next_node_id(&mut self) -> NodeId {
658        let start = self.next_node_id;
659        let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
660        self.next_node_id = NodeId::from_u32(next);
661        start
662    }
663
664    /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
665    /// resolver (if any).
666    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
667        self.node_id_to_def_id
668            .get(&node)
669            .or_else(|| self.owner.node_id_to_def_id.get(&node))
670            .copied()
671    }
672
673    fn local_def_id(&self, node: NodeId) -> LocalDefId {
674        self.opt_local_def_id(node).unwrap_or_else(|| {
675            self.resolver.owners.items().any(|(id, items)| {
676                items.node_id_to_def_id.items().any(|(node_id, def_id)| {
677                    if *node_id == node {
678                        let actual_owner = items.node_id_to_def_id.get(id);
679                        {
    ::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})",)
680                    }
681                    false
682                })
683            });
684            {
    ::core::panicking::panic_fmt(format_args!("no entry for node id: `{0:?}`",
            node));
};panic!("no entry for node id: `{node:?}`");
685        })
686    }
687
688    fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
689        match self.partial_res_overrides.get(&id) {
690            Some(self_param_id) => Some(PartialRes::new(Res::Local(*self_param_id))),
691            None => self.resolver.partial_res_map.get(&id).copied(),
692        }
693    }
694
695    /// Given the id of an owner node in the AST, returns the corresponding `OwnerId`.
696    fn owner_id(&self, node: NodeId) -> hir::OwnerId {
697        hir::OwnerId { def_id: self.resolver.owners[&node].def_id }
698    }
699
700    /// Freshen the `LoweringContext` and ready it to lower a nested item.
701    /// The lowered item is registered into `self.children`.
702    ///
703    /// This function sets up `HirId` lowering infrastructure,
704    /// and stashes the shared mutable state to avoid pollution by the closure.
705    #[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(705u32),
                                    ::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 =
                std::mem::replace(&mut self.current_disambiguator,
                    new_disambig);
            let current_ast_owner =
                std::mem::replace(&mut self.owner,
                    &self.resolver.owners[&owner]);
            let current_attrs = std::mem::take(&mut self.attrs);
            let current_bodies = std::mem::take(&mut self.bodies);
            let current_define_opaque =
                std::mem::take(&mut self.define_opaque);
            let current_ident_and_label_to_local_id =
                std::mem::take(&mut self.ident_and_label_to_local_id);
            let current_node_id_to_local_id =
                std::mem::take(&mut self.node_id_to_local_id);
            let current_trait_map = std::mem::take(&mut self.trait_map);
            let current_owner =
                std::mem::replace(&mut self.current_hir_id_owner, owner_id);
            let current_local_counter =
                std::mem::replace(&mut self.item_local_id_counter,
                    hir::ItemLocalId::new(1));
            let current_impl_trait_defs =
                std::mem::take(&mut self.impl_trait_defs);
            let current_impl_trait_bounds =
                std::mem::take(&mut self.impl_trait_bounds);
            let current_delayed_lints =
                std::mem::take(&mut self.delayed_lints);
            {
                let _old =
                    self.node_id_to_local_id.insert(owner,
                        hir::ItemLocalId::ZERO);
                if true {
                    match (&_old, &None) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    };
                };
            }
            let item = f(self);
            match (&owner_id, &item.def_id()) {
                (left_val, right_val) => {
                    if !(*left_val == *right_val) {
                        let kind = ::core::panicking::AssertKind::Eq;
                        ::core::panicking::assert_failed(kind, &*left_val,
                            &*right_val, ::core::option::Option::None);
                    }
                }
            };
            if !self.impl_trait_defs.is_empty() {
                ::core::panicking::panic("assertion failed: self.impl_trait_defs.is_empty()")
            };
            if !self.impl_trait_bounds.is_empty() {
                ::core::panicking::panic("assertion failed: self.impl_trait_bounds.is_empty()")
            };
            let info = self.make_owner_info(item);
            self.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.node_id_to_local_id = current_node_id_to_local_id; }
            self.trait_map = current_trait_map;
            self.current_hir_id_owner = current_owner;
            self.item_local_id_counter = current_local_counter;
            self.impl_trait_defs = current_impl_trait_defs;
            self.impl_trait_bounds = current_impl_trait_bounds;
            self.delayed_lints = current_delayed_lints;
            if true {
                if !!self.children.iter().any(|(id, _)|
                                    id == &owner_id.def_id) {
                    ::core::panicking::panic("assertion failed: !self.children.iter().any(|(id, _)| id == &owner_id.def_id)")
                };
            };
            self.children.push((owner_id.def_id,
                    hir::MaybeOwner::Owner(info)));
        }
    }
}#[instrument(level = "debug", skip(self, f))]
706    fn with_hir_id_owner(
707        &mut self,
708        owner: NodeId,
709        f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
710    ) {
711        let owner_id = self.owner_id(owner);
712        let def_id = owner_id.def_id;
713
714        let new_disambig = self
715            .resolver
716            .disambiguators
717            .get(&def_id)
718            .map(|s| s.steal())
719            .unwrap_or_else(|| PerParentDisambiguatorState::new(def_id));
720
721        let disambiguator = std::mem::replace(&mut self.current_disambiguator, new_disambig);
722        let current_ast_owner = std::mem::replace(&mut self.owner, &self.resolver.owners[&owner]);
723        let current_attrs = std::mem::take(&mut self.attrs);
724        let current_bodies = std::mem::take(&mut self.bodies);
725        let current_define_opaque = std::mem::take(&mut self.define_opaque);
726        let current_ident_and_label_to_local_id =
727            std::mem::take(&mut self.ident_and_label_to_local_id);
728
729        #[cfg(debug_assertions)]
730        let current_node_id_to_local_id = std::mem::take(&mut self.node_id_to_local_id);
731        let current_trait_map = std::mem::take(&mut self.trait_map);
732        let current_owner = std::mem::replace(&mut self.current_hir_id_owner, owner_id);
733        let current_local_counter =
734            std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
735        let current_impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
736        let current_impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
737        let current_delayed_lints = std::mem::take(&mut self.delayed_lints);
738
739        // Do not reset `next_node_id` and `node_id_to_def_id`:
740        // we want `f` to be able to refer to the `LocalDefId`s that the caller created.
741        // and the caller to refer to some of the subdefinitions' nodes' `LocalDefId`s.
742
743        // Always allocate the first `HirId` for the owner itself.
744        #[cfg(debug_assertions)]
745        {
746            let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::ZERO);
747            debug_assert_eq!(_old, None);
748        }
749
750        let item = f(self);
751        assert_eq!(owner_id, item.def_id());
752        // `f` should have consumed all the elements in these vectors when constructing `item`.
753        assert!(self.impl_trait_defs.is_empty());
754        assert!(self.impl_trait_bounds.is_empty());
755        let info = self.make_owner_info(item);
756
757        self.current_disambiguator = disambiguator;
758        self.owner = current_ast_owner;
759        self.attrs = current_attrs;
760        self.bodies = current_bodies;
761        self.define_opaque = current_define_opaque;
762        self.ident_and_label_to_local_id = current_ident_and_label_to_local_id;
763
764        #[cfg(debug_assertions)]
765        {
766            self.node_id_to_local_id = current_node_id_to_local_id;
767        }
768        self.trait_map = current_trait_map;
769        self.current_hir_id_owner = current_owner;
770        self.item_local_id_counter = current_local_counter;
771        self.impl_trait_defs = current_impl_trait_defs;
772        self.impl_trait_bounds = current_impl_trait_bounds;
773        self.delayed_lints = current_delayed_lints;
774
775        debug_assert!(!self.children.iter().any(|(id, _)| id == &owner_id.def_id));
776        self.children.push((owner_id.def_id, hir::MaybeOwner::Owner(info)));
777    }
778
779    fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> {
780        let attrs = std::mem::take(&mut self.attrs);
781        let mut bodies = std::mem::take(&mut self.bodies);
782        let define_opaque = std::mem::take(&mut self.define_opaque);
783        let trait_map = std::mem::take(&mut self.trait_map);
784        let delayed_lints = Steal::new(std::mem::take(&mut self.delayed_lints).into_boxed_slice());
785
786        #[cfg(debug_assertions)]
787        for (id, attrs) in attrs.iter() {
788            // Verify that we do not store empty slices in the map.
789            if attrs.is_empty() {
790                {
    ::core::panicking::panic_fmt(format_args!("Stored empty attributes for {0:?}",
            id));
};panic!("Stored empty attributes for {:?}", id);
791            }
792        }
793
794        bodies.sort_by_key(|(k, _)| *k);
795        let bodies = SortedMap::from_presorted_elements(bodies);
796
797        // Don't hash unless necessary, because it's expensive.
798        let rustc_middle::hir::Hashes { opt_hash_including_bodies, attrs_hash } =
799            self.tcx.hash_owner_nodes(node, &bodies, &attrs, define_opaque);
800        let num_nodes = self.item_local_id_counter.as_usize();
801        let (nodes, parenting) = index::index_hir(self.tcx, node, &bodies, num_nodes);
802        let nodes = hir::OwnerNodes { opt_hash_including_bodies, nodes, bodies };
803        let attrs = hir::AttributeMap { map: attrs, opt_hash: attrs_hash, define_opaque };
804
805        self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map, delayed_lints })
806    }
807
808    /// This method allocates a new `HirId` for the given `NodeId`.
809    /// Take care not to call this method if the resulting `HirId` is then not
810    /// actually used in the HIR, as that would trigger an assertion in the
811    /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
812    /// properly. Calling the method twice with the same `NodeId` is also forbidden.
813    x;#[instrument(level = "debug", skip(self), ret)]
814    fn lower_node_id(&mut self, ast_node_id: NodeId) -> HirId {
815        assert_ne!(ast_node_id, DUMMY_NODE_ID);
816
817        let owner = self.current_hir_id_owner;
818        let local_id = self.item_local_id_counter;
819        assert_ne!(local_id, hir::ItemLocalId::ZERO);
820        self.item_local_id_counter.increment_by(1);
821        let hir_id = HirId { owner, local_id };
822
823        if let Some(def_id) = self.opt_local_def_id(ast_node_id) {
824            self.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id)));
825        }
826
827        if let Some(traits) = self.resolver.trait_map.get(&ast_node_id) {
828            self.trait_map.insert(hir_id.local_id, &traits[..]);
829        }
830
831        // Check whether the same `NodeId` is lowered more than once.
832        #[cfg(debug_assertions)]
833        {
834            let old = self.node_id_to_local_id.insert(ast_node_id, local_id);
835            assert_eq!(old, None);
836        }
837
838        hir_id
839    }
840
841    /// Generate a new `HirId` without a backing `NodeId`.
842    x;#[instrument(level = "debug", skip(self), ret)]
843    fn next_id(&mut self) -> HirId {
844        let owner = self.current_hir_id_owner;
845        let local_id = self.item_local_id_counter;
846        assert_ne!(local_id, hir::ItemLocalId::ZERO);
847        self.item_local_id_counter.increment_by(1);
848        HirId { owner, local_id }
849    }
850
851    #[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(851u32),
                                    ::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:858",
                                    "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(858u32),
                                    ::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))]
852    fn lower_res(&mut self, res: Res<NodeId>) -> Res {
853        let res: Result<Res, ()> = res.apply_id(|id| {
854            let owner = self.current_hir_id_owner;
855            let local_id = self.ident_and_label_to_local_id.get(&id).copied().ok_or(())?;
856            Ok(HirId { owner, local_id })
857        });
858        trace!(?res);
859
860        // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
861        // This can happen when trying to lower the return type `x` in erroneous code like
862        //   async fn foo(x: u8) -> x {}
863        // In that case, `x` is lowered as a function parameter, and the return type is lowered as
864        // an opaque type as a synthesized HIR owner.
865        res.unwrap_or(Res::Err)
866    }
867
868    fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
869        self.get_partial_res(id).map_or(Res::Err, |pr| pr.expect_full_res())
870    }
871
872    fn lower_import_res(&mut self, id: NodeId, span: Span) -> PerNS<Option<Res>> {
873        let per_ns = self.resolver.get_import_res(id);
874        let per_ns = per_ns.map(|res| res.map(|res| self.lower_res(res)));
875        if per_ns.is_empty() {
876            // Propagate the error to all namespaces, just to be sure.
877            self.dcx().span_delayed_bug(span, "no resolution for an import");
878            let err = Some(Res::Err);
879            return PerNS { type_ns: err, value_ns: err, macro_ns: err };
880        }
881        per_ns
882    }
883
884    fn make_lang_item_qpath(
885        &mut self,
886        lang_item: hir::LangItem,
887        span: Span,
888        args: Option<&'hir hir::GenericArgs<'hir>>,
889    ) -> hir::QPath<'hir> {
890        hir::QPath::Resolved(None, self.make_lang_item_path(lang_item, span, args))
891    }
892
893    fn make_lang_item_path(
894        &mut self,
895        lang_item: hir::LangItem,
896        span: Span,
897        args: Option<&'hir hir::GenericArgs<'hir>>,
898    ) -> &'hir hir::Path<'hir> {
899        let def_id = self.tcx.require_lang_item(lang_item, span);
900        let def_kind = self.tcx.def_kind(def_id);
901        let res = Res::Def(def_kind, def_id);
902        self.arena.alloc(hir::Path {
903            span,
904            res,
905            segments: self.arena.alloc_from_iter([hir::PathSegment {
906                ident: Ident::new(lang_item.name(), span),
907                hir_id: self.next_id(),
908                res,
909                args,
910                infer_args: args.is_none(),
911            }]),
912        })
913    }
914
915    /// Reuses the span but adds information like the kind of the desugaring and features that are
916    /// allowed inside this span.
917    fn mark_span_with_reason(
918        &self,
919        reason: DesugaringKind,
920        span: Span,
921        allow_internal_unstable: Option<Arc<[Symbol]>>,
922    ) -> Span {
923        self.tcx.with_stable_hashing_context(|hcx| {
924            span.mark_with_reason(allow_internal_unstable, reason, span.edition(), hcx)
925        })
926    }
927
928    fn span_lowerer(&self) -> SpanLowerer {
929        SpanLowerer {
930            is_incremental: self.tcx.sess.opts.incremental.is_some(),
931            def_id: self.current_hir_id_owner.def_id,
932        }
933    }
934
935    /// Intercept all spans entering HIR.
936    /// Mark a span as relative to the current owning item.
937    fn lower_span(&self, span: Span) -> Span {
938        self.span_lowerer().lower(span)
939    }
940
941    fn lower_ident(&self, ident: Ident) -> Ident {
942        Ident::new(ident.name, self.lower_span(ident.span))
943    }
944
945    /// Converts a lifetime into a new generic parameter.
946    #[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(946u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["ident", "node_id",
                                                    "res", "source"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<hir::GenericParam<'hir>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (name, kind) =
                match res {
                    LifetimeRes::Param { .. } => {
                        (hir::ParamName::Plain(ident),
                            hir::LifetimeParamKind::Explicit)
                    }
                    LifetimeRes::Fresh { param, kind, .. } => {
                        let _def_id =
                            self.create_def(param, Some(kw::UnderscoreLifetime),
                                DefKind::LifetimeParam, 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:966",
                                                "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(966u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                                ::tracing_core::field::FieldSet::new(&["_def_id"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&_def_id) as
                                                                    &dyn Value))])
                                    });
                            } else { ; }
                        };
                        (hir::ParamName::Fresh,
                            hir::LifetimeParamKind::Elided(kind))
                    }
                    LifetimeRes::Static { .. } | LifetimeRes::Error(..) =>
                        return None,
                    res => {
                        ::core::panicking::panic_fmt(format_args!("Unexpected lifetime resolution {0:?} for {1:?} at {2:?}",
                                res, ident, ident.span));
                    }
                };
            let hir_id = self.lower_node_id(node_id);
            let def_id = self.local_def_id(node_id);
            Some(hir::GenericParam {
                    hir_id,
                    def_id,
                    name,
                    span: self.lower_span(ident.span),
                    pure_wrt_drop: false,
                    kind: hir::GenericParamKind::Lifetime { kind },
                    colon_span: None,
                    source,
                })
        }
    }
}#[instrument(level = "debug", skip(self))]
947    fn lifetime_res_to_generic_param(
948        &mut self,
949        ident: Ident,
950        node_id: NodeId,
951        res: LifetimeRes,
952        source: hir::GenericParamSource,
953    ) -> Option<hir::GenericParam<'hir>> {
954        let (name, kind) = match res {
955            LifetimeRes::Param { .. } => {
956                (hir::ParamName::Plain(ident), hir::LifetimeParamKind::Explicit)
957            }
958            LifetimeRes::Fresh { param, kind, .. } => {
959                // Late resolution delegates to us the creation of the `LocalDefId`.
960                let _def_id = self.create_def(
961                    param,
962                    Some(kw::UnderscoreLifetime),
963                    DefKind::LifetimeParam,
964                    ident.span,
965                );
966                debug!(?_def_id);
967
968                (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided(kind))
969            }
970            LifetimeRes::Static { .. } | LifetimeRes::Error(..) => return None,
971            res => panic!(
972                "Unexpected lifetime resolution {:?} for {:?} at {:?}",
973                res, ident, ident.span
974            ),
975        };
976        let hir_id = self.lower_node_id(node_id);
977        let def_id = self.local_def_id(node_id);
978        Some(hir::GenericParam {
979            hir_id,
980            def_id,
981            name,
982            span: self.lower_span(ident.span),
983            pure_wrt_drop: false,
984            kind: hir::GenericParamKind::Lifetime { kind },
985            colon_span: None,
986            source,
987        })
988    }
989
990    /// Lowers a lifetime binder that defines `generic_params`, returning the corresponding HIR
991    /// nodes. The returned list includes any "extra" lifetime parameters that were added by the
992    /// name resolver owing to lifetime elision; this also populates the resolver's node-id->def-id
993    /// map, so that later calls to `opt_node_id_to_def_id` that refer to these extra lifetime
994    /// parameters will be successful.
995    x;#[instrument(level = "debug", skip(self), ret)]
996    #[inline]
997    fn lower_lifetime_binder(
998        &mut self,
999        binder: NodeId,
1000        generic_params: &[GenericParam],
1001    ) -> &'hir [hir::GenericParam<'hir>] {
1002        // Start by creating params for extra lifetimes params, as this creates the definitions
1003        // that may be referred to by the AST inside `generic_params`.
1004        let extra_lifetimes = self.resolver.extra_lifetime_params(binder);
1005        debug!(?extra_lifetimes);
1006        let extra_lifetimes: Vec<_> = extra_lifetimes
1007            .iter()
1008            .filter_map(|&(ident, node_id, res)| {
1009                self.lifetime_res_to_generic_param(
1010                    ident,
1011                    node_id,
1012                    res,
1013                    hir::GenericParamSource::Binder,
1014                )
1015            })
1016            .collect();
1017        let arena = self.arena;
1018        let explicit_generic_params =
1019            self.lower_generic_params_mut(generic_params, hir::GenericParamSource::Binder);
1020        arena.alloc_from_iter(explicit_generic_params.chain(extra_lifetimes.into_iter()))
1021    }
1022
1023    fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
1024        let was_in_dyn_type = self.is_in_dyn_type;
1025        self.is_in_dyn_type = in_scope;
1026
1027        let result = f(self);
1028
1029        self.is_in_dyn_type = was_in_dyn_type;
1030
1031        result
1032    }
1033
1034    fn with_new_scopes<T>(&mut self, scope_span: Span, f: impl FnOnce(&mut Self) -> T) -> T {
1035        let current_item = self.current_item;
1036        self.current_item = Some(scope_span);
1037
1038        let was_in_loop_condition = self.is_in_loop_condition;
1039        self.is_in_loop_condition = false;
1040
1041        let old_contract = self.contract_ensures.take();
1042
1043        let try_block_scope = mem::replace(&mut self.try_block_scope, TryBlockScope::Function);
1044        let loop_scope = self.loop_scope.take();
1045        let ret = f(self);
1046        self.try_block_scope = try_block_scope;
1047        self.loop_scope = loop_scope;
1048
1049        self.contract_ensures = old_contract;
1050
1051        self.is_in_loop_condition = was_in_loop_condition;
1052
1053        self.current_item = current_item;
1054
1055        ret
1056    }
1057
1058    fn lower_attrs(
1059        &mut self,
1060        id: HirId,
1061        attrs: &[Attribute],
1062        target_span: Span,
1063        target: Target,
1064    ) -> &'hir [hir::Attribute] {
1065        self.lower_attrs_with_extra(id, attrs, target_span, target, &[])
1066    }
1067
1068    fn lower_attrs_with_extra(
1069        &mut self,
1070        id: HirId,
1071        attrs: &[Attribute],
1072        target_span: Span,
1073        target: Target,
1074        extra_hir_attributes: &[hir::Attribute],
1075    ) -> &'hir [hir::Attribute] {
1076        if attrs.is_empty() && extra_hir_attributes.is_empty() {
1077            &[]
1078        } else {
1079            let mut lowered_attrs =
1080                self.lower_attrs_vec(attrs, self.lower_span(target_span), id, target);
1081            lowered_attrs.extend(extra_hir_attributes.iter().cloned());
1082
1083            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);
1084            let ret = self.arena.alloc_from_iter(lowered_attrs);
1085
1086            // this is possible if an item contained syntactical attribute,
1087            // but none of them parse successfully or all of them were ignored
1088            // for not being built-in attributes at all. They could be remaining
1089            // unexpanded attributes used as markers in proc-macro derives for example.
1090            // This will have emitted some diagnostics for the misparse, but will then
1091            // not emit the attribute making the list empty.
1092            if ret.is_empty() {
1093                &[]
1094            } else {
1095                self.attrs.insert(id.local_id, ret);
1096                ret
1097            }
1098        }
1099    }
1100
1101    fn lower_attrs_vec(
1102        &mut self,
1103        attrs: &[Attribute],
1104        target_span: Span,
1105        target_hir_id: HirId,
1106        target: Target,
1107    ) -> Vec<hir::Attribute> {
1108        let l = self.span_lowerer();
1109        self.attribute_parser.parse_attribute_list(
1110            attrs,
1111            target_span,
1112            target,
1113            OmitDoc::Lower,
1114            |s| l.lower(s),
1115            |lint_id, span, kind| {
1116                self.delayed_lints.push(DelayedLint {
1117                    lint_id,
1118                    id: target_hir_id,
1119                    span,
1120                    callback: Box::new(move |dcx, level, sess: &dyn std::any::Any| {
1121                        let sess = sess
1122                            .downcast_ref::<rustc_session::Session>()
1123                            .expect("expected `Session`");
1124                        (kind.0)(dcx, level, sess)
1125                    }),
1126                });
1127            },
1128        )
1129    }
1130
1131    fn alias_attrs(&mut self, id: HirId, target_id: HirId) {
1132        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);
1133        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);
1134        if let Some(&a) = self.attrs.get(&target_id.local_id) {
1135            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
1136            self.attrs.insert(id.local_id, a);
1137        }
1138    }
1139
1140    fn lower_delim_args(&self, args: &DelimArgs) -> DelimArgs {
1141        args.clone()
1142    }
1143
1144    /// Lower an associated item constraint.
1145    #[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(1145u32),
                                    ::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:1151",
                                    "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(1151u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["constraint",
                                                    "itctx"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&constraint)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&itctx) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            let gen_args =
                if let Some(gen_args) = &constraint.gen_args {
                    let gen_args_ctor =
                        match gen_args {
                            GenericArgs::AngleBracketed(data) => {
                                self.lower_angle_bracketed_parameter_data(data,
                                        ParamMode::Explicit, itctx).0
                            }
                            GenericArgs::Parenthesized(data) => {
                                if let Some(first_char) =
                                            constraint.ident.as_str().chars().next() &&
                                        first_char.is_ascii_lowercase() {
                                    let err =
                                        match (&data.inputs[..], &data.output) {
                                            ([_, ..], FnRetTy::Default(_)) => {
                                                errors::BadReturnTypeNotation::Inputs {
                                                    span: data.inputs_span,
                                                }
                                            }
                                            ([], FnRetTy::Default(_)) => {
                                                errors::BadReturnTypeNotation::NeedsDots {
                                                    span: data.inputs_span,
                                                }
                                            }
                                            (_, FnRetTy::Ty(ty)) => {
                                                let span = data.inputs_span.shrink_to_hi().to(ty.span);
                                                errors::BadReturnTypeNotation::Output {
                                                    span,
                                                    suggestion: errors::RTNSuggestion {
                                                        output: span,
                                                        input: data.inputs_span,
                                                    },
                                                }
                                            }
                                        };
                                    let mut err = self.dcx().create_err(err);
                                    if !self.tcx.features().return_type_notation() &&
                                            self.tcx.sess.is_nightly_build() {
                                        add_feature_diagnostics(&mut err, &self.tcx.sess,
                                            sym::return_type_notation);
                                    }
                                    err.emit();
                                    GenericArgsCtor {
                                        args: Default::default(),
                                        constraints: &[],
                                        parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
                                        span: data.span,
                                    }
                                } else {
                                    self.emit_bad_parenthesized_trait_in_assoc_ty(data);
                                    self.lower_angle_bracketed_parameter_data(&data.as_angle_bracketed_args(),
                                            ParamMode::Explicit, itctx).0
                                }
                            }
                            GenericArgs::ParenthesizedElided(span) =>
                                GenericArgsCtor {
                                    args: Default::default(),
                                    constraints: &[],
                                    parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
                                    span: *span,
                                },
                        };
                    gen_args_ctor.into_generic_args(self)
                } else { hir::GenericArgs::NONE };
            let kind =
                match &constraint.kind {
                    AssocItemConstraintKind::Equality { term } => {
                        let term =
                            match term {
                                Term::Ty(ty) => self.lower_ty_alloc(ty, itctx).into(),
                                Term::Const(c) =>
                                    self.lower_anon_const_to_const_arg_and_alloc(c).into(),
                            };
                        hir::AssocItemConstraintKind::Equality { term }
                    }
                    AssocItemConstraintKind::Bound { bounds } => {
                        if self.is_in_dyn_type {
                            let suggestion =
                                match itctx {
                                    ImplTraitContext::OpaqueTy { .. } |
                                        ImplTraitContext::Universal => {
                                        let bound_end_span =
                                            constraint.gen_args.as_ref().map_or(constraint.ident.span,
                                                |args| args.span());
                                        if bound_end_span.eq_ctxt(constraint.span) {
                                            Some(self.tcx.sess.source_map().next_point(bound_end_span))
                                        } else { None }
                                    }
                                    _ => None,
                                };
                            let guar =
                                self.dcx().emit_err(errors::MisplacedAssocTyBinding {
                                        span: constraint.span,
                                        suggestion,
                                    });
                            let err_ty =
                                &*self.arena.alloc(self.ty(constraint.span,
                                                hir::TyKind::Err(guar)));
                            hir::AssocItemConstraintKind::Equality {
                                term: err_ty.into(),
                            }
                        } else {
                            let bounds =
                                self.lower_param_bounds(bounds,
                                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::AssocTyBounds),
                                    itctx);
                            hir::AssocItemConstraintKind::Bound { bounds }
                        }
                    }
                };
            hir::AssocItemConstraint {
                hir_id: self.lower_node_id(constraint.id),
                ident: self.lower_ident(constraint.ident),
                gen_args,
                kind,
                span: self.lower_span(constraint.span),
            }
        }
    }
}#[instrument(level = "debug", skip_all)]
1146    fn lower_assoc_item_constraint(
1147        &mut self,
1148        constraint: &AssocItemConstraint,
1149        itctx: ImplTraitContext,
1150    ) -> hir::AssocItemConstraint<'hir> {
1151        debug!(?constraint, ?itctx);
1152        // Lower the generic arguments for the associated item.
1153        let gen_args = if let Some(gen_args) = &constraint.gen_args {
1154            let gen_args_ctor = match gen_args {
1155                GenericArgs::AngleBracketed(data) => {
1156                    self.lower_angle_bracketed_parameter_data(data, ParamMode::Explicit, itctx).0
1157                }
1158                GenericArgs::Parenthesized(data) => {
1159                    if let Some(first_char) = constraint.ident.as_str().chars().next()
1160                        && first_char.is_ascii_lowercase()
1161                    {
1162                        let err = match (&data.inputs[..], &data.output) {
1163                            ([_, ..], FnRetTy::Default(_)) => {
1164                                errors::BadReturnTypeNotation::Inputs { span: data.inputs_span }
1165                            }
1166                            ([], FnRetTy::Default(_)) => {
1167                                errors::BadReturnTypeNotation::NeedsDots { span: data.inputs_span }
1168                            }
1169                            // The case `T: Trait<method(..) -> Ret>` is handled in the parser.
1170                            (_, FnRetTy::Ty(ty)) => {
1171                                let span = data.inputs_span.shrink_to_hi().to(ty.span);
1172                                errors::BadReturnTypeNotation::Output {
1173                                    span,
1174                                    suggestion: errors::RTNSuggestion {
1175                                        output: span,
1176                                        input: data.inputs_span,
1177                                    },
1178                                }
1179                            }
1180                        };
1181                        let mut err = self.dcx().create_err(err);
1182                        if !self.tcx.features().return_type_notation()
1183                            && self.tcx.sess.is_nightly_build()
1184                        {
1185                            add_feature_diagnostics(
1186                                &mut err,
1187                                &self.tcx.sess,
1188                                sym::return_type_notation,
1189                            );
1190                        }
1191                        err.emit();
1192                        GenericArgsCtor {
1193                            args: Default::default(),
1194                            constraints: &[],
1195                            parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
1196                            span: data.span,
1197                        }
1198                    } else {
1199                        self.emit_bad_parenthesized_trait_in_assoc_ty(data);
1200                        self.lower_angle_bracketed_parameter_data(
1201                            &data.as_angle_bracketed_args(),
1202                            ParamMode::Explicit,
1203                            itctx,
1204                        )
1205                        .0
1206                    }
1207                }
1208                GenericArgs::ParenthesizedElided(span) => GenericArgsCtor {
1209                    args: Default::default(),
1210                    constraints: &[],
1211                    parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
1212                    span: *span,
1213                },
1214            };
1215            gen_args_ctor.into_generic_args(self)
1216        } else {
1217            hir::GenericArgs::NONE
1218        };
1219        let kind = match &constraint.kind {
1220            AssocItemConstraintKind::Equality { term } => {
1221                let term = match term {
1222                    Term::Ty(ty) => self.lower_ty_alloc(ty, itctx).into(),
1223                    Term::Const(c) => self.lower_anon_const_to_const_arg_and_alloc(c).into(),
1224                };
1225                hir::AssocItemConstraintKind::Equality { term }
1226            }
1227            AssocItemConstraintKind::Bound { bounds } => {
1228                // Disallow ATB in dyn types
1229                if self.is_in_dyn_type {
1230                    let suggestion = match itctx {
1231                        ImplTraitContext::OpaqueTy { .. } | ImplTraitContext::Universal => {
1232                            let bound_end_span = constraint
1233                                .gen_args
1234                                .as_ref()
1235                                .map_or(constraint.ident.span, |args| args.span());
1236                            if bound_end_span.eq_ctxt(constraint.span) {
1237                                Some(self.tcx.sess.source_map().next_point(bound_end_span))
1238                            } else {
1239                                None
1240                            }
1241                        }
1242                        _ => None,
1243                    };
1244
1245                    let guar = self.dcx().emit_err(errors::MisplacedAssocTyBinding {
1246                        span: constraint.span,
1247                        suggestion,
1248                    });
1249                    let err_ty =
1250                        &*self.arena.alloc(self.ty(constraint.span, hir::TyKind::Err(guar)));
1251                    hir::AssocItemConstraintKind::Equality { term: err_ty.into() }
1252                } else {
1253                    let bounds = self.lower_param_bounds(
1254                        bounds,
1255                        RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::AssocTyBounds),
1256                        itctx,
1257                    );
1258                    hir::AssocItemConstraintKind::Bound { bounds }
1259                }
1260            }
1261        };
1262
1263        hir::AssocItemConstraint {
1264            hir_id: self.lower_node_id(constraint.id),
1265            ident: self.lower_ident(constraint.ident),
1266            gen_args,
1267            kind,
1268            span: self.lower_span(constraint.span),
1269        }
1270    }
1271
1272    fn emit_bad_parenthesized_trait_in_assoc_ty(&self, data: &ParenthesizedArgs) {
1273        // Suggest removing empty parentheses: "Trait()" -> "Trait"
1274        let sub = if data.inputs.is_empty() {
1275            let parentheses_span =
1276                data.inputs_span.shrink_to_lo().to(data.inputs_span.shrink_to_hi());
1277            AssocTyParenthesesSub::Empty { parentheses_span }
1278        }
1279        // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
1280        else {
1281            // Start of parameters to the 1st argument
1282            let open_param = data.inputs_span.shrink_to_lo().to(data
1283                .inputs
1284                .first()
1285                .unwrap()
1286                .span
1287                .shrink_to_lo());
1288            // End of last argument to end of parameters
1289            let close_param =
1290                data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi());
1291            AssocTyParenthesesSub::NotEmpty { open_param, close_param }
1292        };
1293        self.dcx().emit_err(AssocTyParentheses { span: data.span, sub });
1294    }
1295
1296    #[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(1296u32),
                                    ::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:1333",
                                                            "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(1333u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                        ::tracing::__macro_support::Option::Some(&format_args!("lower_generic_arg: Lowering type argument as const argument: {0:?}",
                                                                                        ty) as &dyn Value))])
                                                });
                                        } else { ; }
                                    };
                                    let ct =
                                        self.lower_const_path_to_const_arg(path, res, ty.id,
                                            ty.span);
                                    return GenericArg::Const(ct.try_as_ambig_ct().unwrap());
                                }
                            }
                        }
                        _ => {}
                    }
                    GenericArg::Type(self.lower_ty_alloc(ty,
                                    itctx).try_as_ambig_ty().unwrap())
                }
                ast::GenericArg::Const(ct) => {
                    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))]
1297    fn lower_generic_arg(
1298        &mut self,
1299        arg: &ast::GenericArg,
1300        itctx: ImplTraitContext,
1301    ) -> hir::GenericArg<'hir> {
1302        match arg {
1303            ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(
1304                lt,
1305                LifetimeSource::Path { angle_brackets: hir::AngleBrackets::Full },
1306                lt.ident.into(),
1307            )),
1308            ast::GenericArg::Type(ty) => {
1309                // We cannot just match on `TyKind::Infer` as `(_)` is represented as
1310                // `TyKind::Paren(TyKind::Infer)` and should also be lowered to `GenericArg::Infer`
1311                if ty.is_maybe_parenthesised_infer() {
1312                    return GenericArg::Infer(hir::InferArg {
1313                        hir_id: self.lower_node_id(ty.id),
1314                        span: self.lower_span(ty.span),
1315                    });
1316                }
1317
1318                match &ty.kind {
1319                    // We parse const arguments as path types as we cannot distinguish them during
1320                    // parsing. We try to resolve that ambiguity by attempting resolution in both the
1321                    // type and value namespaces. If we resolved the path in the value namespace, we
1322                    // transform it into a generic const argument.
1323                    //
1324                    // FIXME: Should we be handling `(PATH_TO_CONST)`?
1325                    TyKind::Path(None, path) => {
1326                        if let Some(res) = self
1327                            .get_partial_res(ty.id)
1328                            .and_then(|partial_res| partial_res.full_res())
1329                        {
1330                            if !res.matches_ns(Namespace::TypeNS)
1331                                && path.is_potential_trivial_const_arg()
1332                            {
1333                                debug!(
1334                                    "lower_generic_arg: Lowering type argument as const argument: {:?}",
1335                                    ty,
1336                                );
1337
1338                                let ct =
1339                                    self.lower_const_path_to_const_arg(path, res, ty.id, ty.span);
1340                                return GenericArg::Const(ct.try_as_ambig_ct().unwrap());
1341                            }
1342                        }
1343                    }
1344                    _ => {}
1345                }
1346                GenericArg::Type(self.lower_ty_alloc(ty, itctx).try_as_ambig_ty().unwrap())
1347            }
1348            ast::GenericArg::Const(ct) => {
1349                let ct = self.lower_anon_const_to_const_arg_and_alloc(ct);
1350                match ct.try_as_ambig_ct() {
1351                    Some(ct) => GenericArg::Const(ct),
1352                    None => GenericArg::Infer(hir::InferArg { hir_id: ct.hir_id, span: ct.span }),
1353                }
1354            }
1355        }
1356    }
1357
1358    #[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(1358u32),
                                    ::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))]
1359    fn lower_ty_alloc(&mut self, t: &Ty, itctx: ImplTraitContext) -> &'hir hir::Ty<'hir> {
1360        self.arena.alloc(self.lower_ty(t, itctx))
1361    }
1362
1363    fn lower_path_ty(
1364        &mut self,
1365        t: &Ty,
1366        qself: &Option<Box<QSelf>>,
1367        path: &Path,
1368        param_mode: ParamMode,
1369        itctx: ImplTraitContext,
1370    ) -> hir::Ty<'hir> {
1371        // Check whether we should interpret this as a bare trait object.
1372        // This check mirrors the one in late resolution. We only introduce this special case in
1373        // the rare occurrence we need to lower `Fresh` anonymous lifetimes.
1374        // The other cases when a qpath should be opportunistically made a trait object are handled
1375        // by `ty_path`.
1376        if qself.is_none()
1377            && let Some(partial_res) = self.get_partial_res(t.id)
1378            && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res()
1379        {
1380            let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1381                let bound = this.lower_poly_trait_ref(
1382                    &PolyTraitRef {
1383                        bound_generic_params: ThinVec::new(),
1384                        modifiers: TraitBoundModifiers::NONE,
1385                        trait_ref: TraitRef { path: path.clone(), ref_id: t.id },
1386                        span: t.span,
1387                        parens: ast::Parens::No,
1388                    },
1389                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitObjectTy),
1390                    itctx,
1391                );
1392                let bounds = this.arena.alloc_from_iter([bound]);
1393                let lifetime_bound = this.elided_dyn_bound(t.span);
1394                (bounds, lifetime_bound)
1395            });
1396            let kind = hir::TyKind::TraitObject(
1397                bounds,
1398                TaggedRef::new(lifetime_bound, TraitObjectSyntax::None),
1399            );
1400            return hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.next_id() };
1401        }
1402
1403        let id = self.lower_node_id(t.id);
1404        let qpath = self.lower_qpath(
1405            t.id,
1406            qself,
1407            path,
1408            param_mode,
1409            AllowReturnTypeNotation::Yes,
1410            itctx,
1411            None,
1412        );
1413        self.ty_path(id, t.span, qpath)
1414    }
1415
1416    fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1417        hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1418    }
1419
1420    fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1421        self.ty(span, hir::TyKind::Tup(tys))
1422    }
1423
1424    fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> hir::Ty<'hir> {
1425        let kind = match &t.kind {
1426            TyKind::Infer => hir::TyKind::Infer(()),
1427            TyKind::Err(guar) => hir::TyKind::Err(*guar),
1428            TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty_alloc(ty, itctx)),
1429            TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1430            TyKind::Ref(region, mt) => {
1431                let lifetime = self.lower_ty_direct_lifetime(t, *region);
1432                hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx))
1433            }
1434            TyKind::PinnedRef(region, mt) => {
1435                let lifetime = self.lower_ty_direct_lifetime(t, *region);
1436                let kind = hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx));
1437                let span = self.lower_span(t.span);
1438                let arg = hir::Ty { kind, span, hir_id: self.next_id() };
1439                let args = self.arena.alloc(hir::GenericArgs {
1440                    args: self.arena.alloc([hir::GenericArg::Type(self.arena.alloc(arg))]),
1441                    constraints: &[],
1442                    parenthesized: hir::GenericArgsParentheses::No,
1443                    span_ext: span,
1444                });
1445                let path = self.make_lang_item_qpath(hir::LangItem::Pin, span, Some(args));
1446                hir::TyKind::Path(path)
1447            }
1448            TyKind::FnPtr(f) => {
1449                let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1450                hir::TyKind::FnPtr(self.arena.alloc(hir::FnPtrTy {
1451                    generic_params,
1452                    safety: self.lower_safety(f.safety, hir::Safety::Safe),
1453                    abi: self.lower_extern(f.ext),
1454                    decl: self.lower_fn_decl(&f.decl, t.id, t.span, FnDeclKind::Pointer, None),
1455                    param_idents: self.lower_fn_params_to_idents(&f.decl),
1456                }))
1457            }
1458            TyKind::UnsafeBinder(f) => {
1459                let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1460                hir::TyKind::UnsafeBinder(self.arena.alloc(hir::UnsafeBinderTy {
1461                    generic_params,
1462                    inner_ty: self.lower_ty_alloc(&f.inner_ty, itctx),
1463                }))
1464            }
1465            TyKind::Never => hir::TyKind::Never,
1466            TyKind::Tup(tys) => hir::TyKind::Tup(
1467                self.arena.alloc_from_iter(tys.iter().map(|ty| self.lower_ty(ty, itctx))),
1468            ),
1469            TyKind::Paren(ty) => {
1470                return self.lower_ty(ty, itctx);
1471            }
1472            TyKind::Path(qself, path) => {
1473                return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1474            }
1475            TyKind::ImplicitSelf => {
1476                let hir_id = self.next_id();
1477                let res = self.expect_full_res(t.id);
1478                let res = self.lower_res(res);
1479                hir::TyKind::Path(hir::QPath::Resolved(
1480                    None,
1481                    self.arena.alloc(hir::Path {
1482                        res,
1483                        segments: self.arena.alloc_from_iter([hir::PathSegment::new(Ident::with_dummy_span(kw::SelfUpper),
                hir_id, res)])arena_vec![self; hir::PathSegment::new(
1484                            Ident::with_dummy_span(kw::SelfUpper),
1485                            hir_id,
1486                            res
1487                        )],
1488                        span: self.lower_span(t.span),
1489                    }),
1490                ))
1491            }
1492            TyKind::Array(ty, length) => hir::TyKind::Array(
1493                self.lower_ty_alloc(ty, itctx),
1494                self.lower_array_length_to_const_arg(length),
1495            ),
1496            TyKind::TraitObject(bounds, kind) => {
1497                let mut lifetime_bound = None;
1498                let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1499                    let bounds =
1500                        this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| match bound {
1501                            // We can safely ignore constness here since AST validation
1502                            // takes care of rejecting invalid modifier combinations and
1503                            // const trait bounds in trait object types.
1504                            GenericBound::Trait(ty) => {
1505                                let trait_ref = this.lower_poly_trait_ref(
1506                                    ty,
1507                                    RelaxedBoundPolicy::Forbidden(
1508                                        RelaxedBoundForbiddenReason::TraitObjectTy,
1509                                    ),
1510                                    itctx,
1511                                );
1512                                Some(trait_ref)
1513                            }
1514                            GenericBound::Outlives(lifetime) => {
1515                                if lifetime_bound.is_none() {
1516                                    lifetime_bound = Some(this.lower_lifetime(
1517                                        lifetime,
1518                                        LifetimeSource::Other,
1519                                        lifetime.ident.into(),
1520                                    ));
1521                                }
1522                                None
1523                            }
1524                            // Ignore `use` syntax since that is not valid in objects.
1525                            GenericBound::Use(_, span) => {
1526                                this.dcx()
1527                                    .span_delayed_bug(*span, "use<> not allowed in dyn types");
1528                                None
1529                            }
1530                        }));
1531                    let lifetime_bound =
1532                        lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1533                    (bounds, lifetime_bound)
1534                });
1535                hir::TyKind::TraitObject(bounds, TaggedRef::new(lifetime_bound, *kind))
1536            }
1537            TyKind::ImplTrait(def_node_id, bounds) => {
1538                let span = t.span;
1539                match itctx {
1540                    ImplTraitContext::OpaqueTy { origin } => {
1541                        self.lower_opaque_impl_trait(span, origin, *def_node_id, bounds, itctx)
1542                    }
1543                    ImplTraitContext::Universal => {
1544                        if let Some(span) = bounds.iter().find_map(|bound| match *bound {
1545                            ast::GenericBound::Use(_, span) => Some(span),
1546                            _ => None,
1547                        }) {
1548                            self.tcx.dcx().emit_err(errors::NoPreciseCapturesOnApit { span });
1549                        }
1550
1551                        let def_id = self.local_def_id(*def_node_id);
1552                        let name = self.tcx.item_name(def_id.to_def_id());
1553                        let ident = Ident::new(name, span);
1554                        let (param, bounds, path) = self.lower_universal_param_and_bounds(
1555                            *def_node_id,
1556                            span,
1557                            ident,
1558                            bounds,
1559                        );
1560                        self.impl_trait_defs.push(param);
1561                        if let Some(bounds) = bounds {
1562                            self.impl_trait_bounds.push(bounds);
1563                        }
1564                        path
1565                    }
1566                    ImplTraitContext::InBinding => hir::TyKind::TraitAscription(
1567                        self.lower_param_bounds(bounds, RelaxedBoundPolicy::Allowed, itctx),
1568                    ),
1569                    ImplTraitContext::FeatureGated(position, feature) => {
1570                        let guar = self
1571                            .tcx
1572                            .sess
1573                            .create_feature_err(
1574                                MisplacedImplTrait {
1575                                    span: t.span,
1576                                    position: DiagArgFromDisplay(&position),
1577                                },
1578                                feature,
1579                            )
1580                            .emit();
1581                        hir::TyKind::Err(guar)
1582                    }
1583                    ImplTraitContext::Disallowed(position) => {
1584                        let guar = self.dcx().emit_err(MisplacedImplTrait {
1585                            span: t.span,
1586                            position: DiagArgFromDisplay(&position),
1587                        });
1588                        hir::TyKind::Err(guar)
1589                    }
1590                }
1591            }
1592            TyKind::Pat(ty, pat) => {
1593                hir::TyKind::Pat(self.lower_ty_alloc(ty, itctx), self.lower_ty_pat(pat, ty.span))
1594            }
1595            TyKind::FieldOf(ty, variant, field) => hir::TyKind::FieldOf(
1596                self.lower_ty_alloc(ty, itctx),
1597                self.arena.alloc(hir::TyFieldPath {
1598                    variant: variant.map(|variant| self.lower_ident(variant)),
1599                    field: self.lower_ident(*field),
1600                }),
1601            ),
1602            TyKind::MacCall(_) => {
1603                ::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")
1604            }
1605            TyKind::CVarArgs => {
1606                let guar = self.dcx().span_delayed_bug(
1607                    t.span,
1608                    "`TyKind::CVarArgs` should have been handled elsewhere",
1609                );
1610                hir::TyKind::Err(guar)
1611            }
1612            TyKind::Dummy => {
    ::core::panicking::panic_fmt(format_args!("`TyKind::Dummy` should never be lowered"));
}panic!("`TyKind::Dummy` should never be lowered"),
1613        };
1614
1615        hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1616    }
1617
1618    fn lower_ty_direct_lifetime(
1619        &mut self,
1620        t: &Ty,
1621        region: Option<Lifetime>,
1622    ) -> &'hir hir::Lifetime {
1623        let (region, syntax) = match region {
1624            Some(region) => (region, region.ident.into()),
1625
1626            None => {
1627                let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1628                    self.resolver.get_lifetime_res(t.id)
1629                {
1630                    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);
1631                    start
1632                } else {
1633                    self.next_node_id()
1634                };
1635                let span = self.tcx.sess.source_map().start_point(t.span).shrink_to_hi();
1636                let region = Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id };
1637                (region, LifetimeSyntax::Implicit)
1638            }
1639        };
1640        self.lower_lifetime(&region, LifetimeSource::Reference, syntax)
1641    }
1642
1643    /// Lowers a `ReturnPositionOpaqueTy` (`-> impl Trait`) or a `TypeAliasesOpaqueTy` (`type F =
1644    /// impl Trait`): this creates the associated Opaque Type (TAIT) definition and then returns a
1645    /// HIR type that references the TAIT.
1646    ///
1647    /// Given a function definition like:
1648    ///
1649    /// ```rust
1650    /// use std::fmt::Debug;
1651    ///
1652    /// fn test<'a, T: Debug>(x: &'a T) -> impl Debug + 'a {
1653    ///     x
1654    /// }
1655    /// ```
1656    ///
1657    /// we will create a TAIT definition in the HIR like
1658    ///
1659    /// ```rust,ignore (pseudo-Rust)
1660    /// type TestReturn<'a, T, 'x> = impl Debug + 'x
1661    /// ```
1662    ///
1663    /// and return a type like `TestReturn<'static, T, 'a>`, so that the function looks like:
1664    ///
1665    /// ```rust,ignore (pseudo-Rust)
1666    /// fn test<'a, T: Debug>(x: &'a T) -> TestReturn<'static, T, 'a>
1667    /// ```
1668    ///
1669    /// Note the subtlety around type parameters! The new TAIT, `TestReturn`, inherits all the
1670    /// type parameters from the function `test` (this is implemented in the query layer, they aren't
1671    /// added explicitly in the HIR). But this includes all the lifetimes, and we only want to
1672    /// capture the lifetimes that are referenced in the bounds. Therefore, we add *extra* lifetime parameters
1673    /// for the lifetimes that get captured (`'x`, in our example above) and reference those.
1674    x;#[instrument(level = "debug", skip(self), ret)]
1675    fn lower_opaque_impl_trait(
1676        &mut self,
1677        span: Span,
1678        origin: hir::OpaqueTyOrigin<LocalDefId>,
1679        opaque_ty_node_id: NodeId,
1680        bounds: &GenericBounds,
1681        itctx: ImplTraitContext,
1682    ) -> hir::TyKind<'hir> {
1683        // Make sure we know that some funky desugaring has been going on here.
1684        // This is a first: there is code in other places like for loop
1685        // desugaring that explicitly states that we don't want to track that.
1686        // Not tracking it makes lints in rustc and clippy very fragile, as
1687        // frequently opened issues show.
1688        let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1689
1690        self.lower_opaque_inner(opaque_ty_node_id, origin, opaque_ty_span, |this| {
1691            this.lower_param_bounds(bounds, RelaxedBoundPolicy::Allowed, itctx)
1692        })
1693    }
1694
1695    fn lower_opaque_inner(
1696        &mut self,
1697        opaque_ty_node_id: NodeId,
1698        origin: hir::OpaqueTyOrigin<LocalDefId>,
1699        opaque_ty_span: Span,
1700        lower_item_bounds: impl FnOnce(&mut Self) -> &'hir [hir::GenericBound<'hir>],
1701    ) -> hir::TyKind<'hir> {
1702        let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id);
1703        let opaque_ty_hir_id = self.lower_node_id(opaque_ty_node_id);
1704        {
    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:1704",
                        "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(1704u32),
                        ::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);
1705
1706        let bounds = lower_item_bounds(self);
1707        let opaque_ty_def = hir::OpaqueTy {
1708            hir_id: opaque_ty_hir_id,
1709            def_id: opaque_ty_def_id,
1710            bounds,
1711            origin,
1712            span: self.lower_span(opaque_ty_span),
1713        };
1714        let opaque_ty_def = self.arena.alloc(opaque_ty_def);
1715
1716        hir::TyKind::OpaqueDef(opaque_ty_def)
1717    }
1718
1719    fn lower_precise_capturing_args(
1720        &mut self,
1721        precise_capturing_args: &[PreciseCapturingArg],
1722    ) -> &'hir [hir::PreciseCapturingArg<'hir>] {
1723        self.arena.alloc_from_iter(precise_capturing_args.iter().map(|arg| match arg {
1724            PreciseCapturingArg::Lifetime(lt) => hir::PreciseCapturingArg::Lifetime(
1725                self.lower_lifetime(lt, LifetimeSource::PreciseCapturing, lt.ident.into()),
1726            ),
1727            PreciseCapturingArg::Arg(path, id) => {
1728                let [segment] = path.segments.as_slice() else {
1729                    ::core::panicking::panic("explicit panic");panic!();
1730                };
1731                let res = self.get_partial_res(*id).map_or(Res::Err, |partial_res| {
1732                    partial_res.full_res().expect("no partial res expected for precise capture arg")
1733                });
1734                hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
1735                    hir_id: self.lower_node_id(*id),
1736                    ident: self.lower_ident(segment.ident),
1737                    res: self.lower_res(res),
1738                })
1739            }
1740        }))
1741    }
1742
1743    fn lower_fn_params_to_idents(&mut self, decl: &FnDecl) -> &'hir [Option<Ident>] {
1744        self.arena.alloc_from_iter(decl.inputs.iter().map(|param| match param.pat.kind {
1745            PatKind::Missing => None,
1746            PatKind::Ident(_, ident, _) => Some(self.lower_ident(ident)),
1747            PatKind::Wild => Some(Ident::new(kw::Underscore, self.lower_span(param.pat.span))),
1748            _ => {
1749                self.dcx().span_delayed_bug(
1750                    param.pat.span,
1751                    "non-missing/ident/wild param pat must trigger an error",
1752                );
1753                None
1754            }
1755        }))
1756    }
1757
1758    /// Lowers a function declaration.
1759    ///
1760    /// `decl`: the unlowered (AST) function declaration.
1761    ///
1762    /// `fn_node_id`: `impl Trait` arguments are lowered into generic parameters on the given
1763    /// `NodeId`.
1764    ///
1765    /// `transform_return_type`: if `Some`, applies some conversion to the return type, such as is
1766    /// needed for `async fn` and `gen fn`. See [`CoroutineKind`] for more details.
1767    #[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(1767u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["decl", "fn_node_id",
                                                    "fn_span", "kind", "coro"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&decl)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_node_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coro)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'hir hir::FnDecl<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let c_variadic = decl.c_variadic();
            let mut inputs = &decl.inputs[..];
            if decl.c_variadic() { inputs = &inputs[..inputs.len() - 1]; }
            let inputs =
                self.arena.alloc_from_iter(inputs.iter().map(|param|
                            {
                                let itctx =
                                    match kind {
                                        FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl |
                                            FnDeclKind::Trait => {
                                            ImplTraitContext::Universal
                                        }
                                        FnDeclKind::ExternFn => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnParam)
                                        }
                                        FnDeclKind::Closure => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureParam)
                                        }
                                        FnDeclKind::Pointer => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerParam)
                                        }
                                    };
                                self.lower_ty(&param.ty, itctx)
                            }));
            let output =
                match coro {
                    Some(coro) => {
                        let fn_def_id = self.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.resolver.lifetime_elision_allowed(fn_node_id)).set_c_variadic(c_variadic);
            self.arena.alloc(hir::FnDecl { inputs, output, fn_decl_kind })
        }
    }
}#[instrument(level = "debug", skip(self))]
1768    fn lower_fn_decl(
1769        &mut self,
1770        decl: &FnDecl,
1771        fn_node_id: NodeId,
1772        fn_span: Span,
1773        kind: FnDeclKind,
1774        coro: Option<CoroutineKind>,
1775    ) -> &'hir hir::FnDecl<'hir> {
1776        let c_variadic = decl.c_variadic();
1777
1778        // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1779        // as they are not explicit in HIR/Ty function signatures.
1780        // (instead, the `c_variadic` flag is set to `true`)
1781        let mut inputs = &decl.inputs[..];
1782        if decl.c_variadic() {
1783            inputs = &inputs[..inputs.len() - 1];
1784        }
1785        let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1786            let itctx = match kind {
1787                FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait => {
1788                    ImplTraitContext::Universal
1789                }
1790                FnDeclKind::ExternFn => {
1791                    ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnParam)
1792                }
1793                FnDeclKind::Closure => {
1794                    ImplTraitContext::Disallowed(ImplTraitPosition::ClosureParam)
1795                }
1796                FnDeclKind::Pointer => {
1797                    ImplTraitContext::Disallowed(ImplTraitPosition::PointerParam)
1798                }
1799            };
1800            self.lower_ty(&param.ty, itctx)
1801        }));
1802
1803        let output = match coro {
1804            Some(coro) => {
1805                let fn_def_id = self.owner.def_id;
1806                self.lower_coroutine_fn_ret_ty(&decl.output, fn_def_id, coro, kind)
1807            }
1808            None => match &decl.output {
1809                FnRetTy::Ty(ty) => {
1810                    let itctx = match kind {
1811                        FnDeclKind::Fn | FnDeclKind::Inherent => ImplTraitContext::OpaqueTy {
1812                            origin: hir::OpaqueTyOrigin::FnReturn {
1813                                parent: self.owner.def_id,
1814                                in_trait_or_impl: None,
1815                            },
1816                        },
1817                        FnDeclKind::Trait => ImplTraitContext::OpaqueTy {
1818                            origin: hir::OpaqueTyOrigin::FnReturn {
1819                                parent: self.owner.def_id,
1820                                in_trait_or_impl: Some(hir::RpitContext::Trait),
1821                            },
1822                        },
1823                        FnDeclKind::Impl => ImplTraitContext::OpaqueTy {
1824                            origin: hir::OpaqueTyOrigin::FnReturn {
1825                                parent: self.owner.def_id,
1826                                in_trait_or_impl: Some(hir::RpitContext::TraitImpl),
1827                            },
1828                        },
1829                        FnDeclKind::ExternFn => {
1830                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnReturn)
1831                        }
1832                        FnDeclKind::Closure => {
1833                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureReturn)
1834                        }
1835                        FnDeclKind::Pointer => {
1836                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerReturn)
1837                        }
1838                    };
1839                    hir::FnRetTy::Return(self.lower_ty_alloc(ty, itctx))
1840                }
1841                FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(*span)),
1842            },
1843        };
1844
1845        let fn_decl_kind = hir::FnDeclFlags::default()
1846            .set_implicit_self(decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1847                let is_mutable_pat = matches!(
1848                    arg.pat.kind,
1849                    PatKind::Ident(hir::BindingMode(_, Mutability::Mut), ..)
1850                );
1851
1852                match &arg.ty.kind {
1853                    TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1854                    TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1855                    // Given we are only considering `ImplicitSelf` types, we needn't consider
1856                    // the case where we have a mutable pattern to a reference as that would
1857                    // no longer be an `ImplicitSelf`.
1858                    TyKind::Ref(_, mt) | TyKind::PinnedRef(_, mt)
1859                        if mt.ty.kind.is_implicit_self() =>
1860                    {
1861                        match mt.mutbl {
1862                            hir::Mutability::Not => hir::ImplicitSelfKind::RefImm,
1863                            hir::Mutability::Mut => hir::ImplicitSelfKind::RefMut,
1864                        }
1865                    }
1866                    _ => hir::ImplicitSelfKind::None,
1867                }
1868            }))
1869            .set_lifetime_elision_allowed(self.resolver.lifetime_elision_allowed(fn_node_id))
1870            .set_c_variadic(c_variadic);
1871
1872        self.arena.alloc(hir::FnDecl { inputs, output, fn_decl_kind })
1873    }
1874
1875    // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1876    // combined with the following definition of `OpaqueTy`:
1877    //
1878    //     type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1879    //
1880    // `output`: unlowered output type (`T` in `-> T`)
1881    // `fn_node_id`: `NodeId` of the parent function (used to create child impl trait definition)
1882    // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1883    #[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(1883u32),
                                    ::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))]
1884    fn lower_coroutine_fn_ret_ty(
1885        &mut self,
1886        output: &FnRetTy,
1887        fn_def_id: LocalDefId,
1888        coro: CoroutineKind,
1889        fn_kind: FnDeclKind,
1890    ) -> hir::FnRetTy<'hir> {
1891        let span = self.lower_span(output.span());
1892
1893        let (opaque_ty_node_id, allowed_features) = match coro {
1894            CoroutineKind::Async { return_impl_trait_id, .. } => (return_impl_trait_id, None),
1895            CoroutineKind::Gen { return_impl_trait_id, .. } => (return_impl_trait_id, None),
1896            CoroutineKind::AsyncGen { return_impl_trait_id, .. } => {
1897                (return_impl_trait_id, Some(Arc::clone(&self.allow_async_iterator)))
1898            }
1899        };
1900
1901        let opaque_ty_span =
1902            self.mark_span_with_reason(DesugaringKind::Async, span, allowed_features);
1903
1904        let in_trait_or_impl = match fn_kind {
1905            FnDeclKind::Trait => Some(hir::RpitContext::Trait),
1906            FnDeclKind::Impl => Some(hir::RpitContext::TraitImpl),
1907            FnDeclKind::Fn | FnDeclKind::Inherent => None,
1908            FnDeclKind::ExternFn | FnDeclKind::Closure | FnDeclKind::Pointer => unreachable!(),
1909        };
1910
1911        let opaque_ty_ref = self.lower_opaque_inner(
1912            opaque_ty_node_id,
1913            hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, in_trait_or_impl },
1914            opaque_ty_span,
1915            |this| {
1916                let bound = this.lower_coroutine_fn_output_type_to_bound(
1917                    output,
1918                    coro,
1919                    opaque_ty_span,
1920                    ImplTraitContext::OpaqueTy {
1921                        origin: hir::OpaqueTyOrigin::FnReturn {
1922                            parent: fn_def_id,
1923                            in_trait_or_impl,
1924                        },
1925                    },
1926                );
1927                arena_vec![this; bound]
1928            },
1929        );
1930
1931        let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1932        hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
1933    }
1934
1935    /// Transforms `-> T` into `Future<Output = T>`.
1936    fn lower_coroutine_fn_output_type_to_bound(
1937        &mut self,
1938        output: &FnRetTy,
1939        coro: CoroutineKind,
1940        opaque_ty_span: Span,
1941        itctx: ImplTraitContext,
1942    ) -> hir::GenericBound<'hir> {
1943        // Compute the `T` in `Future<Output = T>` from the return type.
1944        let output_ty = match output {
1945            FnRetTy::Ty(ty) => {
1946                // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1947                // `impl Future` opaque type that `async fn` implicitly
1948                // generates.
1949                self.lower_ty_alloc(ty, itctx)
1950            }
1951            FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1952        };
1953
1954        // "<$assoc_ty_name = T>"
1955        let (assoc_ty_name, trait_lang_item) = match coro {
1956            CoroutineKind::Async { .. } => (sym::Output, hir::LangItem::Future),
1957            CoroutineKind::Gen { .. } => (sym::Item, hir::LangItem::Iterator),
1958            CoroutineKind::AsyncGen { .. } => (sym::Item, hir::LangItem::AsyncIterator),
1959        };
1960
1961        let bound_args = self.arena.alloc(hir::GenericArgs {
1962            args: &[],
1963            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)],
1964            parenthesized: hir::GenericArgsParentheses::No,
1965            span_ext: DUMMY_SP,
1966        });
1967
1968        hir::GenericBound::Trait(hir::PolyTraitRef {
1969            bound_generic_params: &[],
1970            modifiers: hir::TraitBoundModifiers::NONE,
1971            trait_ref: hir::TraitRef {
1972                path: self.make_lang_item_path(trait_lang_item, opaque_ty_span, Some(bound_args)),
1973                hir_ref_id: self.next_id(),
1974            },
1975            span: opaque_ty_span,
1976        })
1977    }
1978
1979    #[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(1979u32),
                                    ::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))]
1980    fn lower_param_bound(
1981        &mut self,
1982        tpb: &GenericBound,
1983        rbp: RelaxedBoundPolicy<'_>,
1984        itctx: ImplTraitContext,
1985    ) -> hir::GenericBound<'hir> {
1986        match tpb {
1987            GenericBound::Trait(p) => {
1988                hir::GenericBound::Trait(self.lower_poly_trait_ref(p, rbp, itctx))
1989            }
1990            GenericBound::Outlives(lifetime) => hir::GenericBound::Outlives(self.lower_lifetime(
1991                lifetime,
1992                LifetimeSource::OutlivesBound,
1993                lifetime.ident.into(),
1994            )),
1995            GenericBound::Use(args, span) => hir::GenericBound::Use(
1996                self.lower_precise_capturing_args(args),
1997                self.lower_span(*span),
1998            ),
1999        }
2000    }
2001
2002    fn lower_lifetime(
2003        &mut self,
2004        l: &Lifetime,
2005        source: LifetimeSource,
2006        syntax: LifetimeSyntax,
2007    ) -> &'hir hir::Lifetime {
2008        self.new_named_lifetime(l.id, l.id, l.ident, source, syntax)
2009    }
2010
2011    fn lower_lifetime_hidden_in_path(
2012        &mut self,
2013        id: NodeId,
2014        span: Span,
2015        angle_brackets: AngleBrackets,
2016    ) -> &'hir hir::Lifetime {
2017        self.new_named_lifetime(
2018            id,
2019            id,
2020            Ident::new(kw::UnderscoreLifetime, span),
2021            LifetimeSource::Path { angle_brackets },
2022            LifetimeSyntax::Implicit,
2023        )
2024    }
2025
2026    #[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(2026u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["id", "new_id",
                                                    "ident", "source", "syntax"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&new_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&syntax)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'hir hir::Lifetime = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let res =
                if let Some(res) = self.resolver.get_lifetime_res(id) {
                    match res {
                        LifetimeRes::Param { param, .. } =>
                            hir::LifetimeKind::Param(param),
                        LifetimeRes::Fresh { param, .. } => {
                            match (&ident.name, &kw::UnderscoreLifetime) {
                                (left_val, right_val) => {
                                    if !(*left_val == *right_val) {
                                        let kind = ::core::panicking::AssertKind::Eq;
                                        ::core::panicking::assert_failed(kind, &*left_val,
                                            &*right_val, ::core::option::Option::None);
                                    }
                                }
                            };
                            let param = self.local_def_id(param);
                            hir::LifetimeKind::Param(param)
                        }
                        LifetimeRes::Infer => {
                            match (&ident.name, &kw::UnderscoreLifetime) {
                                (left_val, right_val) => {
                                    if !(*left_val == *right_val) {
                                        let kind = ::core::panicking::AssertKind::Eq;
                                        ::core::panicking::assert_failed(kind, &*left_val,
                                            &*right_val, ::core::option::Option::None);
                                    }
                                }
                            };
                            hir::LifetimeKind::Infer
                        }
                        LifetimeRes::Static { .. } => {
                            if !#[allow(non_exhaustive_omitted_patterns)] match ident.name
                                        {
                                        kw::StaticLifetime | kw::UnderscoreLifetime => true,
                                        _ => false,
                                    } {
                                ::core::panicking::panic("assertion failed: matches!(ident.name, kw::StaticLifetime | kw::UnderscoreLifetime)")
                            };
                            hir::LifetimeKind::Static
                        }
                        LifetimeRes::Error(guar) => hir::LifetimeKind::Error(guar),
                        LifetimeRes::ElidedAnchor { .. } => {
                            {
                                ::core::panicking::panic_fmt(format_args!("Unexpected `ElidedAnchar` {0:?} at {1:?}",
                                        ident, ident.span));
                            };
                        }
                    }
                } else {
                    hir::LifetimeKind::Error(self.dcx().span_delayed_bug(ident.span,
                            "unresolved lifetime"))
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:2060",
                                    "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(2060u32),
                                    ::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))]
2027    fn new_named_lifetime(
2028        &mut self,
2029        id: NodeId,
2030        new_id: NodeId,
2031        ident: Ident,
2032        source: LifetimeSource,
2033        syntax: LifetimeSyntax,
2034    ) -> &'hir hir::Lifetime {
2035        let res = if let Some(res) = self.resolver.get_lifetime_res(id) {
2036            match res {
2037                LifetimeRes::Param { param, .. } => hir::LifetimeKind::Param(param),
2038                LifetimeRes::Fresh { param, .. } => {
2039                    assert_eq!(ident.name, kw::UnderscoreLifetime);
2040                    let param = self.local_def_id(param);
2041                    hir::LifetimeKind::Param(param)
2042                }
2043                LifetimeRes::Infer => {
2044                    assert_eq!(ident.name, kw::UnderscoreLifetime);
2045                    hir::LifetimeKind::Infer
2046                }
2047                LifetimeRes::Static { .. } => {
2048                    assert!(matches!(ident.name, kw::StaticLifetime | kw::UnderscoreLifetime));
2049                    hir::LifetimeKind::Static
2050                }
2051                LifetimeRes::Error(guar) => hir::LifetimeKind::Error(guar),
2052                LifetimeRes::ElidedAnchor { .. } => {
2053                    panic!("Unexpected `ElidedAnchar` {:?} at {:?}", ident, ident.span);
2054                }
2055            }
2056        } else {
2057            hir::LifetimeKind::Error(self.dcx().span_delayed_bug(ident.span, "unresolved lifetime"))
2058        };
2059
2060        debug!(?res);
2061        self.arena.alloc(hir::Lifetime::new(
2062            self.lower_node_id(new_id),
2063            self.lower_ident(ident),
2064            res,
2065            source,
2066            syntax,
2067        ))
2068    }
2069
2070    fn lower_generic_params_mut(
2071        &mut self,
2072        params: &[GenericParam],
2073        source: hir::GenericParamSource,
2074    ) -> impl Iterator<Item = hir::GenericParam<'hir>> {
2075        params.iter().map(move |param| self.lower_generic_param(param, source))
2076    }
2077
2078    fn lower_generic_params(
2079        &mut self,
2080        params: &[GenericParam],
2081        source: hir::GenericParamSource,
2082    ) -> &'hir [hir::GenericParam<'hir>] {
2083        self.arena.alloc_from_iter(self.lower_generic_params_mut(params, source))
2084    }
2085
2086    #[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(2086u32),
                                    ::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))]
2087    fn lower_generic_param(
2088        &mut self,
2089        param: &GenericParam,
2090        source: hir::GenericParamSource,
2091    ) -> hir::GenericParam<'hir> {
2092        let (name, kind) = self.lower_generic_param_kind(param, source);
2093
2094        let hir_id = self.lower_node_id(param.id);
2095        let param_attrs = &param.attrs;
2096        let param_span = param.span();
2097        let param = hir::GenericParam {
2098            hir_id,
2099            def_id: self.local_def_id(param.id),
2100            name,
2101            span: self.lower_span(param.span()),
2102            pure_wrt_drop: attr::contains_name(&param.attrs, sym::may_dangle),
2103            kind,
2104            colon_span: param.colon_span.map(|s| self.lower_span(s)),
2105            source,
2106        };
2107        self.lower_attrs(hir_id, param_attrs, param_span, Target::from_generic_param(&param));
2108        param
2109    }
2110
2111    fn lower_generic_param_kind(
2112        &mut self,
2113        param: &GenericParam,
2114        source: hir::GenericParamSource,
2115    ) -> (hir::ParamName, hir::GenericParamKind<'hir>) {
2116        match &param.kind {
2117            GenericParamKind::Lifetime => {
2118                // AST resolution emitted an error on those parameters, so we lower them using
2119                // `ParamName::Error`.
2120                let ident = self.lower_ident(param.ident);
2121                let param_name = if let Some(LifetimeRes::Error(..)) =
2122                    self.resolver.get_lifetime_res(param.id)
2123                {
2124                    ParamName::Error(ident)
2125                } else {
2126                    ParamName::Plain(ident)
2127                };
2128                let kind =
2129                    hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2130
2131                (param_name, kind)
2132            }
2133            GenericParamKind::Type { default, .. } => {
2134                // Not only do we deny type param defaults in binders but we also map them to `None`
2135                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2136                let default = default
2137                    .as_ref()
2138                    .filter(|_| match source {
2139                        hir::GenericParamSource::Generics => true,
2140                        hir::GenericParamSource::Binder => {
2141                            self.dcx().emit_err(errors::GenericParamDefaultInBinder {
2142                                span: param.span(),
2143                            });
2144
2145                            false
2146                        }
2147                    })
2148                    .map(|def| {
2149                        self.lower_ty_alloc(
2150                            def,
2151                            ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2152                        )
2153                    });
2154
2155                let kind = hir::GenericParamKind::Type { default, synthetic: false };
2156
2157                (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2158            }
2159            GenericParamKind::Const { ty, span: _, default } => {
2160                let ty = self.lower_ty_alloc(
2161                    ty,
2162                    ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2163                );
2164
2165                // Not only do we deny const param defaults in binders but we also map them to `None`
2166                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2167                let default = default
2168                    .as_ref()
2169                    .filter(|anon_const| match source {
2170                        hir::GenericParamSource::Generics => true,
2171                        hir::GenericParamSource::Binder => {
2172                            let err = errors::GenericParamDefaultInBinder { span: param.span() };
2173                            if expr::WillCreateDefIdsVisitor
2174                                .visit_expr(&anon_const.value)
2175                                .is_break()
2176                            {
2177                                // FIXME(mgca): make this non-fatal once we have a better way
2178                                // to handle nested items in anno const from binder
2179                                // Issue: https://github.com/rust-lang/rust/issues/123629
2180                                self.dcx().emit_fatal(err)
2181                            } else {
2182                                self.dcx().emit_err(err);
2183                                false
2184                            }
2185                        }
2186                    })
2187                    .map(|def| self.lower_anon_const_to_const_arg_and_alloc(def));
2188
2189                (
2190                    hir::ParamName::Plain(self.lower_ident(param.ident)),
2191                    hir::GenericParamKind::Const { ty, default },
2192                )
2193            }
2194        }
2195    }
2196
2197    fn lower_trait_ref(
2198        &mut self,
2199        modifiers: ast::TraitBoundModifiers,
2200        p: &TraitRef,
2201        itctx: ImplTraitContext,
2202    ) -> hir::TraitRef<'hir> {
2203        let path = match self.lower_qpath(
2204            p.ref_id,
2205            &None,
2206            &p.path,
2207            ParamMode::Explicit,
2208            AllowReturnTypeNotation::No,
2209            itctx,
2210            Some(modifiers),
2211        ) {
2212            hir::QPath::Resolved(None, path) => path,
2213            qpath => {
    ::core::panicking::panic_fmt(format_args!("lower_trait_ref: unexpected QPath `{0:?}`",
            qpath));
}panic!("lower_trait_ref: unexpected QPath `{qpath:?}`"),
2214        };
2215        hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2216    }
2217
2218    #[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(2218u32),
                                    ::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))]
2219    fn lower_poly_trait_ref(
2220        &mut self,
2221        PolyTraitRef { bound_generic_params, modifiers, trait_ref, span, parens: _ }: &PolyTraitRef,
2222        rbp: RelaxedBoundPolicy<'_>,
2223        itctx: ImplTraitContext,
2224    ) -> hir::PolyTraitRef<'hir> {
2225        let bound_generic_params =
2226            self.lower_lifetime_binder(trait_ref.ref_id, bound_generic_params);
2227        let trait_ref = self.lower_trait_ref(*modifiers, trait_ref, itctx);
2228        let modifiers = self.lower_trait_bound_modifiers(*modifiers);
2229
2230        if let ast::BoundPolarity::Maybe(_) = modifiers.polarity {
2231            self.validate_relaxed_bound(trait_ref, *span, rbp);
2232        }
2233
2234        hir::PolyTraitRef {
2235            bound_generic_params,
2236            modifiers,
2237            trait_ref,
2238            span: self.lower_span(*span),
2239        }
2240    }
2241
2242    fn validate_relaxed_bound(
2243        &self,
2244        trait_ref: hir::TraitRef<'_>,
2245        span: Span,
2246        rbp: RelaxedBoundPolicy<'_>,
2247    ) {
2248        // Even though feature `more_maybe_bounds` enables the user to relax all default bounds
2249        // other than `Sized` in a lot more positions (thereby bypassing the given policy), we don't
2250        // want to advertise it to the user (via a feature gate error) since it's super internal.
2251        //
2252        // FIXME(more_maybe_bounds): Moreover, if we actually were to add proper default traits
2253        // (like a hypothetical `Move` or `Leak`) we would want to validate the location according
2254        // to default trait elaboration in HIR ty lowering (which depends on the specific trait in
2255        // question: E.g., `?Sized` & `?Move` most likely won't be allowed in all the same places).
2256
2257        match rbp {
2258            RelaxedBoundPolicy::Allowed => return,
2259            RelaxedBoundPolicy::AllowedIfOnTyParam(id, params) => {
2260                if let Some(res) = self.get_partial_res(id).and_then(|r| r.full_res())
2261                    && let Res::Def(DefKind::TyParam, def_id) = res
2262                    && params.iter().any(|p| def_id == self.local_def_id(p.id).to_def_id())
2263                {
2264                    return;
2265                }
2266            }
2267            RelaxedBoundPolicy::Forbidden(reason) => {
2268                let gate = |context, subject| {
2269                    let extended = self.tcx.features().more_maybe_bounds();
2270                    let is_sized = trait_ref
2271                        .trait_def_id()
2272                        .is_some_and(|def_id| self.tcx.is_lang_item(def_id, hir::LangItem::Sized));
2273
2274                    if extended && !is_sized {
2275                        return;
2276                    }
2277
2278                    let prefix = if extended { "`Sized` " } else { "" };
2279                    let mut diag = self.dcx().struct_span_err(
2280                        span,
2281                        ::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}"),
2282                    );
2283                    if is_sized {
2284                        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!(
2285                            "{subject} are not implicitly bounded by `Sized`, \
2286                             so there is nothing to relax"
2287                        ));
2288                    }
2289                    diag.emit();
2290                };
2291
2292                match reason {
2293                    RelaxedBoundForbiddenReason::TraitObjectTy => {
2294                        gate("trait object types", "trait object types");
2295                        return;
2296                    }
2297                    RelaxedBoundForbiddenReason::SuperTrait => {
2298                        gate("supertrait bounds", "traits");
2299                        return;
2300                    }
2301                    RelaxedBoundForbiddenReason::TraitAlias => {
2302                        gate("trait alias bounds", "trait aliases");
2303                        return;
2304                    }
2305                    RelaxedBoundForbiddenReason::AssocTyBounds
2306                    | RelaxedBoundForbiddenReason::LateBoundVarsInScope => {}
2307                };
2308            }
2309        }
2310
2311        self.dcx()
2312            .struct_span_err(span, "this relaxed bound is not permitted here")
2313            .with_note(
2314                "in this context, relaxed bounds are only allowed on \
2315                 type parameters defined on the closest item",
2316            )
2317            .emit();
2318    }
2319
2320    fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy<'hir> {
2321        hir::MutTy { ty: self.lower_ty_alloc(&mt.ty, itctx), mutbl: mt.mutbl }
2322    }
2323
2324    x;#[instrument(level = "debug", skip(self), ret)]
2325    fn lower_param_bounds(
2326        &mut self,
2327        bounds: &[GenericBound],
2328        rbp: RelaxedBoundPolicy<'_>,
2329        itctx: ImplTraitContext,
2330    ) -> hir::GenericBounds<'hir> {
2331        self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, rbp, itctx))
2332    }
2333
2334    fn lower_param_bounds_mut(
2335        &mut self,
2336        bounds: &[GenericBound],
2337        rbp: RelaxedBoundPolicy<'_>,
2338        itctx: ImplTraitContext,
2339    ) -> impl Iterator<Item = hir::GenericBound<'hir>> {
2340        bounds.iter().map(move |bound| self.lower_param_bound(bound, rbp, itctx))
2341    }
2342
2343    x;#[instrument(level = "debug", skip(self), ret)]
2344    fn lower_universal_param_and_bounds(
2345        &mut self,
2346        node_id: NodeId,
2347        span: Span,
2348        ident: Ident,
2349        bounds: &[GenericBound],
2350    ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2351        // Add a definition for the in-band `Param`.
2352        let def_id = self.local_def_id(node_id);
2353        let span = self.lower_span(span);
2354
2355        // Set the name to `impl Bound1 + Bound2`.
2356        let param = hir::GenericParam {
2357            hir_id: self.lower_node_id(node_id),
2358            def_id,
2359            name: ParamName::Plain(self.lower_ident(ident)),
2360            pure_wrt_drop: false,
2361            span,
2362            kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2363            colon_span: None,
2364            source: hir::GenericParamSource::Generics,
2365        };
2366
2367        let preds = self.lower_generic_bound_predicate(
2368            ident,
2369            node_id,
2370            &GenericParamKind::Type { default: None },
2371            bounds,
2372            /* colon_span */ None,
2373            span,
2374            RelaxedBoundPolicy::Allowed,
2375            ImplTraitContext::Universal,
2376            hir::PredicateOrigin::ImplTrait,
2377        );
2378
2379        let hir_id = self.next_id();
2380        let res = Res::Def(DefKind::TyParam, def_id.to_def_id());
2381        let ty = hir::TyKind::Path(hir::QPath::Resolved(
2382            None,
2383            self.arena.alloc(hir::Path {
2384                span,
2385                res,
2386                segments:
2387                    arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2388            }),
2389        ));
2390
2391        (param, preds, ty)
2392    }
2393
2394    /// Lowers a block directly to an expression, presuming that it
2395    /// has no attributes and is not targeted by a `break`.
2396    fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2397        let block = self.lower_block(b, false);
2398        self.expr_block(block)
2399    }
2400
2401    fn lower_array_length_to_const_arg(&mut self, c: &AnonConst) -> &'hir hir::ConstArg<'hir> {
2402        // We cannot just match on `ExprKind::Underscore` as `(_)` is represented as
2403        // `ExprKind::Paren(ExprKind::Underscore)` and should also be lowered to `GenericArg::Infer`
2404        match c.value.peel_parens().kind {
2405            ExprKind::Underscore => {
2406                let ct_kind = hir::ConstArgKind::Infer(());
2407                self.arena.alloc(hir::ConstArg {
2408                    hir_id: self.lower_node_id(c.id),
2409                    kind: ct_kind,
2410                    span: self.lower_span(c.value.span),
2411                })
2412            }
2413            _ => self.lower_anon_const_to_const_arg_and_alloc(c),
2414        }
2415    }
2416
2417    /// Used when lowering a type argument that turned out to actually be a const argument.
2418    ///
2419    /// Only use for that purpose since otherwise it will create a duplicate def.
2420    #[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(2420u32),
                                    ::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))]
2421    fn lower_const_path_to_const_arg(
2422        &mut self,
2423        path: &Path,
2424        res: Res<NodeId>,
2425        ty_id: NodeId,
2426        span: Span,
2427    ) -> &'hir hir::ConstArg<'hir> {
2428        let tcx = self.tcx;
2429
2430        let is_trivial_path = path.is_potential_trivial_const_arg()
2431            && matches!(res, Res::Def(DefKind::ConstParam, _));
2432        let ct_kind = if is_trivial_path || tcx.features().min_generic_const_args() {
2433            let qpath = self.lower_qpath(
2434                ty_id,
2435                &None,
2436                path,
2437                ParamMode::Explicit,
2438                AllowReturnTypeNotation::No,
2439                // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2440                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2441                None,
2442            );
2443            hir::ConstArgKind::Path(qpath)
2444        } else {
2445            // Construct an AnonConst where the expr is the "ty"'s path.
2446            let node_id = self.next_node_id();
2447            let span = self.lower_span(span);
2448
2449            // Add a definition for the in-band const def.
2450            // We're lowering a const argument that was originally thought to be a type argument,
2451            // so the def collector didn't create the def ahead of time. That's why we have to do
2452            // it here.
2453            let def_id = self.create_def(node_id, None, DefKind::AnonConst, span);
2454            let hir_id = self.lower_node_id(node_id);
2455
2456            let path_expr = Expr {
2457                id: ty_id,
2458                kind: ExprKind::Path(None, path.clone()),
2459                span,
2460                attrs: AttrVec::new(),
2461                tokens: None,
2462            };
2463
2464            let ct = self.with_new_scopes(span, |this| {
2465                self.arena.alloc(hir::AnonConst {
2466                    def_id,
2467                    hir_id,
2468                    body: this.lower_const_body(path_expr.span, Some(&path_expr)),
2469                    span,
2470                })
2471            });
2472            hir::ConstArgKind::Anon(ct)
2473        };
2474
2475        self.arena.alloc(hir::ConstArg {
2476            hir_id: self.next_id(),
2477            kind: ct_kind,
2478            span: self.lower_span(span),
2479        })
2480    }
2481
2482    fn lower_const_item_rhs(
2483        &mut self,
2484        rhs_kind: &ConstItemRhsKind,
2485        span: Span,
2486    ) -> hir::ConstItemRhs<'hir> {
2487        match rhs_kind {
2488            ConstItemRhsKind::Body { rhs: Some(body) } => {
2489                hir::ConstItemRhs::Body(self.lower_const_body(span, Some(body)))
2490            }
2491            ConstItemRhsKind::Body { rhs: None } => {
2492                hir::ConstItemRhs::Body(self.lower_const_body(span, None))
2493            }
2494            ConstItemRhsKind::TypeConst { rhs: Some(anon) } => {
2495                hir::ConstItemRhs::TypeConst(self.lower_anon_const_to_const_arg_and_alloc(anon))
2496            }
2497            ConstItemRhsKind::TypeConst { rhs: None } => {
2498                let const_arg = ConstArg {
2499                    hir_id: self.next_id(),
2500                    kind: hir::ConstArgKind::Error(
2501                        self.dcx().span_delayed_bug(DUMMY_SP, "no block"),
2502                    ),
2503                    span: DUMMY_SP,
2504                };
2505                hir::ConstItemRhs::TypeConst(self.arena.alloc(const_arg))
2506            }
2507        }
2508    }
2509
2510    x;#[instrument(level = "debug", skip(self), ret)]
2511    fn lower_expr_to_const_arg_direct(&mut self, expr: &Expr) -> hir::ConstArg<'hir> {
2512        let span = self.lower_span(expr.span);
2513
2514        let overly_complex_const = |this: &mut Self| {
2515            let msg = "complex const arguments must be placed inside of a `const` block";
2516            let e = if expr::WillCreateDefIdsVisitor.visit_expr(expr).is_break() {
2517                // FIXME(mgca): make this non-fatal once we have a better way to handle
2518                // nested items in const args
2519                // Issue: https://github.com/rust-lang/rust/issues/154539
2520                this.dcx().struct_span_fatal(expr.span, msg).emit()
2521            } else {
2522                this.dcx().struct_span_err(expr.span, msg).emit()
2523            };
2524
2525            ConstArg { hir_id: this.next_id(), kind: hir::ConstArgKind::Error(e), span }
2526        };
2527
2528        match &expr.kind {
2529            ExprKind::Call(func, args) if let ExprKind::Path(qself, path) = &func.kind => {
2530                let qpath = self.lower_qpath(
2531                    func.id,
2532                    qself,
2533                    path,
2534                    ParamMode::Explicit,
2535                    AllowReturnTypeNotation::No,
2536                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2537                    None,
2538                );
2539
2540                let lowered_args = self.arena.alloc_from_iter(args.iter().map(|arg| {
2541                    let const_arg = self.lower_expr_to_const_arg_direct(arg);
2542                    &*self.arena.alloc(const_arg)
2543                }));
2544
2545                ConstArg {
2546                    hir_id: self.next_id(),
2547                    kind: hir::ConstArgKind::TupleCall(qpath, lowered_args),
2548                    span,
2549                }
2550            }
2551            ExprKind::Tup(exprs) => {
2552                let exprs = self.arena.alloc_from_iter(exprs.iter().map(|expr| {
2553                    let expr = self.lower_expr_to_const_arg_direct(&expr);
2554                    &*self.arena.alloc(expr)
2555                }));
2556
2557                ConstArg { hir_id: self.next_id(), kind: hir::ConstArgKind::Tup(exprs), span }
2558            }
2559            ExprKind::Path(qself, path) => {
2560                let qpath = self.lower_qpath(
2561                    expr.id,
2562                    qself,
2563                    path,
2564                    ParamMode::Explicit,
2565                    AllowReturnTypeNotation::No,
2566                    // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2567                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2568                    None,
2569                );
2570
2571                ConstArg { hir_id: self.next_id(), kind: hir::ConstArgKind::Path(qpath), span }
2572            }
2573            ExprKind::Struct(se) => {
2574                let path = self.lower_qpath(
2575                    expr.id,
2576                    &se.qself,
2577                    &se.path,
2578                    // FIXME(mgca): we may want this to be `Optional` instead, but
2579                    // we would also need to make sure that HIR ty lowering errors
2580                    // when these paths wind up in signatures.
2581                    ParamMode::Explicit,
2582                    AllowReturnTypeNotation::No,
2583                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2584                    None,
2585                );
2586
2587                let fields = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
2588                    let hir_id = self.lower_node_id(f.id);
2589                    // FIXME(mgca): This might result in lowering attributes that
2590                    // then go unused as the `Target::ExprField` is not actually
2591                    // corresponding to `Node::ExprField`.
2592                    self.lower_attrs(hir_id, &f.attrs, f.span, Target::ExprField);
2593                    let expr = self.lower_expr_to_const_arg_direct(&f.expr);
2594
2595                    &*self.arena.alloc(hir::ConstArgExprField {
2596                        hir_id,
2597                        field: self.lower_ident(f.ident),
2598                        expr: self.arena.alloc(expr),
2599                        span: self.lower_span(f.span),
2600                    })
2601                }));
2602
2603                ConstArg {
2604                    hir_id: self.next_id(),
2605                    kind: hir::ConstArgKind::Struct(path, fields),
2606                    span,
2607                }
2608            }
2609            ExprKind::Array(elements) => {
2610                let lowered_elems = self.arena.alloc_from_iter(elements.iter().map(|element| {
2611                    let const_arg = self.lower_expr_to_const_arg_direct(element);
2612                    &*self.arena.alloc(const_arg)
2613                }));
2614                let array_expr = self.arena.alloc(hir::ConstArgArrayExpr {
2615                    span: self.lower_span(expr.span),
2616                    elems: lowered_elems,
2617                });
2618
2619                ConstArg {
2620                    hir_id: self.next_id(),
2621                    kind: hir::ConstArgKind::Array(array_expr),
2622                    span,
2623                }
2624            }
2625            ExprKind::Underscore => ConstArg {
2626                hir_id: self.lower_node_id(expr.id),
2627                kind: hir::ConstArgKind::Infer(()),
2628                span,
2629            },
2630            ExprKind::Block(block, _) => {
2631                if let [stmt] = block.stmts.as_slice()
2632                    && let StmtKind::Expr(expr) = &stmt.kind
2633                {
2634                    return self.lower_expr_to_const_arg_direct(expr);
2635                }
2636
2637                overly_complex_const(self)
2638            }
2639            ExprKind::Lit(literal) => {
2640                let span = self.lower_span(expr.span);
2641                let literal = self.lower_lit(literal, span);
2642
2643                ConstArg {
2644                    hir_id: self.lower_node_id(expr.id),
2645                    kind: hir::ConstArgKind::Literal { lit: literal.node, negated: false },
2646                    span,
2647                }
2648            }
2649            ExprKind::Unary(UnOp::Neg, inner_expr)
2650                if let ExprKind::Lit(literal) = &inner_expr.kind =>
2651            {
2652                let span = self.lower_span(expr.span);
2653                let literal = self.lower_lit(literal, span);
2654
2655                if !matches!(literal.node, LitKind::Int(..)) {
2656                    let err =
2657                        self.dcx().struct_span_err(expr.span, "negated literal must be an integer");
2658
2659                    return ConstArg {
2660                        hir_id: self.next_id(),
2661                        kind: hir::ConstArgKind::Error(err.emit()),
2662                        span,
2663                    };
2664                }
2665
2666                ConstArg {
2667                    hir_id: self.lower_node_id(expr.id),
2668                    kind: hir::ConstArgKind::Literal { lit: literal.node, negated: true },
2669                    span,
2670                }
2671            }
2672            ExprKind::ConstBlock(anon_const) => {
2673                let def_id = self.local_def_id(anon_const.id);
2674                assert_eq!(DefKind::AnonConst, self.tcx.def_kind(def_id));
2675                self.lower_anon_const_to_const_arg(anon_const, span)
2676            }
2677            _ => overly_complex_const(self),
2678        }
2679    }
2680
2681    /// See [`hir::ConstArg`] for when to use this function vs
2682    /// [`Self::lower_anon_const_to_anon_const`].
2683    fn lower_anon_const_to_const_arg_and_alloc(
2684        &mut self,
2685        anon: &AnonConst,
2686    ) -> &'hir hir::ConstArg<'hir> {
2687        self.arena.alloc(self.lower_anon_const_to_const_arg(anon, anon.value.span))
2688    }
2689
2690    #[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(2690u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["anon", "span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&anon)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::ConstArg<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            if tcx.features().min_generic_const_args() {
                return match anon.mgca_disambiguation {
                        MgcaDisambiguation::AnonConst => {
                            let lowered_anon =
                                self.lower_anon_const_to_anon_const(anon, span);
                            ConstArg {
                                hir_id: self.next_id(),
                                kind: hir::ConstArgKind::Anon(lowered_anon),
                                span: lowered_anon.span,
                            }
                        }
                        MgcaDisambiguation::Direct =>
                            self.lower_expr_to_const_arg_direct(&anon.value),
                    };
            }
            let expr =
                if let ExprKind::Block(block, _) = &anon.value.kind &&
                                let [stmt] = block.stmts.as_slice() &&
                            let StmtKind::Expr(expr) = &stmt.kind &&
                        let ExprKind::Path(..) = &expr.kind {
                    expr
                } else { &anon.value };
            let maybe_res =
                self.get_partial_res(expr.id).and_then(|partial_res|
                        partial_res.full_res());
            if let ExprKind::Path(qself, path) = &expr.kind &&
                        path.is_potential_trivial_const_arg() &&
                    #[allow(non_exhaustive_omitted_patterns)] match maybe_res {
                        Some(Res::Def(DefKind::ConstParam, _)) => true,
                        _ => false,
                    } {
                let qpath =
                    self.lower_qpath(expr.id, qself, path, ParamMode::Explicit,
                        AllowReturnTypeNotation::No,
                        ImplTraitContext::Disallowed(ImplTraitPosition::Path),
                        None);
                return ConstArg {
                        hir_id: self.lower_node_id(anon.id),
                        kind: hir::ConstArgKind::Path(qpath),
                        span: self.lower_span(expr.span),
                    };
            }
            let lowered_anon =
                self.lower_anon_const_to_anon_const(anon, anon.value.span);
            ConstArg {
                hir_id: self.next_id(),
                kind: hir::ConstArgKind::Anon(lowered_anon),
                span: self.lower_span(expr.span),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2691    fn lower_anon_const_to_const_arg(
2692        &mut self,
2693        anon: &AnonConst,
2694        span: Span,
2695    ) -> hir::ConstArg<'hir> {
2696        let tcx = self.tcx;
2697
2698        // We cannot change parsing depending on feature gates available,
2699        // we can only require feature gates to be active as a delayed check.
2700        // Thus we just parse anon consts generally and make the real decision
2701        // making in ast lowering.
2702        // FIXME(min_generic_const_args): revisit once stable
2703        if tcx.features().min_generic_const_args() {
2704            return match anon.mgca_disambiguation {
2705                MgcaDisambiguation::AnonConst => {
2706                    let lowered_anon = self.lower_anon_const_to_anon_const(anon, span);
2707                    ConstArg {
2708                        hir_id: self.next_id(),
2709                        kind: hir::ConstArgKind::Anon(lowered_anon),
2710                        span: lowered_anon.span,
2711                    }
2712                }
2713                MgcaDisambiguation::Direct => self.lower_expr_to_const_arg_direct(&anon.value),
2714            };
2715        }
2716
2717        // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2718        // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2719        let expr = if let ExprKind::Block(block, _) = &anon.value.kind
2720            && let [stmt] = block.stmts.as_slice()
2721            && let StmtKind::Expr(expr) = &stmt.kind
2722            && let ExprKind::Path(..) = &expr.kind
2723        {
2724            expr
2725        } else {
2726            &anon.value
2727        };
2728
2729        let maybe_res =
2730            self.get_partial_res(expr.id).and_then(|partial_res| partial_res.full_res());
2731        if let ExprKind::Path(qself, path) = &expr.kind
2732            && path.is_potential_trivial_const_arg()
2733            && matches!(maybe_res, Some(Res::Def(DefKind::ConstParam, _)))
2734        {
2735            let qpath = self.lower_qpath(
2736                expr.id,
2737                qself,
2738                path,
2739                ParamMode::Explicit,
2740                AllowReturnTypeNotation::No,
2741                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2742                None,
2743            );
2744
2745            return ConstArg {
2746                hir_id: self.lower_node_id(anon.id),
2747                kind: hir::ConstArgKind::Path(qpath),
2748                span: self.lower_span(expr.span),
2749            };
2750        }
2751
2752        let lowered_anon = self.lower_anon_const_to_anon_const(anon, anon.value.span);
2753        ConstArg {
2754            hir_id: self.next_id(),
2755            kind: hir::ConstArgKind::Anon(lowered_anon),
2756            span: self.lower_span(expr.span),
2757        }
2758    }
2759
2760    /// See [`hir::ConstArg`] for when to use this function vs
2761    /// [`Self::lower_anon_const_to_const_arg`].
2762    fn lower_anon_const_to_anon_const(
2763        &mut self,
2764        c: &AnonConst,
2765        span: Span,
2766    ) -> &'hir hir::AnonConst {
2767        self.arena.alloc(self.with_new_scopes(c.value.span, |this| {
2768            let def_id = this.local_def_id(c.id);
2769            let hir_id = this.lower_node_id(c.id);
2770            hir::AnonConst {
2771                def_id,
2772                hir_id,
2773                body: this.lower_const_body(c.value.span, Some(&c.value)),
2774                span: this.lower_span(span),
2775            }
2776        }))
2777    }
2778
2779    fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2780        match u {
2781            CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2782            UserProvided => hir::UnsafeSource::UserProvided,
2783        }
2784    }
2785
2786    fn lower_trait_bound_modifiers(
2787        &mut self,
2788        modifiers: TraitBoundModifiers,
2789    ) -> hir::TraitBoundModifiers {
2790        let constness = match modifiers.constness {
2791            BoundConstness::Never => BoundConstness::Never,
2792            BoundConstness::Always(span) => BoundConstness::Always(self.lower_span(span)),
2793            BoundConstness::Maybe(span) => BoundConstness::Maybe(self.lower_span(span)),
2794        };
2795        let polarity = match modifiers.polarity {
2796            BoundPolarity::Positive => BoundPolarity::Positive,
2797            BoundPolarity::Negative(span) => BoundPolarity::Negative(self.lower_span(span)),
2798            BoundPolarity::Maybe(span) => BoundPolarity::Maybe(self.lower_span(span)),
2799        };
2800        hir::TraitBoundModifiers { constness, polarity }
2801    }
2802
2803    // Helper methods for building HIR.
2804
2805    fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2806        hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2807    }
2808
2809    fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2810        self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2811    }
2812
2813    fn stmt_let_pat(
2814        &mut self,
2815        attrs: Option<&'hir [hir::Attribute]>,
2816        span: Span,
2817        init: Option<&'hir hir::Expr<'hir>>,
2818        pat: &'hir hir::Pat<'hir>,
2819        source: hir::LocalSource,
2820    ) -> hir::Stmt<'hir> {
2821        let hir_id = self.next_id();
2822        if let Some(a) = attrs {
2823            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
2824            self.attrs.insert(hir_id.local_id, a);
2825        }
2826        let local = hir::LetStmt {
2827            super_: None,
2828            hir_id,
2829            init,
2830            pat,
2831            els: None,
2832            source,
2833            span: self.lower_span(span),
2834            ty: None,
2835        };
2836        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
2837    }
2838
2839    fn stmt_super_let_pat(
2840        &mut self,
2841        span: Span,
2842        pat: &'hir hir::Pat<'hir>,
2843        init: Option<&'hir hir::Expr<'hir>>,
2844    ) -> hir::Stmt<'hir> {
2845        let hir_id = self.next_id();
2846        let span = self.lower_span(span);
2847        let local = hir::LetStmt {
2848            super_: Some(span),
2849            hir_id,
2850            init,
2851            pat,
2852            els: None,
2853            source: hir::LocalSource::Normal,
2854            span,
2855            ty: None,
2856        };
2857        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
2858    }
2859
2860    fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2861        self.block_all(expr.span, &[], Some(expr))
2862    }
2863
2864    fn block_all(
2865        &mut self,
2866        span: Span,
2867        stmts: &'hir [hir::Stmt<'hir>],
2868        expr: Option<&'hir hir::Expr<'hir>>,
2869    ) -> &'hir hir::Block<'hir> {
2870        let blk = hir::Block {
2871            stmts,
2872            expr,
2873            hir_id: self.next_id(),
2874            rules: hir::BlockCheckMode::DefaultBlock,
2875            span: self.lower_span(span),
2876            targeted_by_break: false,
2877        };
2878        self.arena.alloc(blk)
2879    }
2880
2881    fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2882        let field = self.single_pat_field(span, pat);
2883        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field)
2884    }
2885
2886    fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2887        let field = self.single_pat_field(span, pat);
2888        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field)
2889    }
2890
2891    fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2892        let field = self.single_pat_field(span, pat);
2893        self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field)
2894    }
2895
2896    fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2897        self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[])
2898    }
2899
2900    fn single_pat_field(
2901        &mut self,
2902        span: Span,
2903        pat: &'hir hir::Pat<'hir>,
2904    ) -> &'hir [hir::PatField<'hir>] {
2905        let field = hir::PatField {
2906            hir_id: self.next_id(),
2907            ident: Ident::new(sym::integer(0), self.lower_span(span)),
2908            is_shorthand: false,
2909            pat,
2910            span: self.lower_span(span),
2911        };
2912        self.arena.alloc_from_iter([field])arena_vec![self; field]
2913    }
2914
2915    fn pat_lang_item_variant(
2916        &mut self,
2917        span: Span,
2918        lang_item: hir::LangItem,
2919        fields: &'hir [hir::PatField<'hir>],
2920    ) -> &'hir hir::Pat<'hir> {
2921        let path = self.make_lang_item_qpath(lang_item, self.lower_span(span), None);
2922        self.pat(span, hir::PatKind::Struct(path, fields, None))
2923    }
2924
2925    fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, HirId) {
2926        self.pat_ident_binding_mode(span, ident, hir::BindingMode::NONE)
2927    }
2928
2929    fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, HirId) {
2930        self.pat_ident_binding_mode_mut(span, ident, hir::BindingMode::NONE)
2931    }
2932
2933    fn pat_ident_binding_mode(
2934        &mut self,
2935        span: Span,
2936        ident: Ident,
2937        bm: hir::BindingMode,
2938    ) -> (&'hir hir::Pat<'hir>, HirId) {
2939        let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2940        (self.arena.alloc(pat), hir_id)
2941    }
2942
2943    fn pat_ident_binding_mode_mut(
2944        &mut self,
2945        span: Span,
2946        ident: Ident,
2947        bm: hir::BindingMode,
2948    ) -> (hir::Pat<'hir>, HirId) {
2949        let hir_id = self.next_id();
2950
2951        (
2952            hir::Pat {
2953                hir_id,
2954                kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2955                span: self.lower_span(span),
2956                default_binding_modes: true,
2957            },
2958            hir_id,
2959        )
2960    }
2961
2962    fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2963        self.arena.alloc(hir::Pat {
2964            hir_id: self.next_id(),
2965            kind,
2966            span: self.lower_span(span),
2967            default_binding_modes: true,
2968        })
2969    }
2970
2971    fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2972        hir::Pat {
2973            hir_id: self.next_id(),
2974            kind,
2975            span: self.lower_span(span),
2976            default_binding_modes: false,
2977        }
2978    }
2979
2980    fn ty_path(&mut self, mut hir_id: HirId, span: Span, qpath: hir::QPath<'hir>) -> hir::Ty<'hir> {
2981        let kind = match qpath {
2982            hir::QPath::Resolved(None, path) => {
2983                // Turn trait object paths into `TyKind::TraitObject` instead.
2984                match path.res {
2985                    Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2986                        let principal = hir::PolyTraitRef {
2987                            bound_generic_params: &[],
2988                            modifiers: hir::TraitBoundModifiers::NONE,
2989                            trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2990                            span: self.lower_span(span),
2991                        };
2992
2993                        // The original ID is taken by the `PolyTraitRef`,
2994                        // so the `Ty` itself needs a different one.
2995                        hir_id = self.next_id();
2996                        hir::TyKind::TraitObject(
2997                            self.arena.alloc_from_iter([principal])arena_vec![self; principal],
2998                            TaggedRef::new(self.elided_dyn_bound(span), TraitObjectSyntax::None),
2999                        )
3000                    }
3001                    _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
3002                }
3003            }
3004            _ => hir::TyKind::Path(qpath),
3005        };
3006
3007        hir::Ty { hir_id, kind, span: self.lower_span(span) }
3008    }
3009
3010    /// Invoked to create the lifetime argument(s) for an elided trait object
3011    /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
3012    /// when the bound is written, even if it is written with `'_` like in
3013    /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
3014    fn elided_dyn_bound(&mut self, span: Span) -> &'hir hir::Lifetime {
3015        let r = hir::Lifetime::new(
3016            self.next_id(),
3017            Ident::new(kw::UnderscoreLifetime, self.lower_span(span)),
3018            hir::LifetimeKind::ImplicitObjectLifetimeDefault,
3019            LifetimeSource::Other,
3020            LifetimeSyntax::Implicit,
3021        );
3022        {
    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:3022",
                        "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(3022u32),
                        ::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);
3023        self.arena.alloc(r)
3024    }
3025}
3026
3027/// Helper struct for the delayed construction of [`hir::GenericArgs`].
3028struct GenericArgsCtor<'hir> {
3029    args: SmallVec<[hir::GenericArg<'hir>; 4]>,
3030    constraints: &'hir [hir::AssocItemConstraint<'hir>],
3031    parenthesized: hir::GenericArgsParentheses,
3032    span: Span,
3033}
3034
3035impl<'hir> GenericArgsCtor<'hir> {
3036    fn is_empty(&self) -> bool {
3037        self.args.is_empty()
3038            && self.constraints.is_empty()
3039            && self.parenthesized == hir::GenericArgsParentheses::No
3040    }
3041
3042    fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
3043        let ga = hir::GenericArgs {
3044            args: this.arena.alloc_from_iter(self.args),
3045            constraints: self.constraints,
3046            parenthesized: self.parenthesized,
3047            span_ext: this.lower_span(self.span),
3048        };
3049        this.arena.alloc(ga)
3050    }
3051}