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))))]
20 #![deny(rust_2018_idioms)]
23 #![feature(staged_api)]
25 #![feature(extern_types)]
26 #![feature(in_band_lifetimes)]
27 #![feature(optin_builtin_traits)]
28 #![feature(non_exhaustive)]
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 `$$`.
227 /// This is a dummy macro, the actual implementation is in `quote::quote`.`
228 #[unstable(feature = "proc_macro_quote", issue = "54722")]
230 macro_rules! quote { () => {} }
232 #[unstable(feature = "proc_macro_internals", issue = "27812")]
236 /// A region of source code, along with macro expansion information.
237 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
238 #[derive(Copy, Clone)]
239 pub struct Span(bridge::client::Span);
241 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
242 impl !Send for Span {}
243 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
244 impl !Sync for Span {}
246 macro_rules! diagnostic_method {
247 ($name:ident, $level:expr) => (
248 /// Creates a new `Diagnostic` with the given `message` at the span
250 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
251 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
252 Diagnostic::spanned(self, $level, message)
258 /// A span that resolves at the macro definition site.
259 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
260 pub fn def_site() -> Span {
261 Span(bridge::client::Span::def_site())
264 /// The span of the invocation of the current procedural macro.
265 /// Identifiers created with this span will be resolved as if they were written
266 /// directly at the macro call location (call-site hygiene) and other code
267 /// at the macro call site will be able to refer to them as well.
268 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
269 pub fn call_site() -> Span {
270 Span(bridge::client::Span::call_site())
273 /// The original source file into which this span points.
274 #[unstable(feature = "proc_macro_span", issue = "54725")]
275 pub fn source_file(&self) -> SourceFile {
276 SourceFile(self.0.source_file())
279 /// The `Span` for the tokens in the previous macro expansion from which
280 /// `self` was generated from, if any.
281 #[unstable(feature = "proc_macro_span", issue = "54725")]
282 pub fn parent(&self) -> Option<Span> {
283 self.0.parent().map(Span)
286 /// The span for the origin source code that `self` was generated from. If
287 /// this `Span` wasn't generated from other macro expansions then the return
288 /// value is the same as `*self`.
289 #[unstable(feature = "proc_macro_span", issue = "54725")]
290 pub fn source(&self) -> Span {
291 Span(self.0.source())
294 /// Gets the starting line/column in the source file for this span.
295 #[unstable(feature = "proc_macro_span", issue = "54725")]
296 pub fn start(&self) -> LineColumn {
300 /// Gets the ending line/column in the source file for this span.
301 #[unstable(feature = "proc_macro_span", issue = "54725")]
302 pub fn end(&self) -> LineColumn {
306 /// Creates a new span encompassing `self` and `other`.
308 /// Returns `None` if `self` and `other` are from different files.
309 #[unstable(feature = "proc_macro_span", issue = "54725")]
310 pub fn join(&self, other: Span) -> Option<Span> {
311 self.0.join(other.0).map(Span)
314 /// Creates a new span with the same line/column information as `self` but
315 /// that resolves symbols as though it were at `other`.
316 #[unstable(feature = "proc_macro_span", issue = "54725")]
317 pub fn resolved_at(&self, other: Span) -> Span {
318 Span(self.0.resolved_at(other.0))
321 /// Creates a new span with the same name resolution behavior as `self` but
322 /// with the line/column information of `other`.
323 #[unstable(feature = "proc_macro_span", issue = "54725")]
324 pub fn located_at(&self, other: Span) -> Span {
325 other.resolved_at(*self)
328 /// Compares to spans to see if they're equal.
329 #[unstable(feature = "proc_macro_span", issue = "54725")]
330 pub fn eq(&self, other: &Span) -> bool {
334 /// Returns the source text behind a span. This preserves the original source
335 /// code, including spaces and comments. It only returns a result if the span
336 /// corresponds to real source code.
338 /// Note: The observable result of a macro should only rely on the tokens and
339 /// not on this source text. The result of this function is a best effort to
340 /// be used for diagnostics only.
341 #[unstable(feature = "proc_macro_span", issue = "54725")]
342 pub fn source_text(&self) -> Option<String> {
346 diagnostic_method!(error, Level::Error);
347 diagnostic_method!(warning, Level::Warning);
348 diagnostic_method!(note, Level::Note);
349 diagnostic_method!(help, Level::Help);
352 /// Prints a span in a form convenient for debugging.
353 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
354 impl fmt::Debug for Span {
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
360 /// A line-column pair representing the start or end of a `Span`.
361 #[unstable(feature = "proc_macro_span", issue = "54725")]
362 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
363 pub struct LineColumn {
364 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
365 #[unstable(feature = "proc_macro_span", issue = "54725")]
367 /// The 0-indexed column (in UTF-8 characters) in the source file on which
368 /// the span starts or ends (inclusive).
369 #[unstable(feature = "proc_macro_span", issue = "54725")]
373 #[unstable(feature = "proc_macro_span", issue = "54725")]
374 impl !Send for LineColumn {}
375 #[unstable(feature = "proc_macro_span", issue = "54725")]
376 impl !Sync for LineColumn {}
378 /// The source file of a given `Span`.
379 #[unstable(feature = "proc_macro_span", issue = "54725")]
381 pub struct SourceFile(bridge::client::SourceFile);
384 /// Gets the path to this source file.
387 /// If the code span associated with this `SourceFile` was generated by an external macro, this
388 /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
390 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
391 /// the command line, the path as given may not actually be valid.
393 /// [`is_real`]: #method.is_real
394 #[unstable(feature = "proc_macro_span", issue = "54725")]
395 pub fn path(&self) -> PathBuf {
396 PathBuf::from(self.0.path())
399 /// Returns `true` if this source file is a real source file, and not generated by an external
400 /// macro's expansion.
401 #[unstable(feature = "proc_macro_span", issue = "54725")]
402 pub fn is_real(&self) -> bool {
403 // This is a hack until intercrate spans are implemented and we can have real source files
404 // for spans generated in external macros.
405 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
411 #[unstable(feature = "proc_macro_span", issue = "54725")]
412 impl fmt::Debug for SourceFile {
413 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
414 f.debug_struct("SourceFile")
415 .field("path", &self.path())
416 .field("is_real", &self.is_real())
421 #[unstable(feature = "proc_macro_span", issue = "54725")]
422 impl PartialEq for SourceFile {
423 fn eq(&self, other: &Self) -> bool {
428 #[unstable(feature = "proc_macro_span", issue = "54725")]
429 impl Eq for SourceFile {}
431 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
432 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
435 /// A token stream surrounded by bracket delimiters.
436 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
438 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
442 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
444 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
447 /// A single punctuation character (`+`, `,`, `$`, etc.).
448 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
450 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
453 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
454 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
456 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
461 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
462 impl !Send for TokenTree {}
463 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
464 impl !Sync for TokenTree {}
467 /// Returns the span of this tree, delegating to the `span` method of
468 /// the contained token or a delimited stream.
469 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
470 pub fn span(&self) -> Span {
472 TokenTree::Group(ref t) => t.span(),
473 TokenTree::Ident(ref t) => t.span(),
474 TokenTree::Punct(ref t) => t.span(),
475 TokenTree::Literal(ref t) => t.span(),
479 /// Configures the span for *only this token*.
481 /// Note that if this token is a `Group` then this method will not configure
482 /// the span of each of the internal tokens, this will simply delegate to
483 /// the `set_span` method of each variant.
484 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
485 pub fn set_span(&mut self, span: Span) {
487 TokenTree::Group(ref mut t) => t.set_span(span),
488 TokenTree::Ident(ref mut t) => t.set_span(span),
489 TokenTree::Punct(ref mut t) => t.set_span(span),
490 TokenTree::Literal(ref mut t) => t.set_span(span),
495 /// Prints token tree in a form convenient for debugging.
496 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
497 impl fmt::Debug for TokenTree {
498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499 // Each of these has the name in the struct type in the derived debug,
500 // so don't bother with an extra layer of indirection
502 TokenTree::Group(ref tt) => tt.fmt(f),
503 TokenTree::Ident(ref tt) => tt.fmt(f),
504 TokenTree::Punct(ref tt) => tt.fmt(f),
505 TokenTree::Literal(ref tt) => tt.fmt(f),
510 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
511 impl From<Group> for TokenTree {
512 fn from(g: Group) -> TokenTree {
517 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
518 impl From<Ident> for TokenTree {
519 fn from(g: Ident) -> TokenTree {
524 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
525 impl From<Punct> for TokenTree {
526 fn from(g: Punct) -> TokenTree {
531 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
532 impl From<Literal> for TokenTree {
533 fn from(g: Literal) -> TokenTree {
534 TokenTree::Literal(g)
538 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
539 // based on it (the reverse of the usual relationship between the two).
540 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
541 impl ToString for TokenTree {
542 fn to_string(&self) -> String {
544 TokenTree::Group(ref t) => t.to_string(),
545 TokenTree::Ident(ref t) => t.to_string(),
546 TokenTree::Punct(ref t) => t.to_string(),
547 TokenTree::Literal(ref t) => t.to_string(),
552 /// Prints the token tree as a string that is supposed to be losslessly convertible back
553 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
554 /// with `Delimiter::None` delimiters and negative numeric literals.
555 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
556 impl fmt::Display for TokenTree {
557 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
558 f.write_str(&self.to_string())
562 /// A delimited token stream.
564 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
566 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
567 pub struct Group(bridge::client::Group);
569 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
570 impl !Send for Group {}
571 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
572 impl !Sync for Group {}
574 /// Describes how a sequence of token trees is delimited.
575 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
576 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
579 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
582 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
585 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
588 /// An implicit delimiter, that may, for example, appear around tokens coming from a
589 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
590 /// `$var * 3` where `$var` is `1 + 2`.
591 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
592 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
597 /// Creates a new `Group` with the given delimiter and token stream.
599 /// This constructor will set the span for this group to
600 /// `Span::call_site()`. To change the span you can use the `set_span`
602 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
603 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
604 Group(bridge::client::Group::new(delimiter, stream.0))
607 /// Returns the delimiter of this `Group`
608 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
609 pub fn delimiter(&self) -> Delimiter {
613 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
615 /// Note that the returned token stream does not include the delimiter
617 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
618 pub fn stream(&self) -> TokenStream {
619 TokenStream(self.0.stream())
622 /// Returns the span for the delimiters of this token stream, spanning the
626 /// pub fn span(&self) -> Span {
629 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
630 pub fn span(&self) -> Span {
634 /// Returns the span pointing to the opening delimiter of this group.
637 /// pub fn span_open(&self) -> Span {
640 #[unstable(feature = "proc_macro_span", issue = "54725")]
641 pub fn span_open(&self) -> Span {
642 Span(self.0.span_open())
645 /// Returns the span pointing to the closing delimiter of this group.
648 /// pub fn span_close(&self) -> Span {
651 #[unstable(feature = "proc_macro_span", issue = "54725")]
652 pub fn span_close(&self) -> Span {
653 Span(self.0.span_close())
656 /// Configures the span for this `Group`'s delimiters, but not its internal
659 /// This method will **not** set the span of all the internal tokens spanned
660 /// by this group, but rather it will only set the span of the delimiter
661 /// tokens at the level of the `Group`.
662 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
663 pub fn set_span(&mut self, span: Span) {
664 self.0.set_span(span.0);
668 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
669 // based on it (the reverse of the usual relationship between the two).
670 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
671 impl ToString for Group {
672 fn to_string(&self) -> String {
673 TokenStream::from(TokenTree::from(self.clone())).to_string()
677 /// Prints the group as a string that should be losslessly convertible back
678 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
679 /// with `Delimiter::None` delimiters.
680 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
681 impl fmt::Display for Group {
682 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
683 f.write_str(&self.to_string())
687 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
688 impl fmt::Debug for Group {
689 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
690 f.debug_struct("Group")
691 .field("delimiter", &self.delimiter())
692 .field("stream", &self.stream())
693 .field("span", &self.span())
698 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
700 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
701 /// forms of `Spacing` returned.
702 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
704 pub struct Punct(bridge::client::Punct);
706 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
707 impl !Send for Punct {}
708 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
709 impl !Sync for Punct {}
711 /// Whether an `Punct` is followed immediately by another `Punct` or
712 /// followed by another token or whitespace.
713 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
714 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
716 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
717 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
719 /// e.g., `+` is `Joint` in `+=` or `'#`.
720 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
721 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
726 /// Creates a new `Punct` from the given character and spacing.
727 /// The `ch` argument must be a valid punctuation character permitted by the language,
728 /// otherwise the function will panic.
730 /// The returned `Punct` will have the default span of `Span::call_site()`
731 /// which can be further configured with the `set_span` method below.
732 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
733 pub fn new(ch: char, spacing: Spacing) -> Punct {
734 Punct(bridge::client::Punct::new(ch, spacing))
737 /// Returns the value of this punctuation character as `char`.
738 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
739 pub fn as_char(&self) -> char {
743 /// Returns the spacing of this punctuation character, indicating whether it's immediately
744 /// followed by another `Punct` in the token stream, so they can potentially be combined into
745 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
746 /// (`Alone`) so the operator has certainly ended.
747 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
748 pub fn spacing(&self) -> Spacing {
752 /// Returns the span for this punctuation character.
753 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
754 pub fn span(&self) -> Span {
758 /// Configure the span for this punctuation character.
759 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
760 pub fn set_span(&mut self, span: Span) {
761 self.0 = self.0.with_span(span.0);
765 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
766 // based on it (the reverse of the usual relationship between the two).
767 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
768 impl ToString for Punct {
769 fn to_string(&self) -> String {
770 TokenStream::from(TokenTree::from(self.clone())).to_string()
774 /// Prints the punctuation character as a string that should be losslessly convertible
775 /// back into the same character.
776 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
777 impl fmt::Display for Punct {
778 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
779 f.write_str(&self.to_string())
783 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
784 impl fmt::Debug for Punct {
785 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
786 f.debug_struct("Punct")
787 .field("ch", &self.as_char())
788 .field("spacing", &self.spacing())
789 .field("span", &self.span())
794 /// An identifier (`ident`).
796 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
797 pub struct Ident(bridge::client::Ident);
800 /// Creates a new `Ident` with the given `string` as well as the specified
802 /// The `string` argument must be a valid identifier permitted by the
803 /// language, otherwise the function will panic.
805 /// Note that `span`, currently in rustc, configures the hygiene information
806 /// for this identifier.
808 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
809 /// meaning that identifiers created with this span will be resolved as if they were written
810 /// directly at the location of the macro call, and other code at the macro call site will be
811 /// able to refer to them as well.
813 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
814 /// meaning that identifiers created with this span will be resolved at the location of the
815 /// macro definition and other code at the macro call site will not be able to refer to them.
817 /// Due to the current importance of hygiene this constructor, unlike other
818 /// tokens, requires a `Span` to be specified at construction.
819 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
820 pub fn new(string: &str, span: Span) -> Ident {
821 Ident(bridge::client::Ident::new(string, span.0, false))
824 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
825 #[unstable(feature = "proc_macro_raw_ident", issue = "54723")]
826 pub fn new_raw(string: &str, span: Span) -> Ident {
827 Ident(bridge::client::Ident::new(string, span.0, true))
830 /// Returns the span of this `Ident`, encompassing the entire string returned
832 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
833 pub fn span(&self) -> Span {
837 /// Configures the span of this `Ident`, possibly changing its hygiene context.
838 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
839 pub fn set_span(&mut self, span: Span) {
840 self.0 = self.0.with_span(span.0);
844 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
845 // based on it (the reverse of the usual relationship between the two).
846 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
847 impl ToString for Ident {
848 fn to_string(&self) -> String {
849 TokenStream::from(TokenTree::from(self.clone())).to_string()
853 /// Prints the identifier as a string that should be losslessly convertible
854 /// back into the same identifier.
855 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
856 impl fmt::Display for Ident {
857 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
858 f.write_str(&self.to_string())
862 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
863 impl fmt::Debug for Ident {
864 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
865 f.debug_struct("Ident")
866 .field("ident", &self.to_string())
867 .field("span", &self.span())
872 /// A literal string (`"hello"`), byte string (`b"hello"`),
873 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
874 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
875 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
877 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
878 pub struct Literal(bridge::client::Literal);
880 macro_rules! suffixed_int_literals {
881 ($($name:ident => $kind:ident,)*) => ($(
882 /// Creates a new suffixed integer literal with the specified value.
884 /// This function will create an integer like `1u32` where the integer
885 /// value specified is the first part of the token and the integral is
886 /// also suffixed at the end.
887 /// Literals created from negative numbers may not survive round-trips through
888 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
890 /// Literals created through this method have the `Span::call_site()`
891 /// span by default, which can be configured with the `set_span` method
893 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
894 pub fn $name(n: $kind) -> Literal {
895 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
900 macro_rules! unsuffixed_int_literals {
901 ($($name:ident => $kind:ident,)*) => ($(
902 /// Creates a new unsuffixed integer literal with the specified value.
904 /// This function will create an integer like `1` where the integer
905 /// value specified is the first part of the token. No suffix is
906 /// specified on this token, meaning that invocations like
907 /// `Literal::i8_unsuffixed(1)` are equivalent to
908 /// `Literal::u32_unsuffixed(1)`.
909 /// Literals created from negative numbers may not survive rountrips through
910 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
912 /// Literals created through this method have the `Span::call_site()`
913 /// span by default, which can be configured with the `set_span` method
915 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
916 pub fn $name(n: $kind) -> Literal {
917 Literal(bridge::client::Literal::integer(&n.to_string()))
923 suffixed_int_literals! {
928 u128_suffixed => u128,
929 usize_suffixed => usize,
934 i128_suffixed => i128,
935 isize_suffixed => isize,
938 unsuffixed_int_literals! {
940 u16_unsuffixed => u16,
941 u32_unsuffixed => u32,
942 u64_unsuffixed => u64,
943 u128_unsuffixed => u128,
944 usize_unsuffixed => usize,
946 i16_unsuffixed => i16,
947 i32_unsuffixed => i32,
948 i64_unsuffixed => i64,
949 i128_unsuffixed => i128,
950 isize_unsuffixed => isize,
953 /// Creates a new unsuffixed floating-point literal.
955 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
956 /// the float's value is emitted directly into the token but no suffix is
957 /// used, so it may be inferred to be a `f64` later in the compiler.
958 /// Literals created from negative numbers may not survive rountrips through
959 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
963 /// This function requires that the specified float is finite, for
964 /// example if it is infinity or NaN this function will panic.
965 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
966 pub fn f32_unsuffixed(n: f32) -> Literal {
968 panic!("Invalid float literal {}", n);
970 Literal(bridge::client::Literal::float(&n.to_string()))
973 /// Creates a new suffixed floating-point literal.
975 /// This constructor will create a literal like `1.0f32` where the value
976 /// specified is the preceding part of the token and `f32` is the suffix of
977 /// the token. This token will always be inferred to be an `f32` in the
979 /// Literals created from negative numbers may not survive rountrips through
980 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
984 /// This function requires that the specified float is finite, for
985 /// example if it is infinity or NaN this function will panic.
986 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
987 pub fn f32_suffixed(n: f32) -> Literal {
989 panic!("Invalid float literal {}", n);
991 Literal(bridge::client::Literal::f32(&n.to_string()))
994 /// Creates a new unsuffixed floating-point literal.
996 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
997 /// the float's value is emitted directly into the token but no suffix is
998 /// used, so it may be inferred to be a `f64` later in the compiler.
999 /// Literals created from negative numbers may not survive rountrips through
1000 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1004 /// This function requires that the specified float is finite, for
1005 /// example if it is infinity or NaN this function will panic.
1006 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1007 pub fn f64_unsuffixed(n: f64) -> Literal {
1009 panic!("Invalid float literal {}", n);
1011 Literal(bridge::client::Literal::float(&n.to_string()))
1014 /// Creates a new suffixed floating-point literal.
1016 /// This constructor will create a literal like `1.0f64` where the value
1017 /// specified is the preceding part of the token and `f64` is the suffix of
1018 /// the token. This token will always be inferred to be an `f64` in the
1020 /// Literals created from negative numbers may not survive rountrips through
1021 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1025 /// This function requires that the specified float is finite, for
1026 /// example if it is infinity or NaN this function will panic.
1027 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1028 pub fn f64_suffixed(n: f64) -> Literal {
1030 panic!("Invalid float literal {}", n);
1032 Literal(bridge::client::Literal::f64(&n.to_string()))
1036 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1037 pub fn string(string: &str) -> Literal {
1038 Literal(bridge::client::Literal::string(string))
1041 /// Character literal.
1042 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1043 pub fn character(ch: char) -> Literal {
1044 Literal(bridge::client::Literal::character(ch))
1047 /// Byte string literal.
1048 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1049 pub fn byte_string(bytes: &[u8]) -> Literal {
1050 Literal(bridge::client::Literal::byte_string(bytes))
1053 /// Returns the span encompassing this literal.
1054 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1055 pub fn span(&self) -> Span {
1059 /// Configures the span associated for this literal.
1060 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1061 pub fn set_span(&mut self, span: Span) {
1062 self.0.set_span(span.0);
1065 /// Returns a `Span` that is a subset of `self.span()` containing only the
1066 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1067 /// span is outside the bounds of `self`.
1068 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1069 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1070 // occur elsewhere when the source text is printed.
1071 // FIXME(SergioBenitez): there is no way for the user to know what
1072 // `self.span()` actually maps to, so this method can currently only be
1073 // called blindly. For example, `to_string()` for the character 'c' returns
1074 // "'\u{63}'"; there is no way for the user to know whether the source text
1075 // was 'c' or whether it was '\u{63}'.
1076 #[unstable(feature = "proc_macro_span", issue = "54725")]
1077 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1078 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1079 fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1081 Bound::Included(x) => Bound::Included(x.clone()),
1082 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1083 Bound::Unbounded => Bound::Unbounded,
1088 cloned_bound(range.start_bound()),
1089 cloned_bound(range.end_bound()),
1094 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1095 // based on it (the reverse of the usual relationship between the two).
1096 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1097 impl ToString for Literal {
1098 fn to_string(&self) -> String {
1099 TokenStream::from(TokenTree::from(self.clone())).to_string()
1103 /// Prints the literal as a string that should be losslessly convertible
1104 /// back into the same literal (except for possible rounding for floating point literals).
1105 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1106 impl fmt::Display for Literal {
1107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1108 f.write_str(&self.to_string())
1112 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1113 impl fmt::Debug for Literal {
1114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1115 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.