1 //! A support library for macro authors when defining new macros.
3 //! This library, provided by the standard distribution, provides the types
4 //! consumed in the interfaces of procedurally defined macro definitions such as
5 //! function-like macros `#[proc_macro]`, macro attributes `#[proc_macro_attribute]` and
6 //! custom derive attributes`#[proc_macro_derive]`.
8 //! See [the book] for more.
10 //! [the book]: ../book/ch19-06-macros.html#procedural-macros-for-generating-code-from-attributes
12 #![stable(feature = "proc_macro_lib", since = "1.15.0")]
13 #![deny(missing_docs)]
14 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
15 html_playground_url = "https://play.rust-lang.org/",
16 issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
17 test(no_crate_inject, attr(deny(warnings))),
18 test(attr(allow(dead_code, deprecated, unused_variables, unused_mut))))]
21 #![feature(staged_api)]
22 #![feature(allow_internal_unstable)]
24 #![feature(decl_macro)]
25 #![feature(extern_types)]
26 #![feature(in_band_lifetimes)]
27 #![feature(optin_builtin_traits)]
28 #![feature(rustc_attrs)]
29 #![feature(specialization)]
31 #![recursion_limit="256"]
33 #[unstable(feature = "proc_macro_internals", issue = "27812")]
39 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
40 pub use diagnostic::{Diagnostic, Level, MultiSpan};
42 use std::{fmt, iter, mem};
43 use std::ops::{Bound, RangeBounds};
44 use std::path::PathBuf;
45 use std::str::FromStr;
47 /// The main type provided by this crate, representing an abstract stream of
48 /// tokens, or, more specifically, a sequence of token trees.
49 /// The type provide interfaces for iterating over those token trees and, conversely,
50 /// collecting a number of token trees into one stream.
52 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
53 /// and `#[proc_macro_derive]` definitions.
54 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
56 pub struct TokenStream(bridge::client::TokenStream);
58 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
59 impl !Send for TokenStream {}
60 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
61 impl !Sync for TokenStream {}
63 /// Error returned from `TokenStream::from_str`.
64 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
70 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
71 impl !Send for LexError {}
72 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
73 impl !Sync for LexError {}
76 /// Returns an empty `TokenStream` containing no token trees.
77 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
78 pub fn new() -> TokenStream {
79 TokenStream(bridge::client::TokenStream::new())
82 /// Checks if this `TokenStream` is empty.
83 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
84 pub fn is_empty(&self) -> bool {
89 /// Attempts to break the string into tokens and parse those tokens into a token stream.
90 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
91 /// or characters not existing in the language.
92 /// All tokens in the parsed stream get `Span::call_site()` spans.
94 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
95 /// change these errors into `LexError`s later.
96 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
97 impl FromStr for TokenStream {
100 fn from_str(src: &str) -> Result<TokenStream, LexError> {
101 Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
105 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
106 // based on it (the reverse of the usual relationship between the two).
107 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
108 impl ToString for TokenStream {
109 fn to_string(&self) -> String {
114 /// Prints the token stream as a string that is supposed to be losslessly convertible back
115 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
116 /// with `Delimiter::None` delimiters and negative numeric literals.
117 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
118 impl fmt::Display for TokenStream {
119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120 f.write_str(&self.to_string())
124 /// Prints token in a form convenient for debugging.
125 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
126 impl fmt::Debug for TokenStream {
127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128 f.write_str("TokenStream ")?;
129 f.debug_list().entries(self.clone()).finish()
133 #[unstable(feature = "proc_macro_quote", issue = "54722")]
134 pub use quote::{quote, quote_span};
136 /// Creates a token stream containing a single token tree.
137 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
138 impl From<TokenTree> for TokenStream {
139 fn from(tree: TokenTree) -> TokenStream {
140 TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
141 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
142 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
143 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
144 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0)
149 /// Collects a number of token trees into a single stream.
150 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
151 impl iter::FromIterator<TokenTree> for TokenStream {
152 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
153 trees.into_iter().map(TokenStream::from).collect()
157 /// A "flattening" operation on token streams, collects token trees
158 /// from multiple token streams into a single stream.
159 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
160 impl iter::FromIterator<TokenStream> for TokenStream {
161 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
162 let mut builder = bridge::client::TokenStreamBuilder::new();
163 streams.into_iter().for_each(|stream| builder.push(stream.0));
164 TokenStream(builder.build())
168 #[stable(feature = "token_stream_extend", since = "1.30.0")]
169 impl Extend<TokenTree> for TokenStream {
170 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
171 self.extend(trees.into_iter().map(TokenStream::from));
175 #[stable(feature = "token_stream_extend", since = "1.30.0")]
176 impl Extend<TokenStream> for TokenStream {
177 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
178 // FIXME(eddyb) Use an optimized implementation if/when possible.
179 *self = iter::once(mem::replace(self, Self::new())).chain(streams).collect();
183 /// Public implementation details for the `TokenStream` type, such as iterators.
184 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
185 pub mod token_stream {
186 use crate::{bridge, Group, Ident, Literal, Punct, TokenTree, TokenStream};
188 /// An iterator over `TokenStream`'s `TokenTree`s.
189 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
190 /// and returns whole groups as token trees.
192 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
193 pub struct IntoIter(bridge::client::TokenStreamIter);
195 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
196 impl Iterator for IntoIter {
197 type Item = TokenTree;
199 fn next(&mut self) -> Option<TokenTree> {
200 self.0.next().map(|tree| match tree {
201 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
202 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
203 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
204 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
209 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
210 impl IntoIterator for TokenStream {
211 type Item = TokenTree;
212 type IntoIter = IntoIter;
214 fn into_iter(self) -> IntoIter {
215 IntoIter(self.0.into_iter())
220 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
221 /// For example, `quote!(a + b)` will produce a expression, that, when evaluated, constructs
222 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
224 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
225 /// To quote `$` itself, use `$$`.
226 #[unstable(feature = "proc_macro_quote", issue = "54722")]
227 #[allow_internal_unstable(proc_macro_def_site)]
228 #[rustc_builtin_macro]
229 pub macro quote ($($t:tt)*) { /* compiler built-in */ }
231 #[unstable(feature = "proc_macro_internals", issue = "27812")]
235 /// A region of source code, along with macro expansion information.
236 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
237 #[derive(Copy, Clone)]
238 pub struct Span(bridge::client::Span);
240 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
241 impl !Send for Span {}
242 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
243 impl !Sync for Span {}
245 macro_rules! diagnostic_method {
246 ($name:ident, $level:expr) => (
247 /// Creates a new `Diagnostic` with the given `message` at the span
249 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
250 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
251 Diagnostic::spanned(self, $level, message)
257 /// A span that resolves at the macro definition site.
258 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
259 pub fn def_site() -> Span {
260 Span(bridge::client::Span::def_site())
263 /// The span of the invocation of the current procedural macro.
264 /// Identifiers created with this span will be resolved as if they were written
265 /// directly at the macro call location (call-site hygiene) and other code
266 /// at the macro call site will be able to refer to them as well.
267 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
268 pub fn call_site() -> Span {
269 Span(bridge::client::Span::call_site())
272 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
273 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
274 /// call site (everything else).
275 /// The span location is taken from the call-site.
276 #[unstable(feature = "proc_macro_mixed_site", issue = "65049")]
277 pub fn mixed_site() -> Span {
278 Span(bridge::client::Span::mixed_site())
281 /// The original source file into which this span points.
282 #[unstable(feature = "proc_macro_span", issue = "54725")]
283 pub fn source_file(&self) -> SourceFile {
284 SourceFile(self.0.source_file())
287 /// The `Span` for the tokens in the previous macro expansion from which
288 /// `self` was generated from, if any.
289 #[unstable(feature = "proc_macro_span", issue = "54725")]
290 pub fn parent(&self) -> Option<Span> {
291 self.0.parent().map(Span)
294 /// The span for the origin source code that `self` was generated from. If
295 /// this `Span` wasn't generated from other macro expansions then the return
296 /// value is the same as `*self`.
297 #[unstable(feature = "proc_macro_span", issue = "54725")]
298 pub fn source(&self) -> Span {
299 Span(self.0.source())
302 /// Gets the starting line/column in the source file for this span.
303 #[unstable(feature = "proc_macro_span", issue = "54725")]
304 pub fn start(&self) -> LineColumn {
308 /// Gets the ending line/column in the source file for this span.
309 #[unstable(feature = "proc_macro_span", issue = "54725")]
310 pub fn end(&self) -> LineColumn {
314 /// Creates a new span encompassing `self` and `other`.
316 /// Returns `None` if `self` and `other` are from different files.
317 #[unstable(feature = "proc_macro_span", issue = "54725")]
318 pub fn join(&self, other: Span) -> Option<Span> {
319 self.0.join(other.0).map(Span)
322 /// Creates a new span with the same line/column information as `self` but
323 /// that resolves symbols as though it were at `other`.
324 #[unstable(feature = "proc_macro_span", issue = "54725")]
325 pub fn resolved_at(&self, other: Span) -> Span {
326 Span(self.0.resolved_at(other.0))
329 /// Creates a new span with the same name resolution behavior as `self` but
330 /// with the line/column information of `other`.
331 #[unstable(feature = "proc_macro_span", issue = "54725")]
332 pub fn located_at(&self, other: Span) -> Span {
333 other.resolved_at(*self)
336 /// Compares to spans to see if they're equal.
337 #[unstable(feature = "proc_macro_span", issue = "54725")]
338 pub fn eq(&self, other: &Span) -> bool {
342 /// Returns the source text behind a span. This preserves the original source
343 /// code, including spaces and comments. It only returns a result if the span
344 /// corresponds to real source code.
346 /// Note: The observable result of a macro should only rely on the tokens and
347 /// not on this source text. The result of this function is a best effort to
348 /// be used for diagnostics only.
349 #[unstable(feature = "proc_macro_span", issue = "54725")]
350 pub fn source_text(&self) -> Option<String> {
354 diagnostic_method!(error, Level::Error);
355 diagnostic_method!(warning, Level::Warning);
356 diagnostic_method!(note, Level::Note);
357 diagnostic_method!(help, Level::Help);
360 /// Prints a span in a form convenient for debugging.
361 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
362 impl fmt::Debug for Span {
363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368 /// A line-column pair representing the start or end of a `Span`.
369 #[unstable(feature = "proc_macro_span", issue = "54725")]
370 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
371 pub struct LineColumn {
372 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
373 #[unstable(feature = "proc_macro_span", issue = "54725")]
375 /// The 0-indexed column (in UTF-8 characters) in the source file on which
376 /// the span starts or ends (inclusive).
377 #[unstable(feature = "proc_macro_span", issue = "54725")]
381 #[unstable(feature = "proc_macro_span", issue = "54725")]
382 impl !Send for LineColumn {}
383 #[unstable(feature = "proc_macro_span", issue = "54725")]
384 impl !Sync for LineColumn {}
386 /// The source file of a given `Span`.
387 #[unstable(feature = "proc_macro_span", issue = "54725")]
389 pub struct SourceFile(bridge::client::SourceFile);
392 /// Gets the path to this source file.
395 /// If the code span associated with this `SourceFile` was generated by an external macro, this
396 /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
398 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
399 /// the command line, the path as given may not actually be valid.
401 /// [`is_real`]: #method.is_real
402 #[unstable(feature = "proc_macro_span", issue = "54725")]
403 pub fn path(&self) -> PathBuf {
404 PathBuf::from(self.0.path())
407 /// Returns `true` if this source file is a real source file, and not generated by an external
408 /// macro's expansion.
409 #[unstable(feature = "proc_macro_span", issue = "54725")]
410 pub fn is_real(&self) -> bool {
411 // This is a hack until intercrate spans are implemented and we can have real source files
412 // for spans generated in external macros.
413 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
419 #[unstable(feature = "proc_macro_span", issue = "54725")]
420 impl fmt::Debug for SourceFile {
421 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
422 f.debug_struct("SourceFile")
423 .field("path", &self.path())
424 .field("is_real", &self.is_real())
429 #[unstable(feature = "proc_macro_span", issue = "54725")]
430 impl PartialEq for SourceFile {
431 fn eq(&self, other: &Self) -> bool {
436 #[unstable(feature = "proc_macro_span", issue = "54725")]
437 impl Eq for SourceFile {}
439 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
440 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
443 /// A token stream surrounded by bracket delimiters.
444 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
446 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
450 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
452 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
455 /// A single punctuation character (`+`, `,`, `$`, etc.).
456 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
458 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
461 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
462 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
464 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
469 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
470 impl !Send for TokenTree {}
471 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
472 impl !Sync for TokenTree {}
475 /// Returns the span of this tree, delegating to the `span` method of
476 /// the contained token or a delimited stream.
477 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
478 pub fn span(&self) -> Span {
480 TokenTree::Group(ref t) => t.span(),
481 TokenTree::Ident(ref t) => t.span(),
482 TokenTree::Punct(ref t) => t.span(),
483 TokenTree::Literal(ref t) => t.span(),
487 /// Configures the span for *only this token*.
489 /// Note that if this token is a `Group` then this method will not configure
490 /// the span of each of the internal tokens, this will simply delegate to
491 /// the `set_span` method of each variant.
492 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
493 pub fn set_span(&mut self, span: Span) {
495 TokenTree::Group(ref mut t) => t.set_span(span),
496 TokenTree::Ident(ref mut t) => t.set_span(span),
497 TokenTree::Punct(ref mut t) => t.set_span(span),
498 TokenTree::Literal(ref mut t) => t.set_span(span),
503 /// Prints token tree in a form convenient for debugging.
504 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
505 impl fmt::Debug for TokenTree {
506 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507 // Each of these has the name in the struct type in the derived debug,
508 // so don't bother with an extra layer of indirection
510 TokenTree::Group(ref tt) => tt.fmt(f),
511 TokenTree::Ident(ref tt) => tt.fmt(f),
512 TokenTree::Punct(ref tt) => tt.fmt(f),
513 TokenTree::Literal(ref tt) => tt.fmt(f),
518 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
519 impl From<Group> for TokenTree {
520 fn from(g: Group) -> TokenTree {
525 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
526 impl From<Ident> for TokenTree {
527 fn from(g: Ident) -> TokenTree {
532 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
533 impl From<Punct> for TokenTree {
534 fn from(g: Punct) -> TokenTree {
539 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
540 impl From<Literal> for TokenTree {
541 fn from(g: Literal) -> TokenTree {
542 TokenTree::Literal(g)
546 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
547 // based on it (the reverse of the usual relationship between the two).
548 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
549 impl ToString for TokenTree {
550 fn to_string(&self) -> String {
552 TokenTree::Group(ref t) => t.to_string(),
553 TokenTree::Ident(ref t) => t.to_string(),
554 TokenTree::Punct(ref t) => t.to_string(),
555 TokenTree::Literal(ref t) => t.to_string(),
560 /// Prints the token tree as a string that is supposed to be losslessly convertible back
561 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
562 /// with `Delimiter::None` delimiters and negative numeric literals.
563 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
564 impl fmt::Display for TokenTree {
565 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
566 f.write_str(&self.to_string())
570 /// A delimited token stream.
572 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
574 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
575 pub struct Group(bridge::client::Group);
577 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
578 impl !Send for Group {}
579 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
580 impl !Sync for Group {}
582 /// Describes how a sequence of token trees is delimited.
583 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
584 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
587 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
590 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
593 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
596 /// An implicit delimiter, that may, for example, appear around tokens coming from a
597 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
598 /// `$var * 3` where `$var` is `1 + 2`.
599 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
600 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
605 /// Creates a new `Group` with the given delimiter and token stream.
607 /// This constructor will set the span for this group to
608 /// `Span::call_site()`. To change the span you can use the `set_span`
610 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
611 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
612 Group(bridge::client::Group::new(delimiter, stream.0))
615 /// Returns the delimiter of this `Group`
616 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
617 pub fn delimiter(&self) -> Delimiter {
621 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
623 /// Note that the returned token stream does not include the delimiter
625 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
626 pub fn stream(&self) -> TokenStream {
627 TokenStream(self.0.stream())
630 /// Returns the span for the delimiters of this token stream, spanning the
634 /// pub fn span(&self) -> Span {
637 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
638 pub fn span(&self) -> Span {
642 /// Returns the span pointing to the opening delimiter of this group.
645 /// pub fn span_open(&self) -> Span {
648 #[unstable(feature = "proc_macro_span", issue = "54725")]
649 pub fn span_open(&self) -> Span {
650 Span(self.0.span_open())
653 /// Returns the span pointing to the closing delimiter of this group.
656 /// pub fn span_close(&self) -> Span {
659 #[unstable(feature = "proc_macro_span", issue = "54725")]
660 pub fn span_close(&self) -> Span {
661 Span(self.0.span_close())
664 /// Configures the span for this `Group`'s delimiters, but not its internal
667 /// This method will **not** set the span of all the internal tokens spanned
668 /// by this group, but rather it will only set the span of the delimiter
669 /// tokens at the level of the `Group`.
670 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
671 pub fn set_span(&mut self, span: Span) {
672 self.0.set_span(span.0);
676 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
677 // based on it (the reverse of the usual relationship between the two).
678 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
679 impl ToString for Group {
680 fn to_string(&self) -> String {
681 TokenStream::from(TokenTree::from(self.clone())).to_string()
685 /// Prints the group as a string that should be losslessly convertible back
686 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
687 /// with `Delimiter::None` delimiters.
688 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
689 impl fmt::Display for Group {
690 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
691 f.write_str(&self.to_string())
695 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
696 impl fmt::Debug for Group {
697 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
698 f.debug_struct("Group")
699 .field("delimiter", &self.delimiter())
700 .field("stream", &self.stream())
701 .field("span", &self.span())
706 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
708 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
709 /// forms of `Spacing` returned.
710 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
712 pub struct Punct(bridge::client::Punct);
714 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
715 impl !Send for Punct {}
716 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
717 impl !Sync for Punct {}
719 /// Whether an `Punct` is followed immediately by another `Punct` or
720 /// followed by another token or whitespace.
721 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
722 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
724 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
725 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
727 /// e.g., `+` is `Joint` in `+=` or `'#`.
728 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
729 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
734 /// Creates a new `Punct` from the given character and spacing.
735 /// The `ch` argument must be a valid punctuation character permitted by the language,
736 /// otherwise the function will panic.
738 /// The returned `Punct` will have the default span of `Span::call_site()`
739 /// which can be further configured with the `set_span` method below.
740 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
741 pub fn new(ch: char, spacing: Spacing) -> Punct {
742 Punct(bridge::client::Punct::new(ch, spacing))
745 /// Returns the value of this punctuation character as `char`.
746 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
747 pub fn as_char(&self) -> char {
751 /// Returns the spacing of this punctuation character, indicating whether it's immediately
752 /// followed by another `Punct` in the token stream, so they can potentially be combined into
753 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
754 /// (`Alone`) so the operator has certainly ended.
755 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
756 pub fn spacing(&self) -> Spacing {
760 /// Returns the span for this punctuation character.
761 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
762 pub fn span(&self) -> Span {
766 /// Configure the span for this punctuation character.
767 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
768 pub fn set_span(&mut self, span: Span) {
769 self.0 = self.0.with_span(span.0);
773 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
774 // based on it (the reverse of the usual relationship between the two).
775 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
776 impl ToString for Punct {
777 fn to_string(&self) -> String {
778 TokenStream::from(TokenTree::from(self.clone())).to_string()
782 /// Prints the punctuation character as a string that should be losslessly convertible
783 /// back into the same character.
784 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
785 impl fmt::Display for Punct {
786 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
787 f.write_str(&self.to_string())
791 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
792 impl fmt::Debug for Punct {
793 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
794 f.debug_struct("Punct")
795 .field("ch", &self.as_char())
796 .field("spacing", &self.spacing())
797 .field("span", &self.span())
802 /// An identifier (`ident`).
804 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
805 pub struct Ident(bridge::client::Ident);
808 /// Creates a new `Ident` with the given `string` as well as the specified
810 /// The `string` argument must be a valid identifier permitted by the
811 /// language, otherwise the function will panic.
813 /// Note that `span`, currently in rustc, configures the hygiene information
814 /// for this identifier.
816 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
817 /// meaning that identifiers created with this span will be resolved as if they were written
818 /// directly at the location of the macro call, and other code at the macro call site will be
819 /// able to refer to them as well.
821 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
822 /// meaning that identifiers created with this span will be resolved at the location of the
823 /// macro definition and other code at the macro call site will not be able to refer to them.
825 /// Due to the current importance of hygiene this constructor, unlike other
826 /// tokens, requires a `Span` to be specified at construction.
827 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
828 pub fn new(string: &str, span: Span) -> Ident {
829 Ident(bridge::client::Ident::new(string, span.0, false))
832 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
833 #[unstable(feature = "proc_macro_raw_ident", issue = "54723")]
834 pub fn new_raw(string: &str, span: Span) -> Ident {
835 Ident(bridge::client::Ident::new(string, span.0, true))
838 /// Returns the span of this `Ident`, encompassing the entire string returned
840 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
841 pub fn span(&self) -> Span {
845 /// Configures the span of this `Ident`, possibly changing its hygiene context.
846 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
847 pub fn set_span(&mut self, span: Span) {
848 self.0 = self.0.with_span(span.0);
852 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
853 // based on it (the reverse of the usual relationship between the two).
854 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
855 impl ToString for Ident {
856 fn to_string(&self) -> String {
857 TokenStream::from(TokenTree::from(self.clone())).to_string()
861 /// Prints the identifier as a string that should be losslessly convertible
862 /// back into the same identifier.
863 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
864 impl fmt::Display for Ident {
865 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
866 f.write_str(&self.to_string())
870 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
871 impl fmt::Debug for Ident {
872 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
873 f.debug_struct("Ident")
874 .field("ident", &self.to_string())
875 .field("span", &self.span())
880 /// A literal string (`"hello"`), byte string (`b"hello"`),
881 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
882 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
883 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
885 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
886 pub struct Literal(bridge::client::Literal);
888 macro_rules! suffixed_int_literals {
889 ($($name:ident => $kind:ident,)*) => ($(
890 /// Creates a new suffixed integer literal with the specified value.
892 /// This function will create an integer like `1u32` where the integer
893 /// value specified is the first part of the token and the integral is
894 /// also suffixed at the end.
895 /// Literals created from negative numbers may not survive round-trips through
896 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
898 /// Literals created through this method have the `Span::call_site()`
899 /// span by default, which can be configured with the `set_span` method
901 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
902 pub fn $name(n: $kind) -> Literal {
903 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
908 macro_rules! unsuffixed_int_literals {
909 ($($name:ident => $kind:ident,)*) => ($(
910 /// Creates a new unsuffixed integer literal with the specified value.
912 /// This function will create an integer like `1` where the integer
913 /// value specified is the first part of the token. No suffix is
914 /// specified on this token, meaning that invocations like
915 /// `Literal::i8_unsuffixed(1)` are equivalent to
916 /// `Literal::u32_unsuffixed(1)`.
917 /// Literals created from negative numbers may not survive rountrips through
918 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
920 /// Literals created through this method have the `Span::call_site()`
921 /// span by default, which can be configured with the `set_span` method
923 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
924 pub fn $name(n: $kind) -> Literal {
925 Literal(bridge::client::Literal::integer(&n.to_string()))
931 suffixed_int_literals! {
936 u128_suffixed => u128,
937 usize_suffixed => usize,
942 i128_suffixed => i128,
943 isize_suffixed => isize,
946 unsuffixed_int_literals! {
948 u16_unsuffixed => u16,
949 u32_unsuffixed => u32,
950 u64_unsuffixed => u64,
951 u128_unsuffixed => u128,
952 usize_unsuffixed => usize,
954 i16_unsuffixed => i16,
955 i32_unsuffixed => i32,
956 i64_unsuffixed => i64,
957 i128_unsuffixed => i128,
958 isize_unsuffixed => isize,
961 /// Creates a new unsuffixed floating-point literal.
963 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
964 /// the float's value is emitted directly into the token but no suffix is
965 /// used, so it may be inferred to be a `f64` later in the compiler.
966 /// Literals created from negative numbers may not survive rountrips through
967 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
971 /// This function requires that the specified float is finite, for
972 /// example if it is infinity or NaN this function will panic.
973 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
974 pub fn f32_unsuffixed(n: f32) -> Literal {
976 panic!("Invalid float literal {}", n);
978 Literal(bridge::client::Literal::float(&n.to_string()))
981 /// Creates a new suffixed floating-point literal.
983 /// This constructor will create a literal like `1.0f32` where the value
984 /// specified is the preceding part of the token and `f32` is the suffix of
985 /// the token. This token will always be inferred to be an `f32` in the
987 /// Literals created from negative numbers may not survive rountrips through
988 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
992 /// This function requires that the specified float is finite, for
993 /// example if it is infinity or NaN this function will panic.
994 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
995 pub fn f32_suffixed(n: f32) -> Literal {
997 panic!("Invalid float literal {}", n);
999 Literal(bridge::client::Literal::f32(&n.to_string()))
1002 /// Creates a new unsuffixed floating-point literal.
1004 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1005 /// the float's value is emitted directly into the token but no suffix is
1006 /// used, so it may be inferred to be a `f64` later in the compiler.
1007 /// Literals created from negative numbers may not survive rountrips through
1008 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1012 /// This function requires that the specified float is finite, for
1013 /// example if it is infinity or NaN this function will panic.
1014 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1015 pub fn f64_unsuffixed(n: f64) -> Literal {
1017 panic!("Invalid float literal {}", n);
1019 Literal(bridge::client::Literal::float(&n.to_string()))
1022 /// Creates a new suffixed floating-point literal.
1024 /// This constructor will create a literal like `1.0f64` where the value
1025 /// specified is the preceding part of the token and `f64` is the suffix of
1026 /// the token. This token will always be inferred to be an `f64` in the
1028 /// Literals created from negative numbers may not survive rountrips through
1029 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1033 /// This function requires that the specified float is finite, for
1034 /// example if it is infinity or NaN this function will panic.
1035 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1036 pub fn f64_suffixed(n: f64) -> Literal {
1038 panic!("Invalid float literal {}", n);
1040 Literal(bridge::client::Literal::f64(&n.to_string()))
1044 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1045 pub fn string(string: &str) -> Literal {
1046 Literal(bridge::client::Literal::string(string))
1049 /// Character literal.
1050 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1051 pub fn character(ch: char) -> Literal {
1052 Literal(bridge::client::Literal::character(ch))
1055 /// Byte string literal.
1056 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1057 pub fn byte_string(bytes: &[u8]) -> Literal {
1058 Literal(bridge::client::Literal::byte_string(bytes))
1061 /// Returns the span encompassing this literal.
1062 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1063 pub fn span(&self) -> Span {
1067 /// Configures the span associated for this literal.
1068 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1069 pub fn set_span(&mut self, span: Span) {
1070 self.0.set_span(span.0);
1073 /// Returns a `Span` that is a subset of `self.span()` containing only the
1074 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1075 /// span is outside the bounds of `self`.
1076 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1077 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1078 // occur elsewhere when the source text is printed.
1079 // FIXME(SergioBenitez): there is no way for the user to know what
1080 // `self.span()` actually maps to, so this method can currently only be
1081 // called blindly. For example, `to_string()` for the character 'c' returns
1082 // "'\u{63}'"; there is no way for the user to know whether the source text
1083 // was 'c' or whether it was '\u{63}'.
1084 #[unstable(feature = "proc_macro_span", issue = "54725")]
1085 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1086 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1087 fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1089 Bound::Included(x) => Bound::Included(x.clone()),
1090 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1091 Bound::Unbounded => Bound::Unbounded,
1096 cloned_bound(range.start_bound()),
1097 cloned_bound(range.end_bound()),
1102 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1103 // based on it (the reverse of the usual relationship between the two).
1104 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1105 impl ToString for Literal {
1106 fn to_string(&self) -> String {
1107 TokenStream::from(TokenTree::from(self.clone())).to_string()
1111 /// Prints the literal as a string that should be losslessly convertible
1112 /// back into the same literal (except for possible rounding for floating point literals).
1113 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1114 impl fmt::Display for Literal {
1115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1116 f.write_str(&self.to_string())
1120 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1121 impl fmt::Debug for Literal {
1122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1123 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.