]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/token.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[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 pub use self::BinOpToken::*;
12 pub use self::Nonterminal::*;
13 pub use self::DelimToken::*;
14 pub use self::IdentStyle::*;
15 pub use self::Lit::*;
16 pub use self::Token::*;
17
18 use ast;
19 use ext::mtwt;
20 use ptr::P;
21 use util::interner::{RcStr, StrInterner};
22 use util::interner;
23
24 use serialize::{Decodable, Decoder, Encodable, Encoder};
25 use std::fmt;
26 use std::mem;
27 use std::ops::Deref;
28 use std::old_path::BytesContainer;
29 use std::rc::Rc;
30
31 #[allow(non_camel_case_types)]
32 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
33 pub enum BinOpToken {
34     Plus,
35     Minus,
36     Star,
37     Slash,
38     Percent,
39     Caret,
40     And,
41     Or,
42     Shl,
43     Shr,
44 }
45
46 /// A delimiter token
47 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
48 pub enum DelimToken {
49     /// A round parenthesis: `(` or `)`
50     Paren,
51     /// A square bracket: `[` or `]`
52     Bracket,
53     /// A curly brace: `{` or `}`
54     Brace,
55 }
56
57 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
58 pub enum IdentStyle {
59     /// `::` follows the identifier with no whitespace in-between.
60     ModName,
61     Plain,
62 }
63
64 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
65 pub enum SpecialMacroVar {
66     /// `$crate` will be filled in with the name of the crate a macro was
67     /// imported from, if any.
68     CrateMacroVar,
69 }
70
71 impl SpecialMacroVar {
72     pub fn as_str(self) -> &'static str {
73         match self {
74             SpecialMacroVar::CrateMacroVar => "crate",
75         }
76     }
77 }
78
79 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
80 pub enum Lit {
81     Byte(ast::Name),
82     Char(ast::Name),
83     Integer(ast::Name),
84     Float(ast::Name),
85     Str_(ast::Name),
86     StrRaw(ast::Name, usize), /* raw str delimited by n hash symbols */
87     Binary(ast::Name),
88     BinaryRaw(ast::Name, usize), /* raw binary str delimited by n hash symbols */
89 }
90
91 impl Lit {
92     pub fn short_name(&self) -> &'static str {
93         match *self {
94             Byte(_) => "byte",
95             Char(_) => "char",
96             Integer(_) => "integer",
97             Float(_) => "float",
98             Str_(_) | StrRaw(..) => "str",
99             Binary(_) | BinaryRaw(..) => "binary str"
100         }
101     }
102 }
103
104 #[allow(non_camel_case_types)]
105 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug)]
106 pub enum Token {
107     /* Expression-operator symbols. */
108     Eq,
109     Lt,
110     Le,
111     EqEq,
112     Ne,
113     Ge,
114     Gt,
115     AndAnd,
116     OrOr,
117     Not,
118     Tilde,
119     BinOp(BinOpToken),
120     BinOpEq(BinOpToken),
121
122     /* Structural symbols */
123     At,
124     Dot,
125     DotDot,
126     DotDotDot,
127     Comma,
128     Semi,
129     Colon,
130     ModSep,
131     RArrow,
132     LArrow,
133     FatArrow,
134     Pound,
135     Dollar,
136     Question,
137     /// An opening delimiter, eg. `{`
138     OpenDelim(DelimToken),
139     /// A closing delimiter, eg. `}`
140     CloseDelim(DelimToken),
141
142     /* Literals */
143     Literal(Lit, Option<ast::Name>),
144
145     /* Name components */
146     Ident(ast::Ident, IdentStyle),
147     Underscore,
148     Lifetime(ast::Ident),
149
150     /* For interpolation */
151     Interpolated(Nonterminal),
152     // Can be expanded into several tokens.
153     /// Doc comment
154     DocComment(ast::Name),
155     // In left-hand-sides of MBE macros:
156     /// Parse a nonterminal (name to bind, name of NT, styles of their idents)
157     MatchNt(ast::Ident, ast::Ident, IdentStyle, IdentStyle),
158     // In right-hand-sides of MBE macros:
159     /// A syntactic variable that will be filled in by macro expansion.
160     SubstNt(ast::Ident, IdentStyle),
161     /// A macro variable with special meaning.
162     SpecialVarNt(SpecialMacroVar),
163
164     // Junk. These carry no data because we don't really care about the data
165     // they *would* carry, and don't really want to allocate a new ident for
166     // them. Instead, users could extract that from the associated span.
167
168     /// Whitespace
169     Whitespace,
170     /// Comment
171     Comment,
172     Shebang(ast::Name),
173
174     Eof,
175 }
176
177 impl Token {
178     /// Returns `true` if the token can appear at the start of an expression.
179     pub fn can_begin_expr(&self) -> bool {
180         match *self {
181             OpenDelim(_)                => true,
182             Ident(_, _)                 => true,
183             Underscore                  => true,
184             Tilde                       => true,
185             Literal(_, _)               => true,
186             Not                         => true,
187             BinOp(Minus)                => true,
188             BinOp(Star)                 => true,
189             BinOp(And)                  => true,
190             BinOp(Or)                   => true, // in lambda syntax
191             OrOr                        => true, // in lambda syntax
192             AndAnd                      => true, // double borrow
193             DotDot                      => true, // range notation
194             ModSep                      => true,
195             Interpolated(NtExpr(..))    => true,
196             Interpolated(NtIdent(..))   => true,
197             Interpolated(NtBlock(..))   => true,
198             Interpolated(NtPath(..))    => true,
199             _                           => false,
200         }
201     }
202
203     /// Returns `true` if the token is any literal
204     pub fn is_lit(&self) -> bool {
205         match *self {
206             Literal(_, _) => true,
207             _          => false,
208         }
209     }
210
211     /// Returns `true` if the token is an identifier.
212     pub fn is_ident(&self) -> bool {
213         match *self {
214             Ident(_, _) => true,
215             _           => false,
216         }
217     }
218
219     /// Returns `true` if the token is an interpolated path.
220     pub fn is_path(&self) -> bool {
221         match *self {
222             Interpolated(NtPath(..))    => true,
223             _                           => false,
224         }
225     }
226
227     /// Returns `true` if the token is a path that is not followed by a `::`
228     /// token.
229     #[allow(non_upper_case_globals)]
230     pub fn is_plain_ident(&self) -> bool {
231         match *self {
232             Ident(_, Plain) => true,
233             _               => false,
234         }
235     }
236
237     /// Returns `true` if the token is a lifetime.
238     pub fn is_lifetime(&self) -> bool {
239         match *self {
240             Lifetime(..) => true,
241             _            => false,
242         }
243     }
244
245     /// Returns `true` if the token is either the `mut` or `const` keyword.
246     pub fn is_mutability(&self) -> bool {
247         self.is_keyword(keywords::Mut) ||
248         self.is_keyword(keywords::Const)
249     }
250
251     /// Maps a token to its corresponding binary operator.
252     pub fn to_binop(&self) -> Option<ast::BinOp_> {
253         match *self {
254             BinOp(Star)     => Some(ast::BiMul),
255             BinOp(Slash)    => Some(ast::BiDiv),
256             BinOp(Percent)  => Some(ast::BiRem),
257             BinOp(Plus)     => Some(ast::BiAdd),
258             BinOp(Minus)    => Some(ast::BiSub),
259             BinOp(Shl)      => Some(ast::BiShl),
260             BinOp(Shr)      => Some(ast::BiShr),
261             BinOp(And)      => Some(ast::BiBitAnd),
262             BinOp(Caret)    => Some(ast::BiBitXor),
263             BinOp(Or)       => Some(ast::BiBitOr),
264             Lt              => Some(ast::BiLt),
265             Le              => Some(ast::BiLe),
266             Ge              => Some(ast::BiGe),
267             Gt              => Some(ast::BiGt),
268             EqEq            => Some(ast::BiEq),
269             Ne              => Some(ast::BiNe),
270             AndAnd          => Some(ast::BiAnd),
271             OrOr            => Some(ast::BiOr),
272             _               => None,
273         }
274     }
275
276     /// Returns `true` if the token is a given keyword, `kw`.
277     #[allow(non_upper_case_globals)]
278     pub fn is_keyword(&self, kw: keywords::Keyword) -> bool {
279         match *self {
280             Ident(sid, Plain) => kw.to_name() == sid.name,
281             _                      => false,
282         }
283     }
284
285     pub fn is_keyword_allow_following_colon(&self, kw: keywords::Keyword) -> bool {
286         match *self {
287             Ident(sid, _) => { kw.to_name() == sid.name }
288             _ => { false }
289         }
290     }
291
292     /// Returns `true` if the token is either a special identifier, or a strict
293     /// or reserved keyword.
294     #[allow(non_upper_case_globals)]
295     pub fn is_any_keyword(&self) -> bool {
296         match *self {
297             Ident(sid, Plain) => {
298                 let n = sid.name;
299
300                    n == SELF_KEYWORD_NAME
301                 || n == STATIC_KEYWORD_NAME
302                 || n == SUPER_KEYWORD_NAME
303                 || n == SELF_TYPE_KEYWORD_NAME
304                 || STRICT_KEYWORD_START <= n
305                 && n <= RESERVED_KEYWORD_FINAL
306             },
307             _ => false
308         }
309     }
310
311     /// Returns `true` if the token may not appear as an identifier.
312     #[allow(non_upper_case_globals)]
313     pub fn is_strict_keyword(&self) -> bool {
314         match *self {
315             Ident(sid, Plain) => {
316                 let n = sid.name;
317
318                    n == SELF_KEYWORD_NAME
319                 || n == STATIC_KEYWORD_NAME
320                 || n == SUPER_KEYWORD_NAME
321                 || n == SELF_TYPE_KEYWORD_NAME
322                 || STRICT_KEYWORD_START <= n
323                 && n <= STRICT_KEYWORD_FINAL
324             },
325             Ident(sid, ModName) => {
326                 let n = sid.name;
327
328                    n != SELF_KEYWORD_NAME
329                 && n != SUPER_KEYWORD_NAME
330                 && STRICT_KEYWORD_START <= n
331                 && n <= STRICT_KEYWORD_FINAL
332             }
333             _ => false,
334         }
335     }
336
337     /// Returns `true` if the token is a keyword that has been reserved for
338     /// possible future use.
339     #[allow(non_upper_case_globals)]
340     pub fn is_reserved_keyword(&self) -> bool {
341         match *self {
342             Ident(sid, Plain) => {
343                 let n = sid.name;
344
345                    RESERVED_KEYWORD_START <= n
346                 && n <= RESERVED_KEYWORD_FINAL
347             },
348             _ => false,
349         }
350     }
351
352     /// Hygienic identifier equality comparison.
353     ///
354     /// See `styntax::ext::mtwt`.
355     pub fn mtwt_eq(&self, other : &Token) -> bool {
356         match (self, other) {
357             (&Ident(id1,_), &Ident(id2,_)) | (&Lifetime(id1), &Lifetime(id2)) =>
358                 mtwt::resolve(id1) == mtwt::resolve(id2),
359             _ => *self == *other
360         }
361     }
362 }
363
364 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash)]
365 /// For interpolation during macro expansion.
366 pub enum Nonterminal {
367     NtItem(P<ast::Item>),
368     NtBlock(P<ast::Block>),
369     NtStmt(P<ast::Stmt>),
370     NtPat(P<ast::Pat>),
371     NtExpr(P<ast::Expr>),
372     NtTy(P<ast::Ty>),
373     NtIdent(Box<ast::Ident>, IdentStyle),
374     /// Stuff inside brackets for attributes
375     NtMeta(P<ast::MetaItem>),
376     NtPath(Box<ast::Path>),
377     NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity
378 }
379
380 impl fmt::Debug for Nonterminal {
381     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
382         match *self {
383             NtItem(..) => f.pad("NtItem(..)"),
384             NtBlock(..) => f.pad("NtBlock(..)"),
385             NtStmt(..) => f.pad("NtStmt(..)"),
386             NtPat(..) => f.pad("NtPat(..)"),
387             NtExpr(..) => f.pad("NtExpr(..)"),
388             NtTy(..) => f.pad("NtTy(..)"),
389             NtIdent(..) => f.pad("NtIdent(..)"),
390             NtMeta(..) => f.pad("NtMeta(..)"),
391             NtPath(..) => f.pad("NtPath(..)"),
392             NtTT(..) => f.pad("NtTT(..)"),
393         }
394     }
395 }
396
397
398 // Get the first "argument"
399 macro_rules! first {
400     ( $first:expr, $( $remainder:expr, )* ) => ( $first )
401 }
402
403 // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
404 macro_rules! last {
405     ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
406     ( $first:expr, ) => ( $first )
407 }
408
409 // In this macro, there is the requirement that the name (the number) must be monotonically
410 // increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
411 // except starting from the next number instead of zero, and with the additional exception that
412 // special identifiers are *also* allowed (they are deduplicated in the important place, the
413 // interner), an exception which is demonstrated by "static" and "self".
414 macro_rules! declare_special_idents_and_keywords {(
415     // So now, in these rules, why is each definition parenthesised?
416     // Answer: otherwise we get a spurious local ambiguity bug on the "}"
417     pub mod special_idents {
418         $( ($si_name:expr, $si_static:ident, $si_str:expr); )*
419     }
420
421     pub mod keywords {
422         'strict:
423         $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
424         'reserved:
425         $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
426     }
427 ) => {
428     static STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*);
429     static STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*);
430     static RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*);
431     static RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*);
432
433     pub mod special_idents {
434         use ast;
435         $(
436             #[allow(non_upper_case_globals)]
437             pub const $si_static: ast::Ident = ast::Ident {
438                 name: ast::Name($si_name),
439                 ctxt: 0,
440             };
441          )*
442     }
443
444     pub mod special_names {
445         use ast;
446         $(
447             #[allow(non_upper_case_globals)]
448             pub const $si_static: ast::Name =  ast::Name($si_name);
449         )*
450     }
451
452     /// All the valid words that have meaning in the Rust language.
453     ///
454     /// Rust keywords are either 'strict' or 'reserved'.  Strict keywords may not
455     /// appear as identifiers at all. Reserved keywords are not used anywhere in
456     /// the language and may not appear as identifiers.
457     pub mod keywords {
458         pub use self::Keyword::*;
459         use ast;
460
461         #[derive(Copy, Clone, PartialEq, Eq)]
462         pub enum Keyword {
463             $( $sk_variant, )*
464             $( $rk_variant, )*
465         }
466
467         impl Keyword {
468             pub fn to_name(&self) -> ast::Name {
469                 match *self {
470                     $( $sk_variant => ast::Name($sk_name), )*
471                     $( $rk_variant => ast::Name($rk_name), )*
472                 }
473             }
474         }
475     }
476
477     fn mk_fresh_ident_interner() -> IdentInterner {
478         // The indices here must correspond to the numbers in
479         // special_idents, in Keyword to_name(), and in static
480         // constants below.
481         let mut init_vec = Vec::new();
482         $(init_vec.push($si_str);)*
483         $(init_vec.push($sk_str);)*
484         $(init_vec.push($rk_str);)*
485         interner::StrInterner::prefill(&init_vec[])
486     }
487 }}
488
489 // If the special idents get renumbered, remember to modify these two as appropriate
490 pub const SELF_KEYWORD_NAME: ast::Name = ast::Name(SELF_KEYWORD_NAME_NUM);
491 const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM);
492 const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM);
493 const SELF_TYPE_KEYWORD_NAME: ast::Name = ast::Name(SELF_TYPE_KEYWORD_NAME_NUM);
494
495 pub const SELF_KEYWORD_NAME_NUM: u32 = 1;
496 const STATIC_KEYWORD_NAME_NUM: u32 = 2;
497 const SUPER_KEYWORD_NAME_NUM: u32 = 3;
498 const SELF_TYPE_KEYWORD_NAME_NUM: u32 = 10;
499
500 // NB: leaving holes in the ident table is bad! a different ident will get
501 // interned with the id from the hole, but it will be between the min and max
502 // of the reserved words, and thus tagged as "reserved".
503
504 declare_special_idents_and_keywords! {
505     pub mod special_idents {
506         // These ones are statics
507         (0,                          invalid,                "");
508         (super::SELF_KEYWORD_NAME_NUM,   self_,              "self");
509         (super::STATIC_KEYWORD_NAME_NUM, statik,             "static");
510         (super::SUPER_KEYWORD_NAME_NUM, super_,              "super");
511         (4,                          static_lifetime,        "'static");
512
513         // for matcher NTs
514         (5,                          tt,                     "tt");
515         (6,                          matchers,               "matchers");
516
517         // outside of libsyntax
518         (7,                          clownshoe_abi,          "__rust_abi");
519         (8,                          opaque,                 "<opaque>");
520         (9,                          unnamed_field,          "<unnamed_field>");
521         (super::SELF_TYPE_KEYWORD_NAME_NUM, type_self,       "Self");
522         (11,                         prelude_import,         "prelude_import");
523     }
524
525     pub mod keywords {
526         // These ones are variants of the Keyword enum
527
528         'strict:
529         (12,                         As,         "as");
530         (13,                         Break,      "break");
531         (14,                         Crate,      "crate");
532         (15,                         Else,       "else");
533         (16,                         Enum,       "enum");
534         (17,                         Extern,     "extern");
535         (18,                         False,      "false");
536         (19,                         Fn,         "fn");
537         (20,                         For,        "for");
538         (21,                         If,         "if");
539         (22,                         Impl,       "impl");
540         (23,                         In,         "in");
541         (24,                         Let,        "let");
542         (25,                         Loop,       "loop");
543         (26,                         Match,      "match");
544         (27,                         Mod,        "mod");
545         (28,                         Move,       "move");
546         (29,                         Mut,        "mut");
547         (30,                         Pub,        "pub");
548         (31,                         Ref,        "ref");
549         (32,                         Return,     "return");
550         // Static and Self are also special idents (prefill de-dupes)
551         (super::STATIC_KEYWORD_NAME_NUM, Static, "static");
552         (super::SELF_KEYWORD_NAME_NUM, SelfValue, "self");
553         (super::SELF_TYPE_KEYWORD_NAME_NUM, SelfType, "Self");
554         (33,                         Struct,     "struct");
555         (super::SUPER_KEYWORD_NAME_NUM, Super,   "super");
556         (34,                         True,       "true");
557         (35,                         Trait,      "trait");
558         (36,                         Type,       "type");
559         (37,                         Unsafe,     "unsafe");
560         (38,                         Use,        "use");
561         (39,                         Virtual,    "virtual");
562         (40,                         While,      "while");
563         (41,                         Continue,   "continue");
564         (42,                         Proc,       "proc");
565         (43,                         Box,        "box");
566         (44,                         Const,      "const");
567         (45,                         Where,      "where");
568         'reserved:
569         (46,                         Alignof,    "alignof");
570         (47,                         Become,     "become");
571         (48,                         Offsetof,   "offsetof");
572         (49,                         Priv,       "priv");
573         (50,                         Pure,       "pure");
574         (51,                         Sizeof,     "sizeof");
575         (52,                         Typeof,     "typeof");
576         (53,                         Unsized,    "unsized");
577         (54,                         Yield,      "yield");
578         (55,                         Do,         "do");
579         (56,                         Abstract,   "abstract");
580         (57,                         Final,      "final");
581         (58,                         Override,   "override");
582         (59,                         Macro,      "macro");
583     }
584 }
585
586 // looks like we can get rid of this completely...
587 pub type IdentInterner = StrInterner;
588
589 // if an interner exists in TLS, return it. Otherwise, prepare a
590 // fresh one.
591 // FIXME(eddyb) #8726 This should probably use a task-local reference.
592 pub fn get_ident_interner() -> Rc<IdentInterner> {
593     thread_local!(static KEY: Rc<::parse::token::IdentInterner> = {
594         Rc::new(mk_fresh_ident_interner())
595     });
596     KEY.with(|k| k.clone())
597 }
598
599 /// Reset the ident interner to its initial state.
600 pub fn reset_ident_interner() {
601     let interner = get_ident_interner();
602     interner.reset(mk_fresh_ident_interner());
603 }
604
605 /// Represents a string stored in the task-local interner. Because the
606 /// interner lives for the life of the task, this can be safely treated as an
607 /// immortal string, as long as it never crosses between tasks.
608 ///
609 /// FIXME(pcwalton): You must be careful about what you do in the destructors
610 /// of objects stored in TLS, because they may run after the interner is
611 /// destroyed. In particular, they must not access string contents. This can
612 /// be fixed in the future by just leaking all strings until task death
613 /// somehow.
614 #[derive(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
615 pub struct InternedString {
616     string: RcStr,
617 }
618
619 impl InternedString {
620     #[inline]
621     pub fn new(string: &'static str) -> InternedString {
622         InternedString {
623             string: RcStr::new(string),
624         }
625     }
626
627     #[inline]
628     fn new_from_rc_str(string: RcStr) -> InternedString {
629         InternedString {
630             string: string,
631         }
632     }
633 }
634
635 impl Deref for InternedString {
636     type Target = str;
637
638     fn deref(&self) -> &str { &*self.string }
639 }
640
641 impl BytesContainer for InternedString {
642     fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
643         // FIXME #12938: This is a workaround for the incorrect signature
644         // of `BytesContainer`, which is itself a workaround for the lack of
645         // DST.
646         unsafe {
647             let this = &self[];
648             mem::transmute::<&[u8],&[u8]>(this.container_as_bytes())
649         }
650     }
651 }
652
653 impl fmt::Debug for InternedString {
654     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
655         fmt::Debug::fmt(&self.string[], f)
656     }
657 }
658
659 impl fmt::Display for InternedString {
660     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
661         fmt::Display::fmt(&self.string[], f)
662     }
663 }
664
665 impl<'a> PartialEq<&'a str> for InternedString {
666     #[inline(always)]
667     fn eq(&self, other: & &'a str) -> bool {
668         PartialEq::eq(&self.string[], *other)
669     }
670     #[inline(always)]
671     fn ne(&self, other: & &'a str) -> bool {
672         PartialEq::ne(&self.string[], *other)
673     }
674 }
675
676 impl<'a> PartialEq<InternedString > for &'a str {
677     #[inline(always)]
678     fn eq(&self, other: &InternedString) -> bool {
679         PartialEq::eq(*self, &other.string[])
680     }
681     #[inline(always)]
682     fn ne(&self, other: &InternedString) -> bool {
683         PartialEq::ne(*self, &other.string[])
684     }
685 }
686
687 impl Decodable for InternedString {
688     fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
689         Ok(get_name(get_ident_interner().intern(&try!(d.read_str())[])))
690     }
691 }
692
693 impl Encodable for InternedString {
694     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
695         s.emit_str(&self.string[])
696     }
697 }
698
699 /// Returns the string contents of a name, using the task-local interner.
700 #[inline]
701 pub fn get_name(name: ast::Name) -> InternedString {
702     let interner = get_ident_interner();
703     InternedString::new_from_rc_str(interner.get(name))
704 }
705
706 /// Returns the string contents of an identifier, using the task-local
707 /// interner.
708 #[inline]
709 pub fn get_ident(ident: ast::Ident) -> InternedString {
710     get_name(ident.name)
711 }
712
713 /// Interns and returns the string contents of an identifier, using the
714 /// task-local interner.
715 #[inline]
716 pub fn intern_and_get_ident(s: &str) -> InternedString {
717     get_name(intern(s))
718 }
719
720 /// Maps a string to its interned representation.
721 #[inline]
722 pub fn intern(s: &str) -> ast::Name {
723     get_ident_interner().intern(s)
724 }
725
726 /// gensym's a new usize, using the current interner.
727 #[inline]
728 pub fn gensym(s: &str) -> ast::Name {
729     get_ident_interner().gensym(s)
730 }
731
732 /// Maps a string to an identifier with an empty syntax context.
733 #[inline]
734 pub fn str_to_ident(s: &str) -> ast::Ident {
735     ast::Ident::new(intern(s))
736 }
737
738 /// Maps a string to a gensym'ed identifier.
739 #[inline]
740 pub fn gensym_ident(s: &str) -> ast::Ident {
741     ast::Ident::new(gensym(s))
742 }
743
744 // create a fresh name that maps to the same string as the old one.
745 // note that this guarantees that str_ptr_eq(ident_to_string(src),interner_get(fresh_name(src)));
746 // that is, that the new name and the old one are connected to ptr_eq strings.
747 pub fn fresh_name(src: &ast::Ident) -> ast::Name {
748     let interner = get_ident_interner();
749     interner.gensym_copy(src.name)
750     // following: debug version. Could work in final except that it's incompatible with
751     // good error messages and uses of struct names in ambiguous could-be-binding
752     // locations. Also definitely destroys the guarantee given above about ptr_eq.
753     /*let num = rand::thread_rng().gen_uint_range(0,0xffff);
754     gensym(format!("{}_{}",ident_to_string(src),num))*/
755 }
756
757 // create a fresh mark.
758 pub fn fresh_mark() -> ast::Mrk {
759     gensym("mark").usize() as u32
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::apply_mark(m, id.ctxt) }
770     }
771
772     #[test] fn mtwt_token_eq_test() {
773         assert!(Gt.mtwt_eq(&Gt));
774         let a = str_to_ident("bac");
775         let a1 = mark_ident(a,92);
776         assert!(Ident(a, ModName).mtwt_eq(&Ident(a1, Plain)));
777     }
778 }