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::visit::Visitor;
43use rustc_ast::{self as ast, *};
44use rustc_attr_parsing::{AttributeParser, EmitAttribute, Late, OmitDoc};
45use rustc_data_structures::fingerprint::Fingerprint;
46use rustc_data_structures::fx::FxIndexSet;
47use rustc_data_structures::sorted_map::SortedMap;
48use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
49use rustc_data_structures::steal::Steal;
50use rustc_data_structures::tagged_ptr::TaggedRef;
51use rustc_errors::{DiagArgFromDisplay, DiagCtxtHandle};
52use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
53use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId};
54use rustc_hir::definitions::PerParentDisambiguatorState;
55use rustc_hir::lints::{AttributeLint, DelayedLint, DynAttribute};
56use rustc_hir::{
57    self as hir, AngleBrackets, ConstArg, GenericArg, HirId, ItemLocalMap, LifetimeSource,
58    LifetimeSyntax, ParamName, Target, TraitCandidate, find_attr,
59};
60use rustc_index::{Idx, IndexSlice, IndexVec};
61use rustc_macros::extension;
62use rustc_middle::hir::{self as mid_hir};
63use rustc_middle::span_bug;
64use rustc_middle::ty::{DelegationInfo, ResolverAstLowering, TyCtxt};
65use rustc_session::parse::add_feature_diagnostics;
66use rustc_span::symbol::{Ident, Symbol, kw, sym};
67use rustc_span::{DUMMY_SP, DesugaringKind, Span};
68use smallvec::SmallVec;
69use thin_vec::ThinVec;
70use tracing::{debug, instrument, trace};
71
72use crate::errors::{AssocTyParentheses, AssocTyParenthesesSub, MisplacedImplTrait};
73use crate::item::{Disambiguators, Owners};
74
75macro_rules! arena_vec {
76    ($this:expr; $($x:expr),*) => (
77        $this.arena.alloc_from_iter([$($x),*])
78    );
79}
80
81mod asm;
82mod block;
83mod contract;
84mod delegation;
85mod errors;
86mod expr;
87mod format;
88mod index;
89mod item;
90mod pat;
91mod path;
92pub mod stability;
93
94struct LoweringContext<'a, 'hir, R> {
95    tcx: TyCtxt<'hir>,
96    resolver: &'a mut R,
97    disambiguators: &'a mut Disambiguators,
98    current_disambiguator: PerParentDisambiguatorState,
99
100    /// Used to allocate HIR nodes.
101    arena: &'hir hir::Arena<'hir>,
102
103    /// Bodies inside the owner being lowered.
104    bodies: Vec<(hir::ItemLocalId, &'hir hir::Body<'hir>)>,
105    /// `#[define_opaque]` attributes
106    define_opaque: Option<&'hir [(Span, LocalDefId)]>,
107    /// Attributes inside the owner being lowered.
108    attrs: SortedMap<hir::ItemLocalId, &'hir [hir::Attribute]>,
109    /// Collect items that were created by lowering the current owner.
110    children: Vec<(LocalDefId, hir::MaybeOwner<'hir>)>,
111
112    contract_ensures: Option<(Span, Ident, HirId)>,
113
114    coroutine_kind: Option<hir::CoroutineKind>,
115
116    /// When inside an `async` context, this is the `HirId` of the
117    /// `task_context` local bound to the resume argument of the coroutine.
118    task_context: Option<HirId>,
119
120    /// Used to get the current `fn`'s def span to point to when using `await`
121    /// outside of an `async fn`.
122    current_item: Option<Span>,
123
124    try_block_scope: TryBlockScope,
125    loop_scope: Option<HirId>,
126    is_in_loop_condition: bool,
127    is_in_dyn_type: bool,
128    is_in_const_context: bool,
129
130    current_hir_id_owner: hir::OwnerId,
131    item_local_id_counter: hir::ItemLocalId,
132    trait_map: ItemLocalMap<&'hir [TraitCandidate<'hir>]>,
133
134    impl_trait_defs: Vec<hir::GenericParam<'hir>>,
135    impl_trait_bounds: Vec<hir::WherePredicate<'hir>>,
136
137    /// NodeIds of pattern identifiers and labelled nodes that are lowered inside the current HIR owner.
138    ident_and_label_to_local_id: NodeMap<hir::ItemLocalId>,
139    /// NodeIds that are lowered inside the current HIR owner. Only used for duplicate lowering check.
140    #[cfg(debug_assertions)]
141    node_id_to_local_id: NodeMap<hir::ItemLocalId>,
142
143    allow_contracts: Arc<[Symbol]>,
144    allow_try_trait: Arc<[Symbol]>,
145    allow_gen_future: Arc<[Symbol]>,
146    allow_pattern_type: Arc<[Symbol]>,
147    allow_async_gen: Arc<[Symbol]>,
148    allow_async_iterator: Arc<[Symbol]>,
149    allow_for_await: Arc<[Symbol]>,
150    allow_async_fn_traits: Arc<[Symbol]>,
151
152    delayed_lints: Vec<DelayedLint>,
153
154    attribute_parser: AttributeParser<'hir>,
155}
156
157impl<'a, 'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'a, 'hir, R> {
158    fn new(tcx: TyCtxt<'hir>, resolver: &'a mut R, disambiguators: &'a mut Disambiguators) -> Self {
159        let registered_tools = tcx.registered_tools(()).iter().map(|x| x.name).collect();
160        Self {
161            tcx,
162            resolver,
163            disambiguators,
164            current_disambiguator: Default::default(),
165            arena: tcx.hir_arena,
166
167            // HirId handling.
168            bodies: Vec::new(),
169            define_opaque: None,
170            attrs: SortedMap::default(),
171            children: Vec::default(),
172            contract_ensures: None,
173            current_hir_id_owner: hir::CRATE_OWNER_ID,
174            item_local_id_counter: hir::ItemLocalId::ZERO,
175            ident_and_label_to_local_id: Default::default(),
176            #[cfg(debug_assertions)]
177            node_id_to_local_id: Default::default(),
178            trait_map: Default::default(),
179
180            // Lowering state.
181            try_block_scope: TryBlockScope::Function,
182            loop_scope: None,
183            is_in_loop_condition: false,
184            is_in_dyn_type: false,
185            is_in_const_context: false,
186            coroutine_kind: None,
187            task_context: None,
188            current_item: None,
189            impl_trait_defs: Vec::new(),
190            impl_trait_bounds: Vec::new(),
191            allow_contracts: [sym::contracts_internals].into(),
192            allow_try_trait: [
193                sym::try_trait_v2,
194                sym::try_trait_v2_residual,
195                sym::yeet_desugar_details,
196            ]
197            .into(),
198            allow_pattern_type: [sym::pattern_types, sym::pattern_type_range_trait].into(),
199            allow_gen_future: if tcx.features().async_fn_track_caller() {
200                [sym::gen_future, sym::closure_track_caller].into()
201            } else {
202                [sym::gen_future].into()
203            },
204            allow_for_await: [sym::async_gen_internals, sym::async_iterator].into(),
205            allow_async_fn_traits: [sym::async_fn_traits].into(),
206            allow_async_gen: [sym::async_gen_internals].into(),
207            // FIXME(gen_blocks): how does `closure_track_caller`/`async_fn_track_caller`
208            // interact with `gen`/`async gen` blocks
209            allow_async_iterator: [sym::gen_future, sym::async_iterator].into(),
210
211            attribute_parser: AttributeParser::new(
212                tcx.sess,
213                tcx.features(),
214                registered_tools,
215                Late,
216            ),
217            delayed_lints: Vec::new(),
218        }
219    }
220
221    pub(crate) fn dcx(&self) -> DiagCtxtHandle<'hir> {
222        self.tcx.dcx()
223    }
224}
225
226struct SpanLowerer {
227    is_incremental: bool,
228    def_id: LocalDefId,
229}
230
231impl SpanLowerer {
232    fn lower(&self, span: Span) -> Span {
233        if self.is_incremental {
234            span.with_parent(Some(self.def_id))
235        } else {
236            // Do not make spans relative when not using incremental compilation.
237            span
238        }
239    }
240}
241
242struct ResolverDelayedAstLowering<'a, 'tcx> {
243    node_id_to_def_id: NodeMap<LocalDefId>,
244    partial_res_map: NodeMap<PartialRes>,
245    next_node_id: NodeId,
246    base: &'a ResolverAstLowering<'tcx>,
247}
248
249// FIXME(fn_delegation): delegate this trait impl to `self.base`
250impl<'a, 'tcx> ResolverAstLoweringExt<'tcx> for ResolverDelayedAstLowering<'a, 'tcx> {
251    fn legacy_const_generic_args(&self, expr: &Expr, tcx: TyCtxt<'tcx>) -> Option<Vec<usize>> {
252        self.base.legacy_const_generic_args(expr, tcx)
253    }
254
255    fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
256        self.partial_res_map.get(&id).copied().or_else(|| self.base.get_partial_res(id))
257    }
258
259    fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
260        self.base.get_import_res(id)
261    }
262
263    fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
264        self.base.get_label_res(id)
265    }
266
267    fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
268        self.base.get_lifetime_res(id)
269    }
270
271    fn extra_lifetime_params(&self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> {
272        self.base.extra_lifetime_params(id)
273    }
274
275    fn delegation_info(&self, id: LocalDefId) -> Option<&DelegationInfo> {
276        self.base.delegation_info(id)
277    }
278
279    fn opt_local_def_id(&self, id: NodeId) -> Option<LocalDefId> {
280        self.node_id_to_def_id.get(&id).copied().or_else(|| self.base.opt_local_def_id(id))
281    }
282
283    fn local_def_id(&self, id: NodeId) -> LocalDefId {
284        self.opt_local_def_id(id).expect("must have def_id")
285    }
286
287    fn lifetime_elision_allowed(&self, id: NodeId) -> bool {
288        self.base.lifetime_elision_allowed(id)
289    }
290
291    fn insert_new_def_id(&mut self, node_id: NodeId, def_id: LocalDefId) {
292        self.node_id_to_def_id.insert(node_id, def_id);
293    }
294
295    fn insert_partial_res(&mut self, node_id: NodeId, res: PartialRes) {
296        self.partial_res_map.insert(node_id, res);
297    }
298
299    fn trait_candidates(&self, node_id: NodeId) -> Option<&'tcx [hir::TraitCandidate<'tcx>]> {
300        self.base.trait_candidates(node_id)
301    }
302
303    #[inline]
304    fn next_node_id(&mut self) -> NodeId {
305        next_node_id(&mut self.next_node_id)
306    }
307}
308
309fn next_node_id(current_id: &mut NodeId) -> NodeId {
310    let start = *current_id;
311    let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
312    *current_id = ast::NodeId::from_u32(next);
313
314    start
315}
316
317impl<'tcx> ResolverAstLoweringExt<'tcx> for ResolverAstLowering<'tcx> {
    fn legacy_const_generic_args(&self, expr: &Expr, tcx: TyCtxt<'tcx>)
        -> Option<Vec<usize>> {
        let ExprKind::Path(None, path) = &expr.kind else { return None; };
        if path.segments.last().unwrap().args.is_some() { return None; }
        let def_id = self.get_partial_res(expr.id)?.full_res()?.opt_def_id()?;
        if def_id.is_local() { return None; }
        {
                {
                    'done:
                        {
                        for i in
                            ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
                            #[allow(unused_imports)]
                            use rustc_hir::attrs::AttributeKind::*;
                            let i: &rustc_hir::Attribute = i;
                            match i {
                                rustc_hir::Attribute::Parsed(RustcLegacyConstGenerics {
                                    fn_indexes, .. }) => {
                                    break 'done Some(fn_indexes);
                                }
                                rustc_hir::Attribute::Unparsed(..) =>
                                    {}
                                    #[deny(unreachable_patterns)]
                                    _ => {}
                            }
                        }
                        None
                    }
                }
            }.map(|fn_indexes|
                fn_indexes.iter().map(|(num, _)| *num).collect())
    }
    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(&self, id: NodeId)
        -> Vec<(Ident, NodeId, LifetimeRes)> {
        self.extra_lifetime_params_map.get(&id).cloned().unwrap_or_default()
    }
    fn delegation_info(&self, id: LocalDefId) -> Option<&DelegationInfo> {
        self.delegation_infos.get(&id)
    }
    fn opt_local_def_id(&self, id: NodeId) -> Option<LocalDefId> {
        self.node_id_to_def_id.get(&id).copied()
    }
    fn local_def_id(&self, id: NodeId) -> LocalDefId {
        self.opt_local_def_id(id).expect("must have def_id")
    }
    fn lifetime_elision_allowed(&self, id: NodeId) -> bool {
        self.lifetime_elision_allowed.contains(&id)
    }
    fn insert_new_def_id(&mut self, node_id: NodeId, def_id: LocalDefId) {
        self.node_id_to_def_id.insert(node_id, def_id);
    }
    fn insert_partial_res(&mut self, node_id: NodeId, res: PartialRes) {
        self.partial_res_map.insert(node_id, res);
    }
    fn trait_candidates(&self, node_id: NodeId)
        -> Option<&'tcx [hir::TraitCandidate<'tcx>]> {
        self.trait_map.get(&node_id).copied()
    }
    #[inline]
    fn next_node_id(&mut self) -> NodeId {
        next_node_id(&mut self.next_node_id)
    }
}#[extension(trait ResolverAstLoweringExt<'tcx>)]
318impl<'tcx> ResolverAstLowering<'tcx> {
319    fn legacy_const_generic_args(&self, expr: &Expr, tcx: TyCtxt<'tcx>) -> Option<Vec<usize>> {
320        let ExprKind::Path(None, path) = &expr.kind else {
321            return None;
322        };
323
324        // Don't perform legacy const generics rewriting if the path already
325        // has generic arguments.
326        if path.segments.last().unwrap().args.is_some() {
327            return None;
328        }
329
330        let def_id = self.get_partial_res(expr.id)?.full_res()?.opt_def_id()?;
331
332        // We only support cross-crate argument rewriting. Uses
333        // within the same crate should be updated to use the new
334        // const generics style.
335        if def_id.is_local() {
336            return None;
337        }
338
339        // we can use parsed attrs here since for other crates they're already available
340        find_attr!(
341            tcx, def_id,
342            RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
343        )
344        .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
345    }
346
347    fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
348        self.partial_res_map.get(&id).copied()
349    }
350
351    /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
352    fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
353        self.import_res_map.get(&id).copied().unwrap_or_default()
354    }
355
356    /// Obtains resolution for a label with the given `NodeId`.
357    fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
358        self.label_res_map.get(&id).copied()
359    }
360
361    /// Obtains resolution for a lifetime with the given `NodeId`.
362    fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
363        self.lifetimes_res_map.get(&id).copied()
364    }
365
366    /// Obtain the list of lifetimes parameters to add to an item.
367    ///
368    /// Extra lifetime parameters should only be added in places that can appear
369    /// as a `binder` in `LifetimeRes`.
370    ///
371    /// The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring
372    /// should appear at the enclosing `PolyTraitRef`.
373    fn extra_lifetime_params(&self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> {
374        self.extra_lifetime_params_map.get(&id).cloned().unwrap_or_default()
375    }
376
377    fn delegation_info(&self, id: LocalDefId) -> Option<&DelegationInfo> {
378        self.delegation_infos.get(&id)
379    }
380
381    fn opt_local_def_id(&self, id: NodeId) -> Option<LocalDefId> {
382        self.node_id_to_def_id.get(&id).copied()
383    }
384
385    fn local_def_id(&self, id: NodeId) -> LocalDefId {
386        self.opt_local_def_id(id).expect("must have def_id")
387    }
388
389    fn lifetime_elision_allowed(&self, id: NodeId) -> bool {
390        self.lifetime_elision_allowed.contains(&id)
391    }
392
393    fn insert_new_def_id(&mut self, node_id: NodeId, def_id: LocalDefId) {
394        self.node_id_to_def_id.insert(node_id, def_id);
395    }
396
397    fn insert_partial_res(&mut self, node_id: NodeId, res: PartialRes) {
398        self.partial_res_map.insert(node_id, res);
399    }
400
401    fn trait_candidates(&self, node_id: NodeId) -> Option<&'tcx [hir::TraitCandidate<'tcx>]> {
402        self.trait_map.get(&node_id).copied()
403    }
404
405    #[inline]
406    fn next_node_id(&mut self) -> NodeId {
407        next_node_id(&mut self.next_node_id)
408    }
409}
410
411/// How relaxed bounds `?Trait` should be treated.
412///
413/// Relaxed bounds should only be allowed in places where we later
414/// (namely during HIR ty lowering) perform *sized elaboration*.
415#[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)]
416enum RelaxedBoundPolicy<'a> {
417    Allowed,
418    AllowedIfOnTyParam(NodeId, &'a [ast::GenericParam]),
419    Forbidden(RelaxedBoundForbiddenReason),
420}
421
422#[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)]
423enum RelaxedBoundForbiddenReason {
424    TraitObjectTy,
425    SuperTrait,
426    TraitAlias,
427    AssocTyBounds,
428    LateBoundVarsInScope,
429}
430
431/// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
432/// and if so, what meaning it has.
433#[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)]
434enum ImplTraitContext {
435    /// Treat `impl Trait` as shorthand for a new universal generic parameter.
436    /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
437    /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
438    ///
439    /// Newly generated parameters should be inserted into the given `Vec`.
440    Universal,
441
442    /// Treat `impl Trait` as shorthand for a new opaque type.
443    /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
444    /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
445    ///
446    OpaqueTy { origin: hir::OpaqueTyOrigin<LocalDefId> },
447
448    /// Treat `impl Trait` as a "trait ascription", which is like a type
449    /// variable but that also enforces that a set of trait goals hold.
450    ///
451    /// This is useful to guide inference for unnameable types.
452    InBinding,
453
454    /// `impl Trait` is unstably accepted in this position.
455    FeatureGated(ImplTraitPosition, Symbol),
456    /// `impl Trait` is not accepted in this position.
457    Disallowed(ImplTraitPosition),
458}
459
460/// Position in which `impl Trait` is disallowed.
461#[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)]
462enum ImplTraitPosition {
463    Path,
464    Variable,
465    Trait,
466    Bound,
467    Generic,
468    ExternFnParam,
469    ClosureParam,
470    PointerParam,
471    FnTraitParam,
472    ExternFnReturn,
473    ClosureReturn,
474    PointerReturn,
475    FnTraitReturn,
476    GenericDefault,
477    ConstTy,
478    StaticTy,
479    AssocTy,
480    FieldTy,
481    Cast,
482    ImplSelf,
483    OffsetOf,
484}
485
486impl std::fmt::Display for ImplTraitPosition {
487    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
488        let name = match self {
489            ImplTraitPosition::Path => "paths",
490            ImplTraitPosition::Variable => "the type of variable bindings",
491            ImplTraitPosition::Trait => "traits",
492            ImplTraitPosition::Bound => "bounds",
493            ImplTraitPosition::Generic => "generics",
494            ImplTraitPosition::ExternFnParam => "`extern fn` parameters",
495            ImplTraitPosition::ClosureParam => "closure parameters",
496            ImplTraitPosition::PointerParam => "`fn` pointer parameters",
497            ImplTraitPosition::FnTraitParam => "the parameters of `Fn` trait bounds",
498            ImplTraitPosition::ExternFnReturn => "`extern fn` return types",
499            ImplTraitPosition::ClosureReturn => "closure return types",
500            ImplTraitPosition::PointerReturn => "`fn` pointer return types",
501            ImplTraitPosition::FnTraitReturn => "the return type of `Fn` trait bounds",
502            ImplTraitPosition::GenericDefault => "generic parameter defaults",
503            ImplTraitPosition::ConstTy => "const types",
504            ImplTraitPosition::StaticTy => "static types",
505            ImplTraitPosition::AssocTy => "associated types",
506            ImplTraitPosition::FieldTy => "field types",
507            ImplTraitPosition::Cast => "cast expression types",
508            ImplTraitPosition::ImplSelf => "impl headers",
509            ImplTraitPosition::OffsetOf => "`offset_of!` parameters",
510        };
511
512        f.write_fmt(format_args!("{0}", name))write!(f, "{name}")
513    }
514}
515
516#[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)]
517enum FnDeclKind {
518    Fn,
519    Inherent,
520    ExternFn,
521    Closure,
522    Pointer,
523    Trait,
524    Impl,
525}
526
527#[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)]
528enum AstOwner<'a> {
529    NonOwner,
530    Crate(&'a ast::Crate),
531    Item(&'a ast::Item),
532    AssocItem(&'a ast::AssocItem, visit::AssocCtxt),
533    ForeignItem(&'a ast::ForeignItem),
534}
535
536#[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)]
537enum TryBlockScope {
538    /// There isn't a `try` block, so a `?` will use `return`.
539    Function,
540    /// We're inside a `try { … }` block, so a `?` will block-break
541    /// from that block using a type depending only on the argument.
542    Homogeneous(HirId),
543    /// We're inside a `try as _ { … }` block, so a `?` will block-break
544    /// from that block using the type specified.
545    Heterogeneous(HirId),
546}
547
548fn index_crate<'a, 'b>(
549    resolver: &'b impl ResolverAstLoweringExt<'a>,
550    krate: &'a Crate,
551) -> IndexVec<LocalDefId, AstOwner<'a>> {
552    let mut indexer = Indexer { resolver, index: IndexVec::new() };
553    *indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner) =
554        AstOwner::Crate(krate);
555    visit::walk_crate(&mut indexer, krate);
556
557    return indexer.index;
558
559    struct Indexer<'a, 'b, R> {
560        resolver: &'b R,
561        index: IndexVec<LocalDefId, AstOwner<'a>>,
562    }
563
564    impl<'a, 'b, R: ResolverAstLoweringExt<'a>> visit::Visitor<'a> for Indexer<'a, 'b, R> {
565        fn visit_attribute(&mut self, _: &'a Attribute) {
566            // We do not want to lower expressions that appear in attributes,
567            // as they are not accessible to the rest of the HIR.
568        }
569
570        fn visit_item(&mut self, item: &'a ast::Item) {
571            let def_id = self.resolver.local_def_id(item.id);
572            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) = AstOwner::Item(item);
573            visit::walk_item(self, item)
574        }
575
576        fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) {
577            let def_id = self.resolver.local_def_id(item.id);
578            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) =
579                AstOwner::AssocItem(item, ctxt);
580            visit::walk_assoc_item(self, item, ctxt);
581        }
582
583        fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) {
584            let def_id = self.resolver.local_def_id(item.id);
585            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) =
586                AstOwner::ForeignItem(item);
587            visit::walk_item(self, item);
588        }
589    }
590}
591
592/// Compute the hash for the HIR of the full crate.
593/// This hash will then be part of the crate_hash which is stored in the metadata.
594fn compute_hir_hash(
595    tcx: TyCtxt<'_>,
596    owners: &IndexSlice<LocalDefId, hir::MaybeOwner<'_>>,
597) -> Fingerprint {
598    let mut hir_body_nodes: Vec<_> = owners
599        .iter_enumerated()
600        .filter_map(|(def_id, info)| {
601            let info = info.as_owner()?;
602            let def_path_hash = tcx.hir_def_path_hash(def_id);
603            Some((def_path_hash, info))
604        })
605        .collect();
606    hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
607
608    tcx.with_stable_hashing_context(|mut hcx| {
609        let mut stable_hasher = StableHasher::new();
610        hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher);
611        stable_hasher.finish()
612    })
613}
614
615pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
616    // Queries that borrow `resolver_for_lowering`.
617    tcx.ensure_done().output_filenames(());
618    tcx.ensure_done().early_lint_checks(());
619    tcx.ensure_done().debugger_visualizers(LOCAL_CRATE);
620    tcx.ensure_done().get_lang_items(());
621    let (mut resolver, krate) = tcx.resolver_for_lowering().steal();
622
623    let ast_index = index_crate(&resolver, &krate);
624    let mut owners = IndexVec::from_fn_n(
625        |_| hir::MaybeOwner::Phantom,
626        tcx.definitions_untracked().def_index_count(),
627    );
628
629    let mut disambiguators = Disambiguators::Default(resolver.disambiguators.steal());
630    let mut lowerer = item::ItemLowerer {
631        tcx,
632        resolver: &mut resolver,
633        ast_index: &ast_index,
634        owners: Owners::IndexVec(&mut owners),
635        disambiguators: &mut disambiguators,
636    };
637
638    let mut delayed_ids: FxIndexSet<LocalDefId> = Default::default();
639
640    for def_id in ast_index.indices() {
641        match &ast_index[def_id] {
642            AstOwner::Item(Item { kind: ItemKind::Delegation { .. }, .. })
643            | AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation { .. }, .. }, _) => {
644                delayed_ids.insert(def_id);
645            }
646            _ => lowerer.lower_node(def_id),
647        };
648    }
649
650    // Don't hash unless necessary, because it's expensive.
651    let opt_hir_hash =
652        if tcx.needs_crate_hash() { Some(compute_hir_hash(tcx, &owners)) } else { None };
653
654    let Disambiguators::Default(disambiguators) = disambiguators else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
655    let delayed_disambigs =
656        Arc::new(disambiguators.into_items().map(|(id, d)| (id, Steal::new(d))).collect());
657
658    let delayed_resolver = Steal::new((resolver, krate, delayed_disambigs));
659    mid_hir::Crate::new(owners, delayed_ids, delayed_resolver, opt_hir_hash)
660}
661
662/// Lowers an AST owner corresponding to `def_id`, now only delegations are lowered this way.
663pub fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
664    let krate = tcx.hir_crate(());
665
666    let (resolver, krate, delayed_disambigs) = &*krate.delayed_resolver.borrow();
667
668    // FIXME!!!(fn_delegation): make ast index lifetime same as resolver,
669    // as it is too bad to reindex whole crate on each delegation lowering.
670    let ast_index = index_crate(resolver, krate);
671
672    let mut resolver = ResolverDelayedAstLowering {
673        next_node_id: resolver.next_node_id,
674        partial_res_map: Default::default(),
675        node_id_to_def_id: Default::default(),
676        base: resolver,
677    };
678
679    let mut map = Default::default();
680    let mut lowerer = item::ItemLowerer {
681        tcx,
682        resolver: &mut resolver,
683        ast_index: &ast_index,
684        owners: Owners::Map(&mut map),
685        disambiguators: &mut Disambiguators::Delayed(Arc::clone(delayed_disambigs)),
686    };
687
688    lowerer.lower_node(def_id);
689
690    for (child_def_id, owner) in map {
691        tcx.feed_delayed_owner(child_def_id, owner);
692    }
693}
694
695#[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)]
696enum ParamMode {
697    /// Any path in a type context.
698    Explicit,
699    /// The `module::Type` in `module::Type::method` in an expression.
700    Optional,
701}
702
703#[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)]
704enum AllowReturnTypeNotation {
705    /// Only in types, since RTN is denied later during HIR lowering.
706    Yes,
707    /// All other positions (path expr, method, use tree).
708    No,
709}
710
711enum GenericArgsMode {
712    /// Allow paren sugar, don't allow RTN.
713    ParenSugar,
714    /// Allow RTN, don't allow paren sugar.
715    ReturnTypeNotation,
716    // Error if parenthesized generics or RTN are encountered.
717    Err,
718    /// Silence errors when lowering generics. Only used with `Res::Err`.
719    Silence,
720}
721
722impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
723    fn create_def(
724        &mut self,
725        node_id: ast::NodeId,
726        name: Option<Symbol>,
727        def_kind: DefKind,
728        span: Span,
729    ) -> LocalDefId {
730        let parent = self.current_hir_id_owner.def_id;
731        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);
732        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!(
733            self.opt_local_def_id(node_id).is_none(),
734            "adding a def'n for node-id {:?} and def kind {:?} but a previous def'n exists: {:?}",
735            node_id,
736            def_kind,
737            self.tcx.hir_def_key(self.local_def_id(node_id)),
738        );
739
740        let def_id = self
741            .tcx
742            .at(span)
743            .create_def(parent, name, def_kind, None, &mut self.current_disambiguator)
744            .def_id();
745
746        {
    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:746",
                        "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(746u32),
                        ::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);
