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)]
23 #![feature(extern_types)]
24 #![feature(in_band_lifetimes)]
25 #![feature(optin_builtin_traits)]
27 #![feature(non_exhaustive)]
28 #![feature(specialization)]
30 #![recursion_limit="256"]
32 #[unstable(feature = "proc_macro_internals", issue = "27812")]
38 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
39 pub use diagnostic::{Diagnostic, Level, MultiSpan};
41 use std::{fmt, iter, mem};
42 use std::ops::{Bound, RangeBounds};
43 use std::path::PathBuf;
44 use std::str::FromStr;
46 /// The main type provided by this crate, representing an abstract stream of
47 /// tokens, or, more specifically, a sequence of token trees.
48 /// The type provide interfaces for iterating over those token trees and, conversely,
49 /// collecting a number of token trees into one stream.
51 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
52 /// and `#[proc_macro_derive]` definitions.
53 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
55 pub struct TokenStream(bridge::client::TokenStream);
57 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
58 impl !Send for TokenStream {}
59 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
60 impl !Sync for TokenStream {}
62 /// Error returned from `TokenStream::from_str`.
63 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
69 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
70 impl !Send for LexError {}
71 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
72 impl !Sync for LexError {}
75 /// Returns an empty `TokenStream` containing no token trees.
76 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
77 pub fn new() -> TokenStream {
78 TokenStream(bridge::client::TokenStream::new())
81 /// Checks if this `TokenStream` is empty.
82 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
83 pub fn is_empty(&self) -> bool {
88 /// Attempts to break the string into tokens and parse those tokens into a token stream.
89 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
90 /// or characters not existing in the language.
91 /// All tokens in the parsed stream get `Span::call_site()` spans.
93 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
94 /// change these errors into `LexError`s later.
95 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
96 impl FromStr for TokenStream {
99 fn from_str(src: &str) -> Result<TokenStream, LexError> {
100 Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
104 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
105 // based on it (the reverse of the usual relationship between the two).
106 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
107 impl ToString for TokenStream {
108 fn to_string(&self) -> String {
113 /// Prints the token stream as a string that is supposed to be losslessly convertible back
114 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
115 /// with `Delimiter::None` delimiters and negative numeric literals.
116 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
117 impl fmt::Display for TokenStream {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119 f.write_str(&self.to_string())
123 /// Prints token in a form convenient for debugging.
124 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
125 impl fmt::Debug for TokenStream {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 f.write_str("TokenStream ")?;
128 f.debug_list().entries(self.clone()).finish()
132 #[unstable(feature = "proc_macro_quote", issue = "54722")]
133 pub use quote::{quote, quote_span};
135 /// Creates a token stream containing a single token tree.
136 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
137 impl From<TokenTree> for TokenStream {
138 fn from(tree: TokenTree) -> TokenStream {
139 TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
140 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
141 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
142 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
143 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0)
148 /// Collects a number of token trees into a single stream.
149 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
150 impl iter::FromIterator<TokenTree> for TokenStream {
151 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
152 trees.into_iter().map(TokenStream::from).collect()
156 /// A "flattening" operation on token streams, collects token trees
157 /// from multiple token streams into a single stream.
158 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
159 impl iter::FromIterator<TokenStream> for TokenStream {
160 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
161 let mut builder = bridge::client::TokenStreamBuilder::new();
162 streams.into_iter().for_each(|stream| builder.push(stream.0));
163 TokenStream(builder.build())
167 #[stable(feature = "token_stream_extend", since = "1.30.0")]
168 impl Extend<TokenTree> for TokenStream {
169 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
170 self.extend(trees.into_iter().map(TokenStream::from));
174 #[stable(feature = "token_stream_extend", since = "1.30.0")]
175 impl Extend<TokenStream> for TokenStream {
176 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
177 // FIXME(eddyb) Use an optimized implementation if/when possible.
178 *self = iter::once(mem::replace(self, Self::new())).chain(streams).collect();
182 /// Public implementation details for the `TokenStream` type, such as iterators.
183 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
184 pub mod token_stream {
185 use crate::{bridge, Group, Ident, Literal, Punct, TokenTree, TokenStream};
187 /// An iterator over `TokenStream`'s `TokenTree`s.
188 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
189 /// and returns whole groups as token trees.
191 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
192 pub struct IntoIter(bridge::client::TokenStreamIter);
194 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
195 impl Iterator for IntoIter {
196 type Item = TokenTree;
198 fn next(&mut self) -> Option<TokenTree> {
199 self.0.next().map(|tree| match tree {
200 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
201 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
202 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
203 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
208 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
209 impl IntoIterator for TokenStream {
210 type Item = TokenTree;
211 type IntoIter = IntoIter;
213 fn into_iter(self) -> IntoIter {
214 IntoIter(self.0.into_iter())
219 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
220 /// For example, `quote!(a + b)` will produce a expression, that, when evaluated, constructs
221 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
223 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
224 /// To quote `$` itself, use `$$`.
226 /// This is a dummy macro, the actual implementation is in `quote::quote`.`
227 #[unstable(feature = "proc_macro_quote", issue = "54722")]
229 macro_rules! quote { () => {} }
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 /// The original source file into which this span points.
273 #[unstable(feature = "proc_macro_span", issue = "54725")]
274 pub fn source_file(&self) -> SourceFile {
275 SourceFile(self.0.source_file())
278 /// The `Span` for the tokens in the previous macro expansion from which
279 /// `self` was generated from, if any.
280 #[unstable(feature = "proc_macro_span", issue = "54725")]
281 pub fn parent(&self) -> Option<Span> {
282 self.0.parent().map(Span)
285 /// The span for the origin source code that `self` was generated from. If
286 /// this `Span` wasn't generated from other macro expansions then the return
287 /// value is the same as `*self`.
288 #[unstable(feature = "proc_macro_span", issue = "54725")]
289 pub fn source(&self) -> Span {
290 Span(self.0.source())
293 /// Gets the starting line/column in the source file for this span.
294 #[unstable(feature = "proc_macro_span", issue = "54725")]
295 pub fn start(&self) -> LineColumn {
299 /// Gets the ending line/column in the source file for this span.
300 #[unstable(feature = "proc_macro_span", issue = "54725")]
301 pub fn end(&self) -> LineColumn {
305 /// Creates a new span encompassing `self` and `other`.
307 /// Returns `None` if `self` and `other` are from different files.
308 #[unstable(feature = "proc_macro_span", issue = "54725")]
309 pub fn join(&self, other: Span) -> Option<Span> {
310 self.0.join(other.0).map(Span)
313 /// Creates a new span with the same line/column information as `self` but
314 /// that resolves symbols as though it were at `other`.
315 #[unstable(feature = "proc_macro_span", issue = "54725")]
316 pub fn resolved_at(&self, other: Span) -> Span {
317 Span(self.0.resolved_at(other.0))
320 /// Creates a new span with the same name resolution behavior as `self` but
321 /// with the line/column information of `other`.
322 #[unstable(feature = "proc_macro_span", issue = "54725")]
323 pub fn located_at(&self, other: Span) -> Span {
324 other.resolved_at(*self)
327 /// Compares to spans to see if they're equal.
328 #[unstable(feature = "proc_macro_span", issue = "54725")]
329 pub fn eq(&self, other: &Span) -> bool {
333 /// Returns the source text behind a span. This preserves the original source
334 /// code, including spaces and comments. It only returns a result if the span
335 /// corresponds to real source code.
337 /// Note: The observable result of a macro should only rely on the tokens and
338 /// not on this source text. The result of this function is a best effort to
339 /// be used for diagnostics only.
340 #[unstable(feature = "proc_macro_span", issue = "54725")]
341 pub fn source_text(&self) -> Option<String> {
345 diagnostic_method!(error, Level::Error);
346 diagnostic_method!(warning, Level::Warning);
347 diagnostic_method!(note, Level::Note);
348 diagnostic_method!(help, Level::Help);
351 /// Prints a span in a form convenient for debugging.
352 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
353 impl fmt::Debug for Span {
354 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359 /// A line-column pair representing the start or end of a `Span`.
360 #[unstable(feature = "proc_macro_span", issue = "54725")]
361 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
362 pub struct LineColumn {
363 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
364 #[unstable(feature = "proc_macro_span", issue = "54725")]
366 /// The 0-indexed column (in UTF-8 characters) in the source file on which
367 /// the span starts or ends (inclusive).
368 #[unstable(feature = "proc_macro_span", issue = "54725")]
372 #[unstable(feature = "proc_macro_span", issue = "54725")]
373 impl !Send for LineColumn {}
374 #[unstable(feature = "proc_macro_span", issue = "54725")]
375 impl !Sync for LineColumn {}
377 /// The source file of a given `Span`.
378 #[unstable(feature = "proc_macro_span", issue = "54725")]
380 pub struct SourceFile(bridge::client::SourceFile);
383 /// Gets the path to this source file.
386 /// If the code span associated with this `SourceFile` was generated by an external macro, this
387 /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
389 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
390 /// the command line, the path as given may not actually be valid.
392 /// [`is_real`]: #method.is_real
393 #[unstable(feature = "proc_macro_span", issue = "54725")]
394 pub fn path(&self) -> PathBuf {
395 PathBuf::from(self.0.path())
398 /// Returns `true` if this source file is a real source file, and not generated by an external
399 /// macro's expansion.
400 #[unstable(feature = "proc_macro_span", issue = "54725")]
401 pub fn is_real(&self) -> bool {
402 // This is a hack until intercrate spans are implemented and we can have real source files
403 // for spans generated in external macros.
404 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
410 #[unstable(feature = "proc_macro_span", issue = "54725")]
411 impl fmt::Debug for SourceFile {
412 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
413 f.debug_struct("SourceFile")
414 .field("path", &self.path())
415 .field("is_real", &self.is_real())
420 #[unstable(feature = "proc_macro_span", issue = "54725")]
421 impl PartialEq for SourceFile {
422 fn eq(&self, other: &Self) -> bool {
427 #[unstable(feature = "proc_macro_span", issue = "54725")]
428 impl Eq for SourceFile {}
430 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
431 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
434 /// A token stream surrounded by bracket delimiters.
435 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
437 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
441 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
443 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
446 /// A single punctuation character (`+`, `,`, `$`, etc.).
447 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
449 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
452 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
453 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
455 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
460 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
461 impl !Send for TokenTree {}
462 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
463 impl !Sync for TokenTree {}
466 /// Returns the span of this tree, delegating to the `span` method of
467 /// the contained token or a delimited stream.
468 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
469 pub fn span(&self) -> Span {
471 TokenTree::Group(ref t) => t.span(),
472 TokenTree::Ident(ref t) => t.span(),
473 TokenTree::Punct(ref t) => t.span(),
474 TokenTree::Literal(ref t) => t.span(),
478 /// Configures the span for *only this token*.
480 /// Note that if this token is a `Group` then this method will not configure
481 /// the span of each of the internal tokens, this will simply delegate to
482 /// the `set_span` method of each variant.
483 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
484 pub fn set_span(&mut self, span: Span) {
486 TokenTree::Group(ref mut t) => t.set_span(span),
487 TokenTree::Ident(ref mut t) => t.set_span(span),
488 TokenTree::Punct(ref mut t) => t.set_span(span),
489 TokenTree::Literal(ref mut t) => t.set_span(span),
494 /// Prints token tree in a form convenient for debugging.
495 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
496 impl fmt::Debug for TokenTree {
497 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
498 // Each of these has the name in the struct type in the derived debug,
499 // so don't bother with an extra layer of indirection
501 TokenTree::Group(ref tt) => tt.fmt(f),
502 TokenTree::Ident(ref tt) => tt.fmt(f),
503 TokenTree::Punct(ref tt) => tt.fmt(f),
504 TokenTree::Literal(ref tt) => tt.fmt(f),
509 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
510 impl From<Group> for TokenTree {
511 fn from(g: Group) -> TokenTree {
516 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
517 impl From<Ident> for TokenTree {
518 fn from(g: Ident) -> TokenTree {
523 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
524 impl From<Punct> for TokenTree {
525 fn from(g: Punct) -> TokenTree {
530 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
531 impl From<Literal> for TokenTree {
532 fn from(g: Literal) -> TokenTree {
533 TokenTree::Literal(g)
537 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
538 // based on it (the reverse of the usual relationship between the two).
539 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
540 impl ToString for TokenTree {
541 fn to_string(&self) -> String {
543 TokenTree::Group(ref t) => t.to_string(),
544 TokenTree::Ident(ref t) => t.to_string(),
545 TokenTree::Punct(ref t) => t.to_string(),
546 TokenTree::Literal(ref t) => t.to_string(),
551 /// Prints the token tree as a string that is supposed to be losslessly convertible back
552 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
553 /// with `Delimiter::None` delimiters and negative numeric literals.
554 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
555 impl fmt::Display for TokenTree {
556 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
557 f.write_str(&self.to_string())
561 /// A delimited token stream.
563 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
565 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
566 pub struct Group(bridge::client::Group);
568 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
569 impl !Send for Group {}
570 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
571 impl !Sync for Group {}
573 /// Describes how a sequence of token trees is delimited.
574 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
575 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
578 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
581 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
584 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
587 /// An implicit delimiter, that may, for example, appear around tokens coming from a
588 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
589 /// `$var * 3` where `$var` is `1 + 2`.
590 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
591 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
596 /// Creates a new `Group` with the given delimiter and token stream.
598 /// This constructor will set the span for this group to
599 /// `Span::call_site()`. To change the span you can use the `set_span`
601 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
602 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
603 Group(bridge::client::Group::new(delimiter, stream.0))
606 /// Returns the delimiter of this `Group`
607 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
608 pub fn delimiter(&self) -> Delimiter {
612 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
614 /// Note that the returned token stream does not include the delimiter
616 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
617 pub fn stream(&self) -> TokenStream {
618 TokenStream(self.0.stream())
621 /// Returns the span for the delimiters of this token stream, spanning the
625 /// pub fn span(&self) -> Span {
628 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
629 pub fn span(&self) -> Span {
633 /// Returns the span pointing to the opening delimiter of this group.
636 /// pub fn span_open(&self) -> Span {
639 #[unstable(feature = "proc_macro_span", issue = "54725")]
640 pub fn span_open(&self) -> Span {
641 Span(self.0.span_open())
644 /// Returns the span pointing to the closing delimiter of this group.
647 /// pub fn span_close(&self) -> Span {
650 #[unstable(feature = "proc_macro_span", issue = "54725")]
651 pub fn span_close(&self) -> Span {
652 Span(self.0.span_close())
655 /// Configures the span for this `Group`'s delimiters, but not its internal
658 /// This method will **not** set the span of all the internal tokens spanned
659 /// by this group, but rather it will only set the span of the delimiter
660 /// tokens at the level of the `Group`.
661 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
662 pub fn set_span(&mut self, span: Span) {
663 self.0.set_span(span.0);
667 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
668 // based on it (the reverse of the usual relationship between the two).
669 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
670 impl ToString for Group {
671 fn to_string(&self) -> String {
672 TokenStream::from(TokenTree::from(self.clone())).to_string()
676 /// Prints the group as a string that should be losslessly convertible back
677 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
678 /// with `Delimiter::None` delimiters.
679 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
680 impl fmt::Display for Group {
681 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
682 f.write_str(&self.to_string())
686 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
687 impl fmt::Debug for Group {
688 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
689 f.debug_struct("Group")
690 .field("delimiter", &self.delimiter())
691 .field("stream", &self.stream())
692 .field("span", &self.span())
697 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
699 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
700 /// forms of `Spacing` returned.
701 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
703 pub struct Punct(bridge::client::Punct);
705 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
706 impl !Send for Punct {}
707 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
708 impl !Sync for Punct {}
710 /// Whether an `Punct` is followed immediately by another `Punct` or
711 /// followed by another token or whitespace.
712 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
713 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
715 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
716 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
718 /// e.g., `+` is `Joint` in `+=` or `'#`.
719 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
720 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
725 /// Creates a new `Punct` from the given character and spacing.
726 /// The `ch` argument must be a valid punctuation character permitted by the language,
727 /// otherwise the function will panic.
729 /// The returned `Punct` will have the default span of `Span::call_site()`
730 /// which can be further configured with the `set_span` method below.
731 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
732 pub fn new(ch: char, spacing: Spacing) -> Punct {
733 Punct(bridge::client::Punct::new(ch, spacing))
736 /// Returns the value of this punctuation character as `char`.
737 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
738 pub fn as_char(&self) -> char {
742 /// Returns the spacing of this punctuation character, indicating whether it's immediately
743 /// followed by another `Punct` in the token stream, so they can potentially be combined into
744 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
745 /// (`Alone`) so the operator has certainly ended.
746 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
747 pub fn spacing(&self) -> Spacing {
751 /// Returns the span for this punctuation character.
752 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
753 pub fn span(&self) -> Span {
757 /// Configure the span for this punctuation character.
758 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
759 pub fn set_span(&mut self, span: Span) {
760 self.0 = self.0.with_span(span.0);
764 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
765 // based on it (the reverse of the usual relationship between the two).
766 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
767 impl ToString for Punct {
768 fn to_string(&self) -> String {
769 TokenStream::from(TokenTree::from(self.clone())).to_string()
773 /// Prints the punctuation character as a string that should be losslessly convertible
774 /// back into the same character.
775 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
776 impl fmt::Display for Punct {
777 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
778 f.write_str(&self.to_string())
782 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
783 impl fmt::Debug for Punct {
784 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
785 f.debug_struct("Punct")
786 .field("ch", &self.as_char())
787 .field("spacing", &self.spacing())
788 .field("span", &self.span())
793 /// An identifier (`ident`).
795 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
796 pub struct Ident(bridge::client::Ident);
799 /// Creates a new `Ident` with the given `string` as well as the specified
801 /// The `string` argument must be a valid identifier permitted by the
802 /// language, otherwise the function will panic.
804 /// Note that `span`, currently in rustc, configures the hygiene information
805 /// for this identifier.
807 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
808 /// meaning that identifiers created with this span will be resolved as if they were written
809 /// directly at the location of the macro call, and other code at the macro call site will be
810 /// able to refer to them as well.
812 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
813 /// meaning that identifiers created with this span will be resolved at the location of the
814 /// macro definition and other code at the macro call site will not be able to refer to them.
816 /// Due to the current importance of hygiene this constructor, unlike other
817 /// tokens, requires a `Span` to be specified at construction.
818 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
819 pub fn new(string: &str, span: Span) -> Ident {
820 Ident(bridge::client::Ident::new(string, span.0, false))
823 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
824 #[unstable(feature = "proc_macro_raw_ident", issue = "54723")]
825 pub fn new_raw(string: &str, span: Span) -> Ident {
826 Ident(bridge::client::Ident::new(string, span.0, true))
829 /// Returns the span of this `Ident`, encompassing the entire string returned
831 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
832 pub fn span(&self) -> Span {
836 /// Configures the span of this `Ident`, possibly changing its hygiene context.
837 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
838 pub fn set_span(&mut self, span: Span) {
839 self.0 = self.0.with_span(span.0);
843 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
844 // based on it (the reverse of the usual relationship between the two).
845 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
846 impl ToString for Ident {
847 fn to_string(&self) -> String {
848 TokenStream::from(TokenTree::from(self.clone())).to_string()
852 /// Prints the identifier as a string that should be losslessly convertible
853 /// back into the same identifier.
854 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
855 impl fmt::Display for Ident {
856 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
857 f.write_str(&self.to_string())
861 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
862 impl fmt::Debug for Ident {
863 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
864 f.debug_struct("Ident")
865 .field("ident", &self.to_string())
866 .field("span", &self.span())
871 /// A literal string (`"hello"`), byte string (`b"hello"`),
872 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
873 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
874 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
876 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
877 pub struct Literal(bridge::client::Literal);
879 macro_rules! suffixed_int_literals {
880 ($($name:ident => $kind:ident,)*) => ($(
881 /// Creates a new suffixed integer literal with the specified value.
883 /// This function will create an integer like `1u32` where the integer
884 /// value specified is the first part of the token and the integral is
885 /// also suffixed at the end.
886 /// Literals created from negative numbers may not survive round-trips through
887 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
889 /// Literals created through this method have the `Span::call_site()`
890 /// span by default, which can be configured with the `set_span` method
892 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
893 pub fn $name(n: $kind) -> Literal {
894 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
899 macro_rules! unsuffixed_int_literals {
900 ($($name:ident => $kind:ident,)*) => ($(
901 /// Creates a new unsuffixed integer literal with the specified value.
903 /// This function will create an integer like `1` where the integer
904 /// value specified is the first part of the token. No suffix is
905 /// specified on this token, meaning that invocations like
906 /// `Literal::i8_unsuffixed(1)` are equivalent to
907 /// `Literal::u32_unsuffixed(1)`.
908 /// Literals created from negative numbers may not survive rountrips through
909 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
911 /// Literals created through this method have the `Span::call_site()`
912 /// span by default, which can be configured with the `set_span` method
914 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
915 pub fn $name(n: $kind) -> Literal {
916 Literal(bridge::client::Literal::integer(&n.to_string()))
922 suffixed_int_literals! {
927 u128_suffixed => u128,
928 usize_suffixed => usize,
933 i128_suffixed => i128,
934 isize_suffixed => isize,
937 unsuffixed_int_literals! {
939 u16_unsuffixed => u16,
940 u32_unsuffixed => u32,
941 u64_unsuffixed => u64,
942 u128_unsuffixed => u128,
943 usize_unsuffixed => usize,
945 i16_unsuffixed => i16,
946 i32_unsuffixed => i32,
947 i64_unsuffixed => i64,
948 i128_unsuffixed => i128,
949 isize_unsuffixed => isize,
952 /// Creates a new unsuffixed floating-point literal.
954 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
955 /// the float's value is emitted directly into the token but no suffix is
956 /// used, so it may be inferred to be a `f64` later in the compiler.
957 /// Literals created from negative numbers may not survive rountrips through
958 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
962 /// This function requires that the specified float is finite, for
963 /// example if it is infinity or NaN this function will panic.
964 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
965 pub fn f32_unsuffixed(n: f32) -> Literal {
967 panic!("Invalid float literal {}", n);
969 Literal(bridge::client::Literal::float(&n.to_string()))
972 /// Creates a new suffixed floating-point literal.
974 /// This constructor will create a literal like `1.0f32` where the value
975 /// specified is the preceding part of the token and `f32` is the suffix of
976 /// the token. This token will always be inferred to be an `f32` in the
978 /// Literals created from negative numbers may not survive rountrips through
979 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
983 /// This function requires that the specified float is finite, for
984 /// example if it is infinity or NaN this function will panic.
985 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
986 pub fn f32_suffixed(n: f32) -> Literal {
988 panic!("Invalid float literal {}", n);
990 Literal(bridge::client::Literal::f32(&n.to_string()))
993 /// Creates a new unsuffixed floating-point literal.
995 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
996 /// the float's value is emitted directly into the token but no suffix is
997 /// used, so it may be inferred to be a `f64` later in the compiler.
998 /// Literals created from negative numbers may not survive rountrips through
999 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1003 /// This function requires that the specified float is finite, for
1004 /// example if it is infinity or NaN this function will panic.
1005 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1006 pub fn f64_unsuffixed(n: f64) -> Literal {
1008 panic!("Invalid float literal {}", n);
1010 Literal(bridge::client::Literal::float(&n.to_string()))
1013 /// Creates a new suffixed floating-point literal.
1015 /// This constructor will create a literal like `1.0f64` where the value
1016 /// specified is the preceding part of the token and `f64` is the suffix of
1017 /// the token. This token will always be inferred to be an `f64` in the
1019 /// Literals created from negative numbers may not survive rountrips through
1020 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1024 /// This function requires that the specified float is finite, for
1025 /// example if it is infinity or NaN this function will panic.
1026 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1027 pub fn f64_suffixed(n: f64) -> Literal {
1029 panic!("Invalid float literal {}", n);
1031 Literal(bridge::client::Literal::f64(&n.to_string()))
1035 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1036 pub fn string(string: &str) -> Literal {
1037 Literal(bridge::client::Literal::string(string))
1040 /// Character literal.
1041 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1042 pub fn character(ch: char) -> Literal {
1043 Literal(bridge::client::Literal::character(ch))
1046 /// Byte string literal.
1047 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1048 pub fn byte_string(bytes: &[u8]) -> Literal {
1049 Literal(bridge::client::Literal::byte_string(bytes))
1052 /// Returns the span encompassing this literal.
1053 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1054 pub fn span(&self) -> Span {
1058 /// Configures the span associated for this literal.
1059 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1060 pub fn set_span(&mut self, span: Span) {
1061 self.0.set_span(span.0);
1064 /// Returns a `Span` that is a subset of `self.span()` containing only the
1065 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1066 /// span is outside the bounds of `self`.
1067 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1068 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1069 // occur elsewhere when the source text is printed.
1070 // FIXME(SergioBenitez): there is no way for the user to know what
1071 // `self.span()` actually maps to, so this method can currently only be
1072 // called blindly. For example, `to_string()` for the character 'c' returns
1073 // "'\u{63}'"; there is no way for the user to know whether the source text
1074 // was 'c' or whether it was '\u{63}'.
1075 #[unstable(feature = "proc_macro_span", issue = "54725")]
1076 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1077 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1078 fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1080 Bound::Included(x) => Bound::Included(x.clone()),
1081 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1082 Bound::Unbounded => Bound::Unbounded,
1087 cloned_bound(range.start_bound()),
1088 cloned_bound(range.end_bound()),
1093 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1094 // based on it (the reverse of the usual relationship between the two).
1095 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1096 impl ToString for Literal {
1097 fn to_string(&self) -> String {
1098 TokenStream::from(TokenTree::from(self.clone())).to_string()
1102 /// Prints the literal as a string that should be losslessly convertible
1103 /// back into the same literal (except for possible rounding for floating point literals).
1104 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1105 impl fmt::Display for Literal {
1106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1107 f.write_str(&self.to_string())
1111 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1112 impl fmt::Debug for Literal {
1113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1114 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.