Skip to main content

rustc_ast_lowering/
path.rs

1use std::sync::Arc;
2
3use rustc_ast::{self as ast, *};
4use rustc_errors::StashKey;
5use rustc_hir::def::{DefKind, PerNS, Res};
6use rustc_hir::def_id::DefId;
7use rustc_hir::{self as hir, GenericArg};
8use rustc_middle::middle::resolve::PartialRes;
9use rustc_middle::{span_bug, ty};
10use rustc_session::diagnostics::add_feature_diagnostics;
11use rustc_span::{BytePos, DUMMY_SP, DesugaringKind, Ident, Span, Symbol, sym};
12use smallvec::smallvec;
13use tracing::{debug, instrument};
14
15use crate::diagnostics::{
16    AsyncBoundNotOnTrait, AsyncBoundOnlyForFnTraits, BadReturnTypeNotation,
17    GenericTypeWithParentheses, RTNSuggestion, UseAngleBrackets,
18};
19use crate::{
20    AllowReturnTypeNotation, GenericArgsCtor, GenericArgsMode, ImplTraitContext, ImplTraitPosition,
21    LifetimeRes, LoweringContext, ParamMode,
22};
23
24impl<'hir> LoweringContext<'_, 'hir> {
25    {}
#[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_qpath",
                                    "rustc_ast_lowering::path", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_ast_lowering/src/path.rs"),
                                    ::tracing_core::__macro_support::Option::Some(25u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering::path"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("qself")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("qself");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("p")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("p");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("param_mode")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("param_mode");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("allow_return_type_notation")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("allow_return_type_notation");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("itctx")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("itctx");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("modifiers")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("modifiers");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&qself)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&p)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_mode)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&allow_return_type_notation)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&modifiers)
                                                            as &dyn ::tracing::field::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::QPath<'hir> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let qself_position = qself.as_ref().map(|q| q.position);
            let qself =
                qself.as_ref().map(|q|
                        {
                            self.lower_ty_alloc(&q.ty,
                                ImplTraitContext::Disallowed(ImplTraitPosition::Path))
                        });
            let partial_res =
                self.get_partial_res(id).unwrap_or_else(||
                        PartialRes::new(Res::Err));
            let base_res = partial_res.base_res();
            let unresolved_segments = partial_res.unresolved_segments();
            let mut res = self.lower_res(base_res);
            if let Some(TraitBoundModifiers {
                    asyncness: BoundAsyncness::Async(_), .. }) = modifiers {
                match res {
                    Res::Def(DefKind::Trait, def_id) => {
                        if let Some(async_def_id) =
                                self.map_trait_to_async_trait(def_id) {
                            res = Res::Def(DefKind::Trait, async_def_id);
                        } else {
                            self.dcx().emit_err(AsyncBoundOnlyForFnTraits {
                                    span: p.span,
                                });
                        }
                    }
                    Res::Err => {}
                    _ => {
                        self.dcx().emit_err(AsyncBoundNotOnTrait {
                                span: p.span,
                                descr: res.descr(),
                            });
                    }
                }
            }
            let bound_modifier_allowed_features =
                if let Res::Def(DefKind::Trait, async_def_id) = res &&
                        self.tcx.async_fn_trait_kind_from_def_id(async_def_id).is_some()
                    {
                    Some(Arc::clone(&self.allow_async_fn_traits))
                } else { None };
            let itctx =
                |i|
                    {
                        if i + 1 == p.segments.len() {
                            itctx
                        } else {
                            ImplTraitContext::Disallowed(ImplTraitPosition::Path)
                        }
                    };
            let path_span_lo = p.span.shrink_to_lo();
            let proj_start = p.segments.len() - unresolved_segments;
            let path =
                self.arena.alloc(hir::Path {
                        res,
                        segments: self.arena.alloc_from_iter(p.segments[..proj_start].iter().enumerate().map(|(i,
                                        segment)|
                                    {
                                        let param_mode =
                                            match (qself_position, param_mode) {
                                                (Some(j), ParamMode::Optional) if i < j => {
                                                    ParamMode::Explicit
                                                }
                                                _ => param_mode,
                                            };
                                        let generic_args_mode =
                                            match base_res {
                                                Res::Def(DefKind::Trait, _) if i + 1 == proj_start => {
                                                    GenericArgsMode::ParenSugar
                                                }
                                                Res::Def(DefKind::AssocFn, _) |
                                                    Res::Def(DefKind::AssocConst, _) |
                                                    Res::Def(DefKind::AssocTy, _) if i + 2 == proj_start => {
                                                    GenericArgsMode::ParenSugar
                                                }
                                                Res::Def(DefKind::AssocFn, _) if i + 1 == proj_start => {
                                                    match allow_return_type_notation {
                                                        AllowReturnTypeNotation::Yes =>
                                                            GenericArgsMode::ReturnTypeNotation,
                                                        AllowReturnTypeNotation::No => GenericArgsMode::Err,
                                                    }
                                                }
                                                Res::Err => GenericArgsMode::Silence,
                                                _ => GenericArgsMode::Err,
                                            };
                                        self.lower_path_segment(p.span, segment, param_mode,
                                            generic_args_mode, itctx(i),
                                            bound_modifier_allowed_features.clone())
                                    })),
                        span: self.lower_span(p.segments[..proj_start].last().map_or(path_span_lo,
                                |segment| path_span_lo.to(segment.span()))),
                    });
            if let Some(bound_modifier_allowed_features) =
                    bound_modifier_allowed_features {
                path.span =
                    self.mark_span_with_reason(DesugaringKind::BoundModifier,
                        path.span, Some(bound_modifier_allowed_features));
            }
            if unresolved_segments == 0 {
                return hir::QPath::Resolved(qself, path);
            }
            let mut ty =
                if path.segments.is_empty() {
                    qself.expect("missing QSelf for <T>::...")
                } else {
                    let new_id = self.next_id();
                    self.arena.alloc(self.ty_path(new_id, path.span,
                            hir::QPath::Resolved(qself, path)))
                };
            for (i, segment) in p.segments.iter().enumerate().skip(proj_start)
                {
                let generic_args_mode =
                    if i + 1 == p.segments.len() &&
                            #[allow(non_exhaustive_omitted_patterns)] match allow_return_type_notation
                                {
                                AllowReturnTypeNotation::Yes => true,
                                _ => false,
                            } {
                        GenericArgsMode::ReturnTypeNotation
                    } else { GenericArgsMode::Err };
                let hir_segment =
                    self.arena.alloc(self.lower_path_segment(p.span, segment,
                            param_mode, generic_args_mode, itctx(i), None));
                let qpath = hir::QPath::TypeRelative(ty, hir_segment);
                if i == p.segments.len() - 1 { return qpath; }
                let new_id = self.next_id();
                ty =
                    self.arena.alloc(self.ty_path(new_id,
                            path_span_lo.to(segment.span()), qpath));
            }
            self.dcx().span_bug(p.span,
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("lower_qpath: no final extension segment in {0}..{1}",
                                proj_start, p.segments.len()))
                    }));
        }
    }
}#[instrument(level = "trace", skip(self))]
26    pub(crate) fn lower_qpath(
27        &mut self,
28        id: NodeId,
29        qself: &Option<Box<QSelf>>,
30        p: &Path,
31        param_mode: ParamMode,
32        allow_return_type_notation: AllowReturnTypeNotation,
33        itctx: ImplTraitContext,
34        // modifiers of the impl/bound if this is a trait path
35        modifiers: Option<ast::TraitBoundModifiers>,
36    ) -> hir::QPath<'hir> {
37        let qself_position = qself.as_ref().map(|q| q.position);
38        let qself = qself
39            .as_ref()
40            // Reject cases like `<impl Trait>::Assoc` and `<impl Trait as Trait>::Assoc`.
41            .map(|q| {
42                self.lower_ty_alloc(&q.ty, ImplTraitContext::Disallowed(ImplTraitPosition::Path))
43            });
44
45        let partial_res = self.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err));
46        let base_res = partial_res.base_res();
47        let unresolved_segments = partial_res.unresolved_segments();
48
49        let mut res = self.lower_res(base_res);
50
51        // When we have an `async` kw on a bound, map the trait it resolves to.
52        if let Some(TraitBoundModifiers { asyncness: BoundAsyncness::Async(_), .. }) = modifiers {
53            match res {
54                Res::Def(DefKind::Trait, def_id) => {
55                    if let Some(async_def_id) = self.map_trait_to_async_trait(def_id) {
56                        res = Res::Def(DefKind::Trait, async_def_id);
57                    } else {
58                        self.dcx().emit_err(AsyncBoundOnlyForFnTraits { span: p.span });
59                    }
60                }
61                Res::Err => {
62                    // No additional error.
63                }
64                _ => {
65                    // This error isn't actually emitted AFAICT, but it's best to keep
66                    // it around in case the resolver doesn't always check the defkind
67                    // of an item or something.
68                    self.dcx().emit_err(AsyncBoundNotOnTrait { span: p.span, descr: res.descr() });
69                }
70            }
71        }
72
73        // Ungate the `async_fn_traits` feature in the path if the trait is
74        // named via either `async Fn*()` or `AsyncFn*()`.
75        let bound_modifier_allowed_features = if let Res::Def(DefKind::Trait, async_def_id) = res
76            && self.tcx.async_fn_trait_kind_from_def_id(async_def_id).is_some()
77        {
78            Some(Arc::clone(&self.allow_async_fn_traits))
79        } else {
80            None
81        };
82
83        // Only permit `impl Trait` in the final segment. E.g., we permit `Option<impl Trait>`,
84        // `option::Option<T>::Xyz<impl Trait>` and reject `option::Option<impl Trait>::Xyz`.
85        let itctx = |i| {
86            if i + 1 == p.segments.len() {
87                itctx
88            } else {
89                ImplTraitContext::Disallowed(ImplTraitPosition::Path)
90            }
91        };
92
93        let path_span_lo = p.span.shrink_to_lo();
94        let proj_start = p.segments.len() - unresolved_segments;
95        let path = self.arena.alloc(hir::Path {
96            res,
97            segments: self.arena.alloc_from_iter(p.segments[..proj_start].iter().enumerate().map(
98                |(i, segment)| {
99                    let param_mode = match (qself_position, param_mode) {
100                        (Some(j), ParamMode::Optional) if i < j => {
101                            // This segment is part of the trait path in a
102                            // qualified path - one of `a`, `b` or `Trait`
103                            // in `<X as a::b::Trait>::T::U::method`.
104                            ParamMode::Explicit
105                        }
106                        _ => param_mode,
107                    };
108
109                    let generic_args_mode = match base_res {
110                        // `a::b::Trait(Args)`
111                        Res::Def(DefKind::Trait, _) if i + 1 == proj_start => {
112                            GenericArgsMode::ParenSugar
113                        }
114                        // `a::b::Trait(Args)::TraitItem`
115                        Res::Def(DefKind::AssocFn, _)
116                        | Res::Def(DefKind::AssocConst, _)
117                        | Res::Def(DefKind::AssocTy, _)
118                            if i + 2 == proj_start =>
119                        {
120                            GenericArgsMode::ParenSugar
121                        }
122                        Res::Def(DefKind::AssocFn, _) if i + 1 == proj_start => {
123                            match allow_return_type_notation {
124                                AllowReturnTypeNotation::Yes => GenericArgsMode::ReturnTypeNotation,
125                                AllowReturnTypeNotation::No => GenericArgsMode::Err,
126                            }
127                        }
128                        // Avoid duplicated errors.
129                        Res::Err => GenericArgsMode::Silence,
130                        // An error
131                        _ => GenericArgsMode::Err,
132                    };
133
134                    self.lower_path_segment(
135                        p.span,
136                        segment,
137                        param_mode,
138                        generic_args_mode,
139                        itctx(i),
140                        bound_modifier_allowed_features.clone(),
141                    )
142                },
143            )),
144            span: self.lower_span(
145                p.segments[..proj_start]
146                    .last()
147                    .map_or(path_span_lo, |segment| path_span_lo.to(segment.span())),
148            ),
149        });
150
151        if let Some(bound_modifier_allowed_features) = bound_modifier_allowed_features {
152            path.span = self.mark_span_with_reason(
153                DesugaringKind::BoundModifier,
154                path.span,
155                Some(bound_modifier_allowed_features),
156            );
157        }
158
159        // Simple case, either no projections, or only fully-qualified.
160        // E.g., `std::mem::size_of` or `<I as Iterator>::Item`.
161        if unresolved_segments == 0 {
162            return hir::QPath::Resolved(qself, path);
163        }
164
165        // Create the innermost type that we're projecting from.
166        let mut ty = if path.segments.is_empty() {
167            // If the base path is empty that means there exists a
168            // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`.
169            qself.expect("missing QSelf for <T>::...")
170        } else {
171            // Otherwise, the base path is an implicit `Self` type path,
172            // e.g., `Vec` in `Vec::new` or `<I as Iterator>::Item` in
173            // `<I as Iterator>::Item::default`.
174            let new_id = self.next_id();
175            self.arena.alloc(self.ty_path(new_id, path.span, hir::QPath::Resolved(qself, path)))
176        };
177
178        // Anything after the base path are associated "extensions",
179        // out of which all but the last one are associated types,
180        // e.g., for `std::vec::Vec::<T>::IntoIter::Item::clone`:
181        // * base path is `std::vec::Vec<T>`
182        // * "extensions" are `IntoIter`, `Item` and `clone`
183        // * type nodes are:
184        //   1. `std::vec::Vec<T>` (created above)
185        //   2. `<std::vec::Vec<T>>::IntoIter`
186        //   3. `<<std::vec::Vec<T>>::IntoIter>::Item`
187        // * final path is `<<<std::vec::Vec<T>>::IntoIter>::Item>::clone`
188        for (i, segment) in p.segments.iter().enumerate().skip(proj_start) {
189            // If this is a type-dependent `T::method(..)`.
190            let generic_args_mode = if i + 1 == p.segments.len()
191                && matches!(allow_return_type_notation, AllowReturnTypeNotation::Yes)
192            {
193                GenericArgsMode::ReturnTypeNotation
194            } else {
195                GenericArgsMode::Err
196            };
197
198            let hir_segment = self.arena.alloc(self.lower_path_segment(
199                p.span,
200                segment,
201                param_mode,
202                generic_args_mode,
203                itctx(i),
204                None,
205            ));
206            let qpath = hir::QPath::TypeRelative(ty, hir_segment);
207
208            // It's finished, return the extension of the right node type.
209            if i == p.segments.len() - 1 {
210                return qpath;
211            }
212
213            // Wrap the associated extension in another type node.
214            let new_id = self.next_id();
215            ty = self.arena.alloc(self.ty_path(new_id, path_span_lo.to(segment.span()), qpath));
216        }
217
218        // We should've returned in the for loop above.
219
220        self.dcx().span_bug(
221            p.span,
222            format!(
223                "lower_qpath: no final extension segment in {}..{}",
224                proj_start,
225                p.segments.len()
226            ),
227        );
228    }
229
230    pub(crate) fn lower_use_path(
231        &mut self,
232        res: PerNS<Option<Res>>,
233        p: &Path,
234        param_mode: ParamMode,
235    ) -> &'hir hir::UsePath<'hir> {
236        if !!res.is_empty() {
    ::core::panicking::panic("assertion failed: !res.is_empty()")
};assert!(!res.is_empty());
237        self.arena.alloc(hir::UsePath {
238            res,
239            segments: self.arena.alloc_from_iter(p.segments.iter().map(|segment| {
240                self.lower_path_segment(
241                    p.span,
242                    segment,
243                    param_mode,
244                    GenericArgsMode::Err,
245                    ImplTraitContext::Disallowed(ImplTraitPosition::Path),
246                    None,
247                )
248            })),
249            span: self.lower_span(p.span),
250        })
251    }
252
253    pub(crate) fn lower_path_segment(
254        &mut self,
255        path_span: Span,
256        segment: &PathSegment,
257        param_mode: ParamMode,
258        generic_args_mode: GenericArgsMode,
259        itctx: ImplTraitContext,
260        // Additional features ungated with a bound modifier like `async`.
261        // This is passed down to the implicit associated type binding in
262        // parenthesized bounds.
263        bound_modifier_allowed_features: Option<Arc<[Symbol]>>,
264    ) -> hir::PathSegment<'hir> {
265        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_ast_lowering/src/path.rs:265",
                        "rustc_ast_lowering::path", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_ast_lowering/src/path.rs"),
                        ::tracing_core::__macro_support::Option::Some(265u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering::path"),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("path_span: {0:?}, lower_path_segment(segment: {1:?})",
                                                    path_span, segment) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("path_span: {:?}, lower_path_segment(segment: {:?})", path_span, segment);
