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 attributes `#[proc_macro_attribute]` and
16 //! custom derive attributes`#[proc_macro_derive]`.
18 //! See [the book](../book/first-edition/procedural-macros.html) for more.
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))))]
31 #![feature(rustc_private)]
32 #![feature(staged_api)]
33 #![feature(lang_items)]
34 #![feature(optin_builtin_traits)]
35 #![feature(non_exhaustive)]
37 #![recursion_limit="256"]
40 extern crate syntax_pos;
41 extern crate rustc_errors;
42 extern crate rustc_data_structures;
44 #[unstable(feature = "proc_macro_internals", issue = "27812")]
50 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
51 pub use diagnostic::{Diagnostic, Level, MultiSpan};
53 use std::{ascii, fmt, iter};
54 use std::path::PathBuf;
55 use rustc_data_structures::sync::Lrc;
56 use std::str::FromStr;
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};
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.
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")]
73 pub struct TokenStream(tokenstream::TokenStream);
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 {}
80 /// Error returned from `TokenStream::from_str`.
81 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
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 {}
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())
99 /// Checks if this `TokenStream` is empty.
100 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
101 pub fn is_empty(&self) -> bool {
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.
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 {
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)
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 {
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()
145 #[unstable(feature = "proc_macro_quote", issue = "54722")]
146 pub use quote::{quote, quote_span};
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())
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()
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);
173 TokenStream(builder.build())
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));
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));
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};
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.
201 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
202 pub struct IntoIter {
203 cursor: tokenstream::Cursor,
204 stack: Vec<TokenTree>,
207 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
208 impl Iterator for IntoIter {
209 type Item = TokenTree;
211 fn next(&mut self) -> Option<TokenTree> {
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))
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);
236 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
237 impl IntoIterator for TokenStream {
238 type Item = TokenTree;
239 type IntoIter = IntoIter;
241 fn into_iter(self) -> IntoIter {
242 IntoIter { cursor: self.0.trees(), stack: Vec::new() }
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")]`.
251 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
252 /// To quote `$` itself, use `$$`.
254 /// This is a dummy macro, the actual implementation is in `quote::quote`.`
255 #[unstable(feature = "proc_macro_quote", issue = "54722")]
257 macro_rules! quote { () => {} }
259 #[unstable(feature = "proc_macro_internals", issue = "27812")]
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);
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 {}
273 macro_rules! diagnostic_method {
274 ($name:ident, $level:expr) => (
275 /// Create a new `Diagnostic` with the given `message` at the span
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)
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)
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)
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 {
304 source_file: __internal::lookup_char_pos(self.0.lo()).file,
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)
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())
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());
329 column: loc.col.to_usize()
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());
339 column: loc.col.to_usize()
343 /// Create a new span encompassing `self` and `other`.
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());
351 if self_loc.file.name != other_loc.file.name { return None }
353 Some(Span(self.0.to(other.0)))
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()))
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)
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 {
376 diagnostic_method!(error, Level::Error);
377 diagnostic_method!(warning, Level::Warning);
378 diagnostic_method!(note, Level::Note);
379 diagnostic_method!(help, Level::Help);
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({}..{})",
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")]
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")]
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 {}
411 /// The source file of a given `Span`.
412 #[unstable(feature = "proc_macro_span", issue = "54725")]
414 pub struct SourceFile {
415 source_file: Lrc<syntax_pos::SourceFile>,
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 {}
424 /// Get the path to this source file.
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.
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.
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())
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()
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())
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)
471 #[unstable(feature = "proc_macro_span", issue = "54725")]
472 impl Eq for SourceFile {}
474 /// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
475 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
478 /// A token stream surrounded by bracket delimiters.
479 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
481 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
485 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
487 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
490 /// A single punctuation character (`+`, `,`, `$`, etc.).
491 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
493 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
496 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
497 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
499 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
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 {}
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 {
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(),
522 /// Configures the span for *only this token*.
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) {
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),
538 /// Prints token treee 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
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),
553 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
554 impl From<Group> for TokenTree {
555 fn from(g: Group) -> TokenTree {
560 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
561 impl From<Ident> for TokenTree {
562 fn from(g: Ident) -> TokenTree {
567 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
568 impl From<Punct> for TokenTree {
569 fn from(g: Punct) -> TokenTree {
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)
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 {
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),
596 /// A delimited token stream.
598 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
600 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
602 delimiter: Delimiter,
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 {}
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")]
617 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
620 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
623 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
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")]
635 /// Creates a new `Group` with the given delimiter and token stream.
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`
640 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
641 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
643 delimiter: delimiter,
645 span: DelimSpan::from_single(Span::call_site().0),
649 /// Returns the delimiter of this `Group`
650 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
651 pub fn delimiter(&self) -> Delimiter {
655 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
657 /// Note that the returned token stream does not include the delimiter
659 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
660 pub fn stream(&self) -> TokenStream {
664 /// Returns the span for the delimiters of this token stream, spanning the
668 /// pub fn span(&self) -> Span {
671 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
672 pub fn span(&self) -> Span {
673 Span(self.span.entire())
676 /// Returns the span pointing to the opening delimiter of this group.
679 /// pub fn span_open(&self) -> Span {
682 #[unstable(feature = "proc_macro_span", issue = "54725")]
683 pub fn span_open(&self) -> Span {
687 /// Returns the span pointing to the closing delimiter of this group.
690 /// pub fn span_close(&self) -> Span {
693 #[unstable(feature = "proc_macro_span", issue = "54725")]
694 pub fn span_close(&self) -> Span {
695 Span(self.span.close)
698 /// Configures the span for this `Group`'s delimiters, but not its internal
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);
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)
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())
731 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
733 /// Multicharacter 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")]
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 {}
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")]
753 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
754 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
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")]
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.
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)
779 span: Span::call_site(),
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 {
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 multicharacter 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 {
798 /// Returns the span for this punctuation character.
799 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
800 pub fn span(&self) -> Span {
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) {
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)
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())
831 /// An identifier (`ident`).
833 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
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 {}
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())
856 /// Creates a new `Ident` with the given `string` as well as the specified
858 /// The `string` argument must be a valid identifier permitted by the
859 /// language, otherwise the function will panic.
861 /// Note that `span`, currently in rustc, configures the hygiene information
862 /// for this identifier.
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.
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.
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)
880 Ident::new_maybe_raw(string, span, false)
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)
889 Ident::new_maybe_raw(string, span, true)
892 /// Returns the span of this `Ident`, encompassing the entire string returned
894 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
895 pub fn span(&self) -> Span {
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) {
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)
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())
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")]
934 suffix: Option<Symbol>,
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 {}
943 macro_rules! suffixed_int_literals {
944 ($($name:ident => $kind:ident,)*) => ($(
945 /// Creates a new suffixed integer literal with the specified value.
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 rountrips through
951 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
953 /// Literals created through this method have the `Span::call_site()`
954 /// span by default, which can be configured with the `set_span` method
956 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
957 pub fn $name(n: $kind) -> Literal {
959 lit: token::Lit::Integer(Symbol::intern(&n.to_string())),
960 suffix: Some(Symbol::intern(stringify!($kind))),
961 span: Span::call_site(),
967 macro_rules! unsuffixed_int_literals {
968 ($($name:ident => $kind:ident,)*) => ($(
969 /// Creates a new unsuffixed integer literal with the specified value.
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).
979 /// Literals created through this method have the `Span::call_site()`
980 /// span by default, which can be configured with the `set_span` method
982 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
983 pub fn $name(n: $kind) -> Literal {
985 lit: token::Lit::Integer(Symbol::intern(&n.to_string())),
987 span: Span::call_site(),
994 suffixed_int_literals! {
999 u128_suffixed => u128,
1000 usize_suffixed => usize,
1002 i16_suffixed => i16,
1003 i32_suffixed => i32,
1004 i64_suffixed => i64,
1005 i128_suffixed => i128,
1006 isize_suffixed => isize,
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,
1024 /// Creates a new unsuffixed floating-point literal.
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).
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 {
1039 panic!("Invalid float literal {}", n);
1042 lit: token::Lit::Float(Symbol::intern(&n.to_string())),
1044 span: Span::call_site(),
1048 /// Creates a new suffixed floating-point literal.
1050 /// This consturctor 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
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).
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 {
1064 panic!("Invalid float literal {}", n);
1067 lit: token::Lit::Float(Symbol::intern(&n.to_string())),
1068 suffix: Some(Symbol::intern("f32")),
1069 span: Span::call_site(),
1073 /// Creates a new unsuffixed floating-point literal.
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).
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 {
1088 panic!("Invalid float literal {}", n);
1091 lit: token::Lit::Float(Symbol::intern(&n.to_string())),
1093 span: Span::call_site(),
1097 /// Creates a new suffixed floating-point literal.
1099 /// This consturctor 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
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).
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 {
1113 panic!("Invalid float literal {}", n);
1116 lit: token::Lit::Float(Symbol::intern(&n.to_string())),
1117 suffix: Some(Symbol::intern("f64")),
1118 span: Span::call_site(),
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());
1130 lit: token::Lit::Str_(Symbol::intern(&escaped)),
1132 span: Span::call_site(),
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());
1142 lit: token::Lit::Char(Symbol::intern(&escaped)),
1144 span: Span::call_site(),
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>();
1154 lit: token::Lit::ByteStr(Symbol::intern(&string)),
1156 span: Span::call_site(),
1160 /// Returns the span encompassing this literal.
1161 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1162 pub fn span(&self) -> Span {
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) {
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)
1182 /// Permanently unstable internal implementation details of this crate. This
1183 /// should not be used.
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.
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")]
1193 pub mod __internal {
1194 use std::cell::Cell;
1198 use syntax::ext::base::ExtCtxt;
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};
1206 use super::{TokenStream, LexError, Span};
1208 pub fn lookup_char_pos(pos: BytePos) -> Loc {
1209 with_sess(|sess, _| sess.source_map().lookup_char_pos(pos))
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())
1217 pub fn token_stream_wrap(inner: tokenstream::TokenStream) -> TokenStream {
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();
1226 while let Some(item) = try!(parser.parse_item().map_err(super::parse_to_lex_err)) {
1234 pub fn token_stream_inner(stream: TokenStream) -> tokenstream::TokenStream {
1238 pub trait Registry {
1239 fn register_custom_derive(&mut self,
1241 expand: fn(TokenStream) -> TokenStream,
1242 attributes: &[&'static str]);
1244 fn register_attr_proc_macro(&mut self,
1246 expand: fn(TokenStream, TokenStream) -> TokenStream);
1248 fn register_bang_proc_macro(&mut self,
1250 expand: fn(TokenStream) -> TokenStream);
1253 #[derive(Clone, Copy)]
1254 pub struct ProcMacroData {
1256 pub call_site: Span,
1259 #[derive(Clone, Copy)]
1260 struct ProcMacroSess {
1261 parse_sess: *const ParseSess,
1262 data: ProcMacroData,
1265 // Emulate scoped_thread_local!() here essentially
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) },
1273 pub fn set_sess<F, R>(cx: &ExtCtxt, f: F) -> R
1274 where F: FnOnce() -> R
1276 struct Reset { prev: ProcMacroSess }
1278 impl Drop for Reset {
1279 fn drop(&mut self) {
1280 CURRENT_SESS.with(|p| p.set(self.prev));
1284 CURRENT_SESS.with(|p| {
1285 let _reset = Reset { prev: p.get() };
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,
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),
1304 pub fn in_sess() -> bool
1306 !CURRENT_SESS.with(|sess| sess.get()).parse_sess.is_null()
1309 pub fn with_sess<F, R>(f: F) -> R
1310 where F: FnOnce(&ParseSess, &ProcMacroData) -> R
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");
1316 f(unsafe { &*sess.parse_sess }, &sess.data)
1320 fn parse_to_lex_err(mut err: DiagnosticBuilder) -> LexError {
1322 LexError { _inner: () }