Skip to main content

rustc_ast_lowering/
lib.rs

1//! Lowers the AST to the HIR.
2//!
3//! Since the AST and HIR are fairly similar, this is mostly a simple procedure,
4//! much like a fold. Where lowering involves a bit more work things get more
5//! interesting and there are some invariants you should know about. These mostly
6//! concern spans and IDs.
7//!
8//! Spans are assigned to AST nodes during parsing and then are modified during
9//! expansion to indicate the origin of a node and the process it went through
10//! being expanded. IDs are assigned to AST nodes just before lowering.
11//!
12//! For the simpler lowering steps, IDs and spans should be preserved. Unlike
13//! expansion we do not preserve the process of lowering in the spans, so spans
14//! should not be modified here. When creating a new node (as opposed to
15//! "folding" an existing one), create a new ID using `next_id()`.
16//!
17//! You must ensure that IDs are unique. That means that you should only use the
18//! ID from an AST node in a single HIR node (you can assume that AST node-IDs
19//! are unique). Every new node must have a unique ID. Avoid cloning HIR nodes.
20//! If you do, you must then set the new node's ID to a fresh one.
21//!
22//! Spans are used for error messages and for tools to map semantics back to
23//! source code. It is therefore not as important with spans as IDs to be strict
24//! about use (you can't break the compiler by screwing up a span). Obviously, a
25//! HIR node can only have a single span. But multiple nodes can have the same
26//! span and spans don't need to be kept in order, etc. Where code is preserved
27//! by lowering, it should have the same span as in the AST. Where HIR nodes are
28//! new it is probably best to give a span for the whole AST node being lowered.
29//! All nodes should have real spans; don't use dummy spans. Tools are likely to
30//! get confused if the spans from leaf AST nodes occur in multiple places
31//! in the HIR, especially for multiple identifiers.
32
33// tidy-alphabetical-start
34#![feature(box_patterns)]
35#![recursion_limit = "256"]
36// tidy-alphabetical-end
37
38use std::mem;
39use std::sync::Arc;
40
41use rustc_ast::node_id::NodeMap;
42use rustc_ast::visit::Visitor;
43use rustc_ast::{self as ast, *};
44use rustc_attr_parsing::{AttributeParser, EmitAttribute, Late, OmitDoc};
45use rustc_data_structures::fingerprint::Fingerprint;
46use rustc_data_structures::fx::FxIndexSet;
47use rustc_data_structures::sorted_map::SortedMap;
48use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
49use rustc_data_structures::steal::Steal;
50use rustc_data_structures::tagged_ptr::TaggedRef;
51use rustc_errors::{DiagArgFromDisplay, DiagCtxtHandle};
52use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
53use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId};
54use rustc_hir::definitions::PerParentDisambiguatorState;
55use rustc_hir::lints::{AttributeLint, DelayedLint, DynAttribute};
56use rustc_hir::{
57    self as hir, AngleBrackets, ConstArg, GenericArg, HirId, ItemLocalMap, LifetimeSource,
58    LifetimeSyntax, ParamName, Target, TraitCandidate, find_attr,
59};
60use rustc_index::{Idx, IndexSlice, IndexVec};
61use rustc_macros::extension;
62use rustc_middle::hir::{self as mid_hir};
63use rustc_middle::span_bug;
64use rustc_middle::ty::{DelegationInfo, ResolverAstLowering, TyCtxt};
65use rustc_session::parse::add_feature_diagnostics;
66use rustc_span::symbol::{Ident, Symbol, kw, sym};
67use rustc_span::{DUMMY_SP, DesugaringKind, Span};
68use smallvec::SmallVec;
69use thin_vec::ThinVec;
70use tracing::{debug, instrument, trace};
71
72use crate::errors::{AssocTyParentheses, AssocTyParenthesesSub, MisplacedImplTrait};
73use crate::item::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: PerParentDisambiguatorState,
98
99    /// Used to allocate HIR nodes.
100    arena: &'hir hir::Arena<'hir>,
101
102    /// Bodies inside the owner being lowered.
103    bodies: Vec<(hir::ItemLocalId, &'hir hir::Body<'hir>)>,
104    /// `#[define_opaque]` attributes
105    define_opaque: Option<&'hir [(Span, LocalDefId)]>,
106    /// Attributes inside the owner being lowered.
107    attrs: SortedMap<hir::ItemLocalId, &'hir [hir::Attribute]>,
108    /// Collect items that were created by lowering the current owner.
109    children: Vec<(LocalDefId, hir::MaybeOwner<'hir>)>,
110
111    contract_ensures: Option<(Span, Ident, HirId)>,
112
113    coroutine_kind: Option<hir::CoroutineKind>,
114
115    /// When inside an `async` context, this is the `HirId` of the
116    /// `task_context` local bound to the resume argument of the coroutine.
117    task_context: Option<HirId>,
118
119    /// Used to get the current `fn`'s def span to point to when using `await`
120    /// outside of an `async fn`.
121    current_item: Option<Span>,
122
123    try_block_scope: TryBlockScope,
124    loop_scope: Option<HirId>,
125    is_in_loop_condition: bool,
126    is_in_dyn_type: bool,
127    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: Default::default(),
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    fn steal_or_create_disambiguator(&self, parent: LocalDefId) -> PerParentDisambiguatorState {
307        self.base.steal_or_create_disambiguator(parent)
308    }
309}
310
311fn next_node_id(current_id: &mut NodeId) -> NodeId {
312    let start = *current_id;
313    let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
314    *current_id = ast::NodeId::from_u32(next);
315
316    start
317}
318
319impl<'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)
    }
    fn steal_or_create_disambiguator(&self, parent: LocalDefId)
        -> PerParentDisambiguatorState {
        self.per_parent_disambiguators.get(&parent).map(|s|
                    s.steal()).unwrap_or_default()
    }
}#[extension(trait ResolverAstLoweringExt<'tcx>)]
320impl<'tcx> ResolverAstLowering<'tcx> {
321    fn legacy_const_generic_args(&self, expr: &Expr, tcx: TyCtxt<'tcx>) -> Option<Vec<usize>> {
322        let ExprKind::Path(None, path) = &expr.kind else {
323            return None;
324        };
325
326        // Don't perform legacy const generics rewriting if the path already
327        // has generic arguments.
328        if path.segments.last().unwrap().args.is_some() {
329            return None;
330        }
331
332        let def_id = self.get_partial_res(expr.id)?.full_res()?.opt_def_id()?;
333
334        // We only support cross-crate argument rewriting. Uses
335        // within the same crate should be updated to use the new
336        // const generics style.
337        if def_id.is_local() {
338            return None;
339        }
340
341        // we can use parsed attrs here since for other crates they're already available
342        find_attr!(
343            tcx, def_id,
344            RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
345        )
346        .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
347    }
348
349    fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
350        self.partial_res_map.get(&id).copied()
351    }
352
353    /// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
354    fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
355        self.import_res_map.get(&id).copied().unwrap_or_default()
356    }
357
358    /// Obtains resolution for a label with the given `NodeId`.
359    fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
360        self.label_res_map.get(&id).copied()
361    }
362
363    /// Obtains resolution for a lifetime with the given `NodeId`.
364    fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
365        self.lifetimes_res_map.get(&id).copied()
366    }
367
368    /// Obtain the list of lifetimes parameters to add to an item.
369    ///
370    /// Extra lifetime parameters should only be added in places that can appear
371    /// as a `binder` in `LifetimeRes`.
372    ///
373    /// The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring
374    /// should appear at the enclosing `PolyTraitRef`.
375    fn extra_lifetime_params(&self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> {
376        self.extra_lifetime_params_map.get(&id).cloned().unwrap_or_default()
377    }
378
379    fn delegation_info(&self, id: LocalDefId) -> Option<&DelegationInfo> {
380        self.delegation_infos.get(&id)
381    }
382
383    fn opt_local_def_id(&self, id: NodeId) -> Option<LocalDefId> {
384        self.node_id_to_def_id.get(&id).copied()
385    }
386
387    fn local_def_id(&self, id: NodeId) -> LocalDefId {
388        self.opt_local_def_id(id).expect("must have def_id")
389    }
390
391    fn lifetime_elision_allowed(&self, id: NodeId) -> bool {
392        self.lifetime_elision_allowed.contains(&id)
393    }
394
395    fn insert_new_def_id(&mut self, node_id: NodeId, def_id: LocalDefId) {
396        self.node_id_to_def_id.insert(node_id, def_id);
397    }
398
399    fn insert_partial_res(&mut self, node_id: NodeId, res: PartialRes) {
400        self.partial_res_map.insert(node_id, res);
401    }
402
403    fn trait_candidates(&self, node_id: NodeId) -> Option<&'tcx [hir::TraitCandidate<'tcx>]> {
404        self.trait_map.get(&node_id).copied()
405    }
406
407    #[inline]
408    fn next_node_id(&mut self) -> NodeId {
409        next_node_id(&mut self.next_node_id)
410    }
411
412    fn steal_or_create_disambiguator(&self, parent: LocalDefId) -> PerParentDisambiguatorState {
413        self.per_parent_disambiguators.get(&parent).map(|s| s.steal()).unwrap_or_default()
414    }
415}
416
417/// How relaxed bounds `?Trait` should be treated.
418///
419/// Relaxed bounds should only be allowed in places where we later
420/// (namely during HIR ty lowering) perform *sized elaboration*.
421#[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)]
422enum RelaxedBoundPolicy<'a> {
423    Allowed,
424    AllowedIfOnTyParam(NodeId, &'a [ast::GenericParam]),
425    Forbidden(RelaxedBoundForbiddenReason),
426}
427
428#[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)]
429enum RelaxedBoundForbiddenReason {
430    TraitObjectTy,
431    SuperTrait,
432    TraitAlias,
433    AssocTyBounds,
434    LateBoundVarsInScope,
435}
436
437/// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree,
438/// and if so, what meaning it has.
439#[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)]
440enum ImplTraitContext {
441    /// Treat `impl Trait` as shorthand for a new universal generic parameter.
442    /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually
443    /// equivalent to a fresh universal parameter like `fn foo<T: Debug>(x: T)`.
444    ///
445    /// Newly generated parameters should be inserted into the given `Vec`.
446    Universal,
447
448    /// Treat `impl Trait` as shorthand for a new opaque type.
449    /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually
450    /// equivalent to a new opaque type like `type T = impl Debug; fn foo() -> T`.
451    ///
452    OpaqueTy { origin: hir::OpaqueTyOrigin<LocalDefId> },
453
454    /// Treat `impl Trait` as a "trait ascription", which is like a type
455    /// variable but that also enforces that a set of trait goals hold.
456    ///
457    /// This is useful to guide inference for unnameable types.
458    InBinding,
459
460    /// `impl Trait` is unstably accepted in this position.
461    FeatureGated(ImplTraitPosition, Symbol),
462    /// `impl Trait` is not accepted in this position.
463    Disallowed(ImplTraitPosition),
464}
465
466/// Position in which `impl Trait` is disallowed.
467#[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)]
468enum ImplTraitPosition {
469    Path,
470    Variable,
471    Trait,
472    Bound,
473    Generic,
474    ExternFnParam,
475    ClosureParam,
476    PointerParam,
477    FnTraitParam,
478    ExternFnReturn,
479    ClosureReturn,
480    PointerReturn,
481    FnTraitReturn,
482    GenericDefault,
483    ConstTy,
484    StaticTy,
485    AssocTy,
486    FieldTy,
487    Cast,
488    ImplSelf,
489    OffsetOf,
490}
491
492impl std::fmt::Display for ImplTraitPosition {
493    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
494        let name = match self {
495            ImplTraitPosition::Path => "paths",
496            ImplTraitPosition::Variable => "the type of variable bindings",
497            ImplTraitPosition::Trait => "traits",
498            ImplTraitPosition::Bound => "bounds",
499            ImplTraitPosition::Generic => "generics",
500            ImplTraitPosition::ExternFnParam => "`extern fn` parameters",
501            ImplTraitPosition::ClosureParam => "closure parameters",
502            ImplTraitPosition::PointerParam => "`fn` pointer parameters",
503            ImplTraitPosition::FnTraitParam => "the parameters of `Fn` trait bounds",
504            ImplTraitPosition::ExternFnReturn => "`extern fn` return types",
505            ImplTraitPosition::ClosureReturn => "closure return types",
506            ImplTraitPosition::PointerReturn => "`fn` pointer return types",
507            ImplTraitPosition::FnTraitReturn => "the return type of `Fn` trait bounds",
508            ImplTraitPosition::GenericDefault => "generic parameter defaults",
509            ImplTraitPosition::ConstTy => "const types",
510            ImplTraitPosition::StaticTy => "static types",
511            ImplTraitPosition::AssocTy => "associated types",
512            ImplTraitPosition::FieldTy => "field types",
513            ImplTraitPosition::Cast => "cast expression types",
514            ImplTraitPosition::ImplSelf => "impl headers",
515            ImplTraitPosition::OffsetOf => "`offset_of!` parameters",
516        };
517
518        f.write_fmt(format_args!("{0}", name))write!(f, "{name}")
519    }
520}
521
522#[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)]
523enum FnDeclKind {
524    Fn,
525    Inherent,
526    ExternFn,
527    Closure,
528    Pointer,
529    Trait,
530    Impl,
531}
532
533#[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)]
534enum AstOwner<'a> {
535    NonOwner,
536    Crate(&'a ast::Crate),
537    Item(&'a ast::Item),
538    AssocItem(&'a ast::AssocItem, visit::AssocCtxt),
539    ForeignItem(&'a ast::ForeignItem),
540}
541
542#[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)]
543enum TryBlockScope {
544    /// There isn't a `try` block, so a `?` will use `return`.
545    Function,
546    /// We're inside a `try { … }` block, so a `?` will block-break
547    /// from that block using a type depending only on the argument.
548    Homogeneous(HirId),
549    /// We're inside a `try as _ { … }` block, so a `?` will block-break
550    /// from that block using the type specified.
551    Heterogeneous(HirId),
552}
553
554fn index_crate<'a, 'b>(
555    resolver: &'b impl ResolverAstLoweringExt<'a>,
556    krate: &'a Crate,
557) -> IndexVec<LocalDefId, AstOwner<'a>> {
558    let mut indexer = Indexer { resolver, index: IndexVec::new() };
559    *indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner) =
560        AstOwner::Crate(krate);
561    visit::walk_crate(&mut indexer, krate);
562
563    return indexer.index;
564
565    struct Indexer<'a, 'b, R> {
566        resolver: &'b R,
567        index: IndexVec<LocalDefId, AstOwner<'a>>,
568    }
569
570    impl<'a, 'b, R: ResolverAstLoweringExt<'a>> visit::Visitor<'a> for Indexer<'a, 'b, R> {
571        fn visit_attribute(&mut self, _: &'a Attribute) {
572            // We do not want to lower expressions that appear in attributes,
573            // as they are not accessible to the rest of the HIR.
574        }
575
576        fn visit_item(&mut self, item: &'a ast::Item) {
577            let def_id = self.resolver.local_def_id(item.id);
578            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) = AstOwner::Item(item);
579            visit::walk_item(self, item)
580        }
581
582        fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) {
583            let def_id = self.resolver.local_def_id(item.id);
584            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) =
585                AstOwner::AssocItem(item, ctxt);
586            visit::walk_assoc_item(self, item, ctxt);
587        }
588
589        fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) {
590            let def_id = self.resolver.local_def_id(item.id);
591            *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) =
592                AstOwner::ForeignItem(item);
593            visit::walk_item(self, item);
594        }
595    }
596}
597
598/// Compute the hash for the HIR of the full crate.
599/// This hash will then be part of the crate_hash which is stored in the metadata.
600fn compute_hir_hash(
601    tcx: TyCtxt<'_>,
602    owners: &IndexSlice<LocalDefId, hir::MaybeOwner<'_>>,
603) -> Fingerprint {
604    let mut hir_body_nodes: Vec<_> = owners
605        .iter_enumerated()
606        .filter_map(|(def_id, info)| {
607            let info = info.as_owner()?;
608            let def_path_hash = tcx.hir_def_path_hash(def_id);
609            Some((def_path_hash, info))
610        })
611        .collect();
612    hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
613
614    tcx.with_stable_hashing_context(|mut hcx| {
615        let mut stable_hasher = StableHasher::new();
616        hir_body_nodes.hash_stable(&mut hcx, &mut stable_hasher);
617        stable_hasher.finish()
618    })
619}
620
621pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
622    // Queries that borrow `resolver_for_lowering`.
623    tcx.ensure_done().output_filenames(());
624    tcx.ensure_done().early_lint_checks(());
625    tcx.ensure_done().debugger_visualizers(LOCAL_CRATE);
626    tcx.ensure_done().get_lang_items(());
627    let (mut resolver, krate) = tcx.resolver_for_lowering().steal();
628
629    let ast_index = index_crate(&resolver, &krate);
630    let mut owners = IndexVec::from_fn_n(
631        |_| hir::MaybeOwner::Phantom,
632        tcx.definitions_untracked().def_index_count(),
633    );
634
635    let mut lowerer = item::ItemLowerer {
636        tcx,
637        resolver: &mut resolver,
638        ast_index: &ast_index,
639        owners: Owners::IndexVec(&mut owners),
640    };
641
642    let mut delayed_ids: FxIndexSet<LocalDefId> = Default::default();
643
644    for def_id in ast_index.indices() {
645        match &ast_index[def_id] {
646            AstOwner::Item(Item { kind: ItemKind::Delegation { .. }, .. })
647            | AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation { .. }, .. }, _) => {
648                delayed_ids.insert(def_id);
649            }
650            _ => lowerer.lower_node(def_id),
651        };
652    }
653
654    // Don't hash unless necessary, because it's expensive.
655    let opt_hir_hash =
656        if tcx.needs_crate_hash() { Some(compute_hir_hash(tcx, &owners)) } else { None };
657
658    let delayed_resolver = Steal::new((resolver, krate));
659    mid_hir::Crate::new(owners, delayed_ids, delayed_resolver, opt_hir_hash)
660}
661
662/// Lowers an AST owner corresponding to `def_id`, now only delegations are lowered this way.
663pub fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
664    let krate = tcx.hir_crate(());
665
666    let (resolver, krate) = &*krate.delayed_resolver.borrow();
667
668    // FIXME!!!(fn_delegation): make ast index lifetime same as resolver,
669    // as it is too bad to reindex whole crate on each delegation lowering.
670    let ast_index = index_crate(resolver, krate);
671
672    let mut resolver = ResolverDelayedAstLowering {
673        next_node_id: resolver.next_node_id,
674        partial_res_map: Default::default(),
675        node_id_to_def_id: Default::default(),
676        base: resolver,
677    };
678
679    let mut map = Default::default();
680
681    let mut lowerer = item::ItemLowerer {
682        tcx,
683        resolver: &mut resolver,
684        ast_index: &ast_index,
685        owners: Owners::Map(&mut map),
686    };
687
688    lowerer.lower_node(def_id);
689
690    for (child_def_id, owner) in map {
691        tcx.feed_delayed_owner(child_def_id, owner);
692    }
693}
694
695#[derive(#[automatically_derived]
impl ::core::marker::Copy for ParamMode { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ParamMode {
    #[inline]
    fn clone(&self) -> ParamMode { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ParamMode {
    #[inline]
    fn eq(&self, other: &ParamMode) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for ParamMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ParamMode::Explicit => "Explicit",
                ParamMode::Optional => "Optional",
            })
    }
}Debug)]
696enum ParamMode {
697    /// Any path in a type context.
698    Explicit,
699    /// The `module::Type` in `module::Type::method` in an expression.
700    Optional,
701}
702
703#[derive(#[automatically_derived]
impl ::core::marker::Copy for AllowReturnTypeNotation { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AllowReturnTypeNotation {
    #[inline]
    fn clone(&self) -> AllowReturnTypeNotation { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AllowReturnTypeNotation {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AllowReturnTypeNotation::Yes => "Yes",
                AllowReturnTypeNotation::No => "No",
            })
    }
}Debug)]
704enum AllowReturnTypeNotation {
705    /// Only in types, since RTN is denied later during HIR lowering.
706    Yes,
707    /// All other positions (path expr, method, use tree).
708    No,
709}
710
711enum GenericArgsMode {
712    /// Allow paren sugar, don't allow RTN.
713    ParenSugar,
714    /// Allow RTN, don't allow paren sugar.
715    ReturnTypeNotation,
716    // Error if parenthesized generics or RTN are encountered.
717    Err,
718    /// Silence errors when lowering generics. Only used with `Res::Err`.
719    Silence,
720}
721
722impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
723    fn create_def(
724        &mut self,
725        node_id: ast::NodeId,
726        name: Option<Symbol>,
727        def_kind: DefKind,
728        span: Span,
729    ) -> LocalDefId {
730        let parent = self.current_hir_id_owner.def_id;
731        match (&node_id, &ast::DUMMY_NODE_ID) {
    (left_val, right_val) => {
        if *left_val == *right_val {
            let kind = ::core::panicking::AssertKind::Ne;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_ne!(node_id, ast::DUMMY_NODE_ID);
732        if !self.opt_local_def_id(node_id).is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("adding a def\'n for node-id {0:?} and def kind {1:?} but a previous def\'n exists: {2:?}",
                node_id, def_kind,
                self.tcx.hir_def_key(self.local_def_id(node_id))));
    }
};assert!(
733            self.opt_local_def_id(node_id).is_none(),
734            "adding a def'n for node-id {:?} and def kind {:?} but a previous def'n exists: {:?}",
735            node_id,
736            def_kind,
737            self.tcx.hir_def_key(self.local_def_id(node_id)),
738        );
739
740        let def_id = self
741            .tcx
742            .at(span)
743            .create_def(parent, name, def_kind, None, &mut self.disambiguator)
744            .def_id();
745
746        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:746",
                        "rustc_ast_lowering", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(746u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("create_def: def_id_to_node_id[{0:?}] <-> {1:?}",
                                                    def_id, node_id) as &dyn Value))])
            });
    } else { ; }
};debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
747        self.resolver.insert_new_def_id(node_id, def_id);
748
749        def_id
750    }
751
752    fn next_node_id(&mut self) -> NodeId {
753        self.resolver.next_node_id()
754    }
755
756    /// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
757    /// resolver (if any).
758    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
759        self.resolver.opt_local_def_id(node)
760    }
761
762    fn local_def_id(&self, node: NodeId) -> LocalDefId {
763        self.opt_local_def_id(node).unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("no entry for node id: `{0:?}`",
            node));
}panic!("no entry for node id: `{node:?}`"))
764    }
765
766    /// Given the id of an owner node in the AST, returns the corresponding `OwnerId`.
767    fn owner_id(&self, node: NodeId) -> hir::OwnerId {
768        hir::OwnerId { def_id: self.local_def_id(node) }
769    }
770
771    /// Freshen the `LoweringContext` and ready it to lower a nested item.
772    /// The lowered item is registered into `self.children`.
773    ///
774    /// This function sets up `HirId` lowering infrastructure,
775    /// and stashes the shared mutable state to avoid pollution by the closure.
776    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("with_hir_id_owner",
                                    "rustc_ast_lowering", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(776u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["owner"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&owner)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<hir::GenericParam<'hir>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (name, kind) =
                match res {
                    LifetimeRes::Param { .. } => {
                        (hir::ParamName::Plain(ident),
                            hir::LifetimeParamKind::Explicit)
                    }
                    LifetimeRes::Fresh { param, kind, .. } => {
                        let _def_id =
                            self.create_def(param, Some(kw::UnderscoreLifetime),
                                DefKind::LifetimeParam, ident.span);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_ast_lowering/src/lib.rs:1028",
                                                "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(1028u32),
                                                ::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))]
1009    fn lifetime_res_to_generic_param(
1010        &mut self,
1011        ident: Ident,
1012        node_id: NodeId,
1013        res: LifetimeRes,
1014        source: hir::GenericParamSource,
1015    ) -> Option<hir::GenericParam<'hir>> {
1016        let (name, kind) = match res {
1017            LifetimeRes::Param { .. } => {
1018                (hir::ParamName::Plain(ident), hir::LifetimeParamKind::Explicit)
1019            }
1020            LifetimeRes::Fresh { param, kind, .. } => {
1021                // Late resolution delegates to us the creation of the `LocalDefId`.
1022                let _def_id = self.create_def(
1023                    param,
1024                    Some(kw::UnderscoreLifetime),
1025                    DefKind::LifetimeParam,
1026                    ident.span,
1027                );
1028                debug!(?_def_id);
1029
1030                (hir::ParamName::Fresh, hir::LifetimeParamKind::Elided(kind))
1031            }
1032            LifetimeRes::Static { .. } | LifetimeRes::Error(..) => return None,
1033            res => panic!(
1034                "Unexpected lifetime resolution {:?} for {:?} at {:?}",
1035                res, ident, ident.span
1036            ),
1037        };
1038        let hir_id = self.lower_node_id(node_id);
1039        let def_id = self.local_def_id(node_id);
1040        Some(hir::GenericParam {
1041            hir_id,
1042            def_id,
1043            name,
1044            span: self.lower_span(ident.span),
1045            pure_wrt_drop: false,
1046            kind: hir::GenericParamKind::Lifetime { kind },
1047            colon_span: None,
1048            source,
1049        })
1050    }
1051
1052    /// Lowers a lifetime binder that defines `generic_params`, returning the corresponding HIR
1053    /// nodes. The returned list includes any "extra" lifetime parameters that were added by the
1054    /// name resolver owing to lifetime elision; this also populates the resolver's node-id->def-id
1055    /// map, so that later calls to `opt_node_id_to_def_id` that refer to these extra lifetime
1056    /// parameters will be successful.
1057    x;#[instrument(level = "debug", skip(self), ret)]
1058    #[inline]
1059    fn lower_lifetime_binder(
1060        &mut self,
1061        binder: NodeId,
1062        generic_params: &[GenericParam],
1063    ) -> &'hir [hir::GenericParam<'hir>] {
1064        // Start by creating params for extra lifetimes params, as this creates the definitions
1065        // that may be referred to by the AST inside `generic_params`.
1066        let extra_lifetimes = self.resolver.extra_lifetime_params(binder);
1067        debug!(?extra_lifetimes);
1068        let extra_lifetimes: Vec<_> = extra_lifetimes
1069            .into_iter()
1070            .filter_map(|(ident, node_id, res)| {
1071                self.lifetime_res_to_generic_param(
1072                    ident,
1073                    node_id,
1074                    res,
1075                    hir::GenericParamSource::Binder,
1076                )
1077            })
1078            .collect();
1079        let arena = self.arena;
1080        let explicit_generic_params =
1081            self.lower_generic_params_mut(generic_params, hir::GenericParamSource::Binder);
1082        arena.alloc_from_iter(explicit_generic_params.chain(extra_lifetimes.into_iter()))
1083    }
1084
1085    fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T {
1086        let was_in_dyn_type = self.is_in_dyn_type;
1087        self.is_in_dyn_type = in_scope;
1088
1089        let result = f(self);
1090
1091        self.is_in_dyn_type = was_in_dyn_type;
1092
1093        result
1094    }
1095
1096    fn with_new_scopes<T>(&mut self, scope_span: Span, f: impl FnOnce(&mut Self) -> T) -> T {
1097        let current_item = self.current_item;
1098        self.current_item = Some(scope_span);
1099
1100        let was_in_loop_condition = self.is_in_loop_condition;
1101        self.is_in_loop_condition = false;
1102
1103        let old_contract = self.contract_ensures.take();
1104
1105        let try_block_scope = mem::replace(&mut self.try_block_scope, TryBlockScope::Function);
1106        let loop_scope = self.loop_scope.take();
1107        let ret = f(self);
1108        self.try_block_scope = try_block_scope;
1109        self.loop_scope = loop_scope;
1110
1111        self.contract_ensures = old_contract;
1112
1113        self.is_in_loop_condition = was_in_loop_condition;
1114
1115        self.current_item = current_item;
1116
1117        ret
1118    }
1119
1120    fn lower_attrs(
1121        &mut self,
1122        id: HirId,
1123        attrs: &[Attribute],
1124        target_span: Span,
1125        target: Target,
1126    ) -> &'hir [hir::Attribute] {
1127        self.lower_attrs_with_extra(id, attrs, target_span, target, &[])
1128    }
1129
1130    fn lower_attrs_with_extra(
1131        &mut self,
1132        id: HirId,
1133        attrs: &[Attribute],
1134        target_span: Span,
1135        target: Target,
1136        extra_hir_attributes: &[hir::Attribute],
1137    ) -> &'hir [hir::Attribute] {
1138        if attrs.is_empty() && extra_hir_attributes.is_empty() {
1139            &[]
1140        } else {
1141            let mut lowered_attrs =
1142                self.lower_attrs_vec(attrs, self.lower_span(target_span), id, target);
1143            lowered_attrs.extend(extra_hir_attributes.iter().cloned());
1144
1145            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);
1146            let ret = self.arena.alloc_from_iter(lowered_attrs);
1147
1148            // this is possible if an item contained syntactical attribute,
1149            // but none of them parse successfully or all of them were ignored
1150            // for not being built-in attributes at all. They could be remaining
1151            // unexpanded attributes used as markers in proc-macro derives for example.
1152            // This will have emitted some diagnostics for the misparse, but will then
1153            // not emit the attribute making the list empty.
1154            if ret.is_empty() {
1155                &[]
1156            } else {
1157                self.attrs.insert(id.local_id, ret);
1158                ret
1159            }
1160        }
1161    }
1162
1163    fn lower_attrs_vec(
1164        &mut self,
1165        attrs: &[Attribute],
1166        target_span: Span,
1167        target_hir_id: HirId,
1168        target: Target,
1169    ) -> Vec<hir::Attribute> {
1170        let l = self.span_lowerer();
1171        self.attribute_parser.parse_attribute_list(
1172            attrs,
1173            target_span,
1174            target,
1175            OmitDoc::Lower,
1176            |s| l.lower(s),
1177            |lint_id, span, kind| match kind {
1178                EmitAttribute::Static(attr_kind) => {
1179                    self.delayed_lints.push(DelayedLint::AttributeParsing(AttributeLint {
1180                        lint_id,
1181                        id: target_hir_id,
1182                        span,
1183                        kind: attr_kind,
1184                    }));
1185                }
1186                EmitAttribute::Dynamic(callback) => {
1187                    self.delayed_lints.push(DelayedLint::Dynamic(DynAttribute {
1188                        lint_id,
1189                        id: target_hir_id,
1190                        span,
1191                        callback,
1192                    }));
1193                }
1194            },
1195        )
1196    }
1197
1198    fn alias_attrs(&mut self, id: HirId, target_id: HirId) {
1199        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);
1200        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);
1201        if let Some(&a) = self.attrs.get(&target_id.local_id) {
1202            if !!a.is_empty() {
    ::core::panicking::panic("assertion failed: !a.is_empty()")
};assert!(!a.is_empty());
1203            self.attrs.insert(id.local_id, a);
1204        }
1205    }
1206
1207    fn lower_delim_args(&self, args: &DelimArgs) -> DelimArgs {
1208        args.clone()
1209    }
1210
1211    /// Lower an associated item constraint.
1212    #[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(1212u32),
                                    ::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:1218",
                                    "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(1218u32),
                                    ::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)]
