Skip to main content

rustc_parse/parser/
path.rs

1use std::mem;
2
3use rustc_ast::token::{self, MetaVarKind, Token, TokenKind};
4use rustc_ast::{
5    self as ast, AngleBracketedArg, AngleBracketedArgs, AnonConst, AssocItemConstraint,
6    AssocItemConstraintKind, BlockCheckMode, GenericArg, GenericArgs, Generics, ParenthesizedArgs,
7    Path, PathSegment, QSelf,
8};
9use rustc_errors::{Applicability, Diag, PResult};
10use rustc_span::{BytePos, Ident, Span, kw, sym};
11use thin_vec::ThinVec;
12use tracing::debug;
13
14use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
15use super::{Parser, Restrictions, TokenType};
16use crate::ast::{PatKind, TyKind};
17use crate::diagnostics::{
18    self, ConstGenericWithoutBraces, ConstGenericWithoutBracesSugg, PathSingleColon,
19    PathTripleColon,
20};
21use crate::exp;
22use crate::parser::{CommaRecoveryMode, Expr, FnContext, FnParseMode, RecoverColon, RecoverComma};
23
24/// Specifies how to parse a path.
25#[derive(#[automatically_derived]impl ::core::marker::Copy for PathStyle { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for PathStyle {
}
#[automatically_derived]impl ::core::clone::Clone for PathStyle {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for PathStyle
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for PathStyle {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
26pub enum PathStyle {
27    /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
28    /// with something else. For example, in expressions `segment < ....` can be interpreted
29    /// as a comparison and `segment ( ....` can be interpreted as a function call.
30    /// In all such contexts the non-path interpretation is preferred by default for practical
31    /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
32    /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
33    ///
34    /// Also, a path may never be followed by a `:`. This means that we can eagerly recover if
35    /// we encounter it.
36    Expr,
37    /// The same as `Expr`, but may be followed by a `:`.
38    /// For example, this code:
39    /// ```rust
40    /// struct S;
41    ///
42    /// let S: S;
43    /// //  ^ Followed by a `:`
44    /// ```
45    Pat,
46    /// In other contexts, notably in types, no ambiguity exists and paths can be written
47    /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
48    /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
49    Type,
50    /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
51    /// visibilities or attributes.
52    /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
53    /// (paths in "mod" contexts have to be checked later for absence of generic arguments
54    /// anyway, due to macros), but it is used to avoid weird suggestions about expected
55    /// tokens when something goes wrong.
56    Mod,
57}
58
59impl PathStyle {
60    fn has_generic_ambiguity(&self) -> bool {
61        #[allow(non_exhaustive_omitted_patterns)] match self {
    Self::Expr | Self::Pat => true,
    _ => false,
}matches!(self, Self::Expr | Self::Pat)
62    }
63}
64
65impl<'a> Parser<'a> {
66    /// Parses a qualified path.
67    /// Assumes that the leading `<` has been parsed already.
68    ///
69    /// `qualified_path = <type [as trait_ref]>::path`
70    ///
71    /// # Examples
72    /// `<T>::default`
73    /// `<T as U>::a`
74    /// `<T as U>::F::a<S>` (without disambiguator)
75    /// `<T as U>::F::a::<S>` (with disambiguator)
76    pub(super) fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (Box<QSelf>, Path)> {
77        let mut qpath_span = Some(self.prev_token.span);
78        let ty = self.parse_ty()?;
79        chain_span(&mut qpath_span, ty.span);
80
81        // `path` will contain the prefix of the path up to the `>`,
82        // if any (e.g., `U` in the `<T as U>::*` examples
83        // above). `path_span` has the span of that path, or an empty
84        // span in the case of something like `<T>::Bar`.
85        let (mut path, path_span);
86        if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::As,
    token_type: crate::parser::token_type::TokenType::KwAs,
}exp!(As)) {
87            chain_span(&mut qpath_span, self.prev_token.span);
88            path = self.parse_path(PathStyle::Type)?;
89            path_span = path.span;
90            chain_span(&mut qpath_span, path_span);
91        } else {
92            path_span = self.token.span; // `>`
93            path = ast::Path { segments: ThinVec::new(), span: path_span };
94        }
95
96        // See doc comment for `unmatched_angle_bracket_count`.
97        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Gt,
    token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt))?;
