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};
23 use std::path::BytesContainer;
26 #[allow(non_camel_case_types)]
27 #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash, Show)]
41 #[allow(non_camel_case_types)]
42 #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash, Show)]
44 /* Expression-operator symbols. */
59 /* 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, PartialEq, Eq, Hash)]
106 /// For interpolation during macro expansion.
107 pub enum Nonterminal {
108 NtItem(Gc<ast::Item>),
109 NtBlock(P<ast::Block>),
110 NtStmt(Gc<ast::Stmt>),
111 NtPat( Gc<ast::Pat>),
112 NtExpr(Gc<ast::Expr>),
114 NtIdent(Box<ast::Ident>, bool),
115 NtMeta(Gc<ast::MetaItem>), // stuff inside brackets for attributes
116 NtPath(Box<ast::Path>),
117 NtTT( Gc<ast::TokenTree>), // needs @ed to break a circularity
118 NtMatchers(Vec<ast::Matcher> )
121 impl fmt::Show for Nonterminal {
122 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
124 NtItem(..) => f.pad("NtItem(..)"),
125 NtBlock(..) => f.pad("NtBlock(..)"),
126 NtStmt(..) => f.pad("NtStmt(..)"),
127 NtPat(..) => f.pad("NtPat(..)"),
128 NtExpr(..) => f.pad("NtExpr(..)"),
129 NtTy(..) => f.pad("NtTy(..)"),
130 NtIdent(..) => f.pad("NtIdent(..)"),
131 NtMeta(..) => f.pad("NtMeta(..)"),
132 NtPath(..) => f.pad("NtPath(..)"),
133 NtTT(..) => f.pad("NtTT(..)"),
134 NtMatchers(..) => f.pad("NtMatchers(..)"),
139 pub fn binop_to_str(o: BinOp) -> &'static str {
154 pub fn to_str(t: &Token) -> String {
156 EQ => "=".to_string(),
157 LT => "<".to_string(),
158 LE => "<=".to_string(),
159 EQEQ => "==".to_string(),
160 NE => "!=".to_string(),
161 GE => ">=".to_string(),
162 GT => ">".to_string(),
163 NOT => "!".to_string(),
164 TILDE => "~".to_string(),
165 OROR => "||".to_string(),
166 ANDAND => "&&".to_string(),
167 BINOP(op) => binop_to_str(op).to_string(),
169 let mut s = binop_to_str(op).to_string();
174 /* Structural symbols */
175 AT => "@".to_string(),
176 DOT => ".".to_string(),
177 DOTDOT => "..".to_string(),
178 DOTDOTDOT => "...".to_string(),
179 COMMA => ",".to_string(),
180 SEMI => ";".to_string(),
181 COLON => ":".to_string(),
182 MOD_SEP => "::".to_string(),
183 RARROW => "->".to_string(),
184 LARROW => "<-".to_string(),
185 FAT_ARROW => "=>".to_string(),
186 LPAREN => "(".to_string(),
187 RPAREN => ")".to_string(),
188 LBRACKET => "[".to_string(),
189 RBRACKET => "]".to_string(),
190 LBRACE => "{".to_string(),
191 RBRACE => "}".to_string(),
192 POUND => "#".to_string(),
193 DOLLAR => "$".to_string(),
197 let mut res = String::from_str("'");
198 c.escape_default(|c| {
204 LIT_INT(i, t) => ast_util::int_ty_to_str(t, Some(i),
205 ast_util::ForceSuffix),
206 LIT_UINT(u, t) => ast_util::uint_ty_to_str(t, Some(u),
207 ast_util::ForceSuffix),
208 LIT_INT_UNSUFFIXED(i) => { (i as u64).to_str() }
210 let mut body = String::from_str(get_ident(s).get());
211 if body.as_slice().ends_with(".") {
212 body.push_char('0'); // `10.f` is not a float literal
214 body.push_str(ast_util::float_ty_to_str(t).as_slice());
217 LIT_FLOAT_UNSUFFIXED(s) => {
218 let mut body = String::from_str(get_ident(s).get());
219 if body.as_slice().ends_with(".") {
220 body.push_char('0'); // `10.f` is not a float literal
225 (format!("\"{}\"", get_ident(s).get().escape_default())).to_string()
227 LIT_STR_RAW(s, n) => {
228 (format!("r{delim}\"{string}\"{delim}",
229 delim="#".repeat(n), string=get_ident(s))).to_string()
232 /* Name components */
233 IDENT(s, _) => get_ident(s).get().to_string(),
235 (format!("{}", get_ident(s))).to_string()
237 UNDERSCORE => "_".to_string(),
240 DOC_COMMENT(s) => get_ident(s).get().to_string(),
241 EOF => "<eof>".to_string(),
242 INTERPOLATED(ref nt) => {
244 &NtExpr(ref e) => ::print::pprust::expr_to_str(&**e),
245 &NtMeta(ref e) => ::print::pprust::meta_item_to_str(&**e),
247 let mut s = "an interpolated ".to_string();
249 NtItem(..) => s.push_str("item"),
250 NtBlock(..) => s.push_str("block"),
251 NtStmt(..) => s.push_str("statement"),
252 NtPat(..) => s.push_str("pattern"),
253 NtMeta(..) => fail!("should have been handled"),
254 NtExpr(..) => fail!("should have been handled above"),
255 NtTy(..) => s.push_str("type"),
256 NtIdent(..) => s.push_str("identifier"),
257 NtPath(..) => s.push_str("path"),
258 NtTT(..) => s.push_str("tt"),
259 NtMatchers(..) => s.push_str("matcher sequence")
268 pub fn can_begin_expr(t: &Token) -> bool {
277 LIT_INT(_, _) => true,
278 LIT_UINT(_, _) => true,
279 LIT_INT_UNSUFFIXED(_) => true,
280 LIT_FLOAT(_, _) => true,
281 LIT_FLOAT_UNSUFFIXED(_) => true,
283 LIT_STR_RAW(_, _) => true,
287 BINOP(MINUS) => true,
290 BINOP(OR) => true, // in lambda syntax
291 OROR => true, // in lambda syntax
293 INTERPOLATED(NtExpr(..))
294 | INTERPOLATED(NtIdent(..))
295 | INTERPOLATED(NtBlock(..))
296 | INTERPOLATED(NtPath(..)) => true,
301 /// Returns the matching close delimiter if this is an open delimiter,
302 /// otherwise `None`.
303 pub fn close_delimiter_for(t: &Token) -> Option<Token> {
305 LPAREN => Some(RPAREN),
306 LBRACE => Some(RBRACE),
307 LBRACKET => Some(RBRACKET),
312 pub fn is_lit(t: &Token) -> bool {
315 LIT_INT(_, _) => true,
316 LIT_UINT(_, _) => true,
317 LIT_INT_UNSUFFIXED(_) => true,
318 LIT_FLOAT(_, _) => true,
319 LIT_FLOAT_UNSUFFIXED(_) => true,
321 LIT_STR_RAW(_, _) => true,
326 pub fn is_ident(t: &Token) -> bool {
327 match *t { IDENT(_, _) => true, _ => false }
330 pub fn is_ident_or_path(t: &Token) -> bool {
332 IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
337 pub fn is_plain_ident(t: &Token) -> bool {
338 match *t { IDENT(_, false) => true, _ => false }
341 pub fn is_bar(t: &Token) -> bool {
342 match *t { BINOP(OR) | OROR => true, _ => false }
345 // Get the first "argument"
347 ( $first:expr, $( $remainder:expr, )* ) => ( $first )
350 // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
352 ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
353 ( $first:expr, ) => ( $first )
356 // In this macro, there is the requirement that the name (the number) must be monotonically
357 // increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
358 // except starting from the next number instead of zero, and with the additional exception that
359 // special identifiers are *also* allowed (they are deduplicated in the important place, the
360 // interner), an exception which is demonstrated by "static" and "self".
361 macro_rules! declare_special_idents_and_keywords {(
362 // So now, in these rules, why is each definition parenthesised?
363 // Answer: otherwise we get a spurious local ambiguity bug on the "}"
364 pub mod special_idents {
365 $( ($si_name:expr, $si_static:ident, $si_str:expr); )*
370 $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
372 $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
375 static STRICT_KEYWORD_START: Name = first!($( $sk_name, )*);
376 static STRICT_KEYWORD_FINAL: Name = last!($( $sk_name, )*);
377 static RESERVED_KEYWORD_START: Name = first!($( $rk_name, )*);
378 static RESERVED_KEYWORD_FINAL: Name = last!($( $rk_name, )*);
380 pub mod special_idents {
382 $( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
386 * All the valid words that have meaning in the Rust language.
388 * Rust keywords are either 'strict' or 'reserved'. Strict keywords may not
389 * appear as identifiers at all. Reserved keywords are not used anywhere in
390 * the language and may not appear as identifiers.
401 pub fn to_ident(&self) -> Ident {
403 $( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
404 $( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
410 fn mk_fresh_ident_interner() -> IdentInterner {
411 // The indices here must correspond to the numbers in
412 // special_idents, in Keyword to_ident(), and in static
414 let mut init_vec = Vec::new();
415 $(init_vec.push($si_str);)*
416 $(init_vec.push($sk_str);)*
417 $(init_vec.push($rk_str);)*
418 interner::StrInterner::prefill(init_vec.as_slice())
422 // If the special idents get renumbered, remember to modify these two as appropriate
423 static SELF_KEYWORD_NAME: Name = 1;
424 static STATIC_KEYWORD_NAME: Name = 2;
426 // NB: leaving holes in the ident table is bad! a different ident will get
427 // interned with the id from the hole, but it will be between the min and max
428 // of the reserved words, and thus tagged as "reserved".
430 declare_special_idents_and_keywords! {
431 pub mod special_idents {
432 // These ones are statics
434 (super::SELF_KEYWORD_NAME, self_, "self");
435 (super::STATIC_KEYWORD_NAME, statik, "static");
436 (3, static_lifetime, "'static");
440 (5, matchers, "matchers");
442 // outside of libsyntax
443 (6, clownshoe_abi, "__rust_abi");
444 (7, opaque, "<opaque>");
445 (8, unnamed_field, "<unnamed_field>");
446 (9, type_self, "Self");
450 // These ones are variants of the Keyword enum
454 (11, Break, "break");
455 (12, Crate, "crate");
458 (15, Extern, "extern");
459 (16, False, "false");
467 (24, Match, "match");
473 (30, Return, "return");
474 // Static and Self are also special idents (prefill de-dupes)
475 (super::STATIC_KEYWORD_NAME, Static, "static");
476 (super::SELF_KEYWORD_NAME, Self, "self");
477 (31, Struct, "struct");
478 (32, Super, "super");
480 (34, Trait, "trait");
482 (36, Unsafe, "unsafe");
484 (38, Virtual, "virtual");
485 (39, While, "while");
486 (40, Continue, "continue");
491 (43, Alignof, "alignof");
493 (45, Const, "const");
494 (46, Offsetof, "offsetof");
497 (49, Sizeof, "sizeof");
498 (50, Typeof, "typeof");
499 (51, Unsized, "unsized");
500 (52, Yield, "yield");
506 * Maps a token to a record specifying the corresponding binary
509 pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
511 BINOP(STAR) => Some(ast::BiMul),
512 BINOP(SLASH) => Some(ast::BiDiv),
513 BINOP(PERCENT) => Some(ast::BiRem),
514 BINOP(PLUS) => Some(ast::BiAdd),
515 BINOP(MINUS) => Some(ast::BiSub),
516 BINOP(SHL) => Some(ast::BiShl),
517 BINOP(SHR) => Some(ast::BiShr),
518 BINOP(AND) => Some(ast::BiBitAnd),
519 BINOP(CARET) => Some(ast::BiBitXor),
520 BINOP(OR) => Some(ast::BiBitOr),
521 LT => Some(ast::BiLt),
522 LE => Some(ast::BiLe),
523 GE => Some(ast::BiGe),
524 GT => Some(ast::BiGt),
525 EQEQ => Some(ast::BiEq),
526 NE => Some(ast::BiNe),
527 ANDAND => Some(ast::BiAnd),
528 OROR => Some(ast::BiOr),
533 // looks like we can get rid of this completely...
534 pub type IdentInterner = StrInterner;
536 // if an interner exists in TLS, return it. Otherwise, prepare a
538 // FIXME(eddyb) #8726 This should probably use a task-local reference.
539 pub fn get_ident_interner() -> Rc<IdentInterner> {
540 local_data_key!(key: Rc<::parse::token::IdentInterner>)
542 Some(interner) => interner.clone(),
544 let interner = Rc::new(mk_fresh_ident_interner());
545 key.replace(Some(interner.clone()));
551 /// Represents a string stored in the task-local interner. Because the
552 /// interner lives for the life of the task, this can be safely treated as an
553 /// immortal string, as long as it never crosses between tasks.
555 /// FIXME(pcwalton): You must be careful about what you do in the destructors
556 /// of objects stored in TLS, because they may run after the interner is
557 /// destroyed. In particular, they must not access string contents. This can
558 /// be fixed in the future by just leaking all strings until task death
560 #[deriving(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
561 pub struct InternedString {
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 // FIXME(pcwalton): This is a workaround for the incorrect signature
589 // of `BytesContainer`, which is itself a workaround for the lack of
592 let this = self.get();
593 mem::transmute(this.container_as_bytes())
598 impl fmt::Show for InternedString {
599 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
600 write!(f, "{}", self.string.as_slice())
604 impl<'a> Equiv<&'a str> for InternedString {
605 fn equiv(&self, other: & &'a str) -> bool {
606 (*other) == self.string.as_slice()
610 impl<D:Decoder<E>, E> Decodable<D, E> for InternedString {
611 fn decode(d: &mut D) -> Result<InternedString, E> {
612 Ok(get_name(get_ident_interner().intern(
613 try!(d.read_str()).as_slice())))
617 impl<S:Encoder<E>, E> Encodable<S, E> for InternedString {
618 fn encode(&self, s: &mut S) -> Result<(), E> {
619 s.emit_str(self.string.as_slice())
623 /// Returns the string contents of a name, using the task-local interner.
625 pub fn get_name(name: Name) -> InternedString {
626 let interner = get_ident_interner();
627 InternedString::new_from_rc_str(interner.get(name))
630 /// Returns the string contents of an identifier, using the task-local
633 pub fn get_ident(ident: Ident) -> InternedString {
637 /// Interns and returns the string contents of an identifier, using the
638 /// task-local interner.
640 pub fn intern_and_get_ident(s: &str) -> InternedString {
644 /// Maps a string to its interned representation.
646 pub fn intern(s: &str) -> Name {
647 get_ident_interner().intern(s)
650 /// gensym's a new uint, using the current interner.
652 pub fn gensym(s: &str) -> Name {
653 get_ident_interner().gensym(s)
656 /// Maps a string to an identifier with an empty syntax context.
658 pub fn str_to_ident(s: &str) -> ast::Ident {
659 ast::Ident::new(intern(s))
662 /// Maps a string to a gensym'ed identifier.
664 pub fn gensym_ident(s: &str) -> ast::Ident {
665 ast::Ident::new(gensym(s))
668 // create a fresh name that maps to the same string as the old one.
669 // note that this guarantees that str_ptr_eq(ident_to_str(src),interner_get(fresh_name(src)));
670 // that is, that the new name and the old one are connected to ptr_eq strings.
671 pub fn fresh_name(src: &ast::Ident) -> Name {
672 let interner = get_ident_interner();
673 interner.gensym_copy(src.name)
674 // following: debug version. Could work in final except that it's incompatible with
675 // good error messages and uses of struct names in ambiguous could-be-binding
676 // locations. Also definitely destroys the guarantee given above about ptr_eq.
677 /*let num = rand::task_rng().gen_uint_range(0,0xffff);
678 gensym(format!("{}_{}",ident_to_str(src),num))*/
681 // create a fresh mark.
682 pub fn fresh_mark() -> Mrk {
686 // See the macro above about the types of keywords
688 pub fn is_keyword(kw: keywords::Keyword, tok: &Token) -> bool {
690 token::IDENT(sid, false) => { kw.to_ident().name == sid.name }
695 pub fn is_any_keyword(tok: &Token) -> bool {
697 token::IDENT(sid, false) => match sid.name {
698 SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
699 STRICT_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
706 pub fn is_strict_keyword(tok: &Token) -> bool {
708 token::IDENT(sid, false) => match sid.name {
709 SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
710 STRICT_KEYWORD_START .. STRICT_KEYWORD_FINAL => true,
717 pub fn is_reserved_keyword(tok: &Token) -> bool {
719 token::IDENT(sid, false) => match sid.name {
720 RESERVED_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
727 pub fn mtwt_token_eq(t1 : &Token, t2 : &Token) -> bool {
729 (&IDENT(id1,_),&IDENT(id2,_)) | (&LIFETIME(id1),&LIFETIME(id2)) =>
730 mtwt::resolve(id1) == mtwt::resolve(id2),
742 fn mark_ident(id : ast::Ident, m : ast::Mrk) -> ast::Ident {
743 ast::Ident{name:id.name,ctxt:mtwt::new_mark(m,id.ctxt)}
746 #[test] fn mtwt_token_eq_test() {
747 assert!(mtwt_token_eq(>,>));
748 let a = str_to_ident("bac");
749 let a1 = mark_ident(a,92);
750 assert!(mtwt_token_eq(&IDENT(a,true),&IDENT(a1,false)));