1213    fn lower_assoc_item_constraint(
1214        &mut self,
1215        constraint: &AssocItemConstraint,
1216        itctx: ImplTraitContext,
1217    ) -> hir::AssocItemConstraint<'hir> {
1218        debug!(?constraint, ?itctx);
1219        // Lower the generic arguments for the associated item.
1220        let gen_args = if let Some(gen_args) = &constraint.gen_args {
1221            let gen_args_ctor = match gen_args {
1222                GenericArgs::AngleBracketed(data) => {
1223                    self.lower_angle_bracketed_parameter_data(data, ParamMode::Explicit, itctx).0
1224                }
1225                GenericArgs::Parenthesized(data) => {
1226                    if let Some(first_char) = constraint.ident.as_str().chars().next()
1227                        && first_char.is_ascii_lowercase()
1228                    {
1229                        let err = match (&data.inputs[..], &data.output) {
1230                            ([_, ..], FnRetTy::Default(_)) => {
1231                                errors::BadReturnTypeNotation::Inputs { span: data.inputs_span }
1232                            }
1233                            ([], FnRetTy::Default(_)) => {
1234                                errors::BadReturnTypeNotation::NeedsDots { span: data.inputs_span }
1235                            }
1236                            // The case `T: Trait<method(..) -> Ret>` is handled in the parser.
1237                            (_, FnRetTy::Ty(ty)) => {
1238                                let span = data.inputs_span.shrink_to_hi().to(ty.span);
1239                                errors::BadReturnTypeNotation::Output {
1240                                    span,
1241                                    suggestion: errors::RTNSuggestion {
1242                                        output: span,
1243                                        input: data.inputs_span,
1244                                    },
1245                                }
1246                            }
1247                        };
1248                        let mut err = self.dcx().create_err(err);
1249                        if !self.tcx.features().return_type_notation()
1250                            && self.tcx.sess.is_nightly_build()
1251                        {
1252                            add_feature_diagnostics(
1253                                &mut err,
1254                                &self.tcx.sess,
1255                                sym::return_type_notation,
1256                            );
1257                        }
1258                        err.emit();
1259                        GenericArgsCtor {
1260                            args: Default::default(),
1261                            constraints: &[],
1262                            parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
1263                            span: data.span,
1264                        }
1265                    } else {
1266                        self.emit_bad_parenthesized_trait_in_assoc_ty(data);
1267                        // FIXME(return_type_notation): we could issue a feature error
1268                        // if the parens are empty and there's no return type.
1269                        self.lower_angle_bracketed_parameter_data(
1270                            &data.as_angle_bracketed_args(),
1271                            ParamMode::Explicit,
1272                            itctx,
1273                        )
1274                        .0
1275                    }
1276                }
1277                GenericArgs::ParenthesizedElided(span) => GenericArgsCtor {
1278                    args: Default::default(),
1279                    constraints: &[],
1280                    parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
1281                    span: *span,
1282                },
1283            };
1284            gen_args_ctor.into_generic_args(self)
1285        } else {
1286            hir::GenericArgs::NONE
1287        };
1288        let kind = match &constraint.kind {
1289            AssocItemConstraintKind::Equality { term } => {
1290                let term = match term {
1291                    Term::Ty(ty) => self.lower_ty_alloc(ty, itctx).into(),
1292                    Term::Const(c) => self.lower_anon_const_to_const_arg_and_alloc(c).into(),
1293                };
1294                hir::AssocItemConstraintKind::Equality { term }
1295            }
1296            AssocItemConstraintKind::Bound { bounds } => {
1297                // Disallow ATB in dyn types
1298                if self.is_in_dyn_type {
1299                    let suggestion = match itctx {
1300                        ImplTraitContext::OpaqueTy { .. } | ImplTraitContext::Universal => {
1301                            let bound_end_span = constraint
1302                                .gen_args
1303                                .as_ref()
1304                                .map_or(constraint.ident.span, |args| args.span());
1305                            if bound_end_span.eq_ctxt(constraint.span) {
1306                                Some(self.tcx.sess.source_map().next_point(bound_end_span))
1307                            } else {
1308                                None
1309                            }
1310                        }
1311                        _ => None,
1312                    };
1313
1314                    let guar = self.dcx().emit_err(errors::MisplacedAssocTyBinding {
1315                        span: constraint.span,
1316                        suggestion,
1317                    });
1318                    let err_ty =
1319                        &*self.arena.alloc(self.ty(constraint.span, hir::TyKind::Err(guar)));
1320                    hir::AssocItemConstraintKind::Equality { term: err_ty.into() }
1321                } else {
1322                    let bounds = self.lower_param_bounds(
1323                        bounds,
1324                        RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::AssocTyBounds),
1325                        itctx,
1326                    );
1327                    hir::AssocItemConstraintKind::Bound { bounds }
1328                }
1329            }
1330        };
1331
1332        hir::AssocItemConstraint {
1333            hir_id: self.lower_node_id(constraint.id),
1334            ident: self.lower_ident(constraint.ident),
1335            gen_args,
1336            kind,
1337            span: self.lower_span(constraint.span),
1338        }
1339    }
1340
1341    fn emit_bad_parenthesized_trait_in_assoc_ty(&self, data: &ParenthesizedArgs) {
1342        // Suggest removing empty parentheses: "Trait()" -> "Trait"
1343        let sub = if data.inputs.is_empty() {
1344            let parentheses_span =
1345                data.inputs_span.shrink_to_lo().to(data.inputs_span.shrink_to_hi());
1346            AssocTyParenthesesSub::Empty { parentheses_span }
1347        }
1348        // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
1349        else {
1350            // Start of parameters to the 1st argument
1351            let open_param = data.inputs_span.shrink_to_lo().to(data
1352                .inputs
1353                .first()
1354                .unwrap()
1355                .span
1356                .shrink_to_lo());
1357            // End of last argument to end of parameters
1358            let close_param =
1359                data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi());
1360            AssocTyParenthesesSub::NotEmpty { open_param, close_param }
1361        };
1362        self.dcx().emit_err(AssocTyParentheses { span: data.span, sub });
1363    }
1364
1365    #[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(1365u32),
                                    ::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:1403",
                                                            "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(1403u32),
                                                            ::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))]
