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

                #[allow(deprecated)]
                {
                    {
                        'done:
                            {
                            for i in tcx.get_all_attrs(def_id) {
                                #[allow(unused_imports)]
                                use rustc_hir::attrs::AttributeKind::*;
                                let i: &rustc_hir::Attribute = i;
                                match i {
                                    rustc_hir::Attribute::Parsed(RustcLegacyConstGenerics {
                                        fn_indexes, .. }) => {
                                        break 'done Some(fn_indexes);
                                    }
                                    rustc_hir::Attribute::Unparsed(..) =>
                                        {}
                                        #[deny(unreachable_patterns)]
                                        _ => {}
                                }
                            }
                            None
                        }
                    }
                }
            }.map(|fn_indexes|
                fn_indexes.iter().map(|(num, _)| *num).collect())
    }
    fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
        self.partial_res_map.get(&id).copied()
    }
    #[doc =
    " Obtains per-namespace resolutions for `use` statement with the given `NodeId`."]
    fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
        self.import_res_map.get(&id).copied().unwrap_or_default()
    }
    #[doc = " Obtains resolution for a label with the given `NodeId`."]
    fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
        self.label_res_map.get(&id).copied()
    }
    #[doc = " Obtains resolution for a lifetime with the given `NodeId`."]
    fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
        self.lifetimes_res_map.get(&id).copied()
    }
    #[doc = " Obtain the list of lifetimes parameters to add to an item."]
    #[doc = ""]
    #[doc =
    " Extra lifetime parameters should only be added in places that can appear"]
    #[doc = " as a `binder` in `LifetimeRes`."]
    #[doc = ""]
    #[doc =
    " The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring"]
    #[doc = " should appear at the enclosing `PolyTraitRef`."]
    fn extra_lifetime_params(&mut self, id: NodeId)
        -> Vec<(Ident, NodeId, LifetimeRes)> {
        self.extra_lifetime_params_map.get(&id).cloned().unwrap_or_default()
    }
}#[extension(trait ResolverAstLoweringExt)]
250impl ResolverAstLowering<'_> {
251    fn legacy_const_generic_args(&self, expr: &Expr, tcx: TyCtxt<'_>) -> Option<Vec<usize>> {
252        let ExprKind::Path(None, path) = &expr.kind else {
253            return None;
254        };
255
256        // Don't perform legacy const generics rewriting if the path already
257        // has generic arguments.
258        if path.segments.last().unwrap().args.is_some() {
259            return None;
260        }
261
262        let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
263
264        // We only support cross-crate argument rewriting. Uses
265        // within the same crate should be updated to use the new
266        // const generics style.
267        if def_id.is_local() {
268            return None;
269        }
270
271        // we can use parsed attrs here since for other crates they're already available
272        find_attr!(
273            tcx, def_id,
274            RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
275        )
276        .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
277    }
278
279    fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
280        self.partial_res_map.get(&id).copied()
281    }
282
283    /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
284    fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
285        self.import_res_map.get(&id).copied().unwrap_or_default()
286    }
287
288    /// Obtains resolution for a label with the given `NodeId`.
289    fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
290        self.label_res_map.get(&id).copied()
291    }
292
293    /// Obtains resolution for a lifetime with the given `NodeId`.
294    fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
295        self.lifetimes_res_map.get(&id).copied()
296    }
297
298    /// Obtain the list of lifetimes parameters to add to an item.
299    ///
300    /// Extra lifetime parameters should only be added in places that can appear
301    /// as a `binder` in `LifetimeRes`.
302    ///
303    /// The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring
304    /// should appear at the enclosing `PolyTraitRef`.
305    fn extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> {
306        self.extra_lifetime_params_map.get(&id).cloned().unwrap_or_default()
307    }
308}
309
310/// How relaxed bounds `?Trait` should be treated.
311///
312/// Relaxed bounds should only be allowed in places where we later
313/// (namely during HIR ty lowering) perform *sized elaboration*.
314#[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)]
315enum RelaxedBoundPolicy<'a> {
316    Allowed,
317    AllowedIfOnTyParam(NodeId, &'a [ast::GenericParam]),
318    Forbidden(RelaxedBoundForbiddenReason),
319}
320
321#[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)]
322enum RelaxedBoundForbiddenReason {
323    TraitObjectTy,
324    SuperTrait,
325    TraitAlias,
326    AssocTyBounds,
327    LateBoundVarsInScope,
328}
329
330/// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
331/// and if so, what meaning it has.
332#[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)]
333enum ImplTraitContext {
334    /// Treat `impl Trait` as shorthand for a new universal generic parameter.
335    /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
336    /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
337    ///
338    /// Newly generated parameters should be inserted into the given `Vec`.
339    Universal,
340
341    /// Treat `impl Trait` as shorthand for a new opaque type.
342    /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
343    /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
344    ///
345    OpaqueTy { origin: hir::OpaqueTyOrigin<LocalDefId> },
346
347    /// Treat `impl Trait` as a "trait ascription", which is like a type
348    /// variable but that also enforces that a set of trait goals hold.
349    ///
350    /// This is useful to guide inference for unnameable types.
351    InBinding,
352
353    /// `impl Trait` is unstably accepted in this position.
354    FeatureGated(ImplTraitPosition, Symbol),
355    /// `impl Trait` is not accepted in this position.
356    Disallowed(ImplTraitPosition),
357}
358
359/// Position in which `impl Trait` is disallowed.
360#[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)]
361enum ImplTraitPosition {
362    Path,
363    Variable,
364    Trait,
365    Bound,
366    Generic,
367    ExternFnParam,
368    ClosureParam,
369    PointerParam,
370    FnTraitParam,
371    ExternFnReturn,
372    ClosureReturn,
373    PointerReturn,
374    FnTraitReturn,
375    GenericDefault,
376    ConstTy,
377    StaticTy,
378    AssocTy,
379    FieldTy,
380    Cast,
381    ImplSelf,
382    OffsetOf,
383}
384
385impl std::fmt::Display for ImplTraitPosition {
386    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
387        let name = match self {
388            ImplTraitPosition::Path => "paths",
389            ImplTraitPosition::Variable => "the type of variable bindings",
390            ImplTraitPosition::Trait => "traits",
391            ImplTraitPosition::Bound => "bounds",
392            ImplTraitPosition::Generic => "generics",
393            ImplTraitPosition::ExternFnParam => "`extern fn` parameters",
394            ImplTraitPosition::ClosureParam => "closure parameters",
395            ImplTraitPosition::PointerParam => "`fn` pointer parameters",
396            ImplTraitPosition::FnTraitParam => "the parameters of `Fn` trait bounds",
397            ImplTraitPosition::ExternFnReturn => "`extern fn` return types",
398            ImplTraitPosition::ClosureReturn => "closure return types",
399            ImplTraitPosition::PointerReturn => "`fn` pointer return types",
400            ImplTraitPosition::FnTraitReturn => "the return type of `Fn` trait bounds",
401            ImplTraitPosition::GenericDefault => "generic parameter defaults",
402            ImplTraitPosition::ConstTy => "const types",
403            ImplTraitPosition::StaticTy => "static types",
404            ImplTraitPosition::AssocTy => "associated types",
405            ImplTraitPosition::FieldTy => "field types",
406            ImplTraitPosition::Cast => "cast expression types",
407            ImplTraitPosition::ImplSelf => "impl headers",
408            ImplTraitPosition::OffsetOf => "`offset_of!` parameters",
409        };
410
411        f.write_fmt(format_args!("{0}", name))write!(f, "{name}")
412    }
413}
414
415#[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)]
416enum FnDeclKind {
417    Fn,
418    Inherent,
419    ExternFn,
420    Closure,
421    Pointer,
422    Trait,
423    Impl,
424}
425
426#[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)]
427enum AstOwner<'a> {
428    NonOwner,
429    Crate(&'a ast::Crate),
430    Item(&'a ast::Item),
431    AssocItem(&'a ast::AssocItem, visit::AssocCtxt),
432    ForeignItem(&'a ast::ForeignItem),
433}
434
435#[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)]
436enum TryBlockScope {
437    /// There isn't a `try` block, so a `?` will use `return`.
438    Function,
439    /// We're inside a `try { … }` block, so a `?` will block-break
440    /// from that block using a type depending only on the argument.
441    Homogeneous(HirId),
442    /// We're inside a `try as _ { … }` block, so a `?` will block-break
443    /// from that block using the type specified.
444    Heterogeneous(HirId),
445}
446
447fn index_crate<'a>(
448    node_id_to_def_id: &NodeMap<LocalDefId>,
449    krate: &'a Crate,
450) -> IndexVec<LocalDefId, AstOwner<'a>> {
451    let mut indexer = Indexer { node_id_to_def_id, index: IndexVec::new() };
452    *indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner) =
453        AstOwner::Crate(krate);
454    visit::walk_crate(&mut indexer, krate);
455    return indexer.index;
456
457    struct Indexer<'s, 'a> {
458        node_id_to_def_id: &'s NodeMap<LocalDefId>,
459        index: IndexVec<LocalDefId, AstOwner<'a>>,
460    }
461
462    impl<'a> visit::Visitor<'a> for Indexer<'_, 'a> {
463        fn visit_attribute(&mut self, _: &'a Attribute) {
464            // We do not want to lower expressions that appear in attributes,
465            // as they are not accessible to the rest of the HIR.
466        }
467
468        fn visit_item(&mut self, item: &'a ast::Item) {
469            let def_id = self.node_id_to_def_id[&item.id];
470            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) = AstOwner::Item(item);
471            visit::walk_item(self, item)
472        }
473
474        fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) {
475            let def_id = self.node_id_to_def_id[&item.id];
476            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) =
477                AstOwner::AssocItem(item, ctxt);
478            visit::walk_assoc_item(self, item, ctxt);
479        }
480
481        fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) {
482            let def_id = self.node_id_to_def_id[&item.id];
483            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) =
484                AstOwner::ForeignItem(item);
485            visit::walk_item(self, item);
486        }
487    }
488}
489
490/// Compute the hash for the HIR of the full crate.
491/// This hash will then be part of the crate_hash which is stored in the metadata.
492fn compute_hir_hash(
493    tcx: TyCtxt<'_>,
494    owners: &IndexSlice<LocalDefId, hir::MaybeOwner<'_>>,
495) -> Fingerprint {
496    let mut hir_body_nodes: Vec<_> = owners
497        .iter_enumerated()
498        .filter_map(|(def_id, info)| {
499            let info = info.as_owner()?;
500            let def_path_hash = tcx.hir_def_path_hash(def_id);
501            Some((def_path_hash, info))
502        })
503        .collect();
504    hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
505
506    tcx.with_stable_hashing_context(|mut hcx| {
507        let mut stable_hasher = StableHasher::new();
508        hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher);
509        stable_hasher.finish()
510    })
511}
512
513pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> hir::Crate<'_> {
514    let sess = tcx.sess;
515    // Queries that borrow `resolver_for_lowering`.
516    tcx.ensure_done().output_filenames(());
517    tcx.ensure_done().early_lint_checks(());
518    tcx.ensure_done().debugger_visualizers(LOCAL_CRATE);
519    tcx.ensure_done().get_lang_items(());
520    let (mut resolver, krate) = tcx.resolver_for_lowering().steal();
521
522    let ast_index = index_crate(&resolver.node_id_to_def_id, &krate);
523    let mut owners = IndexVec::from_fn_n(
524        |_| hir::MaybeOwner::Phantom,
525        tcx.definitions_untracked().def_index_count(),
526    );
527
528    let mut lowerer = item::ItemLowerer {
529        tcx,
530        resolver: &mut resolver,
531        ast_index: &ast_index,
532        owners: &mut owners,
533    };
534    for def_id in ast_index.indices() {
535        lowerer.lower_node(def_id);
536    }
537
538    drop(ast_index);
539
540    // Drop AST to free memory. It can be expensive so try to drop it on a separate thread.
541    let prof = sess.prof.clone();
542    spawn(move || {
543        let _timer = prof.verbose_generic_activity("drop_ast");
544        drop(krate);
545    });
546
547    // Don't hash unless necessary, because it's expensive.
548    let opt_hir_hash =
549        if tcx.needs_crate_hash() { Some(compute_hir_hash(tcx, &owners)) } else { None };
550    hir::Crate { owners, opt_hir_hash }
551}
552
553#[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)]
554enum ParamMode {
555    /// Any path in a type context.
556    Explicit,
557    /// The `module::Type` in `module::Type::method` in an expression.
558    Optional,
559}
560
561#[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)]
562enum AllowReturnTypeNotation {
563    /// Only in types, since RTN is denied later during HIR lowering.
564    Yes,
565    /// All other positions (path expr, method, use tree).
566    No,
567}
568
569enum GenericArgsMode {
570    /// Allow paren sugar, don't allow RTN.
571    ParenSugar,
572    /// Allow RTN, don't allow paren sugar.
573    ReturnTypeNotation,
574    // Error if parenthesized generics or RTN are encountered.
575    Err,
576    /// Silence errors when lowering generics. Only used with `Res::Err`.
577    Silence,
578}
579
580impl<'a, 'hir> LoweringContext<'a, 'hir> {
581    fn create_def(
582        &mut self,
583        node_id: ast::NodeId,
584        name: Option<Symbol>,
585        def_kind: DefKind,
586        def_path_data: DefPathData,
587        span: Span,
588    ) -> LocalDefId {
589        let parent = self.current_hir_id_owner.def_id;
590        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);
591        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!(
592            self.opt_local_def_id(node_id).is_none(),
593            "adding a def'n for node-id {:?} and def kind {:?} but a previous def'n exists: {:?}",
594            node_id,
595            def_kind,
596            self.tcx.hir_def_key(self.local_def_id(node_id)),
597        );
598
599        let def_id = self
600            .tcx
601            .at(span)
602            .create_def(parent, name, def_kind, Some(def_path_data), &mut self.disambiguator)
603            .def_id();
604
605        {
    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:605",
                        "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(605u32),
                        ::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);
606        self.resolver.node_id_to_def_id.insert(node_id, def_id);
607
608        def_id
609    }
610
611    fn next_node_id(&mut self) -> NodeId {
612        let start = self.resolver.next_node_id;
613        let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
614        self.resolver.next_node_id = ast::NodeId::from_u32(next);
615        start
616    }
617
618    /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
619    /// resolver (if any).
620    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
621        self.resolver.node_id_to_def_id.get(&node).copied()
622    }
623
624    fn local_def_id(&self, node: NodeId) -> LocalDefId {
625        self.opt_local_def_id(node).unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("no entry for node id: `{0:?}`",
            node));
}panic!("no entry for node id: `{node:?}`"))
626    }
627
628    /// Given the id of an owner node in the AST, returns the corresponding `OwnerId`.
629    fn owner_id(&self, node: NodeId) -> hir::OwnerId {
630        hir::OwnerId { def_id: self.local_def_id(node) }
631    }
632
633    /// Freshen the `LoweringContext` and ready it to lower a nested item.
634    /// The lowered item is registered into `self.children`.
635    ///
636    /// This function sets up `HirId` lowering infrastructure,
637    /// and stashes the shared mutable state to avoid pollution by the closure.
638    #[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(638u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["owner"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&owner)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let owner_id = self.owner_id(owner);
            let current_attrs = std::mem::take(&mut self.attrs);
            let current_bodies = std::mem::take(&mut self.bodies);
            let current_define_opaque =
                std::mem::take(&mut self.define_opaque);
            let current_ident_and_label_to_local_id =
                std::mem::take(&mut self.ident_and_label_to_local_id);
            let current_node_id_to_local_id =
                std::mem::take(&mut self.node_id_to_local_id);
            let current_trait_map = std::mem::take(&mut self.trait_map);
            let current_owner =
                std::mem::replace(&mut self.current_hir_id_owner, owner_id);
            let current_local_counter =
                std::mem::replace(&mut self.item_local_id_counter,
                    hir::ItemLocalId::new(1));
            let current_impl_trait_defs =
                std::mem::take(&mut self.impl_trait_defs);
            let current_impl_trait_bounds =
                std::mem::take(&mut self.impl_trait_bounds);
            let current_delayed_lints =
                std::mem::take(&mut self.delayed_lints);
            {
                let _old =
                    self.node_id_to_local_id.insert(owner,
                        hir::ItemLocalId::ZERO);
                if true {
                    match (&_old, &None) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    };
                };
            }
            let item = f(self);
            match (&owner_id, &item.def_id()) {
                (left_val, right_val) => {
                    if !(*left_val == *right_val) {
                        let kind = ::core::panicking::AssertKind::Eq;
                        ::core::panicking::assert_failed(kind, &*left_val,
                            &*right_val, ::core::option::Option::None);
                    }
                }
            };
            if !self.impl_trait_defs.is_empty() {
                ::core::panicking::panic("assertion failed: self.impl_trait_defs.is_empty()")
            };
            if !self.impl_trait_bounds.is_empty() {
                ::core::panicking::panic("assertion failed: self.impl_trait_bounds.is_empty()")
            };
            let info = self.make_owner_info(item);
            self.attrs = current_attrs;
            self.bodies = current_bodies;
            self.define_opaque = current_define_opaque;
            self.ident_and_label_to_local_id =
                current_ident_and_label_to_local_id;
            { self.node_id_to_local_id = current_node_id_to_local_id; }
            self.trait_map = current_trait_map;
            self.current_hir_id_owner = current_owner;
            self.item_local_id_counter = current_local_counter;
            self.impl_trait_defs = current_impl_trait_defs;
            self.impl_trait_bounds = current_impl_trait_bounds;
            self.delayed_lints = current_delayed_lints;
            if true {
                if !!self.children.iter().any(|(id, _)|
                                    id == &owner_id.def_id) {
                    ::core::panicking::panic("assertion failed: !self.children.iter().any(|(id, _)| id == &owner_id.def_id)")
                };
            };
            self.children.push((owner_id.def_id,
                    hir::MaybeOwner::Owner(info)));
        }
    }
}#[instrument(level = "debug", skip(self, f))]
639    fn with_hir_id_owner(
640        &mut self,
641        owner: NodeId,
642        f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
643    ) {
644        let owner_id = self.owner_id(owner);
645
646        let current_attrs = std::mem::take(&mut self.attrs);
647        let current_bodies = std::mem::take(&mut self.bodies);
648        let current_define_opaque = std::mem::take(&mut self.define_opaque);
649        let current_ident_and_label_to_local_id =
650            std::mem::take(&mut self.ident_and_label_to_local_id);
651
652        #[cfg(debug_assertions)]
653        let current_node_id_to_local_id = std::mem::take(&mut self.node_id_to_local_id);
654        let current_trait_map = std::mem::take(&mut self.trait_map);
655        let current_owner = std::mem::replace(&mut self.current_hir_id_owner, owner_id);
656        let current_local_counter =
657            std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
658        let current_impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
659        let current_impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
660        let current_delayed_lints = std::mem::take(&mut self.delayed_lints);
661
662        // Do not reset `next_node_id` and `node_id_to_def_id`:
663        // we want `f` to be able to refer to the `LocalDefId`s that the caller created.
664        // and the caller to refer to some of the subdefinitions' nodes' `LocalDefId`s.
665
666        // Always allocate the first `HirId` for the owner itself.
667        #[cfg(debug_assertions)]
668        {
669            let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::ZERO);
670            debug_assert_eq!(_old, None);
671        }
672
673        let item = f(self);
674        assert_eq!(owner_id, item.def_id());
675        // `f` should have consumed all the elements in these vectors when constructing `item`.
676        assert!(self.impl_trait_defs.is_empty());
677        assert!(self.impl_trait_bounds.is_empty());
678        let info = self.make_owner_info(item);
679
680        self.attrs = current_attrs;
681        self.bodies = current_bodies;
682        self.define_opaque = current_define_opaque;
683        self.ident_and_label_to_local_id = current_ident_and_label_to_local_id;
684
685        #[cfg(debug_assertions)]
686        {
687            self.node_id_to_local_id = current_node_id_to_local_id;
688        }
689        self.trait_map = current_trait_map;
690        self.current_hir_id_owner = current_owner;
691        self.item_local_id_counter = current_local_counter;
692        self.impl_trait_defs = current_impl_trait_defs;
693        self.impl_trait_bounds = current_impl_trait_bounds;
694        self.delayed_lints = current_delayed_lints;
695
696        debug_assert!(!self.children.iter().any(|(id, _)| id == &owner_id.def_id));
697        self.children.push((owner_id.def_id, hir::MaybeOwner::Owner(info)));
698    }
699
700    fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> {
701        let attrs = std::mem::take(&mut self.attrs);
702        let mut bodies = std::mem::take(&mut self.bodies);
703        let define_opaque = std::mem::take(&mut self.define_opaque);
704        let trait_map = std::mem::take(&mut self.trait_map);
705        let delayed_lints = std::mem::take(&mut self.delayed_lints).into_boxed_slice();
706
707        #[cfg(debug_assertions)]
708        for (id, attrs) in attrs.iter() {
709            // Verify that we do not store empty slices in the map.
710            if attrs.is_empty() {
711                {
    ::core::panicking::panic_fmt(format_args!("Stored empty attributes for {0:?}",
            id));
};panic!("Stored empty attributes for {:?}", id);
712            }
713        }
714
715        bodies.sort_by_key(|(k, _)| *k);
716        let bodies = SortedMap::from_presorted_elements(bodies);
717
718        // Don't hash unless necessary, because it's expensive.
719        let rustc_middle::hir::Hashes { opt_hash_including_bodies, attrs_hash, delayed_lints_hash } =
720            self.tcx.hash_owner_nodes(node, &bodies, &attrs, &delayed_lints, define_opaque);
721        let num_nodes = self.item_local_id_counter.as_usize();
722        let (nodes, parenting) = index::index_hir(self.tcx, node, &bodies, num_nodes);
723        let nodes = hir::OwnerNodes { opt_hash_including_bodies, nodes, bodies };
724        let attrs = hir::AttributeMap { map: attrs, opt_hash: attrs_hash, define_opaque };
725        let delayed_lints =
726            hir::lints::DelayedLints { lints: delayed_lints, opt_hash: delayed_lints_hash };
727
728        self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map, delayed_lints })
729    }
730
731    /// This method allocates a new `HirId` for the given `NodeId`.
732    /// Take care not to call this method if the resulting `HirId` is then not
733    /// actually used in the HIR, as that would trigger an assertion in the
734    /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
735    /// properly. Calling the method twice with the same `NodeId` is also forbidden.
736    x;#[instrument(level = "debug", skip(self), ret)]
737    fn lower_node_id(&mut self, ast_node_id: NodeId) -> HirId {
738        assert_ne!(ast_node_id, DUMMY_NODE_ID);
739
740        let owner = self.current_hir_id_owner;
741        let local_id = self.item_local_id_counter;
742        assert_ne!(local_id, hir::ItemLocalId::ZERO);
743        self.item_local_id_counter.increment_by(1);
744        let hir_id = HirId { owner, local_id };
745
746        if let Some(def_id) = self.opt_local_def_id(ast_node_id) {
747            self.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id)));
748        }
749
750        if let Some(&traits) = self.resolver.trait_map.get(&ast_node_id) {
751            self.trait_map.insert(hir_id.local_id, traits);
752        }
753
754        // Check whether the same `NodeId` is lowered more than once.
755        #[cfg(debug_assertions)]
756        {
757            let old = self.node_id_to_local_id.insert(ast_node_id, local_id);
758            assert_eq!(old, None);
759        }
760
761        hir_id
762    }
763
764    /// Generate a new `HirId` without a backing `NodeId`.
765    x;#[instrument(level = "debug", skip(self), ret)]
766    fn next_id(&mut self) -> HirId {
767        let owner = self.current_hir_id_owner;
768        let local_id = self.item_local_id_counter;
769        assert_ne!(local_id, hir::ItemLocalId::ZERO);
770        self.item_local_id_counter.increment_by(1);
771        HirId { owner, local_id }
772    }
773
774    #[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(774u32),
                                    ::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:781",
                                    "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(781u32),
                                    ::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))]