98        chain_span(&mut qpath_span, self.prev_token.span);
99        if self.unmatched_angle_bracket_count > 0 {
100            self.unmatched_angle_bracket_count -= 1;
101            {
    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_parse/src/parser/path.rs:101",
                        "rustc_parse::parser::path", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_parse/src/parser/path.rs"),
                        ::tracing_core::__macro_support::Option::Some(101u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::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!("parse_qpath: (decrement) count={0:?}",
                                                    self.unmatched_angle_bracket_count) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
102        }
103
104        let is_import_coupler = self.is_import_coupler();
105        if !is_import_coupler && !self.recover_colon_before_qpath_proj() {
106            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::PathSep,
    token_type: crate::parser::token_type::TokenType::PathSep,
}exp!(PathSep))?;
107        }
108
109        let qself = Box::new(QSelf { ty, path_span, position: path.segments.len() });
110        if !is_import_coupler {
111            chain_span(&mut qpath_span, self.prev_token.span); // `::`
112            self.parse_path_segments_with_path_span(
113                &mut path.segments,
114                style,
115                None,
116                &mut qpath_span,
117            )?;
118        }
119
120        Ok((qself, Path { segments: path.segments, span: qpath_span.unwrap() }))
121    }
122
123    /// Recover from an invalid single colon, when the user likely meant a qualified path.
124    /// We avoid emitting this if not followed by an identifier, as our assumption that the user
125    /// intended this to be a qualified path may not be correct.
126    ///
127    /// ```ignore (diagnostics)
128    /// <Bar as Baz<T>>:Qux
129    ///                ^ help: use double colon
130    /// ```
131    fn recover_colon_before_qpath_proj(&mut self) -> bool {
132        if !self.check_noexpect(&TokenKind::Colon)
133            || self.look_ahead(1, |t| !t.is_non_reserved_ident())
134        {
135            return false;
136        }
137
138        self.bump(); // colon
139
140        self.dcx()
141            .struct_span_err(
142                self.prev_token.span,
143                "found single colon before projection in qualified path",
144            )
145            .with_span_suggestion(
146                self.prev_token.span,
147                "use double colon",
148                "::",
149                Applicability::MachineApplicable,
150            )
151            .emit();
152
153        true
154    }
155
156    pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, Path> {
157        self.parse_path_inner(style, None)
158    }
159
160    /// Parses simple paths.
161    ///
162    /// `path = [::] segment+`
163    /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
164    ///
165    /// # Examples
166    /// `a::b::C<D>` (without disambiguator)
167    /// `a::b::C::<D>` (with disambiguator)
168    /// `Fn(Args)` (without disambiguator)
169    /// `Fn::(Args)` (with disambiguator)
170    pub(super) fn parse_path_inner(
171        &mut self,
172        style: PathStyle,
173        ty_generics: Option<&Generics>,
174    ) -> PResult<'a, Path> {
175        let reject_generics_if_mod_style = |parser: &Parser<'_>, path: Path| {
176            // Ensure generic arguments don't end up in attribute paths, such as:
177            //
178            //     macro_rules! m {
179            //         ($p:path) => { #[$p] struct S; }
180            //     }
181            //
182            //     m!(inline<u8>); //~ ERROR: unexpected generic arguments in path
183            //
184            if style == PathStyle::Mod && path.segments.iter().any(|segment| segment.args.is_some())
185            {
186                let span = path
187                    .segments
188                    .iter()
189                    .filter_map(|segment| segment.args.as_ref())
190                    .map(|arg| arg.span())
191                    .collect::<Vec<_>>();
192                parser.dcx().emit_err(diagnostics::GenericsInPath { span });
193                // Ignore these arguments to prevent unexpected behaviors.
194                let segments = path
195                    .segments
196                    .iter()
197                    .map(|segment| PathSegment { ident: segment.ident, id: segment.id, args: None })
198                    .collect();
199                Path { segments, ..path }
200            } else {
201                path
202            }
203        };
204
205        if let Some(path) =
206            self.eat_metavar_seq(MetaVarKind::Path, |this| this.parse_path(PathStyle::Type))
207        {
208            return Ok(reject_generics_if_mod_style(self, path));
209        }
210
211        // If we have a `ty` metavar in the form of a path, reparse it directly as a path, instead
212        // of reparsing it as a `ty` and then extracting the path.
213        if let Some(path) = self.eat_metavar_seq(MetaVarKind::Ty { is_path: true }, |this| {
214            this.parse_path(PathStyle::Type)
215        }) {
216            return Ok(reject_generics_if_mod_style(self, path));
217        }
218
219        let lo = self.token.span;
220        let mut path_span = None;
221        let mut segments = ThinVec::new();
222        let mod_sep_ctxt = self.token.span.ctxt();
223        if self.eat_path_sep() {
224            chain_span(&mut path_span, self.prev_token.span);
225            segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
226        }
227        self.parse_path_segments_with_path_span(&mut segments, style, ty_generics, &mut path_span)?;
228        Ok(Path { segments, span: path_span.unwrap() })
229    }
230
231    pub(super) fn parse_path_segments(
232        &mut self,
233        segments: &mut ThinVec<PathSegment>,
234        style: PathStyle,
235        ty_generics: Option<&Generics>,
236    ) -> PResult<'a, ()> {
237        self.parse_path_segments_with_path_span(segments, style, ty_generics, &mut None)
238    }
239
240    fn parse_path_segments_with_path_span(
241        &mut self,
242        segments: &mut ThinVec<PathSegment>,
243        style: PathStyle,
244        ty_generics: Option<&Generics>,
245        path_span: &mut Option<Span>,
246    ) -> PResult<'a, ()> {
247        loop {
248            let segment = self.parse_path_segment_with_path_span(style, ty_generics, path_span)?;
249            if style.has_generic_ambiguity() {
250                // In order to check for trailing angle brackets, we must have finished
251                // recursing (`parse_path_segment` can indirectly call this function),
252                // that is, the next token must be the highlighted part of the below example:
253                //
254                // `Foo::<Bar as Baz<T>>::Qux`
255                //                      ^ here
256                //
257                // As opposed to the below highlight (if we had only finished the first
258                // recursion):
259                //
260                // `Foo::<Bar as Baz<T>>::Qux`
261                //                     ^ here
262                //
263                // `PathStyle::Expr` is only provided at the root invocation and never in
264                // `parse_path_segment` to recurse and therefore can be checked to maintain
265                // this invariant.
266                self.check_trailing_angle_brackets(&segment, &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::PathSep,
    token_type: crate::parser::token_type::TokenType::PathSep,
}exp!(PathSep)]);
267            }
268            segments.push(segment);
269
270            if self.is_import_coupler() || !self.eat_path_sep() {
271                // IMPORTANT: We can *only ever* treat single colons as typo'ed double colons in
272                // expression contexts (!) since only there paths cannot possibly be followed by
273                // a colon and still form a syntactically valid construct. In pattern contexts,
274                // a path may be followed by a type annotation. E.g., `let pat:ty`. In type
275                // contexts, a path may be followed by a list of bounds. E.g., `where ty:bound`.
276                if self.may_recover()
277                    && style == PathStyle::Expr // (!)
278                    && self.token == token::Colon
279                    && self.look_ahead(1, |token| token.is_non_reserved_ident())
280                {
281                    // Emit a special error message for `a::b:c` to help users
282                    // otherwise, `a: c` might have meant to introduce a new binding
283                    if self.token.span.lo() == self.prev_token.span.hi()
284                        && self.look_ahead(1, |token| self.token.span.hi() == token.span.lo())
285                    {
286                        self.bump(); // bump past the colon
287                        chain_span(path_span, self.prev_token.span);
288                        self.dcx().emit_err(PathSingleColon {
289                            span: self.prev_token.span,
290                            suggestion: self.prev_token.span.shrink_to_hi(),
291                        });
292                    }
293                    continue;
294                }
295
296                return Ok(());
297            }
298            chain_span(path_span, self.prev_token.span); // `::`
299        }
300    }
301
302    /// Eat `::` or, potentially, `:::`.
303    #[must_use]
304    pub(super) fn eat_path_sep(&mut self) -> bool {
305        let result = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::PathSep,
    token_type: crate::parser::token_type::TokenType::PathSep,
}exp!(PathSep));
306        if result && self.may_recover() {
307            if self.eat_noexpect(&token::Colon) {
308                self.dcx().emit_err(PathTripleColon { span: self.prev_token.span });
309            }
310        }
311        result
312    }
313
314    pub(super) fn parse_path_segment(
315        &mut self,
316        style: PathStyle,
317        ty_generics: Option<&Generics>,
318    ) -> PResult<'a, PathSegment> {
319        self.parse_path_segment_with_path_span(style, ty_generics, &mut None)
320    }
321
322    fn parse_path_segment_with_path_span(
323        &mut self,
324        style: PathStyle,
325        ty_generics: Option<&Generics>,
326        path_span: &mut Option<Span>,
327    ) -> PResult<'a, PathSegment> {
328        let ident = self.parse_path_segment_ident()?;
329        chain_span(path_span, self.prev_token.span);
330        let is_args_start = |token: &Token| {
331            #[allow(non_exhaustive_omitted_patterns)] match token.kind {
    token::Lt | token::Shl | token::OpenParen | token::LArrow => true,
    _ => false,
}matches!(token.kind, token::Lt | token::Shl | token::OpenParen | token::LArrow)
332        };
333        let check_args_start = |this: &mut Self| {
334            this.expected_token_types.insert(TokenType::Lt);
335            this.expected_token_types.insert(TokenType::OpenParen);
336            is_args_start(&this.token)
337        };
338
339        // A lifetime followed by `>` or `,` can never start a valid expression, so `<` here
340        // must be the start of generic arguments with a missing `::`.
341        let is_missing_turbofish_for_lifetime = |this: &mut Self| {
342            this.token == token::Lt
343                && this.may_recover()
344                && style == PathStyle::Expr
345                && this.look_ahead(1, |t| t.is_lifetime())
346                && this.look_ahead(2, |t| #[allow(non_exhaustive_omitted_patterns)] match t.kind {
    token::Gt | token::Comma => true,
    _ => false,
}matches!(t.kind, token::Gt | token::Comma))
347        };
348
349        Ok(
350            if style == PathStyle::Type && check_args_start(self)
351                || style != PathStyle::Mod && self.check_path_sep_and_look_ahead(is_args_start)
352                || is_missing_turbofish_for_lifetime(self)
353            {
354                // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
355                // it isn't, then we reset the unmatched angle bracket count as we're about to start
356                // parsing a new path.
357                if style == PathStyle::Expr {
358                    self.unmatched_angle_bracket_count = 0;
359                }
360
361                let missing_turbofish =
362                    style == PathStyle::Expr && !self.check_path_sep_and_look_ahead(is_args_start);
363
364                // Generic arguments are found - `<`, `(`, `::<` or `::(`.
365                // First, eat `::` if it exists.
366                if self.eat_path_sep() {
367                    chain_span(path_span, self.prev_token.span);
368                }
369
370                let lo = self.token.span;
371                let args = if self.eat_lt() {
372                    if missing_turbofish {
373                        self.recover_missing_turbofish_for_lifetimes(lo);
374                    }
375                    // `<'a, T, A = U>`
376                    let args = self.parse_angle_args_with_leading_angle_bracket_recovery(
377                        style,
378                        lo,
379                        ty_generics,
380                    )?;
381                    self.expect_gt().map_err(|mut err| {
382                        // Try to recover a `:` into a `::`
383                        if self.token == token::Colon
384                            && self.look_ahead(1, |token| token.is_non_reserved_ident())
385                        {
386                            err.cancel();
387                            err = self.dcx().create_err(PathSingleColon {
388                                span: self.token.span,
389                                suggestion: self.prev_token.span.shrink_to_hi(),
390                            });
391                        }
392                        // Attempt to find places where a missing `>` might belong.
393                        else if let Some(arg) = args
394                            .iter()
395                            .rev()
396                            .find(|arg| !#[allow(non_exhaustive_omitted_patterns)] match arg {
    AngleBracketedArg::Constraint(_) => true,
    _ => false,
}matches!(arg, AngleBracketedArg::Constraint(_)))
397                        {
398                            err.span_suggestion_verbose(
399                                arg.span().shrink_to_hi(),
400                                "you might have meant to end the type parameters here",
401                                ">",
402                                Applicability::MaybeIncorrect,
403                            );
404                        }
405                        err
406                    })?;
407                    let span = lo.to(self.prev_token.span);
408                    AngleBracketedArgs { args, span }.into()
409                } else if self.token == token::OpenParen
410                    // FIXME(return_type_notation): Could also recover `...` here.
411                    && self.look_ahead(1, |t| *t == token::DotDot)
412                {
413                    self.bump(); // (
414                    self.bump(); // ..
415                    self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
416                    let span = lo.to(self.prev_token.span);
417
418                    self.psess.gated_spans.gate(sym::return_type_notation, span);
419
420                    let prev_lo = self.prev_token.span.shrink_to_hi();
421                    if self.eat_noexpect(&token::RArrow) {
422                        let lo = self.prev_token.span;
423                        let ty = self.parse_ty()?;
424                        let span = lo.to(ty.span);
425                        let suggestion = prev_lo.to(ty.span);
426                        self.dcx().emit_err(diagnostics::BadReturnTypeNotationOutput {
427                            span,
428                            suggestion,
429                        });
430                    }
431
432                    Box::new(ast::GenericArgs::ParenthesizedElided(span))
433                } else {
434                    // `(T, U) -> R`
435
436                    let prev_token_before_parsing = self.prev_token;
437                    let token_before_parsing = self.token;
438                    let mut snapshot = None;
439                    if self.may_recover()
440                        && prev_token_before_parsing == token::PathSep
441                        && (style == PathStyle::Expr && self.token.can_begin_expr()
442                            || style == PathStyle::Pat
443                                && self.token.can_begin_pattern(token::NtPatKind::PatParam {
444                                    inferred: false,
445                                }))
446                    {
447                        snapshot = Some(self.create_snapshot_for_diagnostic());
448                    }
449
450                    let mut first_param = true;
451                    let parse_params_result = self.parse_paren_comma_seq(|p| {
452                        // Inside parenthesized type arguments, we want types only, not names.
453                        let mode = FnParseMode {
454                            context: FnContext::ParenthesizedArgumentList,
455                            req_name: |_, _| false,
456                            req_body: false,
457                            allow_const_params: false,
458                        };
459                        let param = p.parse_param_general(&mode, first_param)?;
460                        first_param = false;
461                        if !#[allow(non_exhaustive_omitted_patterns)] match param.pat.kind {
    PatKind::Missing => true,
    _ => false,
}matches!(param.pat.kind, PatKind::Missing) {
462                            self.psess
463                                .gated_spans
464                                .gate(sym::named_fn_trait_parameters, param.pat.span);
465                        }
466                        if #[allow(non_exhaustive_omitted_patterns)] match param.ty.kind {
    TyKind::CVarArgs => true,
    _ => false,
}matches!(param.ty.kind, TyKind::CVarArgs) {
467                            self.psess
468                                .gated_spans
469                                .gate(sym::named_fn_trait_parameters, param.ty.span);
470                        }
471                        if !param.attrs.is_empty() {
472                            self.psess
473                                .gated_spans
474                                .gate(sym::named_fn_trait_parameters, param.attrs[0].span);
475                        }
476                        Ok(param)
477                    });
478
479                    let (inputs, _) = match parse_params_result {
480                        Ok(output) => output,
481                        Err(mut error) if prev_token_before_parsing == token::PathSep => {
482                            error.span_label(
483                                prev_token_before_parsing.span.to(token_before_parsing.span),
484                                "while parsing this parenthesized list of type arguments starting here",
485                            );
486
487                            if let Some(mut snapshot) = snapshot {
488                                snapshot.recover_fn_call_leading_path_sep(
489                                    style,
490                                    prev_token_before_parsing,
491                                    &mut error,
492                                )
493                            }
494
495                            return Err(error);
496                        }
497                        Err(error) => return Err(error),
498                    };
499                    let inputs_span = lo.to(self.prev_token.span);
500                    let mut span = inputs_span;
501                    if self.token == token::RArrow {
502                        span = span.to(self.token.span);
503                    }
504                    let output =
505                        self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)?;
506                    if let ast::FnRetTy::Ty(ret_ty) = &output {
507                        span = span.to(ret_ty.span);
508                    }
509                    ParenthesizedArgs { span, inputs, inputs_span, output }.into()
510                };
511                chain_span(path_span, args.span());
512
513                PathSegment { ident, args: Some(args), id: ast::DUMMY_NODE_ID }
514            } else {
515                // Generic arguments are not found.
516                PathSegment::from_ident(ident)
517            },
518        )
519    }
520
521    pub(super) fn parse_path_segment_ident(&mut self) -> PResult<'a, Ident> {
522        if let Some(ident) = self.token.non_raw_ident()
523            && ident.is_path_segment_keyword()
524        {
525            self.bump();
526            Ok(ident)
527        } else {
528            self.parse_ident()
529        }
530    }
531
532    /// Recover `$path::(...)` as `$path(...)`.
533    ///
534    /// ```ignore (diagnostics)
535    /// foo::(420, "bar")
536    ///    ^^ remove extra separator to make the function call
537    /// // or
538    /// match x {
539    ///    Foo::(420, "bar") => { ... },
540    ///       ^^ remove extra separator to turn this into tuple struct pattern
541    ///    _ => { ... },
542    /// }
543    /// ```
544    fn recover_fn_call_leading_path_sep(
545        &mut self,
546        style: PathStyle,
547        prev_token_before_parsing: Token,
548        error: &mut Diag<'_>,
549    ) {
550        match style {
551            PathStyle::Expr
552                if let Ok(_) = self
553                    .parse_paren_comma_seq(|p| p.parse_expr())
554                    .map_err(|error| error.cancel()) => {}
555            PathStyle::Pat
556                if let Ok(_) = self
557                    .parse_paren_comma_seq(|p| {
558                        p.parse_pat_allow_top_guard(
559                            None,
560                            RecoverComma::No,
561                            RecoverColon::No,
562                            CommaRecoveryMode::LikelyTuple,
563                        )
564                    })
565                    .map_err(|error| error.cancel()) => {}
566            _ => {
567                return;
568            }
569        }
570
571        if let token::PathSep | token::RArrow = self.token.kind {
572            return;
573        }
574
575        error.span_suggestion_verbose(
576            prev_token_before_parsing.span,
577            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider removing the `::` here to {0}",
                match style {
                    PathStyle::Expr => "call the expression",
                    PathStyle::Pat => "turn this into a tuple struct pattern",
                    _ => { return; }
                }))
    })format!(
578                "consider removing the `::` here to {}",
579                match style {
580                    PathStyle::Expr => "call the expression",
581                    PathStyle::Pat => "turn this into a tuple struct pattern",
582                    _ => {
583                        return;
584                    }
585                }
586            ),
587            "",
588            Applicability::MaybeIncorrect,
589        );
590    }
591
592    /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
593    /// For the purposes of understanding the parsing logic of generic arguments, this function
594    /// can be thought of being the same as just calling `self.parse_angle_args()` if the source
595    /// had the correct amount of leading angle brackets.
596    ///
597    /// ```ignore (diagnostics)
598    /// bar::<<<<T as Foo>::Output>();
599    ///      ^^ help: remove extra angle brackets
600    /// ```
601    fn parse_angle_args_with_leading_angle_bracket_recovery(
602        &mut self,
603        style: PathStyle,
604        lo: Span,
605        ty_generics: Option<&Generics>,
606    ) -> PResult<'a, ThinVec<AngleBracketedArg>> {
607        // We need to detect whether there are extra leading left angle brackets and produce an
608        // appropriate error and suggestion. This cannot be implemented by looking ahead at
609        // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
610        // then there won't be matching `>` tokens to find.
611        //
612        // To explain how this detection works, consider the following example:
613        //
614        // ```ignore (diagnostics)
615        // bar::<<<<T as Foo>::Output>();
616        //      ^^ help: remove extra angle brackets
617        // ```
618        //
619        // Parsing of the left angle brackets starts in this function. We start by parsing the
620        // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
621        // `eat_lt`):
622        //
623        // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
624        // *Unmatched count:* 1
625        // *`parse_path_segment` calls deep:* 0
626        //
627        // This has the effect of recursing as this function is called if a `<` character
628        // is found within the expected generic arguments:
629        //
630        // *Upcoming tokens:* `<<<T as Foo>::Output>;`
631        // *Unmatched count:* 2
632        // *`parse_path_segment` calls deep:* 1
633        //
634        // Eventually we will have recursed until having consumed all of the `<` tokens and
635        // this will be reflected in the count:
636        //
637        // *Upcoming tokens:* `T as Foo>::Output>;`
638        // *Unmatched count:* 4
639        // `parse_path_segment` calls deep:* 3
640        //
641        // The parser will continue until reaching the first `>` - this will decrement the
642        // unmatched angle bracket count and return to the parent invocation of this function
643        // having succeeded in parsing:
644        //
645        // *Upcoming tokens:* `::Output>;`
646        // *Unmatched count:* 3
647        // *`parse_path_segment` calls deep:* 2
648        //
649        // This will continue until the next `>` character which will also return successfully
650        // to the parent invocation of this function and decrement the count:
651        //
652        // *Upcoming tokens:* `;`
653        // *Unmatched count:* 2
654        // *`parse_path_segment` calls deep:* 1
655        //
656        // At this point, this function will expect to find another matching `>` character but
657        // won't be able to and will return an error. This will continue all the way up the
658        // call stack until the first invocation:
659        //
660        // *Upcoming tokens:* `;`
661        // *Unmatched count:* 2
662        // *`parse_path_segment` calls deep:* 0
663        //
664        // In doing this, we have managed to work out how many unmatched leading left angle
665        // brackets there are, but we cannot recover as the unmatched angle brackets have
666        // already been consumed. To remedy this, we keep a snapshot of the parser state
667        // before we do the above. We can then inspect whether we ended up with a parsing error
668        // and unmatched left angle brackets and if so, restore the parser state before we
669        // consumed any `<` characters to emit an error and consume the erroneous tokens to
670        // recover by attempting to parse again.
671        //
672        // In practice, the recursion of this function is indirect and there will be other
673        // locations that consume some `<` characters - as long as we update the count when
674        // this happens, it isn't an issue.
675
676        let is_first_invocation = style == PathStyle::Expr;
677        // Take a snapshot before attempting to parse - we can restore this later.
678        let snapshot = is_first_invocation.then(|| self.clone());
679
680        self.angle_bracket_nesting += 1;
681        {
    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_parse/src/parser/path.rs:681",
                        "rustc_parse::parser::path", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_parse/src/parser/path.rs"),
                        ::tracing_core::__macro_support::Option::Some(681u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::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!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
682        match self.parse_angle_args(ty_generics) {
683            Ok(args) => {
684                self.angle_bracket_nesting -= 1;
685                Ok(args)
686            }
687            Err(e) if self.angle_bracket_nesting > 10 => {
688                self.angle_bracket_nesting -= 1;
689                // When encountering severely malformed code where there are several levels of
690                // nested unclosed angle args (`f::<f::<f::<f::<...`), we avoid severe O(n^2)
691                // behavior by bailing out earlier (#117080).
692                e.emit_err().raise_fatal();
693            }
694            Err(e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
695                self.angle_bracket_nesting -= 1;
696
697                // Swap `self` with our backup of the parser state before attempting to parse
698                // generic arguments.
699                let snapshot = mem::replace(self, snapshot.unwrap());
700
701                // Eat the unmatched angle brackets.
702                let all_angle_brackets = (0..snapshot.unmatched_angle_bracket_count)
703                    .fold(true, |a, _| a && self.eat_lt());
704
705                if !all_angle_brackets {
706                    // If there are other tokens in between the extraneous `<`s, we cannot simply
707                    // suggest to remove them. This check also prevents us from accidentally ending
708                    // up in the middle of a multibyte character (issue #84104).
709                    let _ = mem::replace(self, snapshot);
710                    Err(e)
711                } else {
712                    // Cancel error from being unable to find `>`. We know the error
713                    // must have been this due to a non-zero unmatched angle bracket
714                    // count.
715                    e.cancel();
716
717                    {
    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_parse/src/parser/path.rs:717",
                        "rustc_parse::parser::path", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_parse/src/parser/path.rs"),
                        ::tracing_core::__macro_support::Option::Some(717u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::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!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) snapshot.count={0:?}",
                                                    snapshot.unmatched_angle_bracket_count) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
718                        "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
719                         snapshot.count={:?}",
720                        snapshot.unmatched_angle_bracket_count,
721                    );
722
723                    // Make a span over ${unmatched angle bracket count} characters.
724                    // This is safe because `all_angle_brackets` ensures that there are only `<`s,
725                    // i.e. no multibyte characters, in this range.
726                    let span = lo
727                        .with_hi(lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count.into()));
728                    self.dcx().emit_err(diagnostics::UnmatchedAngle {
729                        span,
730                        plural: snapshot.unmatched_angle_bracket_count > 1,
731                    });
732
733                    // Try again without unmatched angle bracket characters.
734                    self.parse_angle_args(ty_generics)
735                }
736            }
737            Err(e) => {
738                self.angle_bracket_nesting -= 1;
739                Err(e)
740            }
741        }
742    }
743
744    /// Parses (possibly empty) list of generic arguments / associated item constraints,
745    /// possibly including trailing comma.
746    pub(super) fn parse_angle_args(
747        &mut self,
748        ty_generics: Option<&Generics>,
749    ) -> PResult<'a, ThinVec<AngleBracketedArg>> {
750        let mut args = ThinVec::new();
751        while let Some(arg) = self.parse_angle_arg(ty_generics)? {
752            args.push(arg);
753            if !self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
754                if self.check_noexpect(&TokenKind::Semi)
755                    && self.look_ahead(1, |t| t.is_ident() || t.is_lifetime())
756                {
757                    // Add `>` to the list of expected tokens.
758                    self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Gt,
    token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt));