1366    fn lower_generic_arg(
1367        &mut self,
1368        arg: &ast::GenericArg,
1369        itctx: ImplTraitContext,
1370    ) -> hir::GenericArg<'hir> {
1371        match arg {
1372            ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(
1373                lt,
1374                LifetimeSource::Path { angle_brackets: hir::AngleBrackets::Full },
1375                lt.ident.into(),
1376            )),
1377            ast::GenericArg::Type(ty) => {
1378                // We cannot just match on `TyKind::Infer` as `(_)` is represented as
1379                // `TyKind::Paren(TyKind::Infer)` and should also be lowered to `GenericArg::Infer`
1380                if ty.is_maybe_parenthesised_infer() {
1381                    return GenericArg::Infer(hir::InferArg {
1382                        hir_id: self.lower_node_id(ty.id),
1383                        span: self.lower_span(ty.span),
1384                    });
1385                }
1386
1387                match &ty.kind {
1388                    // We parse const arguments as path types as we cannot distinguish them during
1389                    // parsing. We try to resolve that ambiguity by attempting resolution in both the
1390                    // type and value namespaces. If we resolved the path in the value namespace, we
1391                    // transform it into a generic const argument.
1392                    //
1393                    // FIXME: Should we be handling `(PATH_TO_CONST)`?
1394                    TyKind::Path(None, path) => {
1395                        if let Some(res) = self
1396                            .resolver
1397                            .get_partial_res(ty.id)
1398                            .and_then(|partial_res| partial_res.full_res())
1399                        {
1400                            if !res.matches_ns(Namespace::TypeNS)
1401                                && path.is_potential_trivial_const_arg()
1402                            {
1403                                debug!(
1404                                    "lower_generic_arg: Lowering type argument as const argument: {:?}",
1405                                    ty,
1406                                );
1407
1408                                let ct =
1409                                    self.lower_const_path_to_const_arg(path, res, ty.id, ty.span);
1410                                return GenericArg::Const(ct.try_as_ambig_ct().unwrap());
1411                            }
1412                        }
1413                    }
1414                    _ => {}
1415                }
1416                GenericArg::Type(self.lower_ty_alloc(ty, itctx).try_as_ambig_ty().unwrap())
1417            }
1418            ast::GenericArg::Const(ct) => {
1419                let ct = self.lower_anon_const_to_const_arg_and_alloc(ct);
1420                match ct.try_as_ambig_ct() {
1421                    Some(ct) => GenericArg::Const(ct),
1422                    None => GenericArg::Infer(hir::InferArg { hir_id: ct.hir_id, span: ct.span }),
1423                }
1424            }
1425        }
1426    }
1427
1428    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lower_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(1428u32),
                                    ::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))]