775    fn lower_res(&mut self, res: Res<NodeId>) -> Res {
776        let res: Result<Res, ()> = res.apply_id(|id| {
777            let owner = self.current_hir_id_owner;
778            let local_id = self.ident_and_label_to_local_id.get(&id).copied().ok_or(())?;
779            Ok(HirId { owner, local_id })
780        });
781        trace!(?res);
782
783        // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
784        // This can happen when trying to lower the return type `x` in erroneous code like
785        //   async fn foo(x: u8) -> x {}
786        // In that case, `x` is lowered as a function parameter, and the return type is lowered as
787        // an opaque type as a synthesized HIR owner.
788        res.unwrap_or(Res::Err)
789    }
790
791    fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
792        self.resolver.get_partial_res(id).map_or(Res::Err, |pr| pr.expect_full_res())
793    }
794
795    fn lower_import_res(&mut self, id: NodeId, span: Span) -> PerNS<Option<Res>> {
796        let per_ns = self.resolver.get_import_res(id);
797        let per_ns = per_ns.map(|res| res.map(|res| self.lower_res(res)));
798        if per_ns.is_empty() {
799            // Propagate the error to all namespaces, just to be sure.
800            self.dcx().span_delayed_bug(span, "no resolution for an import");
801            let err = Some(Res::Err);
802            return PerNS { type_ns: err, value_ns: err, macro_ns: err };
803        }
804        per_ns
805    }
806
807    fn make_lang_item_qpath(
808        &mut self,
809        lang_item: hir::LangItem,
810        span: Span,
811        args: Option<&'hir hir::GenericArgs<'hir>>,
812    ) -> hir::QPath<'hir> {
813        hir::QPath::Resolved(None, self.make_lang_item_path(lang_item, span, args))
814    }
815
816    fn make_lang_item_path(
817        &mut self,
818        lang_item: hir::LangItem,
819        span: Span,
820        args: Option<&'hir hir::GenericArgs<'hir>>,
821    ) -> &'hir hir::Path<'hir> {
822        let def_id = self.tcx.require_lang_item(lang_item, span);
823        let def_kind = self.tcx.def_kind(def_id);
824        let res = Res::Def(def_kind, def_id);
825        self.arena.alloc(hir::Path {
826            span,
827            res,
828            segments: self.arena.alloc_from_iter([hir::PathSegment {
829                ident: Ident::new(lang_item.name(), span),
830                hir_id: self.next_id(),
831                res,
832                args,
833                infer_args: args.is_none(),
834            }]),
835        })
836    }
837
838    /// Reuses the span but adds information like the kind of the desugaring and features that are
839    /// allowed inside this span.
840    fn mark_span_with_reason(
841        &self,
842        reason: DesugaringKind,
843        span: Span,
844        allow_internal_unstable: Option<Arc<[Symbol]>>,
845    ) -> Span {
846        self.tcx.with_stable_hashing_context(|hcx| {
847            span.mark_with_reason(allow_internal_unstable, reason, span.edition(), hcx)
848        })
849    }
850
851    fn span_lowerer(&self) -> SpanLowerer {
852        SpanLowerer {
853            is_incremental: self.tcx.sess.opts.incremental.is_some(),
854            def_id: self.current_hir_id_owner.def_id,
855        }
856    }
857
858    /// Intercept all spans entering HIR.
859    /// Mark a span as relative to the current owning item.
860    fn lower_span(&self, span: Span) -> Span {
861        self.span_lowerer().lower(span)
862    }
863
864    fn lower_ident(&self, ident: Ident) -> Ident {
865        Ident::new(ident.name, self.lower_span(ident.span))
866    }
867
868    /// Converts a lifetime into a new generic parameter.
869    #[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(869u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["ident", "node_id",
                                                    "res", "source"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<hir::GenericParam<'hir>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (name, kind) =
                match res {
                    LifetimeRes::Param { .. } => {
                        (hir::ParamName::Plain(ident),
                            hir::LifetimeParamKind::Explicit)
                    }
                    LifetimeRes::Fresh { param, kind, .. } => {
                        let _def_id =
                            self.create_def(param, Some(kw::UnderscoreLifetime),
                                DefKind::LifetimeParam,
                                DefPathData::DesugaredAnonymousLifetime, ident.span);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:890",
                                                "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(890u32),
                                                ::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))]