759                    // Handle `,` to `;` substitution
760                    let mut err = self.unexpected().unwrap_err();
761                    self.bump();
762                    err.span_suggestion_verbose(
763                        self.prev_token.span.until(self.token.span),
764                        "use a comma to separate type parameters",
765                        ", ",
766                        Applicability::MachineApplicable,
767                    );
768                    err.emit();
769                    continue;
770                }
771                if !self.token.kind.should_end_const_arg() {
772                    if let Some(arg @ AngleBracketedArg::Arg(GenericArg::Lifetime(_))) = args.last()
773                    {
774                        self.handle_lifetime_arg_preceding_type(arg.span())?;
775                    }
776                    if self.handle_ambiguous_unbraced_const_arg(&mut args)? {
777                        // We've managed to (partially) recover, so continue trying to parse
778                        // arguments.
779                        continue;
780                    }
781                }
782                break;
783            }
784        }
785        Ok(args)
786    }
787
788    /// Parses a single argument in the angle arguments `<...>` of a path segment.
789    fn parse_angle_arg(
790        &mut self,
791        ty_generics: Option<&Generics>,
792    ) -> PResult<'a, Option<AngleBracketedArg>> {
793        let lo = self.token.span;
794        let arg = self.parse_generic_arg(ty_generics)?;
795        match arg {
796            Some(arg) => {
797                // we are using noexpect here because we first want to find out if either `=` or `:`
798                // is present and then use that info to push the other token onto the tokens list
799                let separated =
800                    self.check_noexpect(&token::Colon) || self.check_noexpect(&token::Eq);
801                if separated && (self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Colon,
    token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon)) | self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq))) {
802                    let arg_span = arg.span();
803                    let (binder, ident, gen_args) = match self.get_ident_from_generic_arg(&arg) {
804                        Ok(ident_gen_args) => ident_gen_args,
805                        Err(()) => return Ok(Some(AngleBracketedArg::Arg(arg))),
806                    };
807                    if binder {
808                        // FIXME(compiler-errors): this could be improved by suggesting lifting
809                        // this up to the trait, at least before this becomes real syntax.
810                        // e.g. `Trait<for<'a> Assoc = Ty>` -> `for<'a> Trait<Assoc = Ty>`
811                        return Err(self.dcx().struct_span_err(
812                            arg_span,
813                            "`for<...>` is not allowed on associated type bounds",
814                        ));
815                    }
816                    let kind = if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Colon,
    token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon)) {
817                        AssocItemConstraintKind::Bound { bounds: self.parse_generic_bounds()? }
818                    } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
819                        self.parse_assoc_equality_term(ident, gen_args.as_ref())?
820                    } else {
821                        ::core::panicking::unreachable_default_msg();unreachable!();
822                    };
823
824                    let span = lo.to(self.prev_token.span);
825                    let constraint =
826                        AssocItemConstraint { id: ast::DUMMY_NODE_ID, ident, gen_args, kind, span };
827                    Ok(Some(AngleBracketedArg::Constraint(constraint)))
828                } else {
829                    // we only want to suggest `:` and `=` in contexts where the previous token
830                    // is an ident and the current token or the next token is an ident
831                    if self.prev_token.is_ident()
832                        && (self.token.is_ident() || self.look_ahead(1, |token| token.is_ident()))
833                    {
834                        self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Colon,
    token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon));
