]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/token.rs
auto merge of #20901 : dgrunwald/rust/update-token-can-begin-expr, r=sanxiyn
[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::path::BytesContainer;
29 use std::rc::Rc;
30
31 #[allow(non_camel_case_types)]
32 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, 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, Show, 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, Show, 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, Show, 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, Show, 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, uint), /* raw str delimited by n hash symbols */
87     Binary(ast::Name),
88     BinaryRaw(ast::Name, uint), /* 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, Show)]
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                 || STRICT_KEYWORD_START <= n
304                 && n <= RESERVED_KEYWORD_FINAL
305             },
306             _ => false
307         }
308     }
309
310     /// Returns `true` if the token may not appear as an identifier.
311     #[allow(non_upper_case_globals)]
312     pub fn is_strict_keyword(&self) -> bool {
313         match *self {
314             Ident(sid, Plain) => {
315                 let n = sid.name;
316
317                    n == SELF_KEYWORD_NAME
318                 || n == STATIC_KEYWORD_NAME
319                 || n == SUPER_KEYWORD_NAME
320                 || STRICT_KEYWORD_START <= n
321                 && n <= STRICT_KEYWORD_FINAL
322             },
323             Ident(sid, ModName) => {
324                 let n = sid.name;
325
326                    n != SELF_KEYWORD_NAME
327                 && n != SUPER_KEYWORD_NAME
328                 && STRICT_KEYWORD_START <= n
329                 && n <= STRICT_KEYWORD_FINAL
330             }
331             _ => false,
332         }
333     }
334
335     /// Returns `true` if the token is a keyword that has been reserved for
336     /// possible future use.
337     #[allow(non_upper_case_globals)]
338     pub fn is_reserved_keyword(&self) -> bool {
339         match *self {
340             Ident(sid, Plain) => {
341                 let n = sid.name;
342
343                    RESERVED_KEYWORD_START <= n
344                 && n <= RESERVED_KEYWORD_FINAL
345             },
346             _ => false,
347         }
348     }
349
350     /// Hygienic identifier equality comparison.
351     ///
352     /// See `styntax::ext::mtwt`.
353     pub fn mtwt_eq(&self, other : &Token) -> bool {
354         match (self, other) {
355             (&Ident(id1,_), &Ident(id2,_)) | (&Lifetime(id1), &Lifetime(id2)) =>
356                 mtwt::resolve(id1) == mtwt::resolve(id2),
357             _ => *self == *other
358         }
359     }
360 }
361
362 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash)]
363 /// For interpolation during macro expansion.
364 pub enum Nonterminal {
365     NtItem(P<ast::Item>),
366     NtBlock(P<ast::Block>),
367     NtStmt(P<ast::Stmt>),
368     NtPat(P<ast::Pat>),
369     NtExpr(P<ast::Expr>),
370     NtTy(P<ast::Ty>),
371     NtIdent(Box<ast::Ident>, IdentStyle),
372     /// Stuff inside brackets for attributes
373     NtMeta(P<ast::MetaItem>),
374     NtPath(Box<ast::Path>),
375     NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity
376 }
377
378 impl fmt::Show for Nonterminal {
379     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
380         match *self {
381             NtItem(..) => f.pad("NtItem(..)"),
382             NtBlock(..) => f.pad("NtBlock(..)"),
383             NtStmt(..) => f.pad("NtStmt(..)"),
384             NtPat(..) => f.pad("NtPat(..)"),
385             NtExpr(..) => f.pad("NtExpr(..)"),
386             NtTy(..) => f.pad("NtTy(..)"),
387             NtIdent(..) => f.pad("NtIdent(..)"),
388             NtMeta(..) => f.pad("NtMeta(..)"),
389             NtPath(..) => f.pad("NtPath(..)"),
390             NtTT(..) => f.pad("NtTT(..)"),
391         }
392     }
393 }
394
395
396 // Get the first "argument"
397 macro_rules! first {
398     ( $first:expr, $( $remainder:expr, )* ) => ( $first )
399 }
400
401 // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
402 macro_rules! last {
403     ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
404     ( $first:expr, ) => ( $first )
405 }
406
407 // In this macro, there is the requirement that the name (the number) must be monotonically
408 // increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
409 // except starting from the next number instead of zero, and with the additional exception that
410 // special identifiers are *also* allowed (they are deduplicated in the important place, the
411 // interner), an exception which is demonstrated by "static" and "self".
412 macro_rules! declare_special_idents_and_keywords {(
413     // So now, in these rules, why is each definition parenthesised?
414     // Answer: otherwise we get a spurious local ambiguity bug on the "}"
415     pub mod special_idents {
416         $( ($si_name:expr, $si_static:ident, $si_str:expr); )*
417     }
418
419     pub mod keywords {
420         'strict:
421         $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
422         'reserved:
423         $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
424     }
425 ) => {
426     static STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*);
427     static STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*);
428     static RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*);
429     static RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*);
430
431     pub mod special_idents {
432         use ast;
433         $(
434             #[allow(non_upper_case_globals)]
435             pub const $si_static: ast::Ident = ast::Ident {
436                 name: ast::Name($si_name),
437                 ctxt: 0,
438             };
439          )*
440     }
441
442     pub mod special_names {
443         use ast;
444         $(
445             #[allow(non_upper_case_globals)]
446             pub const $si_static: ast::Name =  ast::Name($si_name);
447         )*
448     }
449
450     /// All the valid words that have meaning in the Rust language.
451     ///
452     /// Rust keywords are either 'strict' or 'reserved'.  Strict keywords may not
453     /// appear as identifiers at all. Reserved keywords are not used anywhere in
454     /// the language and may not appear as identifiers.
455     pub mod keywords {
456         pub use self::Keyword::*;
457         use ast;
458
459         #[derive(Copy)]
460         pub enum Keyword {
461             $( $sk_variant, )*
462             $( $rk_variant, )*
463         }
464
465         impl Keyword {
466             pub fn to_name(&self) -> ast::Name {
467                 match *self {
468                     $( $sk_variant => ast::Name($sk_name), )*
469                     $( $rk_variant => ast::Name($rk_name), )*
470                 }
471             }
472         }
473     }
474
475     fn mk_fresh_ident_interner() -> IdentInterner {
476         // The indices here must correspond to the numbers in
477         // special_idents, in Keyword to_name(), and in static
478         // constants below.
479         let mut init_vec = Vec::new();
480         $(init_vec.push($si_str);)*
481         $(init_vec.push($sk_str);)*
482         $(init_vec.push($rk_str);)*
483         interner::StrInterner::prefill(&init_vec[])
484     }
485 }}
486
487 // If the special idents get renumbered, remember to modify these two as appropriate
488 pub const SELF_KEYWORD_NAME: ast::Name = ast::Name(SELF_KEYWORD_NAME_NUM);
489 const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM);
490 const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM);
491
492 pub const SELF_KEYWORD_NAME_NUM: u32 = 1;
493 const STATIC_KEYWORD_NAME_NUM: u32 = 2;
494 const SUPER_KEYWORD_NAME_NUM: u32 = 3;
495
496 // NB: leaving holes in the ident table is bad! a different ident will get
497 // interned with the id from the hole, but it will be between the min and max
498 // of the reserved words, and thus tagged as "reserved".
499
500 declare_special_idents_and_keywords! {
501     pub mod special_idents {
502         // These ones are statics
503         (0,                          invalid,                "");
504         (super::SELF_KEYWORD_NAME_NUM,   self_,              "self");
505         (super::STATIC_KEYWORD_NAME_NUM, statik,             "static");
506         (super::SUPER_KEYWORD_NAME_NUM, super_,              "super");
507         (4,                          static_lifetime,        "'static");
508
509         // for matcher NTs
510         (5,                          tt,                     "tt");
511         (6,                          matchers,               "matchers");
512
513         // outside of libsyntax
514         (7,                          clownshoe_abi,          "__rust_abi");
515         (8,                          opaque,                 "<opaque>");
516         (9,                          unnamed_field,          "<unnamed_field>");
517         (10,                         type_self,              "Self");
518         (11,                         prelude_import,         "prelude_import");
519         (12,                         FullRange,              "FullRange");
520     }
521
522     pub mod keywords {
523         // These ones are variants of the Keyword enum
524
525         'strict:
526         (13,                         As,         "as");
527         (14,                         Break,      "break");
528         (15,                         Crate,      "crate");
529         (16,                         Else,       "else");
530         (17,                         Enum,       "enum");
531         (18,                         Extern,     "extern");
532         (19,                         False,      "false");
533         (20,                         Fn,         "fn");
534         (21,                         For,        "for");
535         (22,                         If,         "if");
536         (23,                         Impl,       "impl");
537         (24,                         In,         "in");
538         (25,                         Let,        "let");
539         (26,                         Loop,       "loop");
540         (27,                         Match,      "match");
541         (28,                         Mod,        "mod");
542         (29,                         Move,       "move");
543         (30,                         Mut,        "mut");
544         (31,                         Pub,        "pub");
545         (32,                         Ref,        "ref");
546         (33,                         Return,     "return");
547         // Static and Self are also special idents (prefill de-dupes)
548         (super::STATIC_KEYWORD_NAME_NUM, Static, "static");
549         (super::SELF_KEYWORD_NAME_NUM,   Self,   "self");
550         (34,                         Struct,     "struct");
551         (super::SUPER_KEYWORD_NAME_NUM, Super,   "super");
552         (35,                         True,       "true");
553         (36,                         Trait,      "trait");
554         (37,                         Type,       "type");
555         (38,                         Unsafe,     "unsafe");
556         (39,                         Use,        "use");
557         (40,                         Virtual,    "virtual");
558         (41,                         While,      "while");
559         (42,                         Continue,   "continue");
560         (43,                         Proc,       "proc");
561         (44,                         Box,        "box");
562         (45,                         Const,      "const");
563         (46,                         Where,      "where");
564         'reserved:
565         (47,                         Alignof,    "alignof");
566         (48,                         Be,         "be");
567         (49,                         Offsetof,   "offsetof");
568         (50,                         Priv,       "priv");
569         (51,                         Pure,       "pure");
570         (52,                         Sizeof,     "sizeof");
571         (53,                         Typeof,     "typeof");
572         (54,                         Unsized,    "unsized");
573         (55,                         Yield,      "yield");
574         (56,                         Do,         "do");
575         (57,                         Abstract,   "abstract");
576         (58,                         Final,      "final");
577         (59,                         Override,   "override");
578         (60,                         Macro,      "macro");
579     }
580 }
581
582 // looks like we can get rid of this completely...
583 pub type IdentInterner = StrInterner;
584
585 // if an interner exists in TLS, return it. Otherwise, prepare a
586 // fresh one.
587 // FIXME(eddyb) #8726 This should probably use a task-local reference.
588 pub fn get_ident_interner() -> Rc<IdentInterner> {
589     thread_local!(static KEY: Rc<::parse::token::IdentInterner> = {
590         Rc::new(mk_fresh_ident_interner())
591     });
592     KEY.with(|k| k.clone())
593 }
594
595 /// Reset the ident interner to its initial state.
596 pub fn reset_ident_interner() {
597     let interner = get_ident_interner();
598     interner.reset(mk_fresh_ident_interner());
599 }
600
601 /// Represents a string stored in the task-local interner. Because the
602 /// interner lives for the life of the task, this can be safely treated as an
603 /// immortal string, as long as it never crosses between tasks.
604 ///
605 /// FIXME(pcwalton): You must be careful about what you do in the destructors
606 /// of objects stored in TLS, because they may run after the interner is
607 /// destroyed. In particular, they must not access string contents. This can
608 /// be fixed in the future by just leaking all strings until task death
609 /// somehow.
610 #[derive(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
611 pub struct InternedString {
612     string: RcStr,
613 }
614
615 impl InternedString {
616     #[inline]
617     pub fn new(string: &'static str) -> InternedString {
618         InternedString {
619             string: RcStr::new(string),
620         }
621     }
622
623     #[inline]
624     fn new_from_rc_str(string: RcStr) -> InternedString {
625         InternedString {
626             string: string,
627         }
628     }
629
630     #[inline]
631     pub fn get<'a>(&'a self) -> &'a str {
632         &self.string[]
633     }
634 }
635
636 impl Deref for InternedString {
637     type Target = str;
638
639     fn deref(&self) -> &str { &*self.string }
640 }
641
642 impl BytesContainer for InternedString {
643     fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
644         // FIXME #12938: This is a workaround for the incorrect signature
645         // of `BytesContainer`, which is itself a workaround for the lack of
646         // DST.
647         unsafe {
648             let this = self.get();
649             mem::transmute::<&[u8],&[u8]>(this.container_as_bytes())
650         }
651     }
652 }
653
654 impl fmt::Show for InternedString {
655     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
656         fmt::String::fmt(self, f)
657     }
658 }
659
660 impl fmt::String for InternedString {
661     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
662         write!(f, "{}", &self.string[])
663     }
664 }
665
666 impl<'a> PartialEq<&'a str> for InternedString {
667     #[inline(always)]
668     fn eq(&self, other: & &'a str) -> bool {
669         PartialEq::eq(&self.string[], *other)
670     }
671     #[inline(always)]
672     fn ne(&self, other: & &'a str) -> bool {
673         PartialEq::ne(&self.string[], *other)
674     }
675 }
676
677 impl<'a> PartialEq<InternedString > for &'a str {
678     #[inline(always)]
679     fn eq(&self, other: &InternedString) -> bool {
680         PartialEq::eq(*self, &other.string[])
681     }
682     #[inline(always)]
683     fn ne(&self, other: &InternedString) -> bool {
684         PartialEq::ne(*self, &other.string[])
685     }
686 }
687
688 impl Decodable for InternedString {
689     fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
690         Ok(get_name(get_ident_interner().intern(&try!(d.read_str())[])))
691     }
692 }
693
694 impl Encodable for InternedString {
695     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
696         s.emit_str(&self.string[])
697     }
698 }
699
700 /// Returns the string contents of a name, using the task-local interner.
701 #[inline]
702 pub fn get_name(name: ast::Name) -> InternedString {
703     let interner = get_ident_interner();
704     InternedString::new_from_rc_str(interner.get(name))
705 }
706
707 /// Returns the string contents of an identifier, using the task-local
708 /// interner.
709 #[inline]
710 pub fn get_ident(ident: ast::Ident) -> InternedString {
711     get_name(ident.name)
712 }
713
714 /// Interns and returns the string contents of an identifier, using the
715 /// task-local interner.
716 #[inline]
717 pub fn intern_and_get_ident(s: &str) -> InternedString {
718     get_name(intern(s))
719 }
720
721 /// Maps a string to its interned representation.
722 #[inline]
723 pub fn intern(s: &str) -> ast::Name {
724     get_ident_interner().intern(s)
725 }
726
727 /// gensym's a new uint, using the current interner.
728 #[inline]
729 pub fn gensym(s: &str) -> ast::Name {
730     get_ident_interner().gensym(s)
731 }
732
733 /// Maps a string to an identifier with an empty syntax context.
734 #[inline]
735 pub fn str_to_ident(s: &str) -> ast::Ident {
736     ast::Ident::new(intern(s))
737 }
738
739 /// Maps a string to a gensym'ed identifier.
740 #[inline]
741 pub fn gensym_ident(s: &str) -> ast::Ident {
742     ast::Ident::new(gensym(s))
743 }
744
745 // create a fresh name that maps to the same string as the old one.
746 // note that this guarantees that str_ptr_eq(ident_to_string(src),interner_get(fresh_name(src)));
747 // that is, that the new name and the old one are connected to ptr_eq strings.
748 pub fn fresh_name(src: &ast::Ident) -> ast::Name {
749     let interner = get_ident_interner();
750     interner.gensym_copy(src.name)
751     // following: debug version. Could work in final except that it's incompatible with
752     // good error messages and uses of struct names in ambiguous could-be-binding
753     // locations. Also definitely destroys the guarantee given above about ptr_eq.
754     /*let num = rand::thread_rng().gen_uint_range(0,0xffff);
755     gensym(format!("{}_{}",ident_to_string(src),num))*/
756 }
757
758 // create a fresh mark.
759 pub fn fresh_mark() -> ast::Mrk {
760     gensym("mark").uint() as u32
761 }
762
763 #[cfg(test)]
764 mod test {
765     use super::*;
766     use ast;
767     use ext::mtwt;
768
769     fn mark_ident(id : ast::Ident, m : ast::Mrk) -> ast::Ident {
770         ast::Ident { name: id.name, ctxt:mtwt::apply_mark(m, id.ctxt) }
771     }
772
773     #[test] fn mtwt_token_eq_test() {
774         assert!(Gt.mtwt_eq(&Gt));
775         let a = str_to_ident("bac");
776         let a1 = mark_ident(a,92);
777         assert!(Ident(a, ModName).mtwt_eq(&Ident(a1, Plain)));
778     }
779 }