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 /// If the next token is the given keyword, returns `true` without eating it.
515 /// An expectation is also added for diagnostics purposes.
516 fn check_keyword(&mut self, kw: Symbol) -> bool {
517 self.expected_tokens.push(TokenType::Keyword(kw));
518 self.token.is_keyword(kw)
521 /// If the next token is the given keyword, eats it and returns `true`.
522 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
523 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
524 if self.check_keyword(kw) {
532 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
533 if self.token.is_keyword(kw) {
541 /// If the given word is not a keyword, signals an error.
542 /// If the next token is not the given word, signals an error.
543 /// Otherwise, eats it.
544 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
545 if !self.eat_keyword(kw) {
552 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
556 self.expected_tokens.push(typ);
561 crate fn check_ident(&mut self) -> bool {
562 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
565 fn check_path(&mut self) -> bool {
566 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
569 fn check_type(&mut self) -> bool {
570 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
573 fn check_const_arg(&mut self) -> bool {
574 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
577 /// Checks to see if the next token is either `+` or `+=`.
578 /// Otherwise returns `false`.
579 fn check_plus(&mut self) -> bool {
580 self.check_or_expected(
581 self.token.is_like_plus(),
582 TokenType::Token(token::BinOp(token::Plus)),
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 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
608 /// `&` and continues. If an `&` is not seen, signals an error.
609 fn expect_and(&mut self) -> PResult<'a, ()> {
610 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
611 match self.token.kind {
612 token::BinOp(token::And) => {
617 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
618 Ok(self.bump_with(token::BinOp(token::And), span))
620 _ => self.unexpected()
624 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
625 /// `|` and continues. If an `|` is not seen, signals an error.
626 fn expect_or(&mut self) -> PResult<'a, ()> {
627 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
628 match self.token.kind {
629 token::BinOp(token::Or) => {
634 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
635 Ok(self.bump_with(token::BinOp(token::Or), span))
637 _ => self.unexpected()
641 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
642 literal::expect_no_suffix(&self.sess.span_diagnostic, sp, kind, suffix)
645 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
646 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
647 /// and continue. If a `<` is not seen, returns false.
649 /// This is meant to be used when parsing generics on a path to get the
651 fn eat_lt(&mut self) -> bool {
652 self.expected_tokens.push(TokenType::Token(token::Lt));
653 let ate = match self.token.kind {
658 token::BinOp(token::Shl) => {
659 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
660 self.bump_with(token::Lt, span);
664 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
665 self.bump_with(token::BinOp(token::Minus), span);
672 // See doc comment for `unmatched_angle_bracket_count`.
673 self.unmatched_angle_bracket_count += 1;
674 self.max_angle_bracket_count += 1;
675 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
681 fn expect_lt(&mut self) -> PResult<'a, ()> {
689 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
690 /// with a single `>` and continues. If a `>` is not seen, signals an error.
691 fn expect_gt(&mut self) -> PResult<'a, ()> {
692 self.expected_tokens.push(TokenType::Token(token::Gt));
693 let ate = match self.token.kind {
698 token::BinOp(token::Shr) => {
699 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
700 Some(self.bump_with(token::Gt, span))
702 token::BinOpEq(token::Shr) => {
703 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
704 Some(self.bump_with(token::Ge, span))
707 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
708 Some(self.bump_with(token::Eq, span))
715 // See doc comment for `unmatched_angle_bracket_count`.
716 if self.unmatched_angle_bracket_count > 0 {
717 self.unmatched_angle_bracket_count -= 1;
718 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
723 None => self.unexpected(),
727 /// Parses a sequence, including the closing delimiter. The function
728 /// `f` must consume tokens until reaching the next separator or
730 pub fn parse_seq_to_end<T>(
734 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
735 ) -> PResult<'a, Vec<T>> {
736 let (val, _, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
743 /// Parses a sequence, not including the closing delimiter. The function
744 /// `f` must consume tokens until reaching the next separator or
746 pub fn parse_seq_to_before_end<T>(
750 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
751 ) -> PResult<'a, (Vec<T>, bool, bool)> {
752 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
755 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
756 kets.iter().any(|k| {
758 TokenExpectType::Expect => self.check(k),
759 TokenExpectType::NoExpect => self.token == **k,
764 crate fn parse_seq_to_before_tokens<T>(
768 expect: TokenExpectType,
769 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
770 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
771 let mut first = true;
772 let mut recovered = false;
773 let mut trailing = false;
775 while !self.expect_any_with_type(kets, expect) {
776 if let token::CloseDelim(..) | token::Eof = self.token.kind {
779 if let Some(ref t) = sep.sep {
783 match self.expect(t) {
790 // Attempt to keep parsing if it was a similar separator.
791 if let Some(ref tokens) = t.similar_tokens() {
792 if tokens.contains(&self.token.kind) {
797 // Attempt to keep parsing if it was an omitted separator.
812 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
821 Ok((v, trailing, recovered))
824 /// Parses a sequence, including the closing delimiter. The function
825 /// `f` must consume tokens until reaching the next separator or
827 fn parse_unspanned_seq<T>(
832 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
833 ) -> PResult<'a, (Vec<T>, bool)> {
835 let (result, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
839 Ok((result, trailing))
842 fn parse_delim_comma_seq<T>(
845 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
846 ) -> PResult<'a, (Vec<T>, bool)> {
847 self.parse_unspanned_seq(
848 &token::OpenDelim(delim),
849 &token::CloseDelim(delim),
850 SeqSep::trailing_allowed(token::Comma),
855 fn parse_paren_comma_seq<T>(
857 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
858 ) -> PResult<'a, (Vec<T>, bool)> {
859 self.parse_delim_comma_seq(token::Paren, f)
862 /// Advance the parser by one token.
863 pub fn bump(&mut self) {
864 if self.prev_token_kind == PrevTokenKind::Eof {
865 // Bumping after EOF is a bad sign, usually an infinite loop.
866 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
869 self.prev_span = self.meta_var_span.take().unwrap_or(self.token.span);
871 // Record last token kind for possible error recovery.
872 self.prev_token_kind = match self.token.kind {
873 token::DocComment(..) => PrevTokenKind::DocComment,
874 token::Comma => PrevTokenKind::Comma,
875 token::BinOp(token::Plus) => PrevTokenKind::Plus,
876 token::BinOp(token::Or) => PrevTokenKind::BitOr,
877 token::Interpolated(..) => PrevTokenKind::Interpolated,
878 token::Eof => PrevTokenKind::Eof,
879 token::Ident(..) => PrevTokenKind::Ident,
880 _ => PrevTokenKind::Other,
883 self.token = self.next_tok();
884 self.expected_tokens.clear();
885 // Check after each token.
886 self.process_potential_macro_variable();
889 /// Advances the parser using provided token as a next one. Use this when
890 /// consuming a part of a token. For example a single `<` from `<<`.
891 fn bump_with(&mut self, next: TokenKind, span: Span) {
892 self.prev_span = self.token.span.with_hi(span.lo());
893 // It would be incorrect to record the kind of the current token, but
894 // fortunately for tokens currently using `bump_with`, the
895 // `prev_token_kind` will be of no use anyway.
896 self.prev_token_kind = PrevTokenKind::Other;
897 self.token = Token::new(next, span);
898 self.expected_tokens.clear();
901 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
902 /// When `dist == 0` then the current token is looked at.
903 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
905 return looker(&self.token);
908 let frame = &self.token_cursor.frame;
909 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
910 Some(tree) => match tree {
911 TokenTree::Token(token) => token,
912 TokenTree::Delimited(dspan, delim, _) =>
913 Token::new(token::OpenDelim(delim), dspan.open),
915 None => Token::new(token::CloseDelim(frame.delim), frame.span.close)
919 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
920 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
921 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
924 /// Parses asyncness: `async` or nothing.
925 fn parse_asyncness(&mut self) -> IsAsync {
926 if self.eat_keyword(kw::Async) {
928 closure_id: DUMMY_NODE_ID,
929 return_impl_trait_id: DUMMY_NODE_ID,
936 /// Parses unsafety: `unsafe` or nothing.
937 fn parse_unsafety(&mut self) -> Unsafety {
938 if self.eat_keyword(kw::Unsafe) {
945 /// Parses mutability (`mut` or nothing).
946 fn parse_mutability(&mut self) -> Mutability {
947 if self.eat_keyword(kw::Mut) {
950 Mutability::Immutable
954 /// Possibly parses mutability (`const` or `mut`).
955 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
956 if self.eat_keyword(kw::Mut) {
957 Some(Mutability::Mutable)
958 } else if self.eat_keyword(kw::Const) {
959 Some(Mutability::Immutable)
965 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
966 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
968 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
970 Ok(Ident::new(symbol, self.prev_span))
972 self.parse_ident_common(false)
976 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
977 let delim = match self.token.kind {
978 token::OpenDelim(delim) => delim,
980 let msg = "expected open delimiter";
981 let mut err = self.fatal(msg);
982 err.span_label(self.token.span, msg);
986 let tts = match self.parse_token_tree() {
987 TokenTree::Delimited(_, _, tts) => tts,
990 let delim = match delim {
991 token::Paren => MacDelimiter::Parenthesis,
992 token::Bracket => MacDelimiter::Bracket,
993 token::Brace => MacDelimiter::Brace,
994 token::NoDelim => self.bug("unexpected no delimiter"),
996 Ok((delim, tts.into()))
999 fn parse_or_use_outer_attributes(
1001 already_parsed_attrs: Option<ThinVec<Attribute>>,
1002 ) -> PResult<'a, ThinVec<Attribute>> {
1003 if let Some(attrs) = already_parsed_attrs {
1006 self.parse_outer_attributes().map(|a| a.into())
1010 crate fn process_potential_macro_variable(&mut self) {
1011 self.token = match self.token.kind {
1012 token::Dollar if self.token.span.from_expansion() &&
1013 self.look_ahead(1, |t| t.is_ident()) => {
1015 let name = match self.token.kind {
1016 token::Ident(name, _) => name,
1019 let span = self.prev_span.to(self.token.span);
1021 .struct_span_fatal(span, &format!("unknown macro variable `{}`", name))
1022 .span_label(span, "unknown macro variable")
1027 token::Interpolated(ref nt) => {
1028 self.meta_var_span = Some(self.token.span);
1029 // Interpolated identifier and lifetime tokens are replaced with usual identifier
1030 // and lifetime tokens, so the former are never encountered during normal parsing.
1032 token::NtIdent(ident, is_raw) =>
1033 Token::new(token::Ident(ident.name, is_raw), ident.span),
1034 token::NtLifetime(ident) =>
1035 Token::new(token::Lifetime(ident.name), ident.span),
1043 /// Parses a single token tree from the input.
1044 crate fn parse_token_tree(&mut self) -> TokenTree {
1045 match self.token.kind {
1046 token::OpenDelim(..) => {
1047 let frame = mem::replace(&mut self.token_cursor.frame,
1048 self.token_cursor.stack.pop().unwrap());
1049 self.token.span = frame.span.entire();
1051 TokenTree::Delimited(
1054 frame.tree_cursor.stream.into(),
1057 token::CloseDelim(_) | token::Eof => unreachable!(),
1059 let token = self.token.take();
1061 TokenTree::Token(token)
1066 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1067 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1068 let mut tts = Vec::new();
1069 while self.token != token::Eof {
1070 tts.push(self.parse_token_tree());
1075 pub fn parse_tokens(&mut self) -> TokenStream {
1076 let mut result = Vec::new();
1078 match self.token.kind {
1079 token::Eof | token::CloseDelim(..) => break,
1080 _ => result.push(self.parse_token_tree().into()),
1083 TokenStream::new(result)
1086 /// Evaluates the closure with restrictions in place.
1088 /// Afters the closure is evaluated, restrictions are reset.
1089 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1090 let old = self.restrictions;
1091 self.restrictions = res;
1093 self.restrictions = old;
1100 allow_c_variadic: bool,
1101 ) -> PResult<'a, Vec<Param>> {
1102 let sp = self.token.span;
1103 let do_not_enforce_named_params_for_c_variadic = |token: &token::Token| {
1105 token::DotDotDot => false,
1109 let mut c_variadic = false;
1110 let (params, _) = self.parse_paren_comma_seq(|p| {
1111 match p.parse_param_general(
1115 do_not_enforce_named_params_for_c_variadic,
1118 if let TyKind::CVarArgs = param.ty.kind {
1120 if p.token != token::CloseDelim(token::Paren) {
1123 "`...` must be the last argument of a C-variadic function",
1125 // FIXME(eddyb) this should probably still push `CVarArgs`.
1126 // Maybe AST validation/HIR lowering should emit the above error?
1137 let lo = p.prev_span;
1138 // Skip every token until next possible arg or end.
1139 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1140 // Create a placeholder argument for proper arg count (issue #34264).
1141 let span = lo.to(p.prev_span);
1142 Ok(Some(dummy_arg(Ident::new(kw::Invalid, span))))
1147 let params: Vec<_> = params.into_iter().filter_map(|x| x).collect();
1149 if c_variadic && params.len() <= 1 {
1152 "C-variadic function must be declared with at least one named argument",
1159 /// Parses the parameter list and result type of a function that may have a `self` parameter.
1160 fn parse_fn_decl_with_self(
1162 is_name_required: impl Copy + Fn(&token::Token) -> bool,
1163 ) -> PResult<'a, P<FnDecl>> {
1164 // Parse the arguments, starting out with `self` being allowed...
1165 let mut is_self_allowed = true;
1166 let (mut inputs, _): (Vec<_>, _) = self.parse_paren_comma_seq(|p| {
1167 let res = p.parse_param_general(is_self_allowed, true, false, is_name_required);
1168 // ...but now that we've parsed the first argument, `self` is no longer allowed.
1169 is_self_allowed = false;
1173 // Replace duplicated recovered params with `_` pattern to avoid unecessary errors.
1174 self.deduplicate_recovered_params_names(&mut inputs);
1178 output: self.parse_ret_ty(true)?,
1182 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1184 /// This version of parse param doesn't necessarily require identifier names.
1185 fn parse_param_general(
1187 is_self_allowed: bool,
1188 is_trait_item: bool,
1189 allow_c_variadic: bool,
1190 is_name_required: impl Fn(&token::Token) -> bool,
1191 ) -> PResult<'a, Param> {
1192 let lo = self.token.span;
1193 let attrs = self.parse_outer_attributes()?;
1195 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1196 if let Some(mut param) = self.parse_self_param()? {
1197 param.attrs = attrs.into();
1198 return if is_self_allowed {
1201 self.recover_bad_self_param(param, is_trait_item)
1205 let is_name_required = is_name_required(&self.token);
1206 let (pat, ty) = if is_name_required || self.is_named_param() {
1207 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1209 let pat = self.parse_fn_param_pat()?;
1210 if let Err(mut err) = self.expect(&token::Colon) {
1211 if let Some(ident) = self.parameter_without_type(
1219 return Ok(dummy_arg(ident));
1225 self.eat_incorrect_doc_comment_for_param_type();
1226 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1228 debug!("parse_param_general ident_to_pat");
1229 let parser_snapshot_before_ty = self.clone();
1230 self.eat_incorrect_doc_comment_for_param_type();
1231 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1232 if ty.is_ok() && self.token != token::Comma &&
1233 self.token != token::CloseDelim(token::Paren) {
1234 // This wasn't actually a type, but a pattern looking like a type,
1235 // so we are going to rollback and re-parse for recovery.
1236 ty = self.unexpected();
1240 let ident = Ident::new(kw::Invalid, self.prev_span);
1241 let bm = BindingMode::ByValue(Mutability::Immutable);
1242 let pat = self.mk_pat_ident(ty.span, bm, ident);
1245 // If this is a C-variadic argument and we hit an error, return the error.
1246 Err(err) if self.token == token::DotDotDot => return Err(err),
1247 // Recover from attempting to parse the argument as a type without pattern.
1250 mem::replace(self, parser_snapshot_before_ty);
1251 self.recover_arg_parse()?
1256 let span = lo.to(self.token.span);
1259 attrs: attrs.into(),
1260 id: ast::DUMMY_NODE_ID,
1261 is_placeholder: false,
1268 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1270 /// See `parse_self_param_with_attrs` to collect attributes.
1271 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1272 // Extract an identifier *after* having confirmed that the token is one.
1273 let expect_self_ident = |this: &mut Self| {
1274 match this.token.kind {
1275 // Preserve hygienic context.
1276 token::Ident(name, _) => {
1277 let span = this.token.span;
1279 Ident::new(name, span)
1281 _ => unreachable!(),
1284 // Is `self` `n` tokens ahead?
1285 let is_isolated_self = |this: &Self, n| {
1286 this.is_keyword_ahead(n, &[kw::SelfLower])
1287 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1289 // Is `mut self` `n` tokens ahead?
1290 let is_isolated_mut_self = |this: &Self, n| {
1291 this.is_keyword_ahead(n, &[kw::Mut])
1292 && is_isolated_self(this, n + 1)
1294 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1295 let parse_self_possibly_typed = |this: &mut Self, m| {
1296 let eself_ident = expect_self_ident(this);
1297 let eself_hi = this.prev_span;
1298 let eself = if this.eat(&token::Colon) {
1299 SelfKind::Explicit(this.parse_ty()?, m)
1303 Ok((eself, eself_ident, eself_hi))
1305 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1306 let recover_self_ptr = |this: &mut Self| {
1307 let msg = "cannot pass `self` by raw pointer";
1308 let span = this.token.span;
1309 this.struct_span_err(span, msg)
1310 .span_label(span, msg)
1313 Ok((SelfKind::Value(Mutability::Immutable), expect_self_ident(this), this.prev_span))
1316 // Parse optional `self` parameter of a method.
1317 // Only a limited set of initial token sequences is considered `self` parameters; anything
1318 // else is parsed as a normal function parameter list, so some lookahead is required.
1319 let eself_lo = self.token.span;
1320 let (eself, eself_ident, eself_hi) = match self.token.kind {
1321 token::BinOp(token::And) => {
1322 let eself = if is_isolated_self(self, 1) {
1325 SelfKind::Region(None, Mutability::Immutable)
1326 } else if is_isolated_mut_self(self, 1) {
1330 SelfKind::Region(None, Mutability::Mutable)
1331 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1334 let lt = self.expect_lifetime();
1335 SelfKind::Region(Some(lt), Mutability::Immutable)
1336 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1339 let lt = self.expect_lifetime();
1341 SelfKind::Region(Some(lt), Mutability::Mutable)
1346 (eself, expect_self_ident(self), self.prev_span)
1349 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1351 recover_self_ptr(self)?
1353 // `*mut self` and `*const self`
1354 token::BinOp(token::Star) if
1355 self.look_ahead(1, |t| t.is_mutability())
1356 && is_isolated_self(self, 2) =>
1360 recover_self_ptr(self)?
1362 // `self` and `self: TYPE`
1363 token::Ident(..) if is_isolated_self(self, 0) => {
1364 parse_self_possibly_typed(self, Mutability::Immutable)?
1366 // `mut self` and `mut self: TYPE`
1367 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1369 parse_self_possibly_typed(self, Mutability::Mutable)?
1371 _ => return Ok(None),
1374 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1375 Ok(Some(Param::from_self(ThinVec::default(), eself, eself_ident)))
1378 fn is_named_param(&self) -> bool {
1379 let offset = match self.token.kind {
1380 token::Interpolated(ref nt) => match **nt {
1381 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1384 token::BinOp(token::And) | token::AndAnd => 1,
1385 _ if self.token.is_keyword(kw::Mut) => 1,
1389 self.look_ahead(offset, |t| t.is_ident()) &&
1390 self.look_ahead(offset + 1, |t| t == &token::Colon)
1393 fn is_crate_vis(&self) -> bool {
1394 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1397 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1398 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1399 /// If the following element can't be a tuple (i.e., it's a function definition), then
1400 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1401 /// so emit a proper diagnostic.
1402 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
1403 maybe_whole!(self, NtVis, |x| x);
1405 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1406 if self.is_crate_vis() {
1407 self.bump(); // `crate`
1408 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1411 if !self.eat_keyword(kw::Pub) {
1412 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1413 // keyword to grab a span from for inherited visibility; an empty span at the
1414 // beginning of the current token would seem to be the "Schelling span".
1415 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited))
1417 let lo = self.prev_span;
1419 if self.check(&token::OpenDelim(token::Paren)) {
1420 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1421 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1422 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1423 // by the following tokens.
1424 if self.is_keyword_ahead(1, &[kw::Crate])
1425 && self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
1427 // Parse `pub(crate)`.
1429 self.bump(); // `crate`
1430 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1431 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1432 return Ok(respan(lo.to(self.prev_span), vis));
1433 } else if self.is_keyword_ahead(1, &[kw::In]) {
1434 // Parse `pub(in path)`.
1436 self.bump(); // `in`
1437 let path = self.parse_path(PathStyle::Mod)?; // `path`
1438 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1439 let vis = VisibilityKind::Restricted {
1441 id: ast::DUMMY_NODE_ID,
1443 return Ok(respan(lo.to(self.prev_span), vis));
1444 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1445 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1447 // Parse `pub(self)` or `pub(super)`.
1449 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1450 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1451 let vis = VisibilityKind::Restricted {
1453 id: ast::DUMMY_NODE_ID,
1455 return Ok(respan(lo.to(self.prev_span), vis));
1456 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct.
1457 self.recover_incorrect_vis_restriction()?;
1458 // Emit diagnostic, but continue with public visibility.
1462 Ok(respan(lo, VisibilityKind::Public))
1465 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1466 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1468 let path = self.parse_path(PathStyle::Mod)?;
1469 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1471 let msg = "incorrect visibility restriction";
1472 let suggestion = r##"some possible visibility restrictions are:
1473 `pub(crate)`: visible only on the current crate
1474 `pub(super)`: visible only in the current module's parent
1475 `pub(in path::to::module)`: visible only on the specified path"##;
1477 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1481 &format!("make this visible only to module `{}` with `in`", path),
1482 format!("in {}", path),
1483 Applicability::MachineApplicable,
1490 /// Parses a string as an ABI spec on an extern type or module. Consumes
1491 /// the `extern` keyword, if one is found.
1492 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
1493 match self.token.kind {
1494 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
1495 token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
1496 self.expect_no_suffix(self.token.span, "an ABI spec", suffix);
1498 match abi::lookup(&symbol.as_str()) {
1499 Some(abi) => Ok(Some(abi)),
1501 self.error_on_invalid_abi(symbol);
1510 /// Emit an error where `symbol` is an invalid ABI.
1511 fn error_on_invalid_abi(&self, symbol: Symbol) {
1512 let prev_span = self.prev_span;
1514 self.sess.span_diagnostic,
1517 "invalid ABI: found `{}`",
1520 .span_label(prev_span, "invalid ABI")
1521 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1525 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1526 fn ban_async_in_2015(&self, async_span: Span) {
1527 if async_span.rust_2015() {
1529 .struct_span_err_with_code(
1531 "`async fn` is not permitted in the 2015 edition",
1532 DiagnosticId::Error("E0670".into())
1538 fn collect_tokens<R>(
1540 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1541 ) -> PResult<'a, (R, TokenStream)> {
1542 // Record all tokens we parse when parsing this item.
1543 let mut tokens = Vec::new();
1544 let prev_collecting = match self.token_cursor.frame.last_token {
1545 LastToken::Collecting(ref mut list) => {
1546 Some(mem::take(list))
1548 LastToken::Was(ref mut last) => {
1549 tokens.extend(last.take());
1553 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1554 let prev = self.token_cursor.stack.len();
1556 let last_token = if self.token_cursor.stack.len() == prev {
1557 &mut self.token_cursor.frame.last_token
1558 } else if self.token_cursor.stack.get(prev).is_none() {
1559 // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1560 // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1562 return Ok((ret?, TokenStream::new(vec![])));
1564 &mut self.token_cursor.stack[prev].last_token
1567 // Pull out the tokens that we've collected from the call to `f` above.
1568 let mut collected_tokens = match *last_token {
1569 LastToken::Collecting(ref mut v) => mem::take(v),
1570 LastToken::Was(ref was) => {
1571 let msg = format!("our vector went away? - found Was({:?})", was);
1572 debug!("collect_tokens: {}", msg);
1573 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1574 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1575 // with mismatched delimiters *and* recovery lookahead on the likely typo
1576 // `pub ident(` (#62895, different but similar to the case above).
1577 return Ok((ret?, TokenStream::new(vec![])));
1581 // If we're not at EOF our current token wasn't actually consumed by
1582 // `f`, but it'll still be in our list that we pulled out. In that case
1584 let extra_token = if self.token != token::Eof {
1585 collected_tokens.pop()
1590 // If we were previously collecting tokens, then this was a recursive
1591 // call. In that case we need to record all the tokens we collected in
1592 // our parent list as well. To do that we push a clone of our stream
1593 // onto the previous list.
1594 match prev_collecting {
1596 list.extend(collected_tokens.iter().cloned());
1597 list.extend(extra_token);
1598 *last_token = LastToken::Collecting(list);
1601 *last_token = LastToken::Was(extra_token);
1605 Ok((ret?, TokenStream::new(collected_tokens)))
1609 fn is_import_coupler(&mut self) -> bool {
1610 self.check(&token::ModSep) &&
1611 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
1612 *t == token::BinOp(token::Star))
1615 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
1616 let ret = match self.token.kind {
1617 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
1618 (symbol, ast::StrStyle::Cooked, suffix),
1619 token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
1620 (symbol, ast::StrStyle::Raw(n), suffix),
1627 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
1628 match self.parse_optional_str() {
1629 Some((s, style, suf)) => {
1630 let sp = self.prev_span;
1631 self.expect_no_suffix(sp, "a string literal", suf);
1635 let msg = "expected string literal";
1636 let mut err = self.fatal(msg);
1637 err.span_label(self.token.span, msg);
1643 fn report_invalid_macro_expansion_item(&self) {
1644 self.struct_span_err(
1646 "macros that expand to items must be delimited with braces or followed by a semicolon",
1647 ).multipart_suggestion(
1648 "change the delimiters to curly braces",
1650 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
1651 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
1653 Applicability::MaybeIncorrect,
1655 self.sess.source_map.next_point(self.prev_span),
1658 Applicability::MaybeIncorrect,
1663 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
1664 for unmatched in unclosed_delims.iter() {
1665 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
1666 "incorrect close delimiter: `{}`",
1667 pprust::token_kind_to_string(&token::CloseDelim(unmatched.found_delim)),
1669 err.span_label(unmatched.found_span, "incorrect close delimiter");
1670 if let Some(sp) = unmatched.candidate_span {
1671 err.span_label(sp, "close delimiter possibly meant for this");
1673 if let Some(sp) = unmatched.unclosed_span {
1674 err.span_label(sp, "un-closed delimiter");
1678 unclosed_delims.clear();