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, Ident, Name, Mrk};
16 use util::interner::{RcStr, StrInterner};
19 use serialize::{Decodable, Decoder, Encodable, Encoder};
24 use std::path::BytesContainer;
27 #[allow(non_camel_case_types)]
28 #[deriving(Clone, Encodable, Decodable, Eq, Hash, Show)]
42 #[allow(non_camel_case_types)]
43 #[deriving(Clone, Encodable, Decodable, Eq, Hash, Show)]
45 /* Expression-operator symbols. */
60 /* Structural symbols */
84 LIT_INT(i64, ast::IntTy),
85 LIT_UINT(u64, ast::UintTy),
86 LIT_INT_UNSUFFIXED(i64),
87 LIT_FLOAT(ast::Ident, ast::FloatTy),
88 LIT_FLOAT_UNSUFFIXED(ast::Ident),
90 LIT_STR_RAW(ast::Ident, uint), /* raw str delimited by n hash symbols */
93 // an identifier contains an "is_mod_name" boolean,
94 // indicating whether :: follows this token with no
95 // whitespace in between.
96 IDENT(ast::Ident, bool),
100 /* For interpolation */
101 INTERPOLATED(Nonterminal),
103 DOC_COMMENT(ast::Ident),
107 #[deriving(Clone, Encodable, Decodable, Eq, Hash)]
108 /// For interpolation during macro expansion.
109 pub enum Nonterminal {
111 NtBlock(P<ast::Block>),
116 NtIdent(~ast::Ident, bool),
117 NtAttr(@ast::Attribute), // #[foo]
119 NtTT( @ast::TokenTree), // needs @ed to break a circularity
120 NtMatchers(Vec<ast::Matcher> )
123 impl fmt::Show for Nonterminal {
124 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
126 NtItem(..) => f.pad("NtItem(..)"),
127 NtBlock(..) => f.pad("NtBlock(..)"),
128 NtStmt(..) => f.pad("NtStmt(..)"),
129 NtPat(..) => f.pad("NtPat(..)"),
130 NtExpr(..) => f.pad("NtExpr(..)"),
131 NtTy(..) => f.pad("NtTy(..)"),
132 NtIdent(..) => f.pad("NtIdent(..)"),
133 NtAttr(..) => f.pad("NtAttr(..)"),
134 NtPath(..) => f.pad("NtPath(..)"),
135 NtTT(..) => f.pad("NtTT(..)"),
136 NtMatchers(..) => f.pad("NtMatchers(..)"),
141 pub fn binop_to_str(o: BinOp) -> ~str {
156 pub fn to_str(t: &Token) -> ~str {
169 BINOP(op) => binop_to_str(op),
170 BINOPEQ(op) => binop_to_str(op) + "=",
172 /* Structural symbols */
197 char::from_u32(c).unwrap().escape_default(|c| {
204 i.to_str() + ast_util::int_ty_to_str(t)
207 u.to_str() + ast_util::uint_ty_to_str(t)
209 LIT_INT_UNSUFFIXED(i) => { i.to_str() }
211 let mut body = get_ident(s).get().to_str();
212 if body.ends_with(".") {
213 body.push_char('0'); // `10.f` is not a float literal
215 body + ast_util::float_ty_to_str(t)
217 LIT_FLOAT_UNSUFFIXED(s) => {
218 let mut body = get_ident(s).get().to_str();
219 if body.ends_with(".") {
220 body.push_char('0'); // `10.f` is not a float literal
225 format!("\"{}\"", get_ident(s).get().escape_default())
227 LIT_STR_RAW(s, n) => {
228 format!("r{delim}\"{string}\"{delim}",
229 delim="#".repeat(n), string=get_ident(s))
232 /* Name components */
233 IDENT(s, _) => get_ident(s).get().to_str(),
235 format!("'{}", get_ident(s))
240 DOC_COMMENT(s) => get_ident(s).get().to_str(),
242 INTERPOLATED(ref nt) => {
244 &NtExpr(e) => ::print::pprust::expr_to_str(e),
245 &NtAttr(e) => ::print::pprust::attribute_to_str(e),
247 ~"an interpolated " +
249 NtItem(..) => ~"item",
250 NtBlock(..) => ~"block",
251 NtStmt(..) => ~"statement",
252 NtPat(..) => ~"pattern",
253 NtAttr(..) => fail!("should have been handled"),
254 NtExpr(..) => fail!("should have been handled above"),
256 NtIdent(..) => ~"identifier",
257 NtPath(..) => ~"path",
259 NtMatchers(..) => ~"matcher sequence"
267 pub fn can_begin_expr(t: &Token) -> bool {
276 LIT_INT(_, _) => true,
277 LIT_UINT(_, _) => true,
278 LIT_INT_UNSUFFIXED(_) => true,
279 LIT_FLOAT(_, _) => true,
280 LIT_FLOAT_UNSUFFIXED(_) => true,
282 LIT_STR_RAW(_, _) => true,
286 BINOP(MINUS) => true,
289 BINOP(OR) => true, // in lambda syntax
290 OROR => true, // in lambda syntax
292 INTERPOLATED(NtExpr(..))
293 | INTERPOLATED(NtIdent(..))
294 | INTERPOLATED(NtBlock(..))
295 | INTERPOLATED(NtPath(..)) => true,
300 /// what's the opposite delimiter?
301 pub fn flip_delimiter(t: &token::Token) -> token::Token {
305 LBRACKET => RBRACKET,
308 RBRACKET => LBRACKET,
315 pub fn is_lit(t: &Token) -> bool {
318 LIT_INT(_, _) => true,
319 LIT_UINT(_, _) => true,
320 LIT_INT_UNSUFFIXED(_) => true,
321 LIT_FLOAT(_, _) => true,
322 LIT_FLOAT_UNSUFFIXED(_) => true,
324 LIT_STR_RAW(_, _) => true,
329 pub fn is_ident(t: &Token) -> bool {
330 match *t { IDENT(_, _) => true, _ => false }
333 pub fn is_ident_or_path(t: &Token) -> bool {
335 IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
340 pub fn is_plain_ident(t: &Token) -> bool {
341 match *t { IDENT(_, false) => true, _ => false }
344 pub fn is_bar(t: &Token) -> bool {
345 match *t { BINOP(OR) | OROR => true, _ => false }
348 // Get the first "argument"
350 ( $first:expr, $( $remainder:expr, )* ) => ( $first )
353 // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
355 ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
356 ( $first:expr, ) => ( $first )
359 // In this macro, there is the requirement that the name (the number) must be monotonically
360 // increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
361 // except starting from the next number instead of zero, and with the additional exception that
362 // special identifiers are *also* allowed (they are deduplicated in the important place, the
363 // interner), an exception which is demonstrated by "static" and "self".
364 macro_rules! declare_special_idents_and_keywords {(
365 // So now, in these rules, why is each definition parenthesised?
366 // Answer: otherwise we get a spurious local ambiguity bug on the "}"
367 pub mod special_idents {
368 $( ($si_name:expr, $si_static:ident, $si_str:expr); )*
373 $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
375 $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
378 static STRICT_KEYWORD_START: Name = first!($( $sk_name, )*);
379 static STRICT_KEYWORD_FINAL: Name = last!($( $sk_name, )*);
380 static RESERVED_KEYWORD_START: Name = first!($( $rk_name, )*);
381 static RESERVED_KEYWORD_FINAL: Name = last!($( $rk_name, )*);
383 pub mod special_idents {
385 $( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
389 * All the valid words that have meaning in the Rust language.
391 * Rust keywords are either 'strict' or 'reserved'. Strict keywords may not
392 * appear as identifiers at all. Reserved keywords are not used anywhere in
393 * the language and may not appear as identifiers.
404 pub fn to_ident(&self) -> Ident {
406 $( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
407 $( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
413 fn mk_fresh_ident_interner() -> IdentInterner {
414 // The indices here must correspond to the numbers in
415 // special_idents, in Keyword to_ident(), and in static
417 let mut init_vec = Vec::new();
418 $(init_vec.push($si_str);)*
419 $(init_vec.push($sk_str);)*
420 $(init_vec.push($rk_str);)*
421 interner::StrInterner::prefill(init_vec.as_slice())
425 // If the special idents get renumbered, remember to modify these two as appropriate
426 static SELF_KEYWORD_NAME: Name = 1;
427 static STATIC_KEYWORD_NAME: Name = 2;
429 declare_special_idents_and_keywords! {
430 pub mod special_idents {
431 // These ones are statics
433 (super::SELF_KEYWORD_NAME, self_, "self");
434 (super::STATIC_KEYWORD_NAME, statik, "static");
438 (4, matchers, "matchers");
440 // outside of libsyntax
441 (5, clownshoe_abi, "__rust_abi");
442 (6, opaque, "<opaque>");
443 (7, unnamed_field, "<unnamed_field>");
444 (8, type_self, "Self");
448 // These ones are variants of the Keyword enum
452 (10, Break, "break");
453 (11, Const, "const");
454 (12, Crate, "crate");
457 (15, Extern, "extern");
458 (16, False, "false");
465 (23, __LogLevel, "__log_level");
467 (25, Match, "match");
474 (32, Return, "return");
475 // Static and Self are also special idents (prefill de-dupes)
476 (super::STATIC_KEYWORD_NAME, Static, "static");
477 (super::SELF_KEYWORD_NAME, Self, "self");
478 (33, Struct, "struct");
479 (34, Super, "super");
481 (36, Trait, "trait");
483 (38, Unsafe, "unsafe");
485 (40, While, "while");
486 (41, Continue, "continue");
491 (44, Alignof, "alignof");
493 (46, Offsetof, "offsetof");
495 (48, Sizeof, "sizeof");
496 (49, Typeof, "typeof");
497 (50, Unsized, "unsized");
498 (51, Yield, "yield");
504 * Maps a token to a record specifying the corresponding binary
507 pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
509 BINOP(STAR) => Some(ast::BiMul),
510 BINOP(SLASH) => Some(ast::BiDiv),
511 BINOP(PERCENT) => Some(ast::BiRem),
512 BINOP(PLUS) => Some(ast::BiAdd),
513 BINOP(MINUS) => Some(ast::BiSub),
514 BINOP(SHL) => Some(ast::BiShl),
515 BINOP(SHR) => Some(ast::BiShr),
516 BINOP(AND) => Some(ast::BiBitAnd),
517 BINOP(CARET) => Some(ast::BiBitXor),
518 BINOP(OR) => Some(ast::BiBitOr),
519 LT => Some(ast::BiLt),
520 LE => Some(ast::BiLe),
521 GE => Some(ast::BiGe),
522 GT => Some(ast::BiGt),
523 EQEQ => Some(ast::BiEq),
524 NE => Some(ast::BiNe),
525 ANDAND => Some(ast::BiAnd),
526 OROR => Some(ast::BiOr),
531 // looks like we can get rid of this completely...
532 pub type IdentInterner = StrInterner;
534 // if an interner exists in TLS, return it. Otherwise, prepare a
536 pub fn get_ident_interner() -> @IdentInterner {
537 local_data_key!(key: @::parse::token::IdentInterner)
538 match local_data::get(key, |k| k.map(|k| *k)) {
539 Some(interner) => interner,
541 let interner = @mk_fresh_ident_interner();
542 local_data::set(key, interner);
548 /// Represents a string stored in the task-local interner. Because the
549 /// interner lives for the life of the task, this can be safely treated as an
550 /// immortal string, as long as it never crosses between tasks.
552 /// FIXME(pcwalton): You must be careful about what you do in the destructors
553 /// of objects stored in TLS, because they may run after the interner is
554 /// destroyed. In particular, they must not access string contents. This can
555 /// be fixed in the future by just leaking all strings until task death
557 #[deriving(Clone, Eq, Hash, Ord, TotalEq, TotalOrd)]
558 pub struct InternedString {
562 impl InternedString {
564 pub fn new(string: &'static str) -> InternedString {
566 string: RcStr::new(string),
571 fn new_from_rc_str(string: RcStr) -> InternedString {
578 pub fn get<'a>(&'a self) -> &'a str {
579 self.string.as_slice()
583 impl BytesContainer for InternedString {
584 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
585 // FIXME(pcwalton): This is a workaround for the incorrect signature
586 // of `BytesContainer`, which is itself a workaround for the lack of
589 let this = self.get();
590 cast::transmute(this.container_as_bytes())
595 impl fmt::Show for InternedString {
596 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
597 write!(f.buf, "{}", self.string.as_slice())
601 impl<'a> Equiv<&'a str> for InternedString {
602 fn equiv(&self, other: & &'a str) -> bool {
603 (*other) == self.string.as_slice()
607 impl<D:Decoder> Decodable<D> for InternedString {
608 fn decode(d: &mut D) -> InternedString {
609 get_name(get_ident_interner().intern(d.read_str()))
613 impl<E:Encoder> Encodable<E> for InternedString {
614 fn encode(&self, e: &mut E) {
615 e.emit_str(self.string.as_slice())
619 /// Returns the string contents of a name, using the task-local interner.
621 pub fn get_name(name: Name) -> InternedString {
622 let interner = get_ident_interner();
623 InternedString::new_from_rc_str(interner.get(name))
626 /// Returns the string contents of an identifier, using the task-local
629 pub fn get_ident(ident: Ident) -> InternedString {
633 /// Interns and returns the string contents of an identifier, using the
634 /// task-local interner.
636 pub fn intern_and_get_ident(s: &str) -> InternedString {
640 /// Maps a string to its interned representation.
642 pub fn intern(s: &str) -> Name {
643 get_ident_interner().intern(s)
646 /// gensym's a new uint, using the current interner.
648 pub fn gensym(s: &str) -> Name {
649 get_ident_interner().gensym(s)
652 /// Maps a string to an identifier with an empty syntax context.
654 pub fn str_to_ident(s: &str) -> ast::Ident {
655 ast::Ident::new(intern(s))
658 /// Maps a string to a gensym'ed identifier.
660 pub fn gensym_ident(s: &str) -> ast::Ident {
661 ast::Ident::new(gensym(s))
664 // create a fresh name that maps to the same string as the old one.
665 // note that this guarantees that str_ptr_eq(ident_to_str(src),interner_get(fresh_name(src)));
666 // that is, that the new name and the old one are connected to ptr_eq strings.
667 pub fn fresh_name(src: &ast::Ident) -> Name {
668 let interner = get_ident_interner();
669 interner.gensym_copy(src.name)
670 // following: debug version. Could work in final except that it's incompatible with
671 // good error messages and uses of struct names in ambiguous could-be-binding
672 // locations. Also definitely destroys the guarantee given above about ptr_eq.
673 /*let num = rand::task_rng().gen_uint_range(0,0xffff);
674 gensym(format!("{}_{}",ident_to_str(src),num))*/
677 // create a fresh mark.
678 pub fn fresh_mark() -> Mrk {
682 // See the macro above about the types of keywords
684 pub fn is_keyword(kw: keywords::Keyword, tok: &Token) -> bool {
686 token::IDENT(sid, false) => { kw.to_ident().name == sid.name }
691 pub fn is_any_keyword(tok: &Token) -> bool {
693 token::IDENT(sid, false) => match sid.name {
694 SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
695 STRICT_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
702 pub fn is_strict_keyword(tok: &Token) -> bool {
704 token::IDENT(sid, false) => match sid.name {
705 SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
706 STRICT_KEYWORD_START .. STRICT_KEYWORD_FINAL => true,
713 pub fn is_reserved_keyword(tok: &Token) -> bool {
715 token::IDENT(sid, false) => match sid.name {
716 RESERVED_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
723 pub fn mtwt_token_eq(t1 : &Token, t2 : &Token) -> bool {
725 (&IDENT(id1,_),&IDENT(id2,_)) | (&LIFETIME(id1),&LIFETIME(id2)) =>
726 mtwt::resolve(id1) == mtwt::resolve(id2),
738 fn mark_ident(id : ast::Ident, m : ast::Mrk) -> ast::Ident {
739 ast::Ident{name:id.name,ctxt:mtwt::new_mark(m,id.ctxt)}
742 #[test] fn mtwt_token_eq_test() {
743 assert!(mtwt_token_eq(>,>));
744 let a = str_to_ident("bac");
745 let a1 = mark_ident(a,92);
746 assert!(mtwt_token_eq(&IDENT(a,true),&IDENT(a1,false)));