rustc_parse/parser/
path.rs

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