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, 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 /// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
61 /// Is `self` is allowed as the first parameter?
62 is_self_allowed: bool,
63 /// Is `...` allowed as the tail of the parameter list?
64 allow_c_variadic: bool,
65 /// `is_name_required` decides if, per-parameter,
66 /// the parameter must have a pattern or just a type.
67 is_name_required: fn(&token::Token) -> bool,
70 /// Like `maybe_whole_expr`, but for things other than expressions.
72 macro_rules! maybe_whole {
73 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
74 if let token::Interpolated(nt) = &$p.token.kind {
75 if let token::$constructor(x) = &**nt {
84 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
86 macro_rules! maybe_recover_from_interpolated_ty_qpath {
87 ($self: expr, $allow_qpath_recovery: expr) => {
88 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
89 if let token::Interpolated(nt) = &$self.token.kind {
90 if let token::NtTy(ty) = &**nt {
93 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
100 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
101 if let Some(ref mut rhs) = rhs {
107 #[derive(Debug, Clone, Copy, PartialEq)]
119 // NOTE: `Ident`s are handled by `common.rs`.
122 pub struct Parser<'a> {
123 pub sess: &'a ParseSess,
124 /// The current normalized token.
125 /// "Normalized" means that some interpolated tokens
126 /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced
127 /// with non-interpolated identifier and lifetime tokens they refer to.
128 /// Perhaps the normalized / non-normalized setup can be simplified somehow.
130 /// The span of the current non-normalized token.
131 meta_var_span: Option<Span>,
132 /// The span of the previous non-normalized token.
134 /// The kind of the previous normalized token (in simplified form).
135 prev_token_kind: PrevTokenKind,
136 restrictions: Restrictions,
137 /// Used to determine the path to externally loaded source files.
138 crate directory: Directory<'a>,
139 /// `true` to parse sub-modules in other files.
140 pub recurse_into_file_modules: bool,
141 /// Name of the root module this parser originated from. If `None`, then the
142 /// name is not known. This does not change while the parser is descending
143 /// into modules, and sub-parsers have new values for this name.
144 pub root_module_name: Option<String>,
145 crate expected_tokens: Vec<TokenType>,
146 token_cursor: TokenCursor,
147 desugar_doc_comments: bool,
148 /// `true` we should configure out of line modules as we parse.
150 /// This field is used to keep track of how many left angle brackets we have seen. This is
151 /// required in order to detect extra leading left angle brackets (`<` characters) and error
154 /// See the comments in the `parse_path_segment` function for more details.
155 crate unmatched_angle_bracket_count: u32,
156 crate max_angle_bracket_count: u32,
157 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
158 /// it gets removed from here. Every entry left at the end gets emitted as an independent
160 crate unclosed_delims: Vec<UnmatchedBrace>,
161 crate last_unexpected_token_span: Option<Span>,
162 crate last_type_ascription: Option<(Span, bool /* likely path typo */)>,
163 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
164 crate subparser_name: Option<&'static str>,
167 impl<'a> Drop for Parser<'a> {
169 let diag = self.diagnostic();
170 emit_unclosed_delims(&mut self.unclosed_delims, diag);
176 frame: TokenCursorFrame,
177 stack: Vec<TokenCursorFrame>,
181 struct TokenCursorFrame {
182 delim: token::DelimToken,
185 tree_cursor: tokenstream::Cursor,
187 last_token: LastToken,
190 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
191 /// by the parser, and then that's transitively used to record the tokens that
192 /// each parse AST item is created with.
194 /// Right now this has two states, either collecting tokens or not collecting
195 /// tokens. If we're collecting tokens we just save everything off into a local
196 /// `Vec`. This should eventually though likely save tokens from the original
197 /// token stream and just use slicing of token streams to avoid creation of a
198 /// whole new vector.
200 /// The second state is where we're passively not recording tokens, but the last
201 /// token is still tracked for when we want to start recording tokens. This
202 /// "last token" means that when we start recording tokens we'll want to ensure
203 /// that this, the first token, is included in the output.
205 /// You can find some more example usage of this in the `collect_tokens` method
208 crate enum LastToken {
209 Collecting(Vec<TreeAndJoint>),
210 Was(Option<TreeAndJoint>),
213 impl TokenCursorFrame {
214 fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
218 open_delim: delim == token::NoDelim,
219 tree_cursor: tts.clone().into_trees(),
220 close_delim: delim == token::NoDelim,
221 last_token: LastToken::Was(None),
227 fn next(&mut self) -> Token {
229 let tree = if !self.frame.open_delim {
230 self.frame.open_delim = true;
231 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
232 } else if let Some(tree) = self.frame.tree_cursor.next() {
234 } else if !self.frame.close_delim {
235 self.frame.close_delim = true;
236 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
237 } else if let Some(frame) = self.stack.pop() {
241 return Token::new(token::Eof, DUMMY_SP);
244 match self.frame.last_token {
245 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
246 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
250 TokenTree::Token(token) => return token,
251 TokenTree::Delimited(sp, delim, tts) => {
252 let frame = TokenCursorFrame::new(sp, delim, &tts);
253 self.stack.push(mem::replace(&mut self.frame, frame));
259 fn next_desugared(&mut self) -> Token {
260 let (name, sp) = match self.next() {
261 Token { kind: token::DocComment(name), span } => (name, span),
265 let stripped = strip_doc_comment_decoration(&name.as_str());
267 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
268 // required to wrap the text.
269 let mut num_of_hashes = 0;
271 for ch in stripped.chars() {
274 '#' if count > 0 => count + 1,
277 num_of_hashes = cmp::max(num_of_hashes, count);
280 let delim_span = DelimSpan::from_single(sp);
281 let body = TokenTree::Delimited(
285 TokenTree::token(token::Ident(sym::doc, false), sp),
286 TokenTree::token(token::Eq, sp),
287 TokenTree::token(TokenKind::lit(
288 token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None
291 .iter().cloned().collect::<TokenStream>().into(),
294 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
297 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
298 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
299 .iter().cloned().collect::<TokenStream>().into()
301 [TokenTree::token(token::Pound, sp), body]
302 .iter().cloned().collect::<TokenStream>().into()
310 #[derive(Clone, PartialEq)]
311 crate enum TokenType {
323 crate fn to_string(&self) -> String {
325 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
326 TokenType::Keyword(kw) => format!("`{}`", kw),
327 TokenType::Operator => "an operator".to_string(),
328 TokenType::Lifetime => "lifetime".to_string(),
329 TokenType::Ident => "identifier".to_string(),
330 TokenType::Path => "path".to_string(),
331 TokenType::Type => "type".to_string(),
332 TokenType::Const => "const".to_string(),
337 #[derive(Copy, Clone, Debug)]
338 crate enum TokenExpectType {
343 impl<'a> Parser<'a> {
347 directory: Option<Directory<'a>>,
348 recurse_into_file_modules: bool,
349 desugar_doc_comments: bool,
350 subparser_name: Option<&'static str>,
352 let mut parser = Parser {
354 token: Token::dummy(),
357 prev_token_kind: PrevTokenKind::Other,
358 restrictions: Restrictions::empty(),
359 recurse_into_file_modules,
360 directory: Directory {
361 path: Cow::from(PathBuf::new()),
362 ownership: DirectoryOwnership::Owned { relative: None }
364 root_module_name: None,
365 expected_tokens: Vec::new(),
366 token_cursor: TokenCursor {
367 frame: TokenCursorFrame::new(
374 desugar_doc_comments,
376 unmatched_angle_bracket_count: 0,
377 max_angle_bracket_count: 0,
378 unclosed_delims: Vec::new(),
379 last_unexpected_token_span: None,
380 last_type_ascription: None,
384 parser.token = parser.next_tok();
386 if let Some(directory) = directory {
387 parser.directory = directory;
388 } else if !parser.token.span.is_dummy() {
389 if let Some(FileName::Real(path)) =
390 &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path {
391 if let Some(directory_path) = path.parent() {
392 parser.directory.path = Cow::from(directory_path.to_path_buf());
397 parser.process_potential_macro_variable();
401 fn next_tok(&mut self) -> Token {
402 let mut next = if self.desugar_doc_comments {
403 self.token_cursor.next_desugared()
405 self.token_cursor.next()
407 if next.span.is_dummy() {
408 // Tweak the location for better diagnostics, but keep syntactic context intact.
409 next.span = self.prev_span.with_ctxt(next.span.ctxt());
414 /// Converts the current token to a string using `self`'s reader.
415 pub fn this_token_to_string(&self) -> String {
416 pprust::token_to_string(&self.token)
419 crate fn token_descr(&self) -> Option<&'static str> {
420 Some(match &self.token.kind {
421 _ if self.token.is_special_ident() => "reserved identifier",
422 _ if self.token.is_used_keyword() => "keyword",
423 _ if self.token.is_unused_keyword() => "reserved keyword",
424 token::DocComment(..) => "doc comment",
429 crate fn this_token_descr(&self) -> String {
430 if let Some(prefix) = self.token_descr() {
431 format!("{} `{}`", prefix, self.this_token_to_string())
433 format!("`{}`", self.this_token_to_string())
437 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
438 match self.expect_one_of(&[], &[]) {
440 Ok(_) => unreachable!(),
444 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
445 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
446 if self.expected_tokens.is_empty() {
447 if self.token == *t {
451 self.unexpected_try_recover(t)
454 self.expect_one_of(slice::from_ref(t), &[])
458 /// Expect next token to be edible or inedible token. If edible,
459 /// then consume it; if inedible, then return without consuming
460 /// anything. Signal a fatal error if next token is unexpected.
461 pub fn expect_one_of(
463 edible: &[TokenKind],
464 inedible: &[TokenKind],
465 ) -> PResult<'a, bool /* recovered */> {
466 if edible.contains(&self.token.kind) {
469 } else if inedible.contains(&self.token.kind) {
470 // leave it in the input
472 } else if self.last_unexpected_token_span == Some(self.token.span) {
475 self.expected_one_of_not_found(edible, inedible)
479 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
480 self.parse_ident_common(true)
483 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
484 match self.token.kind {
485 token::Ident(name, _) => {
486 if self.token.is_reserved_ident() {
487 let mut err = self.expected_ident_found();
494 let span = self.token.span;
496 Ok(Ident::new(name, span))
499 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
500 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
502 self.expected_ident_found()
508 /// Checks if the next token is `tok`, and returns `true` if so.
510 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
512 crate fn check(&mut self, tok: &TokenKind) -> bool {
513 let is_present = self.token == *tok;
514 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
518 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
519 pub fn eat(&mut self, tok: &TokenKind) -> bool {
520 let is_present = self.check(tok);
521 if is_present { self.bump() }
525 /// If the next token is the given keyword, returns `true` without eating it.
526 /// An expectation is also added for diagnostics purposes.
527 fn check_keyword(&mut self, kw: Symbol) -> bool {
528 self.expected_tokens.push(TokenType::Keyword(kw));
529 self.token.is_keyword(kw)
532 /// If the next token is the given keyword, eats it and returns `true`.
533 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
534 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
535 if self.check_keyword(kw) {
543 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
544 if self.token.is_keyword(kw) {
552 /// If the given word is not a keyword, signals an error.
553 /// If the next token is not the given word, signals an error.
554 /// Otherwise, eats it.
555 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
556 if !self.eat_keyword(kw) {
563 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
567 self.expected_tokens.push(typ);
572 crate fn check_ident(&mut self) -> bool {
573 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
576 fn check_path(&mut self) -> bool {
577 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
580 fn check_type(&mut self) -> bool {
581 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
584 fn check_const_arg(&mut self) -> bool {
585 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
588 /// Checks to see if the next token is either `+` or `+=`.
589 /// Otherwise returns `false`.
590 fn check_plus(&mut self) -> bool {
591 self.check_or_expected(
592 self.token.is_like_plus(),
593 TokenType::Token(token::BinOp(token::Plus)),
597 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
598 /// and continues. If a `+` is not seen, returns `false`.
600 /// This is used when token-splitting `+=` into `+`.
601 /// See issue #47856 for an example of when this may occur.
602 fn eat_plus(&mut self) -> bool {
603 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
604 match self.token.kind {
605 token::BinOp(token::Plus) => {
609 token::BinOpEq(token::Plus) => {
610 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
611 self.bump_with(token::Eq, span);
618 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
619 /// `&` and continues. If an `&` is not seen, signals an error.
620 fn expect_and(&mut self) -> PResult<'a, ()> {
621 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
622 match self.token.kind {
623 token::BinOp(token::And) => {
628 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
629 Ok(self.bump_with(token::BinOp(token::And), span))
631 _ => self.unexpected()
635 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
636 /// `|` and continues. If an `|` is not seen, signals an error.
637 fn expect_or(&mut self) -> PResult<'a, ()> {
638 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
639 match self.token.kind {
640 token::BinOp(token::Or) => {
645 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
646 Ok(self.bump_with(token::BinOp(token::Or), span))
648 _ => self.unexpected()
652 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
653 literal::expect_no_suffix(&self.sess.span_diagnostic, sp, kind, suffix)
656 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
657 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
658 /// and continue. If a `<` is not seen, returns false.
660 /// This is meant to be used when parsing generics on a path to get the
662 fn eat_lt(&mut self) -> bool {
663 self.expected_tokens.push(TokenType::Token(token::Lt));
664 let ate = match self.token.kind {
669 token::BinOp(token::Shl) => {
670 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
671 self.bump_with(token::Lt, span);
675 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
676 self.bump_with(token::BinOp(token::Minus), span);
683 // See doc comment for `unmatched_angle_bracket_count`.
684 self.unmatched_angle_bracket_count += 1;
685 self.max_angle_bracket_count += 1;
686 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
692 fn expect_lt(&mut self) -> PResult<'a, ()> {
700 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
701 /// with a single `>` and continues. If a `>` is not seen, signals an error.
702 fn expect_gt(&mut self) -> PResult<'a, ()> {
703 self.expected_tokens.push(TokenType::Token(token::Gt));
704 let ate = match self.token.kind {
709 token::BinOp(token::Shr) => {
710 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
711 Some(self.bump_with(token::Gt, span))
713 token::BinOpEq(token::Shr) => {
714 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
715 Some(self.bump_with(token::Ge, span))
718 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
719 Some(self.bump_with(token::Eq, span))
726 // See doc comment for `unmatched_angle_bracket_count`.
727 if self.unmatched_angle_bracket_count > 0 {
728 self.unmatched_angle_bracket_count -= 1;
729 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
734 None => self.unexpected(),
738 /// Parses a sequence, including the closing delimiter. The function
739 /// `f` must consume tokens until reaching the next separator or
741 pub fn parse_seq_to_end<T>(
745 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
746 ) -> PResult<'a, Vec<T>> {
747 let (val, _, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
754 /// Parses a sequence, not including the closing delimiter. The function
755 /// `f` must consume tokens until reaching the next separator or
757 pub fn parse_seq_to_before_end<T>(
761 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
762 ) -> PResult<'a, (Vec<T>, bool, bool)> {
763 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
766 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
767 kets.iter().any(|k| {
769 TokenExpectType::Expect => self.check(k),
770 TokenExpectType::NoExpect => self.token == **k,
775 crate fn parse_seq_to_before_tokens<T>(
779 expect: TokenExpectType,
780 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
781 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
782 let mut first = true;
783 let mut recovered = false;
784 let mut trailing = false;
786 while !self.expect_any_with_type(kets, expect) {
787 if let token::CloseDelim(..) | token::Eof = self.token.kind {
790 if let Some(ref t) = sep.sep {
794 match self.expect(t) {
801 // Attempt to keep parsing if it was a similar separator.
802 if let Some(ref tokens) = t.similar_tokens() {
803 if tokens.contains(&self.token.kind) {
808 // Attempt to keep parsing if it was an omitted separator.
823 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
832 Ok((v, trailing, recovered))
835 /// Parses a sequence, including the closing delimiter. The function
836 /// `f` must consume tokens until reaching the next separator or
838 fn parse_unspanned_seq<T>(
843 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
844 ) -> PResult<'a, (Vec<T>, bool)> {
846 let (result, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
850 Ok((result, trailing))
853 fn parse_delim_comma_seq<T>(
856 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
857 ) -> PResult<'a, (Vec<T>, bool)> {
858 self.parse_unspanned_seq(
859 &token::OpenDelim(delim),
860 &token::CloseDelim(delim),
861 SeqSep::trailing_allowed(token::Comma),
866 fn parse_paren_comma_seq<T>(
868 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
869 ) -> PResult<'a, (Vec<T>, bool)> {
870 self.parse_delim_comma_seq(token::Paren, f)
873 /// Advance the parser by one token.
874 pub fn bump(&mut self) {
875 if self.prev_token_kind == PrevTokenKind::Eof {
876 // Bumping after EOF is a bad sign, usually an infinite loop.
877 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
880 self.prev_span = self.meta_var_span.take().unwrap_or(self.token.span);
882 // Record last token kind for possible error recovery.
883 self.prev_token_kind = match self.token.kind {
884 token::DocComment(..) => PrevTokenKind::DocComment,
885 token::Comma => PrevTokenKind::Comma,
886 token::BinOp(token::Plus) => PrevTokenKind::Plus,
887 token::BinOp(token::Or) => PrevTokenKind::BitOr,
888 token::Interpolated(..) => PrevTokenKind::Interpolated,
889 token::Eof => PrevTokenKind::Eof,
890 token::Ident(..) => PrevTokenKind::Ident,
891 _ => PrevTokenKind::Other,
894 self.token = self.next_tok();
895 self.expected_tokens.clear();
896 // Check after each token.
897 self.process_potential_macro_variable();
900 /// Advances the parser using provided token as a next one. Use this when
901 /// consuming a part of a token. For example a single `<` from `<<`.
902 fn bump_with(&mut self, next: TokenKind, span: Span) {
903 self.prev_span = self.token.span.with_hi(span.lo());
904 // It would be incorrect to record the kind of the current token, but
905 // fortunately for tokens currently using `bump_with`, the
906 // `prev_token_kind` will be of no use anyway.
907 self.prev_token_kind = PrevTokenKind::Other;
908 self.token = Token::new(next, span);
909 self.expected_tokens.clear();
912 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
913 /// When `dist == 0` then the current token is looked at.
914 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
916 return looker(&self.token);
919 let frame = &self.token_cursor.frame;
920 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
921 Some(tree) => match tree {
922 TokenTree::Token(token) => token,
923 TokenTree::Delimited(dspan, delim, _) =>
924 Token::new(token::OpenDelim(delim), dspan.open),
926 None => Token::new(token::CloseDelim(frame.delim), frame.span.close)
930 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
931 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
932 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
935 /// Parses asyncness: `async` or nothing.
936 fn parse_asyncness(&mut self) -> IsAsync {
937 if self.eat_keyword(kw::Async) {
939 closure_id: DUMMY_NODE_ID,
940 return_impl_trait_id: DUMMY_NODE_ID,
947 /// Parses unsafety: `unsafe` or nothing.
948 fn parse_unsafety(&mut self) -> Unsafety {
949 if self.eat_keyword(kw::Unsafe) {
956 /// Parses mutability (`mut` or nothing).
957 fn parse_mutability(&mut self) -> Mutability {
958 if self.eat_keyword(kw::Mut) {
961 Mutability::Immutable
965 /// Possibly parses mutability (`const` or `mut`).
966 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
967 if self.eat_keyword(kw::Mut) {
968 Some(Mutability::Mutable)
969 } else if self.eat_keyword(kw::Const) {
970 Some(Mutability::Immutable)
976 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
977 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
979 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
981 Ok(Ident::new(symbol, self.prev_span))
983 self.parse_ident_common(false)
987 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
988 let delim = match self.token.kind {
989 token::OpenDelim(delim) => delim,
991 let msg = "expected open delimiter";
992 let mut err = self.fatal(msg);
993 err.span_label(self.token.span, msg);
997 let tts = match self.parse_token_tree() {
998 TokenTree::Delimited(_, _, tts) => tts,
1001 let delim = match delim {
1002 token::Paren => MacDelimiter::Parenthesis,
1003 token::Bracket => MacDelimiter::Bracket,
1004 token::Brace => MacDelimiter::Brace,
1005 token::NoDelim => self.bug("unexpected no delimiter"),
1007 Ok((delim, tts.into()))
1010 fn parse_or_use_outer_attributes(
1012 already_parsed_attrs: Option<ThinVec<Attribute>>,
1013 ) -> PResult<'a, ThinVec<Attribute>> {
1014 if let Some(attrs) = already_parsed_attrs {
1017 self.parse_outer_attributes().map(|a| a.into())
1021 crate fn process_potential_macro_variable(&mut self) {
1022 self.token = match self.token.kind {
1023 token::Dollar if self.token.span.from_expansion() &&
1024 self.look_ahead(1, |t| t.is_ident()) => {
1026 let name = match self.token.kind {
1027 token::Ident(name, _) => name,
1030 let span = self.prev_span.to(self.token.span);
1032 .struct_span_fatal(span, &format!("unknown macro variable `{}`", name))
1033 .span_label(span, "unknown macro variable")
1038 token::Interpolated(ref nt) => {
1039 self.meta_var_span = Some(self.token.span);
1040 // Interpolated identifier and lifetime tokens are replaced with usual identifier
1041 // and lifetime tokens, so the former are never encountered during normal parsing.
1043 token::NtIdent(ident, is_raw) =>
1044 Token::new(token::Ident(ident.name, is_raw), ident.span),
1045 token::NtLifetime(ident) =>
1046 Token::new(token::Lifetime(ident.name), ident.span),
1054 /// Parses a single token tree from the input.
1055 crate fn parse_token_tree(&mut self) -> TokenTree {
1056 match self.token.kind {
1057 token::OpenDelim(..) => {
1058 let frame = mem::replace(&mut self.token_cursor.frame,
1059 self.token_cursor.stack.pop().unwrap());
1060 self.token.span = frame.span.entire();
1062 TokenTree::Delimited(
1065 frame.tree_cursor.stream.into(),
1068 token::CloseDelim(_) | token::Eof => unreachable!(),
1070 let token = self.token.take();
1072 TokenTree::Token(token)
1077 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1078 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1079 let mut tts = Vec::new();
1080 while self.token != token::Eof {
1081 tts.push(self.parse_token_tree());
1086 pub fn parse_tokens(&mut self) -> TokenStream {
1087 let mut result = Vec::new();
1089 match self.token.kind {
1090 token::Eof | token::CloseDelim(..) => break,
1091 _ => result.push(self.parse_token_tree().into()),
1094 TokenStream::new(result)
1097 /// Evaluates the closure with restrictions in place.
1099 /// Afters the closure is evaluated, restrictions are reset.
1100 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1101 let old = self.restrictions;
1102 self.restrictions = res;
1104 self.restrictions = old;
1108 /// Parses the parameter list of a function, including the `(` and `)` delimiters.
1109 fn parse_fn_params(&mut self, mut cfg: ParamCfg) -> PResult<'a, Vec<Param>> {
1110 let sp = self.token.span;
1111 let is_trait_item = cfg.is_self_allowed;
1112 let mut c_variadic = false;
1113 // Parse the arguments, starting out with `self` being possibly allowed...
1114 let (params, _) = self.parse_paren_comma_seq(|p| {
1115 let param = p.parse_param_general(&cfg, is_trait_item);
1116 // ...now that we've parsed the first argument, `self` is no longer allowed.
1117 cfg.is_self_allowed = false;
1121 if let TyKind::CVarArgs = param.ty.kind {
1123 if p.token != token::CloseDelim(token::Paren) {
1126 "`...` must be the last argument of a C-variadic function",
1128 // FIXME(eddyb) this should probably still push `CVarArgs`.
1129 // Maybe AST validation/HIR lowering should emit the above error?
1140 let lo = p.prev_span;
1141 // Skip every token until next possible arg or end.
1142 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1143 // Create a placeholder argument for proper arg count (issue #34264).
1144 let span = lo.to(p.prev_span);
1145 Ok(Some(dummy_arg(Ident::new(kw::Invalid, span))))
1150 let mut params: Vec<_> = params.into_iter().filter_map(|x| x).collect();
1152 // Replace duplicated recovered params with `_` pattern to avoid unecessary errors.
1153 self.deduplicate_recovered_params_names(&mut params);
1155 if c_variadic && params.len() <= 1 {
1158 "C-variadic function must be declared with at least one named argument",
1165 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1167 /// This version of parse param doesn't necessarily require identifier names.
1168 fn parse_param_general(&mut self, cfg: &ParamCfg, is_trait_item: bool) -> PResult<'a, Param> {
1169 let lo = self.token.span;
1170 let attrs = self.parse_outer_attributes()?;
1172 // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
1173 if let Some(mut param) = self.parse_self_param()? {
1174 param.attrs = attrs.into();
1175 return if cfg.is_self_allowed {
1178 self.recover_bad_self_param(param, is_trait_item)
1182 let is_name_required = match self.token.kind {
1183 token::DotDotDot => false,
1184 _ => (cfg.is_name_required)(&self.token),
1186 let (pat, ty) = if is_name_required || self.is_named_param() {
1187 debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
1189 let pat = self.parse_fn_param_pat()?;
1190 if let Err(mut err) = self.expect(&token::Colon) {
1191 return if let Some(ident) = self.parameter_without_type(
1195 cfg.is_self_allowed,
1199 Ok(dummy_arg(ident))
1205 self.eat_incorrect_doc_comment_for_param_type();
1206 (pat, self.parse_ty_common(true, true, cfg.allow_c_variadic)?)
1208 debug!("parse_param_general ident_to_pat");
1209 let parser_snapshot_before_ty = self.clone();
1210 self.eat_incorrect_doc_comment_for_param_type();
1211 let mut ty = self.parse_ty_common(true, true, cfg.allow_c_variadic);
1212 if ty.is_ok() && self.token != token::Comma &&
1213 self.token != token::CloseDelim(token::Paren) {
1214 // This wasn't actually a type, but a pattern looking like a type,
1215 // so we are going to rollback and re-parse for recovery.
1216 ty = self.unexpected();
1220 let ident = Ident::new(kw::Invalid, self.prev_span);
1221 let bm = BindingMode::ByValue(Mutability::Immutable);
1222 let pat = self.mk_pat_ident(ty.span, bm, ident);
1225 // If this is a C-variadic argument and we hit an error, return the error.
1226 Err(err) if self.token == token::DotDotDot => return Err(err),
1227 // Recover from attempting to parse the argument as a type without pattern.
1230 mem::replace(self, parser_snapshot_before_ty);
1231 self.recover_arg_parse()?
1236 let span = lo.to(self.token.span);
1239 attrs: attrs.into(),
1240 id: ast::DUMMY_NODE_ID,
1241 is_placeholder: false,
1248 /// Returns the parsed optional self parameter and whether a self shortcut was used.
1250 /// See `parse_self_param_with_attrs` to collect attributes.
1251 fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1252 // Extract an identifier *after* having confirmed that the token is one.
1253 let expect_self_ident = |this: &mut Self| {
1254 match this.token.kind {
1255 // Preserve hygienic context.
1256 token::Ident(name, _) => {
1257 let span = this.token.span;
1259 Ident::new(name, span)
1261 _ => unreachable!(),
1264 // Is `self` `n` tokens ahead?
1265 let is_isolated_self = |this: &Self, n| {
1266 this.is_keyword_ahead(n, &[kw::SelfLower])
1267 && this.look_ahead(n + 1, |t| t != &token::ModSep)
1269 // Is `mut self` `n` tokens ahead?
1270 let is_isolated_mut_self = |this: &Self, n| {
1271 this.is_keyword_ahead(n, &[kw::Mut])
1272 && is_isolated_self(this, n + 1)
1274 // Parse `self` or `self: TYPE`. We already know the current token is `self`.
1275 let parse_self_possibly_typed = |this: &mut Self, m| {
1276 let eself_ident = expect_self_ident(this);
1277 let eself_hi = this.prev_span;
1278 let eself = if this.eat(&token::Colon) {
1279 SelfKind::Explicit(this.parse_ty()?, m)
1283 Ok((eself, eself_ident, eself_hi))
1285 // Recover for the grammar `*self`, `*const self`, and `*mut self`.
1286 let recover_self_ptr = |this: &mut Self| {
1287 let msg = "cannot pass `self` by raw pointer";
1288 let span = this.token.span;
1289 this.struct_span_err(span, msg)
1290 .span_label(span, msg)
1293 Ok((SelfKind::Value(Mutability::Immutable), expect_self_ident(this), this.prev_span))
1296 // Parse optional `self` parameter of a method.
1297 // Only a limited set of initial token sequences is considered `self` parameters; anything
1298 // else is parsed as a normal function parameter list, so some lookahead is required.
1299 let eself_lo = self.token.span;
1300 let (eself, eself_ident, eself_hi) = match self.token.kind {
1301 token::BinOp(token::And) => {
1302 let eself = if is_isolated_self(self, 1) {
1305 SelfKind::Region(None, Mutability::Immutable)
1306 } else if is_isolated_mut_self(self, 1) {
1310 SelfKind::Region(None, Mutability::Mutable)
1311 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_self(self, 2) {
1314 let lt = self.expect_lifetime();
1315 SelfKind::Region(Some(lt), Mutability::Immutable)
1316 } else if self.look_ahead(1, |t| t.is_lifetime()) && is_isolated_mut_self(self, 2) {
1319 let lt = self.expect_lifetime();
1321 SelfKind::Region(Some(lt), Mutability::Mutable)
1326 (eself, expect_self_ident(self), self.prev_span)
1329 token::BinOp(token::Star) if is_isolated_self(self, 1) => {
1331 recover_self_ptr(self)?
1333 // `*mut self` and `*const self`
1334 token::BinOp(token::Star) if
1335 self.look_ahead(1, |t| t.is_mutability())
1336 && is_isolated_self(self, 2) =>
1340 recover_self_ptr(self)?
1342 // `self` and `self: TYPE`
1343 token::Ident(..) if is_isolated_self(self, 0) => {
1344 parse_self_possibly_typed(self, Mutability::Immutable)?
1346 // `mut self` and `mut self: TYPE`
1347 token::Ident(..) if is_isolated_mut_self(self, 0) => {
1349 parse_self_possibly_typed(self, Mutability::Mutable)?
1351 _ => return Ok(None),
1354 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1355 Ok(Some(Param::from_self(ThinVec::default(), eself, eself_ident)))
1358 fn is_named_param(&self) -> bool {
1359 let offset = match self.token.kind {
1360 token::Interpolated(ref nt) => match **nt {
1361 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1364 token::BinOp(token::And) | token::AndAnd => 1,
1365 _ if self.token.is_keyword(kw::Mut) => 1,
1369 self.look_ahead(offset, |t| t.is_ident()) &&
1370 self.look_ahead(offset + 1, |t| t == &token::Colon)
1373 fn is_crate_vis(&self) -> bool {
1374 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1377 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1378 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1379 /// If the following element can't be a tuple (i.e., it's a function definition), then
1380 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1381 /// so emit a proper diagnostic.
1382 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
1383 maybe_whole!(self, NtVis, |x| x);
1385 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1386 if self.is_crate_vis() {
1387 self.bump(); // `crate`
1388 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1391 if !self.eat_keyword(kw::Pub) {
1392 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1393 // keyword to grab a span from for inherited visibility; an empty span at the
1394 // beginning of the current token would seem to be the "Schelling span".
1395 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited))
1397 let lo = self.prev_span;
1399 if self.check(&token::OpenDelim(token::Paren)) {
1400 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1401 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1402 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1403 // by the following tokens.
1404 if self.is_keyword_ahead(1, &[kw::Crate])
1405 && self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
1407 // Parse `pub(crate)`.
1409 self.bump(); // `crate`
1410 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1411 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1412 return Ok(respan(lo.to(self.prev_span), vis));
1413 } else if self.is_keyword_ahead(1, &[kw::In]) {
1414 // Parse `pub(in path)`.
1416 self.bump(); // `in`
1417 let path = self.parse_path(PathStyle::Mod)?; // `path`
1418 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1419 let vis = VisibilityKind::Restricted {
1421 id: ast::DUMMY_NODE_ID,
1423 return Ok(respan(lo.to(self.prev_span), vis));
1424 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1425 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1427 // Parse `pub(self)` or `pub(super)`.
1429 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1430 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1431 let vis = VisibilityKind::Restricted {
1433 id: ast::DUMMY_NODE_ID,
1435 return Ok(respan(lo.to(self.prev_span), vis));
1436 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct.
1437 self.recover_incorrect_vis_restriction()?;
1438 // Emit diagnostic, but continue with public visibility.
1442 Ok(respan(lo, VisibilityKind::Public))
1445 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1446 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1448 let path = self.parse_path(PathStyle::Mod)?;
1449 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1451 let msg = "incorrect visibility restriction";
1452 let suggestion = r##"some possible visibility restrictions are:
1453 `pub(crate)`: visible only on the current crate
1454 `pub(super)`: visible only in the current module's parent
1455 `pub(in path::to::module)`: visible only on the specified path"##;
1457 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1461 &format!("make this visible only to module `{}` with `in`", path),
1462 format!("in {}", path),
1463 Applicability::MachineApplicable,
1470 /// Parses `extern` followed by an optional ABI string, or nothing.
1471 fn parse_extern_abi(&mut self) -> PResult<'a, Abi> {
1472 if self.eat_keyword(kw::Extern) {
1473 Ok(self.parse_opt_abi()?.unwrap_or(Abi::C))
1479 /// Parses a string as an ABI spec on an extern type or module. Consumes
1480 /// the `extern` keyword, if one is found.
1481 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
1482 match self.token.kind {
1483 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
1484 token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
1485 self.expect_no_suffix(self.token.span, "an ABI spec", suffix);
1487 match abi::lookup(&symbol.as_str()) {
1488 Some(abi) => Ok(Some(abi)),
1490 self.error_on_invalid_abi(symbol);
1499 /// Emit an error where `symbol` is an invalid ABI.
1500 fn error_on_invalid_abi(&self, symbol: Symbol) {
1501 let prev_span = self.prev_span;
1503 self.sess.span_diagnostic,
1506 "invalid ABI: found `{}`",
1509 .span_label(prev_span, "invalid ABI")
1510 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1514 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1515 fn ban_async_in_2015(&self, async_span: Span) {
1516 if async_span.rust_2015() {
1518 .struct_span_err_with_code(
1520 "`async fn` is not permitted in the 2015 edition",
1521 DiagnosticId::Error("E0670".into())
1527 fn collect_tokens<R>(
1529 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1530 ) -> PResult<'a, (R, TokenStream)> {
1531 // Record all tokens we parse when parsing this item.
1532 let mut tokens = Vec::new();
1533 let prev_collecting = match self.token_cursor.frame.last_token {
1534 LastToken::Collecting(ref mut list) => {
1535 Some(mem::take(list))
1537 LastToken::Was(ref mut last) => {
1538 tokens.extend(last.take());
1542 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1543 let prev = self.token_cursor.stack.len();
1545 let last_token = if self.token_cursor.stack.len() == prev {
1546 &mut self.token_cursor.frame.last_token
1547 } else if self.token_cursor.stack.get(prev).is_none() {
1548 // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1549 // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1551 return Ok((ret?, TokenStream::new(vec![])));
1553 &mut self.token_cursor.stack[prev].last_token
1556 // Pull out the tokens that we've collected from the call to `f` above.
1557 let mut collected_tokens = match *last_token {
1558 LastToken::Collecting(ref mut v) => mem::take(v),
1559 LastToken::Was(ref was) => {
1560 let msg = format!("our vector went away? - found Was({:?})", was);
1561 debug!("collect_tokens: {}", msg);
1562 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1563 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1564 // with mismatched delimiters *and* recovery lookahead on the likely typo
1565 // `pub ident(` (#62895, different but similar to the case above).
1566 return Ok((ret?, TokenStream::new(vec![])));
1570 // If we're not at EOF our current token wasn't actually consumed by
1571 // `f`, but it'll still be in our list that we pulled out. In that case
1573 let extra_token = if self.token != token::Eof {
1574 collected_tokens.pop()
1579 // If we were previously collecting tokens, then this was a recursive
1580 // call. In that case we need to record all the tokens we collected in
1581 // our parent list as well. To do that we push a clone of our stream
1582 // onto the previous list.
1583 match prev_collecting {
1585 list.extend(collected_tokens.iter().cloned());
1586 list.extend(extra_token);
1587 *last_token = LastToken::Collecting(list);
1590 *last_token = LastToken::Was(extra_token);
1594 Ok((ret?, TokenStream::new(collected_tokens)))
1598 fn is_import_coupler(&mut self) -> bool {
1599 self.check(&token::ModSep) &&
1600 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
1601 *t == token::BinOp(token::Star))
1604 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
1605 let ret = match self.token.kind {
1606 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
1607 (symbol, ast::StrStyle::Cooked, suffix),
1608 token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
1609 (symbol, ast::StrStyle::Raw(n), suffix),
1616 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
1617 match self.parse_optional_str() {
1618 Some((s, style, suf)) => {
1619 let sp = self.prev_span;
1620 self.expect_no_suffix(sp, "a string literal", suf);
1624 let msg = "expected string literal";
1625 let mut err = self.fatal(msg);
1626 err.span_label(self.token.span, msg);
1632 fn report_invalid_macro_expansion_item(&self) {
1633 self.struct_span_err(
1635 "macros that expand to items must be delimited with braces or followed by a semicolon",
1636 ).multipart_suggestion(
1637 "change the delimiters to curly braces",
1639 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
1640 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
1642 Applicability::MaybeIncorrect,
1644 self.sess.source_map.next_point(self.prev_span),
1647 Applicability::MaybeIncorrect,
1652 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
1653 for unmatched in unclosed_delims.iter() {
1654 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
1655 "incorrect close delimiter: `{}`",
1656 pprust::token_kind_to_string(&token::CloseDelim(unmatched.found_delim)),
1658 err.span_label(unmatched.found_span, "incorrect close delimiter");
1659 if let Some(sp) = unmatched.candidate_span {
1660 err.span_label(sp, "close delimiter possibly meant for this");
1662 if let Some(sp) = unmatched.unclosed_span {
1663 err.span_label(sp, "un-closed delimiter");
1667 unclosed_delims.clear();