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