1429    fn lower_ty_alloc(&mut self, t: &Ty, itctx: ImplTraitContext) -> &'hir hir::Ty<'hir> {
1430        self.arena.alloc(self.lower_ty(t, itctx))
1431    }
1432
1433    fn lower_path_ty(
1434        &mut self,
1435        t: &Ty,
1436        qself: &Option<Box<QSelf>>,
1437        path: &Path,
1438        param_mode: ParamMode,
1439        itctx: ImplTraitContext,
1440    ) -> hir::Ty<'hir> {
1441        // Check whether we should interpret this as a bare trait object.
1442        // This check mirrors the one in late resolution. We only introduce this special case in
1443        // the rare occurrence we need to lower `Fresh` anonymous lifetimes.
1444        // The other cases when a qpath should be opportunistically made a trait object are handled
1445        // by `ty_path`.
1446        if qself.is_none()
1447            && let Some(partial_res) = self.resolver.get_partial_res(t.id)
1448            && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res()
1449        {
1450            let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1451                let bound = this.lower_poly_trait_ref(
1452                    &PolyTraitRef {
1453                        bound_generic_params: ThinVec::new(),
1454                        modifiers: TraitBoundModifiers::NONE,
1455                        trait_ref: TraitRef { path: path.clone(), ref_id: t.id },
1456                        span: t.span,
1457                        parens: ast::Parens::No,
1458                    },
1459                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitObjectTy),
1460                    itctx,
1461                );
1462                let bounds = this.arena.alloc_from_iter([bound]);
1463                let lifetime_bound = this.elided_dyn_bound(t.span);
1464                (bounds, lifetime_bound)
1465            });
1466            let kind = hir::TyKind::TraitObject(
1467                bounds,
1468                TaggedRef::new(lifetime_bound, TraitObjectSyntax::None),
1469            );
1470            return hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.next_id() };
1471        }
1472
1473        let id = self.lower_node_id(t.id);
1474        let qpath = self.lower_qpath(
1475            t.id,
1476            qself,
1477            path,
1478            param_mode,
1479            AllowReturnTypeNotation::Yes,
1480            itctx,
1481            None,
1482        );
1483        self.ty_path(id, t.span, qpath)
1484    }
1485
1486    fn ty(&mut self, span: Span, kind: hir::TyKind<'hir>) -> hir::Ty<'hir> {
1487        hir::Ty { hir_id: self.next_id(), kind, span: self.lower_span(span) }
1488    }
1489
1490    fn ty_tup(&mut self, span: Span, tys: &'hir [hir::Ty<'hir>]) -> hir::Ty<'hir> {
1491        self.ty(span, hir::TyKind::Tup(tys))
1492    }
1493
1494    fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> hir::Ty<'hir> {
1495        let kind = match &t.kind {
1496            TyKind::Infer => hir::TyKind::Infer(()),
1497            TyKind::Err(guar) => hir::TyKind::Err(*guar),
1498            TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty_alloc(ty, itctx)),
1499            TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
1500            TyKind::Ref(region, mt) => {
1501                let lifetime = self.lower_ty_direct_lifetime(t, *region);
1502                hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx))
1503            }
1504            TyKind::PinnedRef(region, mt) => {
1505                let lifetime = self.lower_ty_direct_lifetime(t, *region);
1506                let kind = hir::TyKind::Ref(lifetime, self.lower_mt(mt, itctx));
1507                let span = self.lower_span(t.span);
1508                let arg = hir::Ty { kind, span, hir_id: self.next_id() };
1509                let args = self.arena.alloc(hir::GenericArgs {
1510                    args: self.arena.alloc([hir::GenericArg::Type(self.arena.alloc(arg))]),
1511                    constraints: &[],
1512                    parenthesized: hir::GenericArgsParentheses::No,
1513                    span_ext: span,
1514                });
1515                let path = self.make_lang_item_qpath(hir::LangItem::Pin, span, Some(args));
1516                hir::TyKind::Path(path)
1517            }
1518            TyKind::FnPtr(f) => {
1519                let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1520                hir::TyKind::FnPtr(self.arena.alloc(hir::FnPtrTy {
1521                    generic_params,
1522                    safety: self.lower_safety(f.safety, hir::Safety::Safe),
1523                    abi: self.lower_extern(f.ext),
1524                    decl: self.lower_fn_decl(&f.decl, t.id, t.span, FnDeclKind::Pointer, None),
1525                    param_idents: self.lower_fn_params_to_idents(&f.decl),
1526                }))
1527            }
1528            TyKind::UnsafeBinder(f) => {
1529                let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
1530                hir::TyKind::UnsafeBinder(self.arena.alloc(hir::UnsafeBinderTy {
1531                    generic_params,
1532                    inner_ty: self.lower_ty_alloc(&f.inner_ty, itctx),
1533                }))
1534            }
1535            TyKind::Never => hir::TyKind::Never,
1536            TyKind::Tup(tys) => hir::TyKind::Tup(
1537                self.arena.alloc_from_iter(tys.iter().map(|ty| self.lower_ty(ty, itctx))),
1538            ),
1539            TyKind::Paren(ty) => {
1540                return self.lower_ty(ty, itctx);
1541            }
1542            TyKind::Path(qself, path) => {
1543                return self.lower_path_ty(t, qself, path, ParamMode::Explicit, itctx);
1544            }
1545            TyKind::ImplicitSelf => {
1546                let hir_id = self.next_id();
1547                let res = self.expect_full_res(t.id);
1548                let res = self.lower_res(res);
1549                hir::TyKind::Path(hir::QPath::Resolved(
1550                    None,
1551                    self.arena.alloc(hir::Path {
1552                        res,
1553                        segments: self.arena.alloc_from_iter([hir::PathSegment::new(Ident::with_dummy_span(kw::SelfUpper),
                hir_id, res)])arena_vec![self; hir::PathSegment::new(
1554                            Ident::with_dummy_span(kw::SelfUpper),
1555                            hir_id,
1556                            res
1557                        )],
1558                        span: self.lower_span(t.span),
1559                    }),
1560                ))
1561            }
1562            TyKind::Array(ty, length) => hir::TyKind::Array(
1563                self.lower_ty_alloc(ty, itctx),
1564                self.lower_array_length_to_const_arg(length),
1565            ),
1566            TyKind::TraitObject(bounds, kind) => {
1567                let mut lifetime_bound = None;
1568                let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
1569                    let bounds =
1570                        this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| match bound {
1571                            // We can safely ignore constness here since AST validation
1572                            // takes care of rejecting invalid modifier combinations and
1573                            // const trait bounds in trait object types.
1574                            GenericBound::Trait(ty) => {
1575                                let trait_ref = this.lower_poly_trait_ref(
1576                                    ty,
1577                                    RelaxedBoundPolicy::Forbidden(
1578                                        RelaxedBoundForbiddenReason::TraitObjectTy,
1579                                    ),
1580                                    itctx,
1581                                );
1582                                Some(trait_ref)
1583                            }
1584                            GenericBound::Outlives(lifetime) => {
1585                                if lifetime_bound.is_none() {
1586                                    lifetime_bound = Some(this.lower_lifetime(
1587                                        lifetime,
1588                                        LifetimeSource::Other,
1589                                        lifetime.ident.into(),
1590                                    ));
1591                                }
1592                                None
1593                            }
1594                            // Ignore `use` syntax since that is not valid in objects.
1595                            GenericBound::Use(_, span) => {
1596                                this.dcx()
1597                                    .span_delayed_bug(*span, "use<> not allowed in dyn types");
1598                                None
1599                            }
1600                        }));
1601                    let lifetime_bound =
1602                        lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span));
1603                    (bounds, lifetime_bound)
1604                });
1605                hir::TyKind::TraitObject(bounds, TaggedRef::new(lifetime_bound, *kind))
1606            }
1607            TyKind::ImplTrait(def_node_id, bounds) => {
1608                let span = t.span;
1609                match itctx {
1610                    ImplTraitContext::OpaqueTy { origin } => {
1611                        self.lower_opaque_impl_trait(span, origin, *def_node_id, bounds, itctx)
1612                    }
1613                    ImplTraitContext::Universal => {
1614                        if let Some(span) = bounds.iter().find_map(|bound| match *bound {
1615                            ast::GenericBound::Use(_, span) => Some(span),
1616                            _ => None,
1617                        }) {
1618                            self.tcx.dcx().emit_err(errors::NoPreciseCapturesOnApit { span });
1619                        }
1620
1621                        let def_id = self.local_def_id(*def_node_id);
1622                        let name = self.tcx.item_name(def_id.to_def_id());
1623                        let ident = Ident::new(name, span);
1624                        let (param, bounds, path) = self.lower_universal_param_and_bounds(
1625                            *def_node_id,
1626                            span,
1627                            ident,
1628                            bounds,
1629                        );
1630                        self.impl_trait_defs.push(param);
1631                        if let Some(bounds) = bounds {
1632                            self.impl_trait_bounds.push(bounds);
1633                        }
1634                        path
1635                    }
1636                    ImplTraitContext::InBinding => hir::TyKind::TraitAscription(
1637                        self.lower_param_bounds(bounds, RelaxedBoundPolicy::Allowed, itctx),
1638                    ),
1639                    ImplTraitContext::FeatureGated(position, feature) => {
1640                        let guar = self
1641                            .tcx
1642                            .sess
1643                            .create_feature_err(
1644                                MisplacedImplTrait {
1645                                    span: t.span,
1646                                    position: DiagArgFromDisplay(&position),
1647                                },
1648                                feature,
1649                            )
1650                            .emit();
1651                        hir::TyKind::Err(guar)
1652                    }
1653                    ImplTraitContext::Disallowed(position) => {
1654                        let guar = self.dcx().emit_err(MisplacedImplTrait {
1655                            span: t.span,
1656                            position: DiagArgFromDisplay(&position),
1657                        });
1658                        hir::TyKind::Err(guar)
1659                    }
1660                }
1661            }
1662            TyKind::Pat(ty, pat) => {
1663                hir::TyKind::Pat(self.lower_ty_alloc(ty, itctx), self.lower_ty_pat(pat, ty.span))
1664            }
1665            TyKind::FieldOf(ty, variant, field) => hir::TyKind::FieldOf(
1666                self.lower_ty_alloc(ty, itctx),
1667                self.arena.alloc(hir::TyFieldPath {
1668                    variant: variant.map(|variant| self.lower_ident(variant)),
1669                    field: self.lower_ident(*field),
1670                }),
1671            ),
1672            TyKind::MacCall(_) => {
1673                ::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")
1674            }
1675            TyKind::CVarArgs => {
1676                let guar = self.dcx().span_delayed_bug(
1677                    t.span,
1678                    "`TyKind::CVarArgs` should have been handled elsewhere",
1679                );
1680                hir::TyKind::Err(guar)
1681            }
1682            TyKind::Dummy => {
    ::core::panicking::panic_fmt(format_args!("`TyKind::Dummy` should never be lowered"));
}panic!("`TyKind::Dummy` should never be lowered"),
1683        };
1684
1685        hir::Ty { kind, span: self.lower_span(t.span), hir_id: self.lower_node_id(t.id) }
1686    }
1687
1688    fn lower_ty_direct_lifetime(
1689        &mut self,
1690        t: &Ty,
1691        region: Option<Lifetime>,
1692    ) -> &'hir hir::Lifetime {
1693        let (region, syntax) = match region {
1694            Some(region) => (region, region.ident.into()),
1695
1696            None => {
1697                let id = if let Some(LifetimeRes::ElidedAnchor { start, end }) =
1698                    self.resolver.get_lifetime_res(t.id)
1699                {
1700                    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);
1701                    start
1702                } else {
1703                    self.next_node_id()
1704                };
1705                let span = self.tcx.sess.source_map().start_point(t.span).shrink_to_hi();
1706                let region = Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id };
1707                (region, LifetimeSyntax::Implicit)
1708            }
1709        };
1710        self.lower_lifetime(&region, LifetimeSource::Reference, syntax)
1711    }
1712
1713    /// Lowers a `ReturnPositionOpaqueTy` (`-> impl Trait`) or a `TypeAliasesOpaqueTy` (`type F =
1714    /// impl Trait`): this creates the associated Opaque Type (TAIT) definition and then returns a
1715    /// HIR type that references the TAIT.
1716    ///
1717    /// Given a function definition like:
1718    ///
1719    /// ```rust
1720    /// use std::fmt::Debug;
1721    ///
1722    /// fn test<'a, T: Debug>(x: &'a T) -> impl Debug + 'a {
1723    ///     x
1724    /// }
1725    /// ```
1726    ///
1727    /// we will create a TAIT definition in the HIR like
1728    ///
1729    /// ```rust,ignore (pseudo-Rust)
1730    /// type TestReturn<'a, T, 'x> = impl Debug + 'x
1731    /// ```
1732    ///
1733    /// and return a type like `TestReturn<'static, T, 'a>`, so that the function looks like:
1734    ///
1735    /// ```rust,ignore (pseudo-Rust)
1736    /// fn test<'a, T: Debug>(x: &'a T) -> TestReturn<'static, T, 'a>
1737    /// ```
1738    ///
1739    /// Note the subtlety around type parameters! The new TAIT, `TestReturn`, inherits all the
1740    /// type parameters from the function `test` (this is implemented in the query layer, they aren't
1741    /// added explicitly in the HIR). But this includes all the lifetimes, and we only want to
1742    /// capture the lifetimes that are referenced in the bounds. Therefore, we add *extra* lifetime parameters
1743    /// for the lifetimes that get captured (`'x`, in our example above) and reference those.
1744    x;#[instrument(level = "debug", skip(self), ret)]
1745    fn lower_opaque_impl_trait(
1746        &mut self,
1747        span: Span,
1748        origin: hir::OpaqueTyOrigin<LocalDefId>,
1749        opaque_ty_node_id: NodeId,
1750        bounds: &GenericBounds,
1751        itctx: ImplTraitContext,
1752    ) -> hir::TyKind<'hir> {
1753        // Make sure we know that some funky desugaring has been going on here.
1754        // This is a first: there is code in other places like for loop
1755        // desugaring that explicitly states that we don't want to track that.
1756        // Not tracking it makes lints in rustc and clippy very fragile, as
1757        // frequently opened issues show.
1758        let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
1759
1760        self.lower_opaque_inner(opaque_ty_node_id, origin, opaque_ty_span, |this| {
1761            this.lower_param_bounds(bounds, RelaxedBoundPolicy::Allowed, itctx)
1762        })
1763    }
1764
1765    fn lower_opaque_inner(
1766        &mut self,
1767        opaque_ty_node_id: NodeId,
1768        origin: hir::OpaqueTyOrigin<LocalDefId>,
1769        opaque_ty_span: Span,
1770        lower_item_bounds: impl FnOnce(&mut Self) -> &'hir [hir::GenericBound<'hir>],
1771    ) -> hir::TyKind<'hir> {
1772        let opaque_ty_def_id = self.local_def_id(opaque_ty_node_id);
1773        let opaque_ty_hir_id = self.lower_node_id(opaque_ty_node_id);
1774        {
    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:1774",
                        "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(1774u32),
                        ::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);
