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)]
71 StrRaw(ast::Name, uint), /* raw str delimited by n hash symbols */
73 BinaryRaw(ast::Name, uint), /* raw binary str delimited by n hash symbols */
77 pub fn short_name(&self) -> &'static str {
81 Integer(_) => "integer",
83 Str_(_) | StrRaw(..) => "str",
84 Binary(_) | BinaryRaw(..) => "binary str"
89 #[allow(non_camel_case_types)]
90 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show)]
92 /* Expression-operator symbols. */
107 /* Structural symbols */
122 /// An opening delimeter, eg. `{`
123 OpenDelim(DelimToken),
124 /// A closing delimeter, eg. `}`
125 CloseDelim(DelimToken),
128 Literal(Lit, Option<ast::Name>),
130 /* Name components */
131 Ident(ast::Ident, IdentStyle),
133 Lifetime(ast::Ident),
135 /* For interpolation */
136 Interpolated(Nonterminal),
137 // Can be expanded into several tokens.
139 DocComment(ast::Name),
140 // In left-hand-sides of MBE macros:
141 /// Parse a nonterminal (name to bind, name of NT, styles of their idents)
142 MatchNt(ast::Ident, ast::Ident, IdentStyle, IdentStyle),
143 // In right-hand-sides of MBE macros:
144 /// A syntactic variable that will be filled in by macro expansion.
145 SubstNt(ast::Ident, IdentStyle),
147 // Junk. These carry no data because we don't really care about the data
148 // they *would* carry, and don't really want to allocate a new ident for
149 // them. Instead, users could extract that from the associated span.
161 /// Returns `true` if the token can appear at the start of an expression.
162 pub fn can_begin_expr(&self) -> bool {
164 OpenDelim(_) => true,
168 Literal(_, _) => true,
172 BinOp(Minus) => true,
175 BinOp(Or) => true, // in lambda syntax
176 OrOr => true, // in lambda syntax
178 Interpolated(NtExpr(..)) => true,
179 Interpolated(NtIdent(..)) => true,
180 Interpolated(NtBlock(..)) => true,
181 Interpolated(NtPath(..)) => true,
186 /// Returns `true` if the token is any literal
187 pub fn is_lit(&self) -> bool {
189 Literal(_, _) => true,
194 /// Returns `true` if the token is an identifier.
195 pub fn is_ident(&self) -> bool {
202 /// Returns `true` if the token is an interpolated path.
203 pub fn is_path(&self) -> bool {
205 Interpolated(NtPath(..)) => true,
210 /// Returns `true` if the token is a path that is not followed by a `::`
212 #[allow(non_upper_case_globals)]
213 pub fn is_plain_ident(&self) -> bool {
215 Ident(_, Plain) => true,
220 /// Returns `true` if the token is a lifetime.
221 pub fn is_lifetime(&self) -> bool {
223 Lifetime(..) => true,
228 /// Returns `true` if the token is either the `mut` or `const` keyword.
229 pub fn is_mutability(&self) -> bool {
230 self.is_keyword(keywords::Mut) ||
231 self.is_keyword(keywords::Const)
234 /// Maps a token to its corresponding binary operator.
235 pub fn to_binop(&self) -> Option<ast::BinOp> {
237 BinOp(Star) => Some(ast::BiMul),
238 BinOp(Slash) => Some(ast::BiDiv),
239 BinOp(Percent) => Some(ast::BiRem),
240 BinOp(Plus) => Some(ast::BiAdd),
241 BinOp(Minus) => Some(ast::BiSub),
242 BinOp(Shl) => Some(ast::BiShl),
243 BinOp(Shr) => Some(ast::BiShr),
244 BinOp(And) => Some(ast::BiBitAnd),
245 BinOp(Caret) => Some(ast::BiBitXor),
246 BinOp(Or) => Some(ast::BiBitOr),
247 Lt => Some(ast::BiLt),
248 Le => Some(ast::BiLe),
249 Ge => Some(ast::BiGe),
250 Gt => Some(ast::BiGt),
251 EqEq => Some(ast::BiEq),
252 Ne => Some(ast::BiNe),
253 AndAnd => Some(ast::BiAnd),
254 OrOr => Some(ast::BiOr),
259 /// Returns `true` if the token is a given keyword, `kw`.
260 #[allow(non_upper_case_globals)]
261 pub fn is_keyword(&self, kw: keywords::Keyword) -> bool {
263 Ident(sid, Plain) => kw.to_name() == sid.name,
268 /// Returns `true` if the token is either a special identifier, or a strict
269 /// or reserved keyword.
270 #[allow(non_upper_case_globals)]
271 pub fn is_any_keyword(&self) -> bool {
273 Ident(sid, Plain) => {
276 n == SELF_KEYWORD_NAME
277 || n == STATIC_KEYWORD_NAME
278 || n == SUPER_KEYWORD_NAME
279 || STRICT_KEYWORD_START <= n
280 && n <= RESERVED_KEYWORD_FINAL
286 /// Returns `true` if the token may not appear as an identifier.
287 #[allow(non_upper_case_globals)]
288 pub fn is_strict_keyword(&self) -> bool {
290 Ident(sid, Plain) => {
293 n == SELF_KEYWORD_NAME
294 || n == STATIC_KEYWORD_NAME
295 || n == SUPER_KEYWORD_NAME
296 || STRICT_KEYWORD_START <= n
297 && n <= STRICT_KEYWORD_FINAL
299 Ident(sid, ModName) => {
302 n != SELF_KEYWORD_NAME
303 && n != SUPER_KEYWORD_NAME
304 && STRICT_KEYWORD_START <= n
305 && n <= STRICT_KEYWORD_FINAL
311 /// Returns `true` if the token is a keyword that has been reserved for
312 /// possible future use.
313 #[allow(non_upper_case_globals)]
314 pub fn is_reserved_keyword(&self) -> bool {
316 Ident(sid, Plain) => {
319 RESERVED_KEYWORD_START <= n
320 && n <= RESERVED_KEYWORD_FINAL
326 /// Hygienic identifier equality comparison.
328 /// See `styntax::ext::mtwt`.
329 pub fn mtwt_eq(&self, other : &Token) -> bool {
330 match (self, other) {
331 (&Ident(id1,_), &Ident(id2,_)) | (&Lifetime(id1), &Lifetime(id2)) =>
332 mtwt::resolve(id1) == mtwt::resolve(id2),
338 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash)]
339 /// For interpolation during macro expansion.
340 pub enum Nonterminal {
341 NtItem(P<ast::Item>),
342 NtBlock(P<ast::Block>),
343 NtStmt(P<ast::Stmt>),
345 NtExpr(P<ast::Expr>),
347 NtIdent(Box<ast::Ident>, IdentStyle),
348 /// Stuff inside brackets for attributes
349 NtMeta(P<ast::MetaItem>),
350 NtPath(Box<ast::Path>),
351 NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity
354 impl fmt::Show for Nonterminal {
355 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
357 NtItem(..) => f.pad("NtItem(..)"),
358 NtBlock(..) => f.pad("NtBlock(..)"),
359 NtStmt(..) => f.pad("NtStmt(..)"),
360 NtPat(..) => f.pad("NtPat(..)"),
361 NtExpr(..) => f.pad("NtExpr(..)"),
362 NtTy(..) => f.pad("NtTy(..)"),
363 NtIdent(..) => f.pad("NtIdent(..)"),
364 NtMeta(..) => f.pad("NtMeta(..)"),
365 NtPath(..) => f.pad("NtPath(..)"),
366 NtTT(..) => f.pad("NtTT(..)"),
371 // Get the first "argument"
373 ( $first:expr, $( $remainder:expr, )* ) => ( $first )
376 // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
378 ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
379 ( $first:expr, ) => ( $first )
382 // In this macro, there is the requirement that the name (the number) must be monotonically
383 // increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
384 // except starting from the next number instead of zero, and with the additional exception that
385 // special identifiers are *also* allowed (they are deduplicated in the important place, the
386 // interner), an exception which is demonstrated by "static" and "self".
387 macro_rules! declare_special_idents_and_keywords {(
388 // So now, in these rules, why is each definition parenthesised?
389 // Answer: otherwise we get a spurious local ambiguity bug on the "}"
390 pub mod special_idents {
391 $( ($si_name:expr, $si_static:ident, $si_str:expr); )*
396 $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
398 $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
401 static STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*);
402 static STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*);
403 static RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*);
404 static RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*);
406 pub mod special_idents {
409 #[allow(non_upper_case_globals)]
410 pub const $si_static: ast::Ident = ast::Ident {
411 name: ast::Name($si_name),
417 pub mod special_names {
420 #[allow(non_upper_case_globals)]
421 pub const $si_static: ast::Name = ast::Name($si_name);
425 /// All the valid words that have meaning in the Rust language.
427 /// Rust keywords are either 'strict' or 'reserved'. Strict keywords may not
428 /// appear as identifiers at all. Reserved keywords are not used anywhere in
429 /// the language and may not appear as identifiers.
431 pub use self::Keyword::*;
441 pub fn to_name(&self) -> ast::Name {
443 $( $sk_variant => ast::Name($sk_name), )*
444 $( $rk_variant => ast::Name($rk_name), )*
450 fn mk_fresh_ident_interner() -> IdentInterner {
451 // The indices here must correspond to the numbers in
452 // special_idents, in Keyword to_name(), and in static
454 let mut init_vec = Vec::new();
455 $(init_vec.push($si_str);)*
456 $(init_vec.push($sk_str);)*
457 $(init_vec.push($rk_str);)*
458 interner::StrInterner::prefill(init_vec[])
462 // If the special idents get renumbered, remember to modify these two as appropriate
463 pub const SELF_KEYWORD_NAME: ast::Name = ast::Name(SELF_KEYWORD_NAME_NUM);
464 const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM);
465 const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM);
467 pub const SELF_KEYWORD_NAME_NUM: u32 = 1;
468 const STATIC_KEYWORD_NAME_NUM: u32 = 2;
469 const SUPER_KEYWORD_NAME_NUM: u32 = 3;
471 // NB: leaving holes in the ident table is bad! a different ident will get
472 // interned with the id from the hole, but it will be between the min and max
473 // of the reserved words, and thus tagged as "reserved".
475 declare_special_idents_and_keywords! {
476 pub mod special_idents {
477 // These ones are statics
479 (super::SELF_KEYWORD_NAME_NUM, self_, "self");
480 (super::STATIC_KEYWORD_NAME_NUM, statik, "static");
481 (super::SUPER_KEYWORD_NAME_NUM, super_, "super");
482 (4, static_lifetime, "'static");
486 (6, matchers, "matchers");
488 // outside of libsyntax
489 (7, clownshoe_abi, "__rust_abi");
490 (8, opaque, "<opaque>");
491 (9, unnamed_field, "<unnamed_field>");
492 (10, type_self, "Self");
493 (11, prelude_import, "prelude_import");
497 // These ones are variants of the Keyword enum
501 (13, Break, "break");
502 (14, Crate, "crate");
505 (17, Extern, "extern");
506 (18, False, "false");
514 (26, Match, "match");
520 (32, Return, "return");
521 // Static and Self are also special idents (prefill de-dupes)
522 (super::STATIC_KEYWORD_NAME_NUM, Static, "static");
523 (super::SELF_KEYWORD_NAME_NUM, Self, "self");
524 (33, Struct, "struct");
525 (super::SUPER_KEYWORD_NAME_NUM, Super, "super");
527 (35, Trait, "trait");
529 (37, Unsafe, "unsafe");
531 (39, Virtual, "virtual");
532 (40, While, "while");
533 (41, Continue, "continue");
536 (44, Const, "const");
537 (45, Where, "where");
540 (46, Alignof, "alignof");
542 (48, Offsetof, "offsetof");
545 (51, Sizeof, "sizeof");
546 (52, Typeof, "typeof");
547 (53, Unsized, "unsized");
548 (54, Yield, "yield");
550 (56, Abstract, "abstract");
551 (57, Final, "final");
552 (58, Override, "override");
556 // looks like we can get rid of this completely...
557 pub type IdentInterner = StrInterner;
559 // if an interner exists in TLS, return it. Otherwise, prepare a
561 // FIXME(eddyb) #8726 This should probably use a task-local reference.
562 pub fn get_ident_interner() -> Rc<IdentInterner> {
563 thread_local!(static KEY: Rc<::parse::token::IdentInterner> = {
564 Rc::new(mk_fresh_ident_interner())
566 KEY.with(|k| k.clone())
569 /// Reset the ident interner to its initial state.
570 pub fn reset_ident_interner() {
571 let interner = get_ident_interner();
572 interner.reset(mk_fresh_ident_interner());
575 /// Represents a string stored in the task-local interner. Because the
576 /// interner lives for the life of the task, this can be safely treated as an
577 /// immortal string, as long as it never crosses between tasks.
579 /// FIXME(pcwalton): You must be careful about what you do in the destructors
580 /// of objects stored in TLS, because they may run after the interner is
581 /// destroyed. In particular, they must not access string contents. This can
582 /// be fixed in the future by just leaking all strings until task death
584 #[derive(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
585 pub struct InternedString {
589 impl InternedString {
591 pub fn new(string: &'static str) -> InternedString {
593 string: RcStr::new(string),
598 fn new_from_rc_str(string: RcStr) -> InternedString {
605 pub fn get<'a>(&'a self) -> &'a str {
610 impl Deref for InternedString {
613 fn deref(&self) -> &str { &*self.string }
616 impl BytesContainer for InternedString {
617 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
618 // FIXME #12938: This is a workaround for the incorrect signature
619 // of `BytesContainer`, which is itself a workaround for the lack of
622 let this = self.get();
623 mem::transmute::<&[u8],&[u8]>(this.container_as_bytes())
628 impl fmt::Show for InternedString {
629 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
630 write!(f, "{}", self.string[])
634 impl<'a> PartialEq<&'a str> for InternedString {
636 fn eq(&self, other: & &'a str) -> bool {
637 PartialEq::eq(self.string[], *other)
640 fn ne(&self, other: & &'a str) -> bool {
641 PartialEq::ne(self.string[], *other)
645 impl<'a> PartialEq<InternedString > for &'a str {
647 fn eq(&self, other: &InternedString) -> bool {
648 PartialEq::eq(*self, other.string[])
651 fn ne(&self, other: &InternedString) -> bool {
652 PartialEq::ne(*self, other.string[])
656 impl<D:Decoder<E>, E> Decodable<D, E> for InternedString {
657 fn decode(d: &mut D) -> Result<InternedString, E> {
658 Ok(get_name(get_ident_interner().intern(
659 try!(d.read_str())[])))
663 impl<S:Encoder<E>, E> Encodable<S, E> for InternedString {
664 fn encode(&self, s: &mut S) -> Result<(), E> {
665 s.emit_str(self.string[])
669 /// Returns the string contents of a name, using the task-local interner.
671 pub fn get_name(name: ast::Name) -> InternedString {
672 let interner = get_ident_interner();
673 InternedString::new_from_rc_str(interner.get(name))
676 /// Returns the string contents of an identifier, using the task-local
679 pub fn get_ident(ident: ast::Ident) -> InternedString {
683 /// Interns and returns the string contents of an identifier, using the
684 /// task-local interner.
686 pub fn intern_and_get_ident(s: &str) -> InternedString {
690 /// Maps a string to its interned representation.
692 pub fn intern(s: &str) -> ast::Name {
693 get_ident_interner().intern(s)
696 /// gensym's a new uint, using the current interner.
698 pub fn gensym(s: &str) -> ast::Name {
699 get_ident_interner().gensym(s)
702 /// Maps a string to an identifier with an empty syntax context.
704 pub fn str_to_ident(s: &str) -> ast::Ident {
705 ast::Ident::new(intern(s))
708 /// Maps a string to a gensym'ed identifier.
710 pub fn gensym_ident(s: &str) -> ast::Ident {
711 ast::Ident::new(gensym(s))
714 // create a fresh name that maps to the same string as the old one.
715 // note that this guarantees that str_ptr_eq(ident_to_string(src),interner_get(fresh_name(src)));
716 // that is, that the new name and the old one are connected to ptr_eq strings.
717 pub fn fresh_name(src: &ast::Ident) -> ast::Name {
718 let interner = get_ident_interner();
719 interner.gensym_copy(src.name)
720 // following: debug version. Could work in final except that it's incompatible with
721 // good error messages and uses of struct names in ambiguous could-be-binding
722 // locations. Also definitely destroys the guarantee given above about ptr_eq.
723 /*let num = rand::thread_rng().gen_uint_range(0,0xffff);
724 gensym(format!("{}_{}",ident_to_string(src),num))*/
727 // create a fresh mark.
728 pub fn fresh_mark() -> ast::Mrk {
729 gensym("mark").uint() as u32
738 fn mark_ident(id : ast::Ident, m : ast::Mrk) -> ast::Ident {
739 ast::Ident { name: id.name, ctxt:mtwt::apply_mark(m, id.ctxt) }
742 #[test] fn mtwt_token_eq_test() {
743 assert!(Gt.mtwt_eq(&Gt));
744 let a = str_to_ident("bac");
745 let a1 = mark_ident(a,92);
746 assert!(Ident(a, ModName).mtwt_eq(&Ident(a1, Plain)));