]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/token.rs
librustc: Fix the issue with labels shadowing variable names by making
[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_CHAR(char),
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),
87     LIT_STR(ast::Ident),
88     LIT_STR_RAW(ast::Ident, uint), /* raw str delimited by n hash symbols */
89
90     /* Name components */
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),
95     UNDERSCORE,
96     LIFETIME(ast::Ident),
97
98     /* For interpolation */
99     INTERPOLATED(Nonterminal),
100
101     DOC_COMMENT(ast::Ident),
102     EOF,
103 }
104
105 #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)]
106 /// For interpolation during macro expansion.
107 pub enum Nonterminal {
108     NtItem(Gc<ast::Item>),
109     NtBlock(P<ast::Block>),
110     NtStmt(Gc<ast::Stmt>),
111     NtPat( Gc<ast::Pat>),
112     NtExpr(Gc<ast::Expr>),
113     NtTy(  P<ast::Ty>),
114     NtIdent(Box<ast::Ident>, bool),
115     NtMeta(Gc<ast::MetaItem>), // stuff inside brackets for attributes
116     NtPath(Box<ast::Path>),
117     NtTT(  Gc<ast::TokenTree>), // needs @ed to break a circularity
118     NtMatchers(Vec<ast::Matcher> )
119 }
120
121 impl fmt::Show for Nonterminal {
122     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
123         match *self {
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(..)"),
135         }
136     }
137 }
138
139 pub fn binop_to_str(o: BinOp) -> &'static str {
140     match o {
141       PLUS => "+",
142       MINUS => "-",
143       STAR => "*",
144       SLASH => "/",
145       PERCENT => "%",
146       CARET => "^",
147       AND => "&",
148       OR => "|",
149       SHL => "<<",
150       SHR => ">>"
151     }
152 }
153
154 pub fn to_str(t: &Token) -> String {
155     match *t {
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).to_string(),
168       BINOPEQ(op) => {
169           let mut s = binop_to_str(op).to_string();
170           s.push_str("=");
171           s
172       }
173
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(),
194
195       /* Literals */
196       LIT_CHAR(c) => {
197           let mut res = String::from_str("'");
198           c.escape_default(|c| {
199               res.push_char(c);
200           });
201           res.push_char('\'');
202           res
203       }
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() }
209       LIT_FLOAT(s, t) => {
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
213         }
214         body.push_str(ast_util::float_ty_to_str(t).as_slice());
215         body
216       }
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
221         }
222         body
223       }
224       LIT_STR(s) => {
225           (format!("\"{}\"", get_ident(s).get().escape_default())).to_string()
226       }
227       LIT_STR_RAW(s, n) => {
228           (format!("r{delim}\"{string}\"{delim}",
229                   delim="#".repeat(n), string=get_ident(s))).to_string()
230       }
231
232       /* Name components */
233       IDENT(s, _) => get_ident(s).get().to_string(),
234       LIFETIME(s) => {
235           (format!("{}", get_ident(s))).to_string()
236       }
237       UNDERSCORE => "_".to_string(),
238
239       /* Other */
240       DOC_COMMENT(s) => get_ident(s).get().to_string(),
241       EOF => "<eof>".to_string(),
242       INTERPOLATED(ref nt) => {
243         match nt {
244             &NtExpr(ref e) => ::print::pprust::expr_to_str(&**e),
245             &NtMeta(ref e) => ::print::pprust::meta_item_to_str(&**e),
246             _ => {
247                 let mut s = "an interpolated ".to_string();
248                 match *nt {
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")
260                 };
261                 s
262             }
263         }
264       }
265     }
266 }
267
268 pub fn can_begin_expr(t: &Token) -> bool {
269     match *t {
270       LPAREN => true,
271       LBRACE => true,
272       LBRACKET => true,
273       IDENT(_, _) => true,
274       UNDERSCORE => true,
275       TILDE => true,
276       LIT_CHAR(_) => true,
277       LIT_INT(_, _) => true,
278       LIT_UINT(_, _) => true,
279       LIT_INT_UNSUFFIXED(_) => true,
280       LIT_FLOAT(_, _) => true,
281       LIT_FLOAT_UNSUFFIXED(_) => true,
282       LIT_STR(_) => true,
283       LIT_STR_RAW(_, _) => true,
284       POUND => true,
285       AT => true,
286       NOT => true,
287       BINOP(MINUS) => true,
288       BINOP(STAR) => true,
289       BINOP(AND) => true,
290       BINOP(OR) => true, // in lambda syntax
291       OROR => true, // in lambda syntax
292       MOD_SEP => true,
293       INTERPOLATED(NtExpr(..))
294       | INTERPOLATED(NtIdent(..))
295       | INTERPOLATED(NtBlock(..))
296       | INTERPOLATED(NtPath(..)) => true,
297       _ => false
298     }
299 }
300
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> {
304     match *t {
305         LPAREN   => Some(RPAREN),
306         LBRACE   => Some(RBRACE),
307         LBRACKET => Some(RBRACKET),
308         _        => None
309     }
310 }
311
312 pub fn is_lit(t: &Token) -> bool {
313     match *t {
314       LIT_CHAR(_) => true,
315       LIT_INT(_, _) => true,
316       LIT_UINT(_, _) => true,
317       LIT_INT_UNSUFFIXED(_) => true,
318       LIT_FLOAT(_, _) => true,
319       LIT_FLOAT_UNSUFFIXED(_) => true,
320       LIT_STR(_) => true,
321       LIT_STR_RAW(_, _) => true,
322       _ => false
323     }
324 }
325
326 pub fn is_ident(t: &Token) -> bool {
327     match *t { IDENT(_, _) => true, _ => false }
328 }
329
330 pub fn is_ident_or_path(t: &Token) -> bool {
331     match *t {
332       IDENT(_, _) | INTERPOLATED(NtPath(..)) => true,
333       _ => false
334     }
335 }
336
337 pub fn is_plain_ident(t: &Token) -> bool {
338     match *t { IDENT(_, false) => true, _ => false }
339 }
340
341 pub fn is_bar(t: &Token) -> bool {
342     match *t { BINOP(OR) | OROR => true, _ => false }
343 }
344
345 // Get the first "argument"
346 macro_rules! first {
347     ( $first:expr, $( $remainder:expr, )* ) => ( $first )
348 }
349
350 // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
351 macro_rules! last {
352     ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
353     ( $first:expr, ) => ( $first )
354 }
355
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); )*
366     }
367
368     pub mod keywords {
369         'strict:
370         $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
371         'reserved:
372         $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
373     }
374 ) => {
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, )*);
379
380     pub mod special_idents {
381         use ast::Ident;
382         $( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )*
383     }
384
385     /**
386      * All the valid words that have meaning in the Rust language.
387      *
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.
391      */
392     pub mod keywords {
393         use ast::Ident;
394
395         pub enum Keyword {
396             $( $sk_variant, )*
397             $( $rk_variant, )*
398         }
399
400         impl Keyword {
401             pub fn to_ident(&self) -> Ident {
402                 match *self {
403                     $( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )*
404                     $( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )*
405                 }
406             }
407         }
408     }
409
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
413         // constants below.
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())
419     }
420 }}
421
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;
425
426 // NB: leaving holes in the ident table is bad! a different ident will get
427 // interned with the id from the hole, but it will be between the min and max
428 // of the reserved words, and thus tagged as "reserved".
429
430 declare_special_idents_and_keywords! {
431     pub mod special_idents {
432         // These ones are statics
433         (0,                          invalid,                "");
434         (super::SELF_KEYWORD_NAME,   self_,                  "self");
435         (super::STATIC_KEYWORD_NAME, statik,                 "static");
436         (3,                          static_lifetime,        "'static");
437
438         // for matcher NTs
439         (4,                          tt,                     "tt");
440         (5,                          matchers,               "matchers");
441
442         // outside of libsyntax
443         (6,                          clownshoe_abi,          "__rust_abi");
444         (7,                          opaque,                 "<opaque>");
445         (8,                          unnamed_field,          "<unnamed_field>");
446         (9,                          type_self,              "Self");
447     }
448
449     pub mod keywords {
450         // These ones are variants of the Keyword enum
451
452         'strict:
453         (10,                         As,         "as");
454         (11,                         Break,      "break");
455         (12,                         Crate,      "crate");
456         (13,                         Else,       "else");
457         (14,                         Enum,       "enum");
458         (15,                         Extern,     "extern");
459         (16,                         False,      "false");
460         (17,                         Fn,         "fn");
461         (18,                         For,        "for");
462         (19,                         If,         "if");
463         (20,                         Impl,       "impl");
464         (21,                         In,         "in");
465         (22,                         Let,        "let");
466         (23,                         Loop,       "loop");
467         (24,                         Match,      "match");
468         (25,                         Mod,        "mod");
469         (26,                         Mut,        "mut");
470         (27,                         Once,       "once");
471         (28,                         Pub,        "pub");
472         (29,                         Ref,        "ref");
473         (30,                         Return,     "return");
474         // Static and Self are also special idents (prefill de-dupes)
475         (super::STATIC_KEYWORD_NAME, Static,     "static");
476         (super::SELF_KEYWORD_NAME,   Self,       "self");
477         (31,                         Struct,     "struct");
478         (32,                         Super,      "super");
479         (33,                         True,       "true");
480         (34,                         Trait,      "trait");
481         (35,                         Type,       "type");
482         (36,                         Unsafe,     "unsafe");
483         (37,                         Use,        "use");
484         (38,                         Virtual,    "virtual");
485         (39,                         While,      "while");
486         (40,                         Continue,   "continue");
487         (41,                         Proc,       "proc");
488         (42,                         Box,        "box");
489
490         'reserved:
491         (43,                         Alignof,    "alignof");
492         (44,                         Be,         "be");
493         (45,                         Const,      "const");
494         (46,                         Offsetof,   "offsetof");
495         (47,                         Priv,       "priv");
496         (48,                         Pure,       "pure");
497         (49,                         Sizeof,     "sizeof");
498         (50,                         Typeof,     "typeof");
499         (51,                         Unsized,    "unsized");
500         (52,                         Yield,      "yield");
501         (53,                         Do,         "do");
502     }
503 }
504
505 /**
506  * Maps a token to a record specifying the corresponding binary
507  * operator
508  */
509 pub fn token_to_binop(tok: &Token) -> Option<ast::BinOp> {
510   match *tok {
511       BINOP(STAR)    => Some(ast::BiMul),
512       BINOP(SLASH)   => Some(ast::BiDiv),
513       BINOP(PERCENT) => Some(ast::BiRem),
514       BINOP(PLUS)    => Some(ast::BiAdd),
515       BINOP(MINUS)   => Some(ast::BiSub),
516       BINOP(SHL)     => Some(ast::BiShl),
517       BINOP(SHR)     => Some(ast::BiShr),
518       BINOP(AND)     => Some(ast::BiBitAnd),
519       BINOP(CARET)   => Some(ast::BiBitXor),
520       BINOP(OR)      => Some(ast::BiBitOr),
521       LT             => Some(ast::BiLt),
522       LE             => Some(ast::BiLe),
523       GE             => Some(ast::BiGe),
524       GT             => Some(ast::BiGt),
525       EQEQ           => Some(ast::BiEq),
526       NE             => Some(ast::BiNe),
527       ANDAND         => Some(ast::BiAnd),
528       OROR           => Some(ast::BiOr),
529       _              => None
530   }
531 }
532
533 // looks like we can get rid of this completely...
534 pub type IdentInterner = StrInterner;
535
536 // if an interner exists in TLS, return it. Otherwise, prepare a
537 // fresh one.
538 // FIXME(eddyb) #8726 This should probably use a task-local reference.
539 pub fn get_ident_interner() -> Rc<IdentInterner> {
540     local_data_key!(key: Rc<::parse::token::IdentInterner>)
541     match key.get() {
542         Some(interner) => interner.clone(),
543         None => {
544             let interner = Rc::new(mk_fresh_ident_interner());
545             key.replace(Some(interner.clone()));
546             interner
547         }
548     }
549 }
550
551 /// Represents a string stored in the task-local interner. Because the
552 /// interner lives for the life of the task, this can be safely treated as an
553 /// immortal string, as long as it never crosses between tasks.
554 ///
555 /// FIXME(pcwalton): You must be careful about what you do in the destructors
556 /// of objects stored in TLS, because they may run after the interner is
557 /// destroyed. In particular, they must not access string contents. This can
558 /// be fixed in the future by just leaking all strings until task death
559 /// somehow.
560 #[deriving(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
561 pub struct InternedString {
562     string: RcStr,
563 }
564
565 impl InternedString {
566     #[inline]
567     pub fn new(string: &'static str) -> InternedString {
568         InternedString {
569             string: RcStr::new(string),
570         }
571     }
572
573     #[inline]
574     fn new_from_rc_str(string: RcStr) -> InternedString {
575         InternedString {
576             string: string,
577         }
578     }
579
580     #[inline]
581     pub fn get<'a>(&'a self) -> &'a str {
582         self.string.as_slice()
583     }
584 }
585
586 impl BytesContainer for InternedString {
587     fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
588         // FIXME(pcwalton): This is a workaround for the incorrect signature
589         // of `BytesContainer`, which is itself a workaround for the lack of
590         // DST.
591         unsafe {
592             let this = self.get();
593             mem::transmute(this.container_as_bytes())
594         }
595     }
596 }
597
598 impl fmt::Show for InternedString {
599     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
600         write!(f, "{}", self.string.as_slice())
601     }
602 }
603
604 impl<'a> Equiv<&'a str> for InternedString {
605     fn equiv(&self, other: & &'a str) -> bool {
606         (*other) == self.string.as_slice()
607     }
608 }
609
610 impl<D:Decoder<E>, E> Decodable<D, E> for InternedString {
611     fn decode(d: &mut D) -> Result<InternedString, E> {
612         Ok(get_name(get_ident_interner().intern(
613                     try!(d.read_str()).as_slice())))
614     }
615 }
616
617 impl<S:Encoder<E>, E> Encodable<S, E> for InternedString {
618     fn encode(&self, s: &mut S) -> Result<(), E> {
619         s.emit_str(self.string.as_slice())
620     }
621 }
622
623 /// Returns the string contents of a name, using the task-local interner.
624 #[inline]
625 pub fn get_name(name: Name) -> InternedString {
626     let interner = get_ident_interner();
627     InternedString::new_from_rc_str(interner.get(name))
628 }
629
630 /// Returns the string contents of an identifier, using the task-local
631 /// interner.
632 #[inline]
633 pub fn get_ident(ident: Ident) -> InternedString {
634     get_name(ident.name)
635 }
636
637 /// Interns and returns the string contents of an identifier, using the
638 /// task-local interner.
639 #[inline]
640 pub fn intern_and_get_ident(s: &str) -> InternedString {
641     get_name(intern(s))
642 }
643
644 /// Maps a string to its interned representation.
645 #[inline]
646 pub fn intern(s: &str) -> Name {
647     get_ident_interner().intern(s)
648 }
649
650 /// gensym's a new uint, using the current interner.
651 #[inline]
652 pub fn gensym(s: &str) -> Name {
653     get_ident_interner().gensym(s)
654 }
655
656 /// Maps a string to an identifier with an empty syntax context.
657 #[inline]
658 pub fn str_to_ident(s: &str) -> ast::Ident {
659     ast::Ident::new(intern(s))
660 }
661
662 /// Maps a string to a gensym'ed identifier.
663 #[inline]
664 pub fn gensym_ident(s: &str) -> ast::Ident {
665     ast::Ident::new(gensym(s))
666 }
667
668 // create a fresh name that maps to the same string as the old one.
669 // note that this guarantees that str_ptr_eq(ident_to_str(src),interner_get(fresh_name(src)));
670 // that is, that the new name and the old one are connected to ptr_eq strings.
671 pub fn fresh_name(src: &ast::Ident) -> Name {
672     let interner = get_ident_interner();
673     interner.gensym_copy(src.name)
674     // following: debug version. Could work in final except that it's incompatible with
675     // good error messages and uses of struct names in ambiguous could-be-binding
676     // locations. Also definitely destroys the guarantee given above about ptr_eq.
677     /*let num = rand::task_rng().gen_uint_range(0,0xffff);
678     gensym(format!("{}_{}",ident_to_str(src),num))*/
679 }
680
681 // create a fresh mark.
682 pub fn fresh_mark() -> Mrk {
683     gensym("mark")
684 }
685
686 // See the macro above about the types of keywords
687
688 pub fn is_keyword(kw: keywords::Keyword, tok: &Token) -> bool {
689     match *tok {
690         token::IDENT(sid, false) => { kw.to_ident().name == sid.name }
691         _ => { false }
692     }
693 }
694
695 pub fn is_any_keyword(tok: &Token) -> bool {
696     match *tok {
697         token::IDENT(sid, false) => match sid.name {
698             SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
699             STRICT_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
700             _ => false,
701         },
702         _ => false
703     }
704 }
705
706 pub fn is_strict_keyword(tok: &Token) -> bool {
707     match *tok {
708         token::IDENT(sid, false) => match sid.name {
709             SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME |
710             STRICT_KEYWORD_START .. STRICT_KEYWORD_FINAL => true,
711             _ => false,
712         },
713         _ => false,
714     }
715 }
716
717 pub fn is_reserved_keyword(tok: &Token) -> bool {
718     match *tok {
719         token::IDENT(sid, false) => match sid.name {
720             RESERVED_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true,
721             _ => false,
722         },
723         _ => false,
724     }
725 }
726
727 pub fn mtwt_token_eq(t1 : &Token, t2 : &Token) -> bool {
728     match (t1,t2) {
729         (&IDENT(id1,_),&IDENT(id2,_)) | (&LIFETIME(id1),&LIFETIME(id2)) =>
730             mtwt::resolve(id1) == mtwt::resolve(id2),
731         _ => *t1 == *t2
732     }
733 }
734
735
736 #[cfg(test)]
737 mod test {
738     use super::*;
739     use ast;
740     use ext::mtwt;
741
742     fn mark_ident(id : ast::Ident, m : ast::Mrk) -> ast::Ident {
743         ast::Ident{name:id.name,ctxt:mtwt::new_mark(m,id.ctxt)}
744     }
745
746     #[test] fn mtwt_token_eq_test() {
747         assert!(mtwt_token_eq(&GT,&GT));
748         let a = str_to_ident("bac");
749         let a1 = mark_ident(a,92);
750         assert!(mtwt_token_eq(&IDENT(a,true),&IDENT(a1,false)));
751     }
752 }