1775
1776        let bounds = lower_item_bounds(self);
1777        let opaque_ty_def = hir::OpaqueTy {
1778            hir_id: opaque_ty_hir_id,
1779            def_id: opaque_ty_def_id,
1780            bounds,
1781            origin,
1782            span: self.lower_span(opaque_ty_span),
1783        };
1784        let opaque_ty_def = self.arena.alloc(opaque_ty_def);
1785
1786        hir::TyKind::OpaqueDef(opaque_ty_def)
1787    }
1788
1789    fn lower_precise_capturing_args(
1790        &mut self,
1791        precise_capturing_args: &[PreciseCapturingArg],
1792    ) -> &'hir [hir::PreciseCapturingArg<'hir>] {
1793        self.arena.alloc_from_iter(precise_capturing_args.iter().map(|arg| match arg {
1794            PreciseCapturingArg::Lifetime(lt) => hir::PreciseCapturingArg::Lifetime(
1795                self.lower_lifetime(lt, LifetimeSource::PreciseCapturing, lt.ident.into()),
1796            ),
1797            PreciseCapturingArg::Arg(path, id) => {
1798                let [segment] = path.segments.as_slice() else {
1799                    ::core::panicking::panic("explicit panic");panic!();
1800                };
1801                let res = self.resolver.get_partial_res(*id).map_or(Res::Err, |partial_res| {
1802                    partial_res.full_res().expect("no partial res expected for precise capture arg")
1803                });
1804                hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
1805                    hir_id: self.lower_node_id(*id),
1806                    ident: self.lower_ident(segment.ident),
1807                    res: self.lower_res(res),
1808                })
1809            }
1810        }))
1811    }
1812
1813    fn lower_fn_params_to_idents(&mut self, decl: &FnDecl) -> &'hir [Option<Ident>] {
1814        self.arena.alloc_from_iter(decl.inputs.iter().map(|param| match param.pat.kind {
1815            PatKind::Missing => None,
1816            PatKind::Ident(_, ident, _) => Some(self.lower_ident(ident)),
1817            PatKind::Wild => Some(Ident::new(kw::Underscore, self.lower_span(param.pat.span))),
1818            _ => {
1819                self.dcx().span_delayed_bug(
1820                    param.pat.span,
1821                    "non-missing/ident/wild param pat must trigger an error",
1822                );
1823                None
1824            }
1825        }))
1826    }
1827
1828    /// Lowers a function declaration.
1829    ///
1830    /// `decl`: the unlowered (AST) function declaration.
1831    ///
1832    /// `fn_node_id`: `impl Trait` arguments are lowered into generic parameters on the given
1833    /// `NodeId`.
1834    ///
1835    /// `transform_return_type`: if `Some`, applies some conversion to the return type, such as is
1836    /// needed for `async fn` and `gen fn`. See [`CoroutineKind`] for more details.
1837    #[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(1837u32),
                                    ::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))]