870    fn lifetime_res_to_generic_param(
871        &mut self,
872        ident: Ident,
873        node_id: NodeId,
874        res: LifetimeRes,
875        source: hir::GenericParamSource,
876    ) -> Option<hir::GenericParam<'hir>> {
877        let (name, kind) = match res {
878            LifetimeRes::Param { .. } => {
879                (hir::ParamName::Plain(ident), hir::LifetimeParamKind::Explicit)
880            }
881            LifetimeRes::Fresh { param, kind, .. } => {
882                // Late resolution delegates to us the creation of the `LocalDefId`.
883                let _def_id = self.create_def(
884                    param,
885                    Some(kw::UnderscoreLifetime),
886                    DefKind::LifetimeParam,
887                    DefPathData::DesugaredAnonymousLifetime,
888                    ident.span,
889                );
890                debug!(?_def_id);
891
892                (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided(kind))
893            }
894            LifetimeRes::Static { .. } | LifetimeRes::Error(..) => return None,
895            res => panic!(
896                "Unexpected lifetime resolution {:?} for {:?} at {:?}",
897                res, ident, ident.span
898            ),
899        };
900        let hir_id = self.lower_node_id(node_id);
901        let def_id = self.local_def_id(node_id);
902        Some(hir::GenericParam {
903            hir_id,
904            def_id,
905            name,
906            span: self.lower_span(ident.span),
907            pure_wrt_drop: false,
908            kind: hir::GenericParamKind::Lifetime { kind },
909            colon_span: None,
910            source,
911        })
912    }
913
914    /// Lowers a lifetime binder that defines `generic_params`, returning the corresponding HIR
915    /// nodes. The returned list includes any "extra" lifetime parameters that were added by the
916    /// name resolver owing to lifetime elision; this also populates the resolver's node-id->def-id
917    /// map, so that later calls to `opt_node_id_to_def_id` that refer to these extra lifetime
918    /// parameters will be successful.
919    x;#[instrument(level = "debug", skip(self), ret)]
920    #[inline]
921    fn lower_lifetime_binder(
922        &mut self,
923        binder: NodeId,
924        generic_params: &[GenericParam],
925    ) -> &'hir [hir::GenericParam<'hir>] {
926        // Start by creating params for extra lifetimes params, as this creates the definitions
927        // that may be referred to by the AST inside `generic_params`.
928        let extra_lifetimes = self.resolver.extra_lifetime_params(binder);
929        debug!(?extra_lifetimes);
930        let extra_lifetimes: Vec<_> = extra_lifetimes
931            .into_iter()
932            .filter_map(|(ident, node_id, res)| {
933                self.lifetime_res_to_generic_param(
934                    ident,
935                    node_id,
936                    res,
937                    hir::GenericParamSource::Binder,
938                )
939            })
940            .collect();
941        let arena = self.arena;
942        let explicit_generic_params =
943            self.lower_generic_params_mut(generic_params, hir::GenericParamSource::Binder);
944        arena.alloc_from_iter(explicit_generic_params.chain(extra_lifetimes.into_iter()))
945    }
946
947    fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
948        let was_in_dyn_type = self.is_in_dyn_type;
949        self.is_in_dyn_type = in_scope;
950
951        let result = f(self);
952
953        self.is_in_dyn_type = was_in_dyn_type;
954
955        result
956    }
957
958    fn with_new_scopes<T>(&mut self, scope_span: Span, f: impl FnOnce(&mut Self) -> T) -> T {
959        let current_item = self.current_item;
960        self.current_item = Some(scope_span);
961
962        let was_in_loop_condition = self.is_in_loop_condition;
963        self.is_in_loop_condition = false;
964
965        let old_contract = self.contract_ensures.take();
966
967        let try_block_scope = mem::replace(&mut self.try_block_scope, TryBlockScope::Function);
968        let loop_scope = self.loop_scope.take();
969        let ret = f(self);
970        self.try_block_scope = try_block_scope;
971        self.loop_scope = loop_scope;
972
973        self.contract_ensures = old_contract;
974
975        self.is_in_loop_condition = was_in_loop_condition;
976
977        self.current_item = current_item;
978
979        ret
980    }
981
982    fn lower_attrs(
983        &mut self,
984        id: HirId,
985        attrs: &[Attribute],
986        target_span: Span,
987        target: Target,
988    ) -> &'hir [hir::Attribute] {
989        self.lower_attrs_with_extra(id, attrs, target_span, target, &[])
990    }
991
992    fn lower_attrs_with_extra(
993        &mut self,
994        id: HirId,
995        attrs: &[Attribute],
996        target_span: Span,
997        target: Target,
998        extra_hir_attributes: &[hir::Attribute],
999    ) -> &'hir [hir::Attribute] {
1000        if attrs.is_empty() && extra_hir_attributes.is_empty() {
1001            &[]
1002        } else {
1003            let mut lowered_attrs =
1004                self.lower_attrs_vec(attrs, self.lower_span(target_span), id, target);
1005            lowered_attrs.extend(extra_hir_attributes.iter().cloned());
1006
1007            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);
1008            let ret = self.arena.alloc_from_iter(lowered_attrs);
1009
1010            // this is possible if an item contained syntactical attribute,
1011            // but none of them parse successfully or all of them were ignored
1012            // for not being built-in attributes at all. They could be remaining
1013            // unexpanded attributes used as markers in proc-macro derives for example.
1014            // This will have emitted some diagnostics for the misparse, but will then
1015            // not emit the attribute making the list empty.
1016            if ret.is_empty() {
1017                &[]
1018            } else {
1019                self.attrs.insert(id.local_id, ret);
1020                ret
1021            }
1022        }
1023    }
1024
1025    fn lower_attrs_vec(
1026        &mut self,
1027        attrs: &[Attribute],
1028        target_span: Span,
1029        target_hir_id: HirId,
1030        target: Target,
1031    ) -> Vec<hir::Attribute> {
1032        let l = self.span_lowerer();
1033        self.attribute_parser.parse_attribute_list(
1034            attrs,
1035            target_span,
1036            target,
1037            OmitDoc::Lower,
1038            |s| l.lower(s),
1039            |lint_id, span, kind| {
1040                self.delayed_lints.push(DelayedLint::AttributeParsing(AttributeLint {
1041                    lint_id,
1042                    id: target_hir_id,
1043                    span,
1044                    kind,
1045                }));
1046            },
1047        )
1048    }
1049
1050    fn alias_attrs(&mut self, id: HirId, target_id: HirId) {
1051        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);
1052        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);
1053        if let Some(&a) = self.attrs.get(&target_id.local_id) {
1054            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
1055            self.attrs.insert(id.local_id, a);
1056        }
1057    }
1058
1059    fn lower_delim_args(&self, args: &DelimArgs) -> DelimArgs {
1060        args.clone()
1061    }
1062
1063    /// Lower an associated item constraint.
1064    #[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(1064u32),
                                    ::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:1070",
                                    "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(1070u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["constraint",
                                                    "itctx"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&constraint)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&itctx) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            let gen_args =
                if let Some(gen_args) = &constraint.gen_args {
                    let gen_args_ctor =
                        match gen_args {
                            GenericArgs::AngleBracketed(data) => {
                                self.lower_angle_bracketed_parameter_data(data,
                                        ParamMode::Explicit, itctx).0
                            }
                            GenericArgs::Parenthesized(data) => {
                                if let Some(first_char) =
                                            constraint.ident.as_str().chars().next() &&
                                        first_char.is_ascii_lowercase() {
                                    let err =
                                        match (&data.inputs[..], &data.output) {
                                            ([_, ..], FnRetTy::Default(_)) => {
                                                errors::BadReturnTypeNotation::Inputs {
                                                    span: data.inputs_span,
                                                }
                                            }
                                            ([], FnRetTy::Default(_)) => {
                                                errors::BadReturnTypeNotation::NeedsDots {
                                                    span: data.inputs_span,
                                                }
                                            }
                                            (_, FnRetTy::Ty(ty)) => {
                                                let span = data.inputs_span.shrink_to_hi().to(ty.span);
                                                errors::BadReturnTypeNotation::Output {
                                                    span,
                                                    suggestion: errors::RTNSuggestion {
                                                        output: span,
                                                        input: data.inputs_span,
                                                    },
                                                }
                                            }
                                        };
                                    let mut err = self.dcx().create_err(err);
                                    if !self.tcx.features().return_type_notation() &&
                                            self.tcx.sess.is_nightly_build() {
                                        add_feature_diagnostics(&mut err, &self.tcx.sess,
                                            sym::return_type_notation);
                                    }
                                    err.emit();
                                    GenericArgsCtor {
                                        args: Default::default(),
                                        constraints: &[],
                                        parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
                                        span: data.span,
                                    }
                                } else {
                                    self.emit_bad_parenthesized_trait_in_assoc_ty(data);
                                    self.lower_angle_bracketed_parameter_data(&data.as_angle_bracketed_args(),
                                            ParamMode::Explicit, itctx).0
                                }
                            }
                            GenericArgs::ParenthesizedElided(span) =>
                                GenericArgsCtor {
                                    args: Default::default(),
                                    constraints: &[],
                                    parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
                                    span: *span,
                                },
                        };
                    gen_args_ctor.into_generic_args(self)
                } else { self.arena.alloc(hir::GenericArgs::none()) };
            let kind =
                match &constraint.kind {
                    AssocItemConstraintKind::Equality { term } => {
                        let term =
                            match term {
                                Term::Ty(ty) => self.lower_ty_alloc(ty, itctx).into(),
                                Term::Const(c) =>
                                    self.lower_anon_const_to_const_arg_and_alloc(c).into(),
                            };
                        hir::AssocItemConstraintKind::Equality { term }
                    }
                    AssocItemConstraintKind::Bound { bounds } => {
                        if self.is_in_dyn_type {
                            let suggestion =
                                match itctx {
                                    ImplTraitContext::OpaqueTy { .. } |
                                        ImplTraitContext::Universal => {
                                        let bound_end_span =
                                            constraint.gen_args.as_ref().map_or(constraint.ident.span,
                                                |args| args.span());
                                        if bound_end_span.eq_ctxt(constraint.span) {
                                            Some(self.tcx.sess.source_map().next_point(bound_end_span))
                                        } else { None }
                                    }
                                    _ => None,
                                };
                            let guar =
                                self.dcx().emit_err(errors::MisplacedAssocTyBinding {
                                        span: constraint.span,
                                        suggestion,
                                    });
                            let err_ty =
                                &*self.arena.alloc(self.ty(constraint.span,
                                                hir::TyKind::Err(guar)));
                            hir::AssocItemConstraintKind::Equality {
                                term: err_ty.into(),
                            }
                        } else {
                            let bounds =
                                self.lower_param_bounds(bounds,
                                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::AssocTyBounds),
                                    itctx);
                            hir::AssocItemConstraintKind::Bound { bounds }
                        }
                    }
                };
            hir::AssocItemConstraint {
                hir_id: self.lower_node_id(constraint.id),
                ident: self.lower_ident(constraint.ident),
                gen_args,
                kind,
                span: self.lower_span(constraint.span),
            }
        }
    }
}#[instrument(level = "debug", skip_all)]
1065    fn lower_assoc_item_constraint(
1066        &mut self,
1067        constraint: &AssocItemConstraint,
1068        itctx: ImplTraitContext,
1069    ) -> hir::AssocItemConstraint<'hir> {
1070        debug!(?constraint, ?itctx);
1071        // Lower the generic arguments for the associated item.
1072        let gen_args = if let Some(gen_args) = &constraint.gen_args {
1073            let gen_args_ctor = match gen_args {
1074                GenericArgs::AngleBracketed(data) => {
1075                    self.lower_angle_bracketed_parameter_data(data, ParamMode::Explicit, itctx).0
1076                }
1077                GenericArgs::Parenthesized(data) => {
1078                    if let Some(first_char) = constraint.ident.as_str().chars().next()
1079                        && first_char.is_ascii_lowercase()
1080                    {
1081                        let err = match (&data.inputs[..], &data.output) {
1082                            ([_, ..], FnRetTy::Default(_)) => {
1083                                errors::BadReturnTypeNotation::Inputs { span: data.inputs_span }
1084                            }
1085                            ([], FnRetTy::Default(_)) => {
1086                                errors::BadReturnTypeNotation::NeedsDots { span: data.inputs_span }
1087                            }
1088                            // The case `T: Trait<method(..) -> Ret>` is handled in the parser.
1089                            (_, FnRetTy::Ty(ty)) => {
1090                                let span = data.inputs_span.shrink_to_hi().to(ty.span);
1091                                errors::BadReturnTypeNotation::Output {
1092                                    span,
1093                                    suggestion: errors::RTNSuggestion {
1094                                        output: span,
1095                                        input: data.inputs_span,
1096                                    },
1097                                }
1098                            }
1099                        };
1100                        let mut err = self.dcx().create_err(err);
1101                        if !self.tcx.features().return_type_notation()
1102                            && self.tcx.sess.is_nightly_build()
1103                        {
1104                            add_feature_diagnostics(
1105                                &mut err,
1106                                &self.tcx.sess,
1107                                sym::return_type_notation,
1108                            );
1109                        }
1110                        err.emit();
1111                        GenericArgsCtor {
1112                            args: Default::default(),
1113                            constraints: &[],
1114                            parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
1115                            span: data.span,
1116                        }
1117                    } else {
1118                        self.emit_bad_parenthesized_trait_in_assoc_ty(data);
1119                        // FIXME(return_type_notation): we could issue a feature error
1120                        // if the parens are empty and there's no return type.
1121                        self.lower_angle_bracketed_parameter_data(
1122                            &data.as_angle_bracketed_args(),
1123                            ParamMode::Explicit,
1124                            itctx,
1125                        )
1126                        .0
1127                    }
1128                }
1129                GenericArgs::ParenthesizedElided(span) => GenericArgsCtor {
1130                    args: Default::default(),
1131                    constraints: &[],
1132                    parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
1133                    span: *span,
1134                },
1135            };
1136            gen_args_ctor.into_generic_args(self)
1137        } else {
1138            self.arena.alloc(hir::GenericArgs::none())
1139        };
1140        let kind = match &constraint.kind {
1141            AssocItemConstraintKind::Equality { term } => {
1142                let term = match term {
1143                    Term::Ty(ty) => self.lower_ty_alloc(ty, itctx).into(),
1144                    Term::Const(c) => self.lower_anon_const_to_const_arg_and_alloc(c).into(),
1145                };
1146                hir::AssocItemConstraintKind::Equality { term }
1147            }
1148            AssocItemConstraintKind::Bound { bounds } => {
1149                // Disallow ATB in dyn types
1150                if self.is_in_dyn_type {
1151                    let suggestion = match itctx {
1152                        ImplTraitContext::OpaqueTy { .. } | ImplTraitContext::Universal => {
1153                            let bound_end_span = constraint
1154                                .gen_args
1155                                .as_ref()
1156                                .map_or(constraint.ident.span, |args| args.span());
1157                            if bound_end_span.eq_ctxt(constraint.span) {
1158                                Some(self.tcx.sess.source_map().next_point(bound_end_span))
1159                            } else {
1160                                None
1161                            }
1162                        }
1163                        _ => None,
1164                    };
1165
1166                    let guar = self.dcx().emit_err(errors::MisplacedAssocTyBinding {
1167                        span: constraint.span,
1168                        suggestion,
1169                    });
1170                    let err_ty =
1171                        &*self.arena.alloc(self.ty(constraint.span, hir::TyKind::Err(guar)));
1172                    hir::AssocItemConstraintKind::Equality { term: err_ty.into() }
1173                } else {
1174                    let bounds = self.lower_param_bounds(
1175                        bounds,
1176                        RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::AssocTyBounds),
1177                        itctx,
1178                    );
1179                    hir::AssocItemConstraintKind::Bound { bounds }
1180                }
1181            }
1182        };
1183
1184        hir::AssocItemConstraint {
1185            hir_id: self.lower_node_id(constraint.id),
1186            ident: self.lower_ident(constraint.ident),
1187            gen_args,
1188            kind,
1189            span: self.lower_span(constraint.span),
1190        }
1191    }
1192
1193    fn emit_bad_parenthesized_trait_in_assoc_ty(&self, data: &ParenthesizedArgs) {
1194        // Suggest removing empty parentheses: "Trait()" -> "Trait"
1195        let sub = if data.inputs.is_empty() {
1196            let parentheses_span =
1197                data.inputs_span.shrink_to_lo().to(data.inputs_span.shrink_to_hi());
1198            AssocTyParenthesesSub::Empty { parentheses_span }
1199        }
1200        // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
1201        else {
1202            // Start of parameters to the 1st argument
1203            let open_param = data.inputs_span.shrink_to_lo().to(data
1204                .inputs
1205                .first()
1206                .unwrap()
1207                .span
1208                .shrink_to_lo());
1209            // End of last argument to end of parameters
1210            let close_param =
1211                data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi());
1212            AssocTyParenthesesSub::NotEmpty { open_param, close_param }
1213        };
1214        self.dcx().emit_err(AssocTyParentheses { span: data.span, sub });
1215    }
1216
1217    #[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(1217u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["arg", "itctx"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arg)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::GenericArg<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match arg {
                ast::GenericArg::Lifetime(lt) =>
                    GenericArg::Lifetime(self.lower_lifetime(lt,
                            LifetimeSource::Path {
                                angle_brackets: hir::AngleBrackets::Full,
                            }, lt.ident.into())),
                ast::GenericArg::Type(ty) => {
                    if ty.is_maybe_parenthesised_infer() {
                        return GenericArg::Infer(hir::InferArg {
                                    hir_id: self.lower_node_id(ty.id),
                                    span: self.lower_span(ty.span),
                                });
                    }
                    match &ty.kind {
                        TyKind::Path(None, path) => {
                            if let Some(res) =
                                    self.resolver.get_partial_res(ty.id).and_then(|partial_res|
                                            partial_res.full_res()) {
                                if !res.matches_ns(Namespace::TypeNS) &&
                                        path.is_potential_trivial_const_arg() {
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:1255",
                                                            "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(1255u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                        ::tracing::__macro_support::Option::Some(&format_args!("lower_generic_arg: Lowering type argument as const argument: {0:?}",
                                                                                        ty) as &dyn Value))])
                                                });
                                        } else { ; }
                                    };
                                    let ct =
                                        self.lower_const_path_to_const_arg(path, res, ty.id,
                                            ty.span);
                                    return GenericArg::Const(ct.try_as_ambig_ct().unwrap());
                                }
                            }
                        }
                        _ => {}
                    }
                    GenericArg::Type(self.lower_ty_alloc(ty,
                                    itctx).try_as_ambig_ty().unwrap())
                }
                ast::GenericArg::Const(ct) =>
                    GenericArg::Const(self.lower_anon_const_to_const_arg_and_alloc(ct).try_as_ambig_ct().unwrap()),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1218    fn lower_generic_arg(
1219        &mut self,
1220        arg: &ast::GenericArg,
1221        itctx: ImplTraitContext,
1222    ) -> hir::GenericArg<'hir> {
1223        match arg {
1224            ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(
1225                lt,
1226                LifetimeSource::Path { angle_brackets: hir::AngleBrackets::Full },
1227                lt.ident.into(),
1228            )),
1229            ast::GenericArg::Type(ty) => {
1230                // We cannot just match on `TyKind::Infer` as `(_)` is represented as
1231                // `TyKind::Paren(TyKind::Infer)` and should also be lowered to `GenericArg::Infer`
1232                if ty.is_maybe_parenthesised_infer() {
1233                    return GenericArg::Infer(hir::InferArg {
1234                        hir_id: self.lower_node_id(ty.id),
1235                        span: self.lower_span(ty.span),
1236                    });
1237                }
1238
1239                match &ty.kind {
1240                    // We parse const arguments as path types as we cannot distinguish them during
1241                    // parsing. We try to resolve that ambiguity by attempting resolution in both the
1242                    // type and value namespaces. If we resolved the path in the value namespace, we
1243                    // transform it into a generic const argument.
1244                    //
1245                    // FIXME: Should we be handling `(PATH_TO_CONST)`?
1246                    TyKind::Path(None, path) => {
1247                        if let Some(res) = self
1248                            .resolver
1249                            .get_partial_res(ty.id)
1250                            .and_then(|partial_res| partial_res.full_res())
1251                        {
1252                            if !res.matches_ns(Namespace::TypeNS)
1253                                && path.is_potential_trivial_const_arg()
1254                            {
1255                                debug!(
1256                                    "lower_generic_arg: Lowering type argument as const argument: {:?}",
1257                                    ty,
1258                                );
1259
1260                                let ct =
1261                                    self.lower_const_path_to_const_arg(path, res, ty.id, ty.span);
1262                                return GenericArg::Const(ct.try_as_ambig_ct().unwrap());
1263                            }
1264                        }
1265                    }
1266                    _ => {}
1267                }
1268                GenericArg::Type(self.lower_ty_alloc(ty, itctx).try_as_ambig_ty().unwrap())
1269            }
1270            ast::GenericArg::Const(ct) => GenericArg::Const(
1271                self.lower_anon_const_to_const_arg_and_alloc(ct).try_as_ambig_ct().unwrap(),
1272            ),
1273        }
1274    }
1275
1276    #[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(1276u32),
                                    ::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))]
