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