747        self.resolver.insert_new_def_id(node_id, def_id);
748
749        def_id
750    }
751
752    fn next_node_id(&mut self) -> NodeId {
753        self.resolver.next_node_id()
754    }
755
756    /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
757    /// resolver (if any).
758    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
759        self.resolver.opt_local_def_id(node)
760    }
761
762    fn local_def_id(&self, node: NodeId) -> LocalDefId {
763        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:?}`"))
764    }
765
766    /// Given the id of an owner node in the AST, returns the corresponding `OwnerId`.
767    fn owner_id(&self, node: NodeId) -> hir::OwnerId {
768        hir::OwnerId { def_id: self.local_def_id(node) }
769    }
770
771    /// Freshen the `LoweringContext` and ready it to lower a nested item.
772    /// The lowered item is registered into `self.children`.
773    ///
774    /// This function sets up `HirId` lowering infrastructure,
775    /// and stashes the shared mutable state to avoid pollution by the closure.
776    #[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(776u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["owner"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&owner)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let owner_id = self.owner_id(owner);
            let def_id = owner_id.def_id;
            let new_disambig =
                match &mut self.disambiguators {
                    Disambiguators::Default(map) => map.remove(&def_id),
                    Disambiguators::Delayed(map) =>
                        map.get(&def_id).map(Steal::steal),
                };
            let new_disambig =
                new_disambig.unwrap_or_else(||
                        PerParentDisambiguatorState::new(def_id));
            let disambiguator =
                std::mem::replace(&mut self.current_disambiguator,
                    new_disambig);
            let current_attrs = std::mem::take(&mut self.attrs);
            let current_bodies = std::mem::take(&mut self.bodies);
            let current_define_opaque =
                std::mem::take(&mut self.define_opaque);
            let current_ident_and_label_to_local_id =
                std::mem::take(&mut self.ident_and_label_to_local_id);
            let current_node_id_to_local_id =
                std::mem::take(&mut self.node_id_to_local_id);
            let current_trait_map = std::mem::take(&mut self.trait_map);
            let current_owner =
                std::mem::replace(&mut self.current_hir_id_owner, owner_id);
            let current_local_counter =
                std::mem::replace(&mut self.item_local_id_counter,
                    hir::ItemLocalId::new(1));
            let current_impl_trait_defs =
                std::mem::take(&mut self.impl_trait_defs);
            let current_impl_trait_bounds =
                std::mem::take(&mut self.impl_trait_bounds);
            let current_delayed_lints =
                std::mem::take(&mut self.delayed_lints);
            {
                let _old =
                    self.node_id_to_local_id.insert(owner,
                        hir::ItemLocalId::ZERO);
                if true {
                    match (&_old, &None) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    };
                };
            }
            let item = f(self);
            match (&owner_id, &item.def_id()) {
                (left_val, right_val) => {
                    if !(*left_val == *right_val) {
                        let kind = ::core::panicking::AssertKind::Eq;
                        ::core::panicking::assert_failed(kind, &*left_val,
                            &*right_val, ::core::option::Option::None);
                    }
                }
            };
            if !self.impl_trait_defs.is_empty() {
                ::core::panicking::panic("assertion failed: self.impl_trait_defs.is_empty()")
            };
            if !self.impl_trait_bounds.is_empty() {
                ::core::panicking::panic("assertion failed: self.impl_trait_bounds.is_empty()")
            };
            let info = self.make_owner_info(item);
            self.current_disambiguator = disambiguator;
            self.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))]
777    fn with_hir_id_owner(
778        &mut self,
779        owner: NodeId,
780        f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
781    ) {
782        let owner_id = self.owner_id(owner);
783        let def_id = owner_id.def_id;
784
785        let new_disambig = match &mut self.disambiguators {
786            Disambiguators::Default(map) => map.remove(&def_id),
787            Disambiguators::Delayed(map) => map.get(&def_id).map(Steal::steal),
788        };
789
790        let new_disambig = new_disambig.unwrap_or_else(|| PerParentDisambiguatorState::new(def_id));
791
792        let disambiguator = std::mem::replace(&mut self.current_disambiguator, new_disambig);
793        let current_attrs = std::mem::take(&mut self.attrs);
794        let current_bodies = std::mem::take(&mut self.bodies);
795        let current_define_opaque = std::mem::take(&mut self.define_opaque);
796        let current_ident_and_label_to_local_id =
797            std::mem::take(&mut self.ident_and_label_to_local_id);
798
799        #[cfg(debug_assertions)]
800        let current_node_id_to_local_id = std::mem::take(&mut self.node_id_to_local_id);
801        let current_trait_map = std::mem::take(&mut self.trait_map);
802        let current_owner = std::mem::replace(&mut self.current_hir_id_owner, owner_id);
803        let current_local_counter =
804            std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
805        let current_impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
806        let current_impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
807        let current_delayed_lints = std::mem::take(&mut self.delayed_lints);
808
809        // Do not reset `next_node_id` and `node_id_to_def_id`:
810        // we want `f` to be able to refer to the `LocalDefId`s that the caller created.
811        // and the caller to refer to some of the subdefinitions' nodes' `LocalDefId`s.
812
813        // Always allocate the first `HirId` for the owner itself.
814        #[cfg(debug_assertions)]
815        {
816            let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::ZERO);
817            debug_assert_eq!(_old, None);
818        }
819
820        let item = f(self);
821        assert_eq!(owner_id, item.def_id());
822        // `f` should have consumed all the elements in these vectors when constructing `item`.
823        assert!(self.impl_trait_defs.is_empty());
824        assert!(self.impl_trait_bounds.is_empty());
825        let info = self.make_owner_info(item);
826
827        self.current_disambiguator = disambiguator;
828        self.attrs = current_attrs;
829        self.bodies = current_bodies;
830        self.define_opaque = current_define_opaque;
831        self.ident_and_label_to_local_id = current_ident_and_label_to_local_id;
832
833        #[cfg(debug_assertions)]
834        {
835            self.node_id_to_local_id = current_node_id_to_local_id;
836        }
837        self.trait_map = current_trait_map;
838        self.current_hir_id_owner = current_owner;
839        self.item_local_id_counter = current_local_counter;
840        self.impl_trait_defs = current_impl_trait_defs;
841        self.impl_trait_bounds = current_impl_trait_bounds;
842        self.delayed_lints = current_delayed_lints;
843
844        debug_assert!(!self.children.iter().any(|(id, _)| id == &owner_id.def_id));
845        self.children.push((owner_id.def_id, hir::MaybeOwner::Owner(info)));
846    }
847
848    fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> &'hir hir::OwnerInfo<'hir> {
849        let attrs = std::mem::take(&mut self.attrs);
850        let mut bodies = std::mem::take(&mut self.bodies);
851        let define_opaque = std::mem::take(&mut self.define_opaque);
852        let trait_map = std::mem::take(&mut self.trait_map);
853        let delayed_lints = std::mem::take(&mut self.delayed_lints).into_boxed_slice();
854
855        #[cfg(debug_assertions)]
856        for (id, attrs) in attrs.iter() {
857            // Verify that we do not store empty slices in the map.
858            if attrs.is_empty() {
859                {
    ::core::panicking::panic_fmt(format_args!("Stored empty attributes for {0:?}",
            id));
};panic!("Stored empty attributes for {:?}", id);
860            }
861        }
862
863        bodies.sort_by_key(|(k, _)| *k);
864        let bodies = SortedMap::from_presorted_elements(bodies);
865
866        // Don't hash unless necessary, because it's expensive.
867        let rustc_middle::hir::Hashes { opt_hash_including_bodies, attrs_hash } =
868            self.tcx.hash_owner_nodes(node, &bodies, &attrs, define_opaque);
869        let num_nodes = self.item_local_id_counter.as_usize();
870        let (nodes, parenting) = index::index_hir(self.tcx, node, &bodies, num_nodes);
871        let nodes = hir::OwnerNodes { opt_hash_including_bodies, nodes, bodies };
872        let attrs = hir::AttributeMap { map: attrs, opt_hash: attrs_hash, define_opaque };
873
874        self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map, delayed_lints })
875    }
876
877    /// This method allocates a new `HirId` for the given `NodeId`.
878    /// Take care not to call this method if the resulting `HirId` is then not
879    /// actually used in the HIR, as that would trigger an assertion in the
880    /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
881    /// properly. Calling the method twice with the same `NodeId` is also forbidden.
882    x;#[instrument(level = "debug", skip(self), ret)]
883    fn lower_node_id(&mut self, ast_node_id: NodeId) -> HirId {
884        assert_ne!(ast_node_id, DUMMY_NODE_ID);
885
886        let owner = self.current_hir_id_owner;
887        let local_id = self.item_local_id_counter;
888        assert_ne!(local_id, hir::ItemLocalId::ZERO);
889        self.item_local_id_counter.increment_by(1);
890        let hir_id = HirId { owner, local_id };
891
892        if let Some(def_id) = self.opt_local_def_id(ast_node_id) {
893            self.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id)));
894        }
895
896        if let Some(traits) = self.resolver.trait_candidates(ast_node_id) {
897            self.trait_map.insert(hir_id.local_id, traits);
898        }
899
900        // Check whether the same `NodeId` is lowered more than once.
901        #[cfg(debug_assertions)]
902        {
903            let old = self.node_id_to_local_id.insert(ast_node_id, local_id);
904            assert_eq!(old, None);
905        }
906
907        hir_id
908    }
909
910    /// Generate a new `HirId` without a backing `NodeId`.
911    x;#[instrument(level = "debug", skip(self), ret)]
912    fn next_id(&mut self) -> HirId {
913        let owner = self.current_hir_id_owner;
914        let local_id = self.item_local_id_counter;
915        assert_ne!(local_id, hir::ItemLocalId::ZERO);
916        self.item_local_id_counter.increment_by(1);
917        HirId { owner, local_id }
918    }
919
920    #[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(920u32),
                                    ::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:927",
                                    "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(927u32),
                                    ::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))]
921    fn lower_res(&mut self, res: Res<NodeId>) -> Res {
922        let res: Result<Res, ()> = res.apply_id(|id| {
923            let owner = self.current_hir_id_owner;
924            let local_id = self.ident_and_label_to_local_id.get(&id).copied().ok_or(())?;
925            Ok(HirId { owner, local_id })
926        });
927        trace!(?res);
928
929        // We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
930        // This can happen when trying to lower the return type `x` in erroneous code like
931        //   async fn foo(x: u8) -> x {}
932        // In that case, `x` is lowered as a function parameter, and the return type is lowered as
933        // an opaque type as a synthesized HIR owner.
934        res.unwrap_or(Res::Err)
935    }
936
937    fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
938        self.resolver.get_partial_res(id).map_or(Res::Err, |pr| pr.expect_full_res())
939    }
940
941    fn lower_import_res(&mut self, id: NodeId, span: Span) -> PerNS<Option<Res>> {
942        let per_ns = self.resolver.get_import_res(id);
943        let per_ns = per_ns.map(|res| res.map(|res| self.lower_res(res)));
944        if per_ns.is_empty() {
945            // Propagate the error to all namespaces, just to be sure.
946            self.dcx().span_delayed_bug(span, "no resolution for an import");
947            let err = Some(Res::Err);
948            return PerNS { type_ns: err, value_ns: err, macro_ns: err };
949        }
950        per_ns
951    }
952
953    fn make_lang_item_qpath(
954        &mut self,
955        lang_item: hir::LangItem,
956        span: Span,
957        args: Option<&'hir hir::GenericArgs<'hir>>,
958    ) -> hir::QPath<'hir> {
959        hir::QPath::Resolved(None, self.make_lang_item_path(lang_item, span, args))
960    }
961
962    fn make_lang_item_path(
963        &mut self,
964        lang_item: hir::LangItem,
965        span: Span,
966        args: Option<&'hir hir::GenericArgs<'hir>>,
967    ) -> &'hir hir::Path<'hir> {
968        let def_id = self.tcx.require_lang_item(lang_item, span);
969        let def_kind = self.tcx.def_kind(def_id);
970        let res = Res::Def(def_kind, def_id);
971        self.arena.alloc(hir::Path {
972            span,
973            res,
974            segments: self.arena.alloc_from_iter([hir::PathSegment {
975                ident: Ident::new(lang_item.name(), span),
976                hir_id: self.next_id(),
977                res,
978                args,
979                infer_args: args.is_none(),
980            }]),
981        })
982    }
983
984    /// Reuses the span but adds information like the kind of the desugaring and features that are
985    /// allowed inside this span.
986    fn mark_span_with_reason(
987        &self,
988        reason: DesugaringKind,
989        span: Span,
990        allow_internal_unstable: Option<Arc<[Symbol]>>,
991    ) -> Span {
992        self.tcx.with_stable_hashing_context(|hcx| {
993            span.mark_with_reason(allow_internal_unstable, reason, span.edition(), hcx)
994        })
995    }
996
997    fn span_lowerer(&self) -> SpanLowerer {
998        SpanLowerer {
999            is_incremental: self.tcx.sess.opts.incremental.is_some(),
1000            def_id: self.current_hir_id_owner.def_id,
1001        }
1002    }
1003
1004    /// Intercept all spans entering HIR.
1005    /// Mark a span as relative to the current owning item.
1006    fn lower_span(&self, span: Span) -> Span {
1007        self.span_lowerer().lower(span)
1008    }
1009
1010    fn lower_ident(&self, ident: Ident) -> Ident {
1011        Ident::new(ident.name, self.lower_span(ident.span))
1012    }
1013
1014    /// Converts a lifetime into a new generic parameter.
1015    #[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(1015u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["ident", "node_id",
                                                    "res", "source"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'hir hir::FnDecl<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let c_variadic = decl.c_variadic();
            let mut inputs = &decl.inputs[..];
            if decl.c_variadic() { inputs = &inputs[..inputs.len() - 1]; }
            let inputs =
                self.arena.alloc_from_iter(inputs.iter().map(|param|
                            {
                                let itctx =
                                    match kind {
                                        FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl |
                                            FnDeclKind::Trait => {
                                            ImplTraitContext::Universal
                                        }
                                        FnDeclKind::ExternFn => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnParam)
                                        }
                                        FnDeclKind::Closure => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureParam)
                                        }
                                        FnDeclKind::Pointer => {
                                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerParam)
                                        }
                                    };
                                self.lower_ty(&param.ty, itctx)
                            }));
            let output =
                match coro {
                    Some(coro) => {
                        let fn_def_id = self.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)),
                        },
                };
            let fn_decl_kind =
                hir::FnDeclFlags::default().set_implicit_self(decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None,
                                |arg|
                                    {
                                        let is_mutable_pat =
                                            #[allow(non_exhaustive_omitted_patterns)] match arg.pat.kind
                                                {
                                                PatKind::Ident(hir::BindingMode(_, Mutability::Mut), ..) =>
                                                    true,
                                                _ => false,
                                            };
                                        match &arg.ty.kind {
                                            TyKind::ImplicitSelf if is_mutable_pat =>
                                                hir::ImplicitSelfKind::Mut,
                                            TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
                                            TyKind::Ref(_, mt) | TyKind::PinnedRef(_, mt) if
                                                mt.ty.kind.is_implicit_self() => {
                                                match mt.mutbl {
                                                    hir::Mutability::Not => hir::ImplicitSelfKind::RefImm,
                                                    hir::Mutability::Mut => hir::ImplicitSelfKind::RefMut,
                                                }
                                            }
                                            _ => hir::ImplicitSelfKind::None,
                                        }
                                    })).set_lifetime_elision_allowed(self.resolver.lifetime_elision_allowed(fn_node_id)).set_c_variadic(c_variadic);
            self.arena.alloc(hir::FnDecl { inputs, output, fn_decl_kind })
        }
    }
}#[instrument(level = "debug", skip(self))]
1845    fn lower_fn_decl(
1846        &mut self,
1847        decl: &FnDecl,
1848        fn_node_id: NodeId,
1849        fn_span: Span,
1850        kind: FnDeclKind,
1851        coro: Option<CoroutineKind>,
1852    ) -> &'hir hir::FnDecl<'hir> {
1853        let c_variadic = decl.c_variadic();
1854
1855        // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1856        // as they are not explicit in HIR/Ty function signatures.
1857        // (instead, the `c_variadic` flag is set to `true`)
1858        let mut inputs = &decl.inputs[..];
1859        if decl.c_variadic() {
1860            inputs = &inputs[..inputs.len() - 1];
1861        }
1862        let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1863            let itctx = match kind {
1864                FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait => {
1865                    ImplTraitContext::Universal
1866                }
1867                FnDeclKind::ExternFn => {
1868                    ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnParam)
1869                }
1870                FnDeclKind::Closure => {
1871                    ImplTraitContext::Disallowed(ImplTraitPosition::ClosureParam)
1872                }
1873                FnDeclKind::Pointer => {
1874                    ImplTraitContext::Disallowed(ImplTraitPosition::PointerParam)
1875                }
1876            };
1877            self.lower_ty(&param.ty, itctx)
1878        }));
1879
1880        let output = match coro {
1881            Some(coro) => {
1882                let fn_def_id = self.local_def_id(fn_node_id);
1883                self.lower_coroutine_fn_ret_ty(&decl.output, fn_def_id, coro, kind)
1884            }
1885            None => match &decl.output {
1886                FnRetTy::Ty(ty) => {
1887                    let itctx = match kind {
1888                        FnDeclKind::Fn | FnDeclKind::Inherent => ImplTraitContext::OpaqueTy {
1889                            origin: hir::OpaqueTyOrigin::FnReturn {
1890                                parent: self.local_def_id(fn_node_id),
1891                                in_trait_or_impl: None,
1892                            },
1893                        },
1894                        FnDeclKind::Trait => ImplTraitContext::OpaqueTy {
1895                            origin: hir::OpaqueTyOrigin::FnReturn {
1896                                parent: self.local_def_id(fn_node_id),
1897                                in_trait_or_impl: Some(hir::RpitContext::Trait),
1898                            },
1899                        },
1900                        FnDeclKind::Impl => ImplTraitContext::OpaqueTy {
1901                            origin: hir::OpaqueTyOrigin::FnReturn {
1902                                parent: self.local_def_id(fn_node_id),
1903                                in_trait_or_impl: Some(hir::RpitContext::TraitImpl),
1904                            },
1905                        },
1906                        FnDeclKind::ExternFn => {
1907                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnReturn)
1908                        }
1909                        FnDeclKind::Closure => {
1910                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureReturn)
1911                        }
1912                        FnDeclKind::Pointer => {
1913                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerReturn)
1914                        }
1915                    };
1916                    hir::FnRetTy::Return(self.lower_ty_alloc(ty, itctx))
1917                }
1918                FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(*span)),
1919            },
1920        };
1921
1922        let fn_decl_kind = hir::FnDeclFlags::default()
1923            .set_implicit_self(decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1924                let is_mutable_pat = matches!(
1925                    arg.pat.kind,
1926                    PatKind::Ident(hir::BindingMode(_, Mutability::Mut), ..)
1927                );
1928
1929                match &arg.ty.kind {
1930                    TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1931                    TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1932                    // Given we are only considering `ImplicitSelf` types, we needn't consider
1933                    // the case where we have a mutable pattern to a reference as that would
1934                    // no longer be an `ImplicitSelf`.
1935                    TyKind::Ref(_, mt) | TyKind::PinnedRef(_, mt)
1936                        if mt.ty.kind.is_implicit_self() =>
1937                    {
1938                        match mt.mutbl {
1939                            hir::Mutability::Not => hir::ImplicitSelfKind::RefImm,
1940                            hir::Mutability::Mut => hir::ImplicitSelfKind::RefMut,
1941                        }
1942                    }
1943                    _ => hir::ImplicitSelfKind::None,
1944                }
1945            }))
1946            .set_lifetime_elision_allowed(self.resolver.lifetime_elision_allowed(fn_node_id))
1947            .set_c_variadic(c_variadic);
1948
1949        self.arena.alloc(hir::FnDecl { inputs, output, fn_decl_kind })
1950    }
1951
1952    // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1953    // combined with the following definition of `OpaqueTy`:
1954    //
1955    //     type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1956    //
1957    // `output`: unlowered output type (`T` in `-> T`)
1958    // `fn_node_id`: `NodeId` of the parent function (used to create child impl trait definition)
1959    // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1960    #[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(1960u32),
                                    ::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))]
1961    fn lower_coroutine_fn_ret_ty(
1962        &mut self,
1963        output: &FnRetTy,
1964        fn_def_id: LocalDefId,
1965        coro: CoroutineKind,
1966        fn_kind: FnDeclKind,
1967    ) -> hir::FnRetTy<'hir> {
1968        let span = self.lower_span(output.span());
1969
1970        let (opaque_ty_node_id, allowed_features) = match coro {
1971            CoroutineKind::Async { return_impl_trait_id, .. } => (return_impl_trait_id, None),
1972            CoroutineKind::Gen { return_impl_trait_id, .. } => (return_impl_trait_id, None),
1973            CoroutineKind::AsyncGen { return_impl_trait_id, .. } => {
1974                (return_impl_trait_id, Some(Arc::clone(&self.allow_async_iterator)))
1975            }
1976        };
1977
1978        let opaque_ty_span =
1979            self.mark_span_with_reason(DesugaringKind::Async, span, allowed_features);
1980
1981        let in_trait_or_impl = match fn_kind {
1982            FnDeclKind::Trait => Some(hir::RpitContext::Trait),
1983            FnDeclKind::Impl => Some(hir::RpitContext::TraitImpl),
1984            FnDeclKind::Fn | FnDeclKind::Inherent => None,
1985            FnDeclKind::ExternFn | FnDeclKind::Closure | FnDeclKind::Pointer => unreachable!(),
1986        };
1987
1988        let opaque_ty_ref = self.lower_opaque_inner(
1989            opaque_ty_node_id,
1990            hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, in_trait_or_impl },
1991            opaque_ty_span,
1992            |this| {
1993                let bound = this.lower_coroutine_fn_output_type_to_bound(
1994                    output,
1995                    coro,
1996                    opaque_ty_span,
1997                    ImplTraitContext::OpaqueTy {
1998                        origin: hir::OpaqueTyOrigin::FnReturn {
1999                            parent: fn_def_id,
2000                            in_trait_or_impl,
2001                        },
2002                    },
2003                );
2004                arena_vec![this; bound]
2005            },
2006        );
2007
2008        let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2009        hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
2010    }
2011
2012    /// Transforms `-> T` into `Future<Output = T>`.
2013    fn lower_coroutine_fn_output_type_to_bound(
2014        &mut self,
2015        output: &FnRetTy,
2016        coro: CoroutineKind,
2017        opaque_ty_span: Span,
2018        itctx: ImplTraitContext,
2019    ) -> hir::GenericBound<'hir> {
2020        // Compute the `T` in `Future<Output = T>` from the return type.
2021        let output_ty = match output {
2022            FnRetTy::Ty(ty) => {
2023                // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
2024                // `impl Future` opaque type that `async fn` implicitly
2025                // generates.
2026                self.lower_ty_alloc(ty, itctx)
2027            }
2028            FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
2029        };
2030
2031        // "<$assoc_ty_name = T>"
2032        let (assoc_ty_name, trait_lang_item) = match coro {
2033            CoroutineKind::Async { .. } => (sym::Output, hir::LangItem::Future),
2034            CoroutineKind::Gen { .. } => (sym::Item, hir::LangItem::Iterator),
2035            CoroutineKind::AsyncGen { .. } => (sym::Item, hir::LangItem::AsyncIterator),
2036        };
2037
2038        let bound_args = self.arena.alloc(hir::GenericArgs {
2039            args: &[],
2040            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)],
2041            parenthesized: hir::GenericArgsParentheses::No,
2042            span_ext: DUMMY_SP,
2043        });
2044
2045        hir::GenericBound::Trait(hir::PolyTraitRef {
2046            bound_generic_params: &[],
2047            modifiers: hir::TraitBoundModifiers::NONE,
2048            trait_ref: hir::TraitRef {
2049                path: self.make_lang_item_path(trait_lang_item, opaque_ty_span, Some(bound_args)),
2050                hir_ref_id: self.next_id(),
2051            },
2052            span: opaque_ty_span,
2053        })
2054    }
2055
2056    #[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(2056u32),
                                    ::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))]
2057    fn lower_param_bound(
2058        &mut self,
2059        tpb: &GenericBound,
2060        rbp: RelaxedBoundPolicy<'_>,
2061        itctx: ImplTraitContext,
2062    ) -> hir::GenericBound<'hir> {
2063        match tpb {
2064            GenericBound::Trait(p) => {
2065                hir::GenericBound::Trait(self.lower_poly_trait_ref(p, rbp, itctx))
2066            }
2067            GenericBound::Outlives(lifetime) => hir::GenericBound::Outlives(self.lower_lifetime(
2068                lifetime,
2069                LifetimeSource::OutlivesBound,
2070                lifetime.ident.into(),
2071            )),
2072            GenericBound::Use(args, span) => hir::GenericBound::Use(
2073                self.lower_precise_capturing_args(args),
2074                self.lower_span(*span),
2075            ),
2076        }
2077    }
2078
2079    fn lower_lifetime(
2080        &mut self,
2081        l: &Lifetime,
2082        source: LifetimeSource,
2083        syntax: LifetimeSyntax,
2084    ) -> &'hir hir::Lifetime {
2085        self.new_named_lifetime(l.id, l.id, l.ident, source, syntax)
2086    }
2087
2088    fn lower_lifetime_hidden_in_path(
2089        &mut self,
2090        id: NodeId,
2091        span: Span,
2092        angle_brackets: AngleBrackets,
2093    ) -> &'hir hir::Lifetime {
2094        self.new_named_lifetime(
2095            id,
2096            id,
2097            Ident::new(kw::UnderscoreLifetime, span),
2098            LifetimeSource::Path { angle_brackets },
2099            LifetimeSyntax::Implicit,
2100        )
2101    }
2102
2103    #[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(2103u32),
                                    ::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:2137",
                                    "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(2137u32),
                                    ::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))]
2104    fn new_named_lifetime(
2105        &mut self,
2106        id: NodeId,
2107        new_id: NodeId,
2108        ident: Ident,
2109        source: LifetimeSource,
2110        syntax: LifetimeSyntax,
2111    ) -> &'hir hir::Lifetime {
2112        let res = if let Some(res) = self.resolver.get_lifetime_res(id) {
2113            match res {
2114                LifetimeRes::Param { param, .. } => hir::LifetimeKind::Param(param),
2115                LifetimeRes::Fresh { param, .. } => {
2116                    assert_eq!(ident.name, kw::UnderscoreLifetime);
2117                    let param = self.local_def_id(param);
2118                    hir::LifetimeKind::Param(param)
2119                }
2120                LifetimeRes::Infer => {
2121                    assert_eq!(ident.name, kw::UnderscoreLifetime);
2122                    hir::LifetimeKind::Infer
2123                }
2124                LifetimeRes::Static { .. } => {
2125                    assert!(matches!(ident.name, kw::StaticLifetime | kw::UnderscoreLifetime));
2126                    hir::LifetimeKind::Static
2127                }
2128                LifetimeRes::Error(guar) => hir::LifetimeKind::Error(guar),
2129                LifetimeRes::ElidedAnchor { .. } => {
2130                    panic!("Unexpected `ElidedAnchar` {:?} at {:?}", ident, ident.span);
2131                }
2132            }
2133        } else {
2134            hir::LifetimeKind::Error(self.dcx().span_delayed_bug(ident.span, "unresolved lifetime"))
2135        };
2136
2137        debug!(?res);
2138        self.arena.alloc(hir::Lifetime::new(
2139            self.lower_node_id(new_id),
2140            self.lower_ident(ident),
2141            res,
2142            source,
2143            syntax,
2144        ))
2145    }
2146
2147    fn lower_generic_params_mut(
2148        &mut self,
2149        params: &[GenericParam],
2150        source: hir::GenericParamSource,
2151    ) -> impl Iterator<Item = hir::GenericParam<'hir>> {
2152        params.iter().map(move |param| self.lower_generic_param(param, source))
2153    }
2154
2155    fn lower_generic_params(
2156        &mut self,
2157        params: &[GenericParam],
2158        source: hir::GenericParamSource,
2159    ) -> &'hir [hir::GenericParam<'hir>] {
2160        self.arena.alloc_from_iter(self.lower_generic_params_mut(params, source))
2161    }
2162
2163    #[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(2163u32),
                                    ::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))]
2164    fn lower_generic_param(
2165        &mut self,
2166        param: &GenericParam,
2167        source: hir::GenericParamSource,
2168    ) -> hir::GenericParam<'hir> {
2169        let (name, kind) = self.lower_generic_param_kind(param, source);
2170
2171        let hir_id = self.lower_node_id(param.id);
2172        let param_attrs = &param.attrs;
2173        let param_span = param.span();
2174        let param = hir::GenericParam {
2175            hir_id,
2176            def_id: self.local_def_id(param.id),
2177            name,
2178            span: self.lower_span(param.span()),
2179            pure_wrt_drop: attr::contains_name(&param.attrs, sym::may_dangle),
2180            kind,
2181            colon_span: param.colon_span.map(|s| self.lower_span(s)),
2182            source,
2183        };
2184        self.lower_attrs(hir_id, param_attrs, param_span, Target::from_generic_param(&param));
2185        param
2186    }
2187
2188    fn lower_generic_param_kind(
2189        &mut self,
2190        param: &GenericParam,
2191        source: hir::GenericParamSource,
2192    ) -> (hir::ParamName, hir::GenericParamKind<'hir>) {
2193        match &param.kind {
2194            GenericParamKind::Lifetime => {
2195                // AST resolution emitted an error on those parameters, so we lower them using
2196                // `ParamName::Error`.
2197                let ident = self.lower_ident(param.ident);
2198                let param_name = if let Some(LifetimeRes::Error(..)) =
2199                    self.resolver.get_lifetime_res(param.id)
2200                {
2201                    ParamName::Error(ident)
2202                } else {
2203                    ParamName::Plain(ident)
2204                };
2205                let kind =
2206                    hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2207
2208                (param_name, kind)
2209            }
2210            GenericParamKind::Type { default, .. } => {
2211                // Not only do we deny type param defaults in binders but we also map them to `None`
2212                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2213                let default = default
2214                    .as_ref()
2215                    .filter(|_| match source {
2216                        hir::GenericParamSource::Generics => true,
2217                        hir::GenericParamSource::Binder => {
2218                            self.dcx().emit_err(errors::GenericParamDefaultInBinder {
2219                                span: param.span(),
2220                            });
2221
2222                            false
2223                        }
2224                    })
2225                    .map(|def| {
2226                        self.lower_ty_alloc(
2227                            def,
2228                            ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2229                        )
2230                    });
2231
2232                let kind = hir::GenericParamKind::Type { default, synthetic: false };
2233
2234                (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2235            }
2236            GenericParamKind::Const { ty, span: _, default } => {
2237                let ty = self.lower_ty_alloc(
2238                    ty,
2239                    ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2240                );
2241
2242                // Not only do we deny const param defaults in binders but we also map them to `None`
2243                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2244                let default = default
2245                    .as_ref()
2246                    .filter(|anon_const| match source {
2247                        hir::GenericParamSource::Generics => true,
2248                        hir::GenericParamSource::Binder => {
2249                            let err = errors::GenericParamDefaultInBinder { span: param.span() };
2250                            if expr::WillCreateDefIdsVisitor
2251                                .visit_expr(&anon_const.value)
2252                                .is_break()
2253                            {
2254                                // FIXME(mgca): make this non-fatal once we have a better way
2255                                // to handle nested items in anno const from binder
2256                                // Issue: https://github.com/rust-lang/rust/issues/123629
2257                                self.dcx().emit_fatal(err)
2258                            } else {
2259                                self.dcx().emit_err(err);
2260                                false
2261                            }
2262                        }
2263                    })
2264                    .map(|def| self.lower_anon_const_to_const_arg_and_alloc(def));
2265
2266                (
2267                    hir::ParamName::Plain(self.lower_ident(param.ident)),
2268                    hir::GenericParamKind::Const { ty, default },
2269                )
2270            }
2271        }
2272    }
2273
2274    fn lower_trait_ref(
2275        &mut self,
2276        modifiers: ast::TraitBoundModifiers,
2277        p: &TraitRef,
2278        itctx: ImplTraitContext,
2279    ) -> hir::TraitRef<'hir> {
2280        let path = match self.lower_qpath(
2281            p.ref_id,
2282            &None,
2283            &p.path,
2284            ParamMode::Explicit,
2285            AllowReturnTypeNotation::No,
2286            itctx,
2287            Some(modifiers),
2288        ) {
2289            hir::QPath::Resolved(None, path) => path,
2290            qpath => {
    ::core::panicking::panic_fmt(format_args!("lower_trait_ref: unexpected QPath `{0:?}`",
            qpath));
}panic!("lower_trait_ref: unexpected QPath `{qpath:?}`"),
2291        };
2292        hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2293    }
2294
2295    #[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(2295u32),
                                    ::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))]
2296    fn lower_poly_trait_ref(
2297        &mut self,
2298        PolyTraitRef { bound_generic_params, modifiers, trait_ref, span, parens: _ }: &PolyTraitRef,
2299        rbp: RelaxedBoundPolicy<'_>,
2300        itctx: ImplTraitContext,
2301    ) -> hir::PolyTraitRef<'hir> {
2302        let bound_generic_params =
2303            self.lower_lifetime_binder(trait_ref.ref_id, bound_generic_params);
2304        let trait_ref = self.lower_trait_ref(*modifiers, trait_ref, itctx);
2305        let modifiers = self.lower_trait_bound_modifiers(*modifiers);
2306
2307        if let ast::BoundPolarity::Maybe(_) = modifiers.polarity {
2308            self.validate_relaxed_bound(trait_ref, *span, rbp);
2309        }
2310
2311        hir::PolyTraitRef {
2312            bound_generic_params,
2313            modifiers,
2314            trait_ref,
2315            span: self.lower_span(*span),
2316        }
2317    }
2318
2319    fn validate_relaxed_bound(
2320        &self,
2321        trait_ref: hir::TraitRef<'_>,
2322        span: Span,
2323        rbp: RelaxedBoundPolicy<'_>,
2324    ) {
2325        // Even though feature `more_maybe_bounds` enables the user to relax all default bounds
2326        // other than `Sized` in a lot more positions (thereby bypassing the given policy), we don't
2327        // want to advertise it to the user (via a feature gate error) since it's super internal.
2328        //
2329        // FIXME(more_maybe_bounds): Moreover, if we actually were to add proper default traits
2330        // (like a hypothetical `Move` or `Leak`) we would want to validate the location according
2331        // to default trait elaboration in HIR ty lowering (which depends on the specific trait in
2332        // question: E.g., `?Sized` & `?Move` most likely won't be allowed in all the same places).
2333
2334        match rbp {
2335            RelaxedBoundPolicy::Allowed => return,
2336            RelaxedBoundPolicy::AllowedIfOnTyParam(id, params) => {
2337                if let Some(res) = self.resolver.get_partial_res(id).and_then(|r| r.full_res())
2338                    && let Res::Def(DefKind::TyParam, def_id) = res
2339                    && params.iter().any(|p| def_id == self.local_def_id(p.id).to_def_id())
2340                {
2341                    return;
2342                }
2343            }
2344            RelaxedBoundPolicy::Forbidden(reason) => {
2345                let gate = |context, subject| {
2346                    let extended = self.tcx.features().more_maybe_bounds();
2347                    let is_sized = trait_ref
2348                        .trait_def_id()
2349                        .is_some_and(|def_id| self.tcx.is_lang_item(def_id, hir::LangItem::Sized));
2350
2351                    if extended && !is_sized {
2352                        return;
2353                    }
2354
2355                    let prefix = if extended { "`Sized` " } else { "" };
2356                    let mut diag = self.dcx().struct_span_err(
2357                        span,
2358                        ::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}"),
2359                    );
2360                    if is_sized {
2361                        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!(
2362                            "{subject} are not implicitly bounded by `Sized`, \
2363                             so there is nothing to relax"
2364                        ));
2365                    }
2366                    diag.emit();
2367                };
2368
2369                match reason {
2370                    RelaxedBoundForbiddenReason::TraitObjectTy => {
2371                        gate("trait object types", "trait object types");
2372                        return;
2373                    }
2374                    RelaxedBoundForbiddenReason::SuperTrait => {
2375                        gate("supertrait bounds", "traits");
2376                        return;
2377                    }
2378                    RelaxedBoundForbiddenReason::TraitAlias => {
2379                        gate("trait alias bounds", "trait aliases");
2380                        return;
2381                    }
2382                    RelaxedBoundForbiddenReason::AssocTyBounds
2383                    | RelaxedBoundForbiddenReason::LateBoundVarsInScope => {}
2384                };
2385            }
2386        }
2387
2388        self.dcx()
2389            .struct_span_err(span, "this relaxed bound is not permitted here")
2390            .with_note(
2391                "in this context, relaxed bounds are only allowed on \
2392                 type parameters defined on the closest item",
2393            )
2394            .emit();
2395    }
2396
2397    fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy<'hir> {
2398        hir::MutTy { ty: self.lower_ty_alloc(&mt.ty, itctx), mutbl: mt.mutbl }
2399    }
2400
2401    x;#[instrument(level = "debug", skip(self), ret)]
2402    fn lower_param_bounds(
2403        &mut self,
2404        bounds: &[GenericBound],
2405        rbp: RelaxedBoundPolicy<'_>,
2406        itctx: ImplTraitContext,
2407    ) -> hir::GenericBounds<'hir> {
2408        self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, rbp, itctx))
2409    }
2410
2411    fn lower_param_bounds_mut(
2412        &mut self,
2413        bounds: &[GenericBound],
2414        rbp: RelaxedBoundPolicy<'_>,
2415        itctx: ImplTraitContext,
2416    ) -> impl Iterator<Item = hir::GenericBound<'hir>> {
2417        bounds.iter().map(move |bound| self.lower_param_bound(bound, rbp, itctx))
2418    }
2419
2420    x;#[instrument(level = "debug", skip(self), ret)]
2421    fn lower_universal_param_and_bounds(
2422        &mut self,
2423        node_id: NodeId,
2424        span: Span,
2425        ident: Ident,
2426        bounds: &[GenericBound],
2427    ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2428        // Add a definition for the in-band `Param`.
2429        let def_id = self.local_def_id(node_id);
2430        let span = self.lower_span(span);
2431
2432        // Set the name to `impl Bound1 + Bound2`.
2433        let param = hir::GenericParam {
2434            hir_id: self.lower_node_id(node_id),
2435            def_id,
2436            name: ParamName::Plain(self.lower_ident(ident)),
2437            pure_wrt_drop: false,
2438            span,
2439            kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2440            colon_span: None,
2441            source: hir::GenericParamSource::Generics,
2442        };
2443
2444        let preds = self.lower_generic_bound_predicate(
2445            ident,
2446            node_id,
2447            &GenericParamKind::Type { default: None },
2448            bounds,
2449            /* colon_span */ None,
2450            span,
2451            RelaxedBoundPolicy::Allowed,
2452            ImplTraitContext::Universal,
2453            hir::PredicateOrigin::ImplTrait,
2454        );
2455
2456        let hir_id = self.next_id();
2457        let res = Res::Def(DefKind::TyParam, def_id.to_def_id());
2458        let ty = hir::TyKind::Path(hir::QPath::Resolved(
2459            None,
2460            self.arena.alloc(hir::Path {
2461                span,
2462                res,
2463                segments:
2464                    arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2465            }),
2466        ));
2467
2468        (param, preds, ty)
2469    }
2470
2471    /// Lowers a block directly to an expression, presuming that it
2472    /// has no attributes and is not targeted by a `break`.
2473    fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2474        let block = self.lower_block(b, false);
2475        self.expr_block(block)
2476    }
2477
2478    fn lower_array_length_to_const_arg(&mut self, c: &AnonConst) -> &'hir hir::ConstArg<'hir> {
2479        // We cannot just match on `ExprKind::Underscore` as `(_)` is represented as
2480        // `ExprKind::Paren(ExprKind::Underscore)` and should also be lowered to `GenericArg::Infer`
2481        match c.value.peel_parens().kind {
2482            ExprKind::Underscore => {
2483                let ct_kind = hir::ConstArgKind::Infer(());
2484                self.arena.alloc(hir::ConstArg {
2485                    hir_id: self.lower_node_id(c.id),
2486                    kind: ct_kind,
2487                    span: self.lower_span(c.value.span),
2488                })
2489            }
2490            _ => self.lower_anon_const_to_const_arg_and_alloc(c),
2491        }
2492    }
2493
2494    /// Used when lowering a type argument that turned out to actually be a const argument.
2495    ///
2496    /// Only use for that purpose since otherwise it will create a duplicate def.
2497    #[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(2497u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["path", "res",
                                                    "ty_id", "span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'hir hir::ConstArg<'hir> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            let is_trivial_path =
                path.is_potential_trivial_const_arg() &&
                    #[allow(non_exhaustive_omitted_patterns)] match res {
                        Res::Def(DefKind::ConstParam, _) => true,
                        _ => false,
                    };
            let ct_kind =
                if is_trivial_path || tcx.features().min_generic_const_args()
                    {
                    let qpath =
                        self.lower_qpath(ty_id, &None, path, ParamMode::Explicit,
                            AllowReturnTypeNotation::No,
                            ImplTraitContext::Disallowed(ImplTraitPosition::Path),
                            None);
                    hir::ConstArgKind::Path(qpath)
                } else {
                    let node_id = self.next_node_id();
                    let span = self.lower_span(span);
                    let def_id =
                        self.create_def(node_id, None, DefKind::AnonConst, span);
                    let hir_id = self.lower_node_id(node_id);
                    let path_expr =
                        Expr {
                            id: ty_id,
                            kind: ExprKind::Path(None, path.clone()),
                            span,
                            attrs: AttrVec::new(),
                            tokens: None,
                        };
                    let ct =
                        self.with_new_scopes(span,
                            |this|
                                {
                                    self.arena.alloc(hir::AnonConst {
                                            def_id,
                                            hir_id,
                                            body: this.lower_const_body(path_expr.span,
                                                Some(&path_expr)),
                                            span,
                                        })
                                });
                    hir::ConstArgKind::Anon(ct)
                };
            self.arena.alloc(hir::ConstArg {
                    hir_id: self.next_id(),
                    kind: ct_kind,
                    span: self.lower_span(span),
                })
        }
    }
}#[instrument(level = "debug", skip(self))]
2498    fn lower_const_path_to_const_arg(
2499        &mut self,
2500        path: &Path,
2501        res: Res<NodeId>,
2502        ty_id: NodeId,
2503        span: Span,
2504    ) -> &'hir hir::ConstArg<'hir> {
2505        let tcx = self.tcx;
2506
2507        let is_trivial_path = path.is_potential_trivial_const_arg()
2508            && matches!(res, Res::Def(DefKind::ConstParam, _));
2509        let ct_kind = if is_trivial_path || tcx.features().min_generic_const_args() {
2510            let qpath = self.lower_qpath(
2511                ty_id,
2512                &None,
2513                path,
2514                ParamMode::Explicit,
2515                AllowReturnTypeNotation::No,
2516                // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2517                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2518                None,
2519            );
2520            hir::ConstArgKind::Path(qpath)
2521        } else {
2522            // Construct an AnonConst where the expr is the "ty"'s path.
2523            let node_id = self.next_node_id();
2524            let span = self.lower_span(span);
2525
2526            // Add a definition for the in-band const def.
2527            // We're lowering a const argument that was originally thought to be a type argument,
2528            // so the def collector didn't create the def ahead of time. That's why we have to do
2529            // it here.
2530            let def_id = self.create_def(node_id, None, DefKind::AnonConst, span);
2531            let hir_id = self.lower_node_id(node_id);
2532
2533            let path_expr = Expr {
2534                id: ty_id,
2535                kind: ExprKind::Path(None, path.clone()),
2536                span,
2537                attrs: AttrVec::new(),
2538                tokens: None,
2539            };
2540
2541            let ct = self.with_new_scopes(span, |this| {
2542                self.arena.alloc(hir::AnonConst {
2543                    def_id,
2544                    hir_id,
2545                    body: this.lower_const_body(path_expr.span, Some(&path_expr)),
2546                    span,
2547                })
2548            });
2549            hir::ConstArgKind::Anon(ct)
2550        };
2551
2552        self.arena.alloc(hir::ConstArg {
2553            hir_id: self.next_id(),
2554            kind: ct_kind,
2555            span: self.lower_span(span),
2556        })
2557    }
2558
2559    fn lower_const_item_rhs(
2560        &mut self,
2561        rhs_kind: &ConstItemRhsKind,
2562        span: Span,
2563    ) -> hir::ConstItemRhs<'hir> {
2564        match rhs_kind {
2565            ConstItemRhsKind::Body { rhs: Some(body) } => {
2566                hir::ConstItemRhs::Body(self.lower_const_body(span, Some(body)))
2567            }
2568            ConstItemRhsKind::Body { rhs: None } => {
2569                hir::ConstItemRhs::Body(self.lower_const_body(span, None))
2570            }
2571            ConstItemRhsKind::TypeConst { rhs: Some(anon) } => {
2572                hir::ConstItemRhs::TypeConst(self.lower_anon_const_to_const_arg_and_alloc(anon))
2573            }
2574            ConstItemRhsKind::TypeConst { rhs: None } => {
2575                let const_arg = ConstArg {
2576                    hir_id: self.next_id(),
2577                    kind: hir::ConstArgKind::Error(
2578                        self.dcx().span_delayed_bug(DUMMY_SP, "no block"),
2579                    ),
2580                    span: DUMMY_SP,
2581                };
2582                hir::ConstItemRhs::TypeConst(self.arena.alloc(const_arg))
2583            }
2584        }
2585    }
2586
2587    x;#[instrument(level = "debug", skip(self), ret)]
2588    fn lower_expr_to_const_arg_direct(&mut self, expr: &Expr) -> hir::ConstArg<'hir> {
2589        let span = self.lower_span(expr.span);
2590
2591        let overly_complex_const = |this: &mut Self| {
2592            let msg = "complex const arguments must be placed inside of a `const` block";
2593            let e = if expr::WillCreateDefIdsVisitor.visit_expr(expr).is_break() {
2594                // FIXME(mgca): make this non-fatal once we have a better way to handle
2595                // nested items in const args
2596                // Issue: https://github.com/rust-lang/rust/issues/154539
2597                this.dcx().struct_span_fatal(expr.span, msg).emit()
2598            } else {
2599                this.dcx().struct_span_err(expr.span, msg).emit()
2600            };
2601
2602            ConstArg { hir_id: this.next_id(), kind: hir::ConstArgKind::Error(e), span }
2603        };
2604
2605        match &expr.kind {
2606            ExprKind::Call(func, args) if let ExprKind::Path(qself, path) = &func.kind => {
2607                let qpath = self.lower_qpath(
2608                    func.id,
2609                    qself,
2610                    path,
2611                    ParamMode::Explicit,
2612                    AllowReturnTypeNotation::No,
2613                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2614                    None,
2615                );
2616
2617                let lowered_args = self.arena.alloc_from_iter(args.iter().map(|arg| {
2618                    let const_arg = self.lower_expr_to_const_arg_direct(arg);
2619                    &*self.arena.alloc(const_arg)
2620                }));
2621
2622                ConstArg {
2623                    hir_id: self.next_id(),
2624                    kind: hir::ConstArgKind::TupleCall(qpath, lowered_args),
2625                    span,
2626                }
2627            }
2628            ExprKind::Tup(exprs) => {
2629                let exprs = self.arena.alloc_from_iter(exprs.iter().map(|expr| {
2630                    let expr = self.lower_expr_to_const_arg_direct(&expr);
2631                    &*self.arena.alloc(expr)
2632                }));
2633
2634                ConstArg { hir_id: self.next_id(), kind: hir::ConstArgKind::Tup(exprs), span }
2635            }
2636            ExprKind::Path(qself, path) => {
2637                let qpath = self.lower_qpath(
2638                    expr.id,
2639                    qself,
2640                    path,
2641                    ParamMode::Explicit,
2642                    AllowReturnTypeNotation::No,
2643                    // FIXME(mgca): update for `fn foo() -> Bar<FOO<impl Trait>>` support
2644                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2645                    None,
2646                );
2647
2648                ConstArg { hir_id: self.next_id(), kind: hir::ConstArgKind::Path(qpath), span }
2649            }
2650            ExprKind::Struct(se) => {
2651                let path = self.lower_qpath(
2652                    expr.id,
2653                    &se.qself,
2654                    &se.path,
2655                    // FIXME(mgca): we may want this to be `Optional` instead, but
2656                    // we would also need to make sure that HIR ty lowering errors
2657                    // when these paths wind up in signatures.
2658                    ParamMode::Explicit,
2659                    AllowReturnTypeNotation::No,
2660                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2661                    None,
2662                );
2663
2664                let fields = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
2665                    let hir_id = self.lower_node_id(f.id);
2666                    // FIXME(mgca): This might result in lowering attributes that
2667                    // then go unused as the `Target::ExprField` is not actually
2668                    // corresponding to `Node::ExprField`.
2669                    self.lower_attrs(hir_id, &f.attrs, f.span, Target::ExprField);
2670                    let expr = self.lower_expr_to_const_arg_direct(&f.expr);
2671
2672                    &*self.arena.alloc(hir::ConstArgExprField {
2673                        hir_id,
2674                        field: self.lower_ident(f.ident),
2675                        expr: self.arena.alloc(expr),
2676                        span: self.lower_span(f.span),
2677                    })
2678                }));
2679
2680                ConstArg {
2681                    hir_id: self.next_id(),
2682                    kind: hir::ConstArgKind::Struct(path, fields),
2683                    span,
2684                }
2685            }
2686            ExprKind::Array(elements) => {
2687                let lowered_elems = self.arena.alloc_from_iter(elements.iter().map(|element| {
2688                    let const_arg = self.lower_expr_to_const_arg_direct(element);
2689                    &*self.arena.alloc(const_arg)
2690                }));
2691                let array_expr = self.arena.alloc(hir::ConstArgArrayExpr {
2692                    span: self.lower_span(expr.span),
2693                    elems: lowered_elems,
2694                });
2695
2696                ConstArg {
2697                    hir_id: self.next_id(),
2698                    kind: hir::ConstArgKind::Array(array_expr),
2699                    span,
2700                }
2701            }
2702            ExprKind::Underscore => ConstArg {
2703                hir_id: self.lower_node_id(expr.id),
2704                kind: hir::ConstArgKind::Infer(()),
2705                span,
2706            },
2707            ExprKind::Block(block, _) => {
2708                if let [stmt] = block.stmts.as_slice()
2709                    && let StmtKind::Expr(expr) = &stmt.kind
2710                {
2711                    return self.lower_expr_to_const_arg_direct(expr);
2712                }
2713
2714                overly_complex_const(self)
2715            }
2716            ExprKind::Lit(literal) => {
2717                let span = self.lower_span(expr.span);
2718                let literal = self.lower_lit(literal, span);
2719
2720                ConstArg {
2721                    hir_id: self.lower_node_id(expr.id),
2722                    kind: hir::ConstArgKind::Literal { lit: literal.node, negated: false },
2723                    span,
2724                }
2725            }
2726            ExprKind::Unary(UnOp::Neg, inner_expr)
2727                if let ExprKind::Lit(literal) = &inner_expr.kind =>
2728            {
2729                let span = self.lower_span(expr.span);
2730                let literal = self.lower_lit(literal, span);
2731
2732                if !matches!(literal.node, LitKind::Int(..)) {
2733                    let err =
2734                        self.dcx().struct_span_err(expr.span, "negated literal must be an integer");
2735
2736                    return ConstArg {
2737                        hir_id: self.next_id(),
2738                        kind: hir::ConstArgKind::Error(err.emit()),
2739                        span,
2740                    };
2741                }
2742
2743                ConstArg {
2744                    hir_id: self.lower_node_id(expr.id),
2745                    kind: hir::ConstArgKind::Literal { lit: literal.node, negated: true },
2746                    span,
2747                }
2748            }
2749            ExprKind::ConstBlock(anon_const) => {
2750                let def_id = self.local_def_id(anon_const.id);
2751                assert_eq!(DefKind::AnonConst, self.tcx.def_kind(def_id));
2752                self.lower_anon_const_to_const_arg(anon_const, span)
2753            }
2754            _ => overly_complex_const(self),
2755        }
2756    }
2757
2758    /// See [`hir::ConstArg`] for when to use this function vs
2759    /// [`Self::lower_anon_const_to_anon_const`].
2760    fn lower_anon_const_to_const_arg_and_alloc(
2761        &mut self,
2762        anon: &AnonConst,
2763    ) -> &'hir hir::ConstArg<'hir> {
2764        self.arena.alloc(self.lower_anon_const_to_const_arg(anon, anon.value.span))
2765    }
2766
2767    #[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(2767u32),
                                    ::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))]
2768    fn lower_anon_const_to_const_arg(
2769        &mut self,
2770        anon: &AnonConst,
2771        span: Span,
2772    ) -> hir::ConstArg<'hir> {
2773        let tcx = self.tcx;
2774
2775        // We cannot change parsing depending on feature gates available,
2776        // we can only require feature gates to be active as a delayed check.
2777        // Thus we just parse anon consts generally and make the real decision
2778        // making in ast lowering.
2779        // FIXME(min_generic_const_args): revisit once stable
2780        if tcx.features().min_generic_const_args() {
2781            return match anon.mgca_disambiguation {
2782                MgcaDisambiguation::AnonConst => {
2783                    let lowered_anon = self.lower_anon_const_to_anon_const(anon, span);
2784                    ConstArg {
2785                        hir_id: self.next_id(),
2786                        kind: hir::ConstArgKind::Anon(lowered_anon),
2787                        span: lowered_anon.span,
2788                    }
2789                }
2790                MgcaDisambiguation::Direct => self.lower_expr_to_const_arg_direct(&anon.value),
2791            };
2792        }
2793
2794        // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2795        // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2796        let expr = if let ExprKind::Block(block, _) = &anon.value.kind
2797            && let [stmt] = block.stmts.as_slice()
2798            && let StmtKind::Expr(expr) = &stmt.kind
2799            && let ExprKind::Path(..) = &expr.kind
2800        {
2801            expr
2802        } else {
2803            &anon.value
2804        };
2805
2806        let maybe_res =
2807            self.resolver.get_partial_res(expr.id).and_then(|partial_res| partial_res.full_res());
2808        if let ExprKind::Path(qself, path) = &expr.kind
2809            && path.is_potential_trivial_const_arg()
2810            && matches!(maybe_res, Some(Res::Def(DefKind::ConstParam, _)))
2811        {
2812            let qpath = self.lower_qpath(
2813                expr.id,
2814                qself,
2815                path,
2816                ParamMode::Explicit,
2817                AllowReturnTypeNotation::No,
2818                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
2819                None,
2820            );
2821
2822            return ConstArg {
2823                hir_id: self.lower_node_id(anon.id),
2824                kind: hir::ConstArgKind::Path(qpath),
2825                span: self.lower_span(expr.span),
2826            };
2827        }
2828
2829        let lowered_anon = self.lower_anon_const_to_anon_const(anon, anon.value.span);
2830        ConstArg {
2831            hir_id: self.next_id(),
2832            kind: hir::ConstArgKind::Anon(lowered_anon),
2833            span: self.lower_span(expr.span),
2834        }
2835    }
2836
2837    /// See [`hir::ConstArg`] for when to use this function vs
2838    /// [`Self::lower_anon_const_to_const_arg`].
2839    fn lower_anon_const_to_anon_const(
2840        &mut self,
2841        c: &AnonConst,
2842        span: Span,
2843    ) -> &'hir hir::AnonConst {
2844        self.arena.alloc(self.with_new_scopes(c.value.span, |this| {
2845            let def_id = this.local_def_id(c.id);
2846            let hir_id = this.lower_node_id(c.id);
2847            hir::AnonConst {
2848                def_id,
2849                hir_id,
2850                body: this.lower_const_body(c.value.span, Some(&c.value)),
2851                span: this.lower_span(span),
2852            }
2853        }))
2854    }
2855
2856    fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource {
2857        match u {
2858            CompilerGenerated => hir::UnsafeSource::CompilerGenerated,
2859            UserProvided => hir::UnsafeSource::UserProvided,
2860        }
2861    }
2862
2863    fn lower_trait_bound_modifiers(
2864        &mut self,
2865        modifiers: TraitBoundModifiers,
2866    ) -> hir::TraitBoundModifiers {
2867        let constness = match modifiers.constness {
2868            BoundConstness::Never => BoundConstness::Never,
2869            BoundConstness::Always(span) => BoundConstness::Always(self.lower_span(span)),
2870            BoundConstness::Maybe(span) => BoundConstness::Maybe(self.lower_span(span)),
2871        };
2872        let polarity = match modifiers.polarity {
2873            BoundPolarity::Positive => BoundPolarity::Positive,
2874            BoundPolarity::Negative(span) => BoundPolarity::Negative(self.lower_span(span)),
2875            BoundPolarity::Maybe(span) => BoundPolarity::Maybe(self.lower_span(span)),
2876        };
2877        hir::TraitBoundModifiers { constness, polarity }
2878    }
2879
2880    // Helper methods for building HIR.
2881
2882    fn stmt(&mut self, span: Span, kind: hir::StmtKind<'hir>) -> hir::Stmt<'hir> {
2883        hir::Stmt { span: self.lower_span(span), kind, hir_id: self.next_id() }
2884    }
2885
2886    fn stmt_expr(&mut self, span: Span, expr: hir::Expr<'hir>) -> hir::Stmt<'hir> {
2887        self.stmt(span, hir::StmtKind::Expr(self.arena.alloc(expr)))
2888    }
2889
2890    fn stmt_let_pat(
2891        &mut self,
2892        attrs: Option<&'hir [hir::Attribute]>,
2893        span: Span,
2894        init: Option<&'hir hir::Expr<'hir>>,
2895        pat: &'hir hir::Pat<'hir>,
2896        source: hir::LocalSource,
2897    ) -> hir::Stmt<'hir> {
2898        let hir_id = self.next_id();
2899        if let Some(a) = attrs {
2900            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
2901            self.attrs.insert(hir_id.local_id, a);
2902        }
2903        let local = hir::LetStmt {
2904            super_: None,
2905            hir_id,
2906            init,
2907            pat,
2908            els: None,
2909            source,
2910            span: self.lower_span(span),
2911            ty: None,
2912        };
2913        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
2914    }
2915
2916    fn stmt_super_let_pat(
2917        &mut self,
2918        span: Span,
2919        pat: &'hir hir::Pat<'hir>,
2920        init: Option<&'hir hir::Expr<'hir>>,
2921    ) -> hir::Stmt<'hir> {
2922        let hir_id = self.next_id();
2923        let span = self.lower_span(span);
2924        let local = hir::LetStmt {
2925            super_: Some(span),
2926            hir_id,
2927            init,
2928            pat,
2929            els: None,
2930            source: hir::LocalSource::Normal,
2931            span,
2932            ty: None,
2933        };
2934        self.stmt(span, hir::StmtKind::Let(self.arena.alloc(local)))
2935    }
2936
2937    fn block_expr(&mut self, expr: &'hir hir::Expr<'hir>) -> &'hir hir::Block<'hir> {
2938        self.block_all(expr.span, &[], Some(expr))
2939    }
2940
2941    fn block_all(
2942        &mut self,
2943        span: Span,
2944        stmts: &'hir [hir::Stmt<'hir>],
2945        expr: Option<&'hir hir::Expr<'hir>>,
2946    ) -> &'hir hir::Block<'hir> {
2947        let blk = hir::Block {
2948            stmts,
2949            expr,
2950            hir_id: self.next_id(),
2951            rules: hir::BlockCheckMode::DefaultBlock,
2952            span: self.lower_span(span),
2953            targeted_by_break: false,
2954        };
2955        self.arena.alloc(blk)
2956    }
2957
2958    fn pat_cf_continue(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2959        let field = self.single_pat_field(span, pat);
2960        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowContinue, field)
2961    }
2962
2963    fn pat_cf_break(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2964        let field = self.single_pat_field(span, pat);
2965        self.pat_lang_item_variant(span, hir::LangItem::ControlFlowBreak, field)
2966    }
2967
2968    fn pat_some(&mut self, span: Span, pat: &'hir hir::Pat<'hir>) -> &'hir hir::Pat<'hir> {
2969        let field = self.single_pat_field(span, pat);
2970        self.pat_lang_item_variant(span, hir::LangItem::OptionSome, field)
2971    }
2972
2973    fn pat_none(&mut self, span: Span) -> &'hir hir::Pat<'hir> {
2974        self.pat_lang_item_variant(span, hir::LangItem::OptionNone, &[])
2975    }
2976
2977    fn single_pat_field(
2978        &mut self,
2979        span: Span,
2980        pat: &'hir hir::Pat<'hir>,
2981    ) -> &'hir [hir::PatField<'hir>] {
2982        let field = hir::PatField {
2983            hir_id: self.next_id(),
2984            ident: Ident::new(sym::integer(0), self.lower_span(span)),
2985            is_shorthand: false,
2986            pat,
2987            span: self.lower_span(span),
2988        };
2989        self.arena.alloc_from_iter([field])arena_vec![self; field]
2990    }
2991
2992    fn pat_lang_item_variant(
2993        &mut self,
2994        span: Span,
2995        lang_item: hir::LangItem,
2996        fields: &'hir [hir::PatField<'hir>],
2997    ) -> &'hir hir::Pat<'hir> {
2998        let path = self.make_lang_item_qpath(lang_item, self.lower_span(span), None);
2999        self.pat(span, hir::PatKind::Struct(path, fields, None))
3000    }
3001
3002    fn pat_ident(&mut self, span: Span, ident: Ident) -> (&'hir hir::Pat<'hir>, HirId) {
3003        self.pat_ident_binding_mode(span, ident, hir::BindingMode::NONE)
3004    }
3005
3006    fn pat_ident_mut(&mut self, span: Span, ident: Ident) -> (hir::Pat<'hir>, HirId) {
3007        self.pat_ident_binding_mode_mut(span, ident, hir::BindingMode::NONE)
3008    }
3009
3010    fn pat_ident_binding_mode(
3011        &mut self,
3012        span: Span,
3013        ident: Ident,
3014        bm: hir::BindingMode,
3015    ) -> (&'hir hir::Pat<'hir>, HirId) {
3016        let (pat, hir_id) = self.pat_ident_binding_mode_mut(span, ident, bm);
3017        (self.arena.alloc(pat), hir_id)
3018    }
3019
3020    fn pat_ident_binding_mode_mut(
3021        &mut self,
3022        span: Span,
3023        ident: Ident,
3024        bm: hir::BindingMode,
3025    ) -> (hir::Pat<'hir>, HirId) {
3026        let hir_id = self.next_id();
3027
3028        (
3029            hir::Pat {
3030                hir_id,
3031                kind: hir::PatKind::Binding(bm, hir_id, self.lower_ident(ident), None),
3032                span: self.lower_span(span),
3033                default_binding_modes: true,
3034            },
3035            hir_id,
3036        )
3037    }
3038
3039    fn pat(&mut self, span: Span, kind: hir::PatKind<'hir>) -> &'hir hir::Pat<'hir> {
3040        self.arena.alloc(hir::Pat {
3041            hir_id: self.next_id(),
3042            kind,
3043            span: self.lower_span(span),
3044            default_binding_modes: true,
3045        })
3046    }
3047
3048    fn pat_without_dbm(&mut self, span: Span, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> {
3049        hir::Pat {
3050            hir_id: self.next_id(),
3051            kind,
3052            span: self.lower_span(span),
3053            default_binding_modes: false,
3054        }
3055    }
3056
3057    fn ty_path(&mut self, mut hir_id: HirId, span: Span, qpath: hir::QPath<'hir>) -> hir::Ty<'hir> {
3058        let kind = match qpath {
3059            hir::QPath::Resolved(None, path) => {
3060                // Turn trait object paths into `TyKind::TraitObject` instead.
3061                match path.res {
3062                    Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => {
3063                        let principal = hir::PolyTraitRef {
3064                            bound_generic_params: &[],
3065                            modifiers: hir::TraitBoundModifiers::NONE,
3066                            trait_ref: hir::TraitRef { path, hir_ref_id: hir_id },
3067                            span: self.lower_span(span),
3068                        };
3069
3070                        // The original ID is taken by the `PolyTraitRef`,
3071                        // so the `Ty` itself needs a different one.
3072                        hir_id = self.next_id();
3073                        hir::TyKind::TraitObject(
3074                            self.arena.alloc_from_iter([principal])arena_vec![self; principal],
3075                            TaggedRef::new(self.elided_dyn_bound(span), TraitObjectSyntax::None),
3076                        )
3077                    }
3078                    _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)),
3079                }
3080            }
3081            _ => hir::TyKind::Path(qpath),
3082        };
3083
3084        hir::Ty { hir_id, kind, span: self.lower_span(span) }
3085    }
3086
3087    /// Invoked to create the lifetime argument(s) for an elided trait object
3088    /// bound, like the bound in `Box<dyn Debug>`. This method is not invoked
3089    /// when the bound is written, even if it is written with `'_` like in
3090    /// `Box<dyn Debug + '_>`. In those cases, `lower_lifetime` is invoked.
3091    fn elided_dyn_bound(&mut self, span: Span) -> &'hir hir::Lifetime {
3092        let r = hir::Lifetime::new(
3093            self.next_id(),
3094            Ident::new(kw::UnderscoreLifetime, self.lower_span(span)),
3095            hir::LifetimeKind::ImplicitObjectLifetimeDefault,
3096            LifetimeSource::Other,
3097            LifetimeSyntax::Implicit,
3098        );
3099        {
    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:3099",
                        "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(3099u32),
                        ::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);
3100        self.arena.alloc(r)
3101    }
3102}
3103
3104/// Helper struct for the delayed construction of [`hir::GenericArgs`].
3105struct GenericArgsCtor<'hir> {
3106    args: SmallVec<[hir::GenericArg<'hir>; 4]>,
3107    constraints: &'hir [hir::AssocItemConstraint<'hir>],
3108    parenthesized: hir::GenericArgsParentheses,
3109    span: Span,
3110}
3111
3112impl<'hir> GenericArgsCtor<'hir> {
3113    fn is_empty(&self) -> bool {
3114        self.args.is_empty()
3115            && self.constraints.is_empty()
3116            && self.parenthesized == hir::GenericArgsParentheses::No
3117    }
3118
3119    fn into_generic_args(
3120        self,
3121        this: &LoweringContext<'_, 'hir, impl ResolverAstLoweringExt<'hir>>,
3122    ) -> &'hir hir::GenericArgs<'hir> {
3123        let ga = hir::GenericArgs {
3124            args: this.arena.alloc_from_iter(self.args),
3125            constraints: self.constraints,
3126            parenthesized: self.parenthesized,
3127            span_ext: this.lower_span(self.span),
3128        };
3129        this.arena.alloc(ga)
3130    }
3131}