rustc_parse/parser/
path.rs

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