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