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