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