2 pub use Nonterminal::*;
7 use crate::ast::{self};
8 use crate::parse::ParseSess;
9 use crate::print::pprust;
11 use crate::symbol::keywords;
12 use crate::syntax::parse::parse_stream_from_source_str;
13 use crate::syntax::parse::parser::emit_unclosed_delims;
14 use crate::tokenstream::{self, DelimSpan, TokenStream, TokenTree};
16 use syntax_pos::symbol::{self, Symbol};
17 use syntax_pos::{self, Span, FileName};
22 #[cfg(target_arch = "x86_64")]
23 use rustc_data_structures::static_assert;
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, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
71 StrRaw(ast::Name, u16), /* raw str delimited by n hash symbols */
73 ByteStrRaw(ast::Name, u16), /* raw byte str delimited by n hash symbols */
77 crate fn literal_name(&self) -> &'static str {
79 Byte(_) => "byte literal",
80 Char(_) => "char literal",
81 Err(_) => "invalid literal",
82 Integer(_) => "integer literal",
83 Float(_) => "float literal",
84 Str_(_) | StrRaw(..) => "string literal",
85 ByteStr(_) | ByteStrRaw(..) => "byte string literal"
89 // See comments in `interpolated_to_tokenstream` for why we care about
90 // *probably* equal here rather than actual equality
91 fn probably_equal_for_proc_macro(&self, other: &Lit) -> bool {
92 mem::discriminant(self) == mem::discriminant(other)
96 pub(crate) fn ident_can_begin_expr(ident: ast::Ident, is_raw: bool) -> bool {
97 let ident_token: Token = Ident(ident, is_raw);
99 !ident_token.is_reserved_ident() ||
100 ident_token.is_path_segment_keyword() ||
102 keywords::Async.name(),
104 keywords::Box.name(),
105 keywords::Break.name(),
106 keywords::Continue.name(),
107 keywords::False.name(),
108 keywords::For.name(),
110 keywords::Loop.name(),
111 keywords::Match.name(),
112 keywords::Move.name(),
113 keywords::Return.name(),
114 keywords::True.name(),
115 keywords::Unsafe.name(),
116 keywords::While.name(),
117 keywords::Yield.name(),
118 keywords::Static.name(),
119 ].contains(&ident.name)
122 fn ident_can_begin_type(ident: ast::Ident, is_raw: bool) -> bool {
123 let ident_token: Token = Ident(ident, is_raw);
125 !ident_token.is_reserved_ident() ||
126 ident_token.is_path_segment_keyword() ||
128 keywords::Underscore.name(),
129 keywords::For.name(),
130 keywords::Impl.name(),
132 keywords::Unsafe.name(),
133 keywords::Extern.name(),
134 keywords::Typeof.name(),
135 keywords::Dyn.name(),
136 ].contains(&ident.name)
139 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
141 /* Expression-operator symbols. */
156 /* Structural symbols */
172 /// Used by proc macros for representing lifetimes, not generated by lexer right now.
174 /// An opening delimiter (e.g., `{`).
175 OpenDelim(DelimToken),
176 /// A closing delimiter (e.g., `}`).
177 CloseDelim(DelimToken),
180 Literal(Lit, Option<ast::Name>),
182 /* Name components */
183 Ident(ast::Ident, /* is_raw */ bool),
184 Lifetime(ast::Ident),
186 Interpolated(Lrc<Nonterminal>),
188 // Can be expanded into several tokens.
190 DocComment(ast::Name),
192 // Junk. These carry no data because we don't really care about the data
193 // they *would* carry, and don't really want to allocate a new ident for
194 // them. Instead, users could extract that from the associated span.
205 // `Token` is used a lot. Make sure it doesn't unintentionally get bigger.
206 #[cfg(target_arch = "x86_64")]
207 static_assert!(MEM_SIZE_OF_STATEMENT: mem::size_of::<Token>() == 16);
210 /// Recovers a `Token` from an `ast::Ident`. This creates a raw identifier if necessary.
211 pub fn from_ast_ident(ident: ast::Ident) -> Token {
212 Ident(ident, ident.is_raw_guess())
215 crate fn is_like_plus(&self) -> bool {
217 BinOp(Plus) | BinOpEq(Plus) => true,
222 /// Returns `true` if the token can appear at the start of an expression.
223 crate fn can_begin_expr(&self) -> bool {
225 Ident(ident, is_raw) =>
226 ident_can_begin_expr(ident, is_raw), // value name or keyword
227 OpenDelim(..) | // tuple, array or block
228 Literal(..) | // literal
229 Not | // operator not
230 BinOp(Minus) | // unary minus
231 BinOp(Star) | // dereference
232 BinOp(Or) | OrOr | // closure
233 BinOp(And) | // reference
234 AndAnd | // double reference
235 // DotDotDot is no longer supported, but we need some way to display the error
236 DotDot | DotDotDot | DotDotEq | // range notation
237 Lt | BinOp(Shl) | // associated path
238 ModSep | // global path
239 Lifetime(..) | // labeled loop
240 Pound => true, // expression attributes
241 Interpolated(ref nt) => match **nt {
247 NtLifetime(..) => true,
254 /// Returns `true` if the token can appear at the start of a type.
255 crate fn can_begin_type(&self) -> bool {
257 Ident(ident, is_raw) =>
258 ident_can_begin_type(ident, is_raw), // type name or keyword
259 OpenDelim(Paren) | // tuple
260 OpenDelim(Bracket) | // array
262 BinOp(Star) | // raw pointer
263 BinOp(And) | // reference
264 AndAnd | // double reference
265 Question | // maybe bound in trait object
266 Lifetime(..) | // lifetime bound in trait object
267 Lt | BinOp(Shl) | // associated path
268 ModSep => true, // global path
269 Interpolated(ref nt) => match **nt {
270 NtIdent(..) | NtTy(..) | NtPath(..) | NtLifetime(..) => true,
277 /// Returns `true` if the token can appear at the start of a const param.
278 pub fn can_begin_const_arg(&self) -> bool {
280 OpenDelim(Brace) => true,
281 Interpolated(ref nt) => match **nt {
284 NtLiteral(..) => true,
287 _ => self.can_begin_literal_or_bool(),
291 /// Returns `true` if the token can appear at the start of a generic bound.
292 crate fn can_begin_bound(&self) -> bool {
293 self.is_path_start() || self.is_lifetime() || self.is_keyword(keywords::For) ||
294 self == &Question || self == &OpenDelim(Paren)
297 /// Returns `true` if the token is any literal
298 crate fn is_lit(&self) -> bool {
305 /// Returns `true` if the token is any literal, a minus (which can prefix a literal,
306 /// for example a '-42', or one of the boolean idents).
307 crate fn can_begin_literal_or_bool(&self) -> bool {
310 BinOp(Minus) => true,
311 Ident(ident, false) if ident.name == keywords::True.name() => true,
312 Ident(ident, false) if ident.name == keywords::False.name() => true,
313 Interpolated(ref nt) => match **nt {
314 NtLiteral(..) => true,
321 /// Returns an identifier if this token is an identifier.
322 pub fn ident(&self) -> Option<(ast::Ident, /* is_raw */ bool)> {
324 Ident(ident, is_raw) => Some((ident, is_raw)),
325 Interpolated(ref nt) => match **nt {
326 NtIdent(ident, is_raw) => Some((ident, is_raw)),
332 /// Returns a lifetime identifier if this token is a lifetime.
333 pub fn lifetime(&self) -> Option<ast::Ident> {
335 Lifetime(ident) => Some(ident),
336 Interpolated(ref nt) => match **nt {
337 NtLifetime(ident) => Some(ident),
343 /// Returns `true` if the token is an identifier.
344 pub fn is_ident(&self) -> bool {
345 self.ident().is_some()
347 /// Returns `true` if the token is a lifetime.
348 crate fn is_lifetime(&self) -> bool {
349 self.lifetime().is_some()
352 /// Returns `true` if the token is a identifier whose name is the given
354 crate fn is_ident_named(&self, name: &str) -> bool {
356 Some((ident, _)) => ident.as_str() == name,
361 /// Returns `true` if the token is an interpolated path.
362 fn is_path(&self) -> bool {
363 if let Interpolated(ref nt) = *self {
364 if let NtPath(..) = **nt {
371 /// Returns `true` if the token is either the `mut` or `const` keyword.
372 crate fn is_mutability(&self) -> bool {
373 self.is_keyword(keywords::Mut) ||
374 self.is_keyword(keywords::Const)
377 crate fn is_qpath_start(&self) -> bool {
378 self == &Lt || self == &BinOp(Shl)
381 crate fn is_path_start(&self) -> bool {
382 self == &ModSep || self.is_qpath_start() || self.is_path() ||
383 self.is_path_segment_keyword() || self.is_ident() && !self.is_reserved_ident()
386 /// Returns `true` if the token is a given keyword, `kw`.
387 pub fn is_keyword(&self, kw: keywords::Keyword) -> bool {
388 self.ident().map(|(ident, is_raw)| ident.name == kw.name() && !is_raw).unwrap_or(false)
391 pub fn is_path_segment_keyword(&self) -> bool {
393 Some((id, false)) => id.is_path_segment_keyword(),
398 // Returns true for reserved identifiers used internally for elided lifetimes,
399 // unnamed method parameters, crate root module, error recovery etc.
400 pub fn is_special_ident(&self) -> bool {
402 Some((id, false)) => id.is_special(),
407 /// Returns `true` if the token is a keyword used in the language.
408 crate fn is_used_keyword(&self) -> bool {
410 Some((id, false)) => id.is_used_keyword(),
415 /// Returns `true` if the token is a keyword reserved for possible future use.
416 crate fn is_unused_keyword(&self) -> bool {
418 Some((id, false)) => id.is_unused_keyword(),
423 /// Returns `true` if the token is either a special identifier or a keyword.
424 pub fn is_reserved_ident(&self) -> bool {
426 Some((id, false)) => id.is_reserved(),
431 crate fn glue(self, joint: Token) -> Option<Token> {
442 BinOp(Minus) => LArrow,
455 BinOp(op) => match joint {
457 BinOp(And) if op == And => AndAnd,
458 BinOp(Or) if op == Or => OrOr,
459 Gt if op == Minus => RArrow,
467 DotDot => match joint {
472 Colon => match joint {
476 SingleQuote => match joint {
477 Ident(ident, false) => {
478 let name = Symbol::intern(&format!("'{}", ident));
479 Lifetime(symbol::Ident {
487 Le | EqEq | Ne | Ge | AndAnd | OrOr | Tilde | BinOpEq(..) | At | DotDotDot |
488 DotDotEq | Comma | Semi | ModSep | RArrow | LArrow | FatArrow | Pound | Dollar |
489 Question | OpenDelim(..) | CloseDelim(..) |
490 Literal(..) | Ident(..) | Lifetime(..) | Interpolated(..) | DocComment(..) |
491 Whitespace | Comment | Shebang(..) | Eof => return None,
495 /// Returns tokens that are likely to be typed accidentally instead of the current token.
496 /// Enables better error recovery when the wrong token is found.
497 crate fn similar_tokens(&self) -> Option<Vec<Token>> {
499 Comma => Some(vec![Dot, Lt, Semi]),
500 Semi => Some(vec![Colon, Comma]),
505 pub fn interpolated_to_tokenstream(sess: &ParseSess, nt: Lrc<Nonterminal>, span: Span)
507 // An `Interpolated` token means that we have a `Nonterminal`
508 // which is often a parsed AST item. At this point we now need
509 // to convert the parsed AST to an actual token stream, e.g.
510 // un-parse it basically.
512 // Unfortunately there's not really a great way to do that in a
513 // guaranteed lossless fashion right now. The fallback here is
514 // to just stringify the AST node and reparse it, but this loses
515 // all span information.
517 // As a result, some AST nodes are annotated with the token
518 // stream they came from. Here we attempt to extract these
519 // lossless token streams before we fall back to the
521 let tokens = match *nt {
522 Nonterminal::NtItem(ref item) => {
523 prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span)
525 Nonterminal::NtTraitItem(ref item) => {
526 prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span)
528 Nonterminal::NtImplItem(ref item) => {
529 prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span)
531 Nonterminal::NtIdent(ident, is_raw) => {
532 let token = Token::Ident(ident, is_raw);
533 Some(TokenTree::Token(ident.span, token).into())
535 Nonterminal::NtLifetime(ident) => {
536 let token = Token::Lifetime(ident);
537 Some(TokenTree::Token(ident.span, token).into())
539 Nonterminal::NtTT(ref tt) => {
540 Some(tt.clone().into())
545 // FIXME(#43081): Avoid this pretty-print + reparse hack
546 let source = pprust::nonterminal_to_string(&nt);
547 let filename = FileName::macro_expansion_source_code(&source);
548 let (tokens_for_real, errors) =
549 parse_stream_from_source_str(filename, source, sess, Some(span));
550 emit_unclosed_delims(&errors, &sess.span_diagnostic);
552 // During early phases of the compiler the AST could get modified
553 // directly (e.g., attributes added or removed) and the internal cache
554 // of tokens my not be invalidated or updated. Consequently if the
555 // "lossless" token stream disagrees with our actual stringification
556 // (which has historically been much more battle-tested) then we go
557 // with the lossy stream anyway (losing span information).
559 // Note that the comparison isn't `==` here to avoid comparing spans,
560 // but it *also* is a "probable" equality which is a pretty weird
561 // definition. We mostly want to catch actual changes to the AST
562 // like a `#[cfg]` being processed or some weird `macro_rules!`
565 // What we *don't* want to catch is the fact that a user-defined
566 // literal like `0xf` is stringified as `15`, causing the cached token
567 // stream to not be literal `==` token-wise (ignoring spans) to the
568 // token stream we got from stringification.
570 // Instead the "probably equal" check here is "does each token
571 // recursively have the same discriminant?" We basically don't look at
572 // the token values here and assume that such fine grained token stream
573 // modifications, including adding/removing typically non-semantic
574 // tokens such as extra braces and commas, don't happen.
575 if let Some(tokens) = tokens {
576 if tokens.probably_equal_for_proc_macro(&tokens_for_real) {
579 info!("cached tokens found, but they're not \"probably equal\", \
580 going with stringified version");
582 return tokens_for_real
585 // See comments in `interpolated_to_tokenstream` for why we care about
586 // *probably* equal here rather than actual equality
587 crate fn probably_equal_for_proc_macro(&self, other: &Token) -> bool {
588 if mem::discriminant(self) != mem::discriminant(other) {
591 match (self, other) {
606 (&DotDotDot, &DotDotDot) |
607 (&DotDotEq, &DotDotEq) |
614 (&FatArrow, &FatArrow) |
617 (&Question, &Question) |
618 (&Whitespace, &Whitespace) |
619 (&Comment, &Comment) |
620 (&Eof, &Eof) => true,
622 (&BinOp(a), &BinOp(b)) |
623 (&BinOpEq(a), &BinOpEq(b)) => a == b,
625 (&OpenDelim(a), &OpenDelim(b)) |
626 (&CloseDelim(a), &CloseDelim(b)) => a == b,
628 (&DocComment(a), &DocComment(b)) |
629 (&Shebang(a), &Shebang(b)) => a == b,
631 (&Lifetime(a), &Lifetime(b)) => a.name == b.name,
632 (&Ident(a, b), &Ident(c, d)) => b == d && (a.name == c.name ||
633 a.name == keywords::DollarCrate.name() ||
634 c.name == keywords::DollarCrate.name()),
636 (&Literal(ref a, b), &Literal(ref c, d)) => {
637 b == d && a.probably_equal_for_proc_macro(c)
640 (&Interpolated(_), &Interpolated(_)) => false,
642 _ => panic!("forgot to add a token?"),
647 #[derive(Clone, RustcEncodable, RustcDecodable)]
648 /// For interpolation during macro expansion.
649 pub enum Nonterminal {
650 NtItem(P<ast::Item>),
651 NtBlock(P<ast::Block>),
654 NtExpr(P<ast::Expr>),
656 NtIdent(ast::Ident, /* is_raw */ bool),
657 NtLifetime(ast::Ident),
658 NtLiteral(P<ast::Expr>),
659 /// Stuff inside brackets for attributes
660 NtMeta(ast::MetaItem),
662 NtVis(ast::Visibility),
664 // These are not exposed to macros, but are used by quasiquote.
666 NtImplItem(ast::ImplItem),
667 NtTraitItem(ast::TraitItem),
668 NtForeignItem(ast::ForeignItem),
669 NtGenerics(ast::Generics),
670 NtWhereClause(ast::WhereClause),
674 impl PartialEq for Nonterminal {
675 fn eq(&self, rhs: &Self) -> bool {
677 (NtIdent(ident_lhs, is_raw_lhs), NtIdent(ident_rhs, is_raw_rhs)) =>
678 ident_lhs == ident_rhs && is_raw_lhs == is_raw_rhs,
679 (NtLifetime(ident_lhs), NtLifetime(ident_rhs)) => ident_lhs == ident_rhs,
680 (NtTT(tt_lhs), NtTT(tt_rhs)) => tt_lhs == tt_rhs,
681 // FIXME: Assume that all "complex" nonterminal are not equal, we can't compare them
682 // correctly based on data from AST. This will prevent them from matching each other
683 // in macros. The comparison will become possible only when each nonterminal has an
684 // attached token stream from which it was parsed.
690 impl fmt::Debug for Nonterminal {
691 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
693 NtItem(..) => f.pad("NtItem(..)"),
694 NtBlock(..) => f.pad("NtBlock(..)"),
695 NtStmt(..) => f.pad("NtStmt(..)"),
696 NtPat(..) => f.pad("NtPat(..)"),
697 NtExpr(..) => f.pad("NtExpr(..)"),
698 NtTy(..) => f.pad("NtTy(..)"),
699 NtIdent(..) => f.pad("NtIdent(..)"),
700 NtLiteral(..) => f.pad("NtLiteral(..)"),
701 NtMeta(..) => f.pad("NtMeta(..)"),
702 NtPath(..) => f.pad("NtPath(..)"),
703 NtTT(..) => f.pad("NtTT(..)"),
704 NtArm(..) => f.pad("NtArm(..)"),
705 NtImplItem(..) => f.pad("NtImplItem(..)"),
706 NtTraitItem(..) => f.pad("NtTraitItem(..)"),
707 NtForeignItem(..) => f.pad("NtForeignItem(..)"),
708 NtGenerics(..) => f.pad("NtGenerics(..)"),
709 NtWhereClause(..) => f.pad("NtWhereClause(..)"),
710 NtArg(..) => f.pad("NtArg(..)"),
711 NtVis(..) => f.pad("NtVis(..)"),
712 NtLifetime(..) => f.pad("NtLifetime(..)"),
717 crate fn is_op(tok: &Token) -> bool {
719 OpenDelim(..) | CloseDelim(..) | Literal(..) | DocComment(..) |
720 Ident(..) | Lifetime(..) | Interpolated(..) |
721 Whitespace | Comment | Shebang(..) | Eof => false,
726 fn prepend_attrs(sess: &ParseSess,
727 attrs: &[ast::Attribute],
728 tokens: Option<&tokenstream::TokenStream>,
729 span: syntax_pos::Span)
730 -> Option<tokenstream::TokenStream>
732 let tokens = tokens?;
733 if attrs.len() == 0 {
734 return Some(tokens.clone())
736 let mut builder = tokenstream::TokenStreamBuilder::new();
738 assert_eq!(attr.style, ast::AttrStyle::Outer,
739 "inner attributes should prevent cached tokens from existing");
741 let source = pprust::attr_to_string(attr);
742 let macro_filename = FileName::macro_expansion_source_code(&source);
743 if attr.is_sugared_doc {
744 let (stream, errors) = parse_stream_from_source_str(
750 emit_unclosed_delims(&errors, &sess.span_diagnostic);
751 builder.push(stream);
755 // synthesize # [ $path $tokens ] manually here
756 let mut brackets = tokenstream::TokenStreamBuilder::new();
758 // For simple paths, push the identifier directly
759 if attr.path.segments.len() == 1 && attr.path.segments[0].args.is_none() {
760 let ident = attr.path.segments[0].ident;
761 let token = Ident(ident, ident.as_str().starts_with("r#"));
762 brackets.push(tokenstream::TokenTree::Token(ident.span, token));
764 // ... and for more complicated paths, fall back to a reparse hack that
765 // should eventually be removed.
767 let (stream, errors) = parse_stream_from_source_str(
773 emit_unclosed_delims(&errors, &sess.span_diagnostic);
774 brackets.push(stream);
777 brackets.push(attr.tokens.clone());
779 // The span we list here for `#` and for `[ ... ]` are both wrong in
780 // that it encompasses more than each token, but it hopefully is "good
781 // enough" for now at least.
782 builder.push(tokenstream::TokenTree::Token(attr.span, Pound));
783 let delim_span = DelimSpan::from_single(attr.span);
784 builder.push(tokenstream::TokenTree::Delimited(
785 delim_span, DelimToken::Bracket, brackets.build().into()));
787 builder.push(tokens.clone());
788 Some(builder.build())