]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_parse/src/parser/mod.rs
New upstream version 1.59.0+dfsg1
[rustc.git] / compiler / rustc_parse / src / parser / mod.rs
CommitLineData
e74abb32 1pub mod attr;
6a06907d 2mod attr_wrapper;
3dfed10e 3mod diagnostics;
416331ca 4mod expr;
3dfed10e 5mod generics;
416331ca 6mod item;
3dfed10e 7mod nonterminal;
dfeec247 8mod pat;
416331ca 9mod path;
dfeec247 10mod stmt;
3dfed10e 11mod ty;
416331ca 12
60c5eb7d 13use crate::lexer::UnmatchedBrace;
6a06907d 14pub use attr_wrapper::AttrWrapper;
29967ef6 15pub use diagnostics::AttemptLocalParseRecovery;
3dfed10e 16use diagnostics::Error;
a2a8927a 17pub(crate) use item::FnParseMode;
136023e0 18pub use pat::{RecoverColon, RecoverComma};
3dfed10e 19pub use path::PathStyle;
60c5eb7d 20
74b04a01
XL
21use rustc_ast::ptr::P;
22use rustc_ast::token::{self, DelimToken, Token, TokenKind};
cdc7bbd5 23use rustc_ast::tokenstream::AttributesData;
6a06907d 24use rustc_ast::tokenstream::{self, DelimSpan, Spacing};
cdc7bbd5
XL
25use rustc_ast::tokenstream::{TokenStream, TokenTree};
26use rustc_ast::AttrId;
3dfed10e 27use rustc_ast::DUMMY_NODE_ID;
6a06907d 28use rustc_ast::{self as ast, AnonConst, AstLike, AttrStyle, AttrVec, Const, CrateSugar, Extern};
5869c6ff 29use rustc_ast::{Async, Expr, ExprKind, MacArgs, MacDelimiter, Mutability, StrLit, Unsafe};
29967ef6 30use rustc_ast::{Visibility, VisibilityKind};
74b04a01 31use rustc_ast_pretty::pprust;
cdc7bbd5 32use rustc_data_structures::fx::FxHashMap;
fc512014 33use rustc_data_structures::sync::Lrc;
29967ef6
XL
34use rustc_errors::PResult;
35use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, FatalError};
74b04a01 36use rustc_session::parse::ParseSess;
94222f64 37use rustc_span::source_map::{MultiSpan, Span, DUMMY_SP};
f9f354fc 38use rustc_span::symbol::{kw, sym, Ident, Symbol};
3dfed10e 39use tracing::debug;
74b04a01 40
cdc7bbd5 41use std::ops::Range;
dfeec247 42use std::{cmp, mem, slice};
60c5eb7d 43
9fa01778 44bitflags::bitflags! {
94b46f34 45 struct Restrictions: u8 {
ea8adc8c
XL
46 const STMT_EXPR = 1 << 0;
47 const NO_STRUCT_LITERAL = 1 << 1;
29967ef6 48 const CONST_EXPR = 1 << 2;
1a4d82fc 49 }
223e47cc
LB
50}
51
8faf50e0 52#[derive(Clone, Copy, PartialEq, Debug)]
e74abb32 53enum SemiColonMode {
7453a54e
SL
54 Break,
55 Ignore,
9fa01778 56 Comma,
7453a54e
SL
57}
58
8faf50e0 59#[derive(Clone, Copy, PartialEq, Debug)]
e74abb32 60enum BlockMode {
cc61c64b
XL
61 Break,
62 Ignore,
63}
64
5869c6ff
XL
65/// Whether or not we should force collection of tokens for an AST node,
66/// regardless of whether or not it has attributes
17df50a5 67#[derive(Clone, Copy, PartialEq)]
5869c6ff
XL
68pub enum ForceCollect {
69 Yes,
70 No,
71}
72
cdc7bbd5 73#[derive(Debug, Eq, PartialEq)]
5869c6ff
XL
74pub enum TrailingToken {
75 None,
76 Semi,
6a06907d
XL
77 /// If the trailing token is a comma, then capture it
78 /// Otherwise, ignore the trailing token
79 MaybeComma,
5869c6ff
XL
80}
81
e1599b0c 82/// Like `maybe_whole_expr`, but for things other than expressions.
416331ca 83#[macro_export]
1a4d82fc 84macro_rules! maybe_whole {
c30ab7b3 85 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
dc9dc135 86 if let token::Interpolated(nt) = &$p.token.kind {
532ac7d7
XL
87 if let token::$constructor(x) = &**nt {
88 let $x = x.clone();
c30ab7b3
SL
89 $p.bump();
90 return Ok($e);
223e47cc 91 }
1a4d82fc 92 }
c30ab7b3 93 };
1a4d82fc 94}
223e47cc 95
532ac7d7 96/// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
416331ca 97#[macro_export]
532ac7d7
XL
98macro_rules! maybe_recover_from_interpolated_ty_qpath {
99 ($self: expr, $allow_qpath_recovery: expr) => {
100 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
dc9dc135 101 if let token::Interpolated(nt) = &$self.token.kind {
532ac7d7
XL
102 if let token::NtTy(ty) = &**nt {
103 let ty = ty.clone();
104 $self.bump();
74b04a01 105 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
532ac7d7
XL
106 }
107 }
108 }
dfeec247 109 };
532ac7d7
XL
110}
111
041b39d2 112#[derive(Clone)]
1a4d82fc
JJ
113pub struct Parser<'a> {
114 pub sess: &'a ParseSess,
74b04a01 115 /// The current token.
dc9dc135 116 pub token: Token,
29967ef6
XL
117 /// The spacing for the current token
118 pub token_spacing: Spacing,
74b04a01
XL
119 /// The previous token.
120 pub prev_token: Token,
cdc7bbd5 121 pub capture_cfg: bool,
94b46f34 122 restrictions: Restrictions,
e74abb32 123 expected_tokens: Vec<TokenType>,
29967ef6
XL
124 // Important: This must only be advanced from `next_tok`
125 // to ensure that `token_cursor.num_next_calls` is updated properly
e1599b0c 126 token_cursor: TokenCursor,
94b46f34 127 desugar_doc_comments: bool,
9fa01778
XL
128 /// This field is used to keep track of how many left angle brackets we have seen. This is
129 /// required in order to detect extra leading left angle brackets (`<` characters) and error
130 /// appropriately.
131 ///
132 /// See the comments in the `parse_path_segment` function for more details.
e74abb32
XL
133 unmatched_angle_bracket_count: u32,
134 max_angle_bracket_count: u32,
e1599b0c 135 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
9fa01778
XL
136 /// it gets removed from here. Every entry left at the end gets emitted as an independent
137 /// error.
e74abb32
XL
138 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
139 last_unexpected_token_span: Option<Span>,
3dfed10e
XL
140 /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it
141 /// looked like it could have been a mistyped path or literal `Option:Some(42)`).
e74abb32 142 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
dc9dc135 143 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
e74abb32 144 subparser_name: Option<&'static str>,
cdc7bbd5 145 capture_state: CaptureState,
c295e0f8
XL
146 /// This allows us to recover when the user forget to add braces around
147 /// multiple statements in the closure body.
148 pub current_closure: Option<ClosureSpans>,
149}
150
151/// Stores span informations about a closure.
152#[derive(Clone)]
153pub struct ClosureSpans {
154 pub whole_closure: Span,
155 pub closing_pipe: Span,
156 pub body: Span,
cdc7bbd5
XL
157}
158
159/// Indicates a range of tokens that should be replaced by
160/// the tokens in the provided vector. This is used in two
161/// places during token collection:
162///
163/// 1. During the parsing of an AST node that may have a `#[derive]`
164/// attribute, we parse a nested AST node that has `#[cfg]` or `#[cfg_attr]`
165/// In this case, we use a `ReplaceRange` to replace the entire inner AST node
166/// with `FlatToken::AttrTarget`, allowing us to perform eager cfg-expansion
94222f64 167/// on an `AttrAnnotatedTokenStream`
cdc7bbd5
XL
168///
169/// 2. When we parse an inner attribute while collecting tokens. We
170/// remove inner attributes from the token stream entirely, and
171/// instead track them through the `attrs` field on the AST node.
172/// This allows us to easily manipulate them (for example, removing
173/// the first macro inner attribute to invoke a proc-macro).
174/// When create a `TokenStream`, the inner attributes get inserted
175/// into the proper place in the token stream.
176pub type ReplaceRange = (Range<u32>, Vec<(FlatToken, Spacing)>);
177
178/// Controls how we capture tokens. Capturing can be expensive,
179/// so we try to avoid performing capturing in cases where
94222f64 180/// we will never need an `AttrAnnotatedTokenStream`
cdc7bbd5
XL
181#[derive(Copy, Clone)]
182pub enum Capturing {
183 /// We aren't performing any capturing - this is the default mode.
184 No,
185 /// We are capturing tokens
186 Yes,
187}
188
189#[derive(Clone)]
190struct CaptureState {
191 capturing: Capturing,
192 replace_ranges: Vec<ReplaceRange>,
193 inner_attr_ranges: FxHashMap<AttrId, ReplaceRange>,
1a4d82fc
JJ
194}
195
9fa01778
XL
196impl<'a> Drop for Parser<'a> {
197 fn drop(&mut self) {
e74abb32 198 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
9fa01778
XL
199 }
200}
7cac9316 201
041b39d2 202#[derive(Clone)]
e1599b0c
XL
203struct TokenCursor {
204 frame: TokenCursorFrame,
205 stack: Vec<TokenCursorFrame>,
29967ef6
XL
206 desugar_doc_comments: bool,
207 // Counts the number of calls to `next` or `next_desugared`,
208 // depending on whether `desugar_doc_comments` is set.
209 num_next_calls: usize,
fc512014
XL
210 // During parsing, we may sometimes need to 'unglue' a
211 // glued token into two component tokens
212 // (e.g. '>>' into '>' and '>), so that the parser
213 // can consume them one at a time. This process
214 // bypasses the normal capturing mechanism
215 // (e.g. `num_next_calls` will not be incremented),
216 // since the 'unglued' tokens due not exist in
217 // the original `TokenStream`.
218 //
219 // If we end up consuming both unglued tokens,
220 // then this is not an issue - we'll end up
221 // capturing the single 'glued' token.
222 //
223 // However, in certain circumstances, we may
224 // want to capture just the first 'unglued' token.
225 // For example, capturing the `Vec<u8>`
226 // in `Option<Vec<u8>>` requires us to unglue
cdc7bbd5 227 // the trailing `>>` token. The `break_last_token`
fc512014
XL
228 // field is used to track this token - it gets
229 // appended to the captured stream when
230 // we evaluate a `LazyTokenStream`
cdc7bbd5 231 break_last_token: bool,
8bb4bdeb
XL
232}
233
041b39d2 234#[derive(Clone)]
e1599b0c
XL
235struct TokenCursorFrame {
236 delim: token::DelimToken,
237 span: DelimSpan,
238 open_delim: bool,
239 tree_cursor: tokenstream::Cursor,
240 close_delim: bool,
3b2f2976
XL
241}
242
8bb4bdeb 243impl TokenCursorFrame {
29967ef6 244 fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self {
8bb4bdeb 245 TokenCursorFrame {
dc9dc135
XL
246 delim,
247 span,
cdc7bbd5 248 open_delim: false,
29967ef6 249 tree_cursor: tts.into_trees(),
cdc7bbd5 250 close_delim: false,
8bb4bdeb
XL
251 }
252 }
253}
254
255impl TokenCursor {
29967ef6 256 fn next(&mut self) -> (Token, Spacing) {
8bb4bdeb 257 loop {
29967ef6 258 let (tree, spacing) = if !self.frame.open_delim {
8bb4bdeb 259 self.frame.open_delim = true;
f9f354fc 260 TokenTree::open_tt(self.frame.span, self.frame.delim).into()
1b1a35ee 261 } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() {
8bb4bdeb
XL
262 tree
263 } else if !self.frame.close_delim {
264 self.frame.close_delim = true;
f9f354fc 265 TokenTree::close_tt(self.frame.span, self.frame.delim).into()
8bb4bdeb
XL
266 } else if let Some(frame) = self.stack.pop() {
267 self.frame = frame;
dfeec247 268 continue;
8bb4bdeb 269 } else {
29967ef6 270 (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone)
8bb4bdeb
XL
271 };
272
29967ef6
XL
273 match tree {
274 TokenTree::Token(token) => {
275 return (token, spacing);
f9f354fc 276 }
0731742a 277 TokenTree::Delimited(sp, delim, tts) => {
29967ef6 278 let frame = TokenCursorFrame::new(sp, delim, tts);
8bb4bdeb
XL
279 self.stack.push(mem::replace(&mut self.frame, frame));
280 }
281 }
282 }
283 }
284
29967ef6 285 fn next_desugared(&mut self) -> (Token, Spacing) {
3dfed10e 286 let (data, attr_style, sp) = match self.next() {
29967ef6 287 (Token { kind: token::DocComment(_, attr_style, data), span }, _) => {
3dfed10e
XL
288 (data, attr_style, span)
289 }
7cac9316 290 tok => return tok,
8bb4bdeb
XL
291 };
292
8bb4bdeb
XL
293 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
294 // required to wrap the text.
295 let mut num_of_hashes = 0;
296 let mut count = 0;
3dfed10e 297 for ch in data.as_str().chars() {
8bb4bdeb
XL
298 count = match ch {
299 '"' => 1,
300 '#' if count > 0 => count + 1,
301 _ => 0,
302 };
303 num_of_hashes = cmp::max(num_of_hashes, count);
304 }
305
b7449926 306 let delim_span = DelimSpan::from_single(sp);
0731742a
XL
307 let body = TokenTree::Delimited(
308 delim_span,
309 token::Bracket,
dc9dc135
XL
310 [
311 TokenTree::token(token::Ident(sym::doc, false), sp),
312 TokenTree::token(token::Eq, sp),
3dfed10e 313 TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), sp),
0731742a 314 ]
dfeec247
XL
315 .iter()
316 .cloned()
74b04a01 317 .collect::<TokenStream>(),
0731742a 318 );
8bb4bdeb 319
dfeec247
XL
320 self.stack.push(mem::replace(
321 &mut self.frame,
322 TokenCursorFrame::new(
323 delim_span,
324 token::NoDelim,
29967ef6 325 if attr_style == AttrStyle::Inner {
dfeec247
XL
326 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
327 .iter()
328 .cloned()
329 .collect::<TokenStream>()
330 } else {
331 [TokenTree::token(token::Pound, sp), body]
332 .iter()
333 .cloned()
334 .collect::<TokenStream>()
335 },
336 ),
337 ));
8bb4bdeb
XL
338
339 self.next()
340 }
341}
342
5869c6ff 343#[derive(Debug, Clone, PartialEq)]
e74abb32 344enum TokenType {
dc9dc135
XL
345 Token(TokenKind),
346 Keyword(Symbol),
1a4d82fc 347 Operator,
32a655c1
SL
348 Lifetime,
349 Ident,
350 Path,
351 Type,
9fa01778 352 Const,
1a4d82fc 353}
223e47cc 354
1a4d82fc 355impl TokenType {
e74abb32 356 fn to_string(&self) -> String {
1a4d82fc 357 match *self {
dc9dc135
XL
358 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
359 TokenType::Keyword(kw) => format!("`{}`", kw),
32a655c1
SL
360 TokenType::Operator => "an operator".to_string(),
361 TokenType::Lifetime => "lifetime".to_string(),
362 TokenType::Ident => "identifier".to_string(),
363 TokenType::Path => "path".to_string(),
364 TokenType::Type => "type".to_string(),
fc512014 365 TokenType::Const => "a const expression".to_string(),
1a4d82fc
JJ
366 }
367 }
223e47cc
LB
368}
369
8faf50e0 370#[derive(Copy, Clone, Debug)]
e74abb32 371enum TokenExpectType {
ea8adc8c
XL
372 Expect,
373 NoExpect,
374}
375
e74abb32
XL
376/// A sequence separator.
377struct SeqSep {
378 /// The separator token.
379 sep: Option<TokenKind>,
380 /// `true` if a trailing separator is allowed.
381 trailing_sep_allowed: bool,
382}
383
384impl SeqSep {
385 fn trailing_allowed(t: TokenKind) -> SeqSep {
dfeec247 386 SeqSep { sep: Some(t), trailing_sep_allowed: true }
e74abb32
XL
387 }
388
389 fn none() -> SeqSep {
dfeec247 390 SeqSep { sep: None, trailing_sep_allowed: false }
e74abb32
XL
391 }
392}
393
dfeec247
XL
394pub enum FollowedByType {
395 Yes,
396 No,
397}
398
399fn token_descr_opt(token: &Token) -> Option<&'static str> {
400 Some(match token.kind {
401 _ if token.is_special_ident() => "reserved identifier",
402 _ if token.is_used_keyword() => "keyword",
403 _ if token.is_unused_keyword() => "reserved keyword",
404 token::DocComment(..) => "doc comment",
405 _ => return None,
406 })
407}
408
409pub(super) fn token_descr(token: &Token) -> String {
410 let token_str = pprust::token_to_string(token);
411 match token_descr_opt(token) {
412 Some(prefix) => format!("{} `{}`", prefix, token_str),
413 _ => format!("`{}`", token_str),
414 }
415}
60c5eb7d 416
1a4d82fc 417impl<'a> Parser<'a> {
dc9dc135
XL
418 pub fn new(
419 sess: &'a ParseSess,
420 tokens: TokenStream,
dc9dc135
XL
421 desugar_doc_comments: bool,
422 subparser_name: Option<&'static str>,
423 ) -> Self {
cdc7bbd5
XL
424 let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens);
425 start_frame.open_delim = true;
426 start_frame.close_delim = true;
427
c30ab7b3 428 let mut parser = Parser {
3b2f2976 429 sess,
dc9dc135 430 token: Token::dummy(),
29967ef6 431 token_spacing: Spacing::Alone,
74b04a01 432 prev_token: Token::dummy(),
cdc7bbd5 433 capture_cfg: false,
d9579d0f 434 restrictions: Restrictions::empty(),
1a4d82fc 435 expected_tokens: Vec::new(),
8bb4bdeb 436 token_cursor: TokenCursor {
cdc7bbd5 437 frame: start_frame,
8bb4bdeb 438 stack: Vec::new(),
29967ef6
XL
439 num_next_calls: 0,
440 desugar_doc_comments,
cdc7bbd5 441 break_last_token: false,
8bb4bdeb 442 },
3b2f2976 443 desugar_doc_comments,
9fa01778
XL
444 unmatched_angle_bracket_count: 0,
445 max_angle_bracket_count: 0,
446 unclosed_delims: Vec::new(),
447 last_unexpected_token_span: None,
416331ca 448 last_type_ascription: None,
dc9dc135 449 subparser_name,
cdc7bbd5
XL
450 capture_state: CaptureState {
451 capturing: Capturing::No,
452 replace_ranges: Vec::new(),
453 inner_attr_ranges: Default::default(),
454 },
c295e0f8 455 current_closure: None,
c30ab7b3
SL
456 };
457
74b04a01
XL
458 // Make parser point to the first token.
459 parser.bump();
7cac9316 460
c30ab7b3
SL
461 parser
462 }
463
29967ef6 464 fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) {
cdc7bbd5
XL
465 loop {
466 let (mut next, spacing) = if self.desugar_doc_comments {
467 self.token_cursor.next_desugared()
468 } else {
469 self.token_cursor.next()
470 };
471 self.token_cursor.num_next_calls += 1;
472 // We've retrieved an token from the underlying
473 // cursor, so we no longer need to worry about
474 // an unglued token. See `break_and_eat` for more details
475 self.token_cursor.break_last_token = false;
476 if next.span.is_dummy() {
477 // Tweak the location for better diagnostics, but keep syntactic context intact.
478 next.span = fallback_span.with_ctxt(next.span.ctxt());
479 }
480 if matches!(
481 next.kind,
482 token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim)
483 ) {
484 continue;
485 }
486 return (next, spacing);
1a4d82fc
JJ
487 }
488 }
489
29967ef6 490 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
9346a6ac 491 match self.expect_one_of(&[], &[]) {
9cc50fc6 492 Err(e) => Err(e),
e74abb32
XL
493 // We can get `Ok(true)` from `recover_closing_delimiter`
494 // which is called in `expected_one_of_not_found`.
495 Ok(_) => FatalError.raise(),
9346a6ac 496 }
1a4d82fc
JJ
497 }
498
9fa01778 499 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
dc9dc135 500 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
1a4d82fc
JJ
501 if self.expected_tokens.is_empty() {
502 if self.token == *t {
9cc50fc6 503 self.bump();
9fa01778 504 Ok(false)
1a4d82fc 505 } else {
dc9dc135 506 self.unexpected_try_recover(t)
1a4d82fc
JJ
507 }
508 } else {
94b46f34 509 self.expect_one_of(slice::from_ref(t), &[])
1a4d82fc
JJ
510 }
511 }
512
513 /// Expect next token to be edible or inedible token. If edible,
514 /// then consume it; if inedible, then return without consuming
515 /// anything. Signal a fatal error if next token is unexpected.
9fa01778
XL
516 pub fn expect_one_of(
517 &mut self,
dc9dc135
XL
518 edible: &[TokenKind],
519 inedible: &[TokenKind],
9fa01778 520 ) -> PResult<'a, bool /* recovered */> {
dc9dc135 521 if edible.contains(&self.token.kind) {
9cc50fc6 522 self.bump();
9fa01778 523 Ok(false)
dc9dc135 524 } else if inedible.contains(&self.token.kind) {
1a4d82fc 525 // leave it in the input
9fa01778 526 Ok(false)
dc9dc135 527 } else if self.last_unexpected_token_span == Some(self.token.span) {
9fa01778 528 FatalError.raise();
1a4d82fc 529 } else {
dc9dc135 530 self.expected_one_of_not_found(edible, inedible)
1a4d82fc 531 }
970d7e83
LB
532 }
533
dfeec247 534 // Public for rustfmt usage.
f9f354fc 535 pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
2c00a5a8
XL
536 self.parse_ident_common(true)
537 }
538
17df50a5
XL
539 fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> {
540 self.token.ident().ok_or_else(|| match self.prev_token.kind {
541 TokenKind::DocComment(..) => {
542 self.span_err(self.prev_token.span, Error::UselessDocComment)
543 }
544 _ => self.expected_ident_found(),
545 })
546 }
547
f9f354fc 548 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
17df50a5
XL
549 let (ident, is_raw) = self.ident_or_err()?;
550 if !is_raw && ident.is_reserved() {
551 let mut err = self.expected_ident_found();
552 if recover {
553 err.emit();
554 } else {
555 return Err(err);
970d7e83 556 }
970d7e83 557 }
17df50a5
XL
558 self.bump();
559 Ok(ident)
970d7e83
LB
560 }
561
9fa01778 562 /// Checks if the next token is `tok`, and returns `true` if so.
1a4d82fc 563 ///
7453a54e 564 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
1a4d82fc 565 /// encountered.
e74abb32 566 fn check(&mut self, tok: &TokenKind) -> bool {
1a4d82fc 567 let is_present = self.token == *tok;
dfeec247
XL
568 if !is_present {
569 self.expected_tokens.push(TokenType::Token(tok.clone()));
570 }
1a4d82fc 571 is_present
970d7e83
LB
572 }
573
9fa01778 574 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
dc9dc135 575 pub fn eat(&mut self, tok: &TokenKind) -> bool {
1a4d82fc 576 let is_present = self.check(tok);
dfeec247
XL
577 if is_present {
578 self.bump()
579 }
9cc50fc6 580 is_present
970d7e83
LB
581 }
582
e74abb32
XL
583 /// If the next token is the given keyword, returns `true` without eating it.
584 /// An expectation is also added for diagnostics purposes.
dc9dc135 585 fn check_keyword(&mut self, kw: Symbol) -> bool {
85aaf69f
SL
586 self.expected_tokens.push(TokenType::Keyword(kw));
587 self.token.is_keyword(kw)
588 }
589
e74abb32
XL
590 /// If the next token is the given keyword, eats it and returns `true`.
591 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
dfeec247
XL
592 // Public for rustfmt usage.
593 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
85aaf69f 594 if self.check_keyword(kw) {
9cc50fc6
SL
595 self.bump();
596 true
85aaf69f 597 } else {
9cc50fc6 598 false
85aaf69f
SL
599 }
600 }
601
dc9dc135 602 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
1a4d82fc 603 if self.token.is_keyword(kw) {
9cc50fc6
SL
604 self.bump();
605 true
1a4d82fc 606 } else {
9cc50fc6 607 false
1a4d82fc 608 }
970d7e83
LB
609 }
610
9fa01778
XL
611 /// If the given word is not a keyword, signals an error.
612 /// If the next token is not the given word, signals an error.
613 /// Otherwise, eats it.
dc9dc135 614 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
dfeec247 615 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
970d7e83
LB
616 }
617
74b04a01
XL
618 /// Is the given keyword `kw` followed by a non-reserved identifier?
619 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
620 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
621 }
622
e74abb32
XL
623 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
624 if ok {
32a655c1
SL
625 true
626 } else {
e74abb32 627 self.expected_tokens.push(typ);
32a655c1
SL
628 false
629 }
630 }
631
e74abb32
XL
632 fn check_ident(&mut self) -> bool {
633 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
634 }
635
32a655c1 636 fn check_path(&mut self) -> bool {
e74abb32 637 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
32a655c1
SL
638 }
639
640 fn check_type(&mut self) -> bool {
e74abb32 641 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
32a655c1
SL
642 }
643
9fa01778 644 fn check_const_arg(&mut self) -> bool {
e74abb32
XL
645 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
646 }
647
29967ef6
XL
648 fn check_inline_const(&self, dist: usize) -> bool {
649 self.is_keyword_ahead(dist, &[kw::Const])
650 && self.look_ahead(dist + 1, |t| match t.kind {
651 token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)),
652 token::OpenDelim(DelimToken::Brace) => true,
653 _ => false,
654 })
655 }
656
e74abb32
XL
657 /// Checks to see if the next token is either `+` or `+=`.
658 /// Otherwise returns `false`.
659 fn check_plus(&mut self) -> bool {
660 self.check_or_expected(
661 self.token.is_like_plus(),
662 TokenType::Token(token::BinOp(token::Plus)),
663 )
9fa01778
XL
664 }
665
74b04a01
XL
666 /// Eats the expected token if it's present possibly breaking
667 /// compound tokens like multi-character operators in process.
668 /// Returns `true` if the token was eaten.
669 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
670 if self.token.kind == expected {
671 self.bump();
672 return true;
673 }
674 match self.token.kind.break_two_token_op() {
675 Some((first, second)) if first == expected => {
676 let first_span = self.sess.source_map().start_point(self.token.span);
677 let second_span = self.token.span.with_lo(first_span.hi());
678 self.token = Token::new(first, first_span);
fc512014
XL
679 // Keep track of this token - if we end token capturing now,
680 // we'll want to append this token to the captured stream.
681 //
682 // If we consume any additional tokens, then this token
683 // is not needed (we'll capture the entire 'glued' token),
684 // and `next_tok` will set this field to `None`
cdc7bbd5 685 self.token_cursor.break_last_token = true;
29967ef6
XL
686 // Use the spacing of the glued token as the spacing
687 // of the unglued second token.
688 self.bump_with((Token::new(second, second_span), self.token_spacing));
94b46f34
XL
689 true
690 }
74b04a01
XL
691 _ => {
692 self.expected_tokens.push(TokenType::Token(expected));
693 false
94b46f34 694 }
94b46f34
XL
695 }
696 }
697
74b04a01
XL
698 /// Eats `+` possibly breaking tokens like `+=` in process.
699 fn eat_plus(&mut self) -> bool {
700 self.break_and_eat(token::BinOp(token::Plus))
701 }
702
703 /// Eats `&` possibly breaking tokens like `&&` in process.
704 /// Signals an error if `&` is not eaten.
9cc50fc6 705 fn expect_and(&mut self) -> PResult<'a, ()> {
74b04a01 706 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
ea8adc8c
XL
707 }
708
74b04a01
XL
709 /// Eats `|` possibly breaking tokens like `||` in process.
710 /// Signals an error if `|` was not eaten.
ea8adc8c 711 fn expect_or(&mut self) -> PResult<'a, ()> {
74b04a01 712 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
970d7e83
LB
713 }
714
74b04a01 715 /// Eats `<` possibly breaking tokens like `<<` in process.
9cc50fc6 716 fn eat_lt(&mut self) -> bool {
74b04a01 717 let ate = self.break_and_eat(token::Lt);
9fa01778
XL
718 if ate {
719 // See doc comment for `unmatched_angle_bracket_count`.
720 self.unmatched_angle_bracket_count += 1;
721 self.max_angle_bracket_count += 1;
722 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1a4d82fc 723 }
9fa01778 724 ate
1a4d82fc
JJ
725 }
726
74b04a01
XL
727 /// Eats `<` possibly breaking tokens like `<<` in process.
728 /// Signals an error if `<` was not eaten.
9cc50fc6 729 fn expect_lt(&mut self) -> PResult<'a, ()> {
74b04a01 730 if self.eat_lt() { Ok(()) } else { self.unexpected() }
1a4d82fc
JJ
731 }
732
74b04a01
XL
733 /// Eats `>` possibly breaking tokens like `>>` in process.
734 /// Signals an error if `>` was not eaten.
94b46f34 735 fn expect_gt(&mut self) -> PResult<'a, ()> {
74b04a01
XL
736 if self.break_and_eat(token::Gt) {
737 // See doc comment for `unmatched_angle_bracket_count`.
738 if self.unmatched_angle_bracket_count > 0 {
739 self.unmatched_angle_bracket_count -= 1;
740 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
dfeec247 741 }
74b04a01
XL
742 Ok(())
743 } else {
744 self.unexpected()
1a4d82fc
JJ
745 }
746 }
747
416331ca 748 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
dfeec247
XL
749 kets.iter().any(|k| match expect {
750 TokenExpectType::Expect => self.check(k),
751 TokenExpectType::NoExpect => self.token == **k,
416331ca
XL
752 })
753 }
754
e74abb32 755 fn parse_seq_to_before_tokens<T>(
b7449926 756 &mut self,
dc9dc135 757 kets: &[&TokenKind],
b7449926
XL
758 sep: SeqSep,
759 expect: TokenExpectType,
416331ca
XL
760 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
761 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
9fa01778
XL
762 let mut first = true;
763 let mut recovered = false;
416331ca 764 let mut trailing = false;
c30ab7b3 765 let mut v = vec![];
cdc7bbd5
XL
766 let unclosed_delims = !self.unclosed_delims.is_empty();
767
416331ca
XL
768 while !self.expect_any_with_type(kets, expect) {
769 if let token::CloseDelim(..) | token::Eof = self.token.kind {
dfeec247 770 break;
416331ca 771 }
7cac9316
XL
772 if let Some(ref t) = sep.sep {
773 if first {
774 first = false;
775 } else {
9fa01778 776 match self.expect(t) {
c295e0f8
XL
777 Ok(false) => {
778 self.current_closure.take();
779 }
9fa01778 780 Ok(true) => {
c295e0f8 781 self.current_closure.take();
9fa01778
XL
782 recovered = true;
783 break;
abe05a73 784 }
60c5eb7d 785 Err(mut expect_err) => {
74b04a01 786 let sp = self.prev_token.span.shrink_to_hi();
60c5eb7d
XL
787 let token_str = pprust::token_kind_to_string(t);
788
c295e0f8
XL
789 match self.current_closure.take() {
790 Some(closure_spans) if self.token.kind == TokenKind::Semi => {
791 // Finding a semicolon instead of a comma
792 // after a closure body indicates that the
793 // closure body may be a block but the user
794 // forgot to put braces around its
795 // statements.
796
797 self.recover_missing_braces_around_closure_body(
798 closure_spans,
799 expect_err,
800 )?;
801
802 continue;
803 }
804
805 _ => {
806 // Attempt to keep parsing if it was a similar separator.
807 if let Some(ref tokens) = t.similar_tokens() {
808 if tokens.contains(&self.token.kind) && !unclosed_delims {
809 self.bump();
810 }
811 }
9fa01778
XL
812 }
813 }
60c5eb7d 814
f9f354fc
XL
815 // If this was a missing `@` in a binding pattern
816 // bail with a suggestion
817 // https://github.com/rust-lang/rust/issues/72373
f035d41b 818 if self.prev_token.is_ident() && self.token.kind == token::DotDot {
f9f354fc
XL
819 let msg = format!(
820 "if you meant to bind the contents of \
821 the rest of the array pattern into `{}`, use `@`",
822 pprust::token_to_string(&self.prev_token)
823 );
824 expect_err
825 .span_suggestion_verbose(
826 self.prev_token.span.shrink_to_hi().until(self.token.span),
827 &msg,
828 " @ ".to_string(),
829 Applicability::MaybeIncorrect,
830 )
831 .emit();
832 break;
833 }
834
e1599b0c 835 // Attempt to keep parsing if it was an omitted separator.
9fa01778
XL
836 match f(self) {
837 Ok(t) => {
60c5eb7d
XL
838 // Parsed successfully, therefore most probably the code only
839 // misses a separator.
840 expect_err
841 .span_suggestion_short(
5869c6ff 842 sp,
60c5eb7d 843 &format!("missing `{}`", token_str),
94222f64 844 token_str.into(),
60c5eb7d
XL
845 Applicability::MaybeIncorrect,
846 )
847 .emit();
848
9fa01778
XL
849 v.push(t);
850 continue;
dfeec247 851 }
9fa01778 852 Err(mut e) => {
60c5eb7d
XL
853 // Parsing failed, therefore it must be something more serious
854 // than just a missing separator.
855 expect_err.emit();
856
9fa01778
XL
857 e.cancel();
858 break;
859 }
abe05a73
XL
860 }
861 }
7453a54e
SL
862 }
863 }
7453a54e 864 }
416331ca
XL
865 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
866 trailing = true;
7453a54e
SL
867 break;
868 }
869
abe05a73
XL
870 let t = f(self)?;
871 v.push(t);
970d7e83 872 }
7453a54e 873
416331ca 874 Ok((v, trailing, recovered))
970d7e83
LB
875 }
876
c295e0f8
XL
877 fn recover_missing_braces_around_closure_body(
878 &mut self,
879 closure_spans: ClosureSpans,
880 mut expect_err: DiagnosticBuilder<'_>,
881 ) -> PResult<'a, ()> {
882 let initial_semicolon = self.token.span;
883
884 while self.eat(&TokenKind::Semi) {
885 let _ = self.parse_stmt(ForceCollect::Yes)?;
886 }
887
888 expect_err.set_primary_message(
889 "closure bodies that contain statements must be surrounded by braces",
890 );
891
892 let preceding_pipe_span = closure_spans.closing_pipe;
893 let following_token_span = self.token.span;
894
895 let mut first_note = MultiSpan::from(vec![initial_semicolon]);
896 first_note.push_span_label(
897 initial_semicolon,
898 "this `;` turns the preceding closure into a statement".to_string(),
899 );
900 first_note.push_span_label(
901 closure_spans.body,
902 "this expression is a statement because of the trailing semicolon".to_string(),
903 );
904 expect_err.span_note(first_note, "statement found outside of a block");
905
906 let mut second_note = MultiSpan::from(vec![closure_spans.whole_closure]);
907 second_note.push_span_label(
908 closure_spans.whole_closure,
909 "this is the parsed closure...".to_string(),
910 );
911 second_note.push_span_label(
912 following_token_span,
913 "...but likely you meant the closure to end here".to_string(),
914 );
915 expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
916
917 expect_err.set_span(vec![preceding_pipe_span, following_token_span]);
918
919 let opening_suggestion_str = " {".to_string();
920 let closing_suggestion_str = "}".to_string();
921
922 expect_err.multipart_suggestion(
923 "try adding braces",
924 vec![
925 (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
926 (following_token_span.shrink_to_lo(), closing_suggestion_str),
927 ],
928 Applicability::MaybeIncorrect,
929 );
930
931 expect_err.emit();
932
933 Ok(())
934 }
935
dfeec247
XL
936 /// Parses a sequence, not including the closing delimiter. The function
937 /// `f` must consume tokens until reaching the next separator or
938 /// closing bracket.
939 fn parse_seq_to_before_end<T>(
940 &mut self,
941 ket: &TokenKind,
942 sep: SeqSep,
943 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
944 ) -> PResult<'a, (Vec<T>, bool, bool)> {
945 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
946 }
947
948 /// Parses a sequence, including the closing delimiter. The function
949 /// `f` must consume tokens until reaching the next separator or
950 /// closing bracket.
951 fn parse_seq_to_end<T>(
952 &mut self,
953 ket: &TokenKind,
954 sep: SeqSep,
955 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
956 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
957 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
958 if !recovered {
959 self.eat(ket);
960 }
961 Ok((val, trailing))
962 }
963
9fa01778
XL
964 /// Parses a sequence, including the closing delimiter. The function
965 /// `f` must consume tokens until reaching the next separator or
1a4d82fc 966 /// closing bracket.
416331ca 967 fn parse_unspanned_seq<T>(
9fa01778 968 &mut self,
dc9dc135
XL
969 bra: &TokenKind,
970 ket: &TokenKind,
9fa01778 971 sep: SeqSep,
416331ca
XL
972 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
973 ) -> PResult<'a, (Vec<T>, bool)> {
54a0048b 974 self.expect(bra)?;
dfeec247 975 self.parse_seq_to_end(ket, sep, f)
416331ca
XL
976 }
977
978 fn parse_delim_comma_seq<T>(
979 &mut self,
980 delim: DelimToken,
981 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
982 ) -> PResult<'a, (Vec<T>, bool)> {
983 self.parse_unspanned_seq(
984 &token::OpenDelim(delim),
985 &token::CloseDelim(delim),
986 SeqSep::trailing_allowed(token::Comma),
987 f,
988 )
989 }
990
991 fn parse_paren_comma_seq<T>(
992 &mut self,
993 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
994 ) -> PResult<'a, (Vec<T>, bool)> {
995 self.parse_delim_comma_seq(token::Paren, f)
970d7e83
LB
996 }
997
74b04a01 998 /// Advance the parser by one token using provided token as the next one.
29967ef6 999 fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
74b04a01
XL
1000 // Bumping after EOF is a bad sign, usually an infinite loop.
1001 if self.prev_token.kind == TokenKind::Eof {
dfeec247
XL
1002 let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
1003 self.span_bug(self.token.span, msg);
7453a54e
SL
1004 }
1005
74b04a01
XL
1006 // Update the current and previous tokens.
1007 self.prev_token = mem::replace(&mut self.token, next_token);
29967ef6 1008 self.token_spacing = next_spacing;
9e0c209e 1009
74b04a01 1010 // Diagnostics.
7453a54e 1011 self.expected_tokens.clear();
223e47cc 1012 }
7453a54e 1013
74b04a01
XL
1014 /// Advance the parser by one token.
1015 pub fn bump(&mut self) {
1016 let next_token = self.next_tok(self.token.span);
1017 self.bump_with(next_token);
1018 }
1019
e74abb32
XL
1020 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
1021 /// When `dist == 0` then the current token is looked at.
1022 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
c30ab7b3 1023 if dist == 0 {
e74abb32 1024 return looker(&self.token);
223e47cc 1025 }
8bb4bdeb 1026
dc9dc135 1027 let frame = &self.token_cursor.frame;
cdc7bbd5
XL
1028 if frame.delim != DelimToken::NoDelim {
1029 let all_normal = (0..dist).all(|i| {
1030 let token = frame.tree_cursor.look_ahead(i);
1031 !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _)))
1032 });
1033 if all_normal {
1034 return match frame.tree_cursor.look_ahead(dist - 1) {
1035 Some(tree) => match tree {
1036 TokenTree::Token(token) => looker(token),
1037 TokenTree::Delimited(dspan, delim, _) => {
1038 looker(&Token::new(token::OpenDelim(*delim), dspan.open))
1039 }
1040 },
1041 None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)),
1042 };
1043 }
29967ef6 1044 }
cdc7bbd5
XL
1045
1046 let mut cursor = self.token_cursor.clone();
1047 let mut i = 0;
1048 let mut token = Token::dummy();
1049 while i < dist {
1050 token = cursor.next().0;
1051 if matches!(
1052 token.kind,
1053 token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim)
1054 ) {
1055 continue;
1056 }
1057 i += 1;
1058 }
1059 return looker(&token);
223e47cc 1060 }
ff7c6d11 1061
dc9dc135
XL
1062 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1063 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1064 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
223e47cc 1065 }
223e47cc 1066
9fa01778 1067 /// Parses asyncness: `async` or nothing.
74b04a01 1068 fn parse_asyncness(&mut self) -> Async {
dc9dc135 1069 if self.eat_keyword(kw::Async) {
74b04a01
XL
1070 let span = self.prev_token.uninterpolated_span();
1071 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
8faf50e0 1072 } else {
74b04a01 1073 Async::No
8faf50e0
XL
1074 }
1075 }
1076
9fa01778 1077 /// Parses unsafety: `unsafe` or nothing.
74b04a01
XL
1078 fn parse_unsafety(&mut self) -> Unsafe {
1079 if self.eat_keyword(kw::Unsafe) {
1080 Unsafe::Yes(self.prev_token.uninterpolated_span())
1081 } else {
1082 Unsafe::No
1083 }
1084 }
1085
1086 /// Parses constness: `const` or nothing.
1087 fn parse_constness(&mut self) -> Const {
29967ef6
XL
1088 // Avoid const blocks to be parsed as const items
1089 if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace))
1090 && self.eat_keyword(kw::Const)
1091 {
74b04a01
XL
1092 Const::Yes(self.prev_token.uninterpolated_span())
1093 } else {
1094 Const::No
1095 }
1a4d82fc
JJ
1096 }
1097
29967ef6 1098 /// Parses inline const expressions.
3c0e092e
XL
1099 fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P<Expr>> {
1100 if pat {
1101 self.sess.gated_spans.gate(sym::inline_const_pat, span);
1102 } else {
1103 self.sess.gated_spans.gate(sym::inline_const, span);
1104 }
29967ef6
XL
1105 self.eat_keyword(kw::Const);
1106 let blk = self.parse_block()?;
1107 let anon_const = AnonConst {
1108 id: DUMMY_NODE_ID,
1109 value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()),
1110 };
fc512014
XL
1111 let blk_span = anon_const.value.span;
1112 Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new()))
29967ef6
XL
1113 }
1114
416331ca
XL
1115 /// Parses mutability (`mut` or nothing).
1116 fn parse_mutability(&mut self) -> Mutability {
dfeec247 1117 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
223e47cc
LB
1118 }
1119
e74abb32
XL
1120 /// Possibly parses mutability (`const` or `mut`).
1121 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1122 if self.eat_keyword(kw::Mut) {
dfeec247 1123 Some(Mutability::Mut)
e74abb32 1124 } else if self.eat_keyword(kw::Const) {
dfeec247 1125 Some(Mutability::Not)
e74abb32
XL
1126 } else {
1127 None
1128 }
1129 }
1130
416331ca 1131 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
dfeec247
XL
1132 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1133 {
416331ca
XL
1134 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1135 self.bump();
74b04a01 1136 Ok(Ident::new(symbol, self.prev_token.span))
223e47cc 1137 } else {
6a06907d 1138 self.parse_ident_common(true)
223e47cc
LB
1139 }
1140 }
1141
60c5eb7d
XL
1142 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
1143 self.parse_mac_args_common(true).map(P)
1144 }
1145
1146 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1147 self.parse_mac_args_common(false)
1148 }
1149
1150 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
dfeec247
XL
1151 Ok(
1152 if self.check(&token::OpenDelim(DelimToken::Paren))
1153 || self.check(&token::OpenDelim(DelimToken::Bracket))
1154 || self.check(&token::OpenDelim(DelimToken::Brace))
1155 {
1156 match self.parse_token_tree() {
1157 TokenTree::Delimited(dspan, delim, tokens) =>
60c5eb7d 1158 // We've confirmed above that there is a delimiter so unwrapping is OK.
dfeec247
XL
1159 {
1160 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
60c5eb7d 1161 }
dfeec247 1162 _ => unreachable!(),
60c5eb7d 1163 }
dfeec247
XL
1164 } else if !delimited_only {
1165 if self.eat(&token::Eq) {
74b04a01 1166 let eq_span = self.prev_token.span;
60c5eb7d 1167
5869c6ff 1168 // Collect tokens because they are used during lowering to HIR.
cdc7bbd5 1169 let expr = self.parse_expr_force_collect()?;
fc512014
XL
1170 let span = expr.span;
1171
5869c6ff
XL
1172 let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr)));
1173 MacArgs::Eq(eq_span, Token::new(token_kind, span))
dfeec247
XL
1174 } else {
1175 MacArgs::Empty
1176 }
60c5eb7d 1177 } else {
dfeec247
XL
1178 return self.unexpected();
1179 },
1180 )
416331ca 1181 }
041b39d2 1182
e74abb32
XL
1183 fn parse_or_use_outer_attributes(
1184 &mut self,
6a06907d
XL
1185 already_parsed_attrs: Option<AttrWrapper>,
1186 ) -> PResult<'a, AttrWrapper> {
416331ca
XL
1187 if let Some(attrs) = already_parsed_attrs {
1188 Ok(attrs)
970d7e83 1189 } else {
6a06907d 1190 self.parse_outer_attributes()
970d7e83
LB
1191 }
1192 }
1193
416331ca 1194 /// Parses a single token tree from the input.
3dfed10e 1195 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
dc9dc135 1196 match self.token.kind {
416331ca 1197 token::OpenDelim(..) => {
29967ef6
XL
1198 let depth = self.token_cursor.stack.len();
1199
1200 // We keep advancing the token cursor until we hit
1201 // the matching `CloseDelim` token.
1202 while !(depth == self.token_cursor.stack.len()
1203 && matches!(self.token.kind, token::CloseDelim(_)))
1204 {
1205 // Advance one token at a time, so `TokenCursor::next()`
1206 // can capture these tokens if necessary.
1207 self.bump();
1208 }
1209 // We are still inside the frame corresponding
1210 // to the delimited stream we captured, so grab
1211 // the tokens from this frame.
1212 let frame = &self.token_cursor.frame;
1213 let stream = frame.tree_cursor.stream.clone();
1214 let span = frame.span;
1215 let delim = frame.delim;
1216 // Consume close delimiter
0731742a 1217 self.bump();
29967ef6 1218 TokenTree::Delimited(span, delim, stream)
dfeec247 1219 }
416331ca
XL
1220 token::CloseDelim(_) | token::Eof => unreachable!(),
1221 _ => {
416331ca 1222 self.bump();
74b04a01 1223 TokenTree::Token(self.prev_token.clone())
0731742a 1224 }
0731742a
XL
1225 }
1226 }
1227
416331ca
XL
1228 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1229 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1230 let mut tts = Vec::new();
1231 while self.token != token::Eof {
1232 tts.push(self.parse_token_tree());
54a0048b 1233 }
416331ca 1234 Ok(tts)
54a0048b
SL
1235 }
1236
416331ca
XL
1237 pub fn parse_tokens(&mut self) -> TokenStream {
1238 let mut result = Vec::new();
1239 loop {
1240 match self.token.kind {
1241 token::Eof | token::CloseDelim(..) => break,
1242 _ => result.push(self.parse_token_tree().into()),
ff7c6d11 1243 }
223e47cc 1244 }
416331ca 1245 TokenStream::new(result)
223e47cc
LB
1246 }
1247
416331ca
XL
1248 /// Evaluates the closure with restrictions in place.
1249 ///
1250 /// Afters the closure is evaluated, restrictions are reset.
e74abb32 1251 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
416331ca 1252 let old = self.restrictions;
e74abb32
XL
1253 self.restrictions = res;
1254 let res = f(self);
416331ca 1255 self.restrictions = old;
e74abb32 1256 res
8faf50e0
XL
1257 }
1258
416331ca
XL
1259 fn is_crate_vis(&self) -> bool {
1260 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
223e47cc
LB
1261 }
1262
416331ca
XL
1263 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1264 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1265 /// If the following element can't be a tuple (i.e., it's a function definition), then
3c0e092e 1266 /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
416331ca 1267 /// so emit a proper diagnostic.
1b1a35ee
XL
1268 // Public for rustfmt usage.
1269 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
416331ca 1270 maybe_whole!(self, NtVis, |x| x);
dc9dc135 1271
416331ca
XL
1272 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1273 if self.is_crate_vis() {
1274 self.bump(); // `crate`
74b04a01 1275 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
1b1a35ee
XL
1276 return Ok(Visibility {
1277 span: self.prev_token.span,
1278 kind: VisibilityKind::Crate(CrateSugar::JustCrate),
1279 tokens: None,
1280 });
416331ca 1281 }
223e47cc 1282
416331ca
XL
1283 if !self.eat_keyword(kw::Pub) {
1284 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1285 // keyword to grab a span from for inherited visibility; an empty span at the
1286 // beginning of the current token would seem to be the "Schelling span".
1b1a35ee
XL
1287 return Ok(Visibility {
1288 span: self.token.span.shrink_to_lo(),
1289 kind: VisibilityKind::Inherited,
1290 tokens: None,
1291 });
416331ca 1292 }
74b04a01 1293 let lo = self.prev_token.span;
223e47cc 1294
416331ca
XL
1295 if self.check(&token::OpenDelim(token::Paren)) {
1296 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1297 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1298 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1299 // by the following tokens.
dfeec247
XL
1300 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1301 // account for `pub(crate::foo)`
416331ca 1302 {
e74abb32 1303 // Parse `pub(crate)`.
416331ca
XL
1304 self.bump(); // `(`
1305 self.bump(); // `crate`
1306 self.expect(&token::CloseDelim(token::Paren))?; // `)`
e74abb32 1307 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1b1a35ee
XL
1308 return Ok(Visibility {
1309 span: lo.to(self.prev_token.span),
1310 kind: vis,
1311 tokens: None,
1312 });
416331ca 1313 } else if self.is_keyword_ahead(1, &[kw::In]) {
e74abb32 1314 // Parse `pub(in path)`.
416331ca
XL
1315 self.bump(); // `(`
1316 self.bump(); // `in`
1317 let path = self.parse_path(PathStyle::Mod)?; // `path`
1318 self.expect(&token::CloseDelim(token::Paren))?; // `)`
dfeec247 1319 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1b1a35ee
XL
1320 return Ok(Visibility {
1321 span: lo.to(self.prev_token.span),
1322 kind: vis,
1323 tokens: None,
1324 });
e74abb32
XL
1325 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1326 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
416331ca 1327 {
e74abb32 1328 // Parse `pub(self)` or `pub(super)`.
416331ca
XL
1329 self.bump(); // `(`
1330 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1331 self.expect(&token::CloseDelim(token::Paren))?; // `)`
dfeec247 1332 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1b1a35ee
XL
1333 return Ok(Visibility {
1334 span: lo.to(self.prev_token.span),
1335 kind: vis,
1336 tokens: None,
1337 });
60c5eb7d
XL
1338 } else if let FollowedByType::No = fbt {
1339 // Provide this diagnostic if a type cannot follow;
1340 // in particular, if this is not a tuple struct.
e74abb32
XL
1341 self.recover_incorrect_vis_restriction()?;
1342 // Emit diagnostic, but continue with public visibility.
532ac7d7 1343 }
223e47cc 1344 }
223e47cc 1345
1b1a35ee 1346 Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
223e47cc
LB
1347 }
1348
e74abb32
XL
1349 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1350 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1351 self.bump(); // `(`
1352 let path = self.parse_path(PathStyle::Mod)?;
dfeec247 1353 self.expect(&token::CloseDelim(token::Paren))?; // `)`
e74abb32
XL
1354
1355 let msg = "incorrect visibility restriction";
1356 let suggestion = r##"some possible visibility restrictions are:
1357`pub(crate)`: visible only on the current crate
1358`pub(super)`: visible only in the current module's parent
1359`pub(in path::to::module)`: visible only on the specified path"##;
1360
1361 let path_str = pprust::path_to_string(&path);
1362
1363 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1364 .help(suggestion)
1365 .span_suggestion(
1366 path.span,
1367 &format!("make this visible only to module `{}` with `in`", path_str),
1368 format!("in {}", path_str),
1369 Applicability::MachineApplicable,
1370 )
1371 .emit();
1372
1373 Ok(())
1374 }
1375
60c5eb7d 1376 /// Parses `extern string_literal?`.
6a06907d
XL
1377 fn parse_extern(&mut self) -> Extern {
1378 if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None }
e74abb32
XL
1379 }
1380
60c5eb7d
XL
1381 /// Parses a string literal as an ABI spec.
1382 fn parse_abi(&mut self) -> Option<StrLit> {
1383 match self.parse_str_lit() {
1384 Ok(str_lit) => Some(str_lit),
1385 Err(Some(lit)) => match lit.kind {
1386 ast::LitKind::Err(_) => None,
1387 _ => {
1388 self.struct_span_err(lit.span, "non-string ABI literal")
1389 .span_suggestion(
1390 lit.span,
1391 "specify the ABI with a string literal",
1392 "\"C\"".to_string(),
1393 Applicability::MaybeIncorrect,
1394 )
1395 .emit();
1396 None
223e47cc 1397 }
dfeec247 1398 },
60c5eb7d 1399 Err(None) => None,
223e47cc
LB
1400 }
1401 }
1402
6a06907d 1403 pub fn collect_tokens_no_attrs<R: AstLike>(
5869c6ff
XL
1404 &mut self,
1405 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1406 ) -> PResult<'a, R> {
6a06907d
XL
1407 // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1408 // `ForceCollect::Yes`
1409 self.collect_tokens_trailing_token(
1410 AttrWrapper::empty(),
1411 ForceCollect::Yes,
1412 |this, _attrs| Ok((f(this)?, TrailingToken::None)),
1413 )
3b2f2976
XL
1414 }
1415
0531ce1d
XL
1416 /// `::{` or `::*`
1417 fn is_import_coupler(&mut self) -> bool {
dfeec247
XL
1418 self.check(&token::ModSep)
1419 && self.look_ahead(1, |t| {
1420 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1421 })
a7813a04 1422 }
1b1a35ee
XL
1423
1424 pub fn clear_expected_tokens(&mut self) {
1425 self.expected_tokens.clear();
1426 }
e74abb32 1427}
532ac7d7 1428
e74abb32
XL
1429crate fn make_unclosed_delims_error(
1430 unmatched: UnmatchedBrace,
1431 sess: &ParseSess,
1432) -> Option<DiagnosticBuilder<'_>> {
1433 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1434 // `unmatched_braces` only for error recovery in the `Parser`.
1435 let found_delim = unmatched.found_delim?;
94222f64
XL
1436 let span: MultiSpan = if let Some(sp) = unmatched.unclosed_span {
1437 vec![unmatched.found_span, sp].into()
1438 } else {
1439 unmatched.found_span.into()
1440 };
dfeec247 1441 let mut err = sess.span_diagnostic.struct_span_err(
94222f64 1442 span,
dfeec247
XL
1443 &format!(
1444 "mismatched closing delimiter: `{}`",
1445 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1446 ),
1447 );
1448 err.span_label(unmatched.found_span, "mismatched closing delimiter");
e74abb32 1449 if let Some(sp) = unmatched.candidate_span {
dfeec247 1450 err.span_label(sp, "closing delimiter possibly meant for this");
e74abb32
XL
1451 }
1452 if let Some(sp) = unmatched.unclosed_span {
dfeec247 1453 err.span_label(sp, "unclosed delimiter");
e74abb32
XL
1454 }
1455 Some(err)
223e47cc 1456}
9fa01778 1457
e74abb32 1458pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
dfeec247
XL
1459 *sess.reached_eof.borrow_mut() |=
1460 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
e74abb32 1461 for unmatched in unclosed_delims.drain(..) {
f9f354fc 1462 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
74b04a01 1463 e.emit();
f9f354fc 1464 }
9fa01778 1465 }
9fa01778 1466}
cdc7bbd5 1467
94222f64 1468/// A helper struct used when building an `AttrAnnotatedTokenStream` from
cdc7bbd5
XL
1469/// a `LazyTokenStream`. Both delimiter and non-delimited tokens
1470/// are stored as `FlatToken::Token`. A vector of `FlatToken`s
94222f64 1471/// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested
cdc7bbd5
XL
1472/// `AttrAnnotatedTokenTree::Delimited` tokens
1473#[derive(Debug, Clone)]
1474pub enum FlatToken {
1475 /// A token - this holds both delimiter (e.g. '{' and '}')
1476 /// and non-delimiter tokens
1477 Token(Token),
1478 /// Holds the `AttributesData` for an AST node. The
1479 /// `AttributesData` is inserted directly into the
1480 /// constructed `AttrAnnotatedTokenStream` as
94222f64 1481 /// an `AttrAnnotatedTokenTree::Attributes`
cdc7bbd5
XL
1482 AttrTarget(AttributesData),
1483 /// A special 'empty' token that is ignored during the conversion
94222f64 1484 /// to an `AttrAnnotatedTokenStream`. This is used to simplify the
cdc7bbd5
XL
1485 /// handling of replace ranges.
1486 Empty,
1487}