1277    fn lower_ty_alloc(&mut self, t: &Ty, itctx: ImplTraitContext) -> &'hir hir::Ty<'hir> {
1278        self.arena.alloc(self.lower_ty(t, itctx))
1279    }
1280
1281    fn lower_path_ty(
1282        &mut self,
1283        t: &Ty,
1284        qself: &Option<Box<QSelf>>,
1285        path: &Path,
1286        param_mode: ParamMode,
1287        itctx: ImplTraitContext,
1288    ) -> hir::Ty<'hir> {
1289        // Check whether we should interpret this as a bare trait object.
1290        // This check mirrors the one in late resolution. We only introduce this special case in
1291        // the rare occurrence we need to lower `Fresh` anonymous lifetimes.
1292        // The other cases when a qpath should be opportunistically made a trait object are handled
1293        // by `ty_path`.
1294        if qself.is_none()
1295            && let Some(partial_res) = self.resolver.get_partial_res(t.id)
1296            && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res()
1297        {
1298            let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1299                let bound = this.lower_poly_trait_ref(
1300                    &PolyTraitRef {
1301                        bound_generic_params: ThinVec::new(),
1302                        modifiers: TraitBoundModifiers::NONE,
1303                        trait_ref: TraitRef { path: path.clone(), ref_id: t.id },
1304                        span: t.span,
1305                        parens: ast::Parens::No,
1306                    },
1307                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitObjectTy),
1308                    itctx,
1309                );
1310                let bounds = this.arena.alloc_from_iter([bound]);
1311                let lifetime_bound = this.elided_dyn_bound(t.span);
1312                (bounds, lifetime_bound)
1313            });
1314            let kind = hir::TyKind::TraitObject(
1315                bounds,
1316                TaggedRef::new(lifetime_bound, TraitObjectSyntax::None),
1317            );
1318            return hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.next_id() };
1319        }
1320
1321        let id = self.lower_node_id(t.id);
1322        let qpath = self.lower_qpath(
1323            t.id,
1324            qself,
1325            path,
1326            param_mode,
1327            AllowReturnTypeNotation::Yes,
1328            itctx,
1329            None,
1330        );
1331        self.ty_path(id, t.span, qpath)
1332    }
1333
1334    fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1335        hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1336    }
1337
1338    fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1339        self.ty(span, hir::TyKind::Tup(tys))
1340    }
1341
1342    fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> hir::Ty<'hir> {
1343        let kind = match &t.kind {
1344            TyKind::Infer => hir::TyKind::Infer(()),
1345            TyKind::Err(guar) => hir::TyKind::Err(*guar),
1346            TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty_alloc(ty, itctx)),
1347            TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1348            TyKind::Ref(region, mt) => {
1349                let lifetime = self.lower_ty_direct_lifetime(t, *region);
1350                hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx))
1351            }
1352            TyKind::PinnedRef(region, mt) => {
1353                let lifetime = self.lower_ty_direct_lifetime(t, *region);
1354                let kind = hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx));
1355                let span = self.lower_span(t.span);
1356                let arg = hir::Ty { kind, span, hir_id: self.next_id() };
1357                let args = self.arena.alloc(hir::GenericArgs {
1358                    args: self.arena.alloc([hir::GenericArg::Type(self.arena.alloc(arg))]),
1359                    constraints: &[],
1360                    parenthesized: hir::GenericArgsParentheses::No,
1361                    span_ext: span,
1362                });
1363                let path = self.make_lang_item_qpath(hir::LangItem::Pin, span, Some(args));
1364                hir::TyKind::Path(path)
1365            }
1366            TyKind::FnPtr(f) => {
1367                let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1368                hir::TyKind::FnPtr(self.arena.alloc(hir::FnPtrTy {
1369                    generic_params,
1370                    safety: self.lower_safety(f.safety, hir::Safety::Safe),
1371                    abi: self.lower_extern(f.ext),
1372                    decl: self.lower_fn_decl(&f.decl, t.id, t.span, FnDeclKind::Pointer, None),
1373                    param_idents: self.lower_fn_params_to_idents(&f.decl),
1374                }))
1375            }
1376            TyKind::UnsafeBinder(f) => {
1377                let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1378                hir::TyKind::UnsafeBinder(self.arena.alloc(hir::UnsafeBinderTy {
1379                    generic_params,
1380                    inner_ty: self.lower_ty_alloc(&f.inner_ty, itctx),
1381                }))
1382            }
1383            TyKind::Never => hir::TyKind::Never,
1384            TyKind::Tup(tys) => hir::TyKind::Tup(
1385                self.arena.alloc_from_iter(tys.iter().map(|ty| self.lower_ty(ty, itctx))),
1386            ),
1387            TyKind::Paren(ty) => {
1388                return self.lower_ty(ty, itctx);
1389            }
1390            TyKind::Path(qself, path) => {
1391                return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1392            }
1393            TyKind::ImplicitSelf => {
1394                let hir_id = self.next_id();
1395                let res = self.expect_full_res(t.id);
1396                let res = self.lower_res(res);
1397                hir::TyKind::Path(hir::QPath::Resolved(
1398                    None,
1399                    self.arena.alloc(hir::Path {
1400                        res,
1401                        segments: self.arena.alloc_from_iter([hir::PathSegment::new(Ident::with_dummy_span(kw::SelfUpper),
                hir_id, res)])arena_vec![self; hir::PathSegment::new(
1402                            Ident::with_dummy_span(kw::SelfUpper),
1403                            hir_id,
1404                            res
1405                        )],
1406                        span: self.lower_span(t.span),
1407                    }),
1408                ))
1409            }
1410            TyKind::Array(ty, length) => hir::TyKind::Array(
1411                self.lower_ty_alloc(ty, itctx),
1412                self.lower_array_length_to_const_arg(length),
1413            ),
1414            TyKind::TraitObject(bounds, kind) => {
1415                let mut lifetime_bound = None;
1416                let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1417                    let bounds =
1418                        this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| match bound {
1419                            // We can safely ignore constness here since AST validation
1420                            // takes care of rejecting invalid modifier combinations and
1421                            // const trait bounds in trait object types.
1422                            GenericBound::Trait(ty) => {
1423                                let trait_ref = this.lower_poly_trait_ref(
1424                                    ty,
1425                                    RelaxedBoundPolicy::Forbidden(
1426                                        RelaxedBoundForbiddenReason::TraitObjectTy,
1427                                    ),
1428                                    itctx,
1429                                );
1430                                Some(trait_ref)
1431                            }
1432                            GenericBound::Outlives(lifetime) => {
1433                                if lifetime_bound.is_none() {
1434                                    lifetime_bound = Some(this.lower_lifetime(
1435                                        lifetime,
1436                                        LifetimeSource::Other,
1437                                        lifetime.ident.into(),
1438                                    ));
1439                                }
1440                                None
1441                            }
1442                            // Ignore `use` syntax since that is not valid in objects.
1443                            GenericBound::Use(_, span) => {
1444                                this.dcx()
1445                                    .span_delayed_bug(*span, "use<> not allowed in dyn types");
1446                                None
1447                            }
1448                        }));
1449                    let lifetime_bound =
1450                        lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1451                    (bounds, lifetime_bound)
1452                });
1453                hir::TyKind::TraitObject(bounds, TaggedRef::new(lifetime_bound, *kind))
1454            }
1455            TyKind::ImplTrait(def_node_id, bounds) => {
1456                let span = t.span;
1457                match itctx {
1458                    ImplTraitContext::OpaqueTy { origin } => {
1459                        self.lower_opaque_impl_trait(span, origin, *def_node_id, bounds, itctx)
1460                    }
1461                    ImplTraitContext::Universal => {
1462                        if let Some(span) = bounds.iter().find_map(|bound| match *bound {
1463                            ast::GenericBound::Use(_, span) => Some(span),
1464                            _ => None,
1465                        }) {
1466                            self.tcx.dcx().emit_err(errors::NoPreciseCapturesOnApit { span });
1467                        }
1468
1469                        let def_id = self.local_def_id(*def_node_id);
1470                        let name = self.tcx.item_name(def_id.to_def_id());
1471                        let ident = Ident::new(name, span);
1472                        let (param, bounds, path) = self.lower_universal_param_and_bounds(
1473                            *def_node_id,
1474                            span,
1475                            ident,
1476                            bounds,
1477                        );
1478                        self.impl_trait_defs.push(param);
1479                        if let Some(bounds) = bounds {
1480                            self.impl_trait_bounds.push(bounds);
1481                        }
1482                        path
1483                    }
1484                    ImplTraitContext::InBinding => hir::TyKind::TraitAscription(
1485                        self.lower_param_bounds(bounds, RelaxedBoundPolicy::Allowed, itctx),
1486                    ),
1487                    ImplTraitContext::FeatureGated(position, feature) => {
1488                        let guar = self
1489                            .tcx
1490                            .sess
1491                            .create_feature_err(
1492                                MisplacedImplTrait {
1493                                    span: t.span,
1494                                    position: DiagArgFromDisplay(&position),
1495                                },
1496                                feature,
1497                            )
1498                            .emit();
1499                        hir::TyKind::Err(guar)
1500                    }
1501                    ImplTraitContext::Disallowed(position) => {
1502                        let guar = self.dcx().emit_err(MisplacedImplTrait {
1503                            span: t.span,
1504                            position: DiagArgFromDisplay(&position),
1505                        });
1506                        hir::TyKind::Err(guar)
1507                    }
1508                }
1509            }
1510            TyKind::Pat(ty, pat) => {
1511                hir::TyKind::Pat(self.lower_ty_alloc(ty, itctx), self.lower_ty_pat(pat, ty.span))
1512            }
1513            TyKind::FieldOf(ty, variant, field) => hir::TyKind::FieldOf(
1514                self.lower_ty_alloc(ty, itctx),
1515                self.arena.alloc(hir::TyFieldPath {
1516                    variant: variant.map(|variant| self.lower_ident(variant)),
1517                    field: self.lower_ident(*field),
1518                }),
1519            ),
1520            TyKind::MacCall(_) => {
1521                ::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")
1522            }
1523            TyKind::CVarArgs => {
1524                let guar = self.dcx().span_delayed_bug(
1525                    t.span,
1526                    "`TyKind::CVarArgs` should have been handled elsewhere",
1527                );
1528                hir::TyKind::Err(guar)
1529            }
1530            TyKind::Dummy => {
    ::core::panicking::panic_fmt(format_args!("`TyKind::Dummy` should never be lowered"));
}panic!("`TyKind::Dummy` should never be lowered"),
1531        };
1532
1533        hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1534    }
1535
1536    fn lower_ty_direct_lifetime(
1537        &mut self,
1538        t: &Ty,
1539        region: Option<Lifetime>,
1540    ) -> &'hir hir::Lifetime {
1541        let (region, syntax) = match region {
1542            Some(region) => (region, region.ident.into()),
1543
1544            None => {
1545                let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1546                    self.resolver.get_lifetime_res(t.id)
1547                {
1548                    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);
1549                    start
1550                } else {
1551                    self.next_node_id()
1552                };
1553                let span = self.tcx.sess.source_map().start_point(t.span).shrink_to_hi();
1554                let region = Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id };
1555                (region, LifetimeSyntax::Implicit)
1556            }
1557        };
1558        self.lower_lifetime(&region, LifetimeSource::Reference, syntax)
1559    }
1560
1561    /// Lowers a `ReturnPositionOpaqueTy` (`-> impl Trait`) or a `TypeAliasesOpaqueTy` (`type F =
1562    /// impl Trait`): this creates the associated Opaque Type (TAIT) definition and then returns a
1563    /// HIR type that references the TAIT.
1564    ///
1565    /// Given a function definition like:
1566    ///
1567    /// ```rust
1568    /// use std::fmt::Debug;
1569    ///
1570    /// fn test<'a, T: Debug>(x: &'a T) -> impl Debug + 'a {
1571    ///     x
1572    /// }
1573    /// ```
1574    ///
1575    /// we will create a TAIT definition in the HIR like
1576    ///
1577    /// ```rust,ignore (pseudo-Rust)
1578    /// type TestReturn<'a, T, 'x> = impl Debug + 'x
1579    /// ```
1580    ///
1581    /// and return a type like `TestReturn<'static, T, 'a>`, so that the function looks like:
1582    ///
1583    /// ```rust,ignore (pseudo-Rust)
1584    /// fn test<'a, T: Debug>(x: &'a T) -> TestReturn<'static, T, 'a>
1585    /// ```
1586    ///
1587    /// Note the subtlety around type parameters! The new TAIT, `TestReturn`, inherits all the
1588    /// type parameters from the function `test` (this is implemented in the query layer, they aren't
1589    /// added explicitly in the HIR). But this includes all the lifetimes, and we only want to
1590    /// capture the lifetimes that are referenced in the bounds. Therefore, we add *extra* lifetime parameters
1591    /// for the lifetimes that get captured (`'x`, in our example above) and reference those.
1592    x;#[instrument(level = "debug", skip(self), ret)]
1593    fn lower_opaque_impl_trait(
1594        &mut self,
1595        span: Span,
1596        origin: hir::OpaqueTyOrigin<LocalDefId>,
1597        opaque_ty_node_id: NodeId,
1598        bounds: &GenericBounds,
1599        itctx: ImplTraitContext,
1600    ) -> hir::TyKind<'hir> {
1601        // Make sure we know that some funky desugaring has been going on here.
1602        // This is a first: there is code in other places like for loop
1603        // desugaring that explicitly states that we don't want to track that.
1604        // Not tracking it makes lints in rustc and clippy very fragile, as
1605        // frequently opened issues show.
1606        let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1607
1608        self.lower_opaque_inner(opaque_ty_node_id, origin, opaque_ty_span, |this| {
1609            this.lower_param_bounds(bounds, RelaxedBoundPolicy::Allowed, itctx)
1610        })
1611    }
1612
1613    fn lower_opaque_inner(
1614        &mut self,
1615        opaque_ty_node_id: NodeId,
1616        origin: hir::OpaqueTyOrigin<LocalDefId>,
1617        opaque_ty_span: Span,
1618        lower_item_bounds: impl FnOnce(&mut Self) -> &'hir [hir::GenericBound<'hir>],
1619    ) -> hir::TyKind<'hir> {
1620        let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id);
1621        let opaque_ty_hir_id = self.lower_node_id(opaque_ty_node_id);
1622        {
    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:1622",
                        "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(1622u32),
                        ::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);