1838    fn lower_fn_decl(
1839        &mut self,
1840        decl: &FnDecl,
1841        fn_node_id: NodeId,
1842        fn_span: Span,
1843        kind: FnDeclKind,
1844        coro: Option<CoroutineKind>,
1845    ) -> &'hir hir::FnDecl<'hir> {
1846        let c_variadic = decl.c_variadic();
1847
1848        // Skip the `...` (`CVarArgs`) trailing arguments from the AST,
1849        // as they are not explicit in HIR/Ty function signatures.
1850        // (instead, the `c_variadic` flag is set to `true`)
1851        let mut inputs = &decl.inputs[..];
1852        if c_variadic {
1853            inputs = &inputs[..inputs.len() - 1];
1854        }
1855        let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
1856            let itctx = match kind {
1857                FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait => {
1858                    ImplTraitContext::Universal
1859                }
1860                FnDeclKind::ExternFn => {
1861                    ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnParam)
1862                }
1863                FnDeclKind::Closure => {
1864                    ImplTraitContext::Disallowed(ImplTraitPosition::ClosureParam)
1865                }
1866                FnDeclKind::Pointer => {
1867                    ImplTraitContext::Disallowed(ImplTraitPosition::PointerParam)
1868                }
1869            };
1870            self.lower_ty(&param.ty, itctx)
1871        }));
1872
1873        let output = match coro {
1874            Some(coro) => {
1875                let fn_def_id = self.local_def_id(fn_node_id);
1876                self.lower_coroutine_fn_ret_ty(&decl.output, fn_def_id, coro, kind)
1877            }
1878            None => match &decl.output {
1879                FnRetTy::Ty(ty) => {
1880                    let itctx = match kind {
1881                        FnDeclKind::Fn | FnDeclKind::Inherent => ImplTraitContext::OpaqueTy {
1882                            origin: hir::OpaqueTyOrigin::FnReturn {
1883                                parent: self.local_def_id(fn_node_id),
1884                                in_trait_or_impl: None,
1885                            },
1886                        },
1887                        FnDeclKind::Trait => ImplTraitContext::OpaqueTy {
1888                            origin: hir::OpaqueTyOrigin::FnReturn {
1889                                parent: self.local_def_id(fn_node_id),
1890                                in_trait_or_impl: Some(hir::RpitContext::Trait),
1891                            },
1892                        },
1893                        FnDeclKind::Impl => ImplTraitContext::OpaqueTy {
1894                            origin: hir::OpaqueTyOrigin::FnReturn {
1895                                parent: self.local_def_id(fn_node_id),
1896                                in_trait_or_impl: Some(hir::RpitContext::TraitImpl),
1897                            },
1898                        },
1899                        FnDeclKind::ExternFn => {
1900                            ImplTraitContext::Disallowed(ImplTraitPosition::ExternFnReturn)
1901                        }
1902                        FnDeclKind::Closure => {
1903                            ImplTraitContext::Disallowed(ImplTraitPosition::ClosureReturn)
1904                        }
1905                        FnDeclKind::Pointer => {
1906                            ImplTraitContext::Disallowed(ImplTraitPosition::PointerReturn)
1907                        }
1908                    };
1909                    hir::FnRetTy::Return(self.lower_ty_alloc(ty, itctx))
1910                }
1911                FnRetTy::Default(span) => hir::FnRetTy::DefaultReturn(self.lower_span(*span)),
1912            },
1913        };
1914
1915        self.arena.alloc(hir::FnDecl {
1916            inputs,
1917            output,
1918            c_variadic,
1919            lifetime_elision_allowed: self.resolver.lifetime_elision_allowed(fn_node_id),
1920            implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
1921                let is_mutable_pat = matches!(
1922                    arg.pat.kind,
1923                    PatKind::Ident(hir::BindingMode(_, Mutability::Mut), ..)
1924                );
1925
1926                match &arg.ty.kind {
1927                    TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut,
1928                    TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm,
1929                    // Given we are only considering `ImplicitSelf` types, we needn't consider
1930                    // the case where we have a mutable pattern to a reference as that would
1931                    // no longer be an `ImplicitSelf`.
1932                    TyKind::Ref(_, mt) | TyKind::PinnedRef(_, mt)
1933                        if mt.ty.kind.is_implicit_self() =>
1934                    {
1935                        match mt.mutbl {
1936                            hir::Mutability::Not => hir::ImplicitSelfKind::RefImm,
1937                            hir::Mutability::Mut => hir::ImplicitSelfKind::RefMut,
1938                        }
1939                    }
1940                    _ => hir::ImplicitSelfKind::None,
1941                }
1942            }),
1943        })
1944    }
1945
1946    // Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
1947    // combined with the following definition of `OpaqueTy`:
1948    //
1949    //     type OpaqueTy<generics_from_parent_fn> = impl Future<Output = T>;
1950    //
1951    // `output`: unlowered output type (`T` in `-> T`)
1952    // `fn_node_id`: `NodeId` of the parent function (used to create child impl trait definition)
1953    // `opaque_ty_node_id`: `NodeId` of the opaque `impl Trait` type that should be created
1954    #[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(1954u32),
                                    ::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))]
