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 #[allow(non_camel_case_types)]
27 #[deriving(Clone, Encodable, Decodable, Eq, TotalEq, Hash, Show)]
41 #[allow(non_camel_case_types)]
42 #[deriving(Clone, Encodable, Decodable, Eq, TotalEq, 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 */
92 // an identifier contains an "is_mod_name" boolean,
93 // indicating whether :: follows this token with no
94 // whitespace in between.
95 IDENT(ast::Ident, bool),
99 /* For interpolation */
100 INTERPOLATED(Nonterminal),
102 DOC_COMMENT(ast::Ident),
106 #[deriving(Clone, Encodable, Decodable, Eq, TotalEq, Hash)]
107 /// For interpolation during macro expansion.
108 pub enum Nonterminal {
110 NtBlock(P<ast::Block>),
115 NtIdent(~ast::Ident, bool),
116 NtAttr(@ast::Attribute), // #[foo]
118 NtTT( @ast::TokenTree), // needs @ed to break a circularity
119 NtMatchers(Vec<ast::Matcher> )
122 impl fmt::Show for Nonterminal {
123 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
125 NtItem(..) => f.pad("NtItem(..)"),
126 NtBlock(..) => f.pad("NtBlock(..)"),
127 NtStmt(..) => f.pad("NtStmt(..)"),
128 NtPat(..) => f.pad("NtPat(..)"),
129 NtExpr(..) => f.pad("NtExpr(..)"),
130 NtTy(..) => f.pad("NtTy(..)"),
131 NtIdent(..) => f.pad("NtIdent(..)"),
132 NtAttr(..) => f.pad("NtAttr(..)"),
133 NtPath(..) => f.pad("NtPath(..)"),
134 NtTT(..) => f.pad("NtTT(..)"),
135 NtMatchers(..) => f.pad("NtMatchers(..)"),
140 pub fn binop_to_str(o: BinOp) -> ~str {
155 pub fn to_str(t: &Token) -> ~str {
168 BINOP(op) => binop_to_str(op),
169 BINOPEQ(op) => binop_to_str(op) + "=",
171 /* Structural symbols */
196 char::from_u32(c).unwrap().escape_default(|c| {
203 i.to_str() + ast_util::int_ty_to_str(t)
206 u.to_str() + ast_util::uint_ty_to_str(t)
208 LIT_INT_UNSUFFIXED(i) => { i.to_str() }
210 let mut body = get_ident(s).get().to_str();
211 if body.ends_with(".") {
212 body.push_char('0'); // `10.f` is not a float literal
214 body + ast_util::float_ty_to_str(t)
216 LIT_FLOAT_UNSUFFIXED(s) => {
217 let mut body = get_ident(s).get().to_str();
218 if body.ends_with(".") {
219 body.push_char('0'); // `10.f` is not a float literal
224 format!("\"{}\"", get_ident(s).get().escape_default())
226 LIT_STR_RAW(s, n) => {
227 format!("r{delim}\"{string}\"{delim}",
228 delim="#".repeat(n), string=get_ident(s))
231 /* Name components */
232 IDENT(s, _) => get_ident(s).get().to_str(),
234 format!("'{}", get_ident(s))
239 DOC_COMMENT(s) => get_ident(s).get().to_str(),
241 INTERPOLATED(ref nt) => {
243 &NtExpr(e) => ::print::pprust::expr_to_str(e),
244 &NtAttr(e) => ::print::pprust::attribute_to_str(e),
246 ~"an interpolated " +
248 NtItem(..) => ~"item",
249 NtBlock(..) => ~"block",
250 NtStmt(..) => ~"statement",
251 NtPat(..) => ~"pattern",
252 NtAttr(..) => fail!("should have been handled"),
253 NtExpr(..) => fail!("should have been handled above"),
255 NtIdent(..) => ~"identifier",
256 NtPath(..) => ~"path",
258 NtMatchers(..) => ~"matcher sequence"
266 pub fn can_begin_expr(t: &Token) -> bool {
275 LIT_INT(_, _) => true,
276 LIT_UINT(_, _) => true,
277 LIT_INT_UNSUFFIXED(_) => true,
278 LIT_FLOAT(_, _) => true,
279 LIT_FLOAT_UNSUFFIXED(_) => true,
281 LIT_STR_RAW(_, _) => true,
285 BINOP(MINUS) => true,
288 BINOP(OR) => true, // in lambda syntax
289 OROR => true, // in lambda syntax
291 INTERPOLATED(NtExpr(..))
292 | INTERPOLATED(NtIdent(..))
293 | INTERPOLATED(NtBlock(..))
294 | INTERPOLATED(NtPath(..)) => true,
299 /// what's the opposite delimiter?
300 pub fn flip_delimiter(t: &token::Token) -> token::Token {
304 LBRACKET => RBRACKET,
307 RBRACKET => LBRACKET,
314 pub fn is_lit(t: &Token) -> bool {
317 LIT_INT(_, _) => true,
318 LIT_UINT(_, _) => true,
319 LIT_INT_UNSUFFIXED(_) => true,
320 LIT_FLOAT(_, _) => true,
321 LIT_FLOAT_UNSUFFIXED(_) => true,
323 LIT_STR_RAW(_, _) => true,
328 pub fn is_ident(t: &Token) -> bool {
329 match *t { IDENT(_, _) => true, _ => false }
332 pub fn is_ident_or_path(t: &Token) -> bool {
334 IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
339 pub fn is_plain_ident(t: &Token) -> bool {
340 match *t { IDENT(_, false) => true, _ => false }
343 pub fn is_bar(t: &Token) -> bool {
344 match *t { BINOP(OR) | OROR => true, _ => false }
347 // Get the first "argument"
349 ( $first:expr, $( $remainder:expr, )* ) => ( $first )
352 // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
354 ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
355 ( $first:expr, ) => ( $first )
358 // In this macro, there is the requirement that the name (the number) must be monotonically
359 // increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
360 // except starting from the next number instead of zero, and with the additional exception that
361 // special identifiers are *also* allowed (they are deduplicated in the important place, the
362 // interner), an exception which is demonstrated by "static" and "self".
363 macro_rules! declare_special_idents_and_keywords {(
364 // So now, in these rules, why is each definition parenthesised?
365 // Answer: otherwise we get a spurious local ambiguity bug on the "}"
366 pub mod special_idents {
367 $( ($si_name:expr, $si_static:ident, $si_str:expr); )*
372 $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
374 $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
377 static STRICT_KEYWORD_START: Name = first!($( $sk_name, )*);
378 static STRICT_KEYWORD_FINAL: Name = last!($( $sk_name, )*);
379 static RESERVED_KEYWORD_START: Name = first!($( $rk_name, )*);
380 static RESERVED_KEYWORD_FINAL: Name = last!($( $rk_name, )*);
382 pub mod special_idents {
384 $( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
388 * All the valid words that have meaning in the Rust language.
390 * Rust keywords are either 'strict' or 'reserved'. Strict keywords may not
391 * appear as identifiers at all. Reserved keywords are not used anywhere in
392 * the language and may not appear as identifiers.
403 pub fn to_ident(&self) -> Ident {
405 $( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
406 $( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
412 fn mk_fresh_ident_interner() -> IdentInterner {
413 // The indices here must correspond to the numbers in
414 // special_idents, in Keyword to_ident(), and in static
416 let mut init_vec = Vec::new();
417 $(init_vec.push($si_str);)*
418 $(init_vec.push($sk_str);)*
419 $(init_vec.push($rk_str);)*
420 interner::StrInterner::prefill(init_vec.as_slice())
424 // If the special idents get renumbered, remember to modify these two as appropriate
425 static SELF_KEYWORD_NAME: Name = 1;
426 static STATIC_KEYWORD_NAME: Name = 2;
428 declare_special_idents_and_keywords! {
429 pub mod special_idents {
430 // These ones are statics
432 (super::SELF_KEYWORD_NAME, self_, "self");
433 (super::STATIC_KEYWORD_NAME, statik, "static");
437 (4, matchers, "matchers");
439 // outside of libsyntax
440 (5, clownshoe_abi, "__rust_abi");
441 (6, opaque, "<opaque>");
442 (7, unnamed_field, "<unnamed_field>");
443 (8, type_self, "Self");
447 // These ones are variants of the Keyword enum
451 (10, Break, "break");
452 (11, Const, "const");
453 (12, Crate, "crate");
456 (15, Extern, "extern");
457 (16, False, "false");
465 (24, Match, "match");
472 (31, Return, "return");
473 // Static and Self are also special idents (prefill de-dupes)
474 (super::STATIC_KEYWORD_NAME, Static, "static");
475 (super::SELF_KEYWORD_NAME, Self, "self");
476 (32, Struct, "struct");
477 (33, Super, "super");
479 (35, Trait, "trait");
481 (37, Unsafe, "unsafe");
483 (39, While, "while");
484 (40, Continue, "continue");
489 (43, Alignof, "alignof");
491 (45, Offsetof, "offsetof");
493 (47, Sizeof, "sizeof");
494 (48, Typeof, "typeof");
495 (49, Unsized, "unsized");
496 (50, Yield, "yield");
502 * Maps a token to a record specifying the corresponding binary
505 pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
507 BINOP(STAR) => Some(ast::BiMul),
508 BINOP(SLASH) => Some(ast::BiDiv),
509 BINOP(PERCENT) => Some(ast::BiRem),
510 BINOP(PLUS) => Some(ast::BiAdd),
511 BINOP(MINUS) => Some(ast::BiSub),
512 BINOP(SHL) => Some(ast::BiShl),
513 BINOP(SHR) => Some(ast::BiShr),
514 BINOP(AND) => Some(ast::BiBitAnd),
515 BINOP(CARET) => Some(ast::BiBitXor),
516 BINOP(OR) => Some(ast::BiBitOr),
517 LT => Some(ast::BiLt),
518 LE => Some(ast::BiLe),
519 GE => Some(ast::BiGe),
520 GT => Some(ast::BiGt),
521 EQEQ => Some(ast::BiEq),
522 NE => Some(ast::BiNe),
523 ANDAND => Some(ast::BiAnd),
524 OROR => Some(ast::BiOr),
529 // looks like we can get rid of this completely...
530 pub type IdentInterner = StrInterner;
532 // if an interner exists in TLS, return it. Otherwise, prepare a
534 pub fn get_ident_interner() -> @IdentInterner {
535 local_data_key!(key: @::parse::token::IdentInterner)
536 match local_data::get(key, |k| k.map(|k| *k)) {
537 Some(interner) => interner,
539 let interner = @mk_fresh_ident_interner();
540 local_data::set(key, interner);
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, Eq, Hash, Ord, TotalEq, TotalOrd)]
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 cast::transmute(this.container_as_bytes())
593 impl fmt::Show for InternedString {
594 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
595 write!(f.buf, "{}", 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> Decodable<D> for InternedString {
606 fn decode(d: &mut D) -> InternedString {
607 get_name(get_ident_interner().intern(d.read_str()))
611 impl<E:Encoder> Encodable<E> for InternedString {
612 fn encode(&self, e: &mut E) {
613 e.emit_str(self.string.as_slice())
617 /// Returns the string contents of a name, using the task-local interner.
619 pub fn get_name(name: Name) -> InternedString {
620 let interner = get_ident_interner();
621 InternedString::new_from_rc_str(interner.get(name))
624 /// Returns the string contents of an identifier, using the task-local
627 pub fn get_ident(ident: Ident) -> InternedString {
631 /// Interns and returns the string contents of an identifier, using the
632 /// task-local interner.
634 pub fn intern_and_get_ident(s: &str) -> InternedString {
638 /// Maps a string to its interned representation.
640 pub fn intern(s: &str) -> Name {
641 get_ident_interner().intern(s)
644 /// gensym's a new uint, using the current interner.
646 pub fn gensym(s: &str) -> Name {
647 get_ident_interner().gensym(s)
650 /// Maps a string to an identifier with an empty syntax context.
652 pub fn str_to_ident(s: &str) -> ast::Ident {
653 ast::Ident::new(intern(s))
656 /// Maps a string to a gensym'ed identifier.
658 pub fn gensym_ident(s: &str) -> ast::Ident {
659 ast::Ident::new(gensym(s))
662 // create a fresh name that maps to the same string as the old one.
663 // note that this guarantees that str_ptr_eq(ident_to_str(src),interner_get(fresh_name(src)));
664 // that is, that the new name and the old one are connected to ptr_eq strings.
665 pub fn fresh_name(src: &ast::Ident) -> Name {
666 let interner = get_ident_interner();
667 interner.gensym_copy(src.name)
668 // following: debug version. Could work in final except that it's incompatible with
669 // good error messages and uses of struct names in ambiguous could-be-binding
670 // locations. Also definitely destroys the guarantee given above about ptr_eq.
671 /*let num = rand::task_rng().gen_uint_range(0,0xffff);
672 gensym(format!("{}_{}",ident_to_str(src),num))*/
675 // create a fresh mark.
676 pub fn fresh_mark() -> Mrk {
680 // See the macro above about the types of keywords
682 pub fn is_keyword(kw: keywords::Keyword, tok: &Token) -> bool {
684 token::IDENT(sid, false) => { kw.to_ident().name == sid.name }
689 pub fn is_any_keyword(tok: &Token) -> bool {
691 token::IDENT(sid, false) => match sid.name {
692 SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
693 STRICT_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
700 pub fn is_strict_keyword(tok: &Token) -> bool {
702 token::IDENT(sid, false) => match sid.name {
703 SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
704 STRICT_KEYWORD_START .. STRICT_KEYWORD_FINAL => true,
711 pub fn is_reserved_keyword(tok: &Token) -> bool {
713 token::IDENT(sid, false) => match sid.name {
714 RESERVED_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
721 pub fn mtwt_token_eq(t1 : &Token, t2 : &Token) -> bool {
723 (&IDENT(id1,_),&IDENT(id2,_)) | (&LIFETIME(id1),&LIFETIME(id2)) =>
724 mtwt::resolve(id1) == mtwt::resolve(id2),
736 fn mark_ident(id : ast::Ident, m : ast::Mrk) -> ast::Ident {
737 ast::Ident{name:id.name,ctxt:mtwt::new_mark(m,id.ctxt)}
740 #[test] fn mtwt_token_eq_test() {
741 assert!(mtwt_token_eq(>,>));
742 let a = str_to_ident("bac");
743 let a1 = mark_ident(a,92);
744 assert!(mtwt_token_eq(&IDENT(a,true),&IDENT(a1,false)));