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;
26 use std::strbuf::StrBuf;
28 #[allow(non_camel_case_types)]
29 #[deriving(Clone, Encodable, Decodable, Eq, TotalEq, Hash, Show)]
43 #[allow(non_camel_case_types)]
44 #[deriving(Clone, Encodable, Decodable, Eq, TotalEq, Hash, Show)]
46 /* Expression-operator symbols. */
61 /* Structural symbols */
85 LIT_INT(i64, ast::IntTy),
86 LIT_UINT(u64, ast::UintTy),
87 LIT_INT_UNSUFFIXED(i64),
88 LIT_FLOAT(ast::Ident, ast::FloatTy),
89 LIT_FLOAT_UNSUFFIXED(ast::Ident),
91 LIT_STR_RAW(ast::Ident, uint), /* raw 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, Eq, TotalEq, Hash)]
109 /// For interpolation during macro expansion.
110 pub enum Nonterminal {
112 NtBlock(P<ast::Block>),
117 NtIdent(~ast::Ident, bool),
118 NtMeta(@ast::MetaItem), // stuff inside brackets for attributes
120 NtTT( @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) -> ~str {
157 pub fn to_str(t: &Token) -> ~str {
170 BINOP(op) => binop_to_str(op),
171 BINOPEQ(op) => binop_to_str(op) + "=",
173 /* Structural symbols */
197 let mut res = StrBuf::from_str("'");
198 char::from_u32(c).unwrap().escape_default(|c| {
204 LIT_INT(i, t) => ast_util::int_ty_to_str(t, Some(i)),
205 LIT_UINT(u, t) => ast_util::uint_ty_to_str(t, Some(u)),
206 LIT_INT_UNSUFFIXED(i) => { i.to_str() }
208 let mut body = StrBuf::from_str(get_ident(s).get());
209 if body.as_slice().ends_with(".") {
210 body.push_char('0'); // `10.f` is not a float literal
212 body.push_str(ast_util::float_ty_to_str(t));
215 LIT_FLOAT_UNSUFFIXED(s) => {
216 let mut body = StrBuf::from_str(get_ident(s).get());
217 if body.as_slice().ends_with(".") {
218 body.push_char('0'); // `10.f` is not a float literal
223 format!("\"{}\"", get_ident(s).get().escape_default())
225 LIT_STR_RAW(s, n) => {
226 format!("r{delim}\"{string}\"{delim}",
227 delim="#".repeat(n), string=get_ident(s))
230 /* Name components */
231 IDENT(s, _) => get_ident(s).get().to_str(),
233 format!("'{}", get_ident(s))
238 DOC_COMMENT(s) => get_ident(s).get().to_str(),
240 INTERPOLATED(ref nt) => {
242 &NtExpr(e) => ::print::pprust::expr_to_str(e),
243 &NtMeta(e) => ::print::pprust::meta_item_to_str(e),
245 ~"an interpolated " +
247 NtItem(..) => ~"item",
248 NtBlock(..) => ~"block",
249 NtStmt(..) => ~"statement",
250 NtPat(..) => ~"pattern",
251 NtMeta(..) => fail!("should have been handled"),
252 NtExpr(..) => fail!("should have been handled above"),
254 NtIdent(..) => ~"identifier",
255 NtPath(..) => ~"path",
257 NtMatchers(..) => ~"matcher sequence"
265 pub fn can_begin_expr(t: &Token) -> bool {
274 LIT_INT(_, _) => true,
275 LIT_UINT(_, _) => true,
276 LIT_INT_UNSUFFIXED(_) => true,
277 LIT_FLOAT(_, _) => true,
278 LIT_FLOAT_UNSUFFIXED(_) => true,
280 LIT_STR_RAW(_, _) => true,
284 BINOP(MINUS) => true,
287 BINOP(OR) => true, // in lambda syntax
288 OROR => true, // in lambda syntax
290 INTERPOLATED(NtExpr(..))
291 | INTERPOLATED(NtIdent(..))
292 | INTERPOLATED(NtBlock(..))
293 | INTERPOLATED(NtPath(..)) => true,
298 /// Returns the matching close delimiter if this is an open delimiter,
299 /// otherwise `None`.
300 pub fn close_delimiter_for(t: &Token) -> Option<Token> {
302 LPAREN => Some(RPAREN),
303 LBRACE => Some(RBRACE),
304 LBRACKET => Some(RBRACKET),
309 pub fn is_lit(t: &Token) -> bool {
312 LIT_INT(_, _) => true,
313 LIT_UINT(_, _) => true,
314 LIT_INT_UNSUFFIXED(_) => true,
315 LIT_FLOAT(_, _) => true,
316 LIT_FLOAT_UNSUFFIXED(_) => true,
318 LIT_STR_RAW(_, _) => true,
323 pub fn is_ident(t: &Token) -> bool {
324 match *t { IDENT(_, _) => true, _ => false }
327 pub fn is_ident_or_path(t: &Token) -> bool {
329 IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
334 pub fn is_plain_ident(t: &Token) -> bool {
335 match *t { IDENT(_, false) => true, _ => false }
338 pub fn is_bar(t: &Token) -> bool {
339 match *t { BINOP(OR) | OROR => true, _ => false }
342 // Get the first "argument"
344 ( $first:expr, $( $remainder:expr, )* ) => ( $first )
347 // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
349 ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
350 ( $first:expr, ) => ( $first )
353 // In this macro, there is the requirement that the name (the number) must be monotonically
354 // increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
355 // except starting from the next number instead of zero, and with the additional exception that
356 // special identifiers are *also* allowed (they are deduplicated in the important place, the
357 // interner), an exception which is demonstrated by "static" and "self".
358 macro_rules! declare_special_idents_and_keywords {(
359 // So now, in these rules, why is each definition parenthesised?
360 // Answer: otherwise we get a spurious local ambiguity bug on the "}"
361 pub mod special_idents {
362 $( ($si_name:expr, $si_static:ident, $si_str:expr); )*
367 $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
369 $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
372 static STRICT_KEYWORD_START: Name = first!($( $sk_name, )*);
373 static STRICT_KEYWORD_FINAL: Name = last!($( $sk_name, )*);
374 static RESERVED_KEYWORD_START: Name = first!($( $rk_name, )*);
375 static RESERVED_KEYWORD_FINAL: Name = last!($( $rk_name, )*);
377 pub mod special_idents {
379 $( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
383 * All the valid words that have meaning in the Rust language.
385 * Rust keywords are either 'strict' or 'reserved'. Strict keywords may not
386 * appear as identifiers at all. Reserved keywords are not used anywhere in
387 * the language and may not appear as identifiers.
398 pub fn to_ident(&self) -> Ident {
400 $( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
401 $( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
407 fn mk_fresh_ident_interner() -> IdentInterner {
408 // The indices here must correspond to the numbers in
409 // special_idents, in Keyword to_ident(), and in static
411 let mut init_vec = Vec::new();
412 $(init_vec.push($si_str);)*
413 $(init_vec.push($sk_str);)*
414 $(init_vec.push($rk_str);)*
415 interner::StrInterner::prefill(init_vec.as_slice())
419 // If the special idents get renumbered, remember to modify these two as appropriate
420 static SELF_KEYWORD_NAME: Name = 1;
421 static STATIC_KEYWORD_NAME: Name = 2;
423 declare_special_idents_and_keywords! {
424 pub mod special_idents {
425 // These ones are statics
427 (super::SELF_KEYWORD_NAME, self_, "self");
428 (super::STATIC_KEYWORD_NAME, statik, "static");
432 (4, matchers, "matchers");
434 // outside of libsyntax
435 (5, clownshoe_abi, "__rust_abi");
436 (6, opaque, "<opaque>");
437 (7, unnamed_field, "<unnamed_field>");
438 (8, type_self, "Self");
442 // These ones are variants of the Keyword enum
446 (10, Break, "break");
447 (11, Const, "const");
448 (12, Crate, "crate");
451 (15, Extern, "extern");
452 (16, False, "false");
460 (24, Match, "match");
466 (30, Return, "return");
467 // Static and Self are also special idents (prefill de-dupes)
468 (super::STATIC_KEYWORD_NAME, Static, "static");
469 (super::SELF_KEYWORD_NAME, Self, "self");
470 (31, Struct, "struct");
471 (32, Super, "super");
473 (34, Trait, "trait");
475 (36, Unsafe, "unsafe");
477 (38, While, "while");
478 (39, Continue, "continue");
483 (42, Alignof, "alignof");
485 (44, Offsetof, "offsetof");
488 (47, Sizeof, "sizeof");
489 (48, Typeof, "typeof");
490 (49, Unsized, "unsized");
491 (50, Yield, "yield");
497 * Maps a token to a record specifying the corresponding binary
500 pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
502 BINOP(STAR) => Some(ast::BiMul),
503 BINOP(SLASH) => Some(ast::BiDiv),
504 BINOP(PERCENT) => Some(ast::BiRem),
505 BINOP(PLUS) => Some(ast::BiAdd),
506 BINOP(MINUS) => Some(ast::BiSub),
507 BINOP(SHL) => Some(ast::BiShl),
508 BINOP(SHR) => Some(ast::BiShr),
509 BINOP(AND) => Some(ast::BiBitAnd),
510 BINOP(CARET) => Some(ast::BiBitXor),
511 BINOP(OR) => Some(ast::BiBitOr),
512 LT => Some(ast::BiLt),
513 LE => Some(ast::BiLe),
514 GE => Some(ast::BiGe),
515 GT => Some(ast::BiGt),
516 EQEQ => Some(ast::BiEq),
517 NE => Some(ast::BiNe),
518 ANDAND => Some(ast::BiAnd),
519 OROR => Some(ast::BiOr),
524 // looks like we can get rid of this completely...
525 pub type IdentInterner = StrInterner;
527 // if an interner exists in TLS, return it. Otherwise, prepare a
529 // FIXME(eddyb) #8726 This should probably use a task-local reference.
530 pub fn get_ident_interner() -> Rc<IdentInterner> {
531 local_data_key!(key: Rc<::parse::token::IdentInterner>)
532 match local_data::get(key, |k| k.map(|k| k.clone())) {
533 Some(interner) => interner,
535 let interner = Rc::new(mk_fresh_ident_interner());
536 local_data::set(key, interner.clone());
542 /// Represents a string stored in the task-local interner. Because the
543 /// interner lives for the life of the task, this can be safely treated as an
544 /// immortal string, as long as it never crosses between tasks.
546 /// FIXME(pcwalton): You must be careful about what you do in the destructors
547 /// of objects stored in TLS, because they may run after the interner is
548 /// destroyed. In particular, they must not access string contents. This can
549 /// be fixed in the future by just leaking all strings until task death
551 #[deriving(Clone, Eq, Hash, Ord, TotalEq, TotalOrd)]
552 pub struct InternedString {
556 impl InternedString {
558 pub fn new(string: &'static str) -> InternedString {
560 string: RcStr::new(string),
565 fn new_from_rc_str(string: RcStr) -> InternedString {
572 pub fn get<'a>(&'a self) -> &'a str {
573 self.string.as_slice()
577 impl BytesContainer for InternedString {
578 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
579 // FIXME(pcwalton): This is a workaround for the incorrect signature
580 // of `BytesContainer`, which is itself a workaround for the lack of
583 let this = self.get();
584 cast::transmute(this.container_as_bytes())
589 impl fmt::Show for InternedString {
590 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
591 write!(f.buf, "{}", self.string.as_slice())
595 impl<'a> Equiv<&'a str> for InternedString {
596 fn equiv(&self, other: & &'a str) -> bool {
597 (*other) == self.string.as_slice()
601 impl<D:Decoder<E>, E> Decodable<D, E> for InternedString {
602 fn decode(d: &mut D) -> Result<InternedString, E> {
603 Ok(get_name(get_ident_interner().intern(try!(d.read_str()))))
607 impl<S:Encoder<E>, E> Encodable<S, E> for InternedString {
608 fn encode(&self, s: &mut S) -> Result<(), E> {
609 s.emit_str(self.string.as_slice())
613 /// Returns the string contents of a name, using the task-local interner.
615 pub fn get_name(name: Name) -> InternedString {
616 let interner = get_ident_interner();
617 InternedString::new_from_rc_str(interner.get(name))
620 /// Returns the string contents of an identifier, using the task-local
623 pub fn get_ident(ident: Ident) -> InternedString {
627 /// Interns and returns the string contents of an identifier, using the
628 /// task-local interner.
630 pub fn intern_and_get_ident(s: &str) -> InternedString {
634 /// Maps a string to its interned representation.
636 pub fn intern(s: &str) -> Name {
637 get_ident_interner().intern(s)
640 /// gensym's a new uint, using the current interner.
642 pub fn gensym(s: &str) -> Name {
643 get_ident_interner().gensym(s)
646 /// Maps a string to an identifier with an empty syntax context.
648 pub fn str_to_ident(s: &str) -> ast::Ident {
649 ast::Ident::new(intern(s))
652 /// Maps a string to a gensym'ed identifier.
654 pub fn gensym_ident(s: &str) -> ast::Ident {
655 ast::Ident::new(gensym(s))
658 // create a fresh name that maps to the same string as the old one.
659 // note that this guarantees that str_ptr_eq(ident_to_str(src),interner_get(fresh_name(src)));
660 // that is, that the new name and the old one are connected to ptr_eq strings.
661 pub fn fresh_name(src: &ast::Ident) -> Name {
662 let interner = get_ident_interner();
663 interner.gensym_copy(src.name)
664 // following: debug version. Could work in final except that it's incompatible with
665 // good error messages and uses of struct names in ambiguous could-be-binding
666 // locations. Also definitely destroys the guarantee given above about ptr_eq.
667 /*let num = rand::task_rng().gen_uint_range(0,0xffff);
668 gensym(format!("{}_{}",ident_to_str(src),num))*/
671 // create a fresh mark.
672 pub fn fresh_mark() -> Mrk {
676 // See the macro above about the types of keywords
678 pub fn is_keyword(kw: keywords::Keyword, tok: &Token) -> bool {
680 token::IDENT(sid, false) => { kw.to_ident().name == sid.name }
685 pub fn is_any_keyword(tok: &Token) -> bool {
687 token::IDENT(sid, false) => match sid.name {
688 SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
689 STRICT_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
696 pub fn is_strict_keyword(tok: &Token) -> bool {
698 token::IDENT(sid, false) => match sid.name {
699 SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
700 STRICT_KEYWORD_START .. STRICT_KEYWORD_FINAL => true,
707 pub fn is_reserved_keyword(tok: &Token) -> bool {
709 token::IDENT(sid, false) => match sid.name {
710 RESERVED_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
717 pub fn mtwt_token_eq(t1 : &Token, t2 : &Token) -> bool {
719 (&IDENT(id1,_),&IDENT(id2,_)) | (&LIFETIME(id1),&LIFETIME(id2)) =>
720 mtwt::resolve(id1) == mtwt::resolve(id2),
732 fn mark_ident(id : ast::Ident, m : ast::Mrk) -> ast::Ident {
733 ast::Ident{name:id.name,ctxt:mtwt::new_mark(m,id.ctxt)}
736 #[test] fn mtwt_token_eq_test() {
737 assert!(mtwt_token_eq(>,>));
738 let a = str_to_ident("bac");
739 let a1 = mark_ident(a,92);
740 assert!(mtwt_token_eq(&IDENT(a,true),&IDENT(a1,false)));