4 pub use Nonterminal::*;
9 use crate::tokenstream::TokenTree;
11 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
12 use rustc_data_structures::sync::Lrc;
13 use rustc_macros::HashStable_Generic;
14 use rustc_span::symbol::kw;
15 use rustc_span::symbol::Symbol;
16 use rustc_span::{self, Span, DUMMY_SP};
20 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
21 #[derive(HashStable_Generic)]
35 /// A delimiter token.
36 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
37 #[derive(HashStable_Generic)]
39 /// A round parenthesis (i.e., `(` or `)`).
41 /// A square bracket (i.e., `[` or `]`).
43 /// A curly brace (i.e., `{` or `}`).
45 /// An empty delimiter.
50 pub fn len(self) -> usize {
51 if self == NoDelim { 0 } else { 1 }
54 pub fn is_empty(self) -> bool {
59 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
61 Bool, // AST only, must never appear in a `Token`
67 StrRaw(u16), // raw string delimited by `n` hash symbols
69 ByteStrRaw(u16), // raw byte string delimited by `n` hash symbols
74 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
78 pub suffix: Option<Symbol>,
81 impl fmt::Display for Lit {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 let Lit { kind, symbol, suffix } = *self;
85 Byte => write!(f, "b'{}'", symbol)?,
86 Char => write!(f, "'{}'", symbol)?,
87 Str => write!(f, "\"{}\"", symbol)?,
90 "r{delim}\"{string}\"{delim}",
91 delim = "#".repeat(n as usize),
94 ByteStr => write!(f, "b\"{}\"", symbol)?,
95 ByteStrRaw(n) => write!(
97 "br{delim}\"{string}\"{delim}",
98 delim = "#".repeat(n as usize),
101 Integer | Float | Bool | Err => write!(f, "{}", symbol)?,
104 if let Some(suffix) = suffix {
105 write!(f, "{}", suffix)?;
113 /// An English article for the literal token kind.
114 pub fn article(self) -> &'static str {
116 Integer | Err => "an",
121 pub fn descr(self) -> &'static str {
123 Bool => panic!("literal token contains `Lit::Bool`"),
126 Integer => "integer",
128 Str | StrRaw(..) => "string",
129 ByteStr | ByteStrRaw(..) => "byte string",
134 crate fn may_have_suffix(self) -> bool {
136 Integer | Float | Err => true,
143 pub fn new(kind: LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Lit {
144 Lit { kind, symbol, suffix }
148 pub fn ident_can_begin_expr(name: ast::Name, span: Span, is_raw: bool) -> bool {
149 let ident_token = Token::new(Ident(name, is_raw), span);
150 token_can_begin_expr(&ident_token)
153 pub fn token_can_begin_expr(ident_token: &Token) -> bool {
154 !ident_token.is_reserved_ident()
155 || ident_token.is_path_segment_keyword()
156 || match ident_token.kind {
157 TokenKind::Ident(ident, _) => [
182 fn ident_can_begin_type(name: ast::Name, span: Span, is_raw: bool) -> bool {
183 let ident_token = Token::new(Ident(name, is_raw), span);
185 !ident_token.is_reserved_ident()
186 || ident_token.is_path_segment_keyword()
187 || [kw::Underscore, kw::For, kw::Impl, kw::Fn, kw::Unsafe, kw::Extern, kw::Typeof, kw::Dyn]
191 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
193 /* Expression-operator symbols. */
208 /* Structural symbols */
224 /// Used by proc macros for representing lifetimes, not generated by lexer right now.
226 /// An opening delimiter (e.g., `{`).
227 OpenDelim(DelimToken),
228 /// A closing delimiter (e.g., `}`).
229 CloseDelim(DelimToken),
234 /* Name components */
235 Ident(ast::Name, /* is_raw */ bool),
238 Interpolated(Lrc<Nonterminal>),
240 // Can be expanded into several tokens.
242 DocComment(ast::Name),
244 // Junk. These carry no data because we don't really care about the data
245 // they *would* carry, and don't really want to allocate a new ident for
246 // them. Instead, users could extract that from the associated span.
252 /// A completely invalid token which should be skipped.
258 // `TokenKind` is used a lot. Make sure it doesn't unintentionally get bigger.
259 #[cfg(target_arch = "x86_64")]
260 rustc_data_structures::static_assert_size!(TokenKind, 16);
262 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
269 pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option<Symbol>) -> TokenKind {
270 Literal(Lit::new(kind, symbol, suffix))
273 /// Returns tokens that are likely to be typed accidentally instead of the current token.
274 /// Enables better error recovery when the wrong token is found.
275 pub fn similar_tokens(&self) -> Option<Vec<TokenKind>> {
277 Comma => Some(vec![Dot, Lt, Semi]),
278 Semi => Some(vec![Colon, Comma]),
285 pub fn new(kind: TokenKind, span: Span) -> Self {
289 /// Some token that will be thrown away later.
290 pub fn dummy() -> Self {
291 Token::new(TokenKind::Whitespace, DUMMY_SP)
294 /// Recovers a `Token` from an `ast::Ident`. This creates a raw identifier if necessary.
295 pub fn from_ast_ident(ident: ast::Ident) -> Self {
296 Token::new(Ident(ident.name, ident.is_raw_guess()), ident.span)
299 /// Return this token by value and leave a dummy token in its place.
300 pub fn take(&mut self) -> Self {
301 mem::replace(self, Token::dummy())
304 pub fn is_op(&self) -> bool {
306 OpenDelim(..) | CloseDelim(..) | Literal(..) | DocComment(..) | Ident(..)
307 | Lifetime(..) | Interpolated(..) | Whitespace | Comment | Shebang(..) | Eof => false,
312 pub fn is_like_plus(&self) -> bool {
314 BinOp(Plus) | BinOpEq(Plus) => true,
319 /// Returns `true` if the token can appear at the start of an expression.
320 pub fn can_begin_expr(&self) -> bool {
322 Ident(name, is_raw) =>
323 ident_can_begin_expr(name, self.span, is_raw), // value name or keyword
324 OpenDelim(..) | // tuple, array or block
325 Literal(..) | // literal
326 Not | // operator not
327 BinOp(Minus) | // unary minus
328 BinOp(Star) | // dereference
329 BinOp(Or) | OrOr | // closure
330 BinOp(And) | // reference
331 AndAnd | // double reference
332 // DotDotDot is no longer supported, but we need some way to display the error
333 DotDot | DotDotDot | DotDotEq | // range notation
334 Lt | BinOp(Shl) | // associated path
335 ModSep | // global path
336 Lifetime(..) | // labeled loop
337 Pound => true, // expression attributes
338 Interpolated(ref nt) => match **nt {
344 NtLifetime(..) => true,
351 /// Returns `true` if the token can appear at the start of a type.
352 pub fn can_begin_type(&self) -> bool {
354 Ident(name, is_raw) =>
355 ident_can_begin_type(name, self.span, is_raw), // type name or keyword
356 OpenDelim(Paren) | // tuple
357 OpenDelim(Bracket) | // array
359 BinOp(Star) | // raw pointer
360 BinOp(And) | // reference
361 AndAnd | // double reference
362 Question | // maybe bound in trait object
363 Lifetime(..) | // lifetime bound in trait object
364 Lt | BinOp(Shl) | // associated path
365 ModSep => true, // global path
366 Interpolated(ref nt) => match **nt {
367 NtIdent(..) | NtTy(..) | NtPath(..) | NtLifetime(..) => true,
374 /// Returns `true` if the token can appear at the start of a const param.
375 pub fn can_begin_const_arg(&self) -> bool {
377 OpenDelim(Brace) => true,
378 Interpolated(ref nt) => match **nt {
379 NtExpr(..) | NtBlock(..) | NtLiteral(..) => true,
382 _ => self.can_begin_literal_or_bool(),
386 /// Returns `true` if the token can appear at the start of a generic bound.
387 pub fn can_begin_bound(&self) -> bool {
389 || self.is_lifetime()
390 || self.is_keyword(kw::For)
392 || self == &OpenDelim(Paren)
395 /// Returns `true` if the token is any literal
396 pub fn is_lit(&self) -> bool {
403 /// Returns `true` if the token is any literal, a minus (which can prefix a literal,
404 /// for example a '-42', or one of the boolean idents).
405 pub fn can_begin_literal_or_bool(&self) -> bool {
407 Literal(..) | BinOp(Minus) => true,
408 Ident(name, false) if name.is_bool_lit() => true,
409 Interpolated(ref nt) => match **nt {
410 NtLiteral(..) => true,
417 /// Returns an identifier if this token is an identifier.
418 pub fn ident(&self) -> Option<(ast::Ident, /* is_raw */ bool)> {
420 Ident(name, is_raw) => Some((ast::Ident::new(name, self.span), is_raw)),
421 Interpolated(ref nt) => match **nt {
422 NtIdent(ident, is_raw) => Some((ident, is_raw)),
429 /// Returns a lifetime identifier if this token is a lifetime.
430 pub fn lifetime(&self) -> Option<ast::Ident> {
432 Lifetime(name) => Some(ast::Ident::new(name, self.span)),
433 Interpolated(ref nt) => match **nt {
434 NtLifetime(ident) => Some(ident),
441 /// Returns `true` if the token is an identifier.
442 pub fn is_ident(&self) -> bool {
443 self.ident().is_some()
446 /// Returns `true` if the token is a lifetime.
447 pub fn is_lifetime(&self) -> bool {
448 self.lifetime().is_some()
451 /// Returns `true` if the token is a identifier whose name is the given
453 pub fn is_ident_named(&self, name: Symbol) -> bool {
454 self.ident().map_or(false, |(ident, _)| ident.name == name)
457 /// Returns `true` if the token is an interpolated path.
458 fn is_path(&self) -> bool {
459 if let Interpolated(ref nt) = self.kind {
460 if let NtPath(..) = **nt {
467 /// Would `maybe_whole_expr` in `parser.rs` return `Ok(..)`?
468 /// That is, is this a pre-parsed expression dropped into the token stream
469 /// (which happens while parsing the result of macro expansion)?
470 pub fn is_whole_expr(&self) -> bool {
471 if let Interpolated(ref nt) = self.kind {
472 if let NtExpr(_) | NtLiteral(_) | NtPath(_) | NtIdent(..) | NtBlock(_) = **nt {
480 /// Returns `true` if the token is either the `mut` or `const` keyword.
481 pub fn is_mutability(&self) -> bool {
482 self.is_keyword(kw::Mut) || self.is_keyword(kw::Const)
485 pub fn is_qpath_start(&self) -> bool {
486 self == &Lt || self == &BinOp(Shl)
489 pub fn is_path_start(&self) -> bool {
491 || self.is_qpath_start()
493 || self.is_path_segment_keyword()
494 || self.is_ident() && !self.is_reserved_ident()
497 /// Returns `true` if the token is a given keyword, `kw`.
498 pub fn is_keyword(&self, kw: Symbol) -> bool {
499 self.is_non_raw_ident_where(|id| id.name == kw)
502 pub fn is_path_segment_keyword(&self) -> bool {
503 self.is_non_raw_ident_where(ast::Ident::is_path_segment_keyword)
506 // Returns true for reserved identifiers used internally for elided lifetimes,
507 // unnamed method parameters, crate root module, error recovery etc.
508 pub fn is_special_ident(&self) -> bool {
509 self.is_non_raw_ident_where(ast::Ident::is_special)
512 /// Returns `true` if the token is a keyword used in the language.
513 pub fn is_used_keyword(&self) -> bool {
514 self.is_non_raw_ident_where(ast::Ident::is_used_keyword)
517 /// Returns `true` if the token is a keyword reserved for possible future use.
518 pub fn is_unused_keyword(&self) -> bool {
519 self.is_non_raw_ident_where(ast::Ident::is_unused_keyword)
522 /// Returns `true` if the token is either a special identifier or a keyword.
523 pub fn is_reserved_ident(&self) -> bool {
524 self.is_non_raw_ident_where(ast::Ident::is_reserved)
527 /// Returns `true` if the token is the identifier `true` or `false`.
528 pub fn is_bool_lit(&self) -> bool {
529 self.is_non_raw_ident_where(|id| id.name.is_bool_lit())
532 /// Returns `true` if the token is a non-raw identifier for which `pred` holds.
533 fn is_non_raw_ident_where(&self, pred: impl FnOnce(ast::Ident) -> bool) -> bool {
535 Some((id, false)) => pred(id),
540 pub fn glue(&self, joint: &Token) -> Option<Token> {
541 let kind = match self.kind {
542 Eq => match joint.kind {
547 Lt => match joint.kind {
551 BinOp(Minus) => LArrow,
554 Gt => match joint.kind {
560 Not => match joint.kind {
564 BinOp(op) => match joint.kind {
566 BinOp(And) if op == And => AndAnd,
567 BinOp(Or) if op == Or => OrOr,
568 Gt if op == Minus => RArrow,
571 Dot => match joint.kind {
576 DotDot => match joint.kind {
581 Colon => match joint.kind {
585 SingleQuote => match joint.kind {
586 Ident(name, false) => Lifetime(Symbol::intern(&format!("'{}", name))),
590 Le | EqEq | Ne | Ge | AndAnd | OrOr | Tilde | BinOpEq(..) | At | DotDotDot
591 | DotDotEq | Comma | Semi | ModSep | RArrow | LArrow | FatArrow | Pound | Dollar
592 | Question | OpenDelim(..) | CloseDelim(..) | Literal(..) | Ident(..)
593 | Lifetime(..) | Interpolated(..) | DocComment(..) | Whitespace | Comment
594 | Shebang(..) | Unknown(..) | Eof => return None,
597 Some(Token::new(kind, self.span.to(joint.span)))
600 // See comments in `Nonterminal::to_tokenstream` for why we care about
601 // *probably* equal here rather than actual equality
602 crate fn probably_equal_for_proc_macro(&self, other: &Token) -> bool {
603 if mem::discriminant(&self.kind) != mem::discriminant(&other.kind) {
606 match (&self.kind, &other.kind) {
621 | (&DotDotDot, &DotDotDot)
622 | (&DotDotEq, &DotDotEq)
629 | (&FatArrow, &FatArrow)
632 | (&Question, &Question)
633 | (&Whitespace, &Whitespace)
634 | (&Comment, &Comment)
635 | (&Eof, &Eof) => true,
637 (&BinOp(a), &BinOp(b)) | (&BinOpEq(a), &BinOpEq(b)) => a == b,
639 (&OpenDelim(a), &OpenDelim(b)) | (&CloseDelim(a), &CloseDelim(b)) => a == b,
641 (&DocComment(a), &DocComment(b)) | (&Shebang(a), &Shebang(b)) => a == b,
643 (&Literal(a), &Literal(b)) => a == b,
645 (&Lifetime(a), &Lifetime(b)) => a == b,
646 (&Ident(a, b), &Ident(c, d)) => {
647 b == d && (a == c || a == kw::DollarCrate || c == kw::DollarCrate)
650 (&Interpolated(_), &Interpolated(_)) => false,
652 _ => panic!("forgot to add a token?"),
657 impl PartialEq<TokenKind> for Token {
658 fn eq(&self, rhs: &TokenKind) -> bool {
663 #[derive(Clone, RustcEncodable, RustcDecodable)]
664 /// For interpolation during macro expansion.
665 pub enum Nonterminal {
666 NtItem(P<ast::Item>),
667 NtBlock(P<ast::Block>),
670 NtExpr(P<ast::Expr>),
672 NtIdent(ast::Ident, /* is_raw */ bool),
673 NtLifetime(ast::Ident),
674 NtLiteral(P<ast::Expr>),
675 /// Stuff inside brackets for attributes
676 NtMeta(ast::AttrItem),
678 NtVis(ast::Visibility),
680 // Used only for passing items to proc macro attributes (they are not
681 // strictly necessary for that, `Annotatable` can be converted into
682 // tokens directly, but doing that naively regresses pretty-printing).
683 NtTraitItem(ast::AssocItem),
684 NtImplItem(ast::AssocItem),
685 NtForeignItem(ast::ForeignItem),
688 impl PartialEq for Nonterminal {
689 fn eq(&self, rhs: &Self) -> bool {
691 (NtIdent(ident_lhs, is_raw_lhs), NtIdent(ident_rhs, is_raw_rhs)) => {
692 ident_lhs == ident_rhs && is_raw_lhs == is_raw_rhs
694 (NtLifetime(ident_lhs), NtLifetime(ident_rhs)) => ident_lhs == ident_rhs,
695 (NtTT(tt_lhs), NtTT(tt_rhs)) => tt_lhs == tt_rhs,
696 // FIXME: Assume that all "complex" nonterminal are not equal, we can't compare them
697 // correctly based on data from AST. This will prevent them from matching each other
698 // in macros. The comparison will become possible only when each nonterminal has an
699 // attached token stream from which it was parsed.
705 impl fmt::Debug for Nonterminal {
706 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
708 NtItem(..) => f.pad("NtItem(..)"),
709 NtBlock(..) => f.pad("NtBlock(..)"),
710 NtStmt(..) => f.pad("NtStmt(..)"),
711 NtPat(..) => f.pad("NtPat(..)"),
712 NtExpr(..) => f.pad("NtExpr(..)"),
713 NtTy(..) => f.pad("NtTy(..)"),
714 NtIdent(..) => f.pad("NtIdent(..)"),
715 NtLiteral(..) => f.pad("NtLiteral(..)"),
716 NtMeta(..) => f.pad("NtMeta(..)"),
717 NtPath(..) => f.pad("NtPath(..)"),
718 NtTT(..) => f.pad("NtTT(..)"),
719 NtImplItem(..) => f.pad("NtImplItem(..)"),
720 NtTraitItem(..) => f.pad("NtTraitItem(..)"),
721 NtForeignItem(..) => f.pad("NtForeignItem(..)"),
722 NtVis(..) => f.pad("NtVis(..)"),
723 NtLifetime(..) => f.pad("NtLifetime(..)"),
728 impl<CTX> HashStable<CTX> for Nonterminal
730 CTX: crate::HashStableContext,
732 fn hash_stable(&self, _hcx: &mut CTX, _hasher: &mut StableHasher) {
733 panic!("interpolated tokens should not be present in the HIR")