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](../book/first-edition/procedural-macros.html) for more.
10 #![stable(feature = "proc_macro_lib", since = "1.15.0")]
11 #![deny(missing_docs)]
12 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
13 html_playground_url = "https://play.rust-lang.org/",
14 issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
15 test(no_crate_inject, attr(deny(warnings))),
16 test(attr(allow(dead_code, deprecated, unused_variables, unused_mut))))]
18 #![deny(rust_2018_idioms)]
21 #![feature(staged_api)]
23 #![feature(extern_types)]
24 #![feature(in_band_lifetimes)]
25 #![feature(optin_builtin_traits)]
26 #![feature(non_exhaustive)]
27 #![feature(specialization)]
29 #![recursion_limit="256"]
31 #[unstable(feature = "proc_macro_internals", issue = "27812")]
37 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
38 pub use diagnostic::{Diagnostic, Level, MultiSpan};
40 use std::{fmt, iter, mem};
41 use std::ops::{Bound, RangeBounds};
42 use std::path::PathBuf;
43 use std::str::FromStr;
45 /// The main type provided by this crate, representing an abstract stream of
46 /// tokens, or, more specifically, a sequence of token trees.
47 /// The type provide interfaces for iterating over those token trees and, conversely,
48 /// collecting a number of token trees into one stream.
50 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
51 /// and `#[proc_macro_derive]` definitions.
52 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
54 pub struct TokenStream(bridge::client::TokenStream);
56 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
57 impl !Send for TokenStream {}
58 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
59 impl !Sync for TokenStream {}
61 /// Error returned from `TokenStream::from_str`.
62 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
68 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
69 impl !Send for LexError {}
70 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
71 impl !Sync for LexError {}
74 /// Returns an empty `TokenStream` containing no token trees.
75 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
76 pub fn new() -> TokenStream {
77 TokenStream(bridge::client::TokenStream::new())
80 /// Checks if this `TokenStream` is empty.
81 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
82 pub fn is_empty(&self) -> bool {
87 /// Attempts to break the string into tokens and parse those tokens into a token stream.
88 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
89 /// or characters not existing in the language.
90 /// All tokens in the parsed stream get `Span::call_site()` spans.
92 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
93 /// change these errors into `LexError`s later.
94 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
95 impl FromStr for TokenStream {
98 fn from_str(src: &str) -> Result<TokenStream, LexError> {
99 Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
103 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
104 // based on it (the reverse of the usual relationship between the two).
105 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
106 impl ToString for TokenStream {
107 fn to_string(&self) -> String {
112 /// Prints the token stream as a string that is supposed to be losslessly convertible back
113 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
114 /// with `Delimiter::None` delimiters and negative numeric literals.
115 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
116 impl fmt::Display for TokenStream {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 f.write_str(&self.to_string())
122 /// Prints token in a form convenient for debugging.
123 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
124 impl fmt::Debug for TokenStream {
125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126 f.write_str("TokenStream ")?;
127 f.debug_list().entries(self.clone()).finish()
131 #[unstable(feature = "proc_macro_quote", issue = "54722")]
132 pub use quote::{quote, quote_span};
134 /// Creates a token stream containing a single token tree.
135 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
136 impl From<TokenTree> for TokenStream {
137 fn from(tree: TokenTree) -> TokenStream {
138 TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
139 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
140 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
141 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
142 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0)
147 /// Collects a number of token trees into a single stream.
148 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
149 impl iter::FromIterator<TokenTree> for TokenStream {
150 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
151 trees.into_iter().map(TokenStream::from).collect()
155 /// A "flattening" operation on token streams, collects token trees
156 /// from multiple token streams into a single stream.
157 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
158 impl iter::FromIterator<TokenStream> for TokenStream {
159 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
160 let mut builder = bridge::client::TokenStreamBuilder::new();
161 for stream in streams {
162 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 diagnostic_method!(error, Level::Error);
335 diagnostic_method!(warning, Level::Warning);
336 diagnostic_method!(note, Level::Note);
337 diagnostic_method!(help, Level::Help);
340 /// Prints a span in a form convenient for debugging.
341 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
342 impl fmt::Debug for Span {
343 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 /// A line-column pair representing the start or end of a `Span`.
349 #[unstable(feature = "proc_macro_span", issue = "54725")]
350 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
351 pub struct LineColumn {
352 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
353 #[unstable(feature = "proc_macro_span", issue = "54725")]
355 /// The 0-indexed column (in UTF-8 characters) in the source file on which
356 /// the span starts or ends (inclusive).
357 #[unstable(feature = "proc_macro_span", issue = "54725")]
361 #[unstable(feature = "proc_macro_span", issue = "54725")]
362 impl !Send for LineColumn {}
363 #[unstable(feature = "proc_macro_span", issue = "54725")]
364 impl !Sync for LineColumn {}
366 /// The source file of a given `Span`.
367 #[unstable(feature = "proc_macro_span", issue = "54725")]
369 pub struct SourceFile(bridge::client::SourceFile);
372 /// Gets the path to this source file.
375 /// If the code span associated with this `SourceFile` was generated by an external macro, this
376 /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
378 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
379 /// the command line, the path as given may not actually be valid.
381 /// [`is_real`]: #method.is_real
382 #[unstable(feature = "proc_macro_span", issue = "54725")]
383 pub fn path(&self) -> PathBuf {
384 PathBuf::from(self.0.path())
387 /// Returns `true` if this source file is a real source file, and not generated by an external
388 /// macro's expansion.
389 #[unstable(feature = "proc_macro_span", issue = "54725")]
390 pub fn is_real(&self) -> bool {
391 // This is a hack until intercrate spans are implemented and we can have real source files
392 // for spans generated in external macros.
393 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
399 #[unstable(feature = "proc_macro_span", issue = "54725")]
400 impl fmt::Debug for SourceFile {
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402 f.debug_struct("SourceFile")
403 .field("path", &self.path())
404 .field("is_real", &self.is_real())
409 #[unstable(feature = "proc_macro_span", issue = "54725")]
410 impl PartialEq for SourceFile {
411 fn eq(&self, other: &Self) -> bool {
416 #[unstable(feature = "proc_macro_span", issue = "54725")]
417 impl Eq for SourceFile {}
419 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
420 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
423 /// A token stream surrounded by bracket delimiters.
424 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
426 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
430 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
432 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
435 /// A single punctuation character (`+`, `,`, `$`, etc.).
436 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
438 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
441 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
442 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
444 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
449 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
450 impl !Send for TokenTree {}
451 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
452 impl !Sync for TokenTree {}
455 /// Returns the span of this tree, delegating to the `span` method of
456 /// the contained token or a delimited stream.
457 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
458 pub fn span(&self) -> Span {
460 TokenTree::Group(ref t) => t.span(),
461 TokenTree::Ident(ref t) => t.span(),
462 TokenTree::Punct(ref t) => t.span(),
463 TokenTree::Literal(ref t) => t.span(),
467 /// Configures the span for *only this token*.
469 /// Note that if this token is a `Group` then this method will not configure
470 /// the span of each of the internal tokens, this will simply delegate to
471 /// the `set_span` method of each variant.
472 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
473 pub fn set_span(&mut self, span: Span) {
475 TokenTree::Group(ref mut t) => t.set_span(span),
476 TokenTree::Ident(ref mut t) => t.set_span(span),
477 TokenTree::Punct(ref mut t) => t.set_span(span),
478 TokenTree::Literal(ref mut t) => t.set_span(span),
483 /// Prints token tree in a form convenient for debugging.
484 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
485 impl fmt::Debug for TokenTree {
486 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487 // Each of these has the name in the struct type in the derived debug,
488 // so don't bother with an extra layer of indirection
490 TokenTree::Group(ref tt) => tt.fmt(f),
491 TokenTree::Ident(ref tt) => tt.fmt(f),
492 TokenTree::Punct(ref tt) => tt.fmt(f),
493 TokenTree::Literal(ref tt) => tt.fmt(f),
498 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
499 impl From<Group> for TokenTree {
500 fn from(g: Group) -> TokenTree {
505 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
506 impl From<Ident> for TokenTree {
507 fn from(g: Ident) -> TokenTree {
512 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
513 impl From<Punct> for TokenTree {
514 fn from(g: Punct) -> TokenTree {
519 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
520 impl From<Literal> for TokenTree {
521 fn from(g: Literal) -> TokenTree {
522 TokenTree::Literal(g)
526 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
527 // based on it (the reverse of the usual relationship between the two).
528 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
529 impl ToString for TokenTree {
530 fn to_string(&self) -> String {
532 TokenTree::Group(ref t) => t.to_string(),
533 TokenTree::Ident(ref t) => t.to_string(),
534 TokenTree::Punct(ref t) => t.to_string(),
535 TokenTree::Literal(ref t) => t.to_string(),
540 /// Prints the token tree as a string that is supposed to be losslessly convertible back
541 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
542 /// with `Delimiter::None` delimiters and negative numeric literals.
543 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
544 impl fmt::Display for TokenTree {
545 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
546 f.write_str(&self.to_string())
550 /// A delimited token stream.
552 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
554 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
555 pub struct Group(bridge::client::Group);
557 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
558 impl !Send for Group {}
559 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
560 impl !Sync for Group {}
562 /// Describes how a sequence of token trees is delimited.
563 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
564 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
567 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
570 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
573 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
576 /// An implicit delimiter, that may, for example, appear around tokens coming from a
577 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
578 /// `$var * 3` where `$var` is `1 + 2`.
579 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
580 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
585 /// Creates a new `Group` with the given delimiter and token stream.
587 /// This constructor will set the span for this group to
588 /// `Span::call_site()`. To change the span you can use the `set_span`
590 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
591 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
592 Group(bridge::client::Group::new(delimiter, stream.0))
595 /// Returns the delimiter of this `Group`
596 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
597 pub fn delimiter(&self) -> Delimiter {
601 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
603 /// Note that the returned token stream does not include the delimiter
605 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
606 pub fn stream(&self) -> TokenStream {
607 TokenStream(self.0.stream())
610 /// Returns the span for the delimiters of this token stream, spanning the
614 /// pub fn span(&self) -> Span {
617 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
618 pub fn span(&self) -> Span {
622 /// Returns the span pointing to the opening delimiter of this group.
625 /// pub fn span_open(&self) -> Span {
628 #[unstable(feature = "proc_macro_span", issue = "54725")]
629 pub fn span_open(&self) -> Span {
630 Span(self.0.span_open())
633 /// Returns the span pointing to the closing delimiter of this group.
636 /// pub fn span_close(&self) -> Span {
639 #[unstable(feature = "proc_macro_span", issue = "54725")]
640 pub fn span_close(&self) -> Span {
641 Span(self.0.span_close())
644 /// Configures the span for this `Group`'s delimiters, but not its internal
647 /// This method will **not** set the span of all the internal tokens spanned
648 /// by this group, but rather it will only set the span of the delimiter
649 /// tokens at the level of the `Group`.
650 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
651 pub fn set_span(&mut self, span: Span) {
652 self.0.set_span(span.0);
656 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
657 // based on it (the reverse of the usual relationship between the two).
658 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
659 impl ToString for Group {
660 fn to_string(&self) -> String {
661 TokenStream::from(TokenTree::from(self.clone())).to_string()
665 /// Prints the group as a string that should be losslessly convertible back
666 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
667 /// with `Delimiter::None` delimiters.
668 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
669 impl fmt::Display for Group {
670 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
671 f.write_str(&self.to_string())
675 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
676 impl fmt::Debug for Group {
677 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
678 f.debug_struct("Group")
679 .field("delimiter", &self.delimiter())
680 .field("stream", &self.stream())
681 .field("span", &self.span())
686 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
688 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
689 /// forms of `Spacing` returned.
690 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
692 pub struct Punct(bridge::client::Punct);
694 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
695 impl !Send for Punct {}
696 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
697 impl !Sync for Punct {}
699 /// Whether an `Punct` is followed immediately by another `Punct` or
700 /// followed by another token or whitespace.
701 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
702 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
704 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
705 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
707 /// e.g., `+` is `Joint` in `+=` or `'#`.
708 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
709 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
714 /// Creates a new `Punct` from the given character and spacing.
715 /// The `ch` argument must be a valid punctuation character permitted by the language,
716 /// otherwise the function will panic.
718 /// The returned `Punct` will have the default span of `Span::call_site()`
719 /// which can be further configured with the `set_span` method below.
720 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
721 pub fn new(ch: char, spacing: Spacing) -> Punct {
722 Punct(bridge::client::Punct::new(ch, spacing))
725 /// Returns the value of this punctuation character as `char`.
726 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
727 pub fn as_char(&self) -> char {
731 /// Returns the spacing of this punctuation character, indicating whether it's immediately
732 /// followed by another `Punct` in the token stream, so they can potentially be combined into
733 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
734 /// (`Alone`) so the operator has certainly ended.
735 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
736 pub fn spacing(&self) -> Spacing {
740 /// Returns the span for this punctuation character.
741 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
742 pub fn span(&self) -> Span {
746 /// Configure the span for this punctuation character.
747 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
748 pub fn set_span(&mut self, span: Span) {
749 self.0 = self.0.with_span(span.0);
753 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
754 // based on it (the reverse of the usual relationship between the two).
755 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
756 impl ToString for Punct {
757 fn to_string(&self) -> String {
758 TokenStream::from(TokenTree::from(self.clone())).to_string()
762 /// Prints the punctuation character as a string that should be losslessly convertible
763 /// back into the same character.
764 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
765 impl fmt::Display for Punct {
766 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
767 f.write_str(&self.to_string())
771 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
772 impl fmt::Debug for Punct {
773 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
774 f.debug_struct("Punct")
775 .field("ch", &self.as_char())
776 .field("spacing", &self.spacing())
777 .field("span", &self.span())
782 /// An identifier (`ident`).
784 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
785 pub struct Ident(bridge::client::Ident);
788 /// Creates a new `Ident` with the given `string` as well as the specified
790 /// The `string` argument must be a valid identifier permitted by the
791 /// language, otherwise the function will panic.
793 /// Note that `span`, currently in rustc, configures the hygiene information
794 /// for this identifier.
796 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
797 /// meaning that identifiers created with this span will be resolved as if they were written
798 /// directly at the location of the macro call, and other code at the macro call site will be
799 /// able to refer to them as well.
801 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
802 /// meaning that identifiers created with this span will be resolved at the location of the
803 /// macro definition and other code at the macro call site will not be able to refer to them.
805 /// Due to the current importance of hygiene this constructor, unlike other
806 /// tokens, requires a `Span` to be specified at construction.
807 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
808 pub fn new(string: &str, span: Span) -> Ident {
809 Ident(bridge::client::Ident::new(string, span.0, false))
812 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
813 #[unstable(feature = "proc_macro_raw_ident", issue = "54723")]
814 pub fn new_raw(string: &str, span: Span) -> Ident {
815 Ident(bridge::client::Ident::new(string, span.0, true))
818 /// Returns the span of this `Ident`, encompassing the entire string returned
820 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
821 pub fn span(&self) -> Span {
825 /// Configures the span of this `Ident`, possibly changing its hygiene context.
826 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
827 pub fn set_span(&mut self, span: Span) {
828 self.0 = self.0.with_span(span.0);
832 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
833 // based on it (the reverse of the usual relationship between the two).
834 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
835 impl ToString for Ident {
836 fn to_string(&self) -> String {
837 TokenStream::from(TokenTree::from(self.clone())).to_string()
841 /// Prints the identifier as a string that should be losslessly convertible
842 /// back into the same identifier.
843 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
844 impl fmt::Display for Ident {
845 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
846 f.write_str(&self.to_string())
850 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
851 impl fmt::Debug for Ident {
852 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
853 f.debug_struct("Ident")
854 .field("ident", &self.to_string())
855 .field("span", &self.span())
860 /// A literal string (`"hello"`), byte string (`b"hello"`),
861 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
862 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
863 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
865 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
866 pub struct Literal(bridge::client::Literal);
868 macro_rules! suffixed_int_literals {
869 ($($name:ident => $kind:ident,)*) => ($(
870 /// Creates a new suffixed integer literal with the specified value.
872 /// This function will create an integer like `1u32` where the integer
873 /// value specified is the first part of the token and the integral is
874 /// also suffixed at the end.
875 /// Literals created from negative numbers may not survive round-trips through
876 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
878 /// Literals created through this method have the `Span::call_site()`
879 /// span by default, which can be configured with the `set_span` method
881 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
882 pub fn $name(n: $kind) -> Literal {
883 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
888 macro_rules! unsuffixed_int_literals {
889 ($($name:ident => $kind:ident,)*) => ($(
890 /// Creates a new unsuffixed integer literal with the specified value.
892 /// This function will create an integer like `1` where the integer
893 /// value specified is the first part of the token. No suffix is
894 /// specified on this token, meaning that invocations like
895 /// `Literal::i8_unsuffixed(1)` are equivalent to
896 /// `Literal::u32_unsuffixed(1)`.
897 /// Literals created from negative numbers may not survive rountrips through
898 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
900 /// Literals created through this method have the `Span::call_site()`
901 /// span by default, which can be configured with the `set_span` method
903 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
904 pub fn $name(n: $kind) -> Literal {
905 Literal(bridge::client::Literal::integer(&n.to_string()))
911 suffixed_int_literals! {
916 u128_suffixed => u128,
917 usize_suffixed => usize,
922 i128_suffixed => i128,
923 isize_suffixed => isize,
926 unsuffixed_int_literals! {
928 u16_unsuffixed => u16,
929 u32_unsuffixed => u32,
930 u64_unsuffixed => u64,
931 u128_unsuffixed => u128,
932 usize_unsuffixed => usize,
934 i16_unsuffixed => i16,
935 i32_unsuffixed => i32,
936 i64_unsuffixed => i64,
937 i128_unsuffixed => i128,
938 isize_unsuffixed => isize,
941 /// Creates a new unsuffixed floating-point literal.
943 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
944 /// the float's value is emitted directly into the token but no suffix is
945 /// used, so it may be inferred to be a `f64` later in the compiler.
946 /// Literals created from negative numbers may not survive rountrips through
947 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
951 /// This function requires that the specified float is finite, for
952 /// example if it is infinity or NaN this function will panic.
953 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
954 pub fn f32_unsuffixed(n: f32) -> Literal {
956 panic!("Invalid float literal {}", n);
958 Literal(bridge::client::Literal::float(&n.to_string()))
961 /// Creates a new suffixed floating-point literal.
963 /// This constructor will create a literal like `1.0f32` where the value
964 /// specified is the preceding part of the token and `f32` is the suffix of
965 /// the token. This token will always be inferred to be an `f32` in the
967 /// Literals created from negative numbers may not survive rountrips through
968 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
972 /// This function requires that the specified float is finite, for
973 /// example if it is infinity or NaN this function will panic.
974 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
975 pub fn f32_suffixed(n: f32) -> Literal {
977 panic!("Invalid float literal {}", n);
979 Literal(bridge::client::Literal::f32(&n.to_string()))
982 /// Creates a new unsuffixed floating-point literal.
984 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
985 /// the float's value is emitted directly into the token but no suffix is
986 /// used, so it may be inferred to be a `f64` later in the compiler.
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 f64_unsuffixed(n: f64) -> Literal {
997 panic!("Invalid float literal {}", n);
999 Literal(bridge::client::Literal::float(&n.to_string()))
1002 /// Creates a new suffixed floating-point literal.
1004 /// This constructor will create a literal like `1.0f64` where the value
1005 /// specified is the preceding part of the token and `f64` is the suffix of
1006 /// the token. This token will always be inferred to be an `f64` in the
1008 /// Literals created from negative numbers may not survive rountrips through
1009 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1013 /// This function requires that the specified float is finite, for
1014 /// example if it is infinity or NaN this function will panic.
1015 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1016 pub fn f64_suffixed(n: f64) -> Literal {
1018 panic!("Invalid float literal {}", n);
1020 Literal(bridge::client::Literal::f64(&n.to_string()))
1024 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1025 pub fn string(string: &str) -> Literal {
1026 Literal(bridge::client::Literal::string(string))
1029 /// Character literal.
1030 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1031 pub fn character(ch: char) -> Literal {
1032 Literal(bridge::client::Literal::character(ch))
1035 /// Byte string literal.
1036 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1037 pub fn byte_string(bytes: &[u8]) -> Literal {
1038 Literal(bridge::client::Literal::byte_string(bytes))
1041 /// Returns the span encompassing this literal.
1042 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1043 pub fn span(&self) -> Span {
1047 /// Configures the span associated for this literal.
1048 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1049 pub fn set_span(&mut self, span: Span) {
1050 self.0.set_span(span.0);
1053 /// Returns a `Span` that is a subset of `self.span()` containing only the
1054 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1055 /// span is outside the bounds of `self`.
1056 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1057 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1058 // occur elsewhere when the source text is printed.
1059 // FIXME(SergioBenitez): there is no way for the user to know what
1060 // `self.span()` actually maps to, so this method can currently only be
1061 // called blindly. For example, `to_string()` for the character 'c' returns
1062 // "'\u{63}'"; there is no way for the user to know whether the source text
1063 // was 'c' or whether it was '\u{63}'.
1064 #[unstable(feature = "proc_macro_span", issue = "54725")]
1065 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1066 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1067 fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1069 Bound::Included(x) => Bound::Included(x.clone()),
1070 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1071 Bound::Unbounded => Bound::Unbounded,
1076 cloned_bound(range.start_bound()),
1077 cloned_bound(range.end_bound()),
1082 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1083 // based on it (the reverse of the usual relationship between the two).
1084 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1085 impl ToString for Literal {
1086 fn to_string(&self) -> String {
1087 TokenStream::from(TokenTree::from(self.clone())).to_string()
1091 /// Prints the literal as a string that should be losslessly convertible
1092 /// back into the same literal (except for possible rounding for floating point literals).
1093 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1094 impl fmt::Display for Literal {
1095 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1096 f.write_str(&self.to_string())
1100 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1101 impl fmt::Debug for Literal {
1102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1103 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.