1pub mod attr;
2mod attr_wrapper;
3mod diagnostics;
4mod expr;
5mod generics;
6mod item;
7mod nonterminal;
8mod pat;
9mod path;
10mod stmt;
11pub mod token_type;
12mod ty;
13
14pub mod asm;
17pub mod cfg_select;
18
19use std::assert_matches::debug_assert_matches;
20use std::{fmt, mem, slice};
21
22use attr_wrapper::{AttrWrapper, UsePreAttrPos};
23pub use diagnostics::AttemptLocalParseRecovery;
24pub(crate) use expr::ForbiddenLetReason;
25pub use expr::LetChainsPolicy;
27pub(crate) use item::{FnContext, FnParseMode};
28pub use pat::{CommaRecoveryMode, RecoverColon, RecoverComma};
29pub use path::PathStyle;
30use rustc_ast::token::{
31 self, IdentIsRaw, InvisibleOrigin, MetaVarKind, NtExprKind, NtPatKind, Token, TokenKind,
32};
33use rustc_ast::tokenstream::{
34 ParserRange, ParserReplacement, Spacing, TokenCursor, TokenStream, TokenTree, TokenTreeCursor,
35};
36use rustc_ast::util::case::Case;
37use rustc_ast::{
38 self as ast, AnonConst, AttrArgs, AttrId, ByRef, Const, CoroutineKind, DUMMY_NODE_ID,
39 DelimArgs, Expr, ExprKind, Extern, HasAttrs, HasTokens, Mutability, Recovered, Safety, StrLit,
40 Visibility, VisibilityKind,
41};
42use rustc_ast_pretty::pprust;
43use rustc_data_structures::fx::FxHashMap;
44use rustc_errors::{Applicability, Diag, FatalError, MultiSpan, PResult};
45use rustc_index::interval::IntervalSet;
46use rustc_session::parse::ParseSess;
47use rustc_span::{Ident, Span, Symbol, kw, sym};
48use thin_vec::ThinVec;
49use token_type::TokenTypeSet;
50pub use token_type::{ExpKeywordPair, ExpTokenPair, TokenType};
51use tracing::debug;
52
53use crate::errors::{self, IncorrectVisibilityRestriction, NonStringAbiLiteral};
54use crate::exp;
55
56#[cfg(test)]
57mod tests;
58
59#[cfg(test)]
62mod tokenstream {
63 mod tests;
64}
65
66bitflags::bitflags! {
67 #[derive(Clone, Copy, Debug)]
73 struct Restrictions: u8 {
74 const STMT_EXPR = 1 << 0;
85 const NO_STRUCT_LITERAL = 1 << 1;
96 const CONST_EXPR = 1 << 2;
103 const ALLOW_LET = 1 << 3;
111 const IN_IF_GUARD = 1 << 4;
117 const IS_PAT = 1 << 5;
124 }
125}
126
127#[derive(Clone, Copy, PartialEq, Debug)]
128enum SemiColonMode {
129 Break,
130 Ignore,
131 Comma,
132}
133
134#[derive(Clone, Copy, PartialEq, Debug)]
135enum BlockMode {
136 Break,
137 Ignore,
138}
139
140#[derive(Clone, Copy, Debug, PartialEq)]
143pub enum ForceCollect {
144 Yes,
145 No,
146}
147
148#[macro_export]
150macro_rules! maybe_recover_from_interpolated_ty_qpath {
151 ($self: expr, $allow_qpath_recovery: expr) => {
152 if $allow_qpath_recovery
153 && $self.may_recover()
154 && let Some(mv_kind) = $self.token.is_metavar_seq()
155 && let token::MetaVarKind::Ty { .. } = mv_kind
156 && $self.check_noexpect_past_close_delim(&token::PathSep)
157 {
158 let ty = $self
160 .eat_metavar_seq(mv_kind, |this| this.parse_ty_no_question_mark_recover())
161 .expect("metavar seq ty");
162
163 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
164 }
165 };
166}
167
168#[derive(Clone, Copy, Debug)]
169pub enum Recovery {
170 Allowed,
171 Forbidden,
172}
173
174#[derive(Clone)]
175pub struct Parser<'a> {
176 pub psess: &'a ParseSess,
177 pub token: Token,
179 token_spacing: Spacing,
181 pub prev_token: Token,
183 pub capture_cfg: bool,
184 restrictions: Restrictions,
185 expected_token_types: TokenTypeSet,
186 token_cursor: TokenCursor,
187 num_bump_calls: u32,
189 break_last_token: u32,
208 unmatched_angle_bracket_count: u16,
214 angle_bracket_nesting: u16,
215
216 last_unexpected_token_span: Option<Span>,
217 subparser_name: Option<&'static str>,
219 capture_state: CaptureState,
220 current_closure: Option<ClosureSpans>,
223 recovery: Recovery,
226}
227
228#[cfg(all(target_pointer_width = "64", any(target_arch = "aarch64", target_arch = "x86_64")))]
232rustc_data_structures::static_assert_size!(Parser<'_>, 288);
233
234#[derive(Clone, Debug)]
236struct ClosureSpans {
237 whole_closure: Span,
238 closing_pipe: Span,
239 body: Span,
240}
241
242#[derive(Copy, Clone, Debug)]
246enum Capturing {
247 No,
249 Yes,
251}
252
253#[derive(Clone, Debug)]
255struct CaptureState {
256 capturing: Capturing,
257 parser_replacements: Vec<ParserReplacement>,
258 inner_attr_parser_ranges: FxHashMap<AttrId, ParserRange>,
259 seen_attrs: IntervalSet<AttrId>,
262}
263
264#[derive(Debug)]
266struct SeqSep {
267 sep: Option<ExpTokenPair>,
269 trailing_sep_allowed: bool,
271}
272
273impl SeqSep {
274 fn trailing_allowed(sep: ExpTokenPair) -> SeqSep {
275 SeqSep { sep: Some(sep), trailing_sep_allowed: true }
276 }
277
278 fn none() -> SeqSep {
279 SeqSep { sep: None, trailing_sep_allowed: false }
280 }
281}
282
283#[derive(Debug)]
284pub enum FollowedByType {
285 Yes,
286 No,
287}
288
289#[derive(Copy, Clone, Debug)]
290pub enum Trailing {
291 No,
292 Yes,
293}
294
295impl From<bool> for Trailing {
296 fn from(b: bool) -> Trailing {
297 if b { Trailing::Yes } else { Trailing::No }
298 }
299}
300
301#[derive(Clone, Copy, Debug, PartialEq, Eq)]
302pub(super) enum TokenDescription {
303 ReservedIdentifier,
304 Keyword,
305 ReservedKeyword,
306 DocComment,
307
308 MetaVar(MetaVarKind),
313}
314
315impl TokenDescription {
316 pub(super) fn from_token(token: &Token) -> Option<Self> {
317 match token.kind {
318 _ if token.is_special_ident() => Some(TokenDescription::ReservedIdentifier),
319 _ if token.is_used_keyword() => Some(TokenDescription::Keyword),
320 _ if token.is_unused_keyword() => Some(TokenDescription::ReservedKeyword),
321 token::DocComment(..) => Some(TokenDescription::DocComment),
322 token::OpenInvisible(InvisibleOrigin::MetaVar(kind)) => {
323 Some(TokenDescription::MetaVar(kind))
324 }
325 _ => None,
326 }
327 }
328}
329
330pub fn token_descr(token: &Token) -> String {
331 let s = pprust::token_to_string(token).to_string();
332
333 match (TokenDescription::from_token(token), &token.kind) {
334 (Some(TokenDescription::ReservedIdentifier), _) => format!("reserved identifier `{s}`"),
335 (Some(TokenDescription::Keyword), _) => format!("keyword `{s}`"),
336 (Some(TokenDescription::ReservedKeyword), _) => format!("reserved keyword `{s}`"),
337 (Some(TokenDescription::DocComment), _) => format!("doc comment `{s}`"),
338 (Some(TokenDescription::MetaVar(kind)), _) => format!("`{kind}` metavariable"),
340 (None, TokenKind::NtIdent(..)) => format!("identifier `{s}`"),
341 (None, TokenKind::NtLifetime(..)) => format!("lifetime `{s}`"),
342 (None, _) => format!("`{s}`"),
343 }
344}
345
346impl<'a> Parser<'a> {
347 pub fn new(
348 psess: &'a ParseSess,
349 stream: TokenStream,
350 subparser_name: Option<&'static str>,
351 ) -> Self {
352 let mut parser = Parser {
353 psess,
354 token: Token::dummy(),
355 token_spacing: Spacing::Alone,
356 prev_token: Token::dummy(),
357 capture_cfg: false,
358 restrictions: Restrictions::empty(),
359 expected_token_types: TokenTypeSet::new(),
360 token_cursor: TokenCursor { curr: TokenTreeCursor::new(stream), stack: Vec::new() },
361 num_bump_calls: 0,
362 break_last_token: 0,
363 unmatched_angle_bracket_count: 0,
364 angle_bracket_nesting: 0,
365 last_unexpected_token_span: None,
366 subparser_name,
367 capture_state: CaptureState {
368 capturing: Capturing::No,
369 parser_replacements: Vec::new(),
370 inner_attr_parser_ranges: Default::default(),
371 seen_attrs: IntervalSet::new(u32::MAX as usize),
372 },
373 current_closure: None,
374 recovery: Recovery::Allowed,
375 };
376
377 parser.bump();
379
380 parser.num_bump_calls = 0;
384
385 parser
386 }
387
388 #[inline]
389 pub fn recovery(mut self, recovery: Recovery) -> Self {
390 self.recovery = recovery;
391 self
392 }
393
394 #[inline]
395 fn with_recovery<T>(&mut self, recovery: Recovery, f: impl FnOnce(&mut Self) -> T) -> T {
396 let old = mem::replace(&mut self.recovery, recovery);
397 let res = f(self);
398 self.recovery = old;
399 res
400 }
401
402 #[inline]
410 fn may_recover(&self) -> bool {
411 matches!(self.recovery, Recovery::Allowed)
412 }
413
414 pub fn unexpected_any<T>(&mut self) -> PResult<'a, T> {
417 match self.expect_one_of(&[], &[]) {
418 Err(e) => Err(e),
419 Ok(_) => FatalError.raise(),
422 }
423 }
424
425 pub fn unexpected(&mut self) -> PResult<'a, ()> {
426 self.unexpected_any()
427 }
428
429 pub fn expect(&mut self, exp: ExpTokenPair) -> PResult<'a, Recovered> {
431 if self.expected_token_types.is_empty() {
432 if self.token == exp.tok {
433 self.bump();
434 Ok(Recovered::No)
435 } else {
436 self.unexpected_try_recover(&exp.tok)
437 }
438 } else {
439 self.expect_one_of(slice::from_ref(&exp), &[])
440 }
441 }
442
443 fn expect_one_of(
447 &mut self,
448 edible: &[ExpTokenPair],
449 inedible: &[ExpTokenPair],
450 ) -> PResult<'a, Recovered> {
451 if edible.iter().any(|exp| exp.tok == self.token.kind) {
452 self.bump();
453 Ok(Recovered::No)
454 } else if inedible.iter().any(|exp| exp.tok == self.token.kind) {
455 Ok(Recovered::No)
457 } else if self.token != token::Eof
458 && self.last_unexpected_token_span == Some(self.token.span)
459 {
460 FatalError.raise();
461 } else {
462 self.expected_one_of_not_found(edible, inedible)
463 .map(|error_guaranteed| Recovered::Yes(error_guaranteed))
464 }
465 }
466
467 pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
469 self.parse_ident_common(true)
470 }
471
472 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
473 let (ident, is_raw) = self.ident_or_err(recover)?;
474
475 if matches!(is_raw, IdentIsRaw::No) && ident.is_reserved() {
476 let err = self.expected_ident_found_err();
477 if recover {
478 err.emit();
479 } else {
480 return Err(err);
481 }
482 }
483 self.bump();
484 Ok(ident)
485 }
486
487 fn ident_or_err(&mut self, recover: bool) -> PResult<'a, (Ident, IdentIsRaw)> {
488 match self.token.ident() {
489 Some(ident) => Ok(ident),
490 None => self.expected_ident_found(recover),
491 }
492 }
493
494 #[inline]
499 pub fn check(&mut self, exp: ExpTokenPair) -> bool {
500 let is_present = self.token == exp.tok;
501 if !is_present {
502 self.expected_token_types.insert(exp.token_type);
503 }
504 is_present
505 }
506
507 #[inline]
508 #[must_use]
509 fn check_noexpect(&self, tok: &TokenKind) -> bool {
510 self.token == *tok
511 }
512
513 fn check_noexpect_past_close_delim(&self, tok: &TokenKind) -> bool {
522 let mut tree_cursor = self.token_cursor.stack.last().unwrap().clone();
523 tree_cursor.bump();
524 matches!(
525 tree_cursor.curr(),
526 Some(TokenTree::Token(token::Token { kind, .. }, _)) if kind == tok
527 )
528 }
529
530 #[inline]
535 #[must_use]
536 fn eat_noexpect(&mut self, tok: &TokenKind) -> bool {
537 let is_present = self.check_noexpect(tok);
538 if is_present {
539 self.bump()
540 }
541 is_present
542 }
543
544 #[inline]
546 #[must_use]
547 pub fn eat(&mut self, exp: ExpTokenPair) -> bool {
548 let is_present = self.check(exp);
549 if is_present {
550 self.bump()
551 }
552 is_present
553 }
554
555 #[inline]
558 #[must_use]
559 fn check_keyword(&mut self, exp: ExpKeywordPair) -> bool {
560 let is_keyword = self.token.is_keyword(exp.kw);
561 if !is_keyword {
562 self.expected_token_types.insert(exp.token_type);
563 }
564 is_keyword
565 }
566
567 #[inline]
568 #[must_use]
569 fn check_keyword_case(&mut self, exp: ExpKeywordPair, case: Case) -> bool {
570 if self.check_keyword(exp) {
571 true
572 } else if case == Case::Insensitive
573 && let Some((ident, IdentIsRaw::No)) = self.token.ident()
574 && ident.as_str().eq_ignore_ascii_case(exp.kw.as_str())
576 {
577 true
578 } else {
579 false
580 }
581 }
582
583 #[inline]
587 #[must_use]
588 pub fn eat_keyword(&mut self, exp: ExpKeywordPair) -> bool {
589 let is_keyword = self.check_keyword(exp);
590 if is_keyword {
591 self.bump();
592 }
593 is_keyword
594 }
595
596 #[inline]
600 #[must_use]
601 fn eat_keyword_case(&mut self, exp: ExpKeywordPair, case: Case) -> bool {
602 if self.eat_keyword(exp) {
603 true
604 } else if case == Case::Insensitive
605 && let Some((ident, IdentIsRaw::No)) = self.token.ident()
606 && ident.as_str().eq_ignore_ascii_case(exp.kw.as_str())
608 {
609 self.dcx().emit_err(errors::KwBadCase { span: ident.span, kw: exp.kw.as_str() });
610 self.bump();
611 true
612 } else {
613 false
614 }
615 }
616
617 #[inline]
621 #[must_use]
622 pub fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
623 let is_keyword = self.token.is_keyword(kw);
624 if is_keyword {
625 self.bump();
626 }
627 is_keyword
628 }
629
630 pub fn expect_keyword(&mut self, exp: ExpKeywordPair) -> PResult<'a, ()> {
634 if !self.eat_keyword(exp) { self.unexpected() } else { Ok(()) }
635 }
636
637 pub fn eat_metavar_seq<T>(
639 &mut self,
640 mv_kind: MetaVarKind,
641 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
642 ) -> Option<T> {
643 self.eat_metavar_seq_with_matcher(|mvk| mvk == mv_kind, f)
644 }
645
646 fn eat_metavar_seq_with_matcher<T>(
650 &mut self,
651 match_mv_kind: impl Fn(MetaVarKind) -> bool,
652 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
653 ) -> Option<T> {
654 if let token::OpenInvisible(InvisibleOrigin::MetaVar(mv_kind)) = self.token.kind
655 && match_mv_kind(mv_kind)
656 {
657 self.bump();
658
659 let res = self.with_recovery(Recovery::Forbidden, |this| f(this));
663
664 let res = match res {
665 Ok(res) => res,
666 Err(err) => {
667 err.delay_as_bug();
669 return None;
670 }
671 };
672
673 if let token::CloseInvisible(InvisibleOrigin::MetaVar(mv_kind)) = self.token.kind
674 && match_mv_kind(mv_kind)
675 {
676 self.bump();
677 Some(res)
678 } else {
679 self.dcx()
683 .span_delayed_bug(self.token.span, "no close delim with reparsing {mv_kind:?}");
684 None
685 }
686 } else {
687 None
688 }
689 }
690
691 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
693 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_non_reserved_ident())
694 }
695
696 #[inline]
697 fn check_or_expected(&mut self, ok: bool, token_type: TokenType) -> bool {
698 if !ok {
699 self.expected_token_types.insert(token_type);
700 }
701 ok
702 }
703
704 fn check_ident(&mut self) -> bool {
705 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
706 }
707
708 fn check_path(&mut self) -> bool {
709 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
710 }
711
712 fn check_type(&mut self) -> bool {
713 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
714 }
715
716 fn check_const_arg(&mut self) -> bool {
717 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
718 }
719
720 fn check_const_closure(&self) -> bool {
721 self.is_keyword_ahead(0, &[kw::Const])
722 && self.look_ahead(1, |t| match &t.kind {
723 token::Ident(kw::Move | kw::Use | kw::Static, IdentIsRaw::No)
725 | token::OrOr
726 | token::Or => true,
727 _ => false,
728 })
729 }
730
731 fn check_inline_const(&self, dist: usize) -> bool {
732 self.is_keyword_ahead(dist, &[kw::Const])
733 && self.look_ahead(dist + 1, |t| match &t.kind {
734 token::OpenBrace => true,
735 token::OpenInvisible(InvisibleOrigin::MetaVar(MetaVarKind::Block)) => true,
736 _ => false,
737 })
738 }
739
740 #[inline]
743 fn check_plus(&mut self) -> bool {
744 self.check_or_expected(self.token.is_like_plus(), TokenType::Plus)
745 }
746
747 fn break_and_eat(&mut self, exp: ExpTokenPair) -> bool {
751 if self.token == exp.tok {
752 self.bump();
753 return true;
754 }
755 match self.token.kind.break_two_token_op(1) {
756 Some((first, second)) if first == exp.tok => {
757 let first_span = self.psess.source_map().start_point(self.token.span);
758 let second_span = self.token.span.with_lo(first_span.hi());
759 self.token = Token::new(first, first_span);
760 self.break_last_token += 1;
767 self.bump_with((Token::new(second, second_span), self.token_spacing));
770 true
771 }
772 _ => {
773 self.expected_token_types.insert(exp.token_type);
774 false
775 }
776 }
777 }
778
779 fn eat_plus(&mut self) -> bool {
781 self.break_and_eat(exp!(Plus))
782 }
783
784 fn expect_and(&mut self) -> PResult<'a, ()> {
787 if self.break_and_eat(exp!(And)) { Ok(()) } else { self.unexpected() }
788 }
789
790 fn expect_or(&mut self) -> PResult<'a, ()> {
793 if self.break_and_eat(exp!(Or)) { Ok(()) } else { self.unexpected() }
794 }
795
796 fn eat_lt(&mut self) -> bool {
798 let ate = self.break_and_eat(exp!(Lt));
799 if ate {
800 self.unmatched_angle_bracket_count += 1;
802 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
803 }
804 ate
805 }
806
807 fn expect_lt(&mut self) -> PResult<'a, ()> {
810 if self.eat_lt() { Ok(()) } else { self.unexpected() }
811 }
812
813 fn expect_gt(&mut self) -> PResult<'a, ()> {
816 if self.break_and_eat(exp!(Gt)) {
817 if self.unmatched_angle_bracket_count > 0 {
819 self.unmatched_angle_bracket_count -= 1;
820 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
821 }
822 Ok(())
823 } else {
824 self.unexpected()
825 }
826 }
827
828 fn expect_any_with_type(
830 &mut self,
831 closes_expected: &[ExpTokenPair],
832 closes_not_expected: &[&TokenKind],
833 ) -> bool {
834 closes_expected.iter().any(|&close| self.check(close))
835 || closes_not_expected.iter().any(|k| self.check_noexpect(k))
836 }
837
838 fn parse_seq_to_before_tokens<T>(
842 &mut self,
843 closes_expected: &[ExpTokenPair],
844 closes_not_expected: &[&TokenKind],
845 sep: SeqSep,
846 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
847 ) -> PResult<'a, (ThinVec<T>, Trailing, Recovered)> {
848 let mut first = true;
849 let mut recovered = Recovered::No;
850 let mut trailing = Trailing::No;
851 let mut v = ThinVec::new();
852
853 while !self.expect_any_with_type(closes_expected, closes_not_expected) {
854 if self.token.kind.is_close_delim_or_eof() {
855 break;
856 }
857 if let Some(exp) = sep.sep {
858 if first {
859 first = false;
861 } else {
862 match self.expect(exp) {
864 Ok(Recovered::No) => {
865 self.current_closure.take();
866 }
867 Ok(Recovered::Yes(guar)) => {
868 self.current_closure.take();
869 recovered = Recovered::Yes(guar);
870 break;
871 }
872 Err(mut expect_err) => {
873 let sp = self.prev_token.span.shrink_to_hi();
874 let token_str = pprust::token_kind_to_string(&exp.tok);
875
876 match self.current_closure.take() {
877 Some(closure_spans) if self.token == TokenKind::Semi => {
878 self.recover_missing_braces_around_closure_body(
885 closure_spans,
886 expect_err,
887 )?;
888
889 continue;
890 }
891
892 _ => {
893 if exp.tok.similar_tokens().contains(&self.token.kind) {
895 self.bump();
896 }
897 }
898 }
899
900 if self.prev_token.is_ident() && self.token == token::DotDot {
904 let msg = format!(
905 "if you meant to bind the contents of the rest of the array \
906 pattern into `{}`, use `@`",
907 pprust::token_to_string(&self.prev_token)
908 );
909 expect_err
910 .with_span_suggestion_verbose(
911 self.prev_token.span.shrink_to_hi().until(self.token.span),
912 msg,
913 " @ ",
914 Applicability::MaybeIncorrect,
915 )
916 .emit();
917 break;
918 }
919
920 self.last_unexpected_token_span = None;
922 match f(self) {
923 Ok(t) => {
924 expect_err
927 .with_span_suggestion_short(
928 sp,
929 format!("missing `{token_str}`"),
930 token_str,
931 Applicability::MaybeIncorrect,
932 )
933 .emit();
934
935 v.push(t);
936 continue;
937 }
938 Err(e) => {
939 for xx in &e.children {
942 expect_err.children.push(xx.clone());
945 }
946 e.cancel();
947 if self.token == token::Colon {
948 return Err(expect_err);
951 } else if let [exp] = closes_expected
952 && exp.token_type == TokenType::CloseParen
953 {
954 return Err(expect_err);
955 } else {
956 expect_err.emit();
957 break;
958 }
959 }
960 }
961 }
962 }
963 }
964 }
965 if sep.trailing_sep_allowed
966 && self.expect_any_with_type(closes_expected, closes_not_expected)
967 {
968 trailing = Trailing::Yes;
969 break;
970 }
971
972 let t = f(self)?;
973 v.push(t);
974 }
975
976 Ok((v, trailing, recovered))
977 }
978
979 fn recover_missing_braces_around_closure_body(
980 &mut self,
981 closure_spans: ClosureSpans,
982 mut expect_err: Diag<'_>,
983 ) -> PResult<'a, ()> {
984 let initial_semicolon = self.token.span;
985
986 while self.eat(exp!(Semi)) {
987 let _ = self
988 .parse_stmt_without_recovery(false, ForceCollect::No, false)
989 .unwrap_or_else(|e| {
990 e.cancel();
991 None
992 });
993 }
994
995 expect_err
996 .primary_message("closure bodies that contain statements must be surrounded by braces");
997
998 let preceding_pipe_span = closure_spans.closing_pipe;
999 let following_token_span = self.token.span;
1000
1001 let mut first_note = MultiSpan::from(vec![initial_semicolon]);
1002 first_note.push_span_label(
1003 initial_semicolon,
1004 "this `;` turns the preceding closure into a statement",
1005 );
1006 first_note.push_span_label(
1007 closure_spans.body,
1008 "this expression is a statement because of the trailing semicolon",
1009 );
1010 expect_err.span_note(first_note, "statement found outside of a block");
1011
1012 let mut second_note = MultiSpan::from(vec![closure_spans.whole_closure]);
1013 second_note.push_span_label(closure_spans.whole_closure, "this is the parsed closure...");
1014 second_note.push_span_label(
1015 following_token_span,
1016 "...but likely you meant the closure to end here",
1017 );
1018 expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
1019
1020 expect_err.span(vec![preceding_pipe_span, following_token_span]);
1021
1022 let opening_suggestion_str = " {".to_string();
1023 let closing_suggestion_str = "}".to_string();
1024
1025 expect_err.multipart_suggestion(
1026 "try adding braces",
1027 vec![
1028 (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
1029 (following_token_span.shrink_to_lo(), closing_suggestion_str),
1030 ],
1031 Applicability::MaybeIncorrect,
1032 );
1033
1034 expect_err.emit();
1035
1036 Ok(())
1037 }
1038
1039 fn parse_seq_to_before_end<T>(
1043 &mut self,
1044 close: ExpTokenPair,
1045 sep: SeqSep,
1046 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1047 ) -> PResult<'a, (ThinVec<T>, Trailing, Recovered)> {
1048 self.parse_seq_to_before_tokens(&[close], &[], sep, f)
1049 }
1050
1051 fn parse_seq_to_end<T>(
1055 &mut self,
1056 close: ExpTokenPair,
1057 sep: SeqSep,
1058 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1059 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1060 let (val, trailing, recovered) = self.parse_seq_to_before_end(close, sep, f)?;
1061 if matches!(recovered, Recovered::No) && !self.eat(close) {
1062 self.dcx().span_delayed_bug(
1063 self.token.span,
1064 "recovered but `parse_seq_to_before_end` did not give us the close token",
1065 );
1066 }
1067 Ok((val, trailing))
1068 }
1069
1070 fn parse_unspanned_seq<T>(
1074 &mut self,
1075 open: ExpTokenPair,
1076 close: ExpTokenPair,
1077 sep: SeqSep,
1078 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1079 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1080 self.expect(open)?;
1081 self.parse_seq_to_end(close, sep, f)
1082 }
1083
1084 fn parse_delim_comma_seq<T>(
1088 &mut self,
1089 open: ExpTokenPair,
1090 close: ExpTokenPair,
1091 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1092 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1093 self.parse_unspanned_seq(open, close, SeqSep::trailing_allowed(exp!(Comma)), f)
1094 }
1095
1096 pub fn parse_paren_comma_seq<T>(
1100 &mut self,
1101 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1102 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1103 self.parse_delim_comma_seq(exp!(OpenParen), exp!(CloseParen), f)
1104 }
1105
1106 fn bump_with(&mut self, next: (Token, Spacing)) {
1108 self.inlined_bump_with(next)
1109 }
1110
1111 #[inline(always)]
1113 fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
1114 self.prev_token = mem::replace(&mut self.token, next_token);
1116 self.token_spacing = next_spacing;
1117
1118 self.expected_token_types.clear();
1120 }
1121
1122 pub fn bump(&mut self) {
1124 let mut next = self.token_cursor.inlined_next();
1127 self.num_bump_calls += 1;
1128 self.break_last_token = 0;
1131 if next.0.span.is_dummy() {
1132 let fallback_span = self.token.span;
1134 next.0.span = fallback_span.with_ctxt(next.0.span.ctxt());
1135 }
1136 debug_assert!(!matches!(
1137 next.0.kind,
1138 token::OpenInvisible(origin) | token::CloseInvisible(origin) if origin.skip()
1139 ));
1140 self.inlined_bump_with(next)
1141 }
1142
1143 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
1147 if dist == 0 {
1148 return looker(&self.token);
1149 }
1150
1151 if dist == 1 {
1154 match self.token_cursor.curr.curr() {
1157 Some(tree) => {
1158 match tree {
1160 TokenTree::Token(token, _) => return looker(token),
1161 &TokenTree::Delimited(dspan, _, delim, _) => {
1162 if !delim.skip() {
1163 return looker(&Token::new(delim.as_open_token_kind(), dspan.open));
1164 }
1165 }
1166 }
1167 }
1168 None => {
1169 if let Some(last) = self.token_cursor.stack.last()
1172 && let Some(&TokenTree::Delimited(span, _, delim, _)) = last.curr()
1173 && !delim.skip()
1174 {
1175 return looker(&Token::new(delim.as_close_token_kind(), span.close));
1178 }
1179 }
1180 }
1181 }
1182
1183 let mut cursor = self.token_cursor.clone();
1186 let mut i = 0;
1187 let mut token = Token::dummy();
1188 while i < dist {
1189 token = cursor.next().0;
1190 if matches!(
1191 token.kind,
1192 token::OpenInvisible(origin) | token::CloseInvisible(origin) if origin.skip()
1193 ) {
1194 continue;
1195 }
1196 i += 1;
1197 }
1198 looker(&token)
1199 }
1200
1201 pub fn tree_look_ahead<R>(
1204 &self,
1205 dist: usize,
1206 looker: impl FnOnce(&TokenTree) -> R,
1207 ) -> Option<R> {
1208 assert_ne!(dist, 0);
1209 self.token_cursor.curr.look_ahead(dist - 1).map(looker)
1210 }
1211
1212 pub(crate) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1214 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1215 }
1216
1217 fn parse_coroutine_kind(&mut self, case: Case) -> Option<CoroutineKind> {
1219 let span = self.token_uninterpolated_span();
1220 if self.eat_keyword_case(exp!(Async), case) {
1221 if self.token_uninterpolated_span().at_least_rust_2024()
1224 && self.eat_keyword_case(exp!(Gen), case)
1225 {
1226 let gen_span = self.prev_token_uninterpolated_span();
1227 Some(CoroutineKind::AsyncGen {
1228 span: span.to(gen_span),
1229 closure_id: DUMMY_NODE_ID,
1230 return_impl_trait_id: DUMMY_NODE_ID,
1231 })
1232 } else {
1233 Some(CoroutineKind::Async {
1234 span,
1235 closure_id: DUMMY_NODE_ID,
1236 return_impl_trait_id: DUMMY_NODE_ID,
1237 })
1238 }
1239 } else if self.token_uninterpolated_span().at_least_rust_2024()
1240 && self.eat_keyword_case(exp!(Gen), case)
1241 {
1242 Some(CoroutineKind::Gen {
1243 span,
1244 closure_id: DUMMY_NODE_ID,
1245 return_impl_trait_id: DUMMY_NODE_ID,
1246 })
1247 } else {
1248 None
1249 }
1250 }
1251
1252 fn parse_safety(&mut self, case: Case) -> Safety {
1254 if self.eat_keyword_case(exp!(Unsafe), case) {
1255 Safety::Unsafe(self.prev_token_uninterpolated_span())
1256 } else if self.eat_keyword_case(exp!(Safe), case) {
1257 Safety::Safe(self.prev_token_uninterpolated_span())
1258 } else {
1259 Safety::Default
1260 }
1261 }
1262
1263 fn parse_constness(&mut self, case: Case) -> Const {
1265 self.parse_constness_(case, false)
1266 }
1267
1268 fn parse_closure_constness(&mut self) -> Const {
1270 let constness = self.parse_constness_(Case::Sensitive, true);
1271 if let Const::Yes(span) = constness {
1272 self.psess.gated_spans.gate(sym::const_closures, span);
1273 }
1274 constness
1275 }
1276
1277 fn parse_constness_(&mut self, case: Case, is_closure: bool) -> Const {
1278 if (self.check_const_closure() == is_closure)
1280 && !self.look_ahead(1, |t| *t == token::OpenBrace || t.is_metavar_block())
1281 && self.eat_keyword_case(exp!(Const), case)
1282 {
1283 Const::Yes(self.prev_token_uninterpolated_span())
1284 } else {
1285 Const::No
1286 }
1287 }
1288
1289 fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, Box<Expr>> {
1291 self.expect_keyword(exp!(Const))?;
1292 let (attrs, blk) = self.parse_inner_attrs_and_block(None)?;
1293 let anon_const = AnonConst {
1294 id: DUMMY_NODE_ID,
1295 value: self.mk_expr(blk.span, ExprKind::Block(blk, None)),
1296 };
1297 let blk_span = anon_const.value.span;
1298 let kind = if pat {
1299 let guar = self
1300 .dcx()
1301 .struct_span_err(blk_span, "const blocks cannot be used as patterns")
1302 .with_help(
1303 "use a named `const`-item or an `if`-guard (`x if x == const { ... }`) instead",
1304 )
1305 .emit();
1306 ExprKind::Err(guar)
1307 } else {
1308 ExprKind::ConstBlock(anon_const)
1309 };
1310 Ok(self.mk_expr_with_attrs(span.to(blk_span), kind, attrs))
1311 }
1312
1313 fn parse_mutability(&mut self) -> Mutability {
1315 if self.eat_keyword(exp!(Mut)) { Mutability::Mut } else { Mutability::Not }
1316 }
1317
1318 fn parse_byref(&mut self) -> ByRef {
1320 if self.eat_keyword(exp!(Ref)) { ByRef::Yes(self.parse_mutability()) } else { ByRef::No }
1321 }
1322
1323 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1325 if self.eat_keyword(exp!(Mut)) {
1326 Some(Mutability::Mut)
1327 } else if self.eat_keyword(exp!(Const)) {
1328 Some(Mutability::Not)
1329 } else {
1330 None
1331 }
1332 }
1333
1334 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1335 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1336 {
1337 if let Some(suffix) = suffix {
1338 self.dcx().emit_err(errors::InvalidLiteralSuffixOnTupleIndex {
1339 span: self.token.span,
1340 suffix,
1341 });
1342 }
1343 self.bump();
1344 Ok(Ident::new(symbol, self.prev_token.span))
1345 } else {
1346 self.parse_ident_common(true)
1347 }
1348 }
1349
1350 fn parse_delim_args(&mut self) -> PResult<'a, Box<DelimArgs>> {
1351 if let Some(args) = self.parse_delim_args_inner() {
1352 Ok(Box::new(args))
1353 } else {
1354 self.unexpected_any()
1355 }
1356 }
1357
1358 fn parse_attr_args(&mut self) -> PResult<'a, AttrArgs> {
1359 Ok(if let Some(args) = self.parse_delim_args_inner() {
1360 AttrArgs::Delimited(args)
1361 } else if self.eat(exp!(Eq)) {
1362 let eq_span = self.prev_token.span;
1363 let expr = self.parse_expr_force_collect()?;
1364 AttrArgs::Eq { eq_span, expr }
1365 } else {
1366 AttrArgs::Empty
1367 })
1368 }
1369
1370 fn parse_delim_args_inner(&mut self) -> Option<DelimArgs> {
1371 let delimited = self.check(exp!(OpenParen))
1372 || self.check(exp!(OpenBracket))
1373 || self.check(exp!(OpenBrace));
1374
1375 delimited.then(|| {
1376 let TokenTree::Delimited(dspan, _, delim, tokens) = self.parse_token_tree() else {
1377 unreachable!()
1378 };
1379 DelimArgs { dspan, delim, tokens }
1380 })
1381 }
1382
1383 pub fn parse_token_tree(&mut self) -> TokenTree {
1385 if self.token.kind.open_delim().is_some() {
1386 let tree = self.token_cursor.stack.last().unwrap().curr().unwrap().clone();
1389 debug_assert_matches!(tree, TokenTree::Delimited(..));
1390
1391 let target_depth = self.token_cursor.stack.len() - 1;
1397
1398 if let Capturing::No = self.capture_state.capturing {
1399 self.token_cursor.curr.bump_to_end();
1404 self.bump();
1405 debug_assert_eq!(self.token_cursor.stack.len(), target_depth);
1406 } else {
1407 loop {
1408 self.bump();
1411 if self.token_cursor.stack.len() == target_depth {
1412 break;
1413 }
1414 }
1415 }
1416 debug_assert!(self.token.kind.close_delim().is_some());
1417
1418 self.bump();
1420 tree
1421 } else {
1422 assert!(!self.token.kind.is_close_delim_or_eof());
1423 let prev_spacing = self.token_spacing;
1424 self.bump();
1425 TokenTree::Token(self.prev_token, prev_spacing)
1426 }
1427 }
1428
1429 pub fn parse_tokens(&mut self) -> TokenStream {
1430 let mut result = Vec::new();
1431 loop {
1432 if self.token.kind.is_close_delim_or_eof() {
1433 break;
1434 } else {
1435 result.push(self.parse_token_tree());
1436 }
1437 }
1438 TokenStream::new(result)
1439 }
1440
1441 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1445 let old = self.restrictions;
1446 self.restrictions = res;
1447 let res = f(self);
1448 self.restrictions = old;
1449 res
1450 }
1451
1452 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1459 if let Some(vis) = self
1460 .eat_metavar_seq(MetaVarKind::Vis, |this| this.parse_visibility(FollowedByType::Yes))
1461 {
1462 return Ok(vis);
1463 }
1464
1465 if !self.eat_keyword(exp!(Pub)) {
1466 return Ok(Visibility {
1470 span: self.token.span.shrink_to_lo(),
1471 kind: VisibilityKind::Inherited,
1472 tokens: None,
1473 });
1474 }
1475 let lo = self.prev_token.span;
1476
1477 if self.check(exp!(OpenParen)) {
1478 if self.is_keyword_ahead(1, &[kw::In]) {
1483 self.bump(); self.bump(); let path = self.parse_path(PathStyle::Mod)?; self.expect(exp!(CloseParen))?; let vis = VisibilityKind::Restricted {
1489 path: Box::new(path),
1490 id: ast::DUMMY_NODE_ID,
1491 shorthand: false,
1492 };
1493 return Ok(Visibility {
1494 span: lo.to(self.prev_token.span),
1495 kind: vis,
1496 tokens: None,
1497 });
1498 } else if self.look_ahead(2, |t| t == &token::CloseParen)
1499 && self.is_keyword_ahead(1, &[kw::Crate, kw::Super, kw::SelfLower])
1500 {
1501 self.bump(); let path = self.parse_path(PathStyle::Mod)?; self.expect(exp!(CloseParen))?; let vis = VisibilityKind::Restricted {
1506 path: Box::new(path),
1507 id: ast::DUMMY_NODE_ID,
1508 shorthand: true,
1509 };
1510 return Ok(Visibility {
1511 span: lo.to(self.prev_token.span),
1512 kind: vis,
1513 tokens: None,
1514 });
1515 } else if let FollowedByType::No = fbt {
1516 self.recover_incorrect_vis_restriction()?;
1519 }
1521 }
1522
1523 Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1524 }
1525
1526 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1528 self.bump(); let path = self.parse_path(PathStyle::Mod)?;
1530 self.expect(exp!(CloseParen))?; let path_str = pprust::path_to_string(&path);
1533 self.dcx()
1534 .emit_err(IncorrectVisibilityRestriction { span: path.span, inner_str: path_str });
1535
1536 Ok(())
1537 }
1538
1539 fn parse_extern(&mut self, case: Case) -> Extern {
1541 if self.eat_keyword_case(exp!(Extern), case) {
1542 let mut extern_span = self.prev_token.span;
1543 let abi = self.parse_abi();
1544 if let Some(abi) = abi {
1545 extern_span = extern_span.to(abi.span);
1546 }
1547 Extern::from_abi(abi, extern_span)
1548 } else {
1549 Extern::None
1550 }
1551 }
1552
1553 fn parse_abi(&mut self) -> Option<StrLit> {
1555 match self.parse_str_lit() {
1556 Ok(str_lit) => Some(str_lit),
1557 Err(Some(lit)) => match lit.kind {
1558 ast::LitKind::Err(_) => None,
1559 _ => {
1560 self.dcx().emit_err(NonStringAbiLiteral { span: lit.span });
1561 None
1562 }
1563 },
1564 Err(None) => None,
1565 }
1566 }
1567
1568 fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>(
1569 &mut self,
1570 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1571 ) -> PResult<'a, R> {
1572 self.collect_tokens(None, AttrWrapper::empty(), ForceCollect::Yes, |this, _attrs| {
1575 Ok((f(this)?, Trailing::No, UsePreAttrPos::No))
1576 })
1577 }
1578
1579 fn check_path_sep_and_look_ahead(&mut self, looker: impl Fn(&Token) -> bool) -> bool {
1581 if self.check(exp!(PathSep)) {
1582 if self.may_recover() && self.look_ahead(1, |t| t.kind == token::Colon) {
1583 debug_assert!(!self.look_ahead(1, &looker), "Looker must not match on colon");
1584 self.look_ahead(2, looker)
1585 } else {
1586 self.look_ahead(1, looker)
1587 }
1588 } else {
1589 false
1590 }
1591 }
1592
1593 fn is_import_coupler(&mut self) -> bool {
1595 self.check_path_sep_and_look_ahead(|t| matches!(t.kind, token::OpenBrace | token::Star))
1596 }
1597
1598 #[allow(unused)]
1601 pub(crate) fn debug_lookahead(&self, lookahead: usize) -> impl fmt::Debug {
1602 fmt::from_fn(move |f| {
1603 let mut dbg_fmt = f.debug_struct("Parser"); dbg_fmt.field("prev_token", &self.prev_token);
1607 let mut tokens = vec![];
1608 for i in 0..lookahead {
1609 let tok = self.look_ahead(i, |tok| tok.kind);
1610 let is_eof = tok == TokenKind::Eof;
1611 tokens.push(tok);
1612 if is_eof {
1613 break;
1615 }
1616 }
1617 dbg_fmt.field_with("tokens", |field| field.debug_list().entries(tokens).finish());
1618 dbg_fmt.field("approx_token_stream_pos", &self.num_bump_calls);
1619
1620 if let Some(subparser) = self.subparser_name {
1622 dbg_fmt.field("subparser_name", &subparser);
1623 }
1624 if let Recovery::Forbidden = self.recovery {
1625 dbg_fmt.field("recovery", &self.recovery);
1626 }
1627
1628 dbg_fmt.finish_non_exhaustive()
1630 })
1631 }
1632
1633 pub fn clear_expected_token_types(&mut self) {
1634 self.expected_token_types.clear();
1635 }
1636
1637 pub fn approx_token_stream_pos(&self) -> u32 {
1638 self.num_bump_calls
1639 }
1640
1641 pub fn token_uninterpolated_span(&self) -> Span {
1648 match &self.token.kind {
1649 token::NtIdent(ident, _) | token::NtLifetime(ident, _) => ident.span,
1650 token::OpenInvisible(InvisibleOrigin::MetaVar(_)) => self.look_ahead(1, |t| t.span),
1651 _ => self.token.span,
1652 }
1653 }
1654
1655 pub fn prev_token_uninterpolated_span(&self) -> Span {
1657 match &self.prev_token.kind {
1658 token::NtIdent(ident, _) | token::NtLifetime(ident, _) => ident.span,
1659 token::OpenInvisible(InvisibleOrigin::MetaVar(_)) => self.look_ahead(0, |t| t.span),
1660 _ => self.prev_token.span,
1661 }
1662 }
1663}
1664
1665#[derive(Clone, Debug)]
1667pub enum ParseNtResult {
1668 Tt(TokenTree),
1669 Ident(Ident, IdentIsRaw),
1670 Lifetime(Ident, IdentIsRaw),
1671 Item(Box<ast::Item>),
1672 Block(Box<ast::Block>),
1673 Stmt(Box<ast::Stmt>),
1674 Pat(Box<ast::Pat>, NtPatKind),
1675 Expr(Box<ast::Expr>, NtExprKind),
1676 Literal(Box<ast::Expr>),
1677 Ty(Box<ast::Ty>),
1678 Meta(Box<ast::AttrItem>),
1679 Path(Box<ast::Path>),
1680 Vis(Box<ast::Visibility>),
1681}