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