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                // IMPORTANT: We can *only ever* treat single colons as typo'ed double colons in
252                // expression contexts (!) since only there paths cannot possibly be followed by
253                // a colon and still form a syntactically valid construct. In pattern contexts,
254                // a path may be followed by a type annotation. E.g., `let pat:ty`. In type
255                // contexts, a path may be followed by a list of bounds. E.g., `where ty:bound`.
256                if self.may_recover()
257                    && style == PathStyle::Expr // (!)
258                    && self.token == token::Colon
259                    && self.look_ahead(1, |token| token.is_ident() && !token.is_reserved_ident())
260                {
261                    // Emit a special error message for `a::b:c` to help users
262                    // otherwise, `a: c` might have meant to introduce a new binding
263                    if self.token.span.lo() == self.prev_token.span.hi()
264                        && self.look_ahead(1, |token| self.token.span.hi() == token.span.lo())
265                    {
266                        self.bump(); // bump past the colon
267                        self.dcx().emit_err(PathSingleColon {
268                            span: self.prev_token.span,
269                            suggestion: self.prev_token.span.shrink_to_hi(),
270                            type_ascription: self.psess.unstable_features.is_nightly_build(),
271                        });
272                    }
273                    continue;
274                }
275
276                return Ok(());
277            }
278        }
279    }
280
281    /// Eat `::` or, potentially, `:::`.
282    #[must_use]
283    pub(super) fn eat_path_sep(&mut self) -> bool {
284        let result = self.eat(exp!(PathSep));
285        if result && self.may_recover() {
286            if self.eat_noexpect(&token::Colon) {
287                self.dcx().emit_err(PathTripleColon { span: self.prev_token.span });
288            }
289        }
290        result
291    }
292
293    pub(super) fn parse_path_segment(
294        &mut self,
295        style: PathStyle,
296        ty_generics: Option<&Generics>,
297    ) -> PResult<'a, PathSegment> {
298        let ident = self.parse_path_segment_ident()?;
299        let is_args_start = |token: &Token| {
300            matches!(
301                token.kind,
302                token::Lt | token::Shl | token::OpenDelim(Delimiter::Parenthesis) | token::LArrow
303            )
304        };
305        let check_args_start = |this: &mut Self| {
306            this.expected_token_types.insert(TokenType::Lt);
307            this.expected_token_types.insert(TokenType::OpenParen);
308            is_args_start(&this.token)
309        };
310
311        Ok(
312            if style == PathStyle::Type && check_args_start(self)
313                || style != PathStyle::Mod && self.check_path_sep_and_look_ahead(is_args_start)
314            {
315                // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
316                // it isn't, then we reset the unmatched angle bracket count as we're about to start
317                // parsing a new path.
318                if style == PathStyle::Expr {
319                    self.unmatched_angle_bracket_count = 0;
320                }
321
322                // Generic arguments are found - `<`, `(`, `::<` or `::(`.
323                // First, eat `::` if it exists.
324                let _ = self.eat_path_sep();
325
326                let lo = self.token.span;
327                let args = if self.eat_lt() {
328                    // `<'a, T, A = U>`
329                    let args = self.parse_angle_args_with_leading_angle_bracket_recovery(
330                        style,
331                        lo,
332                        ty_generics,
333                    )?;
334                    self.expect_gt().map_err(|mut err| {
335                        // Try to recover a `:` into a `::`
336                        if self.token == token::Colon
337                            && self.look_ahead(1, |token| {
338                                token.is_ident() && !token.is_reserved_ident()
339                            })
340                        {
341                            err.cancel();
342                            err = self.dcx().create_err(PathSingleColon {
343                                span: self.token.span,
344                                suggestion: self.prev_token.span.shrink_to_hi(),
345                                type_ascription: self.psess.unstable_features.is_nightly_build(),
346                            });
347                        }
348                        // Attempt to find places where a missing `>` might belong.
349                        else if let Some(arg) = args
350                            .iter()
351                            .rev()
352                            .find(|arg| !matches!(arg, AngleBracketedArg::Constraint(_)))
353                        {
354                            err.span_suggestion_verbose(
355                                arg.span().shrink_to_hi(),
356                                "you might have meant to end the type parameters here",
357                                ">",
358                                Applicability::MaybeIncorrect,
359                            );
360                        }
361                        err
362                    })?;
363                    let span = lo.to(self.prev_token.span);
364                    AngleBracketedArgs { args, span }.into()
365                } else if self.token == token::OpenDelim(Delimiter::Parenthesis)
366                    // FIXME(return_type_notation): Could also recover `...` here.
367                    && self.look_ahead(1, |t| *t == token::DotDot)
368                {
369                    self.bump(); // (
370                    self.bump(); // ..
371                    self.expect(exp!(CloseParen))?;
372                    let span = lo.to(self.prev_token.span);
373
374                    self.psess.gated_spans.gate(sym::return_type_notation, span);
375
376                    let prev_lo = self.prev_token.span.shrink_to_hi();
377                    if self.eat_noexpect(&token::RArrow) {
378                        let lo = self.prev_token.span;
379                        let ty = self.parse_ty()?;
380                        let span = lo.to(ty.span);
381                        let suggestion = prev_lo.to(ty.span);
382                        self.dcx()
383                            .emit_err(errors::BadReturnTypeNotationOutput { span, suggestion });
384                    }
385
386                    P(ast::GenericArgs::ParenthesizedElided(span))
387                } else {
388                    // `(T, U) -> R`
389
390                    let prev_token_before_parsing = self.prev_token.clone();
391                    let token_before_parsing = self.token.clone();
392                    let mut snapshot = None;
393                    if self.may_recover()
394                        && prev_token_before_parsing == token::PathSep
395                        && (style == PathStyle::Expr && self.token.can_begin_expr()
396                            || style == PathStyle::Pat
397                                && self.token.can_begin_pattern(token::NtPatKind::PatParam {
398                                    inferred: false,
399                                }))
400                    {
401                        snapshot = Some(self.create_snapshot_for_diagnostic());
402                    }
403
404                    let (inputs, _) = match self.parse_paren_comma_seq(|p| p.parse_ty()) {
405                        Ok(output) => output,
406                        Err(mut error) if prev_token_before_parsing == token::PathSep => {
407                            error.span_label(
408                                prev_token_before_parsing.span.to(token_before_parsing.span),
409                                "while parsing this parenthesized list of type arguments starting here",
410                            );
411
412                            if let Some(mut snapshot) = snapshot {
413                                snapshot.recover_fn_call_leading_path_sep(
414                                    style,
415                                    prev_token_before_parsing,
416                                    &mut error,
417                                )
418                            }
419
420                            return Err(error);
421                        }
422                        Err(error) => return Err(error),
423                    };
424                    let inputs_span = lo.to(self.prev_token.span);
425                    let output =
426                        self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)?;
427                    let span = ident.span.to(self.prev_token.span);
428                    ParenthesizedArgs { span, inputs, inputs_span, output }.into()
429                };
430
431                PathSegment { ident, args: Some(args), id: ast::DUMMY_NODE_ID }
432            } else {
433                // Generic arguments are not found.
434                PathSegment::from_ident(ident)
435            },
436        )
437    }
438
439    pub(super) fn parse_path_segment_ident(&mut self) -> PResult<'a, Ident> {
440        match self.token.ident() {
441            Some((ident, IdentIsRaw::No)) if ident.is_path_segment_keyword() => {
442                self.bump();
443                Ok(ident)
444            }
445            _ => self.parse_ident(),
446        }
447    }
448
449    /// Recover `$path::(...)` as `$path(...)`.
450    ///
451    /// ```ignore (diagnostics)
452    /// foo::(420, "bar")
453    ///    ^^ remove extra separator to make the function call
454    /// // or
455    /// match x {
456    ///    Foo::(420, "bar") => { ... },
457    ///       ^^ remove extra separator to turn this into tuple struct pattern
458    ///    _ => { ... },
459    /// }
460    /// ```
461    fn recover_fn_call_leading_path_sep(
462        &mut self,
463        style: PathStyle,
464        prev_token_before_parsing: Token,
465        error: &mut Diag<'_>,
466    ) {
467        match style {
468            PathStyle::Expr
469                if let Ok(_) = self
470                    .parse_paren_comma_seq(|p| p.parse_expr())
471                    .map_err(|error| error.cancel()) => {}
472            PathStyle::Pat
473                if let Ok(_) = self
474                    .parse_paren_comma_seq(|p| {
475                        p.parse_pat_allow_top_guard(
476                            None,
477                            RecoverComma::No,
478                            RecoverColon::No,
479                            CommaRecoveryMode::LikelyTuple,
480                        )
481                    })
482                    .map_err(|error| error.cancel()) => {}
483            _ => {
484                return;
485            }
486        }
487
488        if let token::PathSep | token::RArrow = self.token.kind {
489            return;
490        }
491
492        error.span_suggestion_verbose(
493            prev_token_before_parsing.span,
494            format!(
495                "consider removing the `::` here to {}",
496                match style {
497                    PathStyle::Expr => "call the expression",
498                    PathStyle::Pat => "turn this into a tuple struct pattern",
499                    _ => {
500                        return;
501                    }
502                }
503            ),
504            "",
505            Applicability::MaybeIncorrect,
506        );
507    }
508
509    /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
510    /// For the purposes of understanding the parsing logic of generic arguments, this function
511    /// can be thought of being the same as just calling `self.parse_angle_args()` if the source
512    /// had the correct amount of leading angle brackets.
513    ///
514    /// ```ignore (diagnostics)
515    /// bar::<<<<T as Foo>::Output>();
516    ///      ^^ help: remove extra angle brackets
517    /// ```
518    fn parse_angle_args_with_leading_angle_bracket_recovery(
519        &mut self,
520        style: PathStyle,
521        lo: Span,
522        ty_generics: Option<&Generics>,
523    ) -> PResult<'a, ThinVec<AngleBracketedArg>> {
524        // We need to detect whether there are extra leading left angle brackets and produce an
525        // appropriate error and suggestion. This cannot be implemented by looking ahead at
526        // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
527        // then there won't be matching `>` tokens to find.
528        //
529        // To explain how this detection works, consider the following example:
530        //
531        // ```ignore (diagnostics)
532        // bar::<<<<T as Foo>::Output>();
533        //      ^^ help: remove extra angle brackets
534        // ```
535        //
536        // Parsing of the left angle brackets starts in this function. We start by parsing the
537        // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
538        // `eat_lt`):
539        //
540        // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
541        // *Unmatched count:* 1
542        // *`parse_path_segment` calls deep:* 0
543        //
544        // This has the effect of recursing as this function is called if a `<` character
545        // is found within the expected generic arguments:
546        //
547        // *Upcoming tokens:* `<<<T as Foo>::Output>;`
548        // *Unmatched count:* 2
549        // *`parse_path_segment` calls deep:* 1
550        //
551        // Eventually we will have recursed until having consumed all of the `<` tokens and
552        // this will be reflected in the count:
553        //
554        // *Upcoming tokens:* `T as Foo>::Output>;`
555        // *Unmatched count:* 4
556        // `parse_path_segment` calls deep:* 3
557        //
558        // The parser will continue until reaching the first `>` - this will decrement the
559        // unmatched angle bracket count and return to the parent invocation of this function
560        // having succeeded in parsing:
561        //
562        // *Upcoming tokens:* `::Output>;`
563        // *Unmatched count:* 3
564        // *`parse_path_segment` calls deep:* 2
565        //
566        // This will continue until the next `>` character which will also return successfully
567        // to the parent invocation of this function and decrement the count:
568        //
569        // *Upcoming tokens:* `;`
570        // *Unmatched count:* 2
571        // *`parse_path_segment` calls deep:* 1
572        //
573        // At this point, this function will expect to find another matching `>` character but
574        // won't be able to and will return an error. This will continue all the way up the
575        // call stack until the first invocation:
576        //
577        // *Upcoming tokens:* `;`
578        // *Unmatched count:* 2
579        // *`parse_path_segment` calls deep:* 0
580        //
581        // In doing this, we have managed to work out how many unmatched leading left angle
582        // brackets there are, but we cannot recover as the unmatched angle brackets have
583        // already been consumed. To remedy this, we keep a snapshot of the parser state
584        // before we do the above. We can then inspect whether we ended up with a parsing error
585        // and unmatched left angle brackets and if so, restore the parser state before we
586        // consumed any `<` characters to emit an error and consume the erroneous tokens to
587        // recover by attempting to parse again.
588        //
589        // In practice, the recursion of this function is indirect and there will be other
590        // locations that consume some `<` characters - as long as we update the count when
591        // this happens, it isn't an issue.
592
593        let is_first_invocation = style == PathStyle::Expr;
594        // Take a snapshot before attempting to parse - we can restore this later.
595        let snapshot = is_first_invocation.then(|| self.clone());
596
597        self.angle_bracket_nesting += 1;
598        debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
599        match self.parse_angle_args(ty_generics) {
600            Ok(args) => {
601                self.angle_bracket_nesting -= 1;
602                Ok(args)
603            }
604            Err(e) if self.angle_bracket_nesting > 10 => {
605                self.angle_bracket_nesting -= 1;
606                // When encountering severely malformed code where there are several levels of
607                // nested unclosed angle args (`f::<f::<f::<f::<...`), we avoid severe O(n^2)
608                // behavior by bailing out earlier (#117080).
609                e.emit().raise_fatal();
610            }
611            Err(e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
612                self.angle_bracket_nesting -= 1;
613
614                // Swap `self` with our backup of the parser state before attempting to parse
615                // generic arguments.
616                let snapshot = mem::replace(self, snapshot.unwrap());
617
618                // Eat the unmatched angle brackets.
619                let all_angle_brackets = (0..snapshot.unmatched_angle_bracket_count)
620                    .fold(true, |a, _| a && self.eat_lt());
621
622                if !all_angle_brackets {
623                    // If there are other tokens in between the extraneous `<`s, we cannot simply
624                    // suggest to remove them. This check also prevents us from accidentally ending
625                    // up in the middle of a multibyte character (issue #84104).
626                    let _ = mem::replace(self, snapshot);
627                    Err(e)
628                } else {
629                    // Cancel error from being unable to find `>`. We know the error
630                    // must have been this due to a non-zero unmatched angle bracket
631                    // count.
632                    e.cancel();
633
634                    debug!(
635                        "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
636                         snapshot.count={:?}",
637                        snapshot.unmatched_angle_bracket_count,
638                    );
639
640                    // Make a span over ${unmatched angle bracket count} characters.
641                    // This is safe because `all_angle_brackets` ensures that there are only `<`s,
642                    // i.e. no multibyte characters, in this range.
643                    let span = lo
644                        .with_hi(lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count.into()));
645                    self.dcx().emit_err(errors::UnmatchedAngle {
646                        span,
647                        plural: snapshot.unmatched_angle_bracket_count > 1,
648                    });
649
650                    // Try again without unmatched angle bracket characters.
651                    self.parse_angle_args(ty_generics)
652                }
653            }
654            Err(e) => {
655                self.angle_bracket_nesting -= 1;
656                Err(e)
657            }
658        }
659    }
660
661    /// Parses (possibly empty) list of generic arguments / associated item constraints,
662    /// possibly including trailing comma.
663    pub(super) fn parse_angle_args(
664        &mut self,
665        ty_generics: Option<&Generics>,
666    ) -> PResult<'a, ThinVec<AngleBracketedArg>> {
667        let mut args = ThinVec::new();
668        while let Some(arg) = self.parse_angle_arg(ty_generics)? {
669            args.push(arg);
670            if !self.eat(exp!(Comma)) {
671                if self.check_noexpect(&TokenKind::Semi)
672                    && self.look_ahead(1, |t| t.is_ident() || t.is_lifetime())
673                {
674                    // Add `>` to the list of expected tokens.
675                    self.check(exp!(Gt));
676                    // Handle `,` to `;` substitution
677                    let mut err = self.unexpected().unwrap_err();
678                    self.bump();
679                    err.span_suggestion_verbose(
680                        self.prev_token.span.until(self.token.span),
681                        "use a comma to separate type parameters",
682                        ", ",
683                        Applicability::MachineApplicable,
684                    );
685                    err.emit();
686                    continue;
687                }
688                if !self.token.kind.should_end_const_arg()
689                    && self.handle_ambiguous_unbraced_const_arg(&mut args)?
690                {
691                    // We've managed to (partially) recover, so continue trying to parse
692                    // arguments.
693                    continue;
694                }
695                break;
696            }
697        }
698        Ok(args)
699    }
700
701    /// Parses a single argument in the angle arguments `<...>` of a path segment.
702    fn parse_angle_arg(
703        &mut self,
704        ty_generics: Option<&Generics>,
705    ) -> PResult<'a, Option<AngleBracketedArg>> {
706        let lo = self.token.span;
707        let arg = self.parse_generic_arg(ty_generics)?;
708        match arg {
709            Some(arg) => {
710                // we are using noexpect here because we first want to find out if either `=` or `:`
711                // is present and then use that info to push the other token onto the tokens list
712                let separated =
713                    self.check_noexpect(&token::Colon) || self.check_noexpect(&token::Eq);
714                if separated && (self.check(exp!(Colon)) | self.check(exp!(Eq))) {
715                    let arg_span = arg.span();
716                    let (binder, ident, gen_args) = match self.get_ident_from_generic_arg(&arg) {
717                        Ok(ident_gen_args) => ident_gen_args,
718                        Err(()) => return Ok(Some(AngleBracketedArg::Arg(arg))),
719                    };
720                    if binder {
721                        // FIXME(compiler-errors): this could be improved by suggesting lifting
722                        // this up to the trait, at least before this becomes real syntax.
723                        // e.g. `Trait<for<'a> Assoc = Ty>` -> `for<'a> Trait<Assoc = Ty>`
724                        return Err(self.dcx().struct_span_err(
725                            arg_span,
726                            "`for<...>` is not allowed on associated type bounds",
727                        ));
728                    }
729                    let kind = if self.eat(exp!(Colon)) {
730                        AssocItemConstraintKind::Bound { bounds: self.parse_generic_bounds()? }
731                    } else if self.eat(exp!(Eq)) {
732                        self.parse_assoc_equality_term(
733                            ident,
734                            gen_args.as_ref(),
735                            self.prev_token.span,
736                        )?
737                    } else {
738                        unreachable!();
739                    };
740
741                    let span = lo.to(self.prev_token.span);
742
743                    let constraint =
744                        AssocItemConstraint { id: ast::DUMMY_NODE_ID, ident, gen_args, kind, span };
745                    Ok(Some(AngleBracketedArg::Constraint(constraint)))
746                } else {
747                    // we only want to suggest `:` and `=` in contexts where the previous token
748                    // is an ident and the current token or the next token is an ident
749                    if self.prev_token.is_ident()
750                        && (self.token.is_ident() || self.look_ahead(1, |token| token.is_ident()))
751                    {
752                        self.check(exp!(Colon));
753                        self.check(exp!(Eq));
754                    }
755                    Ok(Some(AngleBracketedArg::Arg(arg)))
756                }
757            }
758            _ => Ok(None),
759        }
760    }
761
762    /// Parse the term to the right of an associated item equality constraint.
763    ///
764    /// That is, parse `$term` in `Item = $term` where `$term` is a type or
765    /// a const expression (wrapped in curly braces if complex).
766    fn parse_assoc_equality_term(
767        &mut self,
768        ident: Ident,
769        gen_args: Option<&GenericArgs>,
770        eq: Span,
771    ) -> PResult<'a, AssocItemConstraintKind> {
772        let arg = self.parse_generic_arg(None)?;
773        let span = ident.span.to(self.prev_token.span);
774        let term = match arg {
775            Some(GenericArg::Type(ty)) => ty.into(),
776            Some(GenericArg::Const(c)) => {
777                self.psess.gated_spans.gate(sym::associated_const_equality, span);
778                c.into()
779            }
780            Some(GenericArg::Lifetime(lt)) => {
781                let guar = self.dcx().emit_err(errors::LifetimeInEqConstraint {
782                    span: lt.ident.span,
783                    lifetime: lt.ident,
784                    binding_label: span,
785                    colon_sugg: gen_args
786                        .map_or(ident.span, |args| args.span())
787                        .between(lt.ident.span),
788                });
789                self.mk_ty(lt.ident.span, ast::TyKind::Err(guar)).into()
790            }
791            None => {
792                let after_eq = eq.shrink_to_hi();
793                let before_next = self.token.span.shrink_to_lo();
794                let mut err = self
795                    .dcx()
796                    .struct_span_err(after_eq.to(before_next), "missing type to the right of `=`");
797                if matches!(self.token.kind, token::Comma | token::Gt) {
798                    err.span_suggestion(
799                        self.psess.source_map().next_point(eq).to(before_next),
800                        "to constrain the associated type, add a type after `=`",
801                        " TheType",
802                        Applicability::HasPlaceholders,
803                    );
804                    err.span_suggestion(
805                        eq.to(before_next),
806                        format!("remove the `=` if `{ident}` is a type"),
807                        "",
808                        Applicability::MaybeIncorrect,
809                    )
810                } else {
811                    err.span_label(
812                        self.token.span,
813                        format!("expected type, found {}", super::token_descr(&self.token)),
814                    )
815                };
816                return Err(err);
817            }
818        };
819        Ok(AssocItemConstraintKind::Equality { term })
820    }
821
822    /// We do not permit arbitrary expressions as const arguments. They must be one of:
823    /// - An expression surrounded in `{}`.
824    /// - A literal.
825    /// - A numeric literal prefixed by `-`.
826    /// - A single-segment path.
827    pub(super) fn expr_is_valid_const_arg(&self, expr: &P<rustc_ast::Expr>) -> bool {
828        match &expr.kind {
829            ast::ExprKind::Block(_, _)
830            | ast::ExprKind::Lit(_)
831            | ast::ExprKind::IncludedBytes(..) => true,
832            ast::ExprKind::Unary(ast::UnOp::Neg, expr) => {
833                matches!(expr.kind, ast::ExprKind::Lit(_))
834            }
835            // We can only resolve single-segment paths at the moment, because multi-segment paths
836            // require type-checking: see `visit_generic_arg` in `src/librustc_resolve/late.rs`.
837            ast::ExprKind::Path(None, path)
838                if let [segment] = path.segments.as_slice()
839                    && segment.args.is_none() =>
840            {
841                true
842            }
843            _ => false,
844        }
845    }
846
847    /// Parse a const argument, e.g. `<3>`. It is assumed the angle brackets will be parsed by
848    /// the caller.
849    pub(super) fn parse_const_arg(&mut self) -> PResult<'a, AnonConst> {
850        // Parse const argument.
851        let value = if let token::OpenDelim(Delimiter::Brace) = self.token.kind {
852            self.parse_expr_block(None, self.token.span, BlockCheckMode::Default)?
853        } else {
854            self.handle_unambiguous_unbraced_const_arg()?
855        };
856        Ok(AnonConst { id: ast::DUMMY_NODE_ID, value })
857    }
858
859    /// Parse a generic argument in a path segment.
860    /// This does not include constraints, e.g., `Item = u8`, which is handled in `parse_angle_arg`.
861    pub(super) fn parse_generic_arg(
862        &mut self,
863        ty_generics: Option<&Generics>,
864    ) -> PResult<'a, Option<GenericArg>> {
865        let start = self.token.span;
866        let arg = if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
867            // Parse lifetime argument.
868            GenericArg::Lifetime(self.expect_lifetime())
869        } else if self.check_const_arg() {
870            // Parse const argument.
871            GenericArg::Const(self.parse_const_arg()?)
872        } else if self.check_type() {
873            // Parse type argument.
874
875            // Proactively create a parser snapshot enabling us to rewind and try to reparse the
876            // input as a const expression in case we fail to parse a type. If we successfully
877            // do so, we will report an error that it needs to be wrapped in braces.
878            let mut snapshot = None;
879            if self.may_recover() && self.token.can_begin_expr() {
880                snapshot = Some(self.create_snapshot_for_diagnostic());
881            }
882
883            match self.parse_ty() {
884                Ok(ty) => {
885                    // Since the type parser recovers from some malformed slice and array types and
886                    // successfully returns a type, we need to look for `TyKind::Err`s in the
887                    // type to determine if error recovery has occurred and if the input is not a
888                    // syntactically valid type after all.
889                    if let ast::TyKind::Slice(inner_ty) | ast::TyKind::Array(inner_ty, _) = &ty.kind
890                        && let ast::TyKind::Err(_) = inner_ty.kind
891                        && let Some(snapshot) = snapshot
892                        && let Some(expr) =
893                            self.recover_unbraced_const_arg_that_can_begin_ty(snapshot)
894                    {
895                        return Ok(Some(
896                            self.dummy_const_arg_needs_braces(
897                                self.dcx()
898                                    .struct_span_err(expr.span, "invalid const generic expression"),
899                                expr.span,
900                            ),
901                        ));
902                    }
903
904                    GenericArg::Type(ty)
905                }
906                Err(err) => {
907                    if let Some(snapshot) = snapshot
908                        && let Some(expr) =
909                            self.recover_unbraced_const_arg_that_can_begin_ty(snapshot)
910                    {
911                        return Ok(Some(self.dummy_const_arg_needs_braces(err, expr.span)));
912                    }
913                    // Try to recover from possible `const` arg without braces.
914                    return self.recover_const_arg(start, err).map(Some);
915                }
916            }
917        } else if self.token.is_keyword(kw::Const) {
918            return self.recover_const_param_declaration(ty_generics);
919        } else {
920            // Fall back by trying to parse a const-expr expression. If we successfully do so,
921            // then we should report an error that it needs to be wrapped in braces.
922            let snapshot = self.create_snapshot_for_diagnostic();
923            let attrs = self.parse_outer_attributes()?;
924            match self.parse_expr_res(Restrictions::CONST_EXPR, attrs) {
925                Ok((expr, _)) => {
926                    return Ok(Some(self.dummy_const_arg_needs_braces(
927                        self.dcx().struct_span_err(expr.span, "invalid const generic expression"),
928                        expr.span,
929                    )));
930                }
931                Err(err) => {
932                    self.restore_snapshot(snapshot);
933                    err.cancel();
934                    return Ok(None);
935                }
936            }
937        };
938        Ok(Some(arg))
939    }
940
941    /// Given a arg inside of generics, we try to destructure it as if it were the LHS in
942    /// `LHS = ...`, i.e. an associated item binding.
943    /// This returns a bool indicating if there are any `for<'a, 'b>` binder args, the
944    /// identifier, and any GAT arguments.
945    fn get_ident_from_generic_arg(
946        &self,
947        gen_arg: &GenericArg,
948    ) -> Result<(bool, Ident, Option<GenericArgs>), ()> {
949        if let GenericArg::Type(ty) = gen_arg {
950            if let ast::TyKind::Path(qself, path) = &ty.kind
951                && qself.is_none()
952                && let [seg] = path.segments.as_slice()
953            {
954                return Ok((false, seg.ident, seg.args.as_deref().cloned()));
955            } else if let ast::TyKind::TraitObject(bounds, ast::TraitObjectSyntax::None) = &ty.kind
956                && let [ast::GenericBound::Trait(trait_ref)] = bounds.as_slice()
957                && trait_ref.modifiers == ast::TraitBoundModifiers::NONE
958                && let [seg] = trait_ref.trait_ref.path.segments.as_slice()
959            {
960                return Ok((true, seg.ident, seg.args.as_deref().cloned()));
961            }
962        }
963        Err(())
964    }
965}