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