835                        self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq));
836                    }
837                    Ok(Some(AngleBracketedArg::Arg(arg)))
838                }
839            }
840            _ => Ok(None),
841        }
842    }
843
844    /// Parse the term to the right of an associated item equality constraint.
845    ///
846    /// That is, parse `$term` in `Item = $term` where `$term` is a type or
847    /// a const expression (wrapped in curly braces if complex).
848    fn parse_assoc_equality_term(
849        &mut self,
850        ident: Ident,
851        gen_args: Option<&GenericArgs>,
852    ) -> PResult<'a, AssocItemConstraintKind> {
853        let prev_token_span = self.prev_token.span;
854        let eq_span = self.token.span;
855        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq))?;
856        let arg = self.parse_generic_arg(None)?;
857        let span = ident.span.to(self.prev_token.span);
858        let term = match arg {
859            Some(GenericArg::Type(ty)) => ty.into(),
860            Some(GenericArg::Const(c)) => {
861                self.psess.gated_spans.gate(sym::associated_const_equality, span);
862                c.into()
863            }
864            Some(GenericArg::Lifetime(lt)) => {
865                let guar = self.dcx().emit_err(diagnostics::LifetimeInEqConstraint {
866                    span: lt.ident.span,
867                    lifetime: lt.ident,
868                    binding_label: span,
869                    colon_sugg: gen_args
870                        .map_or(ident.span, |args| args.span())
871                        .between(lt.ident.span),
872                });
873                self.mk_ty(lt.ident.span, ast::TyKind::Err(guar)).into()
874            }
875            None => {
876                let after_eq = eq_span.shrink_to_hi();
877                let before_next = self.token.span.shrink_to_lo();
878                let mut err = self
879                    .dcx()
880                    .struct_span_err(after_eq.to(before_next), "missing type to the right of `=`");
881                if #[allow(non_exhaustive_omitted_patterns)] match self.token.kind {
    token::Comma | token::Gt => true,
    _ => false,
}matches!(self.token.kind, token::Comma | token::Gt) {
882                    err.span_suggestion_verbose(
883                        self.psess.source_map().next_point(eq_span).to(before_next),
884                        "to constrain the associated type, add a type after `=`",
885                        " TheType",
886                        Applicability::HasPlaceholders,
887                    );
888                    err.span_suggestion_verbose(
889                        prev_token_span.shrink_to_hi().to(before_next),
890                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("remove the `=` if `{0}` is a type",
                ident))
    })format!("remove the `=` if `{ident}` is a type"),
