]> git.lizzy.rs Git - rust.git/blob - src/libproc_macro/lib.rs
b54054752eaf14521ea3405f9bb7c91039d2cd02
[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 such as
15 //! function-like macros `#[proc_macro]`, macro attribures `#[proc_macro_attribute]` and
16 //! custom derive attributes`#[proc_macro_derive]`.
17 //!
18 //! Note that this crate is intentionally bare-bones currently.
19 //! This functionality is intended to be expanded over time as more surface
20 //! area for macro authors is stabilized.
21 //!
22 //! See [the book](../book/first-edition/procedural-macros.html) for more.
23
24 #![stable(feature = "proc_macro_lib", since = "1.15.0")]
25 #![deny(missing_docs)]
26 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
27        html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
28        html_root_url = "https://doc.rust-lang.org/nightly/",
29        html_playground_url = "https://play.rust-lang.org/",
30        issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
31        test(no_crate_inject, attr(deny(warnings))),
32        test(attr(allow(dead_code, deprecated, unused_variables, unused_mut))))]
33
34 #![cfg_attr(not(stage0), feature(nll))]
35 #![feature(rustc_private)]
36 #![feature(staged_api)]
37 #![feature(lang_items)]
38 #![feature(optin_builtin_traits)]
39 #![feature(non_exhaustive)]
40
41 #![recursion_limit="256"]
42
43 extern crate syntax;
44 extern crate syntax_pos;
45 extern crate rustc_errors;
46 extern crate rustc_data_structures;
47
48 #[unstable(feature = "proc_macro_internals", issue = "27812")]
49 #[doc(hidden)]
50 pub mod rustc;
51
52 mod diagnostic;
53
54 #[unstable(feature = "proc_macro_diagnostic", issue = "38356")]
55 pub use diagnostic::{Diagnostic, Level};
56
57 use std::{ascii, fmt, iter};
58 use std::path::PathBuf;
59 use rustc_data_structures::sync::Lrc;
60 use std::str::FromStr;
61
62 use syntax::errors::DiagnosticBuilder;
63 use syntax::parse::{self, token};
64 use syntax::symbol::Symbol;
65 use syntax::tokenstream;
66 use syntax_pos::{FileMap, Pos, FileName};
67
68 /// The main type provided by this crate, representing an abstract stream of
69 /// tokens, or, more specifically, a sequence of token trees.
70 /// The type provide interfaces for iterating over those token trees and, conversely,
71 /// collecting a number of token trees into one stream.
72 ///
73 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
74 /// and `#[proc_macro_derive]` definitions.
75 ///
76 /// The API of this type is intentionally bare-bones, but it'll be expanded over
77 /// time!
78 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
79 #[derive(Clone)]
80 pub struct TokenStream(tokenstream::TokenStream);
81
82 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
83 impl !Send for TokenStream {}
84 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
85 impl !Sync for TokenStream {}
86
87 /// Error returned from `TokenStream::from_str`.
88 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
89 #[derive(Debug)]
90 pub struct LexError {
91     _inner: (),
92 }
93
94 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
95 impl !Send for LexError {}
96 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
97 impl !Sync for LexError {}
98
99 impl TokenStream {
100     /// Returns an empty `TokenStream` containing no token trees.
101     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
102     pub fn new() -> TokenStream {
103         TokenStream(tokenstream::TokenStream::empty())
104     }
105
106     /// Checks if this `TokenStream` is empty.
107     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
108     pub fn is_empty(&self) -> bool {
109         self.0.is_empty()
110     }
111 }
112
113 /// Attempts to break the string into tokens and parse those tokens into a token stream.
114 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
115 /// or characters not existing in the language.
116 /// All tokens in the parsed stream get `Span::call_site()` spans.
117 ///
118 /// NOTE: Some errors may cause panics instead of returning `LexError`. We reserve the right to
119 /// change these errors into `LexError`s later.
120 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
121 impl FromStr for TokenStream {
122     type Err = LexError;
123
124     fn from_str(src: &str) -> Result<TokenStream, LexError> {
125         __internal::with_sess(|sess, data| {
126             Ok(__internal::token_stream_wrap(parse::parse_stream_from_source_str(
127                 FileName::ProcMacroSourceCode, src.to_string(), sess, Some(data.call_site.0)
128             )))
129         })
130     }
131 }
132
133 /// Prints the token stream as a string that is supposed to be losslessly convertible back
134 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
135 /// with `Delimiter::None` delimiters and negative numeric literals.
136 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
137 impl fmt::Display for TokenStream {
138     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
139         self.0.fmt(f)
140     }
141 }
142
143 /// Prints token in a form convenient for debugging.
144 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
145 impl fmt::Debug for TokenStream {
146     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
147         f.write_str("TokenStream ")?;
148         f.debug_list().entries(self.clone()).finish()
149     }
150 }
151
152 #[unstable(feature = "proc_macro_quote", issue = "38356")]
153 pub use quote::{quote, quote_span};
154
155 /// Creates a token stream containing a single token tree.
156     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
157 impl From<TokenTree> for TokenStream {
158     fn from(tree: TokenTree) -> TokenStream {
159         TokenStream(tree.to_internal())
160     }
161 }
162
163 /// Collects a number of token trees into a single stream.
164     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
165 impl iter::FromIterator<TokenTree> for TokenStream {
166     fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
167         trees.into_iter().map(TokenStream::from).collect()
168     }
169 }
170
171 /// A "flattening" operation on token streams, collects token trees
172 /// from multiple token streams into a single stream.
173 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
174 impl iter::FromIterator<TokenStream> for TokenStream {
175     fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
176         let mut builder = tokenstream::TokenStreamBuilder::new();
177         for stream in streams {
178             builder.push(stream.0);
179         }
180         TokenStream(builder.build())
181     }
182 }
183
184 #[stable(feature = "token_stream_extend", since = "1.30.0")]
185 impl Extend<TokenTree> for TokenStream {
186     fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
187         self.extend(trees.into_iter().map(TokenStream::from));
188     }
189 }
190
191 #[stable(feature = "token_stream_extend", since = "1.30.0")]
192 impl Extend<TokenStream> for TokenStream {
193     fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
194         self.0.extend(streams.into_iter().map(|stream| stream.0));
195     }
196 }
197
198 /// Public implementation details for the `TokenStream` type, such as iterators.
199 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
200 pub mod token_stream {
201     use syntax::tokenstream;
202     use {TokenTree, TokenStream, Delimiter};
203
204     /// An iterator over `TokenStream`'s `TokenTree`s.
205     /// The iteration is "shallow", e.g. the iterator doesn't recurse into delimited groups,
206     /// and returns whole groups as token trees.
207     #[derive(Clone)]
208     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
209     pub struct IntoIter {
210         cursor: tokenstream::Cursor,
211         stack: Vec<TokenTree>,
212     }
213
214     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
215     impl Iterator for IntoIter {
216         type Item = TokenTree;
217
218         fn next(&mut self) -> Option<TokenTree> {
219             loop {
220                 let tree = self.stack.pop().or_else(|| {
221                     let next = self.cursor.next_as_stream()?;
222                     Some(TokenTree::from_internal(next, &mut self.stack))
223                 })?;
224                 // HACK: The condition "dummy span + group with empty delimiter" represents an AST
225                 // fragment approximately converted into a token stream. This may happen, for
226                 // example, with inputs to proc macro attributes, including derives. Such "groups"
227                 // need to flattened during iteration over stream's token trees.
228                 // Eventually this needs to be removed in favor of keeping original token trees
229                 // and not doing the roundtrip through AST.
230                 if tree.span().0.is_dummy() {
231                     if let TokenTree::Group(ref group) = tree {
232                         if group.delimiter() == Delimiter::None {
233                             self.cursor.insert(group.stream.clone().0);
234                             continue
235                         }
236                     }
237                 }
238                 return Some(tree);
239             }
240         }
241     }
242
243     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
244     impl IntoIterator for TokenStream {
245         type Item = TokenTree;
246         type IntoIter = IntoIter;
247
248         fn into_iter(self) -> IntoIter {
249             IntoIter { cursor: self.0.trees(), stack: Vec::new() }
250         }
251     }
252 }
253
254 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
255 /// For example, `quote!(a + b)` will produce a expression, that, when evaluated, constructs
256 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
257 ///
258 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
259 /// To quote `$` itself, use `$$`.
260 ///
261 /// This is a dummy macro, the actual implementation is in `quote::quote`.`
262 #[unstable(feature = "proc_macro_quote", issue = "38356")]
263 #[macro_export]
264 macro_rules! quote { () => {} }
265
266 #[unstable(feature = "proc_macro_internals", issue = "27812")]
267 #[doc(hidden)]
268 mod quote;
269
270 /// A region of source code, along with macro expansion information.
271 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
272 #[derive(Copy, Clone)]
273 pub struct Span(syntax_pos::Span);
274
275 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
276 impl !Send for Span {}
277 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
278 impl !Sync for Span {}
279
280 macro_rules! diagnostic_method {
281     ($name:ident, $level:expr) => (
282         /// Create a new `Diagnostic` with the given `message` at the span
283         /// `self`.
284         #[unstable(feature = "proc_macro_diagnostic", issue = "38356")]
285         pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
286             Diagnostic::spanned(self, $level, message)
287         }
288     )
289 }
290
291 impl Span {
292     /// A span that resolves at the macro definition site.
293     #[unstable(feature = "proc_macro_span", issue = "38356")]
294     pub fn def_site() -> Span {
295         ::__internal::with_sess(|_, data| data.def_site)
296     }
297
298     /// The span of the invocation of the current procedural macro.
299     /// Identifiers created with this span will be resolved as if they were written
300     /// directly at the macro call location (call-site hygiene) and other code
301     /// at the macro call site will be able to refer to them as well.
302     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
303     pub fn call_site() -> Span {
304         ::__internal::with_sess(|_, data| data.call_site)
305     }
306
307     /// The original source file into which this span points.
308     #[unstable(feature = "proc_macro_span", issue = "38356")]
309     pub fn source_file(&self) -> SourceFile {
310         SourceFile {
311             filemap: __internal::lookup_char_pos(self.0.lo()).file,
312         }
313     }
314
315     /// The `Span` for the tokens in the previous macro expansion from which
316     /// `self` was generated from, if any.
317     #[unstable(feature = "proc_macro_span", issue = "38356")]
318     pub fn parent(&self) -> Option<Span> {
319         self.0.parent().map(Span)
320     }
321
322     /// The span for the origin source code that `self` was generated from. If
323     /// this `Span` wasn't generated from other macro expansions then the return
324     /// value is the same as `*self`.
325     #[unstable(feature = "proc_macro_span", issue = "38356")]
326     pub fn source(&self) -> Span {
327         Span(self.0.source_callsite())
328     }
329
330     /// Get the starting line/column in the source file for this span.
331     #[unstable(feature = "proc_macro_span", issue = "38356")]
332     pub fn start(&self) -> LineColumn {
333         let loc = __internal::lookup_char_pos(self.0.lo());
334         LineColumn {
335             line: loc.line,
336             column: loc.col.to_usize()
337         }
338     }
339
340     /// Get the ending line/column in the source file for this span.
341     #[unstable(feature = "proc_macro_span", issue = "38356")]
342     pub fn end(&self) -> LineColumn {
343         let loc = __internal::lookup_char_pos(self.0.hi());
344         LineColumn {
345             line: loc.line,
346             column: loc.col.to_usize()
347         }
348     }
349
350     /// Create a new span encompassing `self` and `other`.
351     ///
352     /// Returns `None` if `self` and `other` are from different files.
353     #[unstable(feature = "proc_macro_span", issue = "38356")]
354     pub fn join(&self, other: Span) -> Option<Span> {
355         let self_loc = __internal::lookup_char_pos(self.0.lo());
356         let other_loc = __internal::lookup_char_pos(other.0.lo());
357
358         if self_loc.file.name != other_loc.file.name { return None }
359
360         Some(Span(self.0.to(other.0)))
361     }
362
363     /// Creates a new span with the same line/column information as `self` but
364     /// that resolves symbols as though it were at `other`.
365     #[unstable(feature = "proc_macro_span", issue = "38356")]
366     pub fn resolved_at(&self, other: Span) -> Span {
367         Span(self.0.with_ctxt(other.0.ctxt()))
368     }
369
370     /// Creates a new span with the same name resolution behavior as `self` but
371     /// with the line/column information of `other`.
372     #[unstable(feature = "proc_macro_span", issue = "38356")]
373     pub fn located_at(&self, other: Span) -> Span {
374         other.resolved_at(*self)
375     }
376
377     /// Compares to spans to see if they're equal.
378     #[unstable(feature = "proc_macro_span", issue = "38356")]
379     pub fn eq(&self, other: &Span) -> bool {
380         self.0 == other.0
381     }
382
383     diagnostic_method!(error, Level::Error);
384     diagnostic_method!(warning, Level::Warning);
385     diagnostic_method!(note, Level::Note);
386     diagnostic_method!(help, Level::Help);
387 }
388
389 /// Prints a span in a form convenient for debugging.
390 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
391 impl fmt::Debug for Span {
392     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
393         write!(f, "{:?} bytes({}..{})",
394                self.0.ctxt(),
395                self.0.lo().0,
396                self.0.hi().0)
397     }
398 }
399
400 /// A line-column pair representing the start or end of a `Span`.
401 #[unstable(feature = "proc_macro_span", issue = "38356")]
402 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
403 pub struct LineColumn {
404     /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
405     #[unstable(feature = "proc_macro_span", issue = "38356")]
406     pub line: usize,
407     /// The 0-indexed column (in UTF-8 characters) in the source file on which
408     /// the span starts or ends (inclusive).
409     #[unstable(feature = "proc_macro_span", issue = "38356")]
410     pub column: usize
411 }
412
413 #[unstable(feature = "proc_macro_span", issue = "38356")]
414 impl !Send for LineColumn {}
415 #[unstable(feature = "proc_macro_span", issue = "38356")]
416 impl !Sync for LineColumn {}
417
418 /// The source file of a given `Span`.
419 #[unstable(feature = "proc_macro_span", issue = "38356")]
420 #[derive(Clone)]
421 pub struct SourceFile {
422     filemap: Lrc<FileMap>,
423 }
424
425 #[unstable(feature = "proc_macro_span", issue = "38356")]
426 impl !Send for SourceFile {}
427 #[unstable(feature = "proc_macro_span", issue = "38356")]
428 impl !Sync for SourceFile {}
429
430 impl SourceFile {
431     /// Get the path to this source file.
432     ///
433     /// ### Note
434     /// If the code span associated with this `SourceFile` was generated by an external macro, this
435     /// may not be an actual path on the filesystem. Use [`is_real`] to check.
436     ///
437     /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
438     /// the command line, the path as given may not actually be valid.
439     ///
440     /// [`is_real`]: #method.is_real
441     #[unstable(feature = "proc_macro_span", issue = "38356")]
442     pub fn path(&self) -> PathBuf {
443         match self.filemap.name {
444             FileName::Real(ref path) => path.clone(),
445             _ => PathBuf::from(self.filemap.name.to_string())
446         }
447     }
448
449     /// Returns `true` if this source file is a real source file, and not generated by an external
450     /// macro's expansion.
451     #[unstable(feature = "proc_macro_span", issue = "38356")]
452     pub fn is_real(&self) -> bool {
453         // This is a hack until intercrate spans are implemented and we can have real source files
454         // for spans generated in external macros.
455         // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
456         self.filemap.is_real_file()
457     }
458 }
459
460
461 #[unstable(feature = "proc_macro_span", issue = "38356")]
462 impl fmt::Debug for SourceFile {
463     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
464         f.debug_struct("SourceFile")
465             .field("path", &self.path())
466             .field("is_real", &self.is_real())
467             .finish()
468     }
469 }
470
471 #[unstable(feature = "proc_macro_span", issue = "38356")]
472 impl PartialEq for SourceFile {
473     fn eq(&self, other: &Self) -> bool {
474         Lrc::ptr_eq(&self.filemap, &other.filemap)
475     }
476 }
477
478 #[unstable(feature = "proc_macro_span", issue = "38356")]
479 impl Eq for SourceFile {}
480
481 /// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
482 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
483 #[derive(Clone)]
484 pub enum TokenTree {
485     /// A token stream surrounded by bracket delimiters.
486     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
487     Group(
488         #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
489         Group
490     ),
491     /// An identifier.
492     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
493     Ident(
494         #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
495         Ident
496     ),
497     /// A single punctuation character (`+`, `,`, `$`, etc.).
498     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
499     Punct(
500         #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
501         Punct
502     ),
503     /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
504     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
505     Literal(
506         #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
507         Literal
508     ),
509 }
510
511 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
512 impl !Send for TokenTree {}
513 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
514 impl !Sync for TokenTree {}
515
516 impl TokenTree {
517     /// Returns the span of this tree, delegating to the `span` method of
518     /// the contained token or a delimited stream.
519     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
520     pub fn span(&self) -> Span {
521         match *self {
522             TokenTree::Group(ref t) => t.span(),
523             TokenTree::Ident(ref t) => t.span(),
524             TokenTree::Punct(ref t) => t.span(),
525             TokenTree::Literal(ref t) => t.span(),
526         }
527     }
528
529     /// Configures the span for *only this token*.
530     ///
531     /// Note that if this token is a `Group` then this method will not configure
532     /// the span of each of the internal tokens, this will simply delegate to
533     /// the `set_span` method of each variant.
534     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
535     pub fn set_span(&mut self, span: Span) {
536         match *self {
537             TokenTree::Group(ref mut t) => t.set_span(span),
538             TokenTree::Ident(ref mut t) => t.set_span(span),
539             TokenTree::Punct(ref mut t) => t.set_span(span),
540             TokenTree::Literal(ref mut t) => t.set_span(span),
541         }
542     }
543 }
544
545 /// Prints token treee in a form convenient for debugging.
546 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
547 impl fmt::Debug for TokenTree {
548     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
549         // Each of these has the name in the struct type in the derived debug,
550         // so don't bother with an extra layer of indirection
551         match *self {
552             TokenTree::Group(ref tt) => tt.fmt(f),
553             TokenTree::Ident(ref tt) => tt.fmt(f),
554             TokenTree::Punct(ref tt) => tt.fmt(f),
555             TokenTree::Literal(ref tt) => tt.fmt(f),
556         }
557     }
558 }
559
560 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
561 impl From<Group> for TokenTree {
562     fn from(g: Group) -> TokenTree {
563         TokenTree::Group(g)
564     }
565 }
566
567 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
568 impl From<Ident> for TokenTree {
569     fn from(g: Ident) -> TokenTree {
570         TokenTree::Ident(g)
571     }
572 }
573
574 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
575 impl From<Punct> for TokenTree {
576     fn from(g: Punct) -> TokenTree {
577         TokenTree::Punct(g)
578     }
579 }
580
581 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
582 impl From<Literal> for TokenTree {
583     fn from(g: Literal) -> TokenTree {
584         TokenTree::Literal(g)
585     }
586 }
587
588 /// Prints the token tree as a string that is supposed to be losslessly convertible back
589 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
590 /// with `Delimiter::None` delimiters and negative numeric literals.
591 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
592 impl fmt::Display for TokenTree {
593     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
594         match *self {
595             TokenTree::Group(ref t) => t.fmt(f),
596             TokenTree::Ident(ref t) => t.fmt(f),
597             TokenTree::Punct(ref t) => t.fmt(f),
598             TokenTree::Literal(ref t) => t.fmt(f),
599         }
600     }
601 }
602
603 /// A delimited token stream.
604 ///
605 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
606 #[derive(Clone)]
607 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
608 pub struct Group {
609     delimiter: Delimiter,
610     stream: TokenStream,
611     span: Span,
612 }
613
614 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
615 impl !Send for Group {}
616 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
617 impl !Sync for Group {}
618
619 /// Describes how a sequence of token trees is delimited.
620 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
621 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
622 pub enum Delimiter {
623     /// `( ... )`
624     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
625     Parenthesis,
626     /// `{ ... }`
627     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
628     Brace,
629     /// `[ ... ]`
630     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
631     Bracket,
632     /// `Ø ... Ã˜`
633     /// An implicit delimiter, that may, for example, appear around tokens coming from a
634     /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
635     /// `$var * 3` where `$var` is `1 + 2`.
636     /// Implicit delimiters may not survive roundtrip of a token stream through a string.
637     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
638     None,
639 }
640
641 impl Group {
642     /// Creates a new `Group` with the given delimiter and token stream.
643     ///
644     /// This constructor will set the span for this group to
645     /// `Span::call_site()`. To change the span you can use the `set_span`
646     /// method below.
647     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
648     pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
649         Group {
650             delimiter: delimiter,
651             stream: stream,
652             span: Span::call_site(),
653         }
654     }
655
656     /// Returns the delimiter of this `Group`
657     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
658     pub fn delimiter(&self) -> Delimiter {
659         self.delimiter
660     }
661
662     /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
663     ///
664     /// Note that the returned token stream does not include the delimiter
665     /// returned above.
666     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
667     pub fn stream(&self) -> TokenStream {
668         self.stream.clone()
669     }
670
671     /// Returns the span for the delimiters of this token stream, spanning the
672     /// entire `Group`.
673     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
674     pub fn span(&self) -> Span {
675         self.span
676     }
677
678     /// Configures the span for this `Group`'s delimiters, but not its internal
679     /// tokens.
680     ///
681     /// This method will **not** set the span of all the internal tokens spanned
682     /// by this group, but rather it will only set the span of the delimiter
683     /// tokens at the level of the `Group`.
684     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
685     pub fn set_span(&mut self, span: Span) {
686         self.span = span;
687     }
688 }
689
690 /// Prints the group as a string that should be losslessly convertible back
691 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
692 /// with `Delimiter::None` delimiters.
693 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
694 impl fmt::Display for Group {
695     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
696         TokenStream::from(TokenTree::from(self.clone())).fmt(f)
697     }
698 }
699
700 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
701 impl fmt::Debug for Group {
702     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
703         f.debug_struct("Group")
704             .field("delimiter", &self.delimiter())
705             .field("stream", &self.stream())
706             .field("span", &self.span())
707             .finish()
708     }
709 }
710
711 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
712 ///
713 /// Multicharacter operators like `+=` are represented as two instances of `Punct` with different
714 /// forms of `Spacing` returned.
715 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
716 #[derive(Clone)]
717 pub struct Punct {
718     ch: char,
719     spacing: Spacing,
720     span: Span,
721 }
722
723 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
724 impl !Send for Punct {}
725 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
726 impl !Sync for Punct {}
727
728 /// Whether an `Punct` is followed immediately by another `Punct` or
729 /// followed by another token or whitespace.
730 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
731 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
732 pub enum Spacing {
733     /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
734     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
735     Alone,
736     /// E.g. `+` is `Joint` in `+=` or `'#`.
737     /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
738     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
739     Joint,
740 }
741
742 impl Punct {
743     /// Creates a new `Punct` from the given character and spacing.
744     /// The `ch` argument must be a valid punctuation character permitted by the language,
745     /// otherwise the function will panic.
746     ///
747     /// The returned `Punct` will have the default span of `Span::call_site()`
748     /// which can be further configured with the `set_span` method below.
749     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
750     pub fn new(ch: char, spacing: Spacing) -> Punct {
751         const LEGAL_CHARS: &[char] = &['=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^',
752                                        '&', '|', '@', '.', ',', ';', ':', '#', '$', '?', '\''];
753         if !LEGAL_CHARS.contains(&ch) {
754             panic!("unsupported character `{:?}`", ch)
755         }
756         Punct {
757             ch: ch,
758             spacing: spacing,
759             span: Span::call_site(),
760         }
761     }
762
763     /// Returns the value of this punctuation character as `char`.
764     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
765     pub fn as_char(&self) -> char {
766         self.ch
767     }
768
769     /// Returns the spacing of this punctuation character, indicating whether it's immediately
770     /// followed by another `Punct` in the token stream, so they can potentially be combined into
771     /// a multicharacter operator (`Joint`), or it's followed by some other token or whitespace
772     /// (`Alone`) so the operator has certainly ended.
773     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
774     pub fn spacing(&self) -> Spacing {
775         self.spacing
776     }
777
778     /// Returns the span for this punctuation character.
779     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
780     pub fn span(&self) -> Span {
781         self.span
782     }
783
784     /// Configure the span for this punctuation character.
785     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
786     pub fn set_span(&mut self, span: Span) {
787         self.span = span;
788     }
789 }
790
791 /// Prints the punctuation character as a string that should be losslessly convertible
792 /// back into the same character.
793 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
794 impl fmt::Display for Punct {
795     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
796         TokenStream::from(TokenTree::from(self.clone())).fmt(f)
797     }
798 }
799
800 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
801 impl fmt::Debug for Punct {
802     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
803         f.debug_struct("Punct")
804             .field("ch", &self.as_char())
805             .field("spacing", &self.spacing())
806             .field("span", &self.span())
807             .finish()
808     }
809 }
810
811 /// An identifier (`ident`).
812 #[derive(Clone)]
813 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
814 pub struct Ident {
815     sym: Symbol,
816     span: Span,
817     is_raw: bool,
818 }
819
820 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
821 impl !Send for Ident {}
822 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
823 impl !Sync for Ident {}
824
825 impl Ident {
826     fn is_valid(string: &str) -> bool {
827         let mut chars = string.chars();
828         if let Some(start) = chars.next() {
829             (start == '_' || start.is_xid_start())
830                 && chars.all(|cont| cont == '_' || cont.is_xid_continue())
831         } else {
832             false
833         }
834     }
835
836     /// Creates a new `Ident` with the given `string` as well as the specified
837     /// `span`.
838     /// The `string` argument must be a valid identifier permitted by the
839     /// language, otherwise the function will panic.
840     ///
841     /// Note that `span`, currently in rustc, configures the hygiene information
842     /// for this identifier.
843     ///
844     /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
845     /// meaning that identifiers created with this span will be resolved as if they were written
846     /// directly at the location of the macro call, and other code at the macro call site will be
847     /// able to refer to them as well.
848     ///
849     /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
850     /// meaning that identifiers created with this span will be resolved at the location of the
851     /// macro definition and other code at the macro call site will not be able to refer to them.
852     ///
853     /// Due to the current importance of hygiene this constructor, unlike other
854     /// tokens, requires a `Span` to be specified at construction.
855     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
856     pub fn new(string: &str, span: Span) -> Ident {
857         if !Ident::is_valid(string) {
858             panic!("`{:?}` is not a valid identifier", string)
859         }
860         Ident::new_maybe_raw(string, span, false)
861     }
862
863     /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
864     #[unstable(feature = "proc_macro_raw_ident", issue = "38356")]
865     pub fn new_raw(string: &str, span: Span) -> Ident {
866         if !Ident::is_valid(string) {
867             panic!("`{:?}` is not a valid identifier", string)
868         }
869         Ident::new_maybe_raw(string, span, true)
870     }
871
872     /// Returns the span of this `Ident`, encompassing the entire string returned
873     /// by `as_str`.
874     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
875     pub fn span(&self) -> Span {
876         self.span
877     }
878
879     /// Configures the span of this `Ident`, possibly changing its hygiene context.
880     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
881     pub fn set_span(&mut self, span: Span) {
882         self.span = span;
883     }
884 }
885
886 /// Prints the identifier as a string that should be losslessly convertible
887 /// back into the same identifier.
888 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
889 impl fmt::Display for Ident {
890     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
891         TokenStream::from(TokenTree::from(self.clone())).fmt(f)
892     }
893 }
894
895 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
896 impl fmt::Debug for Ident {
897     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
898         f.debug_struct("Ident")
899             .field("ident", &self.to_string())
900             .field("span", &self.span())
901             .finish()
902     }
903 }
904
905 /// A literal string (`"hello"`), byte string (`b"hello"`),
906 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
907 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
908 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
909 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
910 #[derive(Clone, Debug)]
911 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
912 pub struct Literal {
913     lit: token::Lit,
914     suffix: Option<Symbol>,
915     span: Span,
916 }
917
918 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
919 impl !Send for Literal {}
920 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
921 impl !Sync for Literal {}
922
923 macro_rules! suffixed_int_literals {
924     ($($name:ident => $kind:ident,)*) => ($(
925         /// Creates a new suffixed integer literal with the specified value.
926         ///
927         /// This function will create an integer like `1u32` where the integer
928         /// value specified is the first part of the token and the integral is
929         /// also suffixed at the end.
930         /// Literals created from negative numbers may not survive rountrips through
931         /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
932         ///
933         /// Literals created through this method have the `Span::call_site()`
934         /// span by default, which can be configured with the `set_span` method
935         /// below.
936         #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
937         pub fn $name(n: $kind) -> Literal {
938             Literal {
939                 lit: token::Lit::Integer(Symbol::intern(&n.to_string())),
940                 suffix: Some(Symbol::intern(stringify!($kind))),
941                 span: Span::call_site(),
942             }
943         }
944     )*)
945 }
946
947 macro_rules! unsuffixed_int_literals {
948     ($($name:ident => $kind:ident,)*) => ($(
949         /// Creates a new unsuffixed integer literal with the specified value.
950         ///
951         /// This function will create an integer like `1` where the integer
952         /// value specified is the first part of the token. No suffix is
953         /// specified on this token, meaning that invocations like
954         /// `Literal::i8_unsuffixed(1)` are equivalent to
955         /// `Literal::u32_unsuffixed(1)`.
956         /// Literals created from negative numbers may not survive rountrips through
957         /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
958         ///
959         /// Literals created through this method have the `Span::call_site()`
960         /// span by default, which can be configured with the `set_span` method
961         /// below.
962         #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
963         pub fn $name(n: $kind) -> Literal {
964             Literal {
965                 lit: token::Lit::Integer(Symbol::intern(&n.to_string())),
966                 suffix: None,
967                 span: Span::call_site(),
968             }
969         }
970     )*)
971 }
972
973 impl Literal {
974     suffixed_int_literals! {
975         u8_suffixed => u8,
976         u16_suffixed => u16,
977         u32_suffixed => u32,
978         u64_suffixed => u64,
979         u128_suffixed => u128,
980         usize_suffixed => usize,
981         i8_suffixed => i8,
982         i16_suffixed => i16,
983         i32_suffixed => i32,
984         i64_suffixed => i64,
985         i128_suffixed => i128,
986         isize_suffixed => isize,
987     }
988
989     unsuffixed_int_literals! {
990         u8_unsuffixed => u8,
991         u16_unsuffixed => u16,
992         u32_unsuffixed => u32,
993         u64_unsuffixed => u64,
994         u128_unsuffixed => u128,
995         usize_unsuffixed => usize,
996         i8_unsuffixed => i8,
997         i16_unsuffixed => i16,
998         i32_unsuffixed => i32,
999         i64_unsuffixed => i64,
1000         i128_unsuffixed => i128,
1001         isize_unsuffixed => isize,
1002     }
1003
1004     /// Creates a new unsuffixed floating-point literal.
1005     ///
1006     /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1007     /// the float's value is emitted directly into the token but no suffix is
1008     /// used, so it may be inferred to be a `f64` later in the compiler.
1009     /// Literals created from negative numbers may not survive rountrips through
1010     /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1011     ///
1012     /// # Panics
1013     ///
1014     /// This function requires that the specified float is finite, for
1015     /// example if it is infinity or NaN this function will panic.
1016     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1017     pub fn f32_unsuffixed(n: f32) -> Literal {
1018         if !n.is_finite() {
1019             panic!("Invalid float literal {}", n);
1020         }
1021         Literal {
1022             lit: token::Lit::Float(Symbol::intern(&n.to_string())),
1023             suffix: None,
1024             span: Span::call_site(),
1025         }
1026     }
1027
1028     /// Creates a new suffixed floating-point literal.
1029     ///
1030     /// This consturctor will create a literal like `1.0f32` where the value
1031     /// specified is the preceding part of the token and `f32` is the suffix of
1032     /// the token. This token will always be inferred to be an `f32` in the
1033     /// compiler.
1034     /// Literals created from negative numbers may not survive rountrips through
1035     /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1036     ///
1037     /// # Panics
1038     ///
1039     /// This function requires that the specified float is finite, for
1040     /// example if it is infinity or NaN this function will panic.
1041     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1042     pub fn f32_suffixed(n: f32) -> Literal {
1043         if !n.is_finite() {
1044             panic!("Invalid float literal {}", n);
1045         }
1046         Literal {
1047             lit: token::Lit::Float(Symbol::intern(&n.to_string())),
1048             suffix: Some(Symbol::intern("f32")),
1049             span: Span::call_site(),
1050         }
1051     }
1052
1053     /// Creates a new unsuffixed floating-point literal.
1054     ///
1055     /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1056     /// the float's value is emitted directly into the token but no suffix is
1057     /// used, so it may be inferred to be a `f64` later in the compiler.
1058     /// Literals created from negative numbers may not survive rountrips through
1059     /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1060     ///
1061     /// # Panics
1062     ///
1063     /// This function requires that the specified float is finite, for
1064     /// example if it is infinity or NaN this function will panic.
1065     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1066     pub fn f64_unsuffixed(n: f64) -> Literal {
1067         if !n.is_finite() {
1068             panic!("Invalid float literal {}", n);
1069         }
1070         Literal {
1071             lit: token::Lit::Float(Symbol::intern(&n.to_string())),
1072             suffix: None,
1073             span: Span::call_site(),
1074         }
1075     }
1076
1077     /// Creates a new suffixed floating-point literal.
1078     ///
1079     /// This consturctor will create a literal like `1.0f64` where the value
1080     /// specified is the preceding part of the token and `f64` is the suffix of
1081     /// the token. This token will always be inferred to be an `f64` in the
1082     /// compiler.
1083     /// Literals created from negative numbers may not survive rountrips through
1084     /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1085     ///
1086     /// # Panics
1087     ///
1088     /// This function requires that the specified float is finite, for
1089     /// example if it is infinity or NaN this function will panic.
1090     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1091     pub fn f64_suffixed(n: f64) -> Literal {
1092         if !n.is_finite() {
1093             panic!("Invalid float literal {}", n);
1094         }
1095         Literal {
1096             lit: token::Lit::Float(Symbol::intern(&n.to_string())),
1097             suffix: Some(Symbol::intern("f64")),
1098             span: Span::call_site(),
1099         }
1100     }
1101
1102     /// String literal.
1103     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1104     pub fn string(string: &str) -> Literal {
1105         let mut escaped = String::new();
1106         for ch in string.chars() {
1107             escaped.extend(ch.escape_debug());
1108         }
1109         Literal {
1110             lit: token::Lit::Str_(Symbol::intern(&escaped)),
1111             suffix: None,
1112             span: Span::call_site(),
1113         }
1114     }
1115
1116     /// Character literal.
1117     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1118     pub fn character(ch: char) -> Literal {
1119         let mut escaped = String::new();
1120         escaped.extend(ch.escape_unicode());
1121         Literal {
1122             lit: token::Lit::Char(Symbol::intern(&escaped)),
1123             suffix: None,
1124             span: Span::call_site(),
1125         }
1126     }
1127
1128     /// Byte string literal.
1129     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1130     pub fn byte_string(bytes: &[u8]) -> Literal {
1131         let string = bytes.iter().cloned().flat_map(ascii::escape_default)
1132             .map(Into::<char>::into).collect::<String>();
1133         Literal {
1134             lit: token::Lit::ByteStr(Symbol::intern(&string)),
1135             suffix: None,
1136             span: Span::call_site(),
1137         }
1138     }
1139
1140     /// Returns the span encompassing this literal.
1141     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1142     pub fn span(&self) -> Span {
1143         self.span
1144     }
1145
1146     /// Configures the span associated for this literal.
1147     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1148     pub fn set_span(&mut self, span: Span) {
1149         self.span = span;
1150     }
1151 }
1152
1153 /// Prints the literal as a string that should be losslessly convertible
1154 /// back into the same literal (except for possible rounding for floating point literals).
1155 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1156 impl fmt::Display for Literal {
1157     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1158         TokenStream::from(TokenTree::from(self.clone())).fmt(f)
1159     }
1160 }
1161
1162 /// Permanently unstable internal implementation details of this crate. This
1163 /// should not be used.
1164 ///
1165 /// These methods are used by the rest of the compiler to generate instances of
1166 /// `TokenStream` to hand to macro definitions, as well as consume the output.
1167 ///
1168 /// Note that this module is also intentionally separate from the rest of the
1169 /// crate. This allows the `#[unstable]` directive below to naturally apply to
1170 /// all of the contents.
1171 #[unstable(feature = "proc_macro_internals", issue = "27812")]
1172 #[doc(hidden)]
1173 pub mod __internal {
1174     use std::cell::Cell;
1175     use std::ptr;
1176
1177     use syntax::ast;
1178     use syntax::ext::base::ExtCtxt;
1179     use syntax::ptr::P;
1180     use syntax::parse::{self, ParseSess};
1181     use syntax::parse::token::{self, Token};
1182     use syntax::tokenstream;
1183     use syntax_pos::{BytePos, Loc, DUMMY_SP};
1184     use syntax_pos::hygiene::{SyntaxContext, Transparency};
1185
1186     use super::{TokenStream, LexError, Span};
1187
1188     pub fn lookup_char_pos(pos: BytePos) -> Loc {
1189         with_sess(|sess, _| sess.codemap().lookup_char_pos(pos))
1190     }
1191
1192     pub fn new_token_stream(item: P<ast::Item>) -> TokenStream {
1193         let token = Token::interpolated(token::NtItem(item));
1194         TokenStream(tokenstream::TokenTree::Token(DUMMY_SP, token).into())
1195     }
1196
1197     pub fn token_stream_wrap(inner: tokenstream::TokenStream) -> TokenStream {
1198         TokenStream(inner)
1199     }
1200
1201     pub fn token_stream_parse_items(stream: TokenStream) -> Result<Vec<P<ast::Item>>, LexError> {
1202         with_sess(move |sess, _| {
1203             let mut parser = parse::stream_to_parser(sess, stream.0);
1204             let mut items = Vec::new();
1205
1206             while let Some(item) = try!(parser.parse_item().map_err(super::parse_to_lex_err)) {
1207                 items.push(item)
1208             }
1209
1210             Ok(items)
1211         })
1212     }
1213
1214     pub fn token_stream_inner(stream: TokenStream) -> tokenstream::TokenStream {
1215         stream.0
1216     }
1217
1218     pub trait Registry {
1219         fn register_custom_derive(&mut self,
1220                                   trait_name: &str,
1221                                   expand: fn(TokenStream) -> TokenStream,
1222                                   attributes: &[&'static str]);
1223
1224         fn register_attr_proc_macro(&mut self,
1225                                     name: &str,
1226                                     expand: fn(TokenStream, TokenStream) -> TokenStream);
1227
1228         fn register_bang_proc_macro(&mut self,
1229                                     name: &str,
1230                                     expand: fn(TokenStream) -> TokenStream);
1231     }
1232
1233     #[derive(Clone, Copy)]
1234     pub struct ProcMacroData {
1235         pub def_site: Span,
1236         pub call_site: Span,
1237     }
1238
1239     #[derive(Clone, Copy)]
1240     struct ProcMacroSess {
1241         parse_sess: *const ParseSess,
1242         data: ProcMacroData,
1243     }
1244
1245     // Emulate scoped_thread_local!() here essentially
1246     thread_local! {
1247         static CURRENT_SESS: Cell<ProcMacroSess> = Cell::new(ProcMacroSess {
1248             parse_sess: ptr::null(),
1249             data: ProcMacroData { def_site: Span(DUMMY_SP), call_site: Span(DUMMY_SP) },
1250         });
1251     }
1252
1253     pub fn set_sess<F, R>(cx: &ExtCtxt, f: F) -> R
1254         where F: FnOnce() -> R
1255     {
1256         struct Reset { prev: ProcMacroSess }
1257
1258         impl Drop for Reset {
1259             fn drop(&mut self) {
1260                 CURRENT_SESS.with(|p| p.set(self.prev));
1261             }
1262         }
1263
1264         CURRENT_SESS.with(|p| {
1265             let _reset = Reset { prev: p.get() };
1266
1267             // No way to determine def location for a proc macro right now, so use call location.
1268             let location = cx.current_expansion.mark.expn_info().unwrap().call_site;
1269             let to_span = |transparency| Span(location.with_ctxt(
1270                 SyntaxContext::empty().apply_mark_with_transparency(cx.current_expansion.mark,
1271                                                                     transparency))
1272             );
1273             p.set(ProcMacroSess {
1274                 parse_sess: cx.parse_sess,
1275                 data: ProcMacroData {
1276                     def_site: to_span(Transparency::Opaque),
1277                     call_site: to_span(Transparency::Transparent),
1278                 },
1279             });
1280             f()
1281         })
1282     }
1283
1284     pub fn in_sess() -> bool
1285     {
1286         !CURRENT_SESS.with(|sess| sess.get()).parse_sess.is_null()
1287     }
1288
1289     pub fn with_sess<F, R>(f: F) -> R
1290         where F: FnOnce(&ParseSess, &ProcMacroData) -> R
1291     {
1292         let sess = CURRENT_SESS.with(|sess| sess.get());
1293         if sess.parse_sess.is_null() {
1294             panic!("procedural macro API is used outside of a procedural macro");
1295         }
1296         f(unsafe { &*sess.parse_sess }, &sess.data)
1297     }
1298 }
1299
1300 fn parse_to_lex_err(mut err: DiagnosticBuilder) -> LexError {
1301     err.cancel();
1302     LexError { _inner: () }
1303 }