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.
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.
11 //! A support library for macro authors when defining new macros.
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]`.
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.
22 //! See [the book](../book/first-edition/procedural-macros.html) for more.
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))))]
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)]
41 #![recursion_limit="256"]
44 extern crate syntax_pos;
45 extern crate rustc_errors;
46 extern crate rustc_data_structures;
48 #[unstable(feature = "proc_macro_internals", issue = "27812")]
54 #[unstable(feature = "proc_macro_diagnostic", issue = "38356")]
55 pub use diagnostic::{Diagnostic, Level};
57 use std::{ascii, fmt, iter};
58 use std::path::PathBuf;
59 use rustc_data_structures::sync::Lrc;
60 use std::str::FromStr;
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};
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.
73 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
74 /// and `#[proc_macro_derive]` definitions.
76 /// The API of this type is intentionally bare-bones, but it'll be expanded over
78 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
80 pub struct TokenStream(tokenstream::TokenStream);
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 {}
87 /// Error returned from `TokenStream::from_str`.
88 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
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 {}
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())
106 /// Checks if this `TokenStream` is empty.
107 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
108 pub fn is_empty(&self) -> bool {
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.
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 {
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)
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 {
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()
152 #[unstable(feature = "proc_macro_quote", issue = "38356")]
153 pub use quote::{quote, quote_span};
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())
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()
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);
180 TokenStream(builder.build())
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));
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));
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};
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.
208 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
209 pub struct IntoIter {
210 cursor: tokenstream::Cursor,
211 stack: Vec<TokenTree>,
214 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
215 impl Iterator for IntoIter {
216 type Item = TokenTree;
218 fn next(&mut self) -> Option<TokenTree> {
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))
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);
243 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
244 impl IntoIterator for TokenStream {
245 type Item = TokenTree;
246 type IntoIter = IntoIter;
248 fn into_iter(self) -> IntoIter {
249 IntoIter { cursor: self.0.trees(), stack: Vec::new() }
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")]`.
258 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
259 /// To quote `$` itself, use `$$`.
261 /// This is a dummy macro, the actual implementation is in `quote::quote`.`
262 #[unstable(feature = "proc_macro_quote", issue = "38356")]
264 macro_rules! quote { () => {} }
266 #[unstable(feature = "proc_macro_internals", issue = "27812")]
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);
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 {}
280 macro_rules! diagnostic_method {
281 ($name:ident, $level:expr) => (
282 /// Create a new `Diagnostic` with the given `message` at the span
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)
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)
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)
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 {
311 filemap: __internal::lookup_char_pos(self.0.lo()).file,
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)
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())
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());
336 column: loc.col.to_usize()
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());
346 column: loc.col.to_usize()
350 /// Create a new span encompassing `self` and `other`.
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());
358 if self_loc.file.name != other_loc.file.name { return None }
360 Some(Span(self.0.to(other.0)))
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()))
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)
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 {
383 diagnostic_method!(error, Level::Error);
384 diagnostic_method!(warning, Level::Warning);
385 diagnostic_method!(note, Level::Note);
386 diagnostic_method!(help, Level::Help);
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({}..{})",
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")]
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")]
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 {}
418 /// The source file of a given `Span`.
419 #[unstable(feature = "proc_macro_span", issue = "38356")]
421 pub struct SourceFile {
422 filemap: Lrc<FileMap>,
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 {}
431 /// Get the path to this source file.
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.
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.
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())
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()
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())
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)
478 #[unstable(feature = "proc_macro_span", issue = "38356")]
479 impl Eq for SourceFile {}
481 /// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
482 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
485 /// A token stream surrounded by bracket delimiters.
486 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
488 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
492 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
494 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
497 /// A single punctuation character (`+`, `,`, `$`, etc.).
498 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
500 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
503 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
504 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
506 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
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 {}
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 {
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(),
529 /// Configures the span for *only this token*.
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) {
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),
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
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),
560 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
561 impl From<Group> for TokenTree {
562 fn from(g: Group) -> TokenTree {
567 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
568 impl From<Ident> for TokenTree {
569 fn from(g: Ident) -> TokenTree {
574 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
575 impl From<Punct> for TokenTree {
576 fn from(g: Punct) -> TokenTree {
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)
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 {
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),
603 /// A delimited token stream.
605 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
607 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
609 delimiter: Delimiter,
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 {}
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")]
624 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
627 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
630 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
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")]
642 /// Creates a new `Group` with the given delimiter and token stream.
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`
647 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
648 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
650 delimiter: delimiter,
652 span: Span::call_site(),
656 /// Returns the delimiter of this `Group`
657 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
658 pub fn delimiter(&self) -> Delimiter {
662 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
664 /// Note that the returned token stream does not include the delimiter
666 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
667 pub fn stream(&self) -> TokenStream {
671 /// Returns the span for the delimiters of this token stream, spanning the
673 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
674 pub fn span(&self) -> Span {
678 /// Configures the span for this `Group`'s delimiters, but not its internal
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) {
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)
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())
711 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
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")]
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 {}
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")]
733 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
734 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
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")]
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.
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)
759 span: Span::call_site(),
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 {
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 {
778 /// Returns the span for this punctuation character.
779 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
780 pub fn span(&self) -> Span {
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) {
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)
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())
811 /// An identifier (`ident`).
813 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
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 {}
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())
836 /// Creates a new `Ident` with the given `string` as well as the specified
838 /// The `string` argument must be a valid identifier permitted by the
839 /// language, otherwise the function will panic.
841 /// Note that `span`, currently in rustc, configures the hygiene information
842 /// for this identifier.
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.
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.
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)
860 Ident::new_maybe_raw(string, span, false)
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)
869 Ident::new_maybe_raw(string, span, true)
872 /// Returns the span of this `Ident`, encompassing the entire string returned
874 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
875 pub fn span(&self) -> Span {
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) {
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)
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())
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")]
914 suffix: Option<Symbol>,
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 {}
923 macro_rules! suffixed_int_literals {
924 ($($name:ident => $kind:ident,)*) => ($(
925 /// Creates a new suffixed integer literal with the specified value.
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).
933 /// Literals created through this method have the `Span::call_site()`
934 /// span by default, which can be configured with the `set_span` method
936 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
937 pub fn $name(n: $kind) -> Literal {
939 lit: token::Lit::Integer(Symbol::intern(&n.to_string())),
940 suffix: Some(Symbol::intern(stringify!($kind))),
941 span: Span::call_site(),
947 macro_rules! unsuffixed_int_literals {
948 ($($name:ident => $kind:ident,)*) => ($(
949 /// Creates a new unsuffixed integer literal with the specified value.
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).
959 /// Literals created through this method have the `Span::call_site()`
960 /// span by default, which can be configured with the `set_span` method
962 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
963 pub fn $name(n: $kind) -> Literal {
965 lit: token::Lit::Integer(Symbol::intern(&n.to_string())),
967 span: Span::call_site(),
974 suffixed_int_literals! {
979 u128_suffixed => u128,
980 usize_suffixed => usize,
985 i128_suffixed => i128,
986 isize_suffixed => isize,
989 unsuffixed_int_literals! {
991 u16_unsuffixed => u16,
992 u32_unsuffixed => u32,
993 u64_unsuffixed => u64,
994 u128_unsuffixed => u128,
995 usize_unsuffixed => usize,
997 i16_unsuffixed => i16,
998 i32_unsuffixed => i32,
999 i64_unsuffixed => i64,
1000 i128_unsuffixed => i128,
1001 isize_unsuffixed => isize,
1004 /// Creates a new unsuffixed floating-point literal.
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).
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 {
1019 panic!("Invalid float literal {}", n);
1022 lit: token::Lit::Float(Symbol::intern(&n.to_string())),
1024 span: Span::call_site(),
1028 /// Creates a new suffixed floating-point literal.
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
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).
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 {
1044 panic!("Invalid float literal {}", n);
1047 lit: token::Lit::Float(Symbol::intern(&n.to_string())),
1048 suffix: Some(Symbol::intern("f32")),
1049 span: Span::call_site(),
1053 /// Creates a new unsuffixed floating-point literal.
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).
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 {
1068 panic!("Invalid float literal {}", n);
1071 lit: token::Lit::Float(Symbol::intern(&n.to_string())),
1073 span: Span::call_site(),
1077 /// Creates a new suffixed floating-point literal.
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
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).
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 {
1093 panic!("Invalid float literal {}", n);
1096 lit: token::Lit::Float(Symbol::intern(&n.to_string())),
1097 suffix: Some(Symbol::intern("f64")),
1098 span: Span::call_site(),
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());
1110 lit: token::Lit::Str_(Symbol::intern(&escaped)),
1112 span: Span::call_site(),
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());
1122 lit: token::Lit::Char(Symbol::intern(&escaped)),
1124 span: Span::call_site(),
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>();
1134 lit: token::Lit::ByteStr(Symbol::intern(&string)),
1136 span: Span::call_site(),
1140 /// Returns the span encompassing this literal.
1141 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1142 pub fn span(&self) -> Span {
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) {
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)
1162 /// Permanently unstable internal implementation details of this crate. This
1163 /// should not be used.
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.
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")]
1173 pub mod __internal {
1174 use std::cell::Cell;
1178 use syntax::ext::base::ExtCtxt;
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};
1186 use super::{TokenStream, LexError, Span};
1188 pub fn lookup_char_pos(pos: BytePos) -> Loc {
1189 with_sess(|sess, _| sess.codemap().lookup_char_pos(pos))
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())
1197 pub fn token_stream_wrap(inner: tokenstream::TokenStream) -> TokenStream {
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();
1206 while let Some(item) = try!(parser.parse_item().map_err(super::parse_to_lex_err)) {
1214 pub fn token_stream_inner(stream: TokenStream) -> tokenstream::TokenStream {
1218 pub trait Registry {
1219 fn register_custom_derive(&mut self,
1221 expand: fn(TokenStream) -> TokenStream,
1222 attributes: &[&'static str]);
1224 fn register_attr_proc_macro(&mut self,
1226 expand: fn(TokenStream, TokenStream) -> TokenStream);
1228 fn register_bang_proc_macro(&mut self,
1230 expand: fn(TokenStream) -> TokenStream);
1233 #[derive(Clone, Copy)]
1234 pub struct ProcMacroData {
1236 pub call_site: Span,
1239 #[derive(Clone, Copy)]
1240 struct ProcMacroSess {
1241 parse_sess: *const ParseSess,
1242 data: ProcMacroData,
1245 // Emulate scoped_thread_local!() here essentially
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) },
1253 pub fn set_sess<F, R>(cx: &ExtCtxt, f: F) -> R
1254 where F: FnOnce() -> R
1256 struct Reset { prev: ProcMacroSess }
1258 impl Drop for Reset {
1259 fn drop(&mut self) {
1260 CURRENT_SESS.with(|p| p.set(self.prev));
1264 CURRENT_SESS.with(|p| {
1265 let _reset = Reset { prev: p.get() };
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,
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),
1284 pub fn in_sess() -> bool
1286 !CURRENT_SESS.with(|sess| sess.get()).parse_sess.is_null()
1289 pub fn with_sess<F, R>(f: F) -> R
1290 where F: FnOnce(&ParseSess, &ProcMacroData) -> R
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");
1296 f(unsafe { &*sess.parse_sess }, &sess.data)
1300 fn parse_to_lex_err(mut err: DiagnosticBuilder) -> LexError {
1302 LexError { _inner: () }