1955    fn lower_coroutine_fn_ret_ty(
1956        &mut self,
1957        output: &FnRetTy,
1958        fn_def_id: LocalDefId,
1959        coro: CoroutineKind,
1960        fn_kind: FnDeclKind,
1961    ) -> hir::FnRetTy<'hir> {
1962        let span = self.lower_span(output.span());
1963
1964        let (opaque_ty_node_id, allowed_features) = match coro {
1965            CoroutineKind::Async { return_impl_trait_id, .. } => (return_impl_trait_id, None),
1966            CoroutineKind::Gen { return_impl_trait_id, .. } => (return_impl_trait_id, None),
1967            CoroutineKind::AsyncGen { return_impl_trait_id, .. } => {
1968                (return_impl_trait_id, Some(Arc::clone(&self.allow_async_iterator)))
1969            }
1970        };
1971
1972        let opaque_ty_span =
1973            self.mark_span_with_reason(DesugaringKind::Async, span, allowed_features);
1974
1975        let in_trait_or_impl = match fn_kind {
1976            FnDeclKind::Trait => Some(hir::RpitContext::Trait),
1977            FnDeclKind::Impl => Some(hir::RpitContext::TraitImpl),
1978            FnDeclKind::Fn | FnDeclKind::Inherent => None,
1979            FnDeclKind::ExternFn | FnDeclKind::Closure | FnDeclKind::Pointer => unreachable!(),
1980        };
1981
1982        let opaque_ty_ref = self.lower_opaque_inner(
1983            opaque_ty_node_id,
1984            hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, in_trait_or_impl },
1985            opaque_ty_span,
1986            |this| {
1987                let bound = this.lower_coroutine_fn_output_type_to_bound(
1988                    output,
1989                    coro,
1990                    opaque_ty_span,
1991                    ImplTraitContext::OpaqueTy {
1992                        origin: hir::OpaqueTyOrigin::FnReturn {
1993                            parent: fn_def_id,
1994                            in_trait_or_impl,
1995                        },
1996                    },
1997                );
1998                arena_vec![this; bound]
1999            },
2000        );
2001
2002        let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref);
2003        hir::FnRetTy::Return(self.arena.alloc(opaque_ty))
2004    }
2005
2006    /// Transforms `-> T` into `Future<Output = T>`.
2007    fn lower_coroutine_fn_output_type_to_bound(
2008        &mut self,
2009        output: &FnRetTy,
2010        coro: CoroutineKind,
2011        opaque_ty_span: Span,
2012        itctx: ImplTraitContext,
2013    ) -> hir::GenericBound<'hir> {
2014        // Compute the `T` in `Future<Output = T>` from the return type.
2015        let output_ty = match output {
2016            FnRetTy::Ty(ty) => {
2017                // Not `OpaqueTyOrigin::AsyncFn`: that's only used for the
2018                // `impl Future` opaque type that `async fn` implicitly
2019                // generates.
2020                self.lower_ty_alloc(ty, itctx)
2021            }
2022            FnRetTy::Default(ret_ty_span) => self.arena.alloc(self.ty_tup(*ret_ty_span, &[])),
2023        };
2024
2025        // "<$assoc_ty_name = T>"
2026        let (assoc_ty_name, trait_lang_item) = match coro {
2027            CoroutineKind::Async { .. } => (sym::Output, hir::LangItem::Future),
2028            CoroutineKind::Gen { .. } => (sym::Item, hir::LangItem::Iterator),
2029            CoroutineKind::AsyncGen { .. } => (sym::Item, hir::LangItem::AsyncIterator),
2030        };
2031
2032        let bound_args = self.arena.alloc(hir::GenericArgs {
2033            args: &[],
2034            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)],
2035            parenthesized: hir::GenericArgsParentheses::No,
2036            span_ext: DUMMY_SP,
2037        });
2038
2039        hir::GenericBound::Trait(hir::PolyTraitRef {
2040            bound_generic_params: &[],
2041            modifiers: hir::TraitBoundModifiers::NONE,
2042            trait_ref: hir::TraitRef {
2043                path: self.make_lang_item_path(trait_lang_item, opaque_ty_span, Some(bound_args)),
2044                hir_ref_id: self.next_id(),
2045            },
2046            span: opaque_ty_span,
2047        })
2048    }
2049
2050    #[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(2050u32),
                                    ::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))]
2051    fn lower_param_bound(
2052        &mut self,
2053        tpb: &GenericBound,
2054        rbp: RelaxedBoundPolicy<'_>,
2055        itctx: ImplTraitContext,
2056    ) -> hir::GenericBound<'hir> {
2057        match tpb {
2058            GenericBound::Trait(p) => {
2059                hir::GenericBound::Trait(self.lower_poly_trait_ref(p, rbp, itctx))
2060            }
2061            GenericBound::Outlives(lifetime) => hir::GenericBound::Outlives(self.lower_lifetime(
2062                lifetime,
2063                LifetimeSource::OutlivesBound,
2064                lifetime.ident.into(),
2065            )),
2066            GenericBound::Use(args, span) => hir::GenericBound::Use(
2067                self.lower_precise_capturing_args(args),
2068                self.lower_span(*span),
2069            ),
2070        }
2071    }
2072
2073    fn lower_lifetime(
2074        &mut self,
2075        l: &Lifetime,
2076        source: LifetimeSource,
2077        syntax: LifetimeSyntax,
2078    ) -> &'hir hir::Lifetime {
2079        self.new_named_lifetime(l.id, l.id, l.ident, source, syntax)
2080    }
2081
2082    fn lower_lifetime_hidden_in_path(
2083        &mut self,
2084        id: NodeId,
2085        span: Span,
2086        angle_brackets: AngleBrackets,
2087    ) -> &'hir hir::Lifetime {
2088        self.new_named_lifetime(
2089            id,
2090            id,
2091            Ident::new(kw::UnderscoreLifetime, span),
2092            LifetimeSource::Path { angle_brackets },
2093            LifetimeSyntax::Implicit,
2094        )
2095    }
2096
2097    #[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(2097u32),
                                    ::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:2131",
                                    "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(2131u32),
                                    ::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))]
2098    fn new_named_lifetime(
2099        &mut self,
2100        id: NodeId,
2101        new_id: NodeId,
2102        ident: Ident,
2103        source: LifetimeSource,
2104        syntax: LifetimeSyntax,
2105    ) -> &'hir hir::Lifetime {
2106        let res = if let Some(res) = self.resolver.get_lifetime_res(id) {
2107            match res {
2108                LifetimeRes::Param { param, .. } => hir::LifetimeKind::Param(param),
2109                LifetimeRes::Fresh { param, .. } => {
2110                    assert_eq!(ident.name, kw::UnderscoreLifetime);
2111                    let param = self.local_def_id(param);
2112                    hir::LifetimeKind::Param(param)
2113                }
2114                LifetimeRes::Infer => {
2115                    assert_eq!(ident.name, kw::UnderscoreLifetime);
2116                    hir::LifetimeKind::Infer
2117                }
2118                LifetimeRes::Static { .. } => {
2119                    assert!(matches!(ident.name, kw::StaticLifetime | kw::UnderscoreLifetime));
2120                    hir::LifetimeKind::Static
2121                }
2122                LifetimeRes::Error(guar) => hir::LifetimeKind::Error(guar),
2123                LifetimeRes::ElidedAnchor { .. } => {
2124                    panic!("Unexpected `ElidedAnchar` {:?} at {:?}", ident, ident.span);
2125                }
2126            }
2127        } else {
2128            hir::LifetimeKind::Error(self.dcx().span_delayed_bug(ident.span, "unresolved lifetime"))
2129        };
2130
2131        debug!(?res);
2132        self.arena.alloc(hir::Lifetime::new(
2133            self.lower_node_id(new_id),
2134            self.lower_ident(ident),
2135            res,
2136            source,
2137            syntax,
2138        ))
2139    }
2140
2141    fn lower_generic_params_mut(
2142        &mut self,
2143        params: &[GenericParam],
2144        source: hir::GenericParamSource,
2145    ) -> impl Iterator<Item = hir::GenericParam<'hir>> {
2146        params.iter().map(move |param| self.lower_generic_param(param, source))
2147    }
2148
2149    fn lower_generic_params(
2150        &mut self,
2151        params: &[GenericParam],
2152        source: hir::GenericParamSource,
2153    ) -> &'hir [hir::GenericParam<'hir>] {
2154        self.arena.alloc_from_iter(self.lower_generic_params_mut(params, source))
2155    }
2156
2157    #[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(2157u32),
                                    ::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))]
2158    fn lower_generic_param(
2159        &mut self,
2160        param: &GenericParam,
2161        source: hir::GenericParamSource,
2162    ) -> hir::GenericParam<'hir> {
2163        let (name, kind) = self.lower_generic_param_kind(param, source);
2164
2165        let hir_id = self.lower_node_id(param.id);
2166        let param_attrs = &param.attrs;
2167        let param_span = param.span();
2168        let param = hir::GenericParam {
2169            hir_id,
2170            def_id: self.local_def_id(param.id),
2171            name,
2172            span: self.lower_span(param.span()),
2173            pure_wrt_drop: attr::contains_name(&param.attrs, sym::may_dangle),
2174            kind,
2175            colon_span: param.colon_span.map(|s| self.lower_span(s)),
2176            source,
2177        };
2178        self.lower_attrs(hir_id, param_attrs, param_span, Target::from_generic_param(&param));
2179        param
2180    }
2181
2182    fn lower_generic_param_kind(
2183        &mut self,
2184        param: &GenericParam,
2185        source: hir::GenericParamSource,
2186    ) -> (hir::ParamName, hir::GenericParamKind<'hir>) {
2187        match &param.kind {
2188            GenericParamKind::Lifetime => {
2189                // AST resolution emitted an error on those parameters, so we lower them using
2190                // `ParamName::Error`.
2191                let ident = self.lower_ident(param.ident);
2192                let param_name = if let Some(LifetimeRes::Error(..)) =
2193                    self.resolver.get_lifetime_res(param.id)
2194                {
2195                    ParamName::Error(ident)
2196                } else {
2197                    ParamName::Plain(ident)
2198                };
2199                let kind =
2200                    hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit };
2201
2202                (param_name, kind)
2203            }
2204            GenericParamKind::Type { default, .. } => {
2205                // Not only do we deny type param defaults in binders but we also map them to `None`
2206                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2207                let default = default
2208                    .as_ref()
2209                    .filter(|_| match source {
2210                        hir::GenericParamSource::Generics => true,
2211                        hir::GenericParamSource::Binder => {
2212                            self.dcx().emit_err(errors::GenericParamDefaultInBinder {
2213                                span: param.span(),
2214                            });
2215
2216                            false
2217                        }
2218                    })
2219                    .map(|def| {
2220                        self.lower_ty_alloc(
2221                            def,
2222                            ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2223                        )
2224                    });
2225
2226                let kind = hir::GenericParamKind::Type { default, synthetic: false };
2227
2228                (hir::ParamName::Plain(self.lower_ident(param.ident)), kind)
2229            }
2230            GenericParamKind::Const { ty, span: _, default } => {
2231                let ty = self.lower_ty_alloc(
2232                    ty,
2233                    ImplTraitContext::Disallowed(ImplTraitPosition::GenericDefault),
2234                );
2235
2236                // Not only do we deny const param defaults in binders but we also map them to `None`
2237                // since later compiler stages cannot handle them (and shouldn't need to be able to).
2238                let default = default
2239                    .as_ref()
2240                    .filter(|anon_const| match source {
2241                        hir::GenericParamSource::Generics => true,
2242                        hir::GenericParamSource::Binder => {
2243                            let err = errors::GenericParamDefaultInBinder { span: param.span() };
2244                            if expr::WillCreateDefIdsVisitor
2245                                .visit_expr(&anon_const.value)
2246                                .is_break()
2247                            {
2248                                // FIXME(mgca): make this non-fatal once we have a better way
2249                                // to handle nested items in anno const from binder
2250                                // Issue: https://github.com/rust-lang/rust/issues/123629
2251                                self.dcx().emit_fatal(err)
2252                            } else {
2253                                self.dcx().emit_err(err);
2254                                false
2255                            }
2256                        }
2257                    })
2258                    .map(|def| self.lower_anon_const_to_const_arg_and_alloc(def));
2259
2260                (
2261                    hir::ParamName::Plain(self.lower_ident(param.ident)),
2262                    hir::GenericParamKind::Const { ty, default },
2263                )
2264            }
2265        }
2266    }
2267
2268    fn lower_trait_ref(
2269        &mut self,
2270        modifiers: ast::TraitBoundModifiers,
2271        p: &TraitRef,
2272        itctx: ImplTraitContext,
2273    ) -> hir::TraitRef<'hir> {
2274        let path = match self.lower_qpath(
2275            p.ref_id,
2276            &None,
2277            &p.path,
2278            ParamMode::Explicit,
2279            AllowReturnTypeNotation::No,
2280            itctx,
2281            Some(modifiers),
2282        ) {
2283            hir::QPath::Resolved(None, path) => path,
2284            qpath => {
    ::core::panicking::panic_fmt(format_args!("lower_trait_ref: unexpected QPath `{0:?}`",
            qpath));
}panic!("lower_trait_ref: unexpected QPath `{qpath:?}`"),
2285        };
2286        hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) }
2287    }
2288
2289    #[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(2289u32),
                                    ::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))]