891                        "",
892                        Applicability::MaybeIncorrect,
893                    )
894                } else {
895                    err.span_label(
896                        self.token.span,
897                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected type, found {0}",
                super::token_descr(&self.token)))
    })format!("expected type, found {}", super::token_descr(&self.token)),
898                    )
899                };
900                return Err(err);
901            }
902        };
903        Ok(AssocItemConstraintKind::Equality { term })
904    }
905
906    /// We do not permit arbitrary expressions as const arguments. They must be one of:
907    /// - An expression surrounded in `{}`.
908    /// - A literal.
909    /// - A numeric literal prefixed by `-`.
910    /// - A single-segment path.
911    /// - A const block (under mGCA)
912    pub(super) fn expr_is_valid_const_arg(&self, expr: &Box<rustc_ast::Expr>) -> bool {
913        match &expr.kind {
914            ast::ExprKind::Block(_, _)
915            | ast::ExprKind::Lit(_)
916            | ast::ExprKind::IncludedBytes(..) => true,
917            ast::ExprKind::Unary(ast::UnOp::Neg, expr) => {
918                #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    ast::ExprKind::Lit(_) => true,
    _ => false,
}matches!(expr.kind, ast::ExprKind::Lit(_))
919            }
920            // We can only resolve single-segment paths at the moment, because multi-segment paths
921            // require type-checking: see `visit_generic_arg` in `src/librustc_resolve/late.rs`.
922            ast::ExprKind::Path(None, path)
923                if let [segment] = path.segments.as_slice()
924                    && segment.args.is_none() =>
925            {
926                true
927            }
928            ast::ExprKind::ConstBlock(_) => {
929                self.psess.gated_spans.gate(sym::gca_min_const_items, expr.span);
930                true
931            }
932            _ => false,
933        }
934    }
935
936    /// Parse a const argument, e.g. `<3>`. It is assumed the angle brackets will be parsed by
937    /// the caller.
938    pub(super) fn parse_const_arg(&mut self) -> PResult<'a, AnonConst> {
939        // Parse const argument.
940        let value = if self.token.kind == token::OpenBrace {
941            self.parse_expr_block(None, self.token.span, BlockCheckMode::Default)?
942        } else {
943            self.parse_unambiguous_unbraced_const_arg()?
944        };
945        Ok(AnonConst { id: ast::DUMMY_NODE_ID, value })
946    }
947
948    /// Attempt to parse a const argument that has not been enclosed in braces.
949    /// There are a limited number of expressions that are permitted without being
950    /// enclosed in braces:
951    /// - Literals.
952    /// - Single-segment paths (i.e. standalone generic const parameters).
953    /// All other expressions that can be parsed will emit an error suggesting the expression be
954    /// wrapped in braces.
955    pub(super) fn parse_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, Box<Expr>> {
956        let start = self.token.span;
957        let expr = self.parse_expr_res(Restrictions::CONST_EXPR).map_err(|mut err| {
958            err.span_label(
959                start.shrink_to_lo(),
960                "while parsing a const generic argument starting here",
961            );
962            err
963        })?;
964        if !self.expr_is_valid_const_arg(&expr) {
965            return Err(self.dcx().create_err(ConstGenericWithoutBraces {
966                span: expr.span,
967                sugg: ConstGenericWithoutBracesSugg {
968                    left: expr.span.shrink_to_lo(),
969                    right: expr.span.shrink_to_hi(),
970                },
971            }));
972        }
973
974        Ok(expr)
975    }
976
977    /// Parse a generic argument in a path segment.
978    /// This does not include constraints, e.g., `Item = u8`, which is handled in `parse_angle_arg`.
979    pub(super) fn parse_generic_arg(
980        &mut self,
981        ty_generics: Option<&Generics>,
982    ) -> PResult<'a, Option<GenericArg>> {
983        self.recover_from_outer_attributes("generic arguments")?;
984
985        let start = self.token.span;
986        let arg = if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
987            // Parse lifetime argument.
988            GenericArg::Lifetime(self.expect_lifetime())
989        } else if self.check_const_arg() {
990            // Parse const argument.
991            GenericArg::Const(self.parse_const_arg()?)
992        } else if self.check_type() {
993            // Parse type argument.
994
995            // Proactively create a parser snapshot enabling us to rewind and try to reparse the
996            // input as a const expression in case we fail to parse a type. If we successfully
997            // do so, we will report an error that it needs to be wrapped in braces.
998            let mut snapshot = None;
999            if self.may_recover() && self.token.can_begin_expr() {
1000                snapshot = Some(self.create_snapshot_for_diagnostic());
1001            }
1002
1003            match self.parse_ty() {
1004                Ok(ty) => GenericArg::Type(ty),
1005                Err(err) => {
1006                    if let Some(snapshot) = snapshot
1007                        && let Some(expr) =
1008                            self.recover_unbraced_const_arg_that_can_begin_ty(snapshot)
1009                    {
1010                        return Ok(Some(self.dummy_const_arg_needs_braces(err, expr.span)));
1011                    }
1012                    // Try to recover from possible `const` arg without braces.
1013                    return self.recover_const_arg(start, err).map(Some);
1014                }
1015            }
1016        } else if self.token.is_keyword(kw::Const) {
1017            return self.recover_const_param_declaration(ty_generics);
1018        } else {
1019            // Fall back by trying to parse a const-expr expression. If we successfully do so,
1020            // then we should report an error that it needs to be wrapped in braces.
1021            let snapshot = self.create_snapshot_for_diagnostic();
1022            match self.parse_expr_res(Restrictions::CONST_EXPR) {
1023                Ok(expr) => {
1024                    return Ok(Some(self.dummy_const_arg_needs_braces(
1025                        self.dcx().struct_span_err(expr.span, "invalid const generic expression"),
1026                        expr.span,
1027                    )));
1028                }
1029                Err(err) => {
1030                    self.restore_snapshot(snapshot);
1031                    err.cancel();
1032                    return Ok(None);
1033                }
1034            }
1035        };
1036
1037        Ok(Some(arg))
1038    }
1039
1040    /// Given a arg inside of generics, we try to destructure it as if it were the LHS in
1041    /// `LHS = ...`, i.e. an associated item binding.
1042    /// This returns a bool indicating if there are any `for<'a, 'b>` binder args, the
1043    /// identifier, and any GAT arguments.
1044    fn get_ident_from_generic_arg(
1045        &self,
1046        gen_arg: &GenericArg,
1047    ) -> Result<(bool, Ident, Option<GenericArgs>), ()> {
1048        if let GenericArg::Type(ty) = gen_arg {
1049            if let ast::TyKind::Path(qself, path) = &ty.kind
1050                && qself.is_none()
1051                && let [seg] = path.segments.as_slice()
1052            {
1053                return Ok((false, seg.ident, seg.args.as_deref().cloned()));
1054            } else if let ast::TyKind::TraitObject(bounds, ast::TraitObjectSyntax::None) = &ty.kind
1055                && let [ast::GenericBound::Trait(trait_ref)] = bounds.as_slice()
1056                && trait_ref.modifiers == ast::TraitBoundModifiers::NONE
1057                && let [seg] = trait_ref.trait_ref.path.segments.as_slice()
1058            {
1059                return Ok((true, seg.ident, seg.args.as_deref().cloned()));
1060            }
1061        }
1062        Err(())
1063    }
1064}
1065
1066/// Chains `span` into `node_span`.
1067fn chain_span(node_span: &mut Option<Span>, span: Span) {
1068    *node_span = Some(node_span.map_or(span, |s| s.to(span)));
1069}