]> git.proxmox.com Git - rustc.git/blame - src/libsyntax/parse/parser.rs
New upstream version 1.40.0+dfsg1
[rustc.git] / src / libsyntax / parse / parser.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
e1599b0c 14use crate::ast::{
e74abb32
XL
15 self, DUMMY_NODE_ID, AttrStyle, Attribute, CrateSugar, Ident,
16 IsAsync, MacDelimiter, Mutability, StrStyle, Visibility, VisibilityKind, Unsafety,
e1599b0c 17};
e74abb32 18use crate::parse::{PResult, Directory, DirectoryOwnership};
dc9dc135 19use crate::parse::lexer::UnmatchedBrace;
9fa01778 20use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
e74abb32 21use crate::parse::token::{self, Token, TokenKind, DelimToken};
9fa01778
XL
22use crate::print::pprust;
23use crate::ptr::P;
e74abb32
XL
24use crate::sess::ParseSess;
25use crate::source_map::respan;
dc9dc135 26use crate::symbol::{kw, sym, Symbol};
e1599b0c
XL
27use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
28use crate::ThinVec;
9fa01778 29
e74abb32 30use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
83c7162d 31use rustc_target::spec::abi::{self, Abi};
dc9dc135
XL
32use syntax_pos::{Span, BytePos, DUMMY_SP, FileName};
33use log::debug;
1a4d82fc 34
94b46f34 35use std::borrow::Cow;
416331ca
XL
36use std::{cmp, mem, slice};
37use std::path::PathBuf;
8faf50e0 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;
0731742a 212 TokenTree::open_tt(self.frame.span.open, 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;
0731742a 217 TokenTree::close_tt(self.frame.span.close, 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
1a4d82fc 348impl<'a> Parser<'a> {
dc9dc135
XL
349 pub fn new(
350 sess: &'a ParseSess,
351 tokens: TokenStream,
352 directory: Option<Directory<'a>>,
353 recurse_into_file_modules: bool,
354 desugar_doc_comments: bool,
355 subparser_name: Option<&'static str>,
356 ) -> Self {
c30ab7b3 357 let mut parser = Parser {
3b2f2976 358 sess,
dc9dc135
XL
359 token: Token::dummy(),
360 prev_span: DUMMY_SP,
cc61c64b 361 meta_var_span: None,
c30ab7b3 362 prev_token_kind: PrevTokenKind::Other,
d9579d0f 363 restrictions: Restrictions::empty(),
3b2f2976 364 recurse_into_file_modules,
ff7c6d11 365 directory: Directory {
94b46f34 366 path: Cow::from(PathBuf::new()),
ff7c6d11
XL
367 ownership: DirectoryOwnership::Owned { relative: None }
368 },
1a4d82fc
JJ
369 root_module_name: None,
370 expected_tokens: Vec::new(),
8bb4bdeb 371 token_cursor: TokenCursor {
0731742a
XL
372 frame: TokenCursorFrame::new(
373 DelimSpan::dummy(),
374 token::NoDelim,
375 &tokens.into(),
376 ),
8bb4bdeb
XL
377 stack: Vec::new(),
378 },
3b2f2976 379 desugar_doc_comments,
32a655c1 380 cfg_mods: true,
9fa01778
XL
381 unmatched_angle_bracket_count: 0,
382 max_angle_bracket_count: 0,
383 unclosed_delims: Vec::new(),
384 last_unexpected_token_span: None,
416331ca 385 last_type_ascription: None,
dc9dc135 386 subparser_name,
c30ab7b3
SL
387 };
388
dc9dc135 389 parser.token = parser.next_tok();
7cac9316 390
476ff2be
SL
391 if let Some(directory) = directory {
392 parser.directory = directory;
dc9dc135 393 } else if !parser.token.span.is_dummy() {
e1599b0c
XL
394 if let Some(FileName::Real(path)) =
395 &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path {
396 if let Some(directory_path) = path.parent() {
397 parser.directory.path = Cow::from(directory_path.to_path_buf());
398 }
ff7c6d11 399 }
c30ab7b3 400 }
7cac9316 401
cc61c64b 402 parser.process_potential_macro_variable();
c30ab7b3
SL
403 parser
404 }
405
dc9dc135 406 fn next_tok(&mut self) -> Token {
7cac9316
XL
407 let mut next = if self.desugar_doc_comments {
408 self.token_cursor.next_desugared()
409 } else {
410 self.token_cursor.next()
8bb4bdeb 411 };
dc9dc135 412 if next.span.is_dummy() {
83c7162d 413 // Tweak the location for better diagnostics, but keep syntactic context intact.
dc9dc135 414 next.span = self.prev_span.with_ctxt(next.span.ctxt());
1a4d82fc 415 }
8bb4bdeb 416 next
1a4d82fc
JJ
417 }
418
9fa01778 419 /// Converts the current token to a string using `self`'s reader.
85aaf69f 420 pub fn this_token_to_string(&self) -> String {
94b46f34 421 pprust::token_to_string(&self.token)
1a4d82fc
JJ
422 }
423
e74abb32 424 fn token_descr(&self) -> Option<&'static str> {
dc9dc135
XL
425 Some(match &self.token.kind {
426 _ if self.token.is_special_ident() => "reserved identifier",
427 _ if self.token.is_used_keyword() => "keyword",
428 _ if self.token.is_unused_keyword() => "reserved keyword",
a1dfa0c6 429 token::DocComment(..) => "doc comment",
2c00a5a8
XL
430 _ => return None,
431 })
432 }
433
e74abb32 434 pub(super) fn this_token_descr(&self) -> String {
2c00a5a8
XL
435 if let Some(prefix) = self.token_descr() {
436 format!("{} `{}`", prefix, self.this_token_to_string())
437 } else {
438 format!("`{}`", self.this_token_to_string())
439 }
a7813a04
XL
440 }
441
94b46f34 442 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
9346a6ac 443 match self.expect_one_of(&[], &[]) {
9cc50fc6 444 Err(e) => Err(e),
e74abb32
XL
445 // We can get `Ok(true)` from `recover_closing_delimiter`
446 // which is called in `expected_one_of_not_found`.
447 Ok(_) => FatalError.raise(),
9346a6ac 448 }
1a4d82fc
JJ
449 }
450
9fa01778 451 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
dc9dc135 452 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
1a4d82fc
JJ
453 if self.expected_tokens.is_empty() {
454 if self.token == *t {
9cc50fc6 455 self.bump();
9fa01778 456 Ok(false)
1a4d82fc 457 } else {
dc9dc135 458 self.unexpected_try_recover(t)
1a4d82fc
JJ
459 }
460 } else {
94b46f34 461 self.expect_one_of(slice::from_ref(t), &[])
1a4d82fc
JJ
462 }
463 }
464
465 /// Expect next token to be edible or inedible token. If edible,
466 /// then consume it; if inedible, then return without consuming
467 /// anything. Signal a fatal error if next token is unexpected.
9fa01778
XL
468 pub fn expect_one_of(
469 &mut self,
dc9dc135
XL
470 edible: &[TokenKind],
471 inedible: &[TokenKind],
9fa01778 472 ) -> PResult<'a, bool /* recovered */> {
dc9dc135 473 if edible.contains(&self.token.kind) {
9cc50fc6 474 self.bump();
9fa01778 475 Ok(false)
dc9dc135 476 } else if inedible.contains(&self.token.kind) {
1a4d82fc 477 // leave it in the input
9fa01778 478 Ok(false)
dc9dc135 479 } else if self.last_unexpected_token_span == Some(self.token.span) {
9fa01778 480 FatalError.raise();
1a4d82fc 481 } else {
dc9dc135 482 self.expected_one_of_not_found(edible, inedible)
1a4d82fc 483 }
970d7e83
LB
484 }
485
e74abb32 486 fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
2c00a5a8
XL
487 self.parse_ident_common(true)
488 }
489
490 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
dc9dc135
XL
491 match self.token.kind {
492 token::Ident(name, _) => {
041b39d2 493 if self.token.is_reserved_ident() {
2c00a5a8
XL
494 let mut err = self.expected_ident_found();
495 if recover {
496 err.emit();
497 } else {
498 return Err(err);
499 }
041b39d2 500 }
dc9dc135 501 let span = self.token.span;
9cc50fc6 502 self.bump();
dc9dc135 503 Ok(Ident::new(name, span))
970d7e83 504 }
970d7e83 505 _ => {
c30ab7b3 506 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
48663c56
XL
507 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
508 } else {
509 self.expected_ident_found()
510 })
970d7e83
LB
511 }
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
JJ
520 let is_present = self.token == *tok;
521 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
522 is_present
970d7e83
LB
523 }
524
9fa01778 525 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
dc9dc135 526 pub fn eat(&mut self, tok: &TokenKind) -> bool {
1a4d82fc 527 let is_present = self.check(tok);
9cc50fc6
SL
528 if is_present { self.bump() }
529 is_present
970d7e83
LB
530 }
531
e74abb32
XL
532 /// If the next token is the given keyword, returns `true` without eating it.
533 /// An expectation is also added for diagnostics purposes.
dc9dc135 534 fn check_keyword(&mut self, kw: Symbol) -> bool {
85aaf69f
SL
535 self.expected_tokens.push(TokenType::Keyword(kw));
536 self.token.is_keyword(kw)
537 }
538
e74abb32
XL
539 /// If the next token is the given keyword, eats it and returns `true`.
540 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
541 fn eat_keyword(&mut self, kw: Symbol) -> bool {
85aaf69f 542 if self.check_keyword(kw) {
9cc50fc6
SL
543 self.bump();
544 true
85aaf69f 545 } else {
9cc50fc6 546 false
85aaf69f
SL
547 }
548 }
549
dc9dc135 550 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
1a4d82fc 551 if self.token.is_keyword(kw) {
9cc50fc6
SL
552 self.bump();
553 true
1a4d82fc 554 } else {
9cc50fc6 555 false
1a4d82fc 556 }
970d7e83
LB
557 }
558
9fa01778
XL
559 /// If the given word is not a keyword, signals an error.
560 /// If the next token is not the given word, signals an error.
561 /// Otherwise, eats it.
dc9dc135 562 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
9cc50fc6
SL
563 if !self.eat_keyword(kw) {
564 self.unexpected()
9346a6ac
AL
565 } else {
566 Ok(())
970d7e83
LB
567 }
568 }
569
e74abb32
XL
570 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
571 if ok {
32a655c1
SL
572 true
573 } else {
e74abb32 574 self.expected_tokens.push(typ);
32a655c1
SL
575 false
576 }
577 }
578
e74abb32
XL
579 fn check_ident(&mut self) -> bool {
580 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
581 }
582
32a655c1 583 fn check_path(&mut self) -> bool {
e74abb32 584 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
32a655c1
SL
585 }
586
587 fn check_type(&mut self) -> bool {
e74abb32 588 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
32a655c1
SL
589 }
590
9fa01778 591 fn check_const_arg(&mut self) -> bool {
e74abb32
XL
592 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
593 }
594
595 /// Checks to see if the next token is either `+` or `+=`.
596 /// Otherwise returns `false`.
597 fn check_plus(&mut self) -> bool {
598 self.check_or_expected(
599 self.token.is_like_plus(),
600 TokenType::Token(token::BinOp(token::Plus)),
601 )
9fa01778
XL
602 }
603
604 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
605 /// and continues. If a `+` is not seen, returns `false`.
94b46f34 606 ///
9fa01778
XL
607 /// This is used when token-splitting `+=` into `+`.
608 /// See issue #47856 for an example of when this may occur.
94b46f34
XL
609 fn eat_plus(&mut self) -> bool {
610 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
dc9dc135 611 match self.token.kind {
94b46f34
XL
612 token::BinOp(token::Plus) => {
613 self.bump();
614 true
615 }
616 token::BinOpEq(token::Plus) => {
dc9dc135 617 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
94b46f34
XL
618 self.bump_with(token::Eq, span);
619 true
620 }
621 _ => false,
622 }
623 }
624
9fa01778
XL
625 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
626 /// `&` and continues. If an `&` is not seen, signals an error.
9cc50fc6 627 fn expect_and(&mut self) -> PResult<'a, ()> {
85aaf69f 628 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
dc9dc135 629 match self.token.kind {
9cc50fc6
SL
630 token::BinOp(token::And) => {
631 self.bump();
632 Ok(())
633 }
1a4d82fc 634 token::AndAnd => {
dc9dc135 635 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
ea8adc8c
XL
636 Ok(self.bump_with(token::BinOp(token::And), span))
637 }
638 _ => self.unexpected()
639 }
640 }
641
9fa01778
XL
642 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
643 /// `|` and continues. If an `|` is not seen, signals an error.
ea8adc8c
XL
644 fn expect_or(&mut self) -> PResult<'a, ()> {
645 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
dc9dc135 646 match self.token.kind {
ea8adc8c
XL
647 token::BinOp(token::Or) => {
648 self.bump();
649 Ok(())
650 }
651 token::OrOr => {
dc9dc135 652 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
ea8adc8c 653 Ok(self.bump_with(token::BinOp(token::Or), span))
1a4d82fc 654 }
9cc50fc6 655 _ => self.unexpected()
970d7e83
LB
656 }
657 }
658
9fa01778
XL
659 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
660 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
661 /// and continue. If a `<` is not seen, returns false.
1a4d82fc
JJ
662 ///
663 /// This is meant to be used when parsing generics on a path to get the
664 /// starting token.
9cc50fc6 665 fn eat_lt(&mut self) -> bool {
85aaf69f 666 self.expected_tokens.push(TokenType::Token(token::Lt));
dc9dc135 667 let ate = match self.token.kind {
9cc50fc6
SL
668 token::Lt => {
669 self.bump();
670 true
671 }
1a4d82fc 672 token::BinOp(token::Shl) => {
dc9dc135 673 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
ea8adc8c 674 self.bump_with(token::Lt, span);
9cc50fc6 675 true
1a4d82fc 676 }
9fa01778 677 token::LArrow => {
dc9dc135 678 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
9fa01778
XL
679 self.bump_with(token::BinOp(token::Minus), span);
680 true
681 }
9cc50fc6 682 _ => false,
9fa01778
XL
683 };
684
685 if ate {
686 // See doc comment for `unmatched_angle_bracket_count`.
687 self.unmatched_angle_bracket_count += 1;
688 self.max_angle_bracket_count += 1;
689 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1a4d82fc 690 }
9fa01778
XL
691
692 ate
1a4d82fc
JJ
693 }
694
9cc50fc6
SL
695 fn expect_lt(&mut self) -> PResult<'a, ()> {
696 if !self.eat_lt() {
697 self.unexpected()
9346a6ac
AL
698 } else {
699 Ok(())
1a4d82fc
JJ
700 }
701 }
702
9fa01778
XL
703 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
704 /// with a single `>` and continues. If a `>` is not seen, signals an error.
94b46f34 705 fn expect_gt(&mut self) -> PResult<'a, ()> {
85aaf69f 706 self.expected_tokens.push(TokenType::Token(token::Gt));
dc9dc135 707 let ate = match self.token.kind {
9cc50fc6
SL
708 token::Gt => {
709 self.bump();
9fa01778 710 Some(())
9cc50fc6 711 }
1a4d82fc 712 token::BinOp(token::Shr) => {
dc9dc135 713 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
9fa01778 714 Some(self.bump_with(token::Gt, span))
1a4d82fc
JJ
715 }
716 token::BinOpEq(token::Shr) => {
dc9dc135 717 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
9fa01778 718 Some(self.bump_with(token::Ge, span))
1a4d82fc
JJ
719 }
720 token::Ge => {
dc9dc135 721 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
9fa01778 722 Some(self.bump_with(token::Eq, span))
1a4d82fc 723 }
9fa01778
XL
724 _ => None,
725 };
726
727 match ate {
728 Some(_) => {
729 // See doc comment for `unmatched_angle_bracket_count`.
730 if self.unmatched_angle_bracket_count > 0 {
731 self.unmatched_angle_bracket_count -= 1;
732 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
733 }
734
735 Ok(())
736 },
737 None => self.unexpected(),
1a4d82fc
JJ
738 }
739 }
740
9fa01778
XL
741 /// Parses a sequence, including the closing delimiter. The function
742 /// `f` must consume tokens until reaching the next separator or
1a4d82fc 743 /// closing bracket.
e74abb32 744 fn parse_seq_to_end<T>(
416331ca
XL
745 &mut self,
746 ket: &TokenKind,
747 sep: SeqSep,
748 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
749 ) -> PResult<'a, Vec<T>> {
750 let (val, _, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
9fa01778
XL
751 if !recovered {
752 self.bump();
753 }
9346a6ac 754 Ok(val)
970d7e83
LB
755 }
756
9fa01778
XL
757 /// Parses a sequence, not including the closing delimiter. The function
758 /// `f` must consume tokens until reaching the next separator or
1a4d82fc 759 /// closing bracket.
e74abb32 760 fn parse_seq_to_before_end<T>(
9fa01778 761 &mut self,
dc9dc135 762 ket: &TokenKind,
9fa01778 763 sep: SeqSep,
416331ca
XL
764 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
765 ) -> PResult<'a, (Vec<T>, bool, bool)> {
abe05a73 766 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
7453a54e
SL
767 }
768
416331ca
XL
769 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
770 kets.iter().any(|k| {
771 match expect {
772 TokenExpectType::Expect => self.check(k),
773 TokenExpectType::NoExpect => self.token == **k,
774 }
775 })
776 }
777
e74abb32 778 fn parse_seq_to_before_tokens<T>(
b7449926 779 &mut self,
dc9dc135 780 kets: &[&TokenKind],
b7449926
XL
781 sep: SeqSep,
782 expect: TokenExpectType,
416331ca
XL
783 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
784 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
9fa01778
XL
785 let mut first = true;
786 let mut recovered = false;
416331ca 787 let mut trailing = false;
c30ab7b3 788 let mut v = vec![];
416331ca
XL
789 while !self.expect_any_with_type(kets, expect) {
790 if let token::CloseDelim(..) | token::Eof = self.token.kind {
791 break
792 }
7cac9316
XL
793 if let Some(ref t) = sep.sep {
794 if first {
795 first = false;
796 } else {
9fa01778
XL
797 match self.expect(t) {
798 Ok(false) => {}
799 Ok(true) => {
800 recovered = true;
801 break;
abe05a73 802 }
9fa01778 803 Err(mut e) => {
e1599b0c 804 // Attempt to keep parsing if it was a similar separator.
9fa01778 805 if let Some(ref tokens) = t.similar_tokens() {
dc9dc135 806 if tokens.contains(&self.token.kind) {
9fa01778
XL
807 self.bump();
808 }
809 }
810 e.emit();
e1599b0c 811 // Attempt to keep parsing if it was an omitted separator.
9fa01778
XL
812 match f(self) {
813 Ok(t) => {
814 v.push(t);
815 continue;
816 },
817 Err(mut e) => {
818 e.cancel();
819 break;
820 }
abe05a73
XL
821 }
822 }
7453a54e
SL
823 }
824 }
7453a54e 825 }
416331ca
XL
826 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
827 trailing = true;
7453a54e
SL
828 break;
829 }
830
abe05a73
XL
831 let t = f(self)?;
832 v.push(t);
970d7e83 833 }
7453a54e 834
416331ca 835 Ok((v, trailing, recovered))
970d7e83
LB
836 }
837
9fa01778
XL
838 /// Parses a sequence, including the closing delimiter. The function
839 /// `f` must consume tokens until reaching the next separator or
1a4d82fc 840 /// closing bracket.
416331ca 841 fn parse_unspanned_seq<T>(
9fa01778 842 &mut self,
dc9dc135
XL
843 bra: &TokenKind,
844 ket: &TokenKind,
9fa01778 845 sep: SeqSep,
416331ca
XL
846 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
847 ) -> PResult<'a, (Vec<T>, bool)> {
54a0048b 848 self.expect(bra)?;
416331ca 849 let (result, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
9fa01778
XL
850 if !recovered {
851 self.eat(ket);
852 }
416331ca
XL
853 Ok((result, trailing))
854 }
855
856 fn parse_delim_comma_seq<T>(
857 &mut self,
858 delim: DelimToken,
859 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
860 ) -> PResult<'a, (Vec<T>, bool)> {
861 self.parse_unspanned_seq(
862 &token::OpenDelim(delim),
863 &token::CloseDelim(delim),
864 SeqSep::trailing_allowed(token::Comma),
865 f,
866 )
867 }
868
869 fn parse_paren_comma_seq<T>(
870 &mut self,
871 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
872 ) -> PResult<'a, (Vec<T>, bool)> {
873 self.parse_delim_comma_seq(token::Paren, f)
970d7e83
LB
874 }
875
e1599b0c 876 /// Advance the parser by one token.
9cc50fc6 877 pub fn bump(&mut self) {
c30ab7b3 878 if self.prev_token_kind == PrevTokenKind::Eof {
7453a54e
SL
879 // Bumping after EOF is a bad sign, usually an infinite loop.
880 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
881 }
882
dc9dc135 883 self.prev_span = self.meta_var_span.take().unwrap_or(self.token.span);
9e0c209e
SL
884
885 // Record last token kind for possible error recovery.
dc9dc135 886 self.prev_token_kind = match self.token.kind {
c30ab7b3
SL
887 token::DocComment(..) => PrevTokenKind::DocComment,
888 token::Comma => PrevTokenKind::Comma,
cc61c64b 889 token::BinOp(token::Plus) => PrevTokenKind::Plus,
48663c56 890 token::BinOp(token::Or) => PrevTokenKind::BitOr,
c30ab7b3
SL
891 token::Interpolated(..) => PrevTokenKind::Interpolated,
892 token::Eof => PrevTokenKind::Eof,
041b39d2 893 token::Ident(..) => PrevTokenKind::Ident,
c30ab7b3 894 _ => PrevTokenKind::Other,
1a4d82fc 895 };
9e0c209e 896
dc9dc135 897 self.token = self.next_tok();
1a4d82fc 898 self.expected_tokens.clear();
e1599b0c 899 // Check after each token.
cc61c64b 900 self.process_potential_macro_variable();
223e47cc 901 }
1a4d82fc 902
e1599b0c 903 /// Advances the parser using provided token as a next one. Use this when
7453a54e 904 /// consuming a part of a token. For example a single `<` from `<<`.
dc9dc135
XL
905 fn bump_with(&mut self, next: TokenKind, span: Span) {
906 self.prev_span = self.token.span.with_hi(span.lo());
9e0c209e
SL
907 // It would be incorrect to record the kind of the current token, but
908 // fortunately for tokens currently using `bump_with`, the
e1599b0c 909 // `prev_token_kind` will be of no use anyway.
c30ab7b3 910 self.prev_token_kind = PrevTokenKind::Other;
dc9dc135 911 self.token = Token::new(next, span);
7453a54e 912 self.expected_tokens.clear();
223e47cc 913 }
7453a54e 914
e74abb32
XL
915 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
916 /// When `dist == 0` then the current token is looked at.
917 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
c30ab7b3 918 if dist == 0 {
e74abb32 919 return looker(&self.token);
223e47cc 920 }
8bb4bdeb 921
dc9dc135 922 let frame = &self.token_cursor.frame;
e74abb32 923 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
8bb4bdeb 924 Some(tree) => match tree {
dc9dc135
XL
925 TokenTree::Token(token) => token,
926 TokenTree::Delimited(dspan, delim, _) =>
927 Token::new(token::OpenDelim(delim), dspan.open),
928 }
929 None => Token::new(token::CloseDelim(frame.delim), frame.span.close)
8bb4bdeb 930 })
223e47cc 931 }
ff7c6d11 932
dc9dc135
XL
933 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
934 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
935 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
223e47cc 936 }
223e47cc 937
9fa01778 938 /// Parses asyncness: `async` or nothing.
8faf50e0 939 fn parse_asyncness(&mut self) -> IsAsync {
dc9dc135 940 if self.eat_keyword(kw::Async) {
8faf50e0 941 IsAsync::Async {
e1599b0c
XL
942 closure_id: DUMMY_NODE_ID,
943 return_impl_trait_id: DUMMY_NODE_ID,
8faf50e0
XL
944 }
945 } else {
946 IsAsync::NotAsync
947 }
948 }
949
9fa01778 950 /// Parses unsafety: `unsafe` or nothing.
2c00a5a8 951 fn parse_unsafety(&mut self) -> Unsafety {
dc9dc135 952 if self.eat_keyword(kw::Unsafe) {
2c00a5a8 953 Unsafety::Unsafe
1a4d82fc 954 } else {
2c00a5a8 955 Unsafety::Normal
1a4d82fc
JJ
956 }
957 }
958
416331ca
XL
959 /// Parses mutability (`mut` or nothing).
960 fn parse_mutability(&mut self) -> Mutability {
961 if self.eat_keyword(kw::Mut) {
962 Mutability::Mutable
223e47cc 963 } else {
416331ca
XL
964 Mutability::Immutable
965 }
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) {
971 Some(Mutability::Mutable)
972 } else if self.eat_keyword(kw::Const) {
973 Some(Mutability::Immutable)
974 } else {
975 None
976 }
977 }
978
416331ca
XL
979 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
980 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
981 self.token.kind {
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
416331ca
XL
990 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
991 let delim = match self.token.kind {
992 token::OpenDelim(delim) => delim,
993 _ => {
994 let msg = "expected open delimiter";
995 let mut err = self.fatal(msg);
996 err.span_label(self.token.span, msg);
997 return Err(err)
998 }
999 };
1000 let tts = match self.parse_token_tree() {
1001 TokenTree::Delimited(_, _, tts) => tts,
1002 _ => unreachable!(),
1003 };
1004 let delim = match delim {
1005 token::Paren => MacDelimiter::Parenthesis,
1006 token::Bracket => MacDelimiter::Bracket,
1007 token::Brace => MacDelimiter::Brace,
1008 token::NoDelim => self.bug("unexpected no delimiter"),
1009 };
1010 Ok((delim, tts.into()))
1011 }
041b39d2 1012
e74abb32
XL
1013 fn parse_or_use_outer_attributes(
1014 &mut self,
1015 already_parsed_attrs: Option<ThinVec<Attribute>>,
1016 ) -> PResult<'a, ThinVec<Attribute>> {
416331ca
XL
1017 if let Some(attrs) = already_parsed_attrs {
1018 Ok(attrs)
970d7e83 1019 } else {
416331ca 1020 self.parse_outer_attributes().map(|a| a.into())
970d7e83
LB
1021 }
1022 }
1023
e74abb32 1024 pub fn process_potential_macro_variable(&mut self) {
416331ca 1025 self.token = match self.token.kind {
e1599b0c 1026 token::Dollar if self.token.span.from_expansion() &&
416331ca 1027 self.look_ahead(1, |t| t.is_ident()) => {
a7813a04 1028 self.bump();
416331ca
XL
1029 let name = match self.token.kind {
1030 token::Ident(name, _) => name,
1031 _ => unreachable!()
1032 };
1033 let span = self.prev_span.to(self.token.span);
1034 self.diagnostic()
1035 .struct_span_fatal(span, &format!("unknown macro variable `{}`", name))
1036 .span_label(span, "unknown macro variable")
1037 .emit();
1038 self.bump();
1039 return
a7813a04 1040 }
416331ca
XL
1041 token::Interpolated(ref nt) => {
1042 self.meta_var_span = Some(self.token.span);
1043 // Interpolated identifier and lifetime tokens are replaced with usual identifier
1044 // and lifetime tokens, so the former are never encountered during normal parsing.
1045 match **nt {
1046 token::NtIdent(ident, is_raw) =>
1047 Token::new(token::Ident(ident.name, is_raw), ident.span),
1048 token::NtLifetime(ident) =>
1049 Token::new(token::Lifetime(ident.name), ident.span),
1050 _ => return,
1051 }
1052 }
1053 _ => return,
1054 };
83c7162d 1055 }
a7813a04 1056
416331ca 1057 /// Parses a single token tree from the input.
e74abb32 1058 pub fn parse_token_tree(&mut self) -> TokenTree {
dc9dc135 1059 match self.token.kind {
416331ca
XL
1060 token::OpenDelim(..) => {
1061 let frame = mem::replace(&mut self.token_cursor.frame,
1062 self.token_cursor.stack.pop().unwrap());
1063 self.token.span = frame.span.entire();
0731742a 1064 self.bump();
416331ca
XL
1065 TokenTree::Delimited(
1066 frame.span,
1067 frame.delim,
1068 frame.tree_cursor.stream.into(),
1069 )
1070 },
1071 token::CloseDelim(_) | token::Eof => unreachable!(),
1072 _ => {
1073 let token = self.token.take();
1074 self.bump();
1075 TokenTree::Token(token)
0731742a 1076 }
0731742a
XL
1077 }
1078 }
1079
416331ca
XL
1080 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1081 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1082 let mut tts = Vec::new();
1083 while self.token != token::Eof {
1084 tts.push(self.parse_token_tree());
54a0048b 1085 }
416331ca 1086 Ok(tts)
54a0048b
SL
1087 }
1088
416331ca
XL
1089 pub fn parse_tokens(&mut self) -> TokenStream {
1090 let mut result = Vec::new();
1091 loop {
1092 match self.token.kind {
1093 token::Eof | token::CloseDelim(..) => break,
1094 _ => result.push(self.parse_token_tree().into()),
ff7c6d11 1095 }
223e47cc 1096 }
416331ca 1097 TokenStream::new(result)
223e47cc
LB
1098 }
1099
416331ca
XL
1100 /// Evaluates the closure with restrictions in place.
1101 ///
1102 /// Afters the closure is evaluated, restrictions are reset.
e74abb32 1103 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
416331ca 1104 let old = self.restrictions;
e74abb32
XL
1105 self.restrictions = res;
1106 let res = f(self);
416331ca 1107 self.restrictions = old;
e74abb32 1108 res
8faf50e0
XL
1109 }
1110
416331ca
XL
1111 fn is_crate_vis(&self) -> bool {
1112 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
223e47cc
LB
1113 }
1114
416331ca
XL
1115 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1116 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1117 /// If the following element can't be a tuple (i.e., it's a function definition), then
1118 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1119 /// so emit a proper diagnostic.
1120 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
1121 maybe_whole!(self, NtVis, |x| x);
dc9dc135 1122
416331ca
XL
1123 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1124 if self.is_crate_vis() {
1125 self.bump(); // `crate`
e74abb32 1126 self.sess.gated_spans.crate_visibility_modifier.borrow_mut().push(self.prev_span);
416331ca
XL
1127 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1128 }
223e47cc 1129
416331ca
XL
1130 if !self.eat_keyword(kw::Pub) {
1131 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1132 // keyword to grab a span from for inherited visibility; an empty span at the
1133 // beginning of the current token would seem to be the "Schelling span".
1134 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited))
1135 }
1136 let lo = self.prev_span;
223e47cc 1137
416331ca
XL
1138 if self.check(&token::OpenDelim(token::Paren)) {
1139 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1140 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1141 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1142 // by the following tokens.
e74abb32
XL
1143 if self.is_keyword_ahead(1, &[kw::Crate])
1144 && self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
416331ca 1145 {
e74abb32 1146 // Parse `pub(crate)`.
416331ca
XL
1147 self.bump(); // `(`
1148 self.bump(); // `crate`
1149 self.expect(&token::CloseDelim(token::Paren))?; // `)`
e74abb32
XL
1150 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1151 return Ok(respan(lo.to(self.prev_span), vis));
416331ca 1152 } else if self.is_keyword_ahead(1, &[kw::In]) {
e74abb32 1153 // Parse `pub(in path)`.
416331ca
XL
1154 self.bump(); // `(`
1155 self.bump(); // `in`
1156 let path = self.parse_path(PathStyle::Mod)?; // `path`
1157 self.expect(&token::CloseDelim(token::Paren))?; // `)`
e74abb32 1158 let vis = VisibilityKind::Restricted {
416331ca
XL
1159 path: P(path),
1160 id: ast::DUMMY_NODE_ID,
e74abb32
XL
1161 };
1162 return Ok(respan(lo.to(self.prev_span), vis));
1163 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1164 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
416331ca 1165 {
e74abb32 1166 // Parse `pub(self)` or `pub(super)`.
416331ca
XL
1167 self.bump(); // `(`
1168 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1169 self.expect(&token::CloseDelim(token::Paren))?; // `)`
e74abb32 1170 let vis = VisibilityKind::Restricted {
416331ca
XL
1171 path: P(path),
1172 id: ast::DUMMY_NODE_ID,
e74abb32
XL
1173 };
1174 return Ok(respan(lo.to(self.prev_span), vis));
1175 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct.
1176 self.recover_incorrect_vis_restriction()?;
1177 // Emit diagnostic, but continue with public visibility.
532ac7d7 1178 }
223e47cc 1179 }
223e47cc 1180
416331ca 1181 Ok(respan(lo, VisibilityKind::Public))
223e47cc
LB
1182 }
1183
e74abb32
XL
1184 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1185 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1186 self.bump(); // `(`
1187 let path = self.parse_path(PathStyle::Mod)?;
1188 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1189
1190 let msg = "incorrect visibility restriction";
1191 let suggestion = r##"some possible visibility restrictions are:
1192`pub(crate)`: visible only on the current crate
1193`pub(super)`: visible only in the current module's parent
1194`pub(in path::to::module)`: visible only on the specified path"##;
1195
1196 let path_str = pprust::path_to_string(&path);
1197
1198 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1199 .help(suggestion)
1200 .span_suggestion(
1201 path.span,
1202 &format!("make this visible only to module `{}` with `in`", path_str),
1203 format!("in {}", path_str),
1204 Applicability::MachineApplicable,
1205 )
1206 .emit();
1207
1208 Ok(())
1209 }
1210
1211 /// Parses `extern` followed by an optional ABI string, or nothing.
1212 fn parse_extern_abi(&mut self) -> PResult<'a, Abi> {
1213 if self.eat_keyword(kw::Extern) {
1214 Ok(self.parse_opt_abi()?.unwrap_or(Abi::C))
1215 } else {
1216 Ok(Abi::Rust)
1217 }
1218 }
1219
1a4d82fc
JJ
1220 /// Parses a string as an ABI spec on an extern type or module. Consumes
1221 /// the `extern` keyword, if one is found.
2c00a5a8 1222 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
dc9dc135
XL
1223 match self.token.kind {
1224 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
1225 token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
e74abb32 1226 self.expect_no_suffix(self.token.span, "an ABI spec", suffix);
9cc50fc6 1227 self.bump();
dc9dc135 1228 match abi::lookup(&symbol.as_str()) {
9346a6ac 1229 Some(abi) => Ok(Some(abi)),
1a4d82fc 1230 None => {
e74abb32 1231 self.error_on_invalid_abi(symbol);
9346a6ac 1232 Ok(None)
223e47cc
LB
1233 }
1234 }
223e47cc 1235 }
9346a6ac 1236 _ => Ok(None),
223e47cc
LB
1237 }
1238 }
1239
e74abb32
XL
1240 /// Emit an error where `symbol` is an invalid ABI.
1241 fn error_on_invalid_abi(&self, symbol: Symbol) {
1242 let prev_span = self.prev_span;
1243 struct_span_err!(
1244 self.sess.span_diagnostic,
1245 prev_span,
1246 E0703,
1247 "invalid ABI: found `{}`",
1248 symbol
1249 )
1250 .span_label(prev_span, "invalid ABI")
1251 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1252 .emit();
1253 }
1254
dc9dc135
XL
1255 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1256 fn ban_async_in_2015(&self, async_span: Span) {
1257 if async_span.rust_2015() {
1258 self.diagnostic()
1259 .struct_span_err_with_code(
1260 async_span,
1261 "`async fn` is not permitted in the 2015 edition",
1262 DiagnosticId::Error("E0670".into())
1263 )
1264 .emit();
1265 }
1266 }
1267
e74abb32
XL
1268 fn collect_tokens<R>(
1269 &mut self,
1270 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1271 ) -> PResult<'a, (R, TokenStream)> {
3b2f2976
XL
1272 // Record all tokens we parse when parsing this item.
1273 let mut tokens = Vec::new();
8faf50e0
XL
1274 let prev_collecting = match self.token_cursor.frame.last_token {
1275 LastToken::Collecting(ref mut list) => {
416331ca 1276 Some(mem::take(list))
3b2f2976 1277 }
8faf50e0
XL
1278 LastToken::Was(ref mut last) => {
1279 tokens.extend(last.take());
1280 None
1281 }
1282 };
3b2f2976
XL
1283 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1284 let prev = self.token_cursor.stack.len();
1285 let ret = f(self);
1286 let last_token = if self.token_cursor.stack.len() == prev {
1287 &mut self.token_cursor.frame.last_token
dc9dc135
XL
1288 } else if self.token_cursor.stack.get(prev).is_none() {
1289 // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1290 // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1291 // (#62881).
e74abb32 1292 return Ok((ret?, TokenStream::default()));
3b2f2976
XL
1293 } else {
1294 &mut self.token_cursor.stack[prev].last_token
1295 };
8faf50e0 1296
9fa01778 1297 // Pull out the tokens that we've collected from the call to `f` above.
8faf50e0 1298 let mut collected_tokens = match *last_token {
416331ca 1299 LastToken::Collecting(ref mut v) => mem::take(v),
dc9dc135
XL
1300 LastToken::Was(ref was) => {
1301 let msg = format!("our vector went away? - found Was({:?})", was);
1302 debug!("collect_tokens: {}", msg);
1303 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1304 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1305 // with mismatched delimiters *and* recovery lookahead on the likely typo
1306 // `pub ident(` (#62895, different but similar to the case above).
e74abb32 1307 return Ok((ret?, TokenStream::default()));
dc9dc135 1308 }
3b2f2976
XL
1309 };
1310
1311 // If we're not at EOF our current token wasn't actually consumed by
1312 // `f`, but it'll still be in our list that we pulled out. In that case
1313 // put it back.
8faf50e0
XL
1314 let extra_token = if self.token != token::Eof {
1315 collected_tokens.pop()
3b2f2976 1316 } else {
8faf50e0
XL
1317 None
1318 };
1319
1320 // If we were previously collecting tokens, then this was a recursive
1321 // call. In that case we need to record all the tokens we collected in
1322 // our parent list as well. To do that we push a clone of our stream
1323 // onto the previous list.
8faf50e0
XL
1324 match prev_collecting {
1325 Some(mut list) => {
9fa01778 1326 list.extend(collected_tokens.iter().cloned());
8faf50e0
XL
1327 list.extend(extra_token);
1328 *last_token = LastToken::Collecting(list);
1329 }
1330 None => {
1331 *last_token = LastToken::Was(extra_token);
1332 }
3b2f2976
XL
1333 }
1334
9fa01778 1335 Ok((ret?, TokenStream::new(collected_tokens)))
3b2f2976
XL
1336 }
1337
0531ce1d
XL
1338 /// `::{` or `::*`
1339 fn is_import_coupler(&mut self) -> bool {
1340 self.check(&token::ModSep) &&
1341 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
1342 *t == token::BinOp(token::Star))
a7813a04
XL
1343 }
1344
e74abb32 1345 fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
dc9dc135
XL
1346 let ret = match self.token.kind {
1347 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
1348 (symbol, ast::StrStyle::Cooked, suffix),
1349 token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
1350 (symbol, ast::StrStyle::Raw(n), suffix),
9cc50fc6 1351 _ => return None
1a4d82fc 1352 };
9cc50fc6
SL
1353 self.bump();
1354 Some(ret)
1a4d82fc
JJ
1355 }
1356
476ff2be 1357 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
9cc50fc6 1358 match self.parse_optional_str() {
1a4d82fc 1359 Some((s, style, suf)) => {
c30ab7b3 1360 let sp = self.prev_span;
532ac7d7 1361 self.expect_no_suffix(sp, "a string literal", suf);
9346a6ac 1362 Ok((s, style))
970d7e83 1363 }
0531ce1d
XL
1364 _ => {
1365 let msg = "expected string literal";
1366 let mut err = self.fatal(msg);
dc9dc135 1367 err.span_label(self.token.span, msg);
0531ce1d
XL
1368 Err(err)
1369 }
223e47cc
LB
1370 }
1371 }
e74abb32 1372}
532ac7d7 1373
e74abb32
XL
1374crate fn make_unclosed_delims_error(
1375 unmatched: UnmatchedBrace,
1376 sess: &ParseSess,
1377) -> Option<DiagnosticBuilder<'_>> {
1378 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1379 // `unmatched_braces` only for error recovery in the `Parser`.
1380 let found_delim = unmatched.found_delim?;
1381 let mut err = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
1382 "incorrect close delimiter: `{}`",
1383 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1384 ));
1385 err.span_label(unmatched.found_span, "incorrect close delimiter");
1386 if let Some(sp) = unmatched.candidate_span {
1387 err.span_label(sp, "close delimiter possibly meant for this");
1388 }
1389 if let Some(sp) = unmatched.unclosed_span {
1390 err.span_label(sp, "un-closed delimiter");
1391 }
1392 Some(err)
223e47cc 1393}
9fa01778 1394
e74abb32
XL
1395pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1396 *sess.reached_eof.borrow_mut() |= unclosed_delims.iter()
1397 .any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1398 for unmatched in unclosed_delims.drain(..) {
1399 make_unclosed_delims_error(unmatched, sess).map(|mut e| e.emit());
9fa01778 1400 }
9fa01778 1401}