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::path::BytesContainer;
31 #[allow(non_camel_case_types)]
32 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
47 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
49 /// A round parenthesis: `(` or `)`
51 /// A square bracket: `[` or `]`
53 /// A curly brace: `{` or `}`
57 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
59 /// `::` follows the identifier with no whitespace in-between.
64 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, 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, Show, Copy)]
86 StrRaw(ast::Name, uint), /* raw str delimited by n hash symbols */
88 BinaryRaw(ast::Name, uint), /* 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, Show)]
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 || STRICT_KEYWORD_START <= n
304 && n <= RESERVED_KEYWORD_FINAL
310 /// Returns `true` if the token may not appear as an identifier.
311 #[allow(non_upper_case_globals)]
312 pub fn is_strict_keyword(&self) -> bool {
314 Ident(sid, Plain) => {
317 n == SELF_KEYWORD_NAME
318 || n == STATIC_KEYWORD_NAME
319 || n == SUPER_KEYWORD_NAME
320 || STRICT_KEYWORD_START <= n
321 && n <= STRICT_KEYWORD_FINAL
323 Ident(sid, ModName) => {
326 n != SELF_KEYWORD_NAME
327 && n != SUPER_KEYWORD_NAME
328 && STRICT_KEYWORD_START <= n
329 && n <= STRICT_KEYWORD_FINAL
335 /// Returns `true` if the token is a keyword that has been reserved for
336 /// possible future use.
337 #[allow(non_upper_case_globals)]
338 pub fn is_reserved_keyword(&self) -> bool {
340 Ident(sid, Plain) => {
343 RESERVED_KEYWORD_START <= n
344 && n <= RESERVED_KEYWORD_FINAL
350 /// Hygienic identifier equality comparison.
352 /// See `styntax::ext::mtwt`.
353 pub fn mtwt_eq(&self, other : &Token) -> bool {
354 match (self, other) {
355 (&Ident(id1,_), &Ident(id2,_)) | (&Lifetime(id1), &Lifetime(id2)) =>
356 mtwt::resolve(id1) == mtwt::resolve(id2),
362 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash)]
363 /// For interpolation during macro expansion.
364 pub enum Nonterminal {
365 NtItem(P<ast::Item>),
366 NtBlock(P<ast::Block>),
367 NtStmt(P<ast::Stmt>),
369 NtExpr(P<ast::Expr>),
371 NtIdent(Box<ast::Ident>, IdentStyle),
372 /// Stuff inside brackets for attributes
373 NtMeta(P<ast::MetaItem>),
374 NtPath(Box<ast::Path>),
375 NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity
378 impl fmt::Debug for Nonterminal {
379 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
381 NtItem(..) => f.pad("NtItem(..)"),
382 NtBlock(..) => f.pad("NtBlock(..)"),
383 NtStmt(..) => f.pad("NtStmt(..)"),
384 NtPat(..) => f.pad("NtPat(..)"),
385 NtExpr(..) => f.pad("NtExpr(..)"),
386 NtTy(..) => f.pad("NtTy(..)"),
387 NtIdent(..) => f.pad("NtIdent(..)"),
388 NtMeta(..) => f.pad("NtMeta(..)"),
389 NtPath(..) => f.pad("NtPath(..)"),
390 NtTT(..) => f.pad("NtTT(..)"),
396 // Get the first "argument"
398 ( $first:expr, $( $remainder:expr, )* ) => ( $first )
401 // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
403 ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
404 ( $first:expr, ) => ( $first )
407 // In this macro, there is the requirement that the name (the number) must be monotonically
408 // increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
409 // except starting from the next number instead of zero, and with the additional exception that
410 // special identifiers are *also* allowed (they are deduplicated in the important place, the
411 // interner), an exception which is demonstrated by "static" and "self".
412 macro_rules! declare_special_idents_and_keywords {(
413 // So now, in these rules, why is each definition parenthesised?
414 // Answer: otherwise we get a spurious local ambiguity bug on the "}"
415 pub mod special_idents {
416 $( ($si_name:expr, $si_static:ident, $si_str:expr); )*
421 $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
423 $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
426 static STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*);
427 static STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*);
428 static RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*);
429 static RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*);
431 pub mod special_idents {
434 #[allow(non_upper_case_globals)]
435 pub const $si_static: ast::Ident = ast::Ident {
436 name: ast::Name($si_name),
442 pub mod special_names {
445 #[allow(non_upper_case_globals)]
446 pub const $si_static: ast::Name = ast::Name($si_name);
450 /// All the valid words that have meaning in the Rust language.
452 /// Rust keywords are either 'strict' or 'reserved'. Strict keywords may not
453 /// appear as identifiers at all. Reserved keywords are not used anywhere in
454 /// the language and may not appear as identifiers.
456 pub use self::Keyword::*;
466 pub fn to_name(&self) -> ast::Name {
468 $( $sk_variant => ast::Name($sk_name), )*
469 $( $rk_variant => ast::Name($rk_name), )*
475 fn mk_fresh_ident_interner() -> IdentInterner {
476 // The indices here must correspond to the numbers in
477 // special_idents, in Keyword to_name(), and in static
479 let mut init_vec = Vec::new();
480 $(init_vec.push($si_str);)*
481 $(init_vec.push($sk_str);)*
482 $(init_vec.push($rk_str);)*
483 interner::StrInterner::prefill(&init_vec[])
487 // If the special idents get renumbered, remember to modify these two as appropriate
488 pub const SELF_KEYWORD_NAME: ast::Name = ast::Name(SELF_KEYWORD_NAME_NUM);
489 const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM);
490 const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM);
492 pub const SELF_KEYWORD_NAME_NUM: u32 = 1;
493 const STATIC_KEYWORD_NAME_NUM: u32 = 2;
494 const SUPER_KEYWORD_NAME_NUM: u32 = 3;
496 // NB: leaving holes in the ident table is bad! a different ident will get
497 // interned with the id from the hole, but it will be between the min and max
498 // of the reserved words, and thus tagged as "reserved".
500 declare_special_idents_and_keywords! {
501 pub mod special_idents {
502 // These ones are statics
504 (super::SELF_KEYWORD_NAME_NUM, self_, "self");
505 (super::STATIC_KEYWORD_NAME_NUM, statik, "static");
506 (super::SUPER_KEYWORD_NAME_NUM, super_, "super");
507 (4, static_lifetime, "'static");
511 (6, matchers, "matchers");
513 // outside of libsyntax
514 (7, clownshoe_abi, "__rust_abi");
515 (8, opaque, "<opaque>");
516 (9, unnamed_field, "<unnamed_field>");
517 (10, type_self, "Self");
518 (11, prelude_import, "prelude_import");
519 (12, FullRange, "FullRange");
523 // These ones are variants of the Keyword enum
527 (14, Break, "break");
528 (15, Crate, "crate");
531 (18, Extern, "extern");
532 (19, False, "false");
540 (27, Match, "match");
546 (33, Return, "return");
547 // Static and Self are also special idents (prefill de-dupes)
548 (super::STATIC_KEYWORD_NAME_NUM, Static, "static");
549 (super::SELF_KEYWORD_NAME_NUM, Self, "self");
550 (34, Struct, "struct");
551 (super::SUPER_KEYWORD_NAME_NUM, Super, "super");
553 (36, Trait, "trait");
555 (38, Unsafe, "unsafe");
557 (40, Virtual, "virtual");
558 (41, While, "while");
559 (42, Continue, "continue");
562 (45, Const, "const");
563 (46, Where, "where");
565 (47, Alignof, "alignof");
567 (49, Offsetof, "offsetof");
570 (52, Sizeof, "sizeof");
571 (53, Typeof, "typeof");
572 (54, Unsized, "unsized");
573 (55, Yield, "yield");
575 (57, Abstract, "abstract");
576 (58, Final, "final");
577 (59, Override, "override");
578 (60, Macro, "macro");
582 // looks like we can get rid of this completely...
583 pub type IdentInterner = StrInterner;
585 // if an interner exists in TLS, return it. Otherwise, prepare a
587 // FIXME(eddyb) #8726 This should probably use a task-local reference.
588 pub fn get_ident_interner() -> Rc<IdentInterner> {
589 thread_local!(static KEY: Rc<::parse::token::IdentInterner> = {
590 Rc::new(mk_fresh_ident_interner())
592 KEY.with(|k| k.clone())
595 /// Reset the ident interner to its initial state.
596 pub fn reset_ident_interner() {
597 let interner = get_ident_interner();
598 interner.reset(mk_fresh_ident_interner());
601 /// Represents a string stored in the task-local interner. Because the
602 /// interner lives for the life of the task, this can be safely treated as an
603 /// immortal string, as long as it never crosses between tasks.
605 /// FIXME(pcwalton): You must be careful about what you do in the destructors
606 /// of objects stored in TLS, because they may run after the interner is
607 /// destroyed. In particular, they must not access string contents. This can
608 /// be fixed in the future by just leaking all strings until task death
610 #[derive(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
611 pub struct InternedString {
615 impl InternedString {
617 pub fn new(string: &'static str) -> InternedString {
619 string: RcStr::new(string),
624 fn new_from_rc_str(string: RcStr) -> InternedString {
631 pub fn get<'a>(&'a self) -> &'a str {
636 impl Deref for InternedString {
639 fn deref(&self) -> &str { &*self.string }
642 impl BytesContainer for InternedString {
643 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
644 // FIXME #12938: This is a workaround for the incorrect signature
645 // of `BytesContainer`, which is itself a workaround for the lack of
648 let this = self.get();
649 mem::transmute::<&[u8],&[u8]>(this.container_as_bytes())
654 impl fmt::Debug for InternedString {
655 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
656 fmt::Debug::fmt(&self.string[], f)
660 impl fmt::Display for InternedString {
661 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
662 fmt::Display::fmt(&self.string[], f)
666 impl<'a> PartialEq<&'a str> for InternedString {
668 fn eq(&self, other: & &'a str) -> bool {
669 PartialEq::eq(&self.string[], *other)
672 fn ne(&self, other: & &'a str) -> bool {
673 PartialEq::ne(&self.string[], *other)
677 impl<'a> PartialEq<InternedString > for &'a str {
679 fn eq(&self, other: &InternedString) -> bool {
680 PartialEq::eq(*self, &other.string[])
683 fn ne(&self, other: &InternedString) -> bool {
684 PartialEq::ne(*self, &other.string[])
688 impl Decodable for InternedString {
689 fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
690 Ok(get_name(get_ident_interner().intern(&try!(d.read_str())[])))
694 impl Encodable for InternedString {
695 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
696 s.emit_str(&self.string[])
700 /// Returns the string contents of a name, using the task-local interner.
702 pub fn get_name(name: ast::Name) -> InternedString {
703 let interner = get_ident_interner();
704 InternedString::new_from_rc_str(interner.get(name))
707 /// Returns the string contents of an identifier, using the task-local
710 pub fn get_ident(ident: ast::Ident) -> InternedString {
714 /// Interns and returns the string contents of an identifier, using the
715 /// task-local interner.
717 pub fn intern_and_get_ident(s: &str) -> InternedString {
721 /// Maps a string to its interned representation.
723 pub fn intern(s: &str) -> ast::Name {
724 get_ident_interner().intern(s)
727 /// gensym's a new uint, using the current interner.
729 pub fn gensym(s: &str) -> ast::Name {
730 get_ident_interner().gensym(s)
733 /// Maps a string to an identifier with an empty syntax context.
735 pub fn str_to_ident(s: &str) -> ast::Ident {
736 ast::Ident::new(intern(s))
739 /// Maps a string to a gensym'ed identifier.
741 pub fn gensym_ident(s: &str) -> ast::Ident {
742 ast::Ident::new(gensym(s))
745 // create a fresh name that maps to the same string as the old one.
746 // note that this guarantees that str_ptr_eq(ident_to_string(src),interner_get(fresh_name(src)));
747 // that is, that the new name and the old one are connected to ptr_eq strings.
748 pub fn fresh_name(src: &ast::Ident) -> ast::Name {
749 let interner = get_ident_interner();
750 interner.gensym_copy(src.name)
751 // following: debug version. Could work in final except that it's incompatible with
752 // good error messages and uses of struct names in ambiguous could-be-binding
753 // locations. Also definitely destroys the guarantee given above about ptr_eq.
754 /*let num = rand::thread_rng().gen_uint_range(0,0xffff);
755 gensym(format!("{}_{}",ident_to_string(src),num))*/
758 // create a fresh mark.
759 pub fn fresh_mark() -> ast::Mrk {
760 gensym("mark").uint() as u32
769 fn mark_ident(id : ast::Ident, m : ast::Mrk) -> ast::Ident {
770 ast::Ident { name: id.name, ctxt:mtwt::apply_mark(m, id.ctxt) }
773 #[test] fn mtwt_token_eq_test() {
774 assert!(Gt.mtwt_eq(&Gt));
775 let a = str_to_ident("bac");
776 let a1 = mark_ident(a,92);
777 assert!(Ident(a, ModName).mtwt_eq(&Ident(a1, Plain)));