4 pub use item::AliasKind;
6 pub use module::{ModulePath, ModulePathSuccess};
9 pub use path::PathStyle;
14 self, DUMMY_NODE_ID, AttrStyle, Attribute, BindingMode, CrateSugar, FnDecl, Ident,
15 IsAsync, MacDelimiter, Mutability, Param, StrStyle, SelfKind, TyKind, Visibility,
16 VisibilityKind, Unsafety,
18 use crate::parse::{ParseSess, PResult, Directory, DirectoryOwnership, SeqSep, literal, token};
19 use crate::parse::diagnostics::{Error, dummy_arg};
20 use crate::parse::lexer::UnmatchedBrace;
21 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
22 use crate::parse::token::{Token, TokenKind, DelimToken};
23 use crate::print::pprust;
25 use crate::source_map::{self, respan};
26 use crate::symbol::{kw, sym, Symbol};
27 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
30 use errors::{Applicability, DiagnosticId, FatalError};
31 use rustc_target::spec::abi::{self, Abi};
32 use syntax_pos::{Span, BytePos, DUMMY_SP, FileName};
36 use std::{cmp, mem, slice};
37 use std::path::PathBuf;
40 struct Restrictions: u8 {
41 const STMT_EXPR = 1 << 0;
42 const NO_STRUCT_LITERAL = 1 << 1;
46 #[derive(Clone, Copy, PartialEq, Debug)]
47 crate enum SemiColonMode {
53 #[derive(Clone, Copy, PartialEq, Debug)]
54 crate enum BlockMode {
59 /// Like `maybe_whole_expr`, but for things other than expressions.
61 macro_rules! maybe_whole {
62 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
63 if let token::Interpolated(nt) = &$p.token.kind {
64 if let token::$constructor(x) = &**nt {
73 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
75 macro_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) {
78 if let token::Interpolated(nt) = &$self.token.kind {
79 if let token::NtTy(ty) = &**nt {
82 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
89 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
90 if let Some(ref mut rhs) = rhs {
96 #[derive(Debug, Clone, Copy, PartialEq)]
108 // NOTE: `Ident`s are handled by `common.rs`.
111 pub struct Parser<'a> {
112 pub sess: &'a ParseSess,
113 /// The current normalized token.
114 /// "Normalized" means that some interpolated tokens
115 /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced
116 /// with non-interpolated identifier and lifetime tokens they refer to.
117 /// Perhaps the normalized / non-normalized setup can be simplified somehow.
119 /// The span of the current non-normalized token.
120 meta_var_span: Option<Span>,
121 /// The span of the previous non-normalized token.
123 /// The kind of the previous normalized token (in simplified form).
124 prev_token_kind: PrevTokenKind,
125 restrictions: Restrictions,
126 /// Used to determine the path to externally loaded source files.
127 crate directory: Directory<'a>,
128 /// `true` to parse sub-modules in other files.
129 pub recurse_into_file_modules: bool,
130 /// Name of the root module this parser originated from. If `None`, then the
131 /// name is not known. This does not change while the parser is descending
132 /// into modules, and sub-parsers have new values for this name.
133 pub root_module_name: Option<String>,
134 crate expected_tokens: Vec<TokenType>,
135 token_cursor: TokenCursor,
136 desugar_doc_comments: bool,
137 /// `true` we should configure out of line modules as we parse.
139 /// This field is used to keep track of how many left angle brackets we have seen. This is
140 /// required in order to detect extra leading left angle brackets (`<` characters) and error
143 /// See the comments in the `parse_path_segment` function for more details.
144 crate unmatched_angle_bracket_count: u32,
145 crate max_angle_bracket_count: u32,
146 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
147 /// it gets removed from here. Every entry left at the end gets emitted as an independent
149 crate unclosed_delims: Vec<UnmatchedBrace>,
150 crate last_unexpected_token_span: Option<Span>,
151 crate last_type_ascription: Option<(Span, bool /* likely path typo */)>,
152 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
153 crate subparser_name: Option<&'static str>,
156 impl<'a> Drop for Parser<'a> {
158 let diag = self.diagnostic();
159 emit_unclosed_delims(&mut self.unclosed_delims, diag);
165 frame: TokenCursorFrame,
166 stack: Vec<TokenCursorFrame>,
170 struct TokenCursorFrame {
171 delim: token::DelimToken,
174 tree_cursor: tokenstream::Cursor,
176 last_token: LastToken,
179 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
180 /// by the parser, and then that's transitively used to record the tokens that
181 /// each parse AST item is created with.
183 /// Right now this has two states, either collecting tokens or not collecting
184 /// tokens. If we're collecting tokens we just save everything off into a local
185 /// `Vec`. This should eventually though likely save tokens from the original
186 /// token stream and just use slicing of token streams to avoid creation of a
187 /// whole new vector.
189 /// The second state is where we're passively not recording tokens, but the last
190 /// token is still tracked for when we want to start recording tokens. This
191 /// "last token" means that when we start recording tokens we'll want to ensure
192 /// that this, the first token, is included in the output.
194 /// You can find some more example usage of this in the `collect_tokens` method
197 crate enum LastToken {
198 Collecting(Vec<TreeAndJoint>),
199 Was(Option<TreeAndJoint>),
202 impl TokenCursorFrame {
203 fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
207 open_delim: delim == token::NoDelim,
208 tree_cursor: tts.clone().into_trees(),
209 close_delim: delim == token::NoDelim,
210 last_token: LastToken::Was(None),
216 fn next(&mut self) -> Token {
218 let tree = if !self.frame.open_delim {
219 self.frame.open_delim = true;
220 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
221 } else if let Some(tree) = self.frame.tree_cursor.next() {
223 } else if !self.frame.close_delim {
224 self.frame.close_delim = true;
225 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
226 } else if let Some(frame) = self.stack.pop() {
230 return Token::new(token::Eof, DUMMY_SP);
233 match self.frame.last_token {
234 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
235 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
239 TokenTree::Token(token) => return token,
240 TokenTree::Delimited(sp, delim, tts) => {
241 let frame = TokenCursorFrame::new(sp, delim, &tts);
242 self.stack.push(mem::replace(&mut self.frame, frame));
248 fn next_desugared(&mut self) -> Token {
249 let (name, sp) = match self.next() {
250 Token { kind: token::DocComment(name), span } => (name, span),
254 let stripped = strip_doc_comment_decoration(&name.as_str());
256 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
257 // required to wrap the text.
258 let mut num_of_hashes = 0;
260 for ch in stripped.chars() {
263 '#' if count > 0 => count + 1,
266 num_of_hashes = cmp::max(num_of_hashes, count);
269 let delim_span = DelimSpan::from_single(sp);
270 let body = TokenTree::Delimited(
274 TokenTree::token(token::Ident(sym::doc, false), sp),
275 TokenTree::token(token::Eq, sp),
276 TokenTree::token(TokenKind::lit(
277 token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None
280 .iter().cloned().collect::<TokenStream>().into(),
283 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
286 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
287 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
288 .iter().cloned().collect::<TokenStream>().into()
290 [TokenTree::token(token::Pound, sp), body]
291 .iter().cloned().collect::<TokenStream>().into()
299 #[derive(Clone, PartialEq)]
300 crate enum TokenType {
312 crate fn to_string(&self) -> String {
314 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
315 TokenType::Keyword(kw) => format!("`{}`", kw),
316 TokenType::Operator => "an operator".to_string(),
317 TokenType::Lifetime => "lifetime".to_string(),
318 TokenType::Ident => "identifier".to_string(),
319 TokenType::Path => "path".to_string(),
320 TokenType::Type => "type".to_string(),
321 TokenType::Const => "const".to_string(),
326 #[derive(Copy, Clone, Debug)]
327 crate enum TokenExpectType {
332 impl<'a> Parser<'a> {
336 directory: Option<Directory<'a>>,
337 recurse_into_file_modules: bool,
338 desugar_doc_comments: bool,
339 subparser_name: Option<&'static str>,
341 let mut parser = Parser {
343 token: Token::dummy(),
346 prev_token_kind: PrevTokenKind::Other,
347 restrictions: Restrictions::empty(),
348 recurse_into_file_modules,
349 directory: Directory {
350 path: Cow::from(PathBuf::new()),
351 ownership: DirectoryOwnership::Owned { relative: None }
353 root_module_name: None,
354 expected_tokens: Vec::new(),
355 token_cursor: TokenCursor {
356 frame: TokenCursorFrame::new(
363 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,
373 parser.token = parser.next_tok();
375 if let Some(directory) = directory {
376 parser.directory = directory;
377 } else if !parser.token.span.is_dummy() {
378 if let Some(FileName::Real(path)) =
379 &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path {
380 if let Some(directory_path) = path.parent() {
381 parser.directory.path = Cow::from(directory_path.to_path_buf());
386 parser.process_potential_macro_variable();
390 fn next_tok(&mut self) -> Token {
391 let mut next = if self.desugar_doc_comments {
392 self.token_cursor.next_desugared()
394 self.token_cursor.next()
396 if next.span.is_dummy() {
397 // Tweak the location for better diagnostics, but keep syntactic context intact.
398 next.span = self.prev_span.with_ctxt(next.span.ctxt());
403 /// Converts the current token to a string using `self`'s reader.
404 pub fn this_token_to_string(&self) -> String {
405 pprust::token_to_string(&self.token)
408 crate fn token_descr(&self) -> Option<&'static str> {
409 Some(match &self.token.kind {
410 _ if self.token.is_special_ident() => "reserved identifier",
411 _ if self.token.is_used_keyword() => "keyword",
412 _ if self.token.is_unused_keyword() => "reserved keyword",
413 token::DocComment(..) => "doc comment",
418 crate fn this_token_descr(&self) -> String {
419 if let Some(prefix) = self.token_descr() {
420 format!("{} `{}`", prefix, self.this_token_to_string())
422 format!("`{}`", self.this_token_to_string())
426 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
427 match self.expect_one_of(&[], &[]) {
429 Ok(_) => unreachable!(),
433 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
434 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
435 if self.expected_tokens.is_empty() {
436 if self.token == *t {
440 self.unexpected_try_recover(t)
443 self.expect_one_of(slice::from_ref(t), &[])
447 /// Expect next token to be edible or inedible token. If edible,
448 /// then consume it; if inedible, then return without consuming
449 /// anything. Signal a fatal error if next token is unexpected.
450 pub fn expect_one_of(
452 edible: &[TokenKind],
453 inedible: &[TokenKind],
454 ) -> PResult<'a, bool /* recovered */> {
455 if edible.contains(&self.token.kind) {
458 } else if inedible.contains(&self.token.kind) {
459 // leave it in the input
461 } else if self.last_unexpected_token_span == Some(self.token.span) {
464 self.expected_one_of_not_found(edible, inedible)
468 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
469 self.parse_ident_common(true)
472 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
473 match self.token.kind {
474 token::Ident(name, _) => {
475 if self.token.is_reserved_ident() {
476 let mut err = self.expected_ident_found();
483 let span = self.token.span;
485 Ok(Ident::new(name, span))
488 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
489 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
491 self.expected_ident_found()
497 /// Checks if the next token is `tok`, and returns `true` if so.
499 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
501 crate fn check(&mut self, tok: &TokenKind) -> bool {
502 let is_present = self.token == *tok;
503 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
507 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
508 pub fn eat(&mut self, tok: &TokenKind) -> bool {
509 let is_present = self.check(tok);
510 if is_present { self.bump() }
514 fn check_keyword(&mut self, kw: Symbol) -> bool {
515 self.expected_tokens.push(TokenType::Keyword(kw));
516 self.token.is_keyword(kw)
519 /// If the next token is the given keyword, eats it and returns
520 /// `true`. Otherwise, returns `false`.
521 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
522 if self.check_keyword(kw) {
530 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
531 if self.token.is_keyword(kw) {
539 /// If the given word is not a keyword, signals an error.
540 /// If the next token is not the given word, signals an error.
541 /// Otherwise, eats it.
542 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
543 if !self.eat_keyword(kw) {
550 crate fn check_ident(&mut self) -> bool {
551 if self.token.is_ident() {
554 self.expected_tokens.push(TokenType::Ident);
559 fn check_path(&mut self) -> bool {
560 if self.token.is_path_start() {
563 self.expected_tokens.push(TokenType::Path);
568 fn check_type(&mut self) -> bool {
569 if self.token.can_begin_type() {
572 self.expected_tokens.push(TokenType::Type);
577 fn check_const_arg(&mut self) -> bool {
578 if self.token.can_begin_const_arg() {
581 self.expected_tokens.push(TokenType::Const);
586 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
587 /// and continues. If a `+` is not seen, returns `false`.
589 /// This is used when token-splitting `+=` into `+`.
590 /// See issue #47856 for an example of when this may occur.
591 fn eat_plus(&mut self) -> bool {
592 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
593 match self.token.kind {
594 token::BinOp(token::Plus) => {
598 token::BinOpEq(token::Plus) => {
599 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
600 self.bump_with(token::Eq, span);
607 /// Checks to see if the next token is either `+` or `+=`.
608 /// Otherwise returns `false`.
609 fn check_plus(&mut self) -> bool {
610 if self.token.is_like_plus() {
614 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
619 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
620 /// `&` and continues. If an `&` is not seen, signals an error.
621 fn expect_and(&mut self) -> PResult<'a, ()> {
622 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
623 match self.token.kind {
624 token::BinOp(token::And) => {
629 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
630 Ok(self.bump_with(token::BinOp(token::And), span))
632 _ => self.unexpected()
636 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
637 /// `|` and continues. If an `|` is not seen, signals an error.
638 fn expect_or(&mut self) -> PResult<'a, ()> {
639 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
640 match self.token.kind {
641 token::BinOp(token::Or) => {
646 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
647 Ok(self.bump_with(token::BinOp(token::Or), span))
649 _ => self.unexpected()
653 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
654 literal::expect_no_suffix(&self.sess.span_diagnostic, sp, kind, suffix)
657 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
658 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
659 /// and continue. If a `<` is not seen, returns false.
661 /// This is meant to be used when parsing generics on a path to get the
663 fn eat_lt(&mut self) -> bool {
664 self.expected_tokens.push(TokenType::Token(token::Lt));
665 let ate = match self.token.kind {
670 token::BinOp(token::Shl) => {
671 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
672 self.bump_with(token::Lt, span);
676 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
677 self.bump_with(token::BinOp(token::Minus), span);
684 // See doc comment for `unmatched_angle_bracket_count`.
685 self.unmatched_angle_bracket_count += 1;
686 self.max_angle_bracket_count += 1;
687 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
693 fn expect_lt(&mut self) -> PResult<'a, ()> {
701 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
702 /// with a single `>` and continues. If a `>` is not seen, signals an error.
703 fn expect_gt(&mut self) -> PResult<'a, ()> {
704 self.expected_tokens.push(TokenType::Token(token::Gt));
705 let ate = match self.token.kind {
710 token::BinOp(token::Shr) => {
711 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
712 Some(self.bump_with(token::Gt, span))
714 token::BinOpEq(token::Shr) => {
715 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
716 Some(self.bump_with(token::Ge, span))
719 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
720 Some(self.bump_with(token::Eq, span))
727 // See doc comment for `unmatched_angle_bracket_count`.
728 if self.unmatched_angle_bracket_count > 0 {
729 self.unmatched_angle_bracket_count -= 1;
730 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
735 None => self.unexpected(),
739 /// Parses a sequence, including the closing delimiter. The function
740 /// `f` must consume tokens until reaching the next separator or
742 pub fn parse_seq_to_end<T>(
746 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
747 ) -> PResult<'a, Vec<T>> {
748 let (val, _, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
755 /// Parses a sequence, not including the closing delimiter. The function
756 /// `f` must consume tokens until reaching the next separator or
758 pub fn parse_seq_to_before_end<T>(
762 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
763 ) -> PResult<'a, (Vec<T>, bool, bool)> {
764 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
767 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
768 kets.iter().any(|k| {
770 TokenExpectType::Expect => self.check(k),
771 TokenExpectType::NoExpect => self.token == **k,
776 crate fn parse_seq_to_before_tokens<T>(
780 expect: TokenExpectType,
781 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
782 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
783 let mut first = true;
784 let mut recovered = false;
785 let mut trailing = false;
787 while !self.expect_any_with_type(kets, expect) {
788 if let token::CloseDelim(..) | token::Eof = self.token.kind {
791 if let Some(ref t) = sep.sep {
795 match self.expect(t) {
802 // Attempt to keep parsing if it was a similar separator.
803 if let Some(ref tokens) = t.similar_tokens() {
804 if tokens.contains(&self.token.kind) {
809 // Attempt to keep parsing if it was an omitted separator.
824 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
833 Ok((v, trailing, recovered))
836 /// Parses a sequence, including the closing delimiter. The function
837 /// `f` must consume tokens until reaching the next separator or
839 fn parse_unspanned_seq<T>(
844 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
845 ) -> PResult<'a, (Vec<T>, bool)> {
847 let (result, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
851 Ok((result, trailing))
854 fn parse_delim_comma_seq<T>(
857 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
858 ) -> PResult<'a, (Vec<T>, bool)> {
859 self.parse_unspanned_seq(
860 &token::OpenDelim(delim),
861 &token::CloseDelim(delim),
862 SeqSep::trailing_allowed(token::Comma),
867 fn parse_paren_comma_seq<T>(
869 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
870 ) -> PResult<'a, (Vec<T>, bool)> {
871 self.parse_delim_comma_seq(token::Paren, f)
874 /// Advance the parser by one token.
875 pub fn bump(&mut self) {
876 if self.prev_token_kind == PrevTokenKind::Eof {
877 // Bumping after EOF is a bad sign, usually an infinite loop.
878 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
881 self.prev_span = self.meta_var_span.take().unwrap_or(self.token.span);
883 // Record last token kind for possible error recovery.
884 self.prev_token_kind = match self.token.kind {
885 token::DocComment(..) => PrevTokenKind::DocComment,
886 token::Comma => PrevTokenKind::Comma,
887 token::BinOp(token::Plus) => PrevTokenKind::Plus,
888 token::BinOp(token::Or) => PrevTokenKind::BitOr,
889 token::Interpolated(..) => PrevTokenKind::Interpolated,
890 token::Eof => PrevTokenKind::Eof,
891 token::Ident(..) => PrevTokenKind::Ident,
892 _ => PrevTokenKind::Other,
895 self.token = self.next_tok();
896 self.expected_tokens.clear();
897 // Check after each token.
898 self.process_potential_macro_variable();
901 /// Advances the parser using provided token as a next one. Use this when
902 /// consuming a part of a token. For example a single `<` from `<<`.
903 fn bump_with(&mut self, next: TokenKind, span: Span) {
904 self.prev_span = self.token.span.with_hi(span.lo());
905 // It would be incorrect to record the kind of the current token, but
906 // fortunately for tokens currently using `bump_with`, the
907 // `prev_token_kind` will be of no use anyway.
908 self.prev_token_kind = PrevTokenKind::Other;
909 self.token = Token::new(next, span);
910 self.expected_tokens.clear();
913 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
914 F: FnOnce(&Token) -> R,
917 return f(&self.token);
920 let frame = &self.token_cursor.frame;
921 f(&match frame.tree_cursor.look_ahead(dist - 1) {
922 Some(tree) => match tree {
923 TokenTree::Token(token) => token,
924 TokenTree::Delimited(dspan, delim, _) =>
925 Token::new(token::OpenDelim(delim), dspan.open),
927 None => Token::new(token::CloseDelim(frame.delim), frame.span.close)
931 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
932 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
933 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
936 /// Parses asyncness: `async` or nothing.
937 fn parse_asyncness(&mut self) -> IsAsync {
938 if self.eat_keyword(kw::Async) {
940 closure_id: DUMMY_NODE_ID,
941 return_impl_trait_id: DUMMY_NODE_ID,
948 /// Parses unsafety: `unsafe` or nothing.
949 fn parse_unsafety(&mut self) -> Unsafety {
950 if self.eat_keyword(kw::Unsafe) {
957 fn is_named_argument(&self) -> bool {
958 let offset = match self.token.kind {
959 token::Interpolated(ref nt) => match **nt {
960 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
963 token::BinOp(token::And) | token::AndAnd => 1,
964 _ if self.token.is_keyword(kw::Mut) => 1,
968 self.look_ahead(offset, |t| t.is_ident()) &&
969 self.look_ahead(offset + 1, |t| t == &token::Colon)
972 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
974 /// This version of parse param doesn't necessarily require identifier names.
975 fn parse_param_general(
978 allow_c_variadic: bool,
979 is_name_required: impl Fn(&token::Token) -> bool,
980 ) -> PResult<'a, Param> {
981 let lo = self.token.span;
982 let attrs = self.parse_outer_attributes()?;
983 if let Some(mut param) = self.parse_self_param()? {
984 param.attrs = attrs.into();
985 return self.recover_bad_self_param(param, is_trait_item);
988 let is_name_required = is_name_required(&self.token);
989 let (pat, ty) = if is_name_required || self.is_named_argument() {
990 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
992 let pat = self.parse_fn_param_pat()?;
993 if let Err(mut err) = self.expect(&token::Colon) {
994 if let Some(ident) = self.parameter_without_type(
1001 return Ok(dummy_arg(ident));
1007 self.eat_incorrect_doc_comment_for_param_type();
1008 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1010 debug!("parse_param_general ident_to_pat");
1011 let parser_snapshot_before_ty = self.clone();
1012 self.eat_incorrect_doc_comment_for_param_type();
1013 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1014 if ty.is_ok() && self.token != token::Comma &&
1015 self.token != token::CloseDelim(token::Paren) {
1016 // This wasn't actually a type, but a pattern looking like a type,
1017 // so we are going to rollback and re-parse for recovery.
1018 ty = self.unexpected();
1022 let ident = Ident::new(kw::Invalid, self.prev_span);
1023 let bm = BindingMode::ByValue(Mutability::Immutable);
1024 let pat = self.mk_pat_ident(ty.span, bm, ident);
1028 // If this is a C-variadic argument and we hit an error, return the
1030 if self.token == token::DotDotDot {
1033 // Recover from attempting to parse the argument as a type without pattern.
1035 mem::replace(self, parser_snapshot_before_ty);
1036 self.recover_arg_parse()?
1041 let span = lo.to(self.token.span);
1044 attrs: attrs.into(),
1045 id: ast::DUMMY_NODE_ID,
1046 is_placeholder: false,
1053 /// Parses mutability (`mut` or nothing).
1054 fn parse_mutability(&mut self) -> Mutability {
1055 if self.eat_keyword(kw::Mut) {
1058 Mutability::Immutable
1062 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1063 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1065 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1067 Ok(Ident::new(symbol, self.prev_span))
1069 self.parse_ident_common(false)
1073 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
1074 let delim = match self.token.kind {
1075 token::OpenDelim(delim) => delim,
1077 let msg = "expected open delimiter";
1078 let mut err = self.fatal(msg);
1079 err.span_label(self.token.span, msg);
1083 let tts = match self.parse_token_tree() {
1084 TokenTree::Delimited(_, _, tts) => tts,
1085 _ => unreachable!(),
1087 let delim = match delim {
1088 token::Paren => MacDelimiter::Parenthesis,
1089 token::Bracket => MacDelimiter::Bracket,
1090 token::Brace => MacDelimiter::Brace,
1091 token::NoDelim => self.bug("unexpected no delimiter"),
1093 Ok((delim, tts.into()))
1096 fn parse_or_use_outer_attributes(&mut self,
1097 already_parsed_attrs: Option<ThinVec<Attribute>>)
1098 -> PResult<'a, ThinVec<Attribute>> {
1099 if let Some(attrs) = already_parsed_attrs {
1102 self.parse_outer_attributes().map(|a| a.into())
1106 crate fn process_potential_macro_variable(&mut self) {
1107 self.token = match self.token.kind {
1108 token::Dollar if self.token.span.from_expansion() &&
1109 self.look_ahead(1, |t| t.is_ident()) => {
1111 let name = match self.token.kind {
1112 token::Ident(name, _) => name,
1115 let span = self.prev_span.to(self.token.span);
1117 .struct_span_fatal(span, &format!("unknown macro variable `{}`", name))
1118 .span_label(span, "unknown macro variable")
1123 token::Interpolated(ref nt) => {
1124 self.meta_var_span = Some(self.token.span);
1125 // Interpolated identifier and lifetime tokens are replaced with usual identifier
1126 // and lifetime tokens, so the former are never encountered during normal parsing.
1128 token::NtIdent(ident, is_raw) =>
1129 Token::new(token::Ident(ident.name, is_raw), ident.span),
1130 token::NtLifetime(ident) =>
1131 Token::new(token::Lifetime(ident.name), ident.span),
1139 /// Parses a single token tree from the input.
1140 crate fn parse_token_tree(&mut self) -> TokenTree {
1141 match self.token.kind {
1142 token::OpenDelim(..) => {
1143 let frame = mem::replace(&mut self.token_cursor.frame,
1144 self.token_cursor.stack.pop().unwrap());
1145 self.token.span = frame.span.entire();
1147 TokenTree::Delimited(
1150 frame.tree_cursor.stream.into(),
1153 token::CloseDelim(_) | token::Eof => unreachable!(),
1155 let token = self.token.take();
1157 TokenTree::Token(token)
1162 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1163 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1164 let mut tts = Vec::new();
1165 while self.token != token::Eof {
1166 tts.push(self.parse_token_tree());
1171 pub fn parse_tokens(&mut self) -> TokenStream {
1172 let mut result = Vec::new();
1174 match self.token.kind {
1175 token::Eof | token::CloseDelim(..) => break,
1176 _ => result.push(self.parse_token_tree().into()),
1179 TokenStream::new(result)
1182 /// Evaluates the closure with restrictions in place.
1184 /// Afters the closure is evaluated, restrictions are reset.
1185 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
1186 where F: FnOnce(&mut Self) -> T
1188 let old = self.restrictions;
1189 self.restrictions = r;
1191 self.restrictions = old;
1196 fn parse_fn_params(&mut self, named_params: bool, allow_c_variadic: bool)
1197 -> PResult<'a, (Vec<Param> , bool)> {
1198 let sp = self.token.span;
1199 let mut c_variadic = false;
1200 let (params, _): (Vec<Option<Param>>, _) = self.parse_paren_comma_seq(|p| {
1201 let do_not_enforce_named_arguments_for_c_variadic =
1202 |token: &token::Token| -> bool {
1203 if token == &token::DotDotDot {
1209 match p.parse_param_general(
1212 do_not_enforce_named_arguments_for_c_variadic
1215 if let TyKind::CVarArgs = param.ty.kind {
1217 if p.token != token::CloseDelim(token::Paren) {
1218 let span = p.token.span;
1220 "`...` must be the last argument of a C-variadic function");
1231 let lo = p.prev_span;
1232 // Skip every token until next possible arg or end.
1233 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1234 // Create a placeholder argument for proper arg count (issue #34264).
1235 let span = lo.to(p.prev_span);
1236 Ok(Some(dummy_arg(Ident::new(kw::Invalid, span))))
1241 let params: Vec<_> = params.into_iter().filter_map(|x| x).collect();
1243 if c_variadic && params.len() <= 1 {
1245 "C-variadic function must be declared with at least one named argument");
1248 Ok((params, c_variadic))
1251 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1253 /// See `parse_self_param_with_attrs` to collect attributes.
1254 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1255 let expect_ident = |this: &mut Self| match this.token.kind {
1256 // Preserve hygienic context.
1257 token::Ident(name, _) =>
1258 { let span = this.token.span; this.bump(); Ident::new(name, span) }
1261 let isolated_self = |this: &mut Self, n| {
1262 this.look_ahead(n, |t| t.is_keyword(kw::SelfLower)) &&
1263 this.look_ahead(n + 1, |t| t != &token::ModSep)
1266 // Parse optional `self` parameter of a method.
1267 // Only a limited set of initial token sequences is considered `self` parameters; anything
1268 // else is parsed as a normal function parameter list, so some lookahead is required.
1269 let eself_lo = self.token.span;
1270 let (eself, eself_ident, eself_hi) = match self.token.kind {
1271 token::BinOp(token::And) => {
1277 (if isolated_self(self, 1) {
1279 SelfKind::Region(None, Mutability::Immutable)
1280 } else if self.is_keyword_ahead(1, &[kw::Mut]) &&
1281 isolated_self(self, 2) {
1284 SelfKind::Region(None, Mutability::Mutable)
1285 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
1286 isolated_self(self, 2) {
1288 let lt = self.expect_lifetime();
1289 SelfKind::Region(Some(lt), Mutability::Immutable)
1290 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
1291 self.is_keyword_ahead(2, &[kw::Mut]) &&
1292 isolated_self(self, 3) {
1294 let lt = self.expect_lifetime();
1296 SelfKind::Region(Some(lt), Mutability::Mutable)
1299 }, expect_ident(self), self.prev_span)
1301 token::BinOp(token::Star) => {
1306 // Emit special error for `self` cases.
1307 let msg = "cannot pass `self` by raw pointer";
1308 (if isolated_self(self, 1) {
1310 self.struct_span_err(self.token.span, msg)
1311 .span_label(self.token.span, msg)
1313 SelfKind::Value(Mutability::Immutable)
1314 } else if self.look_ahead(1, |t| t.is_mutability()) &&
1315 isolated_self(self, 2) {
1318 self.struct_span_err(self.token.span, msg)
1319 .span_label(self.token.span, msg)
1321 SelfKind::Value(Mutability::Immutable)
1324 }, expect_ident(self), self.prev_span)
1326 token::Ident(..) => {
1327 if isolated_self(self, 0) {
1330 let eself_ident = expect_ident(self);
1331 let eself_hi = self.prev_span;
1332 (if self.eat(&token::Colon) {
1333 let ty = self.parse_ty()?;
1334 SelfKind::Explicit(ty, Mutability::Immutable)
1336 SelfKind::Value(Mutability::Immutable)
1337 }, eself_ident, eself_hi)
1338 } else if self.token.is_keyword(kw::Mut) &&
1339 isolated_self(self, 1) {
1343 let eself_ident = expect_ident(self);
1344 let eself_hi = self.prev_span;
1345 (if self.eat(&token::Colon) {
1346 let ty = self.parse_ty()?;
1347 SelfKind::Explicit(ty, Mutability::Mutable)
1349 SelfKind::Value(Mutability::Mutable)
1350 }, eself_ident, eself_hi)
1355 _ => return Ok(None),
1358 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1359 Ok(Some(Param::from_self(ThinVec::default(), eself, eself_ident)))
1362 /// Returns the parsed optional self parameter with attributes and whether a self
1363 /// shortcut was used.
1364 fn parse_self_parameter_with_attrs(&mut self) -> PResult<'a, Option<Param>> {
1365 let attrs = self.parse_outer_attributes()?;
1366 let param_opt = self.parse_self_param()?;
1367 Ok(param_opt.map(|mut param| {
1368 param.attrs = attrs.into();
1373 /// Parses the parameter list and result type of a function that may have a `self` parameter.
1374 fn parse_fn_decl_with_self<F>(&mut self, parse_param_fn: F) -> PResult<'a, P<FnDecl>>
1375 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Param>,
1377 self.expect(&token::OpenDelim(token::Paren))?;
1379 // Parse optional self argument.
1380 let self_param = self.parse_self_parameter_with_attrs()?;
1382 // Parse the rest of the function parameter list.
1383 let sep = SeqSep::trailing_allowed(token::Comma);
1384 let (mut fn_inputs, recovered) = if let Some(self_param) = self_param {
1385 if self.check(&token::CloseDelim(token::Paren)) {
1386 (vec![self_param], false)
1387 } else if self.eat(&token::Comma) {
1388 let mut fn_inputs = vec![self_param];
1389 let (mut input, _, recovered) = self.parse_seq_to_before_end(
1390 &token::CloseDelim(token::Paren), sep, parse_param_fn)?;
1391 fn_inputs.append(&mut input);
1392 (fn_inputs, recovered)
1394 match self.expect_one_of(&[], &[]) {
1395 Err(err) => return Err(err),
1396 Ok(recovered) => (vec![self_param], recovered),
1400 let (input, _, recovered) =
1401 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
1408 // Parse closing paren and return type.
1409 self.expect(&token::CloseDelim(token::Paren))?;
1411 // Replace duplicated recovered params with `_` pattern to avoid unecessary errors.
1412 self.deduplicate_recovered_params_names(&mut fn_inputs);
1416 output: self.parse_ret_ty(true)?,
1421 fn is_crate_vis(&self) -> bool {
1422 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1425 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1426 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1427 /// If the following element can't be a tuple (i.e., it's a function definition), then
1428 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1429 /// so emit a proper diagnostic.
1430 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
1431 maybe_whole!(self, NtVis, |x| x);
1433 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1434 if self.is_crate_vis() {
1435 self.bump(); // `crate`
1436 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1439 if !self.eat_keyword(kw::Pub) {
1440 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1441 // keyword to grab a span from for inherited visibility; an empty span at the
1442 // beginning of the current token would seem to be the "Schelling span".
1443 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited))
1445 let lo = self.prev_span;
1447 if self.check(&token::OpenDelim(token::Paren)) {
1448 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1449 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1450 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1451 // by the following tokens.
1452 if self.is_keyword_ahead(1, &[kw::Crate]) &&
1453 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
1457 self.bump(); // `crate`
1458 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1460 lo.to(self.prev_span),
1461 VisibilityKind::Crate(CrateSugar::PubCrate),
1464 } else if self.is_keyword_ahead(1, &[kw::In]) {
1467 self.bump(); // `in`
1468 let path = self.parse_path(PathStyle::Mod)?; // `path`
1469 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1470 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
1472 id: ast::DUMMY_NODE_ID,
1475 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
1476 self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1478 // `pub(self)` or `pub(super)`
1480 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1481 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1482 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
1484 id: ast::DUMMY_NODE_ID,
1487 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
1488 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1490 let msg = "incorrect visibility restriction";
1491 let suggestion = r##"some possible visibility restrictions are:
1492 `pub(crate)`: visible only on the current crate
1493 `pub(super)`: visible only in the current module's parent
1494 `pub(in path::to::module)`: visible only on the specified path"##;
1495 let path = self.parse_path(PathStyle::Mod)?;
1497 let help_msg = format!("make this visible only to module `{}` with `in`", path);
1498 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1499 struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg)
1504 format!("in {}", path),
1505 Applicability::MachineApplicable,
1507 .emit(); // Emit diagnostic, but continue with public visibility.
1511 Ok(respan(lo, VisibilityKind::Public))
1514 /// Parses a string as an ABI spec on an extern type or module. Consumes
1515 /// the `extern` keyword, if one is found.
1516 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
1517 match self.token.kind {
1518 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
1519 token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
1520 let sp = self.token.span;
1521 self.expect_no_suffix(sp, "an ABI spec", suffix);
1523 match abi::lookup(&symbol.as_str()) {
1524 Some(abi) => Ok(Some(abi)),
1526 let prev_span = self.prev_span;
1528 self.sess.span_diagnostic,
1531 "invalid ABI: found `{}`",
1534 .span_label(prev_span, "invalid ABI")
1535 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1546 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1547 fn ban_async_in_2015(&self, async_span: Span) {
1548 if async_span.rust_2015() {
1550 .struct_span_err_with_code(
1552 "`async fn` is not permitted in the 2015 edition",
1553 DiagnosticId::Error("E0670".into())
1559 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
1560 where F: FnOnce(&mut Self) -> PResult<'a, R>
1562 // Record all tokens we parse when parsing this item.
1563 let mut tokens = Vec::new();
1564 let prev_collecting = match self.token_cursor.frame.last_token {
1565 LastToken::Collecting(ref mut list) => {
1566 Some(mem::take(list))
1568 LastToken::Was(ref mut last) => {
1569 tokens.extend(last.take());
1573 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1574 let prev = self.token_cursor.stack.len();
1576 let last_token = if self.token_cursor.stack.len() == prev {
1577 &mut self.token_cursor.frame.last_token
1578 } else if self.token_cursor.stack.get(prev).is_none() {
1579 // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1580 // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1582 return Ok((ret?, TokenStream::new(vec![])));
1584 &mut self.token_cursor.stack[prev].last_token
1587 // Pull out the tokens that we've collected from the call to `f` above.
1588 let mut collected_tokens = match *last_token {
1589 LastToken::Collecting(ref mut v) => mem::take(v),
1590 LastToken::Was(ref was) => {
1591 let msg = format!("our vector went away? - found Was({:?})", was);
1592 debug!("collect_tokens: {}", msg);
1593 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1594 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1595 // with mismatched delimiters *and* recovery lookahead on the likely typo
1596 // `pub ident(` (#62895, different but similar to the case above).
1597 return Ok((ret?, TokenStream::new(vec![])));
1601 // If we're not at EOF our current token wasn't actually consumed by
1602 // `f`, but it'll still be in our list that we pulled out. In that case
1604 let extra_token = if self.token != token::Eof {
1605 collected_tokens.pop()
1610 // If we were previously collecting tokens, then this was a recursive
1611 // call. In that case we need to record all the tokens we collected in
1612 // our parent list as well. To do that we push a clone of our stream
1613 // onto the previous list.
1614 match prev_collecting {
1616 list.extend(collected_tokens.iter().cloned());
1617 list.extend(extra_token);
1618 *last_token = LastToken::Collecting(list);
1621 *last_token = LastToken::Was(extra_token);
1625 Ok((ret?, TokenStream::new(collected_tokens)))
1629 fn is_import_coupler(&mut self) -> bool {
1630 self.check(&token::ModSep) &&
1631 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
1632 *t == token::BinOp(token::Star))
1635 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
1636 let ret = match self.token.kind {
1637 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
1638 (symbol, ast::StrStyle::Cooked, suffix),
1639 token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
1640 (symbol, ast::StrStyle::Raw(n), suffix),
1647 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
1648 match self.parse_optional_str() {
1649 Some((s, style, suf)) => {
1650 let sp = self.prev_span;
1651 self.expect_no_suffix(sp, "a string literal", suf);
1655 let msg = "expected string literal";
1656 let mut err = self.fatal(msg);
1657 err.span_label(self.token.span, msg);
1663 fn report_invalid_macro_expansion_item(&self) {
1664 self.struct_span_err(
1666 "macros that expand to items must be delimited with braces or followed by a semicolon",
1667 ).multipart_suggestion(
1668 "change the delimiters to curly braces",
1670 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
1671 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
1673 Applicability::MaybeIncorrect,
1675 self.sess.source_map.next_point(self.prev_span),
1678 Applicability::MaybeIncorrect,
1683 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
1684 for unmatched in unclosed_delims.iter() {
1685 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
1686 "incorrect close delimiter: `{}`",
1687 pprust::token_kind_to_string(&token::CloseDelim(unmatched.found_delim)),
1689 err.span_label(unmatched.found_span, "incorrect close delimiter");
1690 if let Some(sp) = unmatched.candidate_span {
1691 err.span_label(sp, "close delimiter possibly meant for this");
1693 if let Some(sp) = unmatched.unclosed_span {
1694 err.span_label(sp, "un-closed delimiter");
1698 unclosed_delims.clear();