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 */
83 LIT_INT(i64, ast::IntTy),
84 LIT_UINT(u64, ast::UintTy),
85 LIT_INT_UNSUFFIXED(i64),
86 LIT_FLOAT(ast::Ident, ast::FloatTy),
87 LIT_FLOAT_UNSUFFIXED(ast::Ident),
89 LIT_STR_RAW(ast::Ident, uint), /* raw str delimited by n hash symbols */
90 LIT_BINARY(Rc<Vec<u8>>),
91 LIT_BINARY_RAW(Rc<Vec<u8>>, uint), /* raw binary str delimited by n hash symbols */
94 // an identifier contains an "is_mod_name" boolean,
95 // indicating whether :: follows this token with no
96 // whitespace in between.
97 IDENT(ast::Ident, bool),
101 /* For interpolation */
102 INTERPOLATED(Nonterminal),
104 DOC_COMMENT(ast::Ident),
108 #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)]
109 /// For interpolation during macro expansion.
110 pub enum Nonterminal {
111 NtItem(Gc<ast::Item>),
112 NtBlock(P<ast::Block>),
113 NtStmt(Gc<ast::Stmt>),
114 NtPat( Gc<ast::Pat>),
115 NtExpr(Gc<ast::Expr>),
117 NtIdent(Box<ast::Ident>, bool),
118 NtMeta(Gc<ast::MetaItem>), // stuff inside brackets for attributes
119 NtPath(Box<ast::Path>),
120 NtTT( Gc<ast::TokenTree>), // needs @ed to break a circularity
121 NtMatchers(Vec<ast::Matcher> )
124 impl fmt::Show for Nonterminal {
125 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
127 NtItem(..) => f.pad("NtItem(..)"),
128 NtBlock(..) => f.pad("NtBlock(..)"),
129 NtStmt(..) => f.pad("NtStmt(..)"),
130 NtPat(..) => f.pad("NtPat(..)"),
131 NtExpr(..) => f.pad("NtExpr(..)"),
132 NtTy(..) => f.pad("NtTy(..)"),
133 NtIdent(..) => f.pad("NtIdent(..)"),
134 NtMeta(..) => f.pad("NtMeta(..)"),
135 NtPath(..) => f.pad("NtPath(..)"),
136 NtTT(..) => f.pad("NtTT(..)"),
137 NtMatchers(..) => f.pad("NtMatchers(..)"),
142 pub fn binop_to_str(o: BinOp) -> &'static str {
157 pub fn to_str(t: &Token) -> String {
159 EQ => "=".to_string(),
160 LT => "<".to_string(),
161 LE => "<=".to_string(),
162 EQEQ => "==".to_string(),
163 NE => "!=".to_string(),
164 GE => ">=".to_string(),
165 GT => ">".to_string(),
166 NOT => "!".to_string(),
167 TILDE => "~".to_string(),
168 OROR => "||".to_string(),
169 ANDAND => "&&".to_string(),
170 BINOP(op) => binop_to_str(op).to_string(),
172 let mut s = binop_to_str(op).to_string();
177 /* Structural symbols */
178 AT => "@".to_string(),
179 DOT => ".".to_string(),
180 DOTDOT => "..".to_string(),
181 DOTDOTDOT => "...".to_string(),
182 COMMA => ",".to_string(),
183 SEMI => ";".to_string(),
184 COLON => ":".to_string(),
185 MOD_SEP => "::".to_string(),
186 RARROW => "->".to_string(),
187 LARROW => "<-".to_string(),
188 FAT_ARROW => "=>".to_string(),
189 LPAREN => "(".to_string(),
190 RPAREN => ")".to_string(),
191 LBRACKET => "[".to_string(),
192 RBRACKET => "]".to_string(),
193 LBRACE => "{".to_string(),
194 RBRACE => "}".to_string(),
195 POUND => "#".to_string(),
196 DOLLAR => "$".to_string(),
200 let mut res = String::from_str("b'");
201 (b as char).escape_default(|c| {
208 let mut res = String::from_str("'");
209 c.escape_default(|c| {
215 LIT_INT(i, t) => ast_util::int_ty_to_str(t, Some(i),
216 ast_util::ForceSuffix),
217 LIT_UINT(u, t) => ast_util::uint_ty_to_str(t, Some(u),
218 ast_util::ForceSuffix),
219 LIT_INT_UNSUFFIXED(i) => { (i as u64).to_str() }
221 let mut body = String::from_str(get_ident(s).get());
222 if body.as_slice().ends_with(".") {
223 body.push_char('0'); // `10.f` is not a float literal
225 body.push_str(ast_util::float_ty_to_str(t).as_slice());
228 LIT_FLOAT_UNSUFFIXED(s) => {
229 let mut body = String::from_str(get_ident(s).get());
230 if body.as_slice().ends_with(".") {
231 body.push_char('0'); // `10.f` is not a float literal
236 format!("\"{}\"", get_ident(s).get().escape_default())
238 LIT_STR_RAW(s, n) => {
239 format!("r{delim}\"{string}\"{delim}",
240 delim="#".repeat(n), string=get_ident(s))
242 LIT_BINARY(ref v) => {
245 v.iter().map(|&b| b as char).collect::<String>().escape_default())
247 LIT_BINARY_RAW(ref s, n) => {
248 format!("br{delim}\"{string}\"{delim}",
249 delim="#".repeat(n), string=s.as_slice().to_ascii().as_str_ascii())
252 /* Name components */
253 IDENT(s, _) => get_ident(s).get().to_string(),
255 format!("{}", get_ident(s))
257 UNDERSCORE => "_".to_string(),
260 DOC_COMMENT(s) => get_ident(s).get().to_string(),
261 EOF => "<eof>".to_string(),
262 INTERPOLATED(ref nt) => {
264 &NtExpr(ref e) => ::print::pprust::expr_to_str(&**e),
265 &NtMeta(ref e) => ::print::pprust::meta_item_to_str(&**e),
267 let mut s = "an interpolated ".to_string();
269 NtItem(..) => s.push_str("item"),
270 NtBlock(..) => s.push_str("block"),
271 NtStmt(..) => s.push_str("statement"),
272 NtPat(..) => s.push_str("pattern"),
273 NtMeta(..) => fail!("should have been handled"),
274 NtExpr(..) => fail!("should have been handled above"),
275 NtTy(..) => s.push_str("type"),
276 NtIdent(..) => s.push_str("identifier"),
277 NtPath(..) => s.push_str("path"),
278 NtTT(..) => s.push_str("tt"),
279 NtMatchers(..) => s.push_str("matcher sequence")
288 pub fn can_begin_expr(t: &Token) -> bool {
298 LIT_INT(_, _) => true,
299 LIT_UINT(_, _) => true,
300 LIT_INT_UNSUFFIXED(_) => true,
301 LIT_FLOAT(_, _) => true,
302 LIT_FLOAT_UNSUFFIXED(_) => true,
304 LIT_STR_RAW(_, _) => true,
305 LIT_BINARY(_) => true,
306 LIT_BINARY_RAW(_, _) => true,
310 BINOP(MINUS) => true,
313 BINOP(OR) => true, // in lambda syntax
314 OROR => true, // in lambda syntax
316 INTERPOLATED(NtExpr(..))
317 | INTERPOLATED(NtIdent(..))
318 | INTERPOLATED(NtBlock(..))
319 | INTERPOLATED(NtPath(..)) => true,
324 /// Returns the matching close delimiter if this is an open delimiter,
325 /// otherwise `None`.
326 pub fn close_delimiter_for(t: &Token) -> Option<Token> {
328 LPAREN => Some(RPAREN),
329 LBRACE => Some(RBRACE),
330 LBRACKET => Some(RBRACKET),
335 pub fn is_lit(t: &Token) -> bool {
339 LIT_INT(_, _) => true,
340 LIT_UINT(_, _) => true,
341 LIT_INT_UNSUFFIXED(_) => true,
342 LIT_FLOAT(_, _) => true,
343 LIT_FLOAT_UNSUFFIXED(_) => true,
345 LIT_STR_RAW(_, _) => true,
346 LIT_BINARY(_) => true,
347 LIT_BINARY_RAW(_, _) => true,
352 pub fn is_ident(t: &Token) -> bool {
353 match *t { IDENT(_, _) => true, _ => false }
356 pub fn is_ident_or_path(t: &Token) -> bool {
358 IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
363 pub fn is_plain_ident(t: &Token) -> bool {
364 match *t { IDENT(_, false) => true, _ => false }
367 pub fn is_bar(t: &Token) -> bool {
368 match *t { BINOP(OR) | OROR => true, _ => false }
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: Name = first!($( $sk_name, )*);
402 static STRICT_KEYWORD_FINAL: Name = last!($( $sk_name, )*);
403 static RESERVED_KEYWORD_START: Name = first!($( $rk_name, )*);
404 static RESERVED_KEYWORD_FINAL: Name = last!($( $rk_name, )*);
406 pub mod special_idents {
408 $( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
412 * All the valid words that have meaning in the Rust language.
414 * Rust keywords are either 'strict' or 'reserved'. Strict keywords may not
415 * appear as identifiers at all. Reserved keywords are not used anywhere in
416 * the language and may not appear as identifiers.
427 pub fn to_ident(&self) -> Ident {
429 $( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
430 $( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
436 fn mk_fresh_ident_interner() -> IdentInterner {
437 // The indices here must correspond to the numbers in
438 // special_idents, in Keyword to_ident(), and in static
440 let mut init_vec = Vec::new();
441 $(init_vec.push($si_str);)*
442 $(init_vec.push($sk_str);)*
443 $(init_vec.push($rk_str);)*
444 interner::StrInterner::prefill(init_vec.as_slice())
448 // If the special idents get renumbered, remember to modify these two as appropriate
449 static SELF_KEYWORD_NAME: Name = 1;
450 static STATIC_KEYWORD_NAME: Name = 2;
452 // NB: leaving holes in the ident table is bad! a different ident will get
453 // interned with the id from the hole, but it will be between the min and max
454 // of the reserved words, and thus tagged as "reserved".
456 declare_special_idents_and_keywords! {
457 pub mod special_idents {
458 // These ones are statics
460 (super::SELF_KEYWORD_NAME, self_, "self");
461 (super::STATIC_KEYWORD_NAME, statik, "static");
462 (3, static_lifetime, "'static");
466 (5, matchers, "matchers");
468 // outside of libsyntax
469 (6, clownshoe_abi, "__rust_abi");
470 (7, opaque, "<opaque>");
471 (8, unnamed_field, "<unnamed_field>");
472 (9, type_self, "Self");
476 // These ones are variants of the Keyword enum
480 (11, Break, "break");
481 (12, Crate, "crate");
484 (15, Extern, "extern");
485 (16, False, "false");
493 (24, Match, "match");
499 (30, Return, "return");
500 // Static and Self are also special idents (prefill de-dupes)
501 (super::STATIC_KEYWORD_NAME, Static, "static");
502 (super::SELF_KEYWORD_NAME, Self, "self");
503 (31, Struct, "struct");
504 (32, Super, "super");
506 (34, Trait, "trait");
508 (36, Unsafe, "unsafe");
510 (38, Virtual, "virtual");
511 (39, While, "while");
512 (40, Continue, "continue");
515 (43, Const, "const");
518 (44, Alignof, "alignof");
520 (46, Offsetof, "offsetof");
523 (49, Sizeof, "sizeof");
524 (50, Typeof, "typeof");
525 (51, Unsized, "unsized");
526 (52, Yield, "yield");
532 * Maps a token to a record specifying the corresponding binary
535 pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
537 BINOP(STAR) => Some(ast::BiMul),
538 BINOP(SLASH) => Some(ast::BiDiv),
539 BINOP(PERCENT) => Some(ast::BiRem),
540 BINOP(PLUS) => Some(ast::BiAdd),
541 BINOP(MINUS) => Some(ast::BiSub),
542 BINOP(SHL) => Some(ast::BiShl),
543 BINOP(SHR) => Some(ast::BiShr),
544 BINOP(AND) => Some(ast::BiBitAnd),
545 BINOP(CARET) => Some(ast::BiBitXor),
546 BINOP(OR) => Some(ast::BiBitOr),
547 LT => Some(ast::BiLt),
548 LE => Some(ast::BiLe),
549 GE => Some(ast::BiGe),
550 GT => Some(ast::BiGt),
551 EQEQ => Some(ast::BiEq),
552 NE => Some(ast::BiNe),
553 ANDAND => Some(ast::BiAnd),
554 OROR => Some(ast::BiOr),
559 // looks like we can get rid of this completely...
560 pub type IdentInterner = StrInterner;
562 // if an interner exists in TLS, return it. Otherwise, prepare a
564 // FIXME(eddyb) #8726 This should probably use a task-local reference.
565 pub fn get_ident_interner() -> Rc<IdentInterner> {
566 local_data_key!(key: Rc<::parse::token::IdentInterner>)
568 Some(interner) => interner.clone(),
570 let interner = Rc::new(mk_fresh_ident_interner());
571 key.replace(Some(interner.clone()));
577 /// Represents a string stored in the task-local interner. Because the
578 /// interner lives for the life of the task, this can be safely treated as an
579 /// immortal string, as long as it never crosses between tasks.
581 /// FIXME(pcwalton): You must be careful about what you do in the destructors
582 /// of objects stored in TLS, because they may run after the interner is
583 /// destroyed. In particular, they must not access string contents. This can
584 /// be fixed in the future by just leaking all strings until task death
586 #[deriving(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
587 pub struct InternedString {
591 impl InternedString {
593 pub fn new(string: &'static str) -> InternedString {
595 string: RcStr::new(string),
600 fn new_from_rc_str(string: RcStr) -> InternedString {
607 pub fn get<'a>(&'a self) -> &'a str {
608 self.string.as_slice()
612 impl BytesContainer for InternedString {
613 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
614 // FIXME(pcwalton): This is a workaround for the incorrect signature
615 // of `BytesContainer`, which is itself a workaround for the lack of
618 let this = self.get();
619 mem::transmute(this.container_as_bytes())
624 impl fmt::Show for InternedString {
625 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
626 write!(f, "{}", self.string.as_slice())
630 impl<'a> Equiv<&'a str> for InternedString {
631 fn equiv(&self, other: & &'a str) -> bool {
632 (*other) == self.string.as_slice()
636 impl<D:Decoder<E>, E> Decodable<D, E> for InternedString {
637 fn decode(d: &mut D) -> Result<InternedString, E> {
638 Ok(get_name(get_ident_interner().intern(
639 try!(d.read_str()).as_slice())))
643 impl<S:Encoder<E>, E> Encodable<S, E> for InternedString {
644 fn encode(&self, s: &mut S) -> Result<(), E> {
645 s.emit_str(self.string.as_slice())
649 /// Returns the string contents of a name, using the task-local interner.
651 pub fn get_name(name: Name) -> InternedString {
652 let interner = get_ident_interner();
653 InternedString::new_from_rc_str(interner.get(name))
656 /// Returns the string contents of an identifier, using the task-local
659 pub fn get_ident(ident: Ident) -> InternedString {
663 /// Interns and returns the string contents of an identifier, using the
664 /// task-local interner.
666 pub fn intern_and_get_ident(s: &str) -> InternedString {
670 /// Maps a string to its interned representation.
672 pub fn intern(s: &str) -> Name {
673 get_ident_interner().intern(s)
676 /// gensym's a new uint, using the current interner.
678 pub fn gensym(s: &str) -> Name {
679 get_ident_interner().gensym(s)
682 /// Maps a string to an identifier with an empty syntax context.
684 pub fn str_to_ident(s: &str) -> ast::Ident {
685 ast::Ident::new(intern(s))
688 /// Maps a string to a gensym'ed identifier.
690 pub fn gensym_ident(s: &str) -> ast::Ident {
691 ast::Ident::new(gensym(s))
694 // create a fresh name that maps to the same string as the old one.
695 // note that this guarantees that str_ptr_eq(ident_to_str(src),interner_get(fresh_name(src)));
696 // that is, that the new name and the old one are connected to ptr_eq strings.
697 pub fn fresh_name(src: &ast::Ident) -> Name {
698 let interner = get_ident_interner();
699 interner.gensym_copy(src.name)
700 // following: debug version. Could work in final except that it's incompatible with
701 // good error messages and uses of struct names in ambiguous could-be-binding
702 // locations. Also definitely destroys the guarantee given above about ptr_eq.
703 /*let num = rand::task_rng().gen_uint_range(0,0xffff);
704 gensym(format!("{}_{}",ident_to_str(src),num))*/
707 // create a fresh mark.
708 pub fn fresh_mark() -> Mrk {
712 // See the macro above about the types of keywords
714 pub fn is_keyword(kw: keywords::Keyword, tok: &Token) -> bool {
716 token::IDENT(sid, false) => { kw.to_ident().name == sid.name }
721 pub fn is_any_keyword(tok: &Token) -> bool {
723 token::IDENT(sid, false) => match sid.name {
724 SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
725 STRICT_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
732 pub fn is_strict_keyword(tok: &Token) -> bool {
734 token::IDENT(sid, false) => match sid.name {
735 SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
736 STRICT_KEYWORD_START .. STRICT_KEYWORD_FINAL => true,
743 pub fn is_reserved_keyword(tok: &Token) -> bool {
745 token::IDENT(sid, false) => match sid.name {
746 RESERVED_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
753 pub fn mtwt_token_eq(t1 : &Token, t2 : &Token) -> bool {
755 (&IDENT(id1,_),&IDENT(id2,_)) | (&LIFETIME(id1),&LIFETIME(id2)) =>
756 mtwt::resolve(id1) == mtwt::resolve(id2),
768 fn mark_ident(id : ast::Ident, m : ast::Mrk) -> ast::Ident {
769 ast::Ident{name:id.name,ctxt:mtwt::new_mark(m,id.ctxt)}
772 #[test] fn mtwt_token_eq_test() {
773 assert!(mtwt_token_eq(>,>));
774 let a = str_to_ident("bac");
775 let a1 = mark_ident(a,92);
776 assert!(mtwt_token_eq(&IDENT(a,true),&IDENT(a1,false)));