1use std::mem;
2
3use rustc_ast::token::{self, MetaVarKind, Token, TokenKind};
4use rustc_ast::{
5 self as ast, AngleBracketedArg, AngleBracketedArgs, AnonConst, AssocItemConstraint,
6 AssocItemConstraintKind, BlockCheckMode, GenericArg, GenericArgs, Generics, ParenthesizedArgs,
7 Path, PathSegment, QSelf,
8};
9use rustc_errors::{Applicability, Diag, PResult};
10use rustc_span::{BytePos, Ident, Span, kw, sym};
11use thin_vec::ThinVec;
12use tracing::debug;
13
14use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
15use super::{Parser, Restrictions, TokenType};
16use crate::ast::{PatKind, TyKind};
17use crate::diagnostics::{
18 self, ConstGenericWithoutBraces, ConstGenericWithoutBracesSugg, PathSingleColon,
19 PathTripleColon,
20};
21use crate::exp;
22use crate::parser::{CommaRecoveryMode, Expr, FnContext, FnParseMode, RecoverColon, RecoverComma};
23
24#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for PathStyle
{
}
#[automatically_derived]impl ::core::cmp::PartialEq for PathStyle {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
26pub enum PathStyle {
27 Expr,
37 Pat,
46 Type,
50 Mod,
57}
58
59impl PathStyle {
60 fn has_generic_ambiguity(&self) -> bool {
61 #[allow(non_exhaustive_omitted_patterns)] match self {
Self::Expr | Self::Pat => true,
_ => false,
}matches!(self, Self::Expr | Self::Pat)
62 }
63}
64
65impl<'a> Parser<'a> {
66 pub(super) fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (Box<QSelf>, Path)> {
77 let mut qpath_span = Some(self.prev_token.span);
78 let ty = self.parse_ty()?;
79 chain_span(&mut qpath_span, ty.span);
80
81 let (mut path, path_span);
86 if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::As,
token_type: crate::parser::token_type::TokenType::KwAs,
}exp!(As)) {
87 chain_span(&mut qpath_span, self.prev_token.span);
88 path = self.parse_path(PathStyle::Type)?;
89 path_span = path.span;
90 chain_span(&mut qpath_span, path_span);
91 } else {
92 path_span = self.token.span; path = ast::Path { segments: ThinVec::new(), span: path_span };
94 }
95
96 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Gt,
token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt))?;
98 chain_span(&mut qpath_span, self.prev_token.span);
99 if self.unmatched_angle_bracket_count > 0 {
100 self.unmatched_angle_bracket_count -= 1;
101 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_parse/src/parser/path.rs:101",
"rustc_parse::parser::path", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_parse/src/parser/path.rs"),
::tracing_core::__macro_support::Option::Some(101u32),
::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);
102 }
103
104 let is_import_coupler = self.is_import_coupler();
105 if !is_import_coupler && !self.recover_colon_before_qpath_proj() {
106 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::PathSep,
token_type: crate::parser::token_type::TokenType::PathSep,
}exp!(PathSep))?;
107 }
108
109 let qself = Box::new(QSelf { ty, path_span, position: path.segments.len() });
110 if !is_import_coupler {
111 chain_span(&mut qpath_span, self.prev_token.span); self.parse_path_segments_with_path_span(
113 &mut path.segments,
114 style,
115 None,
116 &mut qpath_span,
117 )?;
118 }
119
120 Ok((qself, Path { segments: path.segments, span: qpath_span.unwrap() }))
121 }
122
123 fn recover_colon_before_qpath_proj(&mut self) -> bool {
132 if !self.check_noexpect(&TokenKind::Colon)
133 || self.look_ahead(1, |t| !t.is_non_reserved_ident())
134 {
135 return false;
136 }
137
138 self.bump(); self.dcx()
141 .struct_span_err(
142 self.prev_token.span,
143 "found single colon before projection in qualified path",
144 )
145 .with_span_suggestion(
146 self.prev_token.span,
147 "use double colon",
148 "::",
149 Applicability::MachineApplicable,
150 )
151 .emit();
152
153 true
154 }
155
156 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, Path> {
157 self.parse_path_inner(style, None)
158 }
159
160 pub(super) fn parse_path_inner(
171 &mut self,
172 style: PathStyle,
173 ty_generics: Option<&Generics>,
174 ) -> PResult<'a, Path> {
175 let reject_generics_if_mod_style = |parser: &Parser<'_>, path: Path| {
176 if style == PathStyle::Mod && path.segments.iter().any(|segment| segment.args.is_some())
185 {
186 let span = path
187 .segments
188 .iter()
189 .filter_map(|segment| segment.args.as_ref())
190 .map(|arg| arg.span())
191 .collect::<Vec<_>>();
192 parser.dcx().emit_err(diagnostics::GenericsInPath { span });
193 let segments = path
195 .segments
196 .iter()
197 .map(|segment| PathSegment { ident: segment.ident, id: segment.id, args: None })
198 .collect();
199 Path { segments, ..path }
200 } else {
201 path
202 }
203 };
204
205 if let Some(path) =
206 self.eat_metavar_seq(MetaVarKind::Path, |this| this.parse_path(PathStyle::Type))
207 {
208 return Ok(reject_generics_if_mod_style(self, path));
209 }
210
211 if let Some(path) = self.eat_metavar_seq(MetaVarKind::Ty { is_path: true }, |this| {
214 this.parse_path(PathStyle::Type)
215 }) {
216 return Ok(reject_generics_if_mod_style(self, path));
217 }
218
219 let lo = self.token.span;
220 let mut path_span = None;
221 let mut segments = ThinVec::new();
222 let mod_sep_ctxt = self.token.span.ctxt();
223 if self.eat_path_sep() {
224 chain_span(&mut path_span, self.prev_token.span);
225 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
226 }
227 self.parse_path_segments_with_path_span(&mut segments, style, ty_generics, &mut path_span)?;
228 Ok(Path { segments, span: path_span.unwrap() })
229 }
230
231 pub(super) fn parse_path_segments(
232 &mut self,
233 segments: &mut ThinVec<PathSegment>,
234 style: PathStyle,
235 ty_generics: Option<&Generics>,
236 ) -> PResult<'a, ()> {
237 self.parse_path_segments_with_path_span(segments, style, ty_generics, &mut None)
238 }
239
240 fn parse_path_segments_with_path_span(
241 &mut self,
242 segments: &mut ThinVec<PathSegment>,
243 style: PathStyle,
244 ty_generics: Option<&Generics>,
245 path_span: &mut Option<Span>,
246 ) -> PResult<'a, ()> {
247 loop {
248 let segment = self.parse_path_segment_with_path_span(style, ty_generics, path_span)?;
249 if style.has_generic_ambiguity() {
250 self.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)]);
267 }
268 segments.push(segment);
269
270 if self.is_import_coupler() || !self.eat_path_sep() {
271 if self.may_recover()
277 && style == PathStyle::Expr && self.token == token::Colon
279 && self.look_ahead(1, |token| token.is_non_reserved_ident())
280 {
281 if self.token.span.lo() == self.prev_token.span.hi()
284 && self.look_ahead(1, |token| self.token.span.hi() == token.span.lo())
285 {
286 self.bump(); chain_span(path_span, self.prev_token.span);
288 self.dcx().emit_err(PathSingleColon {
289 span: self.prev_token.span,
290 suggestion: self.prev_token.span.shrink_to_hi(),
291 });
292 }
293 continue;
294 }
295
296 return Ok(());
297 }
298 chain_span(path_span, self.prev_token.span); }
300 }
301
302 #[must_use]
304 pub(super) fn eat_path_sep(&mut self) -> bool {
305 let result = self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::PathSep,
token_type: crate::parser::token_type::TokenType::PathSep,
}exp!(PathSep));
306 if result && self.may_recover() {
307 if self.eat_noexpect(&token::Colon) {
308 self.dcx().emit_err(PathTripleColon { span: self.prev_token.span });
309 }
310 }
311 result
312 }
313
314 pub(super) fn parse_path_segment(
315 &mut self,
316 style: PathStyle,
317 ty_generics: Option<&Generics>,
318 ) -> PResult<'a, PathSegment> {
319 self.parse_path_segment_with_path_span(style, ty_generics, &mut None)
320 }
321
322 fn parse_path_segment_with_path_span(
323 &mut self,
324 style: PathStyle,
325 ty_generics: Option<&Generics>,
326 path_span: &mut Option<Span>,
327 ) -> PResult<'a, PathSegment> {
328 let ident = self.parse_path_segment_ident()?;
329 chain_span(path_span, self.prev_token.span);
330 let is_args_start = |token: &Token| {
331 #[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)
332 };
333 let check_args_start = |this: &mut Self| {
334 this.expected_token_types.insert(TokenType::Lt);
335 this.expected_token_types.insert(TokenType::OpenParen);
336 is_args_start(&this.token)
337 };
338
339 let is_missing_turbofish_for_lifetime = |this: &mut Self| {
342 this.token == token::Lt
343 && this.may_recover()
344 && style == PathStyle::Expr
345 && this.look_ahead(1, |t| t.is_lifetime())
346 && this.look_ahead(2, |t| #[allow(non_exhaustive_omitted_patterns)] match t.kind {
token::Gt | token::Comma => true,
_ => false,
}matches!(t.kind, token::Gt | token::Comma))
347 };
348
349 Ok(
350 if style == PathStyle::Type && check_args_start(self)
351 || style != PathStyle::Mod && self.check_path_sep_and_look_ahead(is_args_start)
352 || is_missing_turbofish_for_lifetime(self)
353 {
354 if style == PathStyle::Expr {
358 self.unmatched_angle_bracket_count = 0;
359 }
360
361 let missing_turbofish =
362 style == PathStyle::Expr && !self.check_path_sep_and_look_ahead(is_args_start);
363
364 if self.eat_path_sep() {
367 chain_span(path_span, self.prev_token.span);
368 }
369
370 let lo = self.token.span;
371 let args = if self.eat_lt() {
372 if missing_turbofish {
373 self.recover_missing_turbofish_for_lifetimes(lo);
374 }
375 let args = self.parse_angle_args_with_leading_angle_bracket_recovery(
377 style,
378 lo,
379 ty_generics,
380 )?;
381 self.expect_gt().map_err(|mut err| {
382 if self.token == token::Colon
384 && self.look_ahead(1, |token| token.is_non_reserved_ident())
385 {
386 err.cancel();
387 err = self.dcx().create_err(PathSingleColon {
388 span: self.token.span,
389 suggestion: self.prev_token.span.shrink_to_hi(),
390 });
391 }
392 else if let Some(arg) = args
394 .iter()
395 .rev()
396 .find(|arg| !#[allow(non_exhaustive_omitted_patterns)] match arg {
AngleBracketedArg::Constraint(_) => true,
_ => false,
}matches!(arg, AngleBracketedArg::Constraint(_)))
397 {
398 err.span_suggestion_verbose(
399 arg.span().shrink_to_hi(),
400 "you might have meant to end the type parameters here",
401 ">",
402 Applicability::MaybeIncorrect,
403 );
404 }
405 err
406 })?;
407 let span = lo.to(self.prev_token.span);
408 AngleBracketedArgs { args, span }.into()
409 } else if self.token == token::OpenParen
410 && self.look_ahead(1, |t| *t == token::DotDot)
412 {
413 self.bump(); self.bump(); self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
416 let span = lo.to(self.prev_token.span);
417
418 self.psess.gated_spans.gate(sym::return_type_notation, span);
419
420 let prev_lo = self.prev_token.span.shrink_to_hi();
421 if self.eat_noexpect(&token::RArrow) {
422 let lo = self.prev_token.span;
423 let ty = self.parse_ty()?;
424 let span = lo.to(ty.span);
425 let suggestion = prev_lo.to(ty.span);
426 self.dcx().emit_err(diagnostics::BadReturnTypeNotationOutput {
427 span,
428 suggestion,
429 });
430 }
431
432 Box::new(ast::GenericArgs::ParenthesizedElided(span))
433 } else {
434 let prev_token_before_parsing = self.prev_token;
437 let token_before_parsing = self.token;
438 let mut snapshot = None;
439 if self.may_recover()
440 && prev_token_before_parsing == token::PathSep
441 && (style == PathStyle::Expr && self.token.can_begin_expr()
442 || style == PathStyle::Pat
443 && self.token.can_begin_pattern(token::NtPatKind::PatParam {
444 inferred: false,
445 }))
446 {
447 snapshot = Some(self.create_snapshot_for_diagnostic());
448 }
449
450 let mut first_param = true;
451 let parse_params_result = self.parse_paren_comma_seq(|p| {
452 let mode = FnParseMode {
454 context: FnContext::ParenthesizedArgumentList,
455 req_name: |_, _| false,
456 req_body: false,
457 allow_const_params: false,
458 };
459 let param = p.parse_param_general(&mode, first_param)?;
460 first_param = false;
461 if !#[allow(non_exhaustive_omitted_patterns)] match param.pat.kind {
PatKind::Missing => true,
_ => false,
}matches!(param.pat.kind, PatKind::Missing) {
462 self.psess
463 .gated_spans
464 .gate(sym::named_fn_trait_parameters, param.pat.span);
465 }
466 if #[allow(non_exhaustive_omitted_patterns)] match param.ty.kind {
TyKind::CVarArgs => true,
_ => false,
}matches!(param.ty.kind, TyKind::CVarArgs) {
467 self.psess
468 .gated_spans
469 .gate(sym::named_fn_trait_parameters, param.ty.span);
470 }
471 if !param.attrs.is_empty() {
472 self.psess
473 .gated_spans
474 .gate(sym::named_fn_trait_parameters, param.attrs[0].span);
475 }
476 Ok(param)
477 });
478
479 let (inputs, _) = match parse_params_result {
480 Ok(output) => output,
481 Err(mut error) if prev_token_before_parsing == token::PathSep => {
482 error.span_label(
483 prev_token_before_parsing.span.to(token_before_parsing.span),
484 "while parsing this parenthesized list of type arguments starting here",
485 );
486
487 if let Some(mut snapshot) = snapshot {
488 snapshot.recover_fn_call_leading_path_sep(
489 style,
490 prev_token_before_parsing,
491 &mut error,
492 )
493 }
494
495 return Err(error);
496 }
497 Err(error) => return Err(error),
498 };
499 let inputs_span = lo.to(self.prev_token.span);
500 let mut span = inputs_span;
501 if self.token == token::RArrow {
502 span = span.to(self.token.span);
503 }
504 let output =
505 self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)?;
506 if let ast::FnRetTy::Ty(ret_ty) = &output {
507 span = span.to(ret_ty.span);
508 }
509 ParenthesizedArgs { span, inputs, inputs_span, output }.into()
510 };
511 chain_span(path_span, args.span());
512
513 PathSegment { ident, args: Some(args), id: ast::DUMMY_NODE_ID }
514 } else {
515 PathSegment::from_ident(ident)
517 },
518 )
519 }
520
521 pub(super) fn parse_path_segment_ident(&mut self) -> PResult<'a, Ident> {
522 if let Some(ident) = self.token.non_raw_ident()
523 && ident.is_path_segment_keyword()
524 {
525 self.bump();
526 Ok(ident)
527 } else {
528 self.parse_ident()
529 }
530 }
531
532 fn recover_fn_call_leading_path_sep(
545 &mut self,
546 style: PathStyle,
547 prev_token_before_parsing: Token,
548 error: &mut Diag<'_>,
549 ) {
550 match style {
551 PathStyle::Expr
552 if let Ok(_) = self
553 .parse_paren_comma_seq(|p| p.parse_expr())
554 .map_err(|error| error.cancel()) => {}
555 PathStyle::Pat
556 if let Ok(_) = self
557 .parse_paren_comma_seq(|p| {
558 p.parse_pat_allow_top_guard(
559 None,
560 RecoverComma::No,
561 RecoverColon::No,
562 CommaRecoveryMode::LikelyTuple,
563 )
564 })
565 .map_err(|error| error.cancel()) => {}
566 _ => {
567 return;
568 }
569 }
570
571 if let token::PathSep | token::RArrow = self.token.kind {
572 return;
573 }
574
575 error.span_suggestion_verbose(
576 prev_token_before_parsing.span,
577 ::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!(
578 "consider removing the `::` here to {}",
579 match style {
580 PathStyle::Expr => "call the expression",
581 PathStyle::Pat => "turn this into a tuple struct pattern",
582 _ => {
583 return;
584 }
585 }
586 ),
587 "",
588 Applicability::MaybeIncorrect,
589 );
590 }
591
592 fn parse_angle_args_with_leading_angle_bracket_recovery(
602 &mut self,
603 style: PathStyle,
604 lo: Span,
605 ty_generics: Option<&Generics>,
606 ) -> PResult<'a, ThinVec<AngleBracketedArg>> {
607 let is_first_invocation = style == PathStyle::Expr;
677 let snapshot = is_first_invocation.then(|| self.clone());
679
680 self.angle_bracket_nesting += 1;
681 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_parse/src/parser/path.rs:681",
"rustc_parse::parser::path", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_parse/src/parser/path.rs"),
::tracing_core::__macro_support::Option::Some(681u32),
::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)");
682 match self.parse_angle_args(ty_generics) {
683 Ok(args) => {
684 self.angle_bracket_nesting -= 1;
685 Ok(args)
686 }
687 Err(e) if self.angle_bracket_nesting > 10 => {
688 self.angle_bracket_nesting -= 1;
689 e.emit_err().raise_fatal();
693 }
694 Err(e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
695 self.angle_bracket_nesting -= 1;
696
697 let snapshot = mem::replace(self, snapshot.unwrap());
700
701 let all_angle_brackets = (0..snapshot.unmatched_angle_bracket_count)
703 .fold(true, |a, _| a && self.eat_lt());
704
705 if !all_angle_brackets {
706 let _ = mem::replace(self, snapshot);
710 Err(e)
711 } else {
712 e.cancel();
716
717 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_parse/src/parser/path.rs:717",
"rustc_parse::parser::path", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_parse/src/parser/path.rs"),
::tracing_core::__macro_support::Option::Some(717u32),
::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!(
718 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
719 snapshot.count={:?}",
720 snapshot.unmatched_angle_bracket_count,
721 );
722
723 let span = lo
727 .with_hi(lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count.into()));
728 self.dcx().emit_err(diagnostics::UnmatchedAngle {
729 span,
730 plural: snapshot.unmatched_angle_bracket_count > 1,
731 });
732
733 self.parse_angle_args(ty_generics)
735 }
736 }
737 Err(e) => {
738 self.angle_bracket_nesting -= 1;
739 Err(e)
740 }
741 }
742 }
743
744 pub(super) fn parse_angle_args(
747 &mut self,
748 ty_generics: Option<&Generics>,
749 ) -> PResult<'a, ThinVec<AngleBracketedArg>> {
750 let mut args = ThinVec::new();
751 while let Some(arg) = self.parse_angle_arg(ty_generics)? {
752 args.push(arg);
753 if !self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Comma,
token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
754 if self.check_noexpect(&TokenKind::Semi)
755 && self.look_ahead(1, |t| t.is_ident() || t.is_lifetime())
756 {
757 self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Gt,
token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt));
759 let mut err = self.unexpected().unwrap_err();
761 self.bump();
762 err.span_suggestion_verbose(
763 self.prev_token.span.until(self.token.span),
764 "use a comma to separate type parameters",
765 ", ",
766 Applicability::MachineApplicable,
767 );
768 err.emit();
769 continue;
770 }
771 if !self.token.kind.should_end_const_arg() {
772 if let Some(arg @ AngleBracketedArg::Arg(GenericArg::Lifetime(_))) = args.last()
773 {
774 self.handle_lifetime_arg_preceding_type(arg.span())?;
775 }
776 if self.handle_ambiguous_unbraced_const_arg(&mut args)? {
777 continue;
780 }
781 }
782 break;
783 }
784 }
785 Ok(args)
786 }
787
788 fn parse_angle_arg(
790 &mut self,
791 ty_generics: Option<&Generics>,
792 ) -> PResult<'a, Option<AngleBracketedArg>> {
793 let lo = self.token.span;
794 let arg = self.parse_generic_arg(ty_generics)?;
795 match arg {
796 Some(arg) => {
797 let separated =
800 self.check_noexpect(&token::Colon) || self.check_noexpect(&token::Eq);
801 if 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))) {
802 let arg_span = arg.span();
803 let (binder, ident, gen_args) = match self.get_ident_from_generic_arg(&arg) {
804 Ok(ident_gen_args) => ident_gen_args,
805 Err(()) => return Ok(Some(AngleBracketedArg::Arg(arg))),
806 };
807 if binder {
808 return Err(self.dcx().struct_span_err(
812 arg_span,
813 "`for<...>` is not allowed on associated type bounds",
814 ));
815 }
816 let kind = if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Colon,
token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon)) {
817 AssocItemConstraintKind::Bound { bounds: self.parse_generic_bounds()? }
818 } else if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eq,
token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
819 self.parse_assoc_equality_term(ident, gen_args.as_ref())?
820 } else {
821 ::core::panicking::unreachable_default_msg();unreachable!();
822 };
823
824 let span = lo.to(self.prev_token.span);
825 let constraint =
826 AssocItemConstraint { id: ast::DUMMY_NODE_ID, ident, gen_args, kind, span };
827 Ok(Some(AngleBracketedArg::Constraint(constraint)))
828 } else {
829 if self.prev_token.is_ident()
832 && (self.token.is_ident() || self.look_ahead(1, |token| token.is_ident()))
833 {
834 self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Colon,
token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon));
835 self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eq,
token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq));
836 }
837 Ok(Some(AngleBracketedArg::Arg(arg)))
838 }
839 }
840 _ => Ok(None),
841 }
842 }
843
844 fn parse_assoc_equality_term(
849 &mut self,
850 ident: Ident,
851 gen_args: Option<&GenericArgs>,
852 ) -> PResult<'a, AssocItemConstraintKind> {
853 let prev_token_span = self.prev_token.span;
854 let eq_span = self.token.span;
855 self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eq,
token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq))?;
856 let arg = self.parse_generic_arg(None)?;
857 let span = ident.span.to(self.prev_token.span);
858 let term = match arg {
859 Some(GenericArg::Type(ty)) => ty.into(),
860 Some(GenericArg::Const(c)) => {
861 self.psess.gated_spans.gate(sym::associated_const_equality, span);
862 c.into()
863 }
864 Some(GenericArg::Lifetime(lt)) => {
865 let guar = self.dcx().emit_err(diagnostics::LifetimeInEqConstraint {
866 span: lt.ident.span,
867 lifetime: lt.ident,
868 binding_label: span,
869 colon_sugg: gen_args
870 .map_or(ident.span, |args| args.span())
871 .between(lt.ident.span),
872 });
873 self.mk_ty(lt.ident.span, ast::TyKind::Err(guar)).into()
874 }
875 None => {
876 let after_eq = eq_span.shrink_to_hi();
877 let before_next = self.token.span.shrink_to_lo();
878 let mut err = self
879 .dcx()
880 .struct_span_err(after_eq.to(before_next), "missing type to the right of `=`");
881 if #[allow(non_exhaustive_omitted_patterns)] match self.token.kind {
token::Comma | token::Gt => true,
_ => false,
}matches!(self.token.kind, token::Comma | token::Gt) {
882 err.span_suggestion_verbose(
883 self.psess.source_map().next_point(eq_span).to(before_next),
884 "to constrain the associated type, add a type after `=`",
885 " TheType",
886 Applicability::HasPlaceholders,
887 );
888 err.span_suggestion_verbose(
889 prev_token_span.shrink_to_hi().to(before_next),
890 ::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"),
891 "",
892 Applicability::MaybeIncorrect,
893 )
894 } else {
895 err.span_label(
896 self.token.span,
897 ::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)),
898 )
899 };
900 return Err(err);
901 }
902 };
903 Ok(AssocItemConstraintKind::Equality { term })
904 }
905
906 pub(super) fn expr_is_valid_const_arg(&self, expr: &Box<rustc_ast::Expr>) -> bool {
913 match &expr.kind {
914 ast::ExprKind::Block(_, _)
915 | ast::ExprKind::Lit(_)
916 | ast::ExprKind::IncludedBytes(..) => true,
917 ast::ExprKind::Unary(ast::UnOp::Neg, expr) => {
918 #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
ast::ExprKind::Lit(_) => true,
_ => false,
}matches!(expr.kind, ast::ExprKind::Lit(_))
919 }
920 ast::ExprKind::Path(None, path)
923 if let [segment] = path.segments.as_slice()
924 && segment.args.is_none() =>
925 {
926 true
927 }
928 ast::ExprKind::ConstBlock(_) => {
929 self.psess.gated_spans.gate(sym::gca_min_const_items, expr.span);
930 true
931 }
932 _ => false,
933 }
934 }
935
936 pub(super) fn parse_const_arg(&mut self) -> PResult<'a, AnonConst> {
939 let value = if self.token.kind == token::OpenBrace {
941 self.parse_expr_block(None, self.token.span, BlockCheckMode::Default)?
942 } else {
943 self.parse_unambiguous_unbraced_const_arg()?
944 };
945 Ok(AnonConst { id: ast::DUMMY_NODE_ID, value })
946 }
947
948 pub(super) fn parse_unambiguous_unbraced_const_arg(&mut self) -> PResult<'a, Box<Expr>> {
956 let start = self.token.span;
957 let expr = self.parse_expr_res(Restrictions::CONST_EXPR).map_err(|mut err| {
958 err.span_label(
959 start.shrink_to_lo(),
960 "while parsing a const generic argument starting here",
961 );
962 err
963 })?;
964 if !self.expr_is_valid_const_arg(&expr) {
965 return Err(self.dcx().create_err(ConstGenericWithoutBraces {
966 span: expr.span,
967 sugg: ConstGenericWithoutBracesSugg {
968 left: expr.span.shrink_to_lo(),
969 right: expr.span.shrink_to_hi(),
970 },
971 }));
972 }
973
974 Ok(expr)
975 }
976
977 pub(super) fn parse_generic_arg(
980 &mut self,
981 ty_generics: Option<&Generics>,
982 ) -> PResult<'a, Option<GenericArg>> {
983 self.recover_from_outer_attributes("generic arguments")?;
984
985 let start = self.token.span;
986 let arg = if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
987 GenericArg::Lifetime(self.expect_lifetime())
989 } else if self.check_const_arg() {
990 GenericArg::Const(self.parse_const_arg()?)
992 } else if self.check_type() {
993 let mut snapshot = None;
999 if self.may_recover() && self.token.can_begin_expr() {
1000 snapshot = Some(self.create_snapshot_for_diagnostic());
1001 }
1002
1003 match self.parse_ty() {
1004 Ok(ty) => GenericArg::Type(ty),
1005 Err(err) => {
1006 if let Some(snapshot) = snapshot
1007 && let Some(expr) =
1008 self.recover_unbraced_const_arg_that_can_begin_ty(snapshot)
1009 {
1010 return Ok(Some(self.dummy_const_arg_needs_braces(err, expr.span)));
1011 }
1012 return self.recover_const_arg(start, err).map(Some);
1014 }
1015 }
1016 } else if self.token.is_keyword(kw::Const) {
1017 return self.recover_const_param_declaration(ty_generics);
1018 } else {
1019 let snapshot = self.create_snapshot_for_diagnostic();
1022 match self.parse_expr_res(Restrictions::CONST_EXPR) {
1023 Ok(expr) => {
1024 return Ok(Some(self.dummy_const_arg_needs_braces(
1025 self.dcx().struct_span_err(expr.span, "invalid const generic expression"),
1026 expr.span,
1027 )));
1028 }
1029 Err(err) => {
1030 self.restore_snapshot(snapshot);
1031 err.cancel();
1032 return Ok(None);
1033 }
1034 }
1035 };
1036
1037 Ok(Some(arg))
1038 }
1039
1040 fn get_ident_from_generic_arg(
1045 &self,
1046 gen_arg: &GenericArg,
1047 ) -> Result<(bool, Ident, Option<GenericArgs>), ()> {
1048 if let GenericArg::Type(ty) = gen_arg {
1049 if let ast::TyKind::Path(qself, path) = &ty.kind
1050 && qself.is_none()
1051 && let [seg] = path.segments.as_slice()
1052 {
1053 return Ok((false, seg.ident, seg.args.as_deref().cloned()));
1054 } else if let ast::TyKind::TraitObject(bounds, ast::TraitObjectSyntax::None) = &ty.kind
1055 && let [ast::GenericBound::Trait(trait_ref)] = bounds.as_slice()
1056 && trait_ref.modifiers == ast::TraitBoundModifiers::NONE
1057 && let [seg] = trait_ref.trait_ref.path.segments.as_slice()
1058 {
1059 return Ok((true, seg.ident, seg.args.as_deref().cloned()));
1060 }
1061 }
1062 Err(())
1063 }
1064}
1065
1066fn chain_span(node_span: &mut Option<Span>, span: Span) {
1068 *node_span = Some(node_span.map_or(span, |s| s.to(span)));
1069}