2 pub use Nonterminal::*;
7 use crate::ast::{self};
8 use crate::parse::ParseSess;
9 use crate::print::pprust;
11 use crate::symbol::kw;
12 use crate::syntax::parse::parse_stream_from_source_str;
13 use crate::tokenstream::{self, DelimSpan, TokenStream, TokenTree};
15 use syntax_pos::symbol::Symbol;
16 use syntax_pos::{self, Span, FileName, DUMMY_SP};
22 #[cfg(target_arch = "x86_64")]
23 use rustc_data_structures::static_assert_size;
24 use rustc_data_structures::sync::Lrc;
26 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
40 /// A delimiter token.
41 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
43 /// A round parenthesis (i.e., `(` or `)`).
45 /// A square bracket (i.e., `[` or `]`).
47 /// A curly brace (i.e., `{` or `}`).
49 /// An empty delimiter.
54 pub fn len(self) -> usize {
55 if self == NoDelim { 0 } else { 1 }
58 pub fn is_empty(self) -> bool {
63 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
65 Bool, // AST only, must never appear in a `Token`
71 StrRaw(u16), // raw string delimited by `n` hash symbols
73 ByteStrRaw(u16), // raw byte string delimited by `n` hash symbols
78 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
82 pub suffix: Option<Symbol>,
86 /// An English article for the literal token kind.
87 crate fn article(self) -> &'static str {
89 Integer | Err => "an",
94 crate fn descr(self) -> &'static str {
96 Bool => panic!("literal token contains `Lit::Bool`"),
101 Str | StrRaw(..) => "string",
102 ByteStr | ByteStrRaw(..) => "byte string",
107 crate fn may_have_suffix(self) -> bool {
109 Integer | Float | Err => true,
116 pub fn new(kind: LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Lit {
117 Lit { kind, symbol, suffix }
121 pub(crate) fn ident_can_begin_expr(name: ast::Name, span: Span, is_raw: bool) -> bool {
122 let ident_token = Token::new(Ident(name, is_raw), span);
124 !ident_token.is_reserved_ident() ||
125 ident_token.is_path_segment_keyword() ||
129 // FIXME: remove when `await!(..)` syntax is removed
130 // https://github.com/rust-lang/rust/issues/60610
152 fn ident_can_begin_type(name: ast::Name, span: Span, is_raw: bool) -> bool {
153 let ident_token = Token::new(Ident(name, is_raw), span);
155 !ident_token.is_reserved_ident() ||
156 ident_token.is_path_segment_keyword() ||
169 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
171 /* Expression-operator symbols. */
186 /* Structural symbols */
202 /// Used by proc macros for representing lifetimes, not generated by lexer right now.
204 /// An opening delimiter (e.g., `{`).
205 OpenDelim(DelimToken),
206 /// A closing delimiter (e.g., `}`).
207 CloseDelim(DelimToken),
212 /* Name components */
213 Ident(ast::Name, /* is_raw */ bool),
216 Interpolated(Lrc<Nonterminal>),
218 // Can be expanded into several tokens.
220 DocComment(ast::Name),
222 // Junk. These carry no data because we don't really care about the data
223 // they *would* carry, and don't really want to allocate a new ident for
224 // them. Instead, users could extract that from the associated span.
235 // `TokenKind` is used a lot. Make sure it doesn't unintentionally get bigger.
236 #[cfg(target_arch = "x86_64")]
237 static_assert_size!(TokenKind, 16);
239 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
246 /// Recovers a `TokenKind` from an `ast::Ident`. This creates a raw identifier if necessary.
247 pub fn from_ast_ident(ident: ast::Ident) -> TokenKind {
248 Ident(ident.name, ident.is_raw_guess())
251 crate fn is_like_plus(&self) -> bool {
253 BinOp(Plus) | BinOpEq(Plus) => true,
260 /// Returns `true` if the token can appear at the start of an expression.
261 crate fn can_begin_expr(&self) -> bool {
263 Ident(name, is_raw) =>
264 ident_can_begin_expr(name, self.span, is_raw), // value name or keyword
265 OpenDelim(..) | // tuple, array or block
266 Literal(..) | // literal
267 Not | // operator not
268 BinOp(Minus) | // unary minus
269 BinOp(Star) | // dereference
270 BinOp(Or) | OrOr | // closure
271 BinOp(And) | // reference
272 AndAnd | // double reference
273 // DotDotDot is no longer supported, but we need some way to display the error
274 DotDot | DotDotDot | DotDotEq | // range notation
275 Lt | BinOp(Shl) | // associated path
276 ModSep | // global path
277 Lifetime(..) | // labeled loop
278 Pound => true, // expression attributes
279 Interpolated(ref nt) => match **nt {
285 NtLifetime(..) => true,
292 /// Returns `true` if the token can appear at the start of a type.
293 crate fn can_begin_type(&self) -> bool {
295 Ident(name, is_raw) =>
296 ident_can_begin_type(name, self.span, is_raw), // type name or keyword
297 OpenDelim(Paren) | // tuple
298 OpenDelim(Bracket) | // array
300 BinOp(Star) | // raw pointer
301 BinOp(And) | // reference
302 AndAnd | // double reference
303 Question | // maybe bound in trait object
304 Lifetime(..) | // lifetime bound in trait object
305 Lt | BinOp(Shl) | // associated path
306 ModSep => true, // global path
307 Interpolated(ref nt) => match **nt {
308 NtIdent(..) | NtTy(..) | NtPath(..) | NtLifetime(..) => true,
317 /// Returns `true` if the token can appear at the start of a const param.
318 pub fn can_begin_const_arg(&self) -> bool {
320 OpenDelim(Brace) => true,
321 Interpolated(ref nt) => match **nt {
324 NtLiteral(..) => true,
327 _ => self.can_begin_literal_or_bool(),
333 /// Returns `true` if the token can appear at the start of a generic bound.
334 crate fn can_begin_bound(&self) -> bool {
335 self.is_path_start() || self.is_lifetime() || self.is_keyword(kw::For) ||
336 self == &Question || self == &OpenDelim(Paren)
341 pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option<Symbol>) -> TokenKind {
342 Literal(Lit::new(kind, symbol, suffix))
345 /// Returns `true` if the token is any literal
346 crate fn is_lit(&self) -> bool {
353 crate fn expect_lit(&self) -> Lit {
356 _=> panic!("`expect_lit` called on non-literal"),
360 /// Returns `true` if the token is any literal, a minus (which can prefix a literal,
361 /// for example a '-42', or one of the boolean idents).
362 crate fn can_begin_literal_or_bool(&self) -> bool {
365 BinOp(Minus) => true,
366 Ident(name, false) if name == kw::True => true,
367 Ident(name, false) if name == kw::False => true,
368 Interpolated(ref nt) => match **nt {
369 NtLiteral(..) => true,
378 /// Returns an identifier if this token is an identifier.
379 pub fn ident(&self) -> Option<(ast::Ident, /* is_raw */ bool)> {
381 Ident(name, is_raw) => Some((ast::Ident::new(name, self.span), is_raw)),
382 Interpolated(ref nt) => match **nt {
383 NtIdent(ident, is_raw) => Some((ident, is_raw)),
390 /// Returns a lifetime identifier if this token is a lifetime.
391 pub fn lifetime(&self) -> Option<ast::Ident> {
393 Lifetime(name) => Some(ast::Ident::new(name, self.span)),
394 Interpolated(ref nt) => match **nt {
395 NtLifetime(ident) => Some(ident),
404 /// Returns an identifier name if this token is an identifier.
405 pub fn ident_name(&self) -> Option<(ast::Name, /* is_raw */ bool)> {
407 Ident(name, is_raw) => Some((name, is_raw)),
408 Interpolated(ref nt) => match **nt {
409 NtIdent(ident, is_raw) => Some((ident.name, is_raw)),
415 /// Returns a lifetime name if this token is a lifetime.
416 pub fn lifetime_name(&self) -> Option<ast::Name> {
418 Lifetime(name) => Some(name),
419 Interpolated(ref nt) => match **nt {
420 NtLifetime(ident) => Some(ident.name),
426 /// Returns `true` if the token is an identifier.
427 pub fn is_ident(&self) -> bool {
428 self.ident_name().is_some()
430 /// Returns `true` if the token is a lifetime.
431 crate fn is_lifetime(&self) -> bool {
432 self.lifetime_name().is_some()
435 /// Returns `true` if the token is a identifier whose name is the given
437 crate fn is_ident_named(&self, name: Symbol) -> bool {
438 self.ident_name().map_or(false, |(ident_name, _)| ident_name == name)
441 /// Returns `true` if the token is an interpolated path.
442 fn is_path(&self) -> bool {
443 if let Interpolated(ref nt) = *self {
444 if let NtPath(..) = **nt {
451 /// Returns `true` if the token is either the `mut` or `const` keyword.
452 crate fn is_mutability(&self) -> bool {
453 self.is_keyword(kw::Mut) ||
454 self.is_keyword(kw::Const)
457 crate fn is_qpath_start(&self) -> bool {
458 self == &Lt || self == &BinOp(Shl)
463 crate fn is_path_start(&self) -> bool {
464 self == &ModSep || self.is_qpath_start() || self.is_path() ||
465 self.is_path_segment_keyword() || self.is_ident() && !self.is_reserved_ident()
470 /// Returns `true` if the token is a given keyword, `kw`.
471 pub fn is_keyword(&self, kw: Symbol) -> bool {
472 self.ident_name().map(|(name, is_raw)| name == kw && !is_raw).unwrap_or(false)
475 pub fn is_path_segment_keyword(&self) -> bool {
476 match self.ident_name() {
477 Some((name, false)) => name.is_path_segment_keyword(),
484 // Returns true for reserved identifiers used internally for elided lifetimes,
485 // unnamed method parameters, crate root module, error recovery etc.
486 pub fn is_special_ident(&self) -> bool {
488 Some((id, false)) => id.is_special(),
493 /// Returns `true` if the token is a keyword used in the language.
494 crate fn is_used_keyword(&self) -> bool {
496 Some((id, false)) => id.is_used_keyword(),
501 /// Returns `true` if the token is a keyword reserved for possible future use.
502 crate fn is_unused_keyword(&self) -> bool {
504 Some((id, false)) => id.is_unused_keyword(),
509 /// Returns `true` if the token is either a special identifier or a keyword.
510 pub fn is_reserved_ident(&self) -> bool {
512 Some((id, false)) => id.is_reserved(),
519 crate fn glue(self, joint: TokenKind) -> Option<TokenKind> {
530 BinOp(Minus) => LArrow,
543 BinOp(op) => match joint {
545 BinOp(And) if op == And => AndAnd,
546 BinOp(Or) if op == Or => OrOr,
547 Gt if op == Minus => RArrow,
555 DotDot => match joint {
560 Colon => match joint {
564 SingleQuote => match joint {
565 Ident(name, false) => Lifetime(Symbol::intern(&format!("'{}", name))),
569 Le | EqEq | Ne | Ge | AndAnd | OrOr | Tilde | BinOpEq(..) | At | DotDotDot |
570 DotDotEq | Comma | Semi | ModSep | RArrow | LArrow | FatArrow | Pound | Dollar |
571 Question | OpenDelim(..) | CloseDelim(..) |
572 Literal(..) | Ident(..) | Lifetime(..) | Interpolated(..) | DocComment(..) |
573 Whitespace | Comment | Shebang(..) | Eof => return None,
577 /// Returns tokens that are likely to be typed accidentally instead of the current token.
578 /// Enables better error recovery when the wrong token is found.
579 crate fn similar_tokens(&self) -> Option<Vec<TokenKind>> {
581 Comma => Some(vec![Dot, Lt, Semi]),
582 Semi => Some(vec![Colon, Comma]),
587 // See comments in `Nonterminal::to_tokenstream` for why we care about
588 // *probably* equal here rather than actual equality
589 crate fn probably_equal_for_proc_macro(&self, other: &TokenKind) -> bool {
590 if mem::discriminant(self) != mem::discriminant(other) {
593 match (self, other) {
608 (&DotDotDot, &DotDotDot) |
609 (&DotDotEq, &DotDotEq) |
616 (&FatArrow, &FatArrow) |
619 (&Question, &Question) |
620 (&Whitespace, &Whitespace) |
621 (&Comment, &Comment) |
622 (&Eof, &Eof) => true,
624 (&BinOp(a), &BinOp(b)) |
625 (&BinOpEq(a), &BinOpEq(b)) => a == b,
627 (&OpenDelim(a), &OpenDelim(b)) |
628 (&CloseDelim(a), &CloseDelim(b)) => a == b,
630 (&DocComment(a), &DocComment(b)) |
631 (&Shebang(a), &Shebang(b)) => a == b,
633 (&Literal(a), &Literal(b)) => a == b,
635 (&Lifetime(a), &Lifetime(b)) => a == b,
636 (&Ident(a, b), &Ident(c, d)) => b == d && (a == c ||
637 a == kw::DollarCrate ||
638 c == kw::DollarCrate),
640 (&Interpolated(_), &Interpolated(_)) => false,
642 _ => panic!("forgot to add a token?"),
648 crate fn new(kind: TokenKind, span: Span) -> Self {
652 /// Some token that will be thrown away later.
653 crate fn dummy() -> Self {
654 Token::new(TokenKind::Whitespace, DUMMY_SP)
657 /// Return this token by value and leave a dummy token in its place.
658 crate fn take(&mut self) -> Self {
659 mem::replace(self, Token::dummy())
663 impl PartialEq<TokenKind> for Token {
664 fn eq(&self, rhs: &TokenKind) -> bool {
669 // FIXME: Remove this after all necessary methods are moved from `TokenKind` to `Token`.
670 impl Deref for Token {
671 type Target = TokenKind;
672 fn deref(&self) -> &Self::Target {
677 #[derive(Clone, RustcEncodable, RustcDecodable)]
678 /// For interpolation during macro expansion.
679 pub enum Nonterminal {
680 NtItem(P<ast::Item>),
681 NtBlock(P<ast::Block>),
684 NtExpr(P<ast::Expr>),
686 NtIdent(ast::Ident, /* is_raw */ bool),
687 NtLifetime(ast::Ident),
688 NtLiteral(P<ast::Expr>),
689 /// Stuff inside brackets for attributes
690 NtMeta(ast::MetaItem),
692 NtVis(ast::Visibility),
694 // Used only for passing items to proc macro attributes (they are not
695 // strictly necessary for that, `Annotatable` can be converted into
696 // tokens directly, but doing that naively regresses pretty-printing).
697 NtTraitItem(ast::TraitItem),
698 NtImplItem(ast::ImplItem),
699 NtForeignItem(ast::ForeignItem),
702 impl PartialEq for Nonterminal {
703 fn eq(&self, rhs: &Self) -> bool {
705 (NtIdent(ident_lhs, is_raw_lhs), NtIdent(ident_rhs, is_raw_rhs)) =>
706 ident_lhs == ident_rhs && is_raw_lhs == is_raw_rhs,
707 (NtLifetime(ident_lhs), NtLifetime(ident_rhs)) => ident_lhs == ident_rhs,
708 (NtTT(tt_lhs), NtTT(tt_rhs)) => tt_lhs == tt_rhs,
709 // FIXME: Assume that all "complex" nonterminal are not equal, we can't compare them
710 // correctly based on data from AST. This will prevent them from matching each other
711 // in macros. The comparison will become possible only when each nonterminal has an
712 // attached token stream from which it was parsed.
718 impl fmt::Debug for Nonterminal {
719 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
721 NtItem(..) => f.pad("NtItem(..)"),
722 NtBlock(..) => f.pad("NtBlock(..)"),
723 NtStmt(..) => f.pad("NtStmt(..)"),
724 NtPat(..) => f.pad("NtPat(..)"),
725 NtExpr(..) => f.pad("NtExpr(..)"),
726 NtTy(..) => f.pad("NtTy(..)"),
727 NtIdent(..) => f.pad("NtIdent(..)"),
728 NtLiteral(..) => f.pad("NtLiteral(..)"),
729 NtMeta(..) => f.pad("NtMeta(..)"),
730 NtPath(..) => f.pad("NtPath(..)"),
731 NtTT(..) => f.pad("NtTT(..)"),
732 NtImplItem(..) => f.pad("NtImplItem(..)"),
733 NtTraitItem(..) => f.pad("NtTraitItem(..)"),
734 NtForeignItem(..) => f.pad("NtForeignItem(..)"),
735 NtVis(..) => f.pad("NtVis(..)"),
736 NtLifetime(..) => f.pad("NtLifetime(..)"),
742 pub fn to_tokenstream(&self, sess: &ParseSess, span: Span) -> TokenStream {
743 // A `Nonterminal` is often a parsed AST item. At this point we now
744 // need to convert the parsed AST to an actual token stream, e.g.
745 // un-parse it basically.
747 // Unfortunately there's not really a great way to do that in a
748 // guaranteed lossless fashion right now. The fallback here is to just
749 // stringify the AST node and reparse it, but this loses all span
752 // As a result, some AST nodes are annotated with the token stream they
753 // came from. Here we attempt to extract these lossless token streams
754 // before we fall back to the stringification.
755 let tokens = match *self {
756 Nonterminal::NtItem(ref item) => {
757 prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span)
759 Nonterminal::NtTraitItem(ref item) => {
760 prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span)
762 Nonterminal::NtImplItem(ref item) => {
763 prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span)
765 Nonterminal::NtIdent(ident, is_raw) => {
766 Some(TokenTree::token(Ident(ident.name, is_raw), ident.span).into())
768 Nonterminal::NtLifetime(ident) => {
769 Some(TokenTree::token(Lifetime(ident.name), ident.span).into())
771 Nonterminal::NtTT(ref tt) => {
772 Some(tt.clone().into())
777 // FIXME(#43081): Avoid this pretty-print + reparse hack
778 let source = pprust::nonterminal_to_string(self);
779 let filename = FileName::macro_expansion_source_code(&source);
780 let tokens_for_real = parse_stream_from_source_str(filename, source, sess, Some(span));
782 // During early phases of the compiler the AST could get modified
783 // directly (e.g., attributes added or removed) and the internal cache
784 // of tokens my not be invalidated or updated. Consequently if the
785 // "lossless" token stream disagrees with our actual stringification
786 // (which has historically been much more battle-tested) then we go
787 // with the lossy stream anyway (losing span information).
789 // Note that the comparison isn't `==` here to avoid comparing spans,
790 // but it *also* is a "probable" equality which is a pretty weird
791 // definition. We mostly want to catch actual changes to the AST
792 // like a `#[cfg]` being processed or some weird `macro_rules!`
795 // What we *don't* want to catch is the fact that a user-defined
796 // literal like `0xf` is stringified as `15`, causing the cached token
797 // stream to not be literal `==` token-wise (ignoring spans) to the
798 // token stream we got from stringification.
800 // Instead the "probably equal" check here is "does each token
801 // recursively have the same discriminant?" We basically don't look at
802 // the token values here and assume that such fine grained token stream
803 // modifications, including adding/removing typically non-semantic
804 // tokens such as extra braces and commas, don't happen.
805 if let Some(tokens) = tokens {
806 if tokens.probably_equal_for_proc_macro(&tokens_for_real) {
809 info!("cached tokens found, but they're not \"probably equal\", \
810 going with stringified version");
812 return tokens_for_real
816 crate fn is_op(tok: &TokenKind) -> bool {
818 OpenDelim(..) | CloseDelim(..) | Literal(..) | DocComment(..) |
819 Ident(..) | Lifetime(..) | Interpolated(..) |
820 Whitespace | Comment | Shebang(..) | Eof => false,
825 fn prepend_attrs(sess: &ParseSess,
826 attrs: &[ast::Attribute],
827 tokens: Option<&tokenstream::TokenStream>,
828 span: syntax_pos::Span)
829 -> Option<tokenstream::TokenStream>
831 let tokens = tokens?;
832 if attrs.len() == 0 {
833 return Some(tokens.clone())
835 let mut builder = tokenstream::TokenStreamBuilder::new();
837 assert_eq!(attr.style, ast::AttrStyle::Outer,
838 "inner attributes should prevent cached tokens from existing");
840 let source = pprust::attr_to_string(attr);
841 let macro_filename = FileName::macro_expansion_source_code(&source);
842 if attr.is_sugared_doc {
843 let stream = parse_stream_from_source_str(macro_filename, source, sess, Some(span));
844 builder.push(stream);
848 // synthesize # [ $path $tokens ] manually here
849 let mut brackets = tokenstream::TokenStreamBuilder::new();
851 // For simple paths, push the identifier directly
852 if attr.path.segments.len() == 1 && attr.path.segments[0].args.is_none() {
853 let ident = attr.path.segments[0].ident;
854 let token = Ident(ident.name, ident.as_str().starts_with("r#"));
855 brackets.push(tokenstream::TokenTree::token(token, ident.span));
857 // ... and for more complicated paths, fall back to a reparse hack that
858 // should eventually be removed.
860 let stream = parse_stream_from_source_str(macro_filename, source, sess, Some(span));
861 brackets.push(stream);
864 brackets.push(attr.tokens.clone());
866 // The span we list here for `#` and for `[ ... ]` are both wrong in
867 // that it encompasses more than each token, but it hopefully is "good
868 // enough" for now at least.
869 builder.push(tokenstream::TokenTree::token(Pound, attr.span));
870 let delim_span = DelimSpan::from_single(attr.span);
871 builder.push(tokenstream::TokenTree::Delimited(
872 delim_span, DelimToken::Bracket, brackets.build().into()));
874 builder.push(tokens.clone());
875 Some(builder.build())