266        let (mut generic_args, infer_args) = if let Some(generic_args) = segment.args.as_deref() {
267            match generic_args {
268                GenericArgs::AngleBracketed(data) => {
269                    self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
270                }
271                GenericArgs::Parenthesized(data) => match generic_args_mode {
272                    GenericArgsMode::ReturnTypeNotation => {
273                        let err = match (&data.inputs[..], &data.output) {
274                            ([_, ..], FnRetTy::Default(_)) => {
275                                BadReturnTypeNotation::Inputs { span: data.inputs_span }
276                            }
277                            ([], FnRetTy::Default(_)) => {
278                                BadReturnTypeNotation::NeedsDots { span: data.inputs_span }
279                            }
280                            // The case `T: Trait<method(..) -> Ret>` is handled in the parser.
281                            (_, FnRetTy::Ty(ty)) => {
282                                let span = data.inputs_span.shrink_to_hi().to(ty.span);
283                                BadReturnTypeNotation::Output {
284                                    span,
285                                    suggestion: RTNSuggestion {
286                                        output: span,
287                                        input: data.inputs_span,
288                                    },
289                                }
290                            }
291                        };
292                        let mut err = self.dcx().create_err(err);
293                        if !self.tcx.features().return_type_notation()
294                            && self.tcx.sess.is_nightly_build()
295                        {
296                            add_feature_diagnostics(
297                                &mut err,
298                                &self.tcx.sess,
299                                sym::return_type_notation,
300                            );
301                        }
302                        err.stash(path_span, StashKey::ReturnTypeNotation);
303                        (
304                            GenericArgsCtor {
305                                args: Default::default(),
306                                constraints: &[],
307                                parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
308                                span: path_span,
309                            },
310                            false,
311                        )
312                    }
313                    GenericArgsMode::ParenSugar | GenericArgsMode::Silence => self
314                        .lower_parenthesized_parameter_data(
315                            data,
316                            itctx,
317                            bound_modifier_allowed_features,
318                        ),
319                    GenericArgsMode::Err => {
320                        // Suggest replacing parentheses with angle brackets `Trait(params...)` to `Trait<params...>`
321                        let sub = if !data.inputs.is_empty() {
322                            // Start of the span to the 1st character of 1st argument
323                            let open_param = data.inputs_span.shrink_to_lo().to(data
324                                .inputs
325                                .first()
326                                .unwrap()
327                                .span
328                                .shrink_to_lo());
329                            // Last character position of last argument to the end of the span
330                            let close_param = data
331                                .inputs
332                                .last()
333                                .unwrap()
334                                .span
335                                .shrink_to_hi()
336                                .to(data.inputs_span.shrink_to_hi());
337
338                            Some(UseAngleBrackets { open_param, close_param })
339                        } else {
340                            None
341                        };
342                        let guar = self
343                            .dcx()
344                            .emit_err(GenericTypeWithParentheses { span: data.span, sub });
345                        (
346                            self.lower_angle_bracketed_parameter_data(
347                                &data.as_angle_bracketed_args(),
348                                param_mode,
349                                ImplTraitContext::AlreadyErrored(guar),
350                            )
351                            .0,
352                            false,
353                        )
354                    }
355                },
356                GenericArgs::ParenthesizedElided(span) => {
357                    match generic_args_mode {
358                        GenericArgsMode::ReturnTypeNotation | GenericArgsMode::Silence => {
359                            // Ok
360                        }
361                        GenericArgsMode::ParenSugar | GenericArgsMode::Err => {
362                            self.dcx().emit_err(BadReturnTypeNotation::Position { span: *span });
363                        }
364                    }
365                    (
366                        GenericArgsCtor {
367                            args: Default::default(),
368                            constraints: &[],
369                            parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation,
370                            span: *span,
371                        },
372                        false,
373                    )
374                }
375            }
376        } else {
377            (
378                GenericArgsCtor {
379                    args: Default::default(),
380                    constraints: &[],
381                    parenthesized: hir::GenericArgsParentheses::No,
382                    span: path_span.shrink_to_hi(),
383                },
384                param_mode == ParamMode::Optional,
385            )
386        };
387
388        let has_lifetimes =
389            generic_args.args.iter().any(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
    GenericArg::Lifetime(_) => true,
    _ => false,
}matches!(arg, GenericArg::Lifetime(_)));
390
391        // FIXME(return_type_notation): Is this correct? I think so.
392        if generic_args.parenthesized != hir::GenericArgsParentheses::ParenSugar && !has_lifetimes {
393            self.maybe_insert_elided_lifetimes_in_path(
394                path_span,
395                segment.id,
396                segment.ident.span,
397                &mut generic_args,
398            );
399        }
400
401        let res = self.expect_full_res(segment.id);
402        let hir_id = self.lower_node_id(segment.id);
403        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_ast_lowering/src/path.rs:403",
                        "rustc_ast_lowering::path", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_ast_lowering/src/path.rs"),
                        ::tracing_core::__macro_support::Option::Some(403u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering::path"),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("lower_path_segment: ident={0:?} original-id={1:?} new-id={2:?}",
                                                    segment.ident, segment.id, hir_id) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
404            "lower_path_segment: ident={:?} original-id={:?} new-id={:?}",
405            segment.ident, segment.id, hir_id,
406        );
407
408        hir::PathSegment {
409            ident: self.lower_ident(segment.ident),
410            hir_id,
411            res: self.lower_res(res),
412            infer_args,
413            args: if generic_args.is_empty() && generic_args.span.is_empty() {
414                None
415            } else {
416                Some(generic_args.into_generic_args(self))
417            },
418            delegation_child_segment: false,
419        }
420    }
421
422    fn maybe_insert_elided_lifetimes_in_path(
423        &mut self,
424        path_span: Span,
425        segment_id: NodeId,
426        segment_ident_span: Span,
427        generic_args: &mut GenericArgsCtor<'hir>,
428    ) {
429        let (start, end) = match self.curr_owner.owner.get_lifetime_res(segment_id) {
430            Some(LifetimeRes::ElidedAnchor { start, end }) => (start, end),
431            None => return,
432            Some(res) => {
433                ::rustc_middle::util::bug::span_bug_fmt(path_span,
    format_args!("expected an elided lifetime to insert. found {0:?}", res))span_bug!(path_span, "expected an elided lifetime to insert. found {res:?}")
434            }
435        };
436        let expected_lifetimes = end.as_usize() - start.as_usize();
437        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_ast_lowering/src/path.rs:437",
                        "rustc_ast_lowering::path", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/574ff7d98bd6d037e5236a8453029173b32631fd/compiler/rustc_ast_lowering/src/path.rs"),
                        ::tracing_core::__macro_support::Option::Some(437u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ast_lowering::path"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("expected_lifetimes")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("expected_lifetimes");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&expected_lifetimes
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(expected_lifetimes);
438
439        // Note: these spans are used for diagnostics when they can't be inferred.
440        // See rustc_resolve::late::lifetimes::LifetimeContext::add_missing_lifetime_specifiers_label
441        let (elided_lifetime_span, angle_brackets) = if generic_args.span.is_empty() {
442            // No brackets, e.g. `Path`: use an empty span just past the end of the identifier.
443            // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
444            // originating from macros, since the segment's span might be from a macro arg.
445            (
446                segment_ident_span.find_ancestor_inside(path_span).unwrap_or(path_span),
447                hir::AngleBrackets::Missing,
448            )
449        } else {
450            // Brackets, e.g. `Path<>` or `Path<T>`: use an empty span just after the `<`.
451            (
452                generic_args.span.with_lo(generic_args.span.lo() + BytePos(1)).shrink_to_lo(),
453                if generic_args.is_empty() {
454                    hir::AngleBrackets::Empty
455                } else {
456                    hir::AngleBrackets::Full
457                },
458            )
459        };
460
461        generic_args.args.insert_many(
462            0,
463            (start..end).map(|id| {
464                let l =
465                    self.lower_lifetime_hidden_in_path(id, elided_lifetime_span, angle_brackets);
466                GenericArg::Lifetime(l)
467            }),
468        );
469    }
470
471    pub(crate) fn lower_angle_bracketed_parameter_data(
472        &mut self,
473        data: &AngleBracketedArgs,
474        param_mode: ParamMode,
475        itctx: ImplTraitContext,
476    ) -> (GenericArgsCtor<'hir>, bool) {
477        let has_non_lt_args = data.args.iter().any(|arg| match arg {
478            AngleBracketedArg::Arg(ast::GenericArg::Lifetime(_))
479            | AngleBracketedArg::Constraint(_) => false,
480            AngleBracketedArg::Arg(ast::GenericArg::Type(_) | ast::GenericArg::Const(_)) => true,
481        });
482        let args = data
483            .args
484            .iter()
485            .filter_map(|arg| match arg {
486                AngleBracketedArg::Arg(arg) => Some(self.lower_generic_arg(arg, itctx)),
487                AngleBracketedArg::Constraint(_) => None,
488            })
489            .collect();
490        let constraints =
491            self.arena.alloc_from_iter(data.args.iter().filter_map(|arg| match arg {
492                AngleBracketedArg::Constraint(c) => {
493                    Some(self.lower_assoc_item_constraint(c, itctx))
494                }
495                AngleBracketedArg::Arg(_) => None,
496            }));
497        let ctor = GenericArgsCtor {
498            args,
499            constraints,
500            parenthesized: hir::GenericArgsParentheses::No,
501            span: data.span,
502        };
503        (ctor, !has_non_lt_args && param_mode == ParamMode::Optional)
504    }
505
506    fn lower_parenthesized_parameter_data(
507        &mut self,
508        data: &ParenthesizedArgs,
509        itctx: ImplTraitContext,
510        bound_modifier_allowed_features: Option<Arc<[Symbol]>>,
511    ) -> (GenericArgsCtor<'hir>, bool) {
512        // Switch to `PassThrough` mode for anonymous lifetimes; this
513        // means that we permit things like `&Ref<T>`, where `Ref` has
514        // a hidden lifetime parameter. This is needed for backwards
515        // compatibility, even in contexts like an impl header where
516        // we generally don't permit such things (see #51008).
517        let ParenthesizedArgs { span, inputs, inputs_span, output } = data;
518        let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
519            self.lower_ty(&param.ty, ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitParam))
520        }));
521        let output_ty = match output {
522            // Only allow `impl Trait` in return position. i.e.:
523            // ```rust
524            // fn f(_: impl Fn() -> impl Debug) -> impl Fn() -> impl Debug
525            // //      disallowed --^^^^^^^^^^        allowed --^^^^^^^^^^
526            // ```
527            FnRetTy::Ty(ty) if #[allow(non_exhaustive_omitted_patterns)] match itctx {
    ImplTraitContext::OpaqueTy { .. } => true,
    _ => false,
}matches!(itctx, ImplTraitContext::OpaqueTy { .. }) => {
528                if self.tcx.features().impl_trait_in_fn_trait_return() {
529                    self.lower_ty_alloc(ty, itctx)
530                } else {
531                    self.lower_ty_alloc(
532                        ty,
533                        ImplTraitContext::FeatureGated(
534                            ImplTraitPosition::FnTraitReturn,
535                            sym::impl_trait_in_fn_trait_return,
536                        ),
537                    )
538                }
539            }
540            FnRetTy::Ty(ty) => self
541                .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitReturn)),
542            FnRetTy::Default(_) => self.arena.alloc(self.ty_tup(*span, &[])),
543        };
544        let args = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(GenericArg::Type(self.arena.alloc(self.ty_tup(*inputs_span,
                                inputs)).try_as_ambig_ty().unwrap()));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [GenericArg::Type(self.arena.alloc(self.ty_tup(*inputs_span,
                                                inputs)).try_as_ambig_ty().unwrap())])))
    }
}smallvec![GenericArg::Type(
545            self.arena.alloc(self.ty_tup(*inputs_span, inputs)).try_as_ambig_ty().unwrap()
546        )];
547
548        // If we have a bound like `async Fn() -> T`, make sure that we mark the
549        // `Output = T` associated type bound with the right feature gates.
550        let mut output_span = output_ty.span;
551        if let Some(bound_modifier_allowed_features) = bound_modifier_allowed_features {
552            output_span = self.mark_span_with_reason(
553                DesugaringKind::BoundModifier,
554                output_span,
555                Some(bound_modifier_allowed_features),
556            );
557        }
558        let constraint = self.assoc_ty_binding(sym::Output, output_span, output_ty);
559
560        (
561            GenericArgsCtor {
562                args,
563                constraints: self.arena.alloc_from_iter([constraint])arena_vec![self; constraint],
564                parenthesized: hir::GenericArgsParentheses::ParenSugar,
565                span: data.inputs_span,
566            },
567            false,
568        )
569    }
570
571    /// An associated type binding (i.e., associated type equality constraint).
572    pub(crate) fn assoc_ty_binding(
573        &mut self,
574        assoc_ty_name: rustc_span::Symbol,
575        span: Span,
576        ty: &'hir hir::Ty<'hir>,
577    ) -> hir::AssocItemConstraint<'hir> {
578        let ident = Ident::with_dummy_span(assoc_ty_name);
579        let kind = hir::AssocItemConstraintKind::Equality { term: ty.into() };
580        let args = self.arena.alloc_from_iter([])arena_vec![self;];
581        let constraints = self.arena.alloc_from_iter([])arena_vec![self;];
582        let gen_args = self.arena.alloc(hir::GenericArgs {
583            args,
584            constraints,
585            parenthesized: hir::GenericArgsParentheses::No,
586            span_ext: DUMMY_SP,
587        });
588        hir::AssocItemConstraint {
589            hir_id: self.next_id(),
590            gen_args,
591            span: self.lower_span(span),
592            ident,
593            kind,
594        }
595    }
596
597    /// When a bound is annotated with `async`, it signals to lowering that the trait
598    /// that the bound refers to should be mapped to the "async" flavor of the trait.
599    ///
600    /// This only needs to be done until we unify `AsyncFn` and `Fn` traits into one
601    /// that is generic over `async`ness, if that's ever possible, or modify the
602    /// lowering of `async Fn()` bounds to desugar to another trait like `LendingFn`.
603    fn map_trait_to_async_trait(&self, def_id: DefId) -> Option<DefId> {
604        let lang_items = self.tcx.lang_items();
605        match self.tcx.fn_trait_kind_from_def_id(def_id)? {
606            ty::ClosureKind::Fn => lang_items.async_fn_trait(),
607            ty::ClosureKind::FnMut => lang_items.async_fn_mut_trait(),
608            ty::ClosureKind::FnOnce => lang_items.async_fn_once_trait(),
609        }
610    }
611}