]> git.lizzy.rs Git - rust.git/blob - src/libproc_macro/lib.rs
Span::resolved_at and Span::located_at to combine behavior of two spans
[rust.git] / src / libproc_macro / lib.rs
1 // Copyright 2016 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 //! A support library for macro authors when defining new macros.
12 //!
13 //! This library, provided by the standard distribution, provides the types
14 //! consumed in the interfaces of procedurally defined macro definitions.
15 //! Currently the primary use of this crate is to provide the ability to define
16 //! new custom derive modes through `#[proc_macro_derive]`.
17 //!
18 //! Note that this crate is intentionally very bare-bones currently. The main
19 //! type, `TokenStream`, only supports `fmt::Display` and `FromStr`
20 //! implementations, indicating that it can only go to and come from a string.
21 //! This functionality is intended to be expanded over time as more surface
22 //! area for macro authors is stabilized.
23 //!
24 //! See [the book](../book/first-edition/procedural-macros.html) for more.
25
26 #![stable(feature = "proc_macro_lib", since = "1.15.0")]
27 #![deny(warnings)]
28 #![deny(missing_docs)]
29 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
30        html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
31        html_root_url = "https://doc.rust-lang.org/nightly/",
32        html_playground_url = "https://play.rust-lang.org/",
33        issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
34        test(no_crate_inject, attr(deny(warnings))),
35        test(attr(allow(dead_code, deprecated, unused_variables, unused_mut))))]
36
37 #![feature(i128_type)]
38 #![feature(rustc_private)]
39 #![feature(staged_api)]
40 #![feature(lang_items)]
41
42 #[macro_use]
43 extern crate syntax;
44 extern crate syntax_pos;
45 extern crate rustc_errors;
46
47 mod diagnostic;
48
49 #[unstable(feature = "proc_macro", issue = "38356")]
50 pub use diagnostic::{Diagnostic, Level};
51
52 use std::{ascii, fmt, iter};
53 use std::rc::Rc;
54 use std::str::FromStr;
55
56 use syntax::ast;
57 use syntax::errors::DiagnosticBuilder;
58 use syntax::parse::{self, token};
59 use syntax::symbol::Symbol;
60 use syntax::tokenstream;
61 use syntax_pos::DUMMY_SP;
62 use syntax_pos::{FileMap, Pos, SyntaxContext, FileName};
63 use syntax_pos::hygiene::Mark;
64
65 /// The main type provided by this crate, representing an abstract stream of
66 /// tokens.
67 ///
68 /// This is both the input and output of `#[proc_macro_derive]` definitions.
69 /// Currently it's required to be a list of valid Rust items, but this
70 /// restriction may be lifted in the future.
71 ///
72 /// The API of this type is intentionally bare-bones, but it'll be expanded over
73 /// time!
74 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
75 #[derive(Clone, Debug)]
76 pub struct TokenStream(tokenstream::TokenStream);
77
78 /// Error returned from `TokenStream::from_str`.
79 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
80 #[derive(Debug)]
81 pub struct LexError {
82     _inner: (),
83 }
84
85 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
86 impl FromStr for TokenStream {
87     type Err = LexError;
88
89     fn from_str(src: &str) -> Result<TokenStream, LexError> {
90         __internal::with_sess(|(sess, mark)| {
91             let src = src.to_string();
92             let name = FileName::ProcMacroSourceCode;
93             let expn_info = mark.expn_info().unwrap();
94             let call_site = expn_info.call_site;
95             // notify the expansion info that it is unhygienic
96             let mark = Mark::fresh(mark);
97             mark.set_expn_info(expn_info);
98             let span = call_site.with_ctxt(call_site.ctxt().apply_mark(mark));
99             let stream = parse::parse_stream_from_source_str(name, src, sess, Some(span));
100             Ok(__internal::token_stream_wrap(stream))
101         })
102     }
103 }
104
105 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
106 impl fmt::Display for TokenStream {
107     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108         self.0.fmt(f)
109     }
110 }
111
112 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
113 /// For example, `quote!(a + b)` will produce a expression, that, when evaluated, constructs
114 /// the `TokenStream` `[Word("a"), Op('+', Alone), Word("b")]`.
115 ///
116 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
117 /// To quote `$` itself, use `$$`.
118 #[unstable(feature = "proc_macro", issue = "38356")]
119 #[macro_export]
120 macro_rules! quote { () => {} }
121
122 #[unstable(feature = "proc_macro_internals", issue = "27812")]
123 #[doc(hidden)]
124 mod quote;
125
126 #[unstable(feature = "proc_macro", issue = "38356")]
127 impl From<TokenTree> for TokenStream {
128     fn from(tree: TokenTree) -> TokenStream {
129         TokenStream(tree.to_internal())
130     }
131 }
132
133 #[unstable(feature = "proc_macro", issue = "38356")]
134 impl From<TokenNode> for TokenStream {
135     fn from(kind: TokenNode) -> TokenStream {
136         TokenTree::from(kind).into()
137     }
138 }
139
140 #[unstable(feature = "proc_macro", issue = "38356")]
141 impl<T: Into<TokenStream>> iter::FromIterator<T> for TokenStream {
142     fn from_iter<I: IntoIterator<Item = T>>(streams: I) -> Self {
143         let mut builder = tokenstream::TokenStreamBuilder::new();
144         for stream in streams {
145             builder.push(stream.into().0);
146         }
147         TokenStream(builder.build())
148     }
149 }
150
151 #[unstable(feature = "proc_macro", issue = "38356")]
152 impl IntoIterator for TokenStream {
153     type Item = TokenTree;
154     type IntoIter = TokenTreeIter;
155
156     fn into_iter(self) -> TokenTreeIter {
157         TokenTreeIter { cursor: self.0.trees(), next: None }
158     }
159 }
160
161 impl TokenStream {
162     /// Returns an empty `TokenStream`.
163     #[unstable(feature = "proc_macro", issue = "38356")]
164     pub fn empty() -> TokenStream {
165         TokenStream(tokenstream::TokenStream::empty())
166     }
167
168     /// Checks if this `TokenStream` is empty.
169     #[unstable(feature = "proc_macro", issue = "38356")]
170     pub fn is_empty(&self) -> bool {
171         self.0.is_empty()
172     }
173 }
174
175 /// A region of source code, along with macro expansion information.
176 #[unstable(feature = "proc_macro", issue = "38356")]
177 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
178 pub struct Span(syntax_pos::Span);
179
180 impl Span {
181     /// A span that resolves at the macro definition site.
182     #[unstable(feature = "proc_macro", issue = "38356")]
183     pub fn def_site() -> Span {
184         ::__internal::with_sess(|(_, mark)| {
185             let call_site = mark.expn_info().unwrap().call_site;
186             Span(call_site.with_ctxt(SyntaxContext::empty().apply_mark(mark)))
187         })
188     }
189 }
190
191 /// Quote a `Span` into a `TokenStream`.
192 /// This is needed to implement a custom quoter.
193 #[unstable(feature = "proc_macro", issue = "38356")]
194 pub fn quote_span(span: Span) -> TokenStream {
195     quote::Quote::quote(span)
196 }
197
198 macro_rules! diagnostic_method {
199     ($name:ident, $level:expr) => (
200         /// Create a new `Diagnostic` with the given `message` at the span
201         /// `self`.
202         #[unstable(feature = "proc_macro", issue = "38356")]
203         pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
204             Diagnostic::spanned(self, $level, message)
205         }
206     )
207 }
208
209 impl Span {
210     /// The span of the invocation of the current procedural macro.
211     #[unstable(feature = "proc_macro", issue = "38356")]
212     pub fn call_site() -> Span {
213         ::__internal::with_sess(|(_, mark)| Span(mark.expn_info().unwrap().call_site))
214     }
215
216     /// The original source file into which this span points.
217     #[unstable(feature = "proc_macro", issue = "38356")]
218     pub fn source_file(&self) -> SourceFile {
219         SourceFile {
220             filemap: __internal::lookup_char_pos(self.0.lo()).file,
221         }
222     }
223
224     /// Get the starting line/column in the source file for this span.
225     #[unstable(feature = "proc_macro", issue = "38356")]
226     pub fn start(&self) -> LineColumn {
227         let loc = __internal::lookup_char_pos(self.0.lo());
228         LineColumn {
229             line: loc.line,
230             column: loc.col.to_usize()
231         }
232     }
233
234     /// Get the ending line/column in the source file for this span.
235     #[unstable(feature = "proc_macro", issue = "38356")]
236     pub fn end(&self) -> LineColumn {
237         let loc = __internal::lookup_char_pos(self.0.hi());
238         LineColumn {
239             line: loc.line,
240             column: loc.col.to_usize()
241         }
242     }
243
244     /// Create a new span encompassing `self` and `other`.
245     ///
246     /// Returns `None` if `self` and `other` are from different files.
247     #[unstable(feature = "proc_macro", issue = "38356")]
248     pub fn join(&self, other: Span) -> Option<Span> {
249         let self_loc = __internal::lookup_char_pos(self.0.lo());
250         let other_loc = __internal::lookup_char_pos(self.0.lo());
251
252         if self_loc.file.name != other_loc.file.name { return None }
253
254         Some(Span(self.0.to(other.0)))
255     }
256
257     /// Creates a new span with the same line/column information as `self` but
258     /// that resolves symbols as though it were at `other`.
259     #[unstable(feature = "proc_macro", issue = "38356")]
260     pub fn resolved_at(&self, other: Span) -> Span {
261         Span(self.0.with_ctxt(other.0.ctxt()))
262     }
263
264     /// Creates a new span with the same name resolution behavior as `self` but
265     /// with the line/column information of `other`.
266     #[unstable(feature = "proc_macro", issue = "38356")]
267     pub fn located_at(&self, other: Span) -> Span {
268         other.resolved_at(*self)
269     }
270
271     diagnostic_method!(error, Level::Error);
272     diagnostic_method!(warning, Level::Warning);
273     diagnostic_method!(note, Level::Note);
274     diagnostic_method!(help, Level::Help);
275 }
276
277 /// A line-column pair representing the start or end of a `Span`.
278 #[unstable(feature = "proc_macro", issue = "38356")]
279 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
280 pub struct LineColumn {
281     /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
282     #[unstable(feature = "proc_macro", issue = "38356")]
283     pub line: usize,
284     /// The 0-indexed column (in UTF-8 characters) in the source file on which
285     /// the span starts or ends (inclusive).
286     #[unstable(feature = "proc_macro", issue = "38356")]
287     pub column: usize
288 }
289
290 /// The source file of a given `Span`.
291 #[unstable(feature = "proc_macro", issue = "38356")]
292 #[derive(Clone)]
293 pub struct SourceFile {
294     filemap: Rc<FileMap>,
295 }
296
297 impl SourceFile {
298     /// Get the path to this source file.
299     ///
300     /// ### Note
301     /// If the code span associated with this `SourceFile` was generated by an external macro, this
302     /// may not be an actual path on the filesystem. Use [`is_real`] to check.
303     ///
304     /// Also note that even if `is_real` returns `true`, if `-Z remap-path-prefix-*` was passed on
305     /// the command line, the path as given may not actually be valid.
306     ///
307     /// [`is_real`]: #method.is_real
308     # [unstable(feature = "proc_macro", issue = "38356")]
309     pub fn path(&self) -> &FileName {
310         &self.filemap.name
311     }
312
313     /// Returns `true` if this source file is a real source file, and not generated by an external
314     /// macro's expansion.
315     # [unstable(feature = "proc_macro", issue = "38356")]
316     pub fn is_real(&self) -> bool {
317         // This is a hack until intercrate spans are implemented and we can have real source files
318         // for spans generated in external macros.
319         // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
320         self.filemap.is_real_file()
321     }
322 }
323
324 #[unstable(feature = "proc_macro", issue = "38356")]
325 impl AsRef<FileName> for SourceFile {
326     fn as_ref(&self) -> &FileName {
327         self.path()
328     }
329 }
330
331 #[unstable(feature = "proc_macro", issue = "38356")]
332 impl fmt::Debug for SourceFile {
333     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
334         f.debug_struct("SourceFile")
335             .field("path", self.path())
336             .field("is_real", &self.is_real())
337             .finish()
338     }
339 }
340
341 #[unstable(feature = "proc_macro", issue = "38356")]
342 impl PartialEq for SourceFile {
343     fn eq(&self, other: &Self) -> bool {
344         Rc::ptr_eq(&self.filemap, &other.filemap)
345     }
346 }
347
348 #[unstable(feature = "proc_macro", issue = "38356")]
349 impl Eq for SourceFile {}
350
351 #[unstable(feature = "proc_macro", issue = "38356")]
352 impl PartialEq<FileName> for SourceFile {
353     fn eq(&self, other: &FileName) -> bool {
354         self.as_ref() == other
355     }
356 }
357
358 /// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
359 #[unstable(feature = "proc_macro", issue = "38356")]
360 #[derive(Clone, Debug)]
361 pub struct TokenTree {
362     /// The `TokenTree`'s span
363     pub span: Span,
364     /// Description of the `TokenTree`
365     pub kind: TokenNode,
366 }
367
368 #[unstable(feature = "proc_macro", issue = "38356")]
369 impl From<TokenNode> for TokenTree {
370     fn from(kind: TokenNode) -> TokenTree {
371         TokenTree { span: Span::def_site(), kind: kind }
372     }
373 }
374
375 #[unstable(feature = "proc_macro", issue = "38356")]
376 impl fmt::Display for TokenTree {
377     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
378         TokenStream::from(self.clone()).fmt(f)
379     }
380 }
381
382 /// Description of a `TokenTree`
383 #[derive(Clone, Debug)]
384 #[unstable(feature = "proc_macro", issue = "38356")]
385 pub enum TokenNode {
386     /// A delimited tokenstream.
387     Group(Delimiter, TokenStream),
388     /// A unicode identifier.
389     Term(Term),
390     /// A punctuation character (`+`, `,`, `$`, etc.).
391     Op(char, Spacing),
392     /// A literal character (`'a'`), string (`"hello"`), or number (`2.3`).
393     Literal(Literal),
394 }
395
396 /// Describes how a sequence of token trees is delimited.
397 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
398 #[unstable(feature = "proc_macro", issue = "38356")]
399 pub enum Delimiter {
400     /// `( ... )`
401     Parenthesis,
402     /// `{ ... }`
403     Brace,
404     /// `[ ... ]`
405     Bracket,
406     /// An implicit delimiter, e.g. `$var`, where $var is  `...`.
407     None,
408 }
409
410 /// An interned string.
411 #[derive(Copy, Clone, Debug)]
412 #[unstable(feature = "proc_macro", issue = "38356")]
413 pub struct Term(Symbol);
414
415 impl Term {
416     /// Intern a string into a `Term`.
417     #[unstable(feature = "proc_macro", issue = "38356")]
418     pub fn intern(string: &str) -> Term {
419         Term(Symbol::intern(string))
420     }
421
422     /// Get a reference to the interned string.
423     #[unstable(feature = "proc_macro", issue = "38356")]
424     pub fn as_str(&self) -> &str {
425         unsafe { &*(&*self.0.as_str() as *const str) }
426     }
427 }
428
429 /// Whether an `Op` is either followed immediately by another `Op` or followed by whitespace.
430 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
431 #[unstable(feature = "proc_macro", issue = "38356")]
432 pub enum Spacing {
433     /// e.g. `+` is `Alone` in `+ =`.
434     Alone,
435     /// e.g. `+` is `Joint` in `+=`.
436     Joint,
437 }
438
439 /// A literal character (`'a'`), string (`"hello"`), or number (`2.3`).
440 #[derive(Clone, Debug)]
441 #[unstable(feature = "proc_macro", issue = "38356")]
442 pub struct Literal(token::Token);
443
444 #[unstable(feature = "proc_macro", issue = "38356")]
445 impl fmt::Display for Literal {
446     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
447         TokenTree { kind: TokenNode::Literal(self.clone()), span: Span(DUMMY_SP) }.fmt(f)
448     }
449 }
450
451 macro_rules! int_literals {
452     ($($int_kind:ident),*) => {$(
453         /// Integer literal.
454         #[unstable(feature = "proc_macro", issue = "38356")]
455         pub fn $int_kind(n: $int_kind) -> Literal {
456             Literal::typed_integer(n as i128, stringify!($int_kind))
457         }
458     )*}
459 }
460
461 impl Literal {
462     /// Integer literal
463     #[unstable(feature = "proc_macro", issue = "38356")]
464     pub fn integer(n: i128) -> Literal {
465         Literal(token::Literal(token::Lit::Integer(Symbol::intern(&n.to_string())), None))
466     }
467
468     int_literals!(u8, i8, u16, i16, u32, i32, u64, i64, usize, isize);
469     fn typed_integer(n: i128, kind: &'static str) -> Literal {
470         Literal(token::Literal(token::Lit::Integer(Symbol::intern(&n.to_string())),
471                                Some(Symbol::intern(kind))))
472     }
473
474     /// Floating point literal.
475     #[unstable(feature = "proc_macro", issue = "38356")]
476     pub fn float(n: f64) -> Literal {
477         if !n.is_finite() {
478             panic!("Invalid float literal {}", n);
479         }
480         Literal(token::Literal(token::Lit::Float(Symbol::intern(&n.to_string())), None))
481     }
482
483     /// Floating point literal.
484     #[unstable(feature = "proc_macro", issue = "38356")]
485     pub fn f32(n: f32) -> Literal {
486         if !n.is_finite() {
487             panic!("Invalid f32 literal {}", n);
488         }
489         Literal(token::Literal(token::Lit::Float(Symbol::intern(&n.to_string())),
490                                Some(Symbol::intern("f32"))))
491     }
492
493     /// Floating point literal.
494     #[unstable(feature = "proc_macro", issue = "38356")]
495     pub fn f64(n: f64) -> Literal {
496         if !n.is_finite() {
497             panic!("Invalid f64 literal {}", n);
498         }
499         Literal(token::Literal(token::Lit::Float(Symbol::intern(&n.to_string())),
500                                Some(Symbol::intern("f64"))))
501     }
502
503     /// String literal.
504     #[unstable(feature = "proc_macro", issue = "38356")]
505     pub fn string(string: &str) -> Literal {
506         let mut escaped = String::new();
507         for ch in string.chars() {
508             escaped.extend(ch.escape_debug());
509         }
510         Literal(token::Literal(token::Lit::Str_(Symbol::intern(&escaped)), None))
511     }
512
513     /// Character literal.
514     #[unstable(feature = "proc_macro", issue = "38356")]
515     pub fn character(ch: char) -> Literal {
516         let mut escaped = String::new();
517         escaped.extend(ch.escape_unicode());
518         Literal(token::Literal(token::Lit::Char(Symbol::intern(&escaped)), None))
519     }
520
521     /// Byte string literal.
522     #[unstable(feature = "proc_macro", issue = "38356")]
523     pub fn byte_string(bytes: &[u8]) -> Literal {
524         let string = bytes.iter().cloned().flat_map(ascii::escape_default)
525             .map(Into::<char>::into).collect::<String>();
526         Literal(token::Literal(token::Lit::ByteStr(Symbol::intern(&string)), None))
527     }
528 }
529
530 /// An iterator over `TokenTree`s.
531 #[derive(Clone)]
532 #[unstable(feature = "proc_macro", issue = "38356")]
533 pub struct TokenTreeIter {
534     cursor: tokenstream::Cursor,
535     next: Option<tokenstream::TokenStream>,
536 }
537
538 #[unstable(feature = "proc_macro", issue = "38356")]
539 impl Iterator for TokenTreeIter {
540     type Item = TokenTree;
541
542     fn next(&mut self) -> Option<TokenTree> {
543         loop {
544             let next =
545                 unwrap_or!(self.next.take().or_else(|| self.cursor.next_as_stream()), return None);
546             let tree = TokenTree::from_internal(next, &mut self.next);
547             if tree.span.0 == DUMMY_SP {
548                 if let TokenNode::Group(Delimiter::None, stream) = tree.kind {
549                     self.cursor.insert(stream.0);
550                     continue
551                 }
552             }
553             return Some(tree);
554         }
555     }
556 }
557
558 impl Delimiter {
559     fn from_internal(delim: token::DelimToken) -> Delimiter {
560         match delim {
561             token::Paren => Delimiter::Parenthesis,
562             token::Brace => Delimiter::Brace,
563             token::Bracket => Delimiter::Bracket,
564             token::NoDelim => Delimiter::None,
565         }
566     }
567
568     fn to_internal(self) -> token::DelimToken {
569         match self {
570             Delimiter::Parenthesis => token::Paren,
571             Delimiter::Brace => token::Brace,
572             Delimiter::Bracket => token::Bracket,
573             Delimiter::None => token::NoDelim,
574         }
575     }
576 }
577
578 impl TokenTree {
579     fn from_internal(stream: tokenstream::TokenStream, next: &mut Option<tokenstream::TokenStream>)
580                 -> TokenTree {
581         use syntax::parse::token::*;
582
583         let (tree, is_joint) = stream.as_tree();
584         let (mut span, token) = match tree {
585             tokenstream::TokenTree::Token(span, token) => (span, token),
586             tokenstream::TokenTree::Delimited(span, delimed) => {
587                 let delimiter = Delimiter::from_internal(delimed.delim);
588                 return TokenTree {
589                     span: Span(span),
590                     kind: TokenNode::Group(delimiter, TokenStream(delimed.tts.into())),
591                 };
592             }
593         };
594
595         let op_kind = if is_joint { Spacing::Joint } else { Spacing::Alone };
596         macro_rules! op {
597             ($op:expr) => { TokenNode::Op($op, op_kind) }
598         }
599
600         macro_rules! joint {
601             ($first:expr, $rest:expr) => { joint($first, $rest, is_joint, &mut span, next) }
602         }
603
604         fn joint(first: char, rest: Token, is_joint: bool, span: &mut syntax_pos::Span,
605                  next: &mut Option<tokenstream::TokenStream>)
606                  -> TokenNode {
607             let (first_span, rest_span) = (*span, *span);
608             *span = first_span;
609             let tree = tokenstream::TokenTree::Token(rest_span, rest);
610             *next = Some(if is_joint { tree.joint() } else { tree.into() });
611             TokenNode::Op(first, Spacing::Joint)
612         }
613
614         let kind = match token {
615             Eq => op!('='),
616             Lt => op!('<'),
617             Le => joint!('<', Eq),
618             EqEq => joint!('=', Eq),
619             Ne => joint!('!', Eq),
620             Ge => joint!('>', Eq),
621             Gt => op!('>'),
622             AndAnd => joint!('&', BinOp(And)),
623             OrOr => joint!('|', BinOp(Or)),
624             Not => op!('!'),
625             Tilde => op!('~'),
626             BinOp(Plus) => op!('+'),
627             BinOp(Minus) => op!('-'),
628             BinOp(Star) => op!('*'),
629             BinOp(Slash) => op!('/'),
630             BinOp(Percent) => op!('%'),
631             BinOp(Caret) => op!('^'),
632             BinOp(And) => op!('&'),
633             BinOp(Or) => op!('|'),
634             BinOp(Shl) => joint!('<', Lt),
635             BinOp(Shr) => joint!('>', Gt),
636             BinOpEq(Plus) => joint!('+', Eq),
637             BinOpEq(Minus) => joint!('-', Eq),
638             BinOpEq(Star) => joint!('*', Eq),
639             BinOpEq(Slash) => joint!('/', Eq),
640             BinOpEq(Percent) => joint!('%', Eq),
641             BinOpEq(Caret) => joint!('^', Eq),
642             BinOpEq(And) => joint!('&', Eq),
643             BinOpEq(Or) => joint!('|', Eq),
644             BinOpEq(Shl) => joint!('<', Le),
645             BinOpEq(Shr) => joint!('>', Ge),
646             At => op!('@'),
647             Dot => op!('.'),
648             DotDot => joint!('.', Dot),
649             DotDotDot => joint!('.', DotDot),
650             DotDotEq => joint!('.', DotEq),
651             Comma => op!(','),
652             Semi => op!(';'),
653             Colon => op!(':'),
654             ModSep => joint!(':', Colon),
655             RArrow => joint!('-', Gt),
656             LArrow => joint!('<', BinOp(Minus)),
657             FatArrow => joint!('=', Gt),
658             Pound => op!('#'),
659             Dollar => op!('$'),
660             Question => op!('?'),
661             Underscore => op!('_'),
662
663             Ident(ident) | Lifetime(ident) => TokenNode::Term(Term(ident.name)),
664             Literal(..) | DocComment(..) => TokenNode::Literal(self::Literal(token)),
665
666             Interpolated(_) => {
667                 __internal::with_sess(|(sess, _)| {
668                     let tts = token.interpolated_to_tokenstream(sess, span);
669                     TokenNode::Group(Delimiter::None, TokenStream(tts))
670                 })
671             }
672
673             DotEq => unreachable!(),
674             OpenDelim(..) | CloseDelim(..) => unreachable!(),
675             Whitespace | Comment | Shebang(..) | Eof => unreachable!(),
676         };
677
678         TokenTree { span: Span(span), kind: kind }
679     }
680
681     fn to_internal(self) -> tokenstream::TokenStream {
682         use syntax::parse::token::*;
683         use syntax::tokenstream::{TokenTree, Delimited};
684
685         let (op, kind) = match self.kind {
686             TokenNode::Op(op, kind) => (op, kind),
687             TokenNode::Group(delimiter, tokens) => {
688                 return TokenTree::Delimited(self.span.0, Delimited {
689                     delim: delimiter.to_internal(),
690                     tts: tokens.0.into(),
691                 }).into();
692             },
693             TokenNode::Term(symbol) => {
694                 let ident = ast::Ident { name: symbol.0, ctxt: self.span.0.ctxt() };
695                 let token =
696                     if symbol.0.as_str().starts_with("'") { Lifetime(ident) } else { Ident(ident) };
697                 return TokenTree::Token(self.span.0, token).into();
698             }
699             TokenNode::Literal(token) => return TokenTree::Token(self.span.0, token.0).into(),
700         };
701
702         let token = match op {
703             '=' => Eq,
704             '<' => Lt,
705             '>' => Gt,
706             '!' => Not,
707             '~' => Tilde,
708             '+' => BinOp(Plus),
709             '-' => BinOp(Minus),
710             '*' => BinOp(Star),
711             '/' => BinOp(Slash),
712             '%' => BinOp(Percent),
713             '^' => BinOp(Caret),
714             '&' => BinOp(And),
715             '|' => BinOp(Or),
716             '@' => At,
717             '.' => Dot,
718             ',' => Comma,
719             ';' => Semi,
720             ':' => Colon,
721             '#' => Pound,
722             '$' => Dollar,
723             '?' => Question,
724             '_' => Underscore,
725             _ => panic!("unsupported character {}", op),
726         };
727
728         let tree = TokenTree::Token(self.span.0, token);
729         match kind {
730             Spacing::Alone => tree.into(),
731             Spacing::Joint => tree.joint(),
732         }
733     }
734 }
735
736 /// Permanently unstable internal implementation details of this crate. This
737 /// should not be used.
738 ///
739 /// These methods are used by the rest of the compiler to generate instances of
740 /// `TokenStream` to hand to macro definitions, as well as consume the output.
741 ///
742 /// Note that this module is also intentionally separate from the rest of the
743 /// crate. This allows the `#[unstable]` directive below to naturally apply to
744 /// all of the contents.
745 #[unstable(feature = "proc_macro_internals", issue = "27812")]
746 #[doc(hidden)]
747 pub mod __internal {
748     pub use quote::{LiteralKind, Quoter, unquote};
749
750     use std::cell::Cell;
751
752     use syntax::ast;
753     use syntax::ext::base::ExtCtxt;
754     use syntax::ext::hygiene::Mark;
755     use syntax::ptr::P;
756     use syntax::parse::{self, ParseSess};
757     use syntax::parse::token::{self, Token};
758     use syntax::tokenstream;
759     use syntax_pos::{BytePos, Loc, DUMMY_SP};
760
761     use super::{TokenStream, LexError};
762
763     pub fn lookup_char_pos(pos: BytePos) -> Loc {
764         with_sess(|(sess, _)| sess.codemap().lookup_char_pos(pos))
765     }
766
767     pub fn new_token_stream(item: P<ast::Item>) -> TokenStream {
768         let token = Token::interpolated(token::NtItem(item));
769         TokenStream(tokenstream::TokenTree::Token(DUMMY_SP, token).into())
770     }
771
772     pub fn token_stream_wrap(inner: tokenstream::TokenStream) -> TokenStream {
773         TokenStream(inner)
774     }
775
776     pub fn token_stream_parse_items(stream: TokenStream) -> Result<Vec<P<ast::Item>>, LexError> {
777         with_sess(move |(sess, _)| {
778             let mut parser = parse::stream_to_parser(sess, stream.0);
779             let mut items = Vec::new();
780
781             while let Some(item) = try!(parser.parse_item().map_err(super::parse_to_lex_err)) {
782                 items.push(item)
783             }
784
785             Ok(items)
786         })
787     }
788
789     pub fn token_stream_inner(stream: TokenStream) -> tokenstream::TokenStream {
790         stream.0
791     }
792
793     pub trait Registry {
794         fn register_custom_derive(&mut self,
795                                   trait_name: &str,
796                                   expand: fn(TokenStream) -> TokenStream,
797                                   attributes: &[&'static str]);
798
799         fn register_attr_proc_macro(&mut self,
800                                     name: &str,
801                                     expand: fn(TokenStream, TokenStream) -> TokenStream);
802
803         fn register_bang_proc_macro(&mut self,
804                                     name: &str,
805                                     expand: fn(TokenStream) -> TokenStream);
806     }
807
808     // Emulate scoped_thread_local!() here essentially
809     thread_local! {
810         static CURRENT_SESS: Cell<(*const ParseSess, Mark)> =
811             Cell::new((0 as *const _, Mark::root()));
812     }
813
814     pub fn set_sess<F, R>(cx: &ExtCtxt, f: F) -> R
815         where F: FnOnce() -> R
816     {
817         struct Reset { prev: (*const ParseSess, Mark) }
818
819         impl Drop for Reset {
820             fn drop(&mut self) {
821                 CURRENT_SESS.with(|p| p.set(self.prev));
822             }
823         }
824
825         CURRENT_SESS.with(|p| {
826             let _reset = Reset { prev: p.get() };
827             p.set((cx.parse_sess, cx.current_expansion.mark));
828             f()
829         })
830     }
831
832     pub fn with_sess<F, R>(f: F) -> R
833         where F: FnOnce((&ParseSess, Mark)) -> R
834     {
835         let p = CURRENT_SESS.with(|p| p.get());
836         assert!(!p.0.is_null(), "proc_macro::__internal::with_sess() called \
837                                  before set_parse_sess()!");
838         f(unsafe { (&*p.0, p.1) })
839     }
840 }
841
842 fn parse_to_lex_err(mut err: DiagnosticBuilder) -> LexError {
843     err.cancel();
844     LexError { _inner: () }
845 }