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