1623
1624        let bounds = lower_item_bounds(self);
1625        let opaque_ty_def = hir::OpaqueTy {
1626            hir_id: opaque_ty_hir_id,
1627            def_id: opaque_ty_def_id,
1628            bounds,
1629            origin,
1630            span: self.lower_span(opaque_ty_span),
1631        };
1632        let opaque_ty_def = self.arena.alloc(opaque_ty_def);
1633
1634        hir::TyKind::OpaqueDef(opaque_ty_def)
1635    }
1636
1637    fn lower_precise_capturing_args(
1638        &mut self,
1639        precise_capturing_args: &[PreciseCapturingArg],
1640    ) -> &'hir [hir::PreciseCapturingArg<'hir>] {
1641        self.arena.alloc_from_iter(precise_capturing_args.iter().map(|arg| match arg {
1642            PreciseCapturingArg::Lifetime(lt) => hir::PreciseCapturingArg::Lifetime(
1643                self.lower_lifetime(lt, LifetimeSource::PreciseCapturing, lt.ident.into()),
1644            ),
1645            PreciseCapturingArg::Arg(path, id) => {
1646                let [segment] = path.segments.as_slice() else {
1647                    ::core::panicking::panic("explicit panic");panic!();
1648                };
1649                let res = self.resolver.get_partial_res(*id).map_or(Res::Err, |partial_res| {
1650                    partial_res.full_res().expect("no partial res expected for precise capture arg")
1651                });
1652                hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
1653                    hir_id: self.lower_node_id(*id),
1654                    ident: self.lower_ident(segment.ident),
1655                    res: self.lower_res(res),
1656                })
1657            }
1658        }))
1659    }
1660
1661    fn lower_fn_params_to_idents(&mut self, decl: &FnDecl) -> &'hir [Option<Ident>] {
1662        self.arena.alloc_from_iter(decl.inputs.iter().map(|param| match param.pat.kind {
1663            PatKind::Missing => None,
1664            PatKind::Ident(_, ident, _) => Some(self.lower_ident(ident)),
1665            PatKind::Wild => Some(Ident::new(kw::Underscore, self.lower_span(param.pat.span))),
1666            _ => {
1667                self.dcx().span_delayed_bug(
1668                    param.pat.span,
1669                    "non-missing/ident/wild param pat must trigger an error",
1670                );
1671                None
1672            }
1673        }))
1674    }
1675
1676    /// Lowers a function declaration.
1677    ///
1678    /// `decl`: the unlowered (AST) function declaration.
1679    ///
1680    /// `fn_node_id`: `impl Trait` arguments are lowered into generic parameters on the given
1681    /// `NodeId`.
1682    ///
1683    /// `transform_return_type`: if `Some`, applies some conversion to the return type, such as is
1684    /// needed for `async fn` and `gen fn`. See [`CoroutineKind`] for more details.
1685    #[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(1685u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["decl", "fn_node_id",
                                                    "fn_span", "kind", "coro"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&decl)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_node_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coro)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'hir hir::FnDecl<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let c_variadic = decl.c_variadic();
            let mut inputs = &decl.inputs[..];
            if c_variadic { inputs = &inputs[..inputs.len() - 1]; }
            let inputs =
                self.arena.alloc_from_iter(inputs.iter().map(|param|
                            {
                                let itctx =
                                    match kind {
                                        FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl |
                                            FnDeclKind::Trait => {
                                            ImplTraitContext::Universal
                                        }
                                        FnDeclKind::ExternFn => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnParam)
                                        }
                                        FnDeclKind::Closure => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureParam)
                                        }
                                        FnDeclKind::Pointer => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerParam)
                                        }
                                    };
                                self.lower_ty(&param.ty, itctx)
                            }));
            let output =
                match coro {
                    Some(coro) => {
                        let fn_def_id = self.local_def_id(fn_node_id);
                        self.lower_coroutine_fn_ret_ty(&decl.output, fn_def_id,
                            coro, kind)
                    }
                    None =>
                        match &decl.output {
                            FnRetTy::Ty(ty) => {
                                let itctx =
                                    match kind {
                                        FnDeclKind::Fn | FnDeclKind::Inherent =>
                                            ImplTraitContext::OpaqueTy {
                                                origin: hir::OpaqueTyOrigin::FnReturn {
                                                    parent: self.local_def_id(fn_node_id),
                                                    in_trait_or_impl: None,
                                                },
                                            },
                                        FnDeclKind::Trait =>
                                            ImplTraitContext::OpaqueTy {
                                                origin: hir::OpaqueTyOrigin::FnReturn {
                                                    parent: self.local_def_id(fn_node_id),
                                                    in_trait_or_impl: Some(hir::RpitContext::Trait),
                                                },
                                            },
                                        FnDeclKind::Impl =>
                                            ImplTraitContext::OpaqueTy {
                                                origin: hir::OpaqueTyOrigin::FnReturn {
                                                    parent: self.local_def_id(fn_node_id),
                                                    in_trait_or_impl: Some(hir::RpitContext::TraitImpl),
                                                },
                                            },
                                        FnDeclKind::ExternFn => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnReturn)
                                        }
                                        FnDeclKind::Closure => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureReturn)
                                        }
                                        FnDeclKind::Pointer => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerReturn)
                                        }
                                    };
                                hir::FnRetTy::Return(self.lower_ty_alloc(ty, itctx))
                            }
                            FnRetTy::Default(span) =>
                                hir::FnRetTy::DefaultReturn(self.lower_span(*span)),
                        },
                };
            self.arena.alloc(hir::FnDecl {
                    inputs,
                    output,
                    c_variadic,
                    lifetime_elision_allowed: self.resolver.lifetime_elision_allowed.contains(&fn_node_id),
                    implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None,
                        |arg|
                            {
                                let is_mutable_pat =
                                    #[allow(non_exhaustive_omitted_patterns)] match arg.pat.kind
                                        {
                                        PatKind::Ident(hir::BindingMode(_, Mutability::Mut), ..) =>
                                            true,
                                        _ => false,
                                    };
                                match &arg.ty.kind {
                                    TyKind::ImplicitSelf if is_mutable_pat =>
                                        hir::ImplicitSelfKind::Mut,
                                    TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
                                    TyKind::Ref(_, mt) | TyKind::PinnedRef(_, mt) if
                                        mt.ty.kind.is_implicit_self() => {
                                        match mt.mutbl {
                                            hir::Mutability::Not => hir::ImplicitSelfKind::RefImm,
                                            hir::Mutability::Mut => hir::ImplicitSelfKind::RefMut,
                                        }
                                    }
                                    _ => hir::ImplicitSelfKind::None,
                                }
                            }),
                })
        }
    }
}#[instrument(level = "debug", skip(self))]
1686    fn lower_fn_decl(
1687        &mut self,
1688        decl: &FnDecl,
1689        fn_node_id: NodeId,
1690        fn_span: Span,
1691        kind: FnDeclKind,
1692        coro: Option<CoroutineKind>,
1693    ) -> &'hir hir::FnDecl<'hir> {
1694        let c_variadic = decl.c_variadic();
1695
1696        // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1697        // as they are not explicit in HIR/Ty function signatures.
1698        // (instead, the `c_variadic` flag is set to `true`)
1699        let mut inputs = &decl.inputs[..];
1700        if c_variadic {
1701            inputs = &inputs[..inputs.len() - 1];
1702        }
1703        let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1704            let itctx = match kind {
1705                FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait => {
1706                    ImplTraitContext::Universal
1707                }
1708                FnDeclKind::ExternFn => {
1709                    ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnParam)
1710                }
1711                FnDeclKind::Closure => {
1712                    ImplTraitContext::Disallowed(ImplTraitPosition::ClosureParam)
1713                }
1714                FnDeclKind::Pointer => {
1715                    ImplTraitContext::Disallowed(ImplTraitPosition::PointerParam)
1716                }
1717            };
1718            self.lower_ty(&param.ty, itctx)
1719        }));
1720
1721        let output = match coro {
1722            Some(coro) => {
1723                let fn_def_id = self.local_def_id(fn_node_id);
1724                self.lower_coroutine_fn_ret_ty(&decl.output, fn_def_id, coro, kind)
1725            }
1726            None => match &decl.output {
1727                FnRetTy::Ty(ty) => {
1728                    let itctx = match kind {
1729                        FnDeclKind::Fn | FnDeclKind::Inherent => ImplTraitContext::OpaqueTy {
1730                            origin: hir::OpaqueTyOrigin::FnReturn {
1731                                parent: self.local_def_id(fn_node_id),
1732                                in_trait_or_impl: None,
1733                            },
1734                        },
1735                        FnDeclKind::Trait => ImplTraitContext::OpaqueTy {
1736                            origin: hir::OpaqueTyOrigin::FnReturn {
1737                                parent: self.local_def_id(fn_node_id),
1738                                in_trait_or_impl: Some(hir::RpitContext::Trait),
1739                            },
1740                        },
1741                        FnDeclKind::Impl => ImplTraitContext::OpaqueTy {
1742                            origin: hir::OpaqueTyOrigin::FnReturn {
1743                                parent: self.local_def_id(fn_node_id),
1744                                in_trait_or_impl: Some(hir::RpitContext::TraitImpl),
1745                            },
1746                        },
1747                        FnDeclKind::ExternFn => {
1748                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnReturn)
1749                        }
1750                        FnDeclKind::Closure => {
1751                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureReturn)
1752                        }
1753                        FnDeclKind::Pointer => {
1754                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerReturn)
1755                        }
1756                    };
1757                    hir::FnRetTy::Return(self.lower_ty_alloc(ty, itctx))
1758                }
1759                FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(*span)),
1760            },
1761        };
1762
1763        self.arena.alloc(hir::FnDecl {
1764            inputs,
1765            output,
1766            c_variadic,
1767            lifetime_elision_allowed: self.resolver.lifetime_elision_allowed.contains(&fn_node_id),
1768            implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1769                let is_mutable_pat = matches!(
1770                    arg.pat.kind,
1771                    PatKind::Ident(hir::BindingMode(_, Mutability::Mut), ..)
1772                );
1773
1774                match &arg.ty.kind {
1775                    TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1776                    TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1777                    // Given we are only considering `ImplicitSelf` types, we needn't consider
1778                    // the case where we have a mutable pattern to a reference as that would
1779                    // no longer be an `ImplicitSelf`.
1780                    TyKind::Ref(_, mt) | TyKind::PinnedRef(_, mt)
1781                        if mt.ty.kind.is_implicit_self() =>
1782                    {
1783                        match mt.mutbl {
1784                            hir::Mutability::Not => hir::ImplicitSelfKind::RefImm,
1785                            hir::Mutability::Mut => hir::ImplicitSelfKind::RefMut,
1786                        }
1787                    }
1788                    _ => hir::ImplicitSelfKind::None,
1789                }
1790            }),
1791        })
1792    }
1793
1794    // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1795    // combined with the following definition of `OpaqueTy`:
1796    //
1797    //     type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1798    //
1799    // `output`: unlowered output type (`T` in `-> T`)
1800    // `fn_node_id`: `NodeId` of the parent function (used to create child impl trait definition)
1801    // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1802    #[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(1802u32),
                                    ::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))]
