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