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};
21 use std::path::BytesContainer;
24 use std::string::String;
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 {
109 NtBlock(P<ast::Block>),
114 NtIdent(Box<ast::Ident>, bool),
115 NtMeta(@ast::MetaItem), // stuff inside brackets for attributes
116 NtPath(Box<ast::Path>),
117 NtTT( @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) -> String {
141 PLUS => "+".to_string(),
142 MINUS => "-".to_string(),
143 STAR => "*".to_string(),
144 SLASH => "/".to_string(),
145 PERCENT => "%".to_string(),
146 CARET => "^".to_string(),
147 AND => "&".to_string(),
148 OR => "|".to_string(),
149 SHL => "<<".to_string(),
150 SHR => ">>".to_string()
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),
169 let mut s = binop_to_str(op);
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().to_string() }
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(e) => ::print::pprust::expr_to_str(e),
245 &NtMeta(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 declare_special_idents_and_keywords! {
427 pub mod special_idents {
428 // These ones are statics
430 (super::SELF_KEYWORD_NAME, self_, "self");
431 (super::STATIC_KEYWORD_NAME, statik, "static");
435 (4, matchers, "matchers");
437 // outside of libsyntax
438 (5, clownshoe_abi, "__rust_abi");
439 (6, opaque, "<opaque>");
440 (7, unnamed_field, "<unnamed_field>");
441 (8, type_self, "Self");
445 // These ones are variants of the Keyword enum
449 (10, Break, "break");
450 (11, Crate, "crate");
453 (14, Extern, "extern");
454 (15, False, "false");
462 (23, Match, "match");
468 (29, Return, "return");
469 // Static and Self are also special idents (prefill de-dupes)
470 (super::STATIC_KEYWORD_NAME, Static, "static");
471 (super::SELF_KEYWORD_NAME, Self, "self");
472 (30, Struct, "struct");
473 (31, Super, "super");
475 (33, Trait, "trait");
477 (35, Unsafe, "unsafe");
479 (37, Virtual, "virtual");
480 (38, While, "while");
481 (39, Continue, "continue");
486 (42, Alignof, "alignof");
488 (44, Const, "const");
489 (45, Offsetof, "offsetof");
492 (48, Sizeof, "sizeof");
493 (49, Typeof, "typeof");
494 (50, Unsized, "unsized");
495 (51, Yield, "yield");
501 * Maps a token to a record specifying the corresponding binary
504 pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
506 BINOP(STAR) => Some(ast::BiMul),
507 BINOP(SLASH) => Some(ast::BiDiv),
508 BINOP(PERCENT) => Some(ast::BiRem),
509 BINOP(PLUS) => Some(ast::BiAdd),
510 BINOP(MINUS) => Some(ast::BiSub),
511 BINOP(SHL) => Some(ast::BiShl),
512 BINOP(SHR) => Some(ast::BiShr),
513 BINOP(AND) => Some(ast::BiBitAnd),
514 BINOP(CARET) => Some(ast::BiBitXor),
515 BINOP(OR) => Some(ast::BiBitOr),
516 LT => Some(ast::BiLt),
517 LE => Some(ast::BiLe),
518 GE => Some(ast::BiGe),
519 GT => Some(ast::BiGt),
520 EQEQ => Some(ast::BiEq),
521 NE => Some(ast::BiNe),
522 ANDAND => Some(ast::BiAnd),
523 OROR => Some(ast::BiOr),
528 // looks like we can get rid of this completely...
529 pub type IdentInterner = StrInterner;
531 // if an interner exists in TLS, return it. Otherwise, prepare a
533 // FIXME(eddyb) #8726 This should probably use a task-local reference.
534 pub fn get_ident_interner() -> Rc<IdentInterner> {
535 local_data_key!(key: Rc<::parse::token::IdentInterner>)
537 Some(interner) => interner.clone(),
539 let interner = Rc::new(mk_fresh_ident_interner());
540 key.replace(Some(interner.clone()));
546 /// Represents a string stored in the task-local interner. Because the
547 /// interner lives for the life of the task, this can be safely treated as an
548 /// immortal string, as long as it never crosses between tasks.
550 /// FIXME(pcwalton): You must be careful about what you do in the destructors
551 /// of objects stored in TLS, because they may run after the interner is
552 /// destroyed. In particular, they must not access string contents. This can
553 /// be fixed in the future by just leaking all strings until task death
555 #[deriving(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
556 pub struct InternedString {
560 impl InternedString {
562 pub fn new(string: &'static str) -> InternedString {
564 string: RcStr::new(string),
569 fn new_from_rc_str(string: RcStr) -> InternedString {
576 pub fn get<'a>(&'a self) -> &'a str {
577 self.string.as_slice()
581 impl BytesContainer for InternedString {
582 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
583 // FIXME(pcwalton): This is a workaround for the incorrect signature
584 // of `BytesContainer`, which is itself a workaround for the lack of
587 let this = self.get();
588 mem::transmute(this.container_as_bytes())
593 impl fmt::Show for InternedString {
594 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
595 write!(f, "{}", self.string.as_slice())
599 impl<'a> Equiv<&'a str> for InternedString {
600 fn equiv(&self, other: & &'a str) -> bool {
601 (*other) == self.string.as_slice()
605 impl<D:Decoder<E>, E> Decodable<D, E> for InternedString {
606 fn decode(d: &mut D) -> Result<InternedString, E> {
607 Ok(get_name(get_ident_interner().intern(
608 try!(d.read_str()).as_slice())))
612 impl<S:Encoder<E>, E> Encodable<S, E> for InternedString {
613 fn encode(&self, s: &mut S) -> Result<(), E> {
614 s.emit_str(self.string.as_slice())
618 /// Returns the string contents of a name, using the task-local interner.
620 pub fn get_name(name: Name) -> InternedString {
621 let interner = get_ident_interner();
622 InternedString::new_from_rc_str(interner.get(name))
625 /// Returns the string contents of an identifier, using the task-local
628 pub fn get_ident(ident: Ident) -> InternedString {
632 /// Interns and returns the string contents of an identifier, using the
633 /// task-local interner.
635 pub fn intern_and_get_ident(s: &str) -> InternedString {
639 /// Maps a string to its interned representation.
641 pub fn intern(s: &str) -> Name {
642 get_ident_interner().intern(s)
645 /// gensym's a new uint, using the current interner.
647 pub fn gensym(s: &str) -> Name {
648 get_ident_interner().gensym(s)
651 /// Maps a string to an identifier with an empty syntax context.
653 pub fn str_to_ident(s: &str) -> ast::Ident {
654 ast::Ident::new(intern(s))
657 /// Maps a string to a gensym'ed identifier.
659 pub fn gensym_ident(s: &str) -> ast::Ident {
660 ast::Ident::new(gensym(s))
663 // create a fresh name that maps to the same string as the old one.
664 // note that this guarantees that str_ptr_eq(ident_to_str(src),interner_get(fresh_name(src)));
665 // that is, that the new name and the old one are connected to ptr_eq strings.
666 pub fn fresh_name(src: &ast::Ident) -> Name {
667 let interner = get_ident_interner();
668 interner.gensym_copy(src.name)
669 // following: debug version. Could work in final except that it's incompatible with
670 // good error messages and uses of struct names in ambiguous could-be-binding
671 // locations. Also definitely destroys the guarantee given above about ptr_eq.
672 /*let num = rand::task_rng().gen_uint_range(0,0xffff);
673 gensym(format!("{}_{}",ident_to_str(src),num))*/
676 // create a fresh mark.
677 pub fn fresh_mark() -> Mrk {
681 // See the macro above about the types of keywords
683 pub fn is_keyword(kw: keywords::Keyword, tok: &Token) -> bool {
685 token::IDENT(sid, false) => { kw.to_ident().name == sid.name }
690 pub fn is_any_keyword(tok: &Token) -> bool {
692 token::IDENT(sid, false) => match sid.name {
693 SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
694 STRICT_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
701 pub fn is_strict_keyword(tok: &Token) -> bool {
703 token::IDENT(sid, false) => match sid.name {
704 SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
705 STRICT_KEYWORD_START .. STRICT_KEYWORD_FINAL => true,
712 pub fn is_reserved_keyword(tok: &Token) -> bool {
714 token::IDENT(sid, false) => match sid.name {
715 RESERVED_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
722 pub fn mtwt_token_eq(t1 : &Token, t2 : &Token) -> bool {
724 (&IDENT(id1,_),&IDENT(id2,_)) | (&LIFETIME(id1),&LIFETIME(id2)) =>
725 mtwt::resolve(id1) == mtwt::resolve(id2),
737 fn mark_ident(id : ast::Ident, m : ast::Mrk) -> ast::Ident {
738 ast::Ident{name:id.name,ctxt:mtwt::new_mark(m,id.ctxt)}
741 #[test] fn mtwt_token_eq_test() {
742 assert!(mtwt_token_eq(>,>));
743 let a = str_to_ident("bac");
744 let a1 = mark_ident(a,92);
745 assert!(mtwt_token_eq(&IDENT(a,true),&IDENT(a1,false)));