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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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