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