2290    fn lower_poly_trait_ref(
2291        &mut self,
2292        PolyTraitRef { bound_generic_params, modifiers, trait_ref, span, parens: _ }: &PolyTraitRef,
2293        rbp: RelaxedBoundPolicy<'_>,
2294        itctx: ImplTraitContext,
2295    ) -> hir::PolyTraitRef<'hir> {
2296        let bound_generic_params =
2297            self.lower_lifetime_binder(trait_ref.ref_id, bound_generic_params);
2298        let trait_ref = self.lower_trait_ref(*modifiers, trait_ref, itctx);
2299        let modifiers = self.lower_trait_bound_modifiers(*modifiers);
2300
2301        if let ast::BoundPolarity::Maybe(_) = modifiers.polarity {
2302            self.validate_relaxed_bound(trait_ref, *span, rbp);
2303        }
2304
2305        hir::PolyTraitRef {
2306            bound_generic_params,
2307            modifiers,
2308            trait_ref,
2309            span: self.lower_span(*span),
2310        }
2311    }
2312
2313    fn validate_relaxed_bound(
2314        &self,
2315        trait_ref: hir::TraitRef<'_>,
2316        span: Span,
2317        rbp: RelaxedBoundPolicy<'_>,
2318    ) {
2319        // Even though feature `more_maybe_bounds` enables the user to relax all default bounds
2320        // other than `Sized` in a lot more positions (thereby bypassing the given policy), we don't
2321        // want to advertise it to the user (via a feature gate error) since it's super internal.
2322        //
2323        // FIXME(more_maybe_bounds): Moreover, if we actually were to add proper default traits
2324        // (like a hypothetical `Move` or `Leak`) we would want to validate the location according
2325        // to default trait elaboration in HIR ty lowering (which depends on the specific trait in
2326        // question: E.g., `?Sized` & `?Move` most likely won't be allowed in all the same places).
2327
2328        match rbp {
2329            RelaxedBoundPolicy::Allowed => return,
2330            RelaxedBoundPolicy::AllowedIfOnTyParam(id, params) => {
2331                if let Some(res) = self.resolver.get_partial_res(id).and_then(|r| r.full_res())
2332                    && let Res::Def(DefKind::TyParam, def_id) = res
2333                    && params.iter().any(|p| def_id == self.local_def_id(p.id).to_def_id())
2334                {
2335                    return;
2336                }
2337            }
2338            RelaxedBoundPolicy::Forbidden(reason) => {
2339                let gate = |context, subject| {
2340                    let extended = self.tcx.features().more_maybe_bounds();
2341                    let is_sized = trait_ref
2342                        .trait_def_id()
2343                        .is_some_and(|def_id| self.tcx.is_lang_item(def_id, hir::LangItem::Sized));
2344
2345                    if extended && !is_sized {
2346                        return;
2347                    }
2348
2349                    let prefix = if extended { "`Sized` " } else { "" };
2350                    let mut diag = self.dcx().struct_span_err(
2351                        span,
2352                        ::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}"),
2353                    );
2354                    if is_sized {
2355                        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!(
2356                            "{subject} are not implicitly bounded by `Sized`, \
2357                             so there is nothing to relax"
2358                        ));
2359                    }
2360                    diag.emit();
2361                };
2362
2363                match reason {
2364                    RelaxedBoundForbiddenReason::TraitObjectTy => {
2365                        gate("trait object types", "trait object types");
2366                        return;
2367                    }
2368                    RelaxedBoundForbiddenReason::SuperTrait => {
2369                        gate("supertrait bounds", "traits");
2370                        return;
2371                    }
2372                    RelaxedBoundForbiddenReason::TraitAlias => {
2373                        gate("trait alias bounds", "trait aliases");
2374                        return;
2375                    }
2376                    RelaxedBoundForbiddenReason::AssocTyBounds
2377                    | RelaxedBoundForbiddenReason::LateBoundVarsInScope => {}
2378                };
2379            }
2380        }
2381
2382        self.dcx()
2383            .struct_span_err(span, "this relaxed bound is not permitted here")
2384            .with_note(
2385                "in this context, relaxed bounds are only allowed on \
2386                 type parameters defined on the closest item",
2387            )
2388            .emit();
2389    }
2390
2391    fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy<'hir> {
2392        hir::MutTy { ty: self.lower_ty_alloc(&mt.ty, itctx), mutbl: mt.mutbl }
2393    }
2394
2395    x;#[instrument(level = "debug", skip(self), ret)]
2396    fn lower_param_bounds(
2397        &mut self,
2398        bounds: &[GenericBound],
2399        rbp: RelaxedBoundPolicy<'_>,
2400        itctx: ImplTraitContext,
2401    ) -> hir::GenericBounds<'hir> {
2402        self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, rbp, itctx))
2403    }
2404
2405    fn lower_param_bounds_mut(
2406        &mut self,
2407        bounds: &[GenericBound],
2408        rbp: RelaxedBoundPolicy<'_>,
2409        itctx: ImplTraitContext,
2410    ) -> impl Iterator<Item = hir::GenericBound<'hir>> {
2411        bounds.iter().map(move |bound| self.lower_param_bound(bound, rbp, itctx))
2412    }
2413
2414    x;#[instrument(level = "debug", skip(self), ret)]
2415    fn lower_universal_param_and_bounds(
2416        &mut self,
2417        node_id: NodeId,
2418        span: Span,
2419        ident: Ident,
2420        bounds: &[GenericBound],
2421    ) -> (hir::GenericParam<'hir>, Option<hir::WherePredicate<'hir>>, hir::TyKind<'hir>) {
2422        // Add a definition for the in-band `Param`.
2423        let def_id = self.local_def_id(node_id);
2424        let span = self.lower_span(span);
2425
2426        // Set the name to `impl Bound1 + Bound2`.
2427        let param = hir::GenericParam {
2428            hir_id: self.lower_node_id(node_id),
2429            def_id,
2430            name: ParamName::Plain(self.lower_ident(ident)),
2431            pure_wrt_drop: false,
2432            span,
2433            kind: hir::GenericParamKind::Type { default: None, synthetic: true },
2434            colon_span: None,
2435            source: hir::GenericParamSource::Generics,
2436        };
2437
2438        let preds = self.lower_generic_bound_predicate(
2439            ident,
2440            node_id,
2441            &GenericParamKind::Type { default: None },
2442            bounds,
2443            /* colon_span */ None,
2444            span,
2445            RelaxedBoundPolicy::Allowed,
2446            ImplTraitContext::Universal,
2447            hir::PredicateOrigin::ImplTrait,
2448        );
2449
2450        let hir_id = self.next_id();
2451        let res = Res::Def(DefKind::TyParam, def_id.to_def_id());
2452        let ty = hir::TyKind::Path(hir::QPath::Resolved(
2453            None,
2454            self.arena.alloc(hir::Path {
2455                span,
2456                res,
2457                segments:
2458                    arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2459            }),
2460        ));
2461
2462        (param, preds, ty)
2463    }
2464
2465    /// Lowers a block directly to an expression, presuming that it
2466    /// has no attributes and is not targeted by a `break`.
2467    fn lower_block_expr(&mut self, b: &Block) -> hir::Expr<'hir> {
2468        let block = self.lower_block(b, false);
2469        self.expr_block(block)
2470    }
2471
2472    fn lower_array_length_to_const_arg(&mut self, c: &AnonConst) -> &'hir hir::ConstArg<'hir> {
2473        // We cannot just match on `ExprKind::Underscore` as `(_)` is represented as
2474        // `ExprKind::Paren(ExprKind::Underscore)` and should also be lowered to `GenericArg::Infer`
2475        match c.value.peel_parens().kind {
2476            ExprKind::Underscore => {
2477                let ct_kind = hir::ConstArgKind::Infer(());
2478                self.arena.alloc(hir::ConstArg {
2479                    hir_id: self.lower_node_id(c.id),
2480                    kind: ct_kind,
2481                    span: self.lower_span(c.value.span),
2482                })
2483            }
2484            _ => self.lower_anon_const_to_const_arg_and_alloc(c),
2485        }
2486    }
2487
2488    /// Used when lowering a type argument that turned out to actually be a const argument.
2489    ///
2490    /// Only use for that purpose since otherwise it will create a duplicate def.
2491    #[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(2491u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["path", "res",
                                                    "ty_id", "span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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