Skip to main content

rustc_ast_lowering/
lib.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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