1803    fn lower_coroutine_fn_ret_ty(
1804        &mut self,
1805        output: &FnRetTy,
1806        fn_def_id: LocalDefId,
1807        coro: CoroutineKind,
1808        fn_kind: FnDeclKind,
1809    ) -> hir::FnRetTy<'hir> {
1810        let span = self.lower_span(output.span());
1811
1812        let (opaque_ty_node_id, allowed_features) = match coro {
1813            CoroutineKind::Async { return_impl_trait_id, .. } => (return_impl_trait_id, None),
1814            CoroutineKind::Gen { return_impl_trait_id, .. } => (return_impl_trait_id, None),
1815            CoroutineKind::AsyncGen { return_impl_trait_id, .. } => {
1816                (return_impl_trait_id, Some(Arc::clone(&self.allow_async_iterator)))
1817            }
1818        };
1819
1820        let opaque_ty_span =
1821            self.mark_span_with_reason(DesugaringKind::Async, span, allowed_features);
1822
1823        let in_trait_or_impl = match fn_kind {
1824            FnDeclKind::Trait => Some(hir::RpitContext::Trait),
1825            FnDeclKind::Impl => Some(hir::RpitContext::TraitImpl),
1826            FnDeclKind::Fn | FnDeclKind::Inherent => None,
1827            FnDeclKind::ExternFn | FnDeclKind::Closure | FnDeclKind::Pointer => unreachable!(),
1828        };
1829
1830        let opaque_ty_ref = self.lower_opaque_inner(
1831            opaque_ty_node_id,
1832            hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, in_trait_or_impl },
1833            opaque_ty_span,
1834            |this| {
1835                let bound = this.lower_coroutine_fn_output_type_to_bound(
1836                    output,
1837                    coro,
1838                    opaque_ty_span,
1839                    ImplTraitContext::OpaqueTy {
1840                        origin: hir::OpaqueTyOrigin::FnReturn {
1841                            parent: fn_def_id,
1842                            in_trait_or_impl,
1843                        },
1844                    },
1845                );
1846                arena_vec![this; bound]
1847            },
1848        );
1849
1850        let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
1851        hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
1852    }
1853
1854    /// Transforms `-> T` into `Future<Output = T>`.
1855    fn lower_coroutine_fn_output_type_to_bound(
1856        &mut self,
1857        output: &FnRetTy,
1858        coro: CoroutineKind,
1859        opaque_ty_span: Span,
1860        itctx: ImplTraitContext,
1861    ) -> hir::GenericBound<'hir> {
1862        // Compute the `T` in `Future<Output = T>` from the return type.
1863        let output_ty = match output {
1864            FnRetTy::Ty(ty) => {
1865                // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
1866                // `impl Future` opaque type that `async fn` implicitly
1867                // generates.
1868                self.lower_ty_alloc(ty, itctx)
1869            }
1870            FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
1871        };
1872
1873        // "<$assoc_ty_name = T>"
1874        let (assoc_ty_name, trait_lang_item) = match coro {
1875            CoroutineKind::Async { .. } => (sym::Output, hir::LangItem::Future),
1876            CoroutineKind::Gen { .. } => (sym::Item, hir::LangItem::Iterator),
1877            CoroutineKind::AsyncGen { .. } => (sym::Item, hir::LangItem::AsyncIterator),
1878        };
1879
1880        let bound_args = self.arena.alloc(hir::GenericArgs {
1881            args: &[],
1882            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)],
1883            parenthesized: hir::GenericArgsParentheses::No,
1884            span_ext: DUMMY_SP,
1885        });
1886
1887        hir::GenericBound::Trait(hir::PolyTraitRef {
1888            bound_generic_params: &[],
1889            modifiers: hir::TraitBoundModifiers::NONE,
1890            trait_ref: hir::TraitRef {
1891                path: self.make_lang_item_path(trait_lang_item, opaque_ty_span, Some(bound_args)),
1892                hir_ref_id: self.next_id(),
1893            },
1894            span: opaque_ty_span,
1895        })
1896    }
1897
1898    #[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(1898u32),
                                    ::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))]
1899    fn lower_param_bound(
1900        &mut self,
1901        tpb: &GenericBound,
1902        rbp: RelaxedBoundPolicy<'_>,
1903        itctx: ImplTraitContext,
1904    ) -> hir::GenericBound<'hir> {
1905        match tpb {
1906            GenericBound::Trait(p) => {
1907                hir::GenericBound::Trait(self.lower_poly_trait_ref(p, rbp, itctx))
1908            }
1909            GenericBound::Outlives(lifetime) => hir::GenericBound::Outlives(self.lower_lifetime(
1910                lifetime,
1911                LifetimeSource::OutlivesBound,
1912                lifetime.ident.into(),
1913            )),
1914            GenericBound::Use(args, span) => hir::GenericBound::Use(
1915                self.lower_precise_capturing_args(args),
1916                self.lower_span(*span),
1917            ),
1918        }
1919    }
1920
1921    fn lower_lifetime(
1922        &mut self,
1923        l: &Lifetime,
1924        source: LifetimeSource,
1925        syntax: LifetimeSyntax,
1926    ) -> &'hir hir::Lifetime {
1927        self.new_named_lifetime(l.id, l.id, l.ident, source, syntax)
1928    }
1929
1930    fn lower_lifetime_hidden_in_path(
1931        &mut self,
1932        id: NodeId,
1933        span: Span,
1934        angle_brackets: AngleBrackets,
1935    ) -> &'hir hir::Lifetime {
1936        self.new_named_lifetime(
1937            id,
1938            id,
1939            Ident::new(kw::UnderscoreLifetime, span),
1940            LifetimeSource::Path { angle_brackets },
1941            LifetimeSyntax::Implicit,
1942        )
1943    }
1944
1945    #[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(1945u32),
                                    ::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:1979",
                                    "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(1979u32),
                                    ::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))]
1946    fn new_named_lifetime(
1947        &mut self,
1948        id: NodeId,
1949        new_id: NodeId,
1950        ident: Ident,
1951        source: LifetimeSource,
1952        syntax: LifetimeSyntax,
1953    ) -> &'hir hir::Lifetime {
1954        let res = if let Some(res) = self.resolver.get_lifetime_res(id) {
1955            match res {
1956                LifetimeRes::Param { param, .. } => hir::LifetimeKind::Param(param),
1957                LifetimeRes::Fresh { param, .. } => {
1958                    assert_eq!(ident.name, kw::UnderscoreLifetime);
1959                    let param = self.local_def_id(param);
1960                    hir::LifetimeKind::Param(param)
1961                }
1962                LifetimeRes::Infer => {
1963                    assert_eq!(ident.name, kw::UnderscoreLifetime);
1964                    hir::LifetimeKind::Infer
1965                }
1966                LifetimeRes::Static { .. } => {
1967                    assert!(matches!(ident.name, kw::StaticLifetime | kw::UnderscoreLifetime));
1968                    hir::LifetimeKind::Static
1969                }
1970                LifetimeRes::Error(guar) => hir::LifetimeKind::Error(guar),
1971                LifetimeRes::ElidedAnchor { .. } => {
1972                    panic!("Unexpected `ElidedAnchar` {:?} at {:?}", ident, ident.span);
1973                }
1974            }
1975        } else {
1976            hir::LifetimeKind::Error(self.dcx().span_delayed_bug(ident.span, "unresolved lifetime"))
1977        };
1978
1979        debug!(?res);
1980        self.arena.alloc(hir::Lifetime::new(
1981            self.lower_node_id(new_id),
1982            self.lower_ident(ident),
1983            res,
1984            source,
1985            syntax,
1986        ))
1987    }
1988
1989    fn lower_generic_params_mut(
1990        &mut self,
1991        params: &[GenericParam],
1992        source: hir::GenericParamSource,
1993    ) -> impl Iterator<Item = hir::GenericParam<'hir>> {
1994        params.iter().map(move |param| self.lower_generic_param(param, source))
1995    }
1996
1997    fn lower_generic_params(
1998        &mut self,
1999        params: &[GenericParam],
2000        source: hir::GenericParamSource,
2001    ) -> &'hir [hir::GenericParam<'hir>] {
2002        self.arena.alloc_from_iter(self.lower_generic_params_mut(params, source))
2003    }
2004
2005    #[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(2005u32),
                                    ::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))]
2006    fn lower_generic_param(
2007        &mut self,
2008        param: &GenericParam,
2009        source: hir::GenericParamSource,
2010    ) -> hir::GenericParam<'hir> {
2011        let (name, kind) = self.lower_generic_param_kind(param, source);
2012
2013        let hir_id = self.lower_node_id(param.id);
2014        let param_attrs = &param.attrs;
2015        let param_span = param.span();
2016        let param = hir::GenericParam {
2017            hir_id,
2018            def_id: self.local_def_id(param.id),
2019            name,
2020            span: self.lower_span(param.span()),
2021            pure_wrt_drop: attr::contains_name(&param.attrs, sym::may_dangle),
2022            kind,
2023            colon_span: param.colon_span.map(|s| self.lower_span(s)),
2024            source,
2025        };
2026        self.lower_attrs(hir_id, param_attrs, param_span, Target::from_generic_param(&param));
2027        param
2028    }
2029
2030    fn lower_generic_param_kind(
2031        &mut self,
2032        param: &GenericParam,
2033        source: hir::GenericParamSource,
2034    ) -> (hir::ParamName, hir::GenericParamKind<'hir>) {
2035        match &param.kind {
2036            GenericParamKind::Lifetime => {
2037                // AST resolution emitted an error on those parameters, so we lower them using
2038                // `ParamName::Error`.
2039                let ident = self.lower_ident(param.ident);
2040                let param_name = if let Some(LifetimeRes::Error(..)) =
2041                    self.resolver.get_lifetime_res(param.id)
2042                {
2043                    ParamName::Error(ident)
2044                } else {
2045                    ParamName::Plain(ident)
2046                };
2047                let kind =
2048                    hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2049
2050                (param_name, kind)
2051            }
2052            GenericParamKind::Type { default, .. } => {
2053                // Not only do we deny type param defaults in binders but we also map them to `None`
2054                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2055                let default = default
2056                    .as_ref()
2057                    .filter(|_| match source {
2058                        hir::GenericParamSource::Generics => true,
2059                        hir::GenericParamSource::Binder => {
2060                            self.dcx().emit_err(errors::GenericParamDefaultInBinder {
2061                                span: param.span(),
2062                            });
2063
2064                            false
2065                        }
2066                    })
2067                    .map(|def| {
2068                        self.lower_ty_alloc(
2069                            def,
2070                            ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2071                        )
2072                    });
2073
2074                let kind = hir::GenericParamKind::Type { default, synthetic: false };
2075
2076                (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2077            }
2078            GenericParamKind::Const { ty, span: _, default } => {
2079                let ty = self.lower_ty_alloc(
2080                    ty,
2081                    ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2082                );
2083
2084                // Not only do we deny const param defaults in binders but we also map them to `None`
2085                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2086                let default = default
2087                    .as_ref()
2088                    .filter(|_| match source {
2089                        hir::GenericParamSource::Generics => true,
2090                        hir::GenericParamSource::Binder => {
2091                            self.dcx().emit_err(errors::GenericParamDefaultInBinder {
2092                                span: param.span(),
2093                            });
2094
2095                            false
2096                        }
2097                    })
2098                    .map(|def| self.lower_anon_const_to_const_arg_and_alloc(def));
2099
2100                (
2101                    hir::ParamName::Plain(self.lower_ident(param.ident)),
2102                    hir::GenericParamKind::Const { ty, default },
2103                )
2104            }
2105        }
2106    }
2107
2108    fn lower_trait_ref(
2109        &mut self,
2110        modifiers: ast::TraitBoundModifiers,
2111        p: &TraitRef,
2112        itctx: ImplTraitContext,
2113    ) -> hir::TraitRef<'hir> {
2114        let path = match self.lower_qpath(
2115            p.ref_id,
2116            &None,
2117            &p.path,
2118            ParamMode::Explicit,
2119            AllowReturnTypeNotation::No,
2120            itctx,
2121            Some(modifiers),
2122        ) {
2123            hir::QPath::Resolved(None, path) => path,
2124            qpath => {
    ::core::panicking::panic_fmt(format_args!("lower_trait_ref: unexpected QPath `{0:?}`",
            qpath));
}panic!("lower_trait_ref: unexpected QPath `{qpath:?}`"),
2125        };
2126        hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2127    }
2128
2129    #[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(2129u32),
                                    ::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))]
