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.
12 use ast::{P, Name, Mrk};
15 use util::interner::{RcStr, StrInterner};
18 use extra::serialize::{Decodable, Decoder, Encodable, Encoder};
23 use std::path::BytesContainer;
25 #[allow(non_camel_case_types)]
26 #[deriving(Clone, Encodable, Decodable, Eq, IterBytes)]
40 #[allow(non_camel_case_types)]
41 #[deriving(Clone, Encodable, Decodable, Eq, IterBytes)]
43 /* Expression-operator symbols. */
58 /* Structural symbols */
82 LIT_INT(i64, ast::IntTy),
83 LIT_UINT(u64, ast::UintTy),
84 LIT_INT_UNSUFFIXED(i64),
85 LIT_FLOAT(ast::Ident, ast::FloatTy),
86 LIT_FLOAT_UNSUFFIXED(ast::Ident),
88 LIT_STR_RAW(ast::Ident, uint), /* raw str delimited by n hash symbols */
91 // an identifier contains an "is_mod_name" boolean,
92 // indicating whether :: follows this token with no
93 // whitespace in between.
94 IDENT(ast::Ident, bool),
98 /* For interpolation */
99 INTERPOLATED(Nonterminal),
101 DOC_COMMENT(ast::Ident),
105 #[deriving(Clone, Encodable, Decodable, Eq, IterBytes)]
106 /// For interpolation during macro expansion.
107 pub enum Nonterminal {
109 NtBlock(P<ast::Block>),
114 NtIdent(~ast::Ident, bool),
115 NtAttr(@ast::Attribute), // #[foo]
117 NtTT( @ast::TokenTree), // needs @ed to break a circularity
118 NtMatchers(~[ast::Matcher])
121 pub fn binop_to_str(o: BinOp) -> ~str {
136 pub fn to_str(input: @IdentInterner, t: &Token) -> ~str {
149 BINOP(op) => binop_to_str(op),
150 BINOPEQ(op) => binop_to_str(op) + "=",
152 /* Structural symbols */
177 char::from_u32(c).unwrap().escape_default(|c| {
184 i.to_str() + ast_util::int_ty_to_str(t)
187 u.to_str() + ast_util::uint_ty_to_str(t)
189 LIT_INT_UNSUFFIXED(i) => { i.to_str() }
190 LIT_FLOAT(ref s, t) => {
191 let body_string = get_ident(s.name);
192 let mut body = body_string.get().to_str();
193 if body.ends_with(".") {
194 body.push_char('0'); // `10.f` is not a float literal
196 body + ast_util::float_ty_to_str(t)
198 LIT_FLOAT_UNSUFFIXED(ref s) => {
199 let body_string = get_ident(s.name);
200 let mut body = body_string.get().to_owned();
201 if body.ends_with(".") {
202 body.push_char('0'); // `10.f` is not a float literal
207 let literal_string = get_ident(s.name);
208 format!("\"{}\"", literal_string.get().escape_default())
210 LIT_STR_RAW(ref s, n) => {
211 let literal_string = get_ident(s.name);
212 format!("r{delim}\"{string}\"{delim}",
213 delim="#".repeat(n), string=literal_string.get())
216 /* Name components */
217 IDENT(s, _) => input.get(s.name).into_owned(),
219 let name = input.get(s.name);
220 format!("'{}", name.as_slice())
225 DOC_COMMENT(ref s) => {
226 let comment_string = get_ident(s.name);
227 comment_string.get().to_str()
230 INTERPOLATED(ref nt) => {
232 &NtExpr(e) => ::print::pprust::expr_to_str(e, input),
233 &NtAttr(e) => ::print::pprust::attribute_to_str(e, input),
235 ~"an interpolated " +
237 NtItem(..) => ~"item",
238 NtBlock(..) => ~"block",
239 NtStmt(..) => ~"statement",
240 NtPat(..) => ~"pattern",
241 NtAttr(..) => fail!("should have been handled"),
242 NtExpr(..) => fail!("should have been handled above"),
244 NtIdent(..) => ~"identifier",
245 NtPath(..) => ~"path",
247 NtMatchers(..) => ~"matcher sequence"
255 pub fn can_begin_expr(t: &Token) -> bool {
264 LIT_INT(_, _) => true,
265 LIT_UINT(_, _) => true,
266 LIT_INT_UNSUFFIXED(_) => true,
267 LIT_FLOAT(_, _) => true,
268 LIT_FLOAT_UNSUFFIXED(_) => true,
270 LIT_STR_RAW(_, _) => true,
274 BINOP(MINUS) => true,
277 BINOP(OR) => true, // in lambda syntax
278 OROR => true, // in lambda syntax
280 INTERPOLATED(NtExpr(..))
281 | INTERPOLATED(NtIdent(..))
282 | INTERPOLATED(NtBlock(..))
283 | INTERPOLATED(NtPath(..)) => true,
288 /// what's the opposite delimiter?
289 pub fn flip_delimiter(t: &token::Token) -> token::Token {
293 LBRACKET => RBRACKET,
296 RBRACKET => LBRACKET,
303 pub fn is_lit(t: &Token) -> bool {
306 LIT_INT(_, _) => true,
307 LIT_UINT(_, _) => true,
308 LIT_INT_UNSUFFIXED(_) => true,
309 LIT_FLOAT(_, _) => true,
310 LIT_FLOAT_UNSUFFIXED(_) => true,
312 LIT_STR_RAW(_, _) => true,
317 pub fn is_ident(t: &Token) -> bool {
318 match *t { IDENT(_, _) => true, _ => false }
321 pub fn is_ident_or_path(t: &Token) -> bool {
323 IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
328 pub fn is_plain_ident(t: &Token) -> bool {
329 match *t { IDENT(_, false) => true, _ => false }
332 pub fn is_bar(t: &Token) -> bool {
333 match *t { BINOP(OR) | OROR => true, _ => false }
336 // Get the first "argument"
338 ( $first:expr, $( $remainder:expr, )* ) => ( $first )
341 // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
343 ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
344 ( $first:expr, ) => ( $first )
347 // In this macro, there is the requirement that the name (the number) must be monotonically
348 // increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
349 // except starting from the next number instead of zero, and with the additional exception that
350 // special identifiers are *also* allowed (they are deduplicated in the important place, the
351 // interner), an exception which is demonstrated by "static" and "self".
352 macro_rules! declare_special_idents_and_keywords {(
353 // So now, in these rules, why is each definition parenthesised?
354 // Answer: otherwise we get a spurious local ambiguity bug on the "}"
355 pub mod special_idents {
356 $( ($si_name:expr, $si_static:ident, $si_str:expr); )*
361 $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
363 $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
366 static STRICT_KEYWORD_START: Name = first!($( $sk_name, )*);
367 static STRICT_KEYWORD_FINAL: Name = last!($( $sk_name, )*);
368 static RESERVED_KEYWORD_START: Name = first!($( $rk_name, )*);
369 static RESERVED_KEYWORD_FINAL: Name = last!($( $rk_name, )*);
371 pub mod special_idents {
373 $( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
377 * All the valid words that have meaning in the Rust language.
379 * Rust keywords are either 'strict' or 'reserved'. Strict keywords may not
380 * appear as identifiers at all. Reserved keywords are not used anywhere in
381 * the language and may not appear as identifiers.
392 pub fn to_ident(&self) -> Ident {
394 $( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
395 $( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
401 fn mk_fresh_ident_interner() -> @IdentInterner {
402 // The indices here must correspond to the numbers in
403 // special_idents, in Keyword to_ident(), and in static
411 @interner::StrInterner::prefill(init_vec)
415 // If the special idents get renumbered, remember to modify these two as appropriate
416 static SELF_KEYWORD_NAME: Name = 3;
417 static STATIC_KEYWORD_NAME: Name = 10;
419 declare_special_idents_and_keywords! {
420 pub mod special_idents {
421 // These ones are statics
424 (1, invalid, ""); // ''
425 (2, clownshoes_extensions, "__extensions__");
427 (super::SELF_KEYWORD_NAME, self_, "self"); // 'self'
431 (5, matchers, "matchers");
433 // outside of libsyntax
435 (7, clownshoe_abi, "__rust_abi");
437 (9, opaque, "<opaque>");
438 (super::STATIC_KEYWORD_NAME, statik, "static");
439 (11, clownshoes_foreign_mod, "__foreign_mod__");
440 (12, unnamed_field, "<unnamed_field>");
441 (13, type_self, "Self"); // `Self`
445 // These ones are variants of the Keyword enum
449 (15, Break, "break");
450 (16, Const, "const");
453 (19, Extern, "extern");
454 (20, False, "false");
461 (27, __LogLevel, "__log_level");
463 (29, Match, "match");
470 (36, Return, "return");
471 // Static and Self are also special idents (prefill de-dupes)
472 (super::STATIC_KEYWORD_NAME, Static, "static");
473 (super::SELF_KEYWORD_NAME, Self, "self");
474 (37, Struct, "struct");
475 (38, Super, "super");
477 (40, Trait, "trait");
479 (42, Unsafe, "unsafe");
481 (44, While, "while");
482 (45, Continue, "continue");
487 (48, Alignof, "alignof");
489 (50, Offsetof, "offsetof");
491 (52, Sizeof, "sizeof");
492 (53, Typeof, "typeof");
493 (54, Unsized, "unsized");
494 (55, Yield, "yield");
499 * Maps a token to a record specifying the corresponding binary
502 pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
504 BINOP(STAR) => Some(ast::BiMul),
505 BINOP(SLASH) => Some(ast::BiDiv),
506 BINOP(PERCENT) => Some(ast::BiRem),
507 BINOP(PLUS) => Some(ast::BiAdd),
508 BINOP(MINUS) => Some(ast::BiSub),
509 BINOP(SHL) => Some(ast::BiShl),
510 BINOP(SHR) => Some(ast::BiShr),
511 BINOP(AND) => Some(ast::BiBitAnd),
512 BINOP(CARET) => Some(ast::BiBitXor),
513 BINOP(OR) => Some(ast::BiBitOr),
514 LT => Some(ast::BiLt),
515 LE => Some(ast::BiLe),
516 GE => Some(ast::BiGe),
517 GT => Some(ast::BiGt),
518 EQEQ => Some(ast::BiEq),
519 NE => Some(ast::BiNe),
520 ANDAND => Some(ast::BiAnd),
521 OROR => Some(ast::BiOr),
526 // looks like we can get rid of this completely...
527 pub type IdentInterner = StrInterner;
529 // if an interner exists in TLS, return it. Otherwise, prepare a
531 pub fn get_ident_interner() -> @IdentInterner {
532 local_data_key!(key: @@::parse::token::IdentInterner)
533 match local_data::get(key, |k| k.map(|k| *k)) {
534 Some(interner) => *interner,
536 let interner = mk_fresh_ident_interner();
537 local_data::set(key, @interner);
543 /// Represents a string stored in the task-local interner. Because the
544 /// interner lives for the life of the task, this can be safely treated as an
545 /// immortal string, as long as it never crosses between tasks.
547 /// XXX(pcwalton): You must be careful about what you do in the destructors of
548 /// objects stored in TLS, because they may run after the interner is
549 /// destroyed. In particular, they must not access string contents. This can
550 /// be fixed in the future by just leaking all strings until task death
553 #[deriving(Clone, Eq, IterBytes, Ord, TotalEq, TotalOrd)]
554 pub struct InternedString {
559 impl Drop for InternedString {
561 // No-op just to make this not implicitly copyable.
565 impl InternedString {
567 pub fn new(string: &'static str) -> InternedString {
569 string: RcStr::new(string),
574 fn new_from_rc_str(string: RcStr) -> InternedString {
581 pub fn get<'a>(&'a self) -> &'a str {
582 self.string.as_slice()
586 impl BytesContainer for InternedString {
587 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
588 // XXX(pcwalton): This is a workaround for the incorrect signature of
589 // `BytesContainer`, which is itself a workaround for the lack of DST.
591 let this = self.get();
592 cast::transmute(this.container_as_bytes())
597 impl fmt::Default for InternedString {
598 fn fmt(obj: &InternedString, f: &mut fmt::Formatter) {
599 write!(f.buf, "{}", obj.string.as_slice());
603 impl<'a> Equiv<&'a str> for InternedString {
604 fn equiv(&self, other: & &'a str) -> bool {
605 (*other) == self.string.as_slice()
609 impl<D:Decoder> Decodable<D> for InternedString {
610 fn decode(d: &mut D) -> InternedString {
611 let interner = get_ident_interner();
612 get_ident(interner.intern(d.read_str()))
616 impl<E:Encoder> Encodable<E> for InternedString {
617 fn encode(&self, e: &mut E) {
618 e.emit_str(self.string.as_slice())
622 /// Returns the string contents of an identifier, using the task-local
625 pub fn get_ident(idx: Name) -> InternedString {
626 let interner = get_ident_interner();
627 InternedString::new_from_rc_str(interner.get(idx))
630 /// Interns and returns the string contents of an identifier, using the
631 /// task-local interner.
633 pub fn intern_and_get_ident(s: &str) -> InternedString {
637 /* for when we don't care about the contents; doesn't interact with TLD or
639 pub fn mk_fake_ident_interner() -> @IdentInterner {
640 @interner::StrInterner::new()
643 // maps a string to its interned representation
645 pub fn intern(str : &str) -> Name {
646 let interner = get_ident_interner();
650 // gensyms a new uint, using the current interner
651 pub fn gensym(str : &str) -> Name {
652 let interner = get_ident_interner();
656 // maps a string to an identifier with an empty syntax context
657 pub fn str_to_ident(str : &str) -> ast::Ident {
658 ast::Ident::new(intern(str))
661 // maps a string to a gensym'ed identifier
662 pub fn gensym_ident(str : &str) -> ast::Ident {
663 ast::Ident::new(gensym(str))
666 // create a fresh name that maps to the same string as the old one.
667 // note that this guarantees that str_ptr_eq(ident_to_str(src),interner_get(fresh_name(src)));
668 // that is, that the new name and the old one are connected to ptr_eq strings.
669 pub fn fresh_name(src : &ast::Ident) -> Name {
670 let interner = get_ident_interner();
671 interner.gensym_copy(src.name)
672 // following: debug version. Could work in final except that it's incompatible with
673 // good error messages and uses of struct names in ambiguous could-be-binding
674 // locations. Also definitely destroys the guarantee given above about ptr_eq.
675 /*let num = rand::rng().gen_uint_range(0,0xffff);
676 gensym(format!("{}_{}",ident_to_str(src),num))*/
679 // create a fresh mark.
680 pub fn fresh_mark() -> Mrk {
684 // See the macro above about the types of keywords
686 pub fn is_keyword(kw: keywords::Keyword, tok: &Token) -> bool {
688 token::IDENT(sid, false) => { kw.to_ident().name == sid.name }
693 pub fn is_any_keyword(tok: &Token) -> bool {
695 token::IDENT(sid, false) => match sid.name {
696 SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
697 STRICT_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
704 pub fn is_strict_keyword(tok: &Token) -> bool {
706 token::IDENT(sid, false) => match sid.name {
707 SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
708 STRICT_KEYWORD_START .. STRICT_KEYWORD_FINAL => true,
715 pub fn is_reserved_keyword(tok: &Token) -> bool {
717 token::IDENT(sid, false) => match sid.name {
718 RESERVED_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
725 pub fn mtwt_token_eq(t1 : &Token, t2 : &Token) -> bool {
727 (&IDENT(id1,_),&IDENT(id2,_)) =>
728 ast_util::mtwt_resolve(id1) == ast_util::mtwt_resolve(id2),
740 fn mark_ident(id : ast::Ident, m : ast::Mrk) -> ast::Ident {
741 ast::Ident{name:id.name,ctxt:ast_util::new_mark(m,id.ctxt)}
744 #[test] fn mtwt_token_eq_test() {
745 assert!(mtwt_token_eq(>,>));
746 let a = str_to_ident("bac");
747 let a1 = mark_ident(a,92);
748 assert!(mtwt_token_eq(&IDENT(a,true),&IDENT(a1,false)));