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