]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/token.rs
8e36339b0e5e360dcfe44ed6d4cc9f6c95670539
[rust.git] / src / libsyntax / parse / token.rs
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.
4 //
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.
10
11 use ast;
12 use ast::{P, Ident, Name, Mrk};
13 use ast_util;
14 use ext::mtwt;
15 use parse::token;
16 use util::interner::{RcStr, StrInterner};
17 use util::interner;
18
19 use serialize::{Decodable, Decoder, Encodable, Encoder};
20 use std::fmt;
21 use std::gc::Gc;
22 use std::mem;
23 use std::path::BytesContainer;
24 use std::rc::Rc;
25
26 #[allow(non_camel_case_types)]
27 #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash, Show)]
28 pub enum BinOp {
29     PLUS,
30     MINUS,
31     STAR,
32     SLASH,
33     PERCENT,
34     CARET,
35     AND,
36     OR,
37     SHL,
38     SHR,
39 }
40
41 #[allow(non_camel_case_types)]
42 #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash, Show)]
43 pub enum Token {
44     /* Expression-operator symbols. */
45     EQ,
46     LT,
47     LE,
48     EQEQ,
49     NE,
50     GE,
51     GT,
52     ANDAND,
53     OROR,
54     NOT,
55     TILDE,
56     BINOP(BinOp),
57     BINOPEQ(BinOp),
58
59     /* Structural symbols */
60     AT,
61     DOT,
62     DOTDOT,
63     DOTDOTDOT,
64     COMMA,
65     SEMI,
66     COLON,
67     MOD_SEP,
68     RARROW,
69     LARROW,
70     FAT_ARROW,
71     LPAREN,
72     RPAREN,
73     LBRACKET,
74     RBRACKET,
75     LBRACE,
76     RBRACE,
77     POUND,
78     DOLLAR,
79
80     /* Literals */
81     LIT_BYTE(u8),
82     LIT_CHAR(char),
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),
88     LIT_STR(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 */
92
93     /* Name components */
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),
98     UNDERSCORE,
99     LIFETIME(ast::Ident),
100
101     /* For interpolation */
102     INTERPOLATED(Nonterminal),
103
104     DOC_COMMENT(ast::Ident),
105     EOF,
106 }
107
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>),
116     NtTy(  P<ast::Ty>),
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> )
122 }
123
124 impl fmt::Show for Nonterminal {
125     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
126         match *self {
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(..)"),
138         }
139     }
140 }
141
142 pub fn binop_to_str(o: BinOp) -> &'static str {
143     match o {
144       PLUS => "+",
145       MINUS => "-",
146       STAR => "*",
147       SLASH => "/",
148       PERCENT => "%",
149       CARET => "^",
150       AND => "&",
151       OR => "|",
152       SHL => "<<",
153       SHR => ">>"
154     }
155 }
156
157 pub fn to_str(t: &Token) -> String {
158     match *t {
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(),
171       BINOPEQ(op) => {
172           let mut s = binop_to_str(op).to_string();
173           s.push_str("=");
174           s
175       }
176
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(),
197
198       /* Literals */
199       LIT_BYTE(b) => {
200           let mut res = String::from_str("b'");
201           (b as char).escape_default(|c| {
202               res.push_char(c);
203           });
204           res.push_char('\'');
205           res
206       }
207       LIT_CHAR(c) => {
208           let mut res = String::from_str("'");
209           c.escape_default(|c| {
210               res.push_char(c);
211           });
212           res.push_char('\'');
213           res
214       }
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() }
220       LIT_FLOAT(s, t) => {
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
224         }
225         body.push_str(ast_util::float_ty_to_str(t).as_slice());
226         body
227       }
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
232         }
233         body
234       }
235       LIT_STR(s) => {
236           format!("\"{}\"", get_ident(s).get().escape_default())
237       }
238       LIT_STR_RAW(s, n) => {
239         format!("r{delim}\"{string}\"{delim}",
240                  delim="#".repeat(n), string=get_ident(s))
241       }
242       LIT_BINARY(ref v) => {
243           format!(
244             "b\"{}\"",
245             v.iter().map(|&b| b as char).collect::<String>().escape_default())
246       }
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())
250       }
251
252       /* Name components */
253       IDENT(s, _) => get_ident(s).get().to_string(),
254       LIFETIME(s) => {
255           format!("{}", get_ident(s))
256       }
257       UNDERSCORE => "_".to_string(),
258
259       /* Other */
260       DOC_COMMENT(s) => get_ident(s).get().to_string(),
261       EOF => "<eof>".to_string(),
262       INTERPOLATED(ref nt) => {
263         match nt {
264             &NtExpr(ref e) => ::print::pprust::expr_to_str(&**e),
265             &NtMeta(ref e) => ::print::pprust::meta_item_to_str(&**e),
266             _ => {
267                 let mut s = "an interpolated ".to_string();
268                 match *nt {
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")
280                 };
281                 s
282             }
283         }
284       }
285     }
286 }
287
288 pub fn can_begin_expr(t: &Token) -> bool {
289     match *t {
290       LPAREN => true,
291       LBRACE => true,
292       LBRACKET => true,
293       IDENT(_, _) => true,
294       UNDERSCORE => true,
295       TILDE => true,
296       LIT_BYTE(_) => true,
297       LIT_CHAR(_) => true,
298       LIT_INT(_, _) => true,
299       LIT_UINT(_, _) => true,
300       LIT_INT_UNSUFFIXED(_) => true,
301       LIT_FLOAT(_, _) => true,
302       LIT_FLOAT_UNSUFFIXED(_) => true,
303       LIT_STR(_) => true,
304       LIT_STR_RAW(_, _) => true,
305       LIT_BINARY(_) => true,
306       LIT_BINARY_RAW(_, _) => true,
307       POUND => true,
308       AT => true,
309       NOT => true,
310       BINOP(MINUS) => true,
311       BINOP(STAR) => true,
312       BINOP(AND) => true,
313       BINOP(OR) => true, // in lambda syntax
314       OROR => true, // in lambda syntax
315       MOD_SEP => true,
316       INTERPOLATED(NtExpr(..))
317       | INTERPOLATED(NtIdent(..))
318       | INTERPOLATED(NtBlock(..))
319       | INTERPOLATED(NtPath(..)) => true,
320       _ => false
321     }
322 }
323
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> {
327     match *t {
328         LPAREN   => Some(RPAREN),
329         LBRACE   => Some(RBRACE),
330         LBRACKET => Some(RBRACKET),
331         _        => None
332     }
333 }
334
335 pub fn is_lit(t: &Token) -> bool {
336     match *t {
337       LIT_BYTE(_) => true,
338       LIT_CHAR(_) => true,
339       LIT_INT(_, _) => true,
340       LIT_UINT(_, _) => true,
341       LIT_INT_UNSUFFIXED(_) => true,
342       LIT_FLOAT(_, _) => true,
343       LIT_FLOAT_UNSUFFIXED(_) => true,
344       LIT_STR(_) => true,
345       LIT_STR_RAW(_, _) => true,
346       LIT_BINARY(_) => true,
347       LIT_BINARY_RAW(_, _) => true,
348       _ => false
349     }
350 }
351
352 pub fn is_ident(t: &Token) -> bool {
353     match *t { IDENT(_, _) => true, _ => false }
354 }
355
356 pub fn is_ident_or_path(t: &Token) -> bool {
357     match *t {
358       IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
359       _ => false
360     }
361 }
362
363 pub fn is_plain_ident(t: &Token) -> bool {
364     match *t { IDENT(_, false) => true, _ => false }
365 }
366
367 pub fn is_bar(t: &Token) -> bool {
368     match *t { BINOP(OR) | OROR => true, _ => false }
369 }
370
371 // Get the first "argument"
372 macro_rules! first {
373     ( $first:expr, $( $remainder:expr, )* ) => ( $first )
374 }
375
376 // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
377 macro_rules! last {
378     ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
379     ( $first:expr, ) => ( $first )
380 }
381
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); )*
392     }
393
394     pub mod keywords {
395         'strict:
396         $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
397         'reserved:
398         $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
399     }
400 ) => {
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, )*);
405
406     pub mod special_idents {
407         use ast::Ident;
408         $( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
409     }
410
411     /**
412      * All the valid words that have meaning in the Rust language.
413      *
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.
417      */
418     pub mod keywords {
419         use ast::Ident;
420
421         pub enum Keyword {
422             $( $sk_variant, )*
423             $( $rk_variant, )*
424         }
425
426         impl Keyword {
427             pub fn to_ident(&self) -> Ident {
428                 match *self {
429                     $( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
430                     $( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
431                 }
432             }
433         }
434     }
435
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
439         // constants below.
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())
445     }
446 }}
447
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;
451
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".
455
456 declare_special_idents_and_keywords! {
457     pub mod special_idents {
458         // These ones are statics
459         (0,                          invalid,                "");
460         (super::SELF_KEYWORD_NAME,   self_,                  "self");
461         (super::STATIC_KEYWORD_NAME, statik,                 "static");
462         (3,                          static_lifetime,        "'static");
463
464         // for matcher NTs
465         (4,                          tt,                     "tt");
466         (5,                          matchers,               "matchers");
467
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");
473     }
474
475     pub mod keywords {
476         // These ones are variants of the Keyword enum
477
478         'strict:
479         (10,                         As,         "as");
480         (11,                         Break,      "break");
481         (12,                         Crate,      "crate");
482         (13,                         Else,       "else");
483         (14,                         Enum,       "enum");
484         (15,                         Extern,     "extern");
485         (16,                         False,      "false");
486         (17,                         Fn,         "fn");
487         (18,                         For,        "for");
488         (19,                         If,         "if");
489         (20,                         Impl,       "impl");
490         (21,                         In,         "in");
491         (22,                         Let,        "let");
492         (23,                         Loop,       "loop");
493         (24,                         Match,      "match");
494         (25,                         Mod,        "mod");
495         (26,                         Mut,        "mut");
496         (27,                         Once,       "once");
497         (28,                         Pub,        "pub");
498         (29,                         Ref,        "ref");
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");
505         (33,                         True,       "true");
506         (34,                         Trait,      "trait");
507         (35,                         Type,       "type");
508         (36,                         Unsafe,     "unsafe");
509         (37,                         Use,        "use");
510         (38,                         Virtual,    "virtual");
511         (39,                         While,      "while");
512         (40,                         Continue,   "continue");
513         (41,                         Proc,       "proc");
514         (42,                         Box,        "box");
515         (43,                         Const,      "const");
516
517         'reserved:
518         (44,                         Alignof,    "alignof");
519         (45,                         Be,         "be");
520         (46,                         Offsetof,   "offsetof");
521         (47,                         Priv,       "priv");
522         (48,                         Pure,       "pure");
523         (49,                         Sizeof,     "sizeof");
524         (50,                         Typeof,     "typeof");
525         (51,                         Unsized,    "unsized");
526         (52,                         Yield,      "yield");
527         (53,                         Do,         "do");
528     }
529 }
530
531 /**
532  * Maps a token to a record specifying the corresponding binary
533  * operator
534  */
535 pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
536   match *tok {
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),
555       _              => None
556   }
557 }
558
559 // looks like we can get rid of this completely...
560 pub type IdentInterner = StrInterner;
561
562 // if an interner exists in TLS, return it. Otherwise, prepare a
563 // fresh one.
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>)
567     match key.get() {
568         Some(interner) => interner.clone(),
569         None => {
570             let interner = Rc::new(mk_fresh_ident_interner());
571             key.replace(Some(interner.clone()));
572             interner
573         }
574     }
575 }
576
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.
580 ///
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
585 /// somehow.
586 #[deriving(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
587 pub struct InternedString {
588     string: RcStr,
589 }
590
591 impl InternedString {
592     #[inline]
593     pub fn new(string: &'static str) -> InternedString {
594         InternedString {
595             string: RcStr::new(string),
596         }
597     }
598
599     #[inline]
600     fn new_from_rc_str(string: RcStr) -> InternedString {
601         InternedString {
602             string: string,
603         }
604     }
605
606     #[inline]
607     pub fn get<'a>(&'a self) -> &'a str {
608         self.string.as_slice()
609     }
610 }
611
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
616         // DST.
617         unsafe {
618             let this = self.get();
619             mem::transmute(this.container_as_bytes())
620         }
621     }
622 }
623
624 impl fmt::Show for InternedString {
625     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
626         write!(f, "{}", self.string.as_slice())
627     }
628 }
629
630 impl<'a> Equiv<&'a str> for InternedString {
631     fn equiv(&self, other: & &'a str) -> bool {
632         (*other) == self.string.as_slice()
633     }
634 }
635
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())))
640     }
641 }
642
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())
646     }
647 }
648
649 /// Returns the string contents of a name, using the task-local interner.
650 #[inline]
651 pub fn get_name(name: Name) -> InternedString {
652     let interner = get_ident_interner();
653     InternedString::new_from_rc_str(interner.get(name))
654 }
655
656 /// Returns the string contents of an identifier, using the task-local
657 /// interner.
658 #[inline]
659 pub fn get_ident(ident: Ident) -> InternedString {
660     get_name(ident.name)
661 }
662
663 /// Interns and returns the string contents of an identifier, using the
664 /// task-local interner.
665 #[inline]
666 pub fn intern_and_get_ident(s: &str) -> InternedString {
667     get_name(intern(s))
668 }
669
670 /// Maps a string to its interned representation.
671 #[inline]
672 pub fn intern(s: &str) -> Name {
673     get_ident_interner().intern(s)
674 }
675
676 /// gensym's a new uint, using the current interner.
677 #[inline]
678 pub fn gensym(s: &str) -> Name {
679     get_ident_interner().gensym(s)
680 }
681
682 /// Maps a string to an identifier with an empty syntax context.
683 #[inline]
684 pub fn str_to_ident(s: &str) -> ast::Ident {
685     ast::Ident::new(intern(s))
686 }
687
688 /// Maps a string to a gensym'ed identifier.
689 #[inline]
690 pub fn gensym_ident(s: &str) -> ast::Ident {
691     ast::Ident::new(gensym(s))
692 }
693
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))*/
705 }
706
707 // create a fresh mark.
708 pub fn fresh_mark() -> Mrk {
709     gensym("mark")
710 }
711
712 // See the macro above about the types of keywords
713
714 pub fn is_keyword(kw: keywords::Keyword, tok: &Token) -> bool {
715     match *tok {
716         token::IDENT(sid, false) => { kw.to_ident().name == sid.name }
717         _ => { false }
718     }
719 }
720
721 pub fn is_any_keyword(tok: &Token) -> bool {
722     match *tok {
723         token::IDENT(sid, false) => match sid.name {
724             SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
725             STRICT_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
726             _ => false,
727         },
728         _ => false
729     }
730 }
731
732 pub fn is_strict_keyword(tok: &Token) -> bool {
733     match *tok {
734         token::IDENT(sid, false) => match sid.name {
735             SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
736             STRICT_KEYWORD_START .. STRICT_KEYWORD_FINAL => true,
737             _ => false,
738         },
739         _ => false,
740     }
741 }
742
743 pub fn is_reserved_keyword(tok: &Token) -> bool {
744     match *tok {
745         token::IDENT(sid, false) => match sid.name {
746             RESERVED_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
747             _ => false,
748         },
749         _ => false,
750     }
751 }
752
753 pub fn mtwt_token_eq(t1 : &Token, t2 : &Token) -> bool {
754     match (t1,t2) {
755         (&IDENT(id1,_),&IDENT(id2,_)) | (&LIFETIME(id1),&LIFETIME(id2)) =>
756             mtwt::resolve(id1) == mtwt::resolve(id2),
757         _ => *t1 == *t2
758     }
759 }
760
761
762 #[cfg(test)]
763 mod test {
764     use super::*;
765     use ast;
766     use ext::mtwt;
767
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)}
770     }
771
772     #[test] fn mtwt_token_eq_test() {
773         assert!(mtwt_token_eq(&GT,&GT));
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)));
777     }
778 }