2130    fn lower_poly_trait_ref(
2131        &mut self,
2132        PolyTraitRef { bound_generic_params, modifiers, trait_ref, span, parens: _ }: &PolyTraitRef,
2133        rbp: RelaxedBoundPolicy<'_>,
2134        itctx: ImplTraitContext,
2135    ) -> hir::PolyTraitRef<'hir> {
2136        let bound_generic_params =
2137            self.lower_lifetime_binder(trait_ref.ref_id, bound_generic_params);
2138        let trait_ref = self.lower_trait_ref(*modifiers, trait_ref, itctx);
2139        let modifiers = self.lower_trait_bound_modifiers(*modifiers);
2140
2141        if let ast::BoundPolarity::Maybe(_) = modifiers.polarity {
2142            self.validate_relaxed_bound(trait_ref, *span, rbp);
2143        }
2144
2145        hir::PolyTraitRef {
2146            bound_generic_params,
2147            modifiers,
2148            trait_ref,
2149            span: self.lower_span(*span),
2150        }
2151    }
2152
2153    fn validate_relaxed_bound(
2154        &self,
2155        trait_ref: hir::TraitRef<'_>,
2156        span: Span,
2157        rbp: RelaxedBoundPolicy<'_>,
2158    ) {
2159        // Even though feature `more_maybe_bounds` enables the user to relax all default bounds
2160        // other than `Sized` in a lot more positions (thereby bypassing the given policy), we don't
2161        // want to advertise it to the user (via a feature gate error) since it's super internal.
2162        //
2163        // FIXME(more_maybe_bounds): Moreover, if we actually were to add proper default traits
2164        // (like a hypothetical `Move` or `Leak`) we would want to validate the location according
2165        // to default trait elaboration in HIR ty lowering (which depends on the specific trait in
2166        // question: E.g., `?Sized` & `?Move` most likely won't be allowed in all the same places).
2167
2168        match rbp {
2169            RelaxedBoundPolicy::Allowed => return,
2170            RelaxedBoundPolicy::AllowedIfOnTyParam(id, params) => {
2171                if let Some(res) = self.resolver.get_partial_res(id).and_then(|r| r.full_res())
2172                    && let Res::Def(DefKind::TyParam, def_id) = res
2173                    && params.iter().any(|p| def_id == self.local_def_id(p.id).to_def_id())
2174                {
2175                    return;
2176                }
2177            }
2178            RelaxedBoundPolicy::Forbidden(reason) => {
2179                let gate = |context, subject| {
2180                    let extended = self.tcx.features().more_maybe_bounds();
2181                    let is_sized = trait_ref
2182                        .trait_def_id()
2183                        .is_some_and(|def_id| self.tcx.is_lang_item(def_id, hir::LangItem::Sized));
2184
2185                    if extended && !is_sized {
2186                        return;
2187                    }
2188
2189                    let prefix = if extended { "`Sized` " } else { "" };
2190                    let mut diag = self.dcx().struct_span_err(
2191                        span,
2192                        ::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}"),
2193                    );
2194                    if is_sized {
2195                        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!(
2196                            "{subject} are not implicitly bounded by `Sized`, \
2197                             so there is nothing to relax"
2198                        ));
2199                    }
2200                    diag.emit();
2201                };
2202
2203                match reason {
2204                    RelaxedBoundForbiddenReason::TraitObjectTy => {
2205                        gate("trait object types", "trait object types");
2206                        return;
2207                    }
2208                    RelaxedBoundForbiddenReason::SuperTrait => {
2209                        gate("supertrait bounds", "traits");
2210                        return;
2211                    }
2212                    RelaxedBoundForbiddenReason::TraitAlias => {
2213                        gate("trait alias bounds", "trait aliases");
2214                        return;
2215                    }
2216                    RelaxedBoundForbiddenReason::AssocTyBounds
2217                    | RelaxedBoundForbiddenReason::LateBoundVarsInScope => {}
2218                };
2219            }
2220        }
2221
2222        self.dcx()
2223            .struct_span_err(span, "this relaxed bound is not permitted here")
2224            .with_note(
2225                "in this context, relaxed bounds are only allowed on \
2226                 type parameters defined on the closest item",
2227            )
2228            .emit();
2229    }
2230
2231    fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy<'hir> {
2232        hir::MutTy { ty: self.lower_ty_alloc(&mt.ty, itctx), mutbl: mt.mutbl }
2233    }
2234
2235    x;#[instrument(level = "debug", skip(self), ret)]
2236    fn lower_param_bounds(
2237        &mut self,
2238        bounds: &[GenericBound],
2239        rbp: RelaxedBoundPolicy<'_>,
2240        itctx: ImplTraitContext,
2241    ) -> hir::GenericBounds<'hir> {
2242        self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, rbp, itctx))
2243    }
2244
2245    fn lower_param_bounds_mut(
2246        &mut self,
2247        bounds: &[GenericBound],
2248        rbp: RelaxedBoundPolicy<'_>,
2249        itctx: ImplTraitContext,
2250    ) -> impl Iterator<Item = hir::GenericBound<'hir>> {
2251        bounds.iter().map(move |bound| self.lower_param_bound(bound, rbp, itctx))
2252    }
2253
2254    x;#[instrument(level = "debug", skip(self), ret)]
2255    fn lower_universal_param_and_bounds(
2256        &mut self,
2257        node_id: NodeId,
2258        span: Span,
2259        ident: Ident,
2260        bounds: &[GenericBound],
2261    ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2262        // Add a definition for the in-band `Param`.
2263        let def_id = self.local_def_id(node_id);
2264        let span = self.lower_span(span);
2265
2266        // Set the name to `impl Bound1 + Bound2`.
2267        let param = hir::GenericParam {
2268            hir_id: self.lower_node_id(node_id),
2269            def_id,
2270            name: ParamName::Plain(self.lower_ident(ident)),
2271            pure_wrt_drop: false,
2272            span,
2273            kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2274            colon_span: None,
2275            source: hir::GenericParamSource::Generics,
2276        };
2277
2278        let preds = self.lower_generic_bound_predicate(
2279            ident,
2280            node_id,
2281            &GenericParamKind::Type { default: None },
2282            bounds,
2283            /* colon_span */ None,
2284            span,
2285            RelaxedBoundPolicy::Allowed,
2286            ImplTraitContext::Universal,
2287            hir::PredicateOrigin::ImplTrait,
2288        );
2289
2290        let hir_id = self.next_id();
2291        let res = Res::Def(DefKind::TyParam, def_id.to_def_id());
2292        let ty = hir::TyKind::Path(hir::QPath::Resolved(
2293            None,
2294            self.arena.alloc(hir::Path {
2295                span,
2296                res,
2297                segments:
2298                    arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2299            }),
2300        ));
2301
2302        (param, preds, ty)
2303    }
2304
2305    /// Lowers a block directly to an expression, presuming that it
2306    /// has no attributes and is not targeted by a `break`.
2307    fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2308        let block = self.lower_block(b, false);
2309        self.expr_block(block)
2310    }
2311
2312    fn lower_array_length_to_const_arg(&mut self, c: &AnonConst) -> &'hir hir::ConstArg<'hir> {
2313        // We cannot just match on `ExprKind::Underscore` as `(_)` is represented as
2314        // `ExprKind::Paren(ExprKind::Underscore)` and should also be lowered to `GenericArg::Infer`
2315        match c.value.peel_parens().kind {
2316            ExprKind::Underscore => {
2317                let ct_kind = hir::ConstArgKind::Infer(());
2318                self.arena.alloc(hir::ConstArg {
2319                    hir_id: self.lower_node_id(c.id),
2320                    kind: ct_kind,
2321                    span: self.lower_span(c.value.span),
2322                })
2323            }
2324            _ => self.lower_anon_const_to_const_arg_and_alloc(c),
2325        }
2326    }
2327
2328    /// Used when lowering a type argument that turned out to actually be a const argument.
2329    ///
2330    /// Only use for that purpose since otherwise it will create a duplicate def.
2331    #[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(2331u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["path", "res",
                                                    "ty_id", "span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'hir hir::ConstArg<'hir> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            let is_trivial_path =
                path.is_potential_trivial_const_arg() &&
                    #[allow(non_exhaustive_omitted_patterns)] match res {
                        Res::Def(DefKind::ConstParam, _) => true,
                        _ => false,
                    };
            let ct_kind =
                if is_trivial_path || tcx.features().min_generic_const_args()
                    {
                    let qpath =
                        self.lower_qpath(ty_id, &None, path, ParamMode::Explicit,
                            AllowReturnTypeNotation::No,
                            ImplTraitContext::Disallowed(ImplTraitPosition::Path),
                            None);
                    hir::ConstArgKind::Path(qpath)
                } else {
                    let node_id = self.next_node_id();
                    let span = self.lower_span(span);
                    let def_id =
                        self.create_def(node_id, None, DefKind::AnonConst,
                            DefPathData::LateAnonConst, span);
                    let hir_id = self.lower_node_id(node_id);
                    let path_expr =
                        Expr {
                            id: ty_id,
                            kind: ExprKind::Path(None, path.clone()),
                            span,
                            attrs: AttrVec::new(),
                            tokens: None,
                        };
                    let ct =
                        self.with_new_scopes(span,
                            |this|
                                {
                                    self.arena.alloc(hir::AnonConst {
                                            def_id,
                                            hir_id,
                                            body: this.lower_const_body(path_expr.span,
                                                Some(&path_expr)),
                                            span,
                                        })
                                });
                    hir::ConstArgKind::Anon(ct)
                };
            self.arena.alloc(hir::ConstArg {
                    hir_id: self.next_id(),
                    kind: ct_kind,
                    span: self.lower_span(span),
                })
        }
    }
}#[instrument(level = "debug", skip(self))]
2332    fn lower_const_path_to_const_arg(
2333        &mut self,
2334        path: &Path,
2335        res: Res<NodeId>,
2336        ty_id: NodeId,
2337        span: Span,
2338    ) -> &'hir hir::ConstArg<'hir> {
2339        let tcx = self.tcx;
2340
2341        let is_trivial_path = path.is_potential_trivial_const_arg()
2342            && matches!(res, Res::Def(DefKind::ConstParam, _));
2343        let ct_kind = if is_trivial_path || tcx.features().min_generic_const_args() {
2344            let qpath = self.lower_qpath(
2345                ty_id,
2346                &None,
2347                path,
2348                ParamMode::Explicit,
2349                AllowReturnTypeNotation::No,
2350                // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2351                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2352                None,
2353            );
2354            hir::ConstArgKind::Path(qpath)
2355        } else {
2356            // Construct an AnonConst where the expr is the "ty"'s path.
2357            let node_id = self.next_node_id();
2358            let span = self.lower_span(span);
2359
2360            // Add a definition for the in-band const def.
2361            // We're lowering a const argument that was originally thought to be a type argument,
2362            // so the def collector didn't create the def ahead of time. That's why we have to do
2363            // it here.
2364            let def_id = self.create_def(
2365                node_id,
2366                None,
2367                DefKind::AnonConst,
2368                DefPathData::LateAnonConst,
2369                span,
2370            );
2371            let hir_id = self.lower_node_id(node_id);
2372
2373            let path_expr = Expr {
2374                id: ty_id,
2375                kind: ExprKind::Path(None, path.clone()),
2376                span,
2377                attrs: AttrVec::new(),
2378                tokens: None,
2379            };
2380
2381            let ct = self.with_new_scopes(span, |this| {
2382                self.arena.alloc(hir::AnonConst {
2383                    def_id,
2384                    hir_id,
2385                    body: this.lower_const_body(path_expr.span, Some(&path_expr)),
2386                    span,
2387                })
2388            });
2389            hir::ConstArgKind::Anon(ct)
2390        };
2391
2392        self.arena.alloc(hir::ConstArg {
2393            hir_id: self.next_id(),
2394            kind: ct_kind,
2395            span: self.lower_span(span),
2396        })
2397    }
2398
2399    fn lower_const_item_rhs(
2400        &mut self,
2401        rhs_kind: &ConstItemRhsKind,
2402        span: Span,
2403    ) -> hir::ConstItemRhs<'hir> {
2404        match rhs_kind {
2405            ConstItemRhsKind::Body { rhs: Some(body) } => {
2406                hir::ConstItemRhs::Body(self.lower_const_body(span, Some(body)))
2407            }
2408            ConstItemRhsKind::Body { rhs: None } => {
2409                hir::ConstItemRhs::Body(self.lower_const_body(span, None))
2410            }
2411            ConstItemRhsKind::TypeConst { rhs: Some(anon) } => {
2412                hir::ConstItemRhs::TypeConst(self.lower_anon_const_to_const_arg_and_alloc(anon))
2413            }
2414            ConstItemRhsKind::TypeConst { rhs: None } => {
2415                let const_arg = ConstArg {
2416                    hir_id: self.next_id(),
2417                    kind: hir::ConstArgKind::Error(
2418                        self.dcx().span_delayed_bug(DUMMY_SP, "no block"),
2419                    ),
2420                    span: DUMMY_SP,
2421                };
2422                hir::ConstItemRhs::TypeConst(self.arena.alloc(const_arg))
2423            }
2424        }
2425    }
2426
2427    x;#[instrument(level = "debug", skip(self), ret)]
2428    fn lower_expr_to_const_arg_direct(&mut self, expr: &Expr) -> hir::ConstArg<'hir> {
2429        let span = self.lower_span(expr.span);
2430
2431        let overly_complex_const = |this: &mut Self| {
2432            let e = this.dcx().struct_span_err(
2433                expr.span,
2434                "complex const arguments must be placed inside of a `const` block",
2435            );
2436
2437            ConstArg { hir_id: this.next_id(), kind: hir::ConstArgKind::Error(e.emit()), span }
2438        };
2439
2440        match &expr.kind {
2441            ExprKind::Call(func, args) if let ExprKind::Path(qself, path) = &func.kind => {
2442                let qpath = self.lower_qpath(
2443                    func.id,
2444                    qself,
2445                    path,
2446                    ParamMode::Explicit,
2447                    AllowReturnTypeNotation::No,
2448                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2449                    None,
2450                );
2451
2452                let lowered_args = self.arena.alloc_from_iter(args.iter().map(|arg| {
2453                    let const_arg = self.lower_expr_to_const_arg_direct(arg);
2454                    &*self.arena.alloc(const_arg)
2455                }));
2456
2457                ConstArg {
2458                    hir_id: self.next_id(),
2459                    kind: hir::ConstArgKind::TupleCall(qpath, lowered_args),
2460                    span,
2461                }
2462            }
2463            ExprKind::Tup(exprs) => {
2464                let exprs = self.arena.alloc_from_iter(exprs.iter().map(|expr| {
2465                    let expr = self.lower_expr_to_const_arg_direct(&expr);
2466                    &*self.arena.alloc(expr)
2467                }));
2468
2469                ConstArg { hir_id: self.next_id(), kind: hir::ConstArgKind::Tup(exprs), span }
2470            }
2471            ExprKind::Path(qself, path) => {
2472                let qpath = self.lower_qpath(
2473                    expr.id,
2474                    qself,
2475                    path,
2476                    ParamMode::Explicit,
2477                    AllowReturnTypeNotation::No,
2478                    // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2479                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2480                    None,
2481                );
2482
2483                ConstArg { hir_id: self.next_id(), kind: hir::ConstArgKind::Path(qpath), span }
2484            }
2485            ExprKind::Struct(se) => {
2486                let path = self.lower_qpath(
2487                    expr.id,
2488                    &se.qself,
2489                    &se.path,
2490                    // FIXME(mgca): we may want this to be `Optional` instead, but
2491                    // we would also need to make sure that HIR ty lowering errors
2492                    // when these paths wind up in signatures.
2493                    ParamMode::Explicit,
2494                    AllowReturnTypeNotation::No,
2495                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2496                    None,
2497                );
2498
2499                let fields = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
2500                    let hir_id = self.lower_node_id(f.id);
2501                    // FIXME(mgca): This might result in lowering attributes that
2502                    // then go unused as the `Target::ExprField` is not actually
2503                    // corresponding to `Node::ExprField`.
2504                    self.lower_attrs(hir_id, &f.attrs, f.span, Target::ExprField);
2505                    let expr = self.lower_expr_to_const_arg_direct(&f.expr);
2506
2507                    &*self.arena.alloc(hir::ConstArgExprField {
2508                        hir_id,
2509                        field: self.lower_ident(f.ident),
2510                        expr: self.arena.alloc(expr),
2511                        span: self.lower_span(f.span),
2512                    })
2513                }));
2514
2515                ConstArg {
2516                    hir_id: self.next_id(),
2517                    kind: hir::ConstArgKind::Struct(path, fields),
2518                    span,
2519                }
2520            }
2521            ExprKind::Array(elements) => {
2522                let lowered_elems = self.arena.alloc_from_iter(elements.iter().map(|element| {
2523                    let const_arg = self.lower_expr_to_const_arg_direct(element);
2524                    &*self.arena.alloc(const_arg)
2525                }));
2526                let array_expr = self.arena.alloc(hir::ConstArgArrayExpr {
2527                    span: self.lower_span(expr.span),
2528                    elems: lowered_elems,
2529                });
2530
2531                ConstArg {
2532                    hir_id: self.next_id(),
2533                    kind: hir::ConstArgKind::Array(array_expr),
2534                    span,
2535                }
2536            }
2537            ExprKind::Underscore => ConstArg {
2538                hir_id: self.lower_node_id(expr.id),
2539                kind: hir::ConstArgKind::Infer(()),
2540                span,
2541            },
2542            ExprKind::Block(block, _) => {
2543                if let [stmt] = block.stmts.as_slice()
2544                    && let StmtKind::Expr(expr) = &stmt.kind
2545                {
2546                    return self.lower_expr_to_const_arg_direct(expr);
2547                }
2548
2549                overly_complex_const(self)
2550            }
2551            ExprKind::Lit(literal) => {
2552                let span = expr.span;
2553                let literal = self.lower_lit(literal, span);
2554
2555                ConstArg {
2556                    hir_id: self.lower_node_id(expr.id),
2557                    kind: hir::ConstArgKind::Literal { lit: literal.node, negated: false },
2558                    span,
2559                }
2560            }
2561            ExprKind::Unary(UnOp::Neg, inner_expr)
2562                if let ExprKind::Lit(literal) = &inner_expr.kind =>
2563            {
2564                let span = expr.span;
2565                let literal = self.lower_lit(literal, span);
2566
2567                if !matches!(literal.node, LitKind::Int(..)) {
2568                    let err =
2569                        self.dcx().struct_span_err(expr.span, "negated literal must be an integer");
2570
2571                    return ConstArg {
2572                        hir_id: self.next_id(),
2573                        kind: hir::ConstArgKind::Error(err.emit()),
2574                        span,
2575                    };
2576                }
2577
2578                ConstArg {
2579                    hir_id: self.lower_node_id(expr.id),
2580                    kind: hir::ConstArgKind::Literal { lit: literal.node, negated: true },
2581                    span,
2582                }
2583            }
2584            ExprKind::ConstBlock(anon_const) => {
2585                let def_id = self.local_def_id(anon_const.id);
2586                assert_eq!(DefKind::AnonConst, self.tcx.def_kind(def_id));
2587                self.lower_anon_const_to_const_arg(anon_const, span)
2588            }
2589            _ => overly_complex_const(self),
2590        }
2591    }
2592
2593    /// See [`hir::ConstArg`] for when to use this function vs
2594    /// [`Self::lower_anon_const_to_anon_const`].
2595    fn lower_anon_const_to_const_arg_and_alloc(
2596        &mut self,
2597        anon: &AnonConst,
2598    ) -> &'hir hir::ConstArg<'hir> {
2599        self.arena.alloc(self.lower_anon_const_to_const_arg(anon, anon.value.span))
2600    }
2601
2602    #[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(2602u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["anon", "span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&anon)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: hir::ConstArg<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            if tcx.features().min_generic_const_args() {
                return match anon.mgca_disambiguation {
                        MgcaDisambiguation::AnonConst => {
                            let lowered_anon =
                                self.lower_anon_const_to_anon_const(anon, span);
                            ConstArg {
                                hir_id: self.next_id(),
                                kind: hir::ConstArgKind::Anon(lowered_anon),
                                span: lowered_anon.span,
                            }
                        }
                        MgcaDisambiguation::Direct =>
                            self.lower_expr_to_const_arg_direct(&anon.value),
                    };
            }
            let expr =
                if let ExprKind::Block(block, _) = &anon.value.kind &&
                                let [stmt] = block.stmts.as_slice() &&
                            let StmtKind::Expr(expr) = &stmt.kind &&
                        let ExprKind::Path(..) = &expr.kind {
                    expr
                } else { &anon.value };
            let maybe_res =
                self.resolver.get_partial_res(expr.id).and_then(|partial_res|
                        partial_res.full_res());
            if let ExprKind::Path(qself, path) = &expr.kind &&
                        path.is_potential_trivial_const_arg() &&
                    #[allow(non_exhaustive_omitted_patterns)] match maybe_res {
                        Some(Res::Def(DefKind::ConstParam, _)) => true,
                        _ => false,
                    } {
                let qpath =
                    self.lower_qpath(expr.id, qself, path, ParamMode::Explicit,
                        AllowReturnTypeNotation::No,
                        ImplTraitContext::Disallowed(ImplTraitPosition::Path),
                        None);
                return ConstArg {
                        hir_id: self.lower_node_id(anon.id),
                        kind: hir::ConstArgKind::Path(qpath),
                        span: self.lower_span(expr.span),
                    };
            }
            let lowered_anon =
                self.lower_anon_const_to_anon_const(anon, anon.value.span);
            ConstArg {
                hir_id: self.next_id(),
                kind: hir::ConstArgKind::Anon(lowered_anon),
                span: self.lower_span(expr.span),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2603    fn lower_anon_const_to_const_arg(
2604        &mut self,
2605        anon: &AnonConst,
2606        span: Span,
2607    ) -> hir::ConstArg<'hir> {
2608        let tcx = self.tcx;
2609
2610        // We cannot change parsing depending on feature gates available,
2611        // we can only require feature gates to be active as a delayed check.
2612        // Thus we just parse anon consts generally and make the real decision
2613        // making in ast lowering.
2614        // FIXME(min_generic_const_args): revisit once stable
2615        if tcx.features().min_generic_const_args() {
2616            return match anon.mgca_disambiguation {
2617                MgcaDisambiguation::AnonConst => {
2618                    let lowered_anon = self.lower_anon_const_to_anon_const(anon, span);
2619                    ConstArg {
2620                        hir_id: self.next_id(),
2621                        kind: hir::ConstArgKind::Anon(lowered_anon),
2622                        span: lowered_anon.span,
2623                    }
2624                }
2625                MgcaDisambiguation::Direct => self.lower_expr_to_const_arg_direct(&anon.value),
2626            };
2627        }
2628
2629        // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2630        // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2631        let expr = if let ExprKind::Block(block, _) = &anon.value.kind
2632            && let [stmt] = block.stmts.as_slice()
2633            && let StmtKind::Expr(expr) = &stmt.kind
2634            && let ExprKind::Path(..) = &expr.kind
2635        {
2636            expr
2637        } else {
2638            &anon.value
2639        };
2640
2641        let maybe_res =
2642            self.resolver.get_partial_res(expr.id).and_then(|partial_res| partial_res.full_res());
2643        if let ExprKind::Path(qself, path) = &expr.kind
2644            && path.is_potential_trivial_const_arg()
2645            && matches!(maybe_res, Some(Res::Def(DefKind::ConstParam, _)))
2646        {
2647            let qpath = self.lower_qpath(
2648                expr.id,
2649                qself,
2650                path,
2651                ParamMode::Explicit,
2652                AllowReturnTypeNotation::No,
2653                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2654                None,
2655            );
2656
2657            return ConstArg {
2658                hir_id: self.lower_node_id(anon.id),
2659                kind: hir::ConstArgKind::Path(qpath),
2660                span: self.lower_span(expr.span),
2661            };
2662        }
2663
2664        let lowered_anon = self.lower_anon_const_to_anon_const(anon, anon.value.span);
2665        ConstArg {
2666            hir_id: self.next_id(),
2667            kind: hir::ConstArgKind::Anon(lowered_anon),
2668            span: self.lower_span(expr.span),
2669        }
2670    }
2671
2672    /// See [`hir::ConstArg`] for when to use this function vs
2673    /// [`Self::lower_anon_const_to_const_arg`].
2674    fn lower_anon_const_to_anon_const(
2675        &mut self,
2676        c: &AnonConst,
2677        span: Span,
2678    ) -> &'hir hir::AnonConst {
2679        self.arena.alloc(self.with_new_scopes(c.value.span, |this| {
2680            let def_id = this.local_def_id(c.id);
2681            let hir_id = this.lower_node_id(c.id);
2682            hir::AnonConst {
2683                def_id,
2684                hir_id,
2685                body: this.lower_const_body(c.value.span, Some(&c.value)),
2686                span: this.lower_span(span),
2687            }
2688        }))
2689    }
2690
2691    fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2692        match u {
2693            CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2694            UserProvided => hir::UnsafeSource::UserProvided,
2695        }
2696    }
2697
2698    fn lower_trait_bound_modifiers(
2699        &mut self,
2700        modifiers: TraitBoundModifiers,
2701    ) -> hir::TraitBoundModifiers {
2702        let constness = match modifiers.constness {
2703            BoundConstness::Never => BoundConstness::Never,
2704            BoundConstness::Always(span) => BoundConstness::Always(self.lower_span(span)),
2705            BoundConstness::Maybe(span) => BoundConstness::Maybe(self.lower_span(span)),
2706        };
2707        let polarity = match modifiers.polarity {
2708            BoundPolarity::Positive => BoundPolarity::Positive,
2709            BoundPolarity::Negative(span) => BoundPolarity::Negative(self.lower_span(span)),
2710            BoundPolarity::Maybe(span) => BoundPolarity::Maybe(self.lower_span(span)),
2711        };
2712        hir::TraitBoundModifiers { constness, polarity }
2713    }
2714
2715    // Helper methods for building HIR.
2716
2717    fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2718        hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2719    }
2720
2721    fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2722        self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2723    }
2724
2725    fn stmt_let_pat(
2726        &mut self,
2727        attrs: Option<&'hir [hir::Attribute]>,
2728        span: Span,
2729        init: Option<&'hir hir::Expr<'hir>>,
2730        pat: &'hir hir::Pat<'hir>,
2731        source: hir::LocalSource,
2732    ) -> hir::Stmt<'hir> {
2733        let hir_id = self.next_id();
2734        if let Some(a) = attrs {
2735            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
2736            self.attrs.insert(hir_id.local_id, a);
2737        }
2738        let local = hir::LetStmt {
2739            super_: None,
2740            hir_id,
2741            init,
2742            pat,
2743            els: None,
2744            source,
2745            span: self.lower_span(span),
2746            ty: None,
2747        };
2748        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
2749    }
2750
2751    fn stmt_super_let_pat(
2752        &mut self,
2753        span: Span,
2754        pat: &'hir hir::Pat<'hir>,
2755        init: Option<&'hir hir::Expr<'hir>>,
2756    ) -> hir::Stmt<'hir> {
2757        let hir_id = self.next_id();
2758        let span = self.lower_span(span);
2759        let local = hir::LetStmt {
2760            super_: Some(span),
2761            hir_id,
2762            init,
2763            pat,
2764            els: None,
2765            source: hir::LocalSource::Normal,
2766            span,
2767            ty: None,
2768        };
2769        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
2770    }
2771
2772    fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2773        self.block_all(expr.span, &[], Some(expr))
2774    }
2775
2776    fn block_all(
2777        &mut self,
2778        span: Span,
2779        stmts: &'hir [hir::Stmt<'hir>],
2780        expr: Option<&'hir hir::Expr<'hir>>,
2781    ) -> &'hir hir::Block<'hir> {
2782        let blk = hir::Block {
2783            stmts,
2784            expr,
2785            hir_id: self.next_id(),
2786            rules: hir::BlockCheckMode::DefaultBlock,
2787            span: self.lower_span(span),
2788            targeted_by_break: false,
2789        };
2790        self.arena.alloc(blk)
2791    }
2792
2793    fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2794        let field = self.single_pat_field(span, pat);
2795        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field)
2796    }
2797
2798    fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2799        let field = self.single_pat_field(span, pat);
2800        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field)
2801    }
2802
2803    fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2804        let field = self.single_pat_field(span, pat);
2805        self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field)
2806    }
2807
2808    fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2809        self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[])
2810    }
2811
2812    fn single_pat_field(
2813        &mut self,
2814        span: Span,
2815        pat: &'hir hir::Pat<'hir>,
2816    ) -> &'hir [hir::PatField<'hir>] {
2817        let field = hir::PatField {
2818            hir_id: self.next_id(),
2819            ident: Ident::new(sym::integer(0), self.lower_span(span)),
2820            is_shorthand: false,
2821            pat,
2822            span: self.lower_span(span),
2823        };
2824        self.arena.alloc_from_iter([field])arena_vec![self; field]
2825    }
2826
2827    fn pat_lang_item_variant(
2828        &mut self,
2829        span: Span,
2830        lang_item: hir::LangItem,
2831        fields: &'hir [hir::PatField<'hir>],
2832    ) -> &'hir hir::Pat<'hir> {
2833        let path = self.make_lang_item_qpath(lang_item, self.lower_span(span), None);
2834        self.pat(span, hir::PatKind::Struct(path, fields, None))
2835    }
2836
2837    fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, HirId) {
2838        self.pat_ident_binding_mode(span, ident, hir::BindingMode::NONE)
2839    }
2840
2841    fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, HirId) {
2842        self.pat_ident_binding_mode_mut(span, ident, hir::BindingMode::NONE)
2843    }
2844
2845    fn pat_ident_binding_mode(
2846        &mut self,
2847        span: Span,
2848        ident: Ident,
2849        bm: hir::BindingMode,
2850    ) -> (&'hir hir::Pat<'hir>, HirId) {
2851        let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
2852        (self.arena.alloc(pat), hir_id)
2853    }
2854
2855    fn pat_ident_binding_mode_mut(
2856        &mut self,
2857        span: Span,
2858        ident: Ident,
2859        bm: hir::BindingMode,
2860    ) -> (hir::Pat<'hir>, HirId) {
2861        let hir_id = self.next_id();
2862
2863        (
2864            hir::Pat {
2865                hir_id,
2866                kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
2867                span: self.lower_span(span),
2868                default_binding_modes: true,
2869            },
2870            hir_id,
2871        )
2872    }
2873
2874    fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
2875        self.arena.alloc(hir::Pat {
2876            hir_id: self.next_id(),
2877            kind,
2878            span: self.lower_span(span),
2879            default_binding_modes: true,
2880        })
2881    }
2882
2883    fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
2884        hir::Pat {
2885            hir_id: self.next_id(),
2886            kind,
2887            span: self.lower_span(span),
2888            default_binding_modes: false,
2889        }
2890    }
2891
2892    fn ty_path(&mut self, mut hir_id: HirId, span: Span, qpath: hir::QPath<'hir>) -> hir::Ty<'hir> {
2893        let kind = match qpath {
2894            hir::QPath::Resolved(None, path) => {
2895                // Turn trait object paths into `TyKind::TraitObject` instead.
2896                match path.res {
2897                    Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
2898                        let principal = hir::PolyTraitRef {
2899                            bound_generic_params: &[],
2900                            modifiers: hir::TraitBoundModifiers::NONE,
2901                            trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
2902                            span: self.lower_span(span),
2903                        };
2904
2905                        // The original ID is taken by the `PolyTraitRef`,
2906                        // so the `Ty` itself needs a different one.
2907                        hir_id = self.next_id();
2908                        hir::TyKind::TraitObject(
2909                            self.arena.alloc_from_iter([principal])arena_vec![self; principal],
2910                            TaggedRef::new(self.elided_dyn_bound(span), TraitObjectSyntax::None),
2911                        )
2912                    }
2913                    _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
2914                }
2915            }
2916            _ => hir::TyKind::Path(qpath),
2917        };
2918
2919        hir::Ty { hir_id, kind, span: self.lower_span(span) }
2920    }
2921
2922    /// Invoked to create the lifetime argument(s) for an elided trait object
2923    /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
2924    /// when the bound is written, even if it is written with `'_` like in
2925    /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
2926    fn elided_dyn_bound(&mut self, span: Span) -> &'hir hir::Lifetime {
2927        let r = hir::Lifetime::new(
2928            self.next_id(),
2929            Ident::new(kw::UnderscoreLifetime, self.lower_span(span)),
2930            hir::LifetimeKind::ImplicitObjectLifetimeDefault,
2931            LifetimeSource::Other,
2932            LifetimeSyntax::Implicit,
2933        );
2934        {
    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:2934",
                        "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(2934u32),
                        ::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);
2935        self.arena.alloc(r)
2936    }
2937}
2938
2939/// Helper struct for the delayed construction of [`hir::GenericArgs`].
2940struct GenericArgsCtor<'hir> {
2941    args: SmallVec<[hir::GenericArg<'hir>; 4]>,
2942    constraints: &'hir [hir::AssocItemConstraint<'hir>],
2943    parenthesized: hir::GenericArgsParentheses,
2944    span: Span,
2945}
2946
2947impl<'hir> GenericArgsCtor<'hir> {
2948    fn is_empty(&self) -> bool {
2949        self.args.is_empty()
2950            && self.constraints.is_empty()
2951            && self.parenthesized == hir::GenericArgsParentheses::No
2952    }
2953
2954    fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
2955        let ga = hir::GenericArgs {
2956            args: this.arena.alloc_from_iter(self.args),
2957            constraints: self.constraints,
2958            parenthesized: self.parenthesized,
2959            span_ext: this.lower_span(self.span),
2960        };
2961        this.arena.alloc(ga)
2962    }
2963}