1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::BinOpToken::*;
12 pub use self::Nonterminal::*;
13 pub use self::DelimToken::*;
14 pub use self::IdentStyle::*;
16 pub use self::Token::*;
21 use util::interner::{RcStr, StrInterner};
24 use serialize::{Decodable, Decoder, Encodable, Encoder};
28 use std::old_path::BytesContainer;
31 #[allow(non_camel_case_types)]
32 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
47 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
49 /// A round parenthesis: `(` or `)`
51 /// A square bracket: `[` or `]`
53 /// A curly brace: `{` or `}`
57 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
59 /// `::` follows the identifier with no whitespace in-between.
64 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
65 pub enum SpecialMacroVar {
66 /// `$crate` will be filled in with the name of the crate a macro was
67 /// imported from, if any.
71 impl SpecialMacroVar {
72 pub fn as_str(self) -> &'static str {
74 SpecialMacroVar::CrateMacroVar => "crate",
79 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
86 StrRaw(ast::Name, usize), /* raw str delimited by n hash symbols */
88 BinaryRaw(ast::Name, usize), /* raw binary str delimited by n hash symbols */
92 pub fn short_name(&self) -> &'static str {
96 Integer(_) => "integer",
98 Str_(_) | StrRaw(..) => "str",
99 Binary(_) | BinaryRaw(..) => "binary str"
104 #[allow(non_camel_case_types)]
105 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug)]
107 /* Expression-operator symbols. */
122 /* Structural symbols */
137 /// An opening delimiter, eg. `{`
138 OpenDelim(DelimToken),
139 /// A closing delimiter, eg. `}`
140 CloseDelim(DelimToken),
143 Literal(Lit, Option<ast::Name>),
145 /* Name components */
146 Ident(ast::Ident, IdentStyle),
148 Lifetime(ast::Ident),
150 /* For interpolation */
151 Interpolated(Nonterminal),
152 // Can be expanded into several tokens.
154 DocComment(ast::Name),
155 // In left-hand-sides of MBE macros:
156 /// Parse a nonterminal (name to bind, name of NT, styles of their idents)
157 MatchNt(ast::Ident, ast::Ident, IdentStyle, IdentStyle),
158 // In right-hand-sides of MBE macros:
159 /// A syntactic variable that will be filled in by macro expansion.
160 SubstNt(ast::Ident, IdentStyle),
161 /// A macro variable with special meaning.
162 SpecialVarNt(SpecialMacroVar),
164 // Junk. These carry no data because we don't really care about the data
165 // they *would* carry, and don't really want to allocate a new ident for
166 // them. Instead, users could extract that from the associated span.
178 /// Returns `true` if the token can appear at the start of an expression.
179 pub fn can_begin_expr(&self) -> bool {
181 OpenDelim(_) => true,
185 Literal(_, _) => true,
187 BinOp(Minus) => true,
190 BinOp(Or) => true, // in lambda syntax
191 OrOr => true, // in lambda syntax
192 AndAnd => true, // double borrow
193 DotDot => true, // range notation
195 Interpolated(NtExpr(..)) => true,
196 Interpolated(NtIdent(..)) => true,
197 Interpolated(NtBlock(..)) => true,
198 Interpolated(NtPath(..)) => true,
203 /// Returns `true` if the token is any literal
204 pub fn is_lit(&self) -> bool {
206 Literal(_, _) => true,
211 /// Returns `true` if the token is an identifier.
212 pub fn is_ident(&self) -> bool {
219 /// Returns `true` if the token is an interpolated path.
220 pub fn is_path(&self) -> bool {
222 Interpolated(NtPath(..)) => true,
227 /// Returns `true` if the token is a path that is not followed by a `::`
229 #[allow(non_upper_case_globals)]
230 pub fn is_plain_ident(&self) -> bool {
232 Ident(_, Plain) => true,
237 /// Returns `true` if the token is a lifetime.
238 pub fn is_lifetime(&self) -> bool {
240 Lifetime(..) => true,
245 /// Returns `true` if the token is either the `mut` or `const` keyword.
246 pub fn is_mutability(&self) -> bool {
247 self.is_keyword(keywords::Mut) ||
248 self.is_keyword(keywords::Const)
251 /// Maps a token to its corresponding binary operator.
252 pub fn to_binop(&self) -> Option<ast::BinOp_> {
254 BinOp(Star) => Some(ast::BiMul),
255 BinOp(Slash) => Some(ast::BiDiv),
256 BinOp(Percent) => Some(ast::BiRem),
257 BinOp(Plus) => Some(ast::BiAdd),
258 BinOp(Minus) => Some(ast::BiSub),
259 BinOp(Shl) => Some(ast::BiShl),
260 BinOp(Shr) => Some(ast::BiShr),
261 BinOp(And) => Some(ast::BiBitAnd),
262 BinOp(Caret) => Some(ast::BiBitXor),
263 BinOp(Or) => Some(ast::BiBitOr),
264 Lt => Some(ast::BiLt),
265 Le => Some(ast::BiLe),
266 Ge => Some(ast::BiGe),
267 Gt => Some(ast::BiGt),
268 EqEq => Some(ast::BiEq),
269 Ne => Some(ast::BiNe),
270 AndAnd => Some(ast::BiAnd),
271 OrOr => Some(ast::BiOr),
276 /// Returns `true` if the token is a given keyword, `kw`.
277 #[allow(non_upper_case_globals)]
278 pub fn is_keyword(&self, kw: keywords::Keyword) -> bool {
280 Ident(sid, Plain) => kw.to_name() == sid.name,
285 pub fn is_keyword_allow_following_colon(&self, kw: keywords::Keyword) -> bool {
287 Ident(sid, _) => { kw.to_name() == sid.name }
292 /// Returns `true` if the token is either a special identifier, or a strict
293 /// or reserved keyword.
294 #[allow(non_upper_case_globals)]
295 pub fn is_any_keyword(&self) -> bool {
297 Ident(sid, Plain) => {
300 n == SELF_KEYWORD_NAME
301 || n == STATIC_KEYWORD_NAME
302 || n == SUPER_KEYWORD_NAME
303 || n == SELF_TYPE_KEYWORD_NAME
304 || STRICT_KEYWORD_START <= n
305 && n <= RESERVED_KEYWORD_FINAL
311 /// Returns `true` if the token may not appear as an identifier.
312 #[allow(non_upper_case_globals)]
313 pub fn is_strict_keyword(&self) -> bool {
315 Ident(sid, Plain) => {
318 n == SELF_KEYWORD_NAME
319 || n == STATIC_KEYWORD_NAME
320 || n == SUPER_KEYWORD_NAME
321 || n == SELF_TYPE_KEYWORD_NAME
322 || STRICT_KEYWORD_START <= n
323 && n <= STRICT_KEYWORD_FINAL
325 Ident(sid, ModName) => {
328 n != SELF_KEYWORD_NAME
329 && n != SUPER_KEYWORD_NAME
330 && STRICT_KEYWORD_START <= n
331 && n <= STRICT_KEYWORD_FINAL
337 /// Returns `true` if the token is a keyword that has been reserved for
338 /// possible future use.
339 #[allow(non_upper_case_globals)]
340 pub fn is_reserved_keyword(&self) -> bool {
342 Ident(sid, Plain) => {
345 RESERVED_KEYWORD_START <= n
346 && n <= RESERVED_KEYWORD_FINAL
352 /// Hygienic identifier equality comparison.
354 /// See `styntax::ext::mtwt`.
355 pub fn mtwt_eq(&self, other : &Token) -> bool {
356 match (self, other) {
357 (&Ident(id1,_), &Ident(id2,_)) | (&Lifetime(id1), &Lifetime(id2)) =>
358 mtwt::resolve(id1) == mtwt::resolve(id2),
364 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash)]
365 /// For interpolation during macro expansion.
366 pub enum Nonterminal {
367 NtItem(P<ast::Item>),
368 NtBlock(P<ast::Block>),
369 NtStmt(P<ast::Stmt>),
371 NtExpr(P<ast::Expr>),
373 NtIdent(Box<ast::Ident>, IdentStyle),
374 /// Stuff inside brackets for attributes
375 NtMeta(P<ast::MetaItem>),
376 NtPath(Box<ast::Path>),
377 NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity
380 impl fmt::Debug for Nonterminal {
381 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
383 NtItem(..) => f.pad("NtItem(..)"),
384 NtBlock(..) => f.pad("NtBlock(..)"),
385 NtStmt(..) => f.pad("NtStmt(..)"),
386 NtPat(..) => f.pad("NtPat(..)"),
387 NtExpr(..) => f.pad("NtExpr(..)"),
388 NtTy(..) => f.pad("NtTy(..)"),
389 NtIdent(..) => f.pad("NtIdent(..)"),
390 NtMeta(..) => f.pad("NtMeta(..)"),
391 NtPath(..) => f.pad("NtPath(..)"),
392 NtTT(..) => f.pad("NtTT(..)"),
398 // Get the first "argument"
400 ( $first:expr, $( $remainder:expr, )* ) => ( $first )
403 // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
405 ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
406 ( $first:expr, ) => ( $first )
409 // In this macro, there is the requirement that the name (the number) must be monotonically
410 // increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
411 // except starting from the next number instead of zero, and with the additional exception that
412 // special identifiers are *also* allowed (they are deduplicated in the important place, the
413 // interner), an exception which is demonstrated by "static" and "self".
414 macro_rules! declare_special_idents_and_keywords {(
415 // So now, in these rules, why is each definition parenthesised?
416 // Answer: otherwise we get a spurious local ambiguity bug on the "}"
417 pub mod special_idents {
418 $( ($si_name:expr, $si_static:ident, $si_str:expr); )*
423 $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
425 $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
428 static STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*);
429 static STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*);
430 static RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*);
431 static RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*);
433 pub mod special_idents {
436 #[allow(non_upper_case_globals)]
437 pub const $si_static: ast::Ident = ast::Ident {
438 name: ast::Name($si_name),
444 pub mod special_names {
447 #[allow(non_upper_case_globals)]
448 pub const $si_static: ast::Name = ast::Name($si_name);
452 /// All the valid words that have meaning in the Rust language.
454 /// Rust keywords are either 'strict' or 'reserved'. Strict keywords may not
455 /// appear as identifiers at all. Reserved keywords are not used anywhere in
456 /// the language and may not appear as identifiers.
458 pub use self::Keyword::*;
461 #[derive(Copy, Clone, PartialEq, Eq)]
468 pub fn to_name(&self) -> ast::Name {
470 $( $sk_variant => ast::Name($sk_name), )*
471 $( $rk_variant => ast::Name($rk_name), )*
477 fn mk_fresh_ident_interner() -> IdentInterner {
478 // The indices here must correspond to the numbers in
479 // special_idents, in Keyword to_name(), and in static
481 let mut init_vec = Vec::new();
482 $(init_vec.push($si_str);)*
483 $(init_vec.push($sk_str);)*
484 $(init_vec.push($rk_str);)*
485 interner::StrInterner::prefill(&init_vec[..])
489 // If the special idents get renumbered, remember to modify these two as appropriate
490 pub const SELF_KEYWORD_NAME: ast::Name = ast::Name(SELF_KEYWORD_NAME_NUM);
491 const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM);
492 const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM);
493 const SELF_TYPE_KEYWORD_NAME: ast::Name = ast::Name(SELF_TYPE_KEYWORD_NAME_NUM);
495 pub const SELF_KEYWORD_NAME_NUM: u32 = 1;
496 const STATIC_KEYWORD_NAME_NUM: u32 = 2;
497 const SUPER_KEYWORD_NAME_NUM: u32 = 3;
498 const SELF_TYPE_KEYWORD_NAME_NUM: u32 = 10;
500 // NB: leaving holes in the ident table is bad! a different ident will get
501 // interned with the id from the hole, but it will be between the min and max
502 // of the reserved words, and thus tagged as "reserved".
504 declare_special_idents_and_keywords! {
505 pub mod special_idents {
506 // These ones are statics
508 (super::SELF_KEYWORD_NAME_NUM, self_, "self");
509 (super::STATIC_KEYWORD_NAME_NUM, statik, "static");
510 (super::SUPER_KEYWORD_NAME_NUM, super_, "super");
511 (4, static_lifetime, "'static");
515 (6, matchers, "matchers");
517 // outside of libsyntax
518 (7, clownshoe_abi, "__rust_abi");
519 (8, opaque, "<opaque>");
520 (9, unnamed_field, "<unnamed_field>");
521 (super::SELF_TYPE_KEYWORD_NAME_NUM, type_self, "Self");
522 (11, prelude_import, "prelude_import");
526 // These ones are variants of the Keyword enum
530 (13, Break, "break");
531 (14, Crate, "crate");
534 (17, Extern, "extern");
535 (18, False, "false");
543 (26, Match, "match");
549 (32, Return, "return");
550 // Static and Self are also special idents (prefill de-dupes)
551 (super::STATIC_KEYWORD_NAME_NUM, Static, "static");
552 (super::SELF_KEYWORD_NAME_NUM, SelfValue, "self");
553 (super::SELF_TYPE_KEYWORD_NAME_NUM, SelfType, "Self");
554 (33, Struct, "struct");
555 (super::SUPER_KEYWORD_NAME_NUM, Super, "super");
557 (35, Trait, "trait");
559 (37, Unsafe, "unsafe");
561 (39, Virtual, "virtual");
562 (40, While, "while");
563 (41, Continue, "continue");
566 (44, Const, "const");
567 (45, Where, "where");
569 (46, Alignof, "alignof");
570 (47, Become, "become");
571 (48, Offsetof, "offsetof");
574 (51, Sizeof, "sizeof");
575 (52, Typeof, "typeof");
576 (53, Unsized, "unsized");
577 (54, Yield, "yield");
579 (56, Abstract, "abstract");
580 (57, Final, "final");
581 (58, Override, "override");
582 (59, Macro, "macro");
586 // looks like we can get rid of this completely...
587 pub type IdentInterner = StrInterner;
589 // if an interner exists in TLS, return it. Otherwise, prepare a
591 // FIXME(eddyb) #8726 This should probably use a task-local reference.
592 pub fn get_ident_interner() -> Rc<IdentInterner> {
593 thread_local!(static KEY: Rc<::parse::token::IdentInterner> = {
594 Rc::new(mk_fresh_ident_interner())
596 KEY.with(|k| k.clone())
599 /// Reset the ident interner to its initial state.
600 pub fn reset_ident_interner() {
601 let interner = get_ident_interner();
602 interner.reset(mk_fresh_ident_interner());
605 /// Represents a string stored in the task-local interner. Because the
606 /// interner lives for the life of the task, this can be safely treated as an
607 /// immortal string, as long as it never crosses between tasks.
609 /// FIXME(pcwalton): You must be careful about what you do in the destructors
610 /// of objects stored in TLS, because they may run after the interner is
611 /// destroyed. In particular, they must not access string contents. This can
612 /// be fixed in the future by just leaking all strings until task death
614 #[derive(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
615 pub struct InternedString {
619 impl InternedString {
621 pub fn new(string: &'static str) -> InternedString {
623 string: RcStr::new(string),
628 fn new_from_rc_str(string: RcStr) -> InternedString {
635 impl Deref for InternedString {
638 fn deref(&self) -> &str { &*self.string }
641 impl BytesContainer for InternedString {
642 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
643 // FIXME #12938: This is a workaround for the incorrect signature
644 // of `BytesContainer`, which is itself a workaround for the lack of
647 let this = &self[..];
648 mem::transmute::<&[u8],&[u8]>(this.container_as_bytes())
653 impl fmt::Debug for InternedString {
654 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
655 fmt::Debug::fmt(&self.string[], f)
659 impl fmt::Display for InternedString {
660 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
661 fmt::Display::fmt(&self.string[], f)
665 impl<'a> PartialEq<&'a str> for InternedString {
667 fn eq(&self, other: & &'a str) -> bool {
668 PartialEq::eq(&self.string[], *other)
671 fn ne(&self, other: & &'a str) -> bool {
672 PartialEq::ne(&self.string[], *other)
676 impl<'a> PartialEq<InternedString > for &'a str {
678 fn eq(&self, other: &InternedString) -> bool {
679 PartialEq::eq(*self, &other.string[])
682 fn ne(&self, other: &InternedString) -> bool {
683 PartialEq::ne(*self, &other.string[])
687 impl Decodable for InternedString {
688 fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
689 Ok(get_name(get_ident_interner().intern(&try!(d.read_str())[])))
693 impl Encodable for InternedString {
694 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
695 s.emit_str(&self.string[])
699 /// Returns the string contents of a name, using the task-local interner.
701 pub fn get_name(name: ast::Name) -> InternedString {
702 let interner = get_ident_interner();
703 InternedString::new_from_rc_str(interner.get(name))
706 /// Returns the string contents of an identifier, using the task-local
709 pub fn get_ident(ident: ast::Ident) -> InternedString {
713 /// Interns and returns the string contents of an identifier, using the
714 /// task-local interner.
716 pub fn intern_and_get_ident(s: &str) -> InternedString {
720 /// Maps a string to its interned representation.
722 pub fn intern(s: &str) -> ast::Name {
723 get_ident_interner().intern(s)
726 /// gensym's a new usize, using the current interner.
728 pub fn gensym(s: &str) -> ast::Name {
729 get_ident_interner().gensym(s)
732 /// Maps a string to an identifier with an empty syntax context.
734 pub fn str_to_ident(s: &str) -> ast::Ident {
735 ast::Ident::new(intern(s))
738 /// Maps a string to a gensym'ed identifier.
740 pub fn gensym_ident(s: &str) -> ast::Ident {
741 ast::Ident::new(gensym(s))
744 // create a fresh name that maps to the same string as the old one.
745 // note that this guarantees that str_ptr_eq(ident_to_string(src),interner_get(fresh_name(src)));
746 // that is, that the new name and the old one are connected to ptr_eq strings.
747 pub fn fresh_name(src: &ast::Ident) -> ast::Name {
748 let interner = get_ident_interner();
749 interner.gensym_copy(src.name)
750 // following: debug version. Could work in final except that it's incompatible with
751 // good error messages and uses of struct names in ambiguous could-be-binding
752 // locations. Also definitely destroys the guarantee given above about ptr_eq.
753 /*let num = rand::thread_rng().gen_uint_range(0,0xffff);
754 gensym(format!("{}_{}",ident_to_string(src),num))*/
757 // create a fresh mark.
758 pub fn fresh_mark() -> ast::Mrk {
759 gensym("mark").usize() as u32
768 fn mark_ident(id : ast::Ident, m : ast::Mrk) -> ast::Ident {
769 ast::Ident { name: id.name, ctxt:mtwt::apply_mark(m, id.ctxt) }
772 #[test] fn mtwt_token_eq_test() {
773 assert!(Gt.mtwt_eq(&Gt));
774 let a = str_to_ident("bac");
775 let a1 = mark_ident(a,92);
776 assert!(Ident(a, ModName).mtwt_eq(&Ident(a1, Plain)));