Skip to main content

rustc_ast_lowering/
path.rs

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