1 //! A support library for macro authors when defining new macros.
3 //! This library, provided by the standard distribution, provides the types
4 //! consumed in the interfaces of procedurally defined macro definitions such as
5 //! function-like macros `#[proc_macro]`, macro attributes `#[proc_macro_attribute]` and
6 //! custom derive attributes`#[proc_macro_derive]`.
8 //! See [the book] for more.
10 //! [the book]: ../book/ch19-06-macros.html#procedural-macros-for-generating-code-from-attributes
12 #![stable(feature = "proc_macro_lib", since = "1.15.0")]
13 #![deny(missing_docs)]
14 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
15 html_playground_url = "https://play.rust-lang.org/",
16 issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
17 test(no_crate_inject, attr(deny(warnings))),
18 test(attr(allow(dead_code, deprecated, unused_variables, unused_mut))))]
21 #![feature(staged_api)]
22 #![feature(allow_internal_unstable)]
24 #![feature(decl_macro)]
25 #![feature(extern_types)]
26 #![feature(in_band_lifetimes)]
27 #![feature(optin_builtin_traits)]
29 #![feature(non_exhaustive)]
30 #![feature(rustc_attrs)]
31 #![feature(specialization)]
33 #![recursion_limit="256"]
35 #[unstable(feature = "proc_macro_internals", issue = "27812")]
41 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
42 pub use diagnostic::{Diagnostic, Level, MultiSpan};
44 use std::{fmt, iter, mem};
45 use std::ops::{Bound, RangeBounds};
46 use std::path::PathBuf;
47 use std::str::FromStr;
49 /// The main type provided by this crate, representing an abstract stream of
50 /// tokens, or, more specifically, a sequence of token trees.
51 /// The type provide interfaces for iterating over those token trees and, conversely,
52 /// collecting a number of token trees into one stream.
54 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
55 /// and `#[proc_macro_derive]` definitions.
56 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
58 pub struct TokenStream(bridge::client::TokenStream);
60 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
61 impl !Send for TokenStream {}
62 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
63 impl !Sync for TokenStream {}
65 /// Error returned from `TokenStream::from_str`.
66 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
72 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
73 impl !Send for LexError {}
74 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
75 impl !Sync for LexError {}
78 /// Returns an empty `TokenStream` containing no token trees.
79 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
80 pub fn new() -> TokenStream {
81 TokenStream(bridge::client::TokenStream::new())
84 /// Checks if this `TokenStream` is empty.
85 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
86 pub fn is_empty(&self) -> bool {
91 /// Attempts to break the string into tokens and parse those tokens into a token stream.
92 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
93 /// or characters not existing in the language.
94 /// All tokens in the parsed stream get `Span::call_site()` spans.
96 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
97 /// change these errors into `LexError`s later.
98 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
99 impl FromStr for TokenStream {
102 fn from_str(src: &str) -> Result<TokenStream, LexError> {
103 Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
107 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
108 // based on it (the reverse of the usual relationship between the two).
109 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
110 impl ToString for TokenStream {
111 fn to_string(&self) -> String {
116 /// Prints the token stream as a string that is supposed to be losslessly convertible back
117 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
118 /// with `Delimiter::None` delimiters and negative numeric literals.
119 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
120 impl fmt::Display for TokenStream {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.write_str(&self.to_string())
126 /// Prints token in a form convenient for debugging.
127 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
128 impl fmt::Debug for TokenStream {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 f.write_str("TokenStream ")?;
131 f.debug_list().entries(self.clone()).finish()
135 #[unstable(feature = "proc_macro_quote", issue = "54722")]
136 pub use quote::{quote, quote_span};
138 /// Creates a token stream containing a single token tree.
139 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
140 impl From<TokenTree> for TokenStream {
141 fn from(tree: TokenTree) -> TokenStream {
142 TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
143 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
144 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
145 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
146 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0)
151 /// Collects a number of token trees into a single stream.
152 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
153 impl iter::FromIterator<TokenTree> for TokenStream {
154 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
155 trees.into_iter().map(TokenStream::from).collect()
159 /// A "flattening" operation on token streams, collects token trees
160 /// from multiple token streams into a single stream.
161 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
162 impl iter::FromIterator<TokenStream> for TokenStream {
163 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
164 let mut builder = bridge::client::TokenStreamBuilder::new();
165 streams.into_iter().for_each(|stream| builder.push(stream.0));
166 TokenStream(builder.build())
170 #[stable(feature = "token_stream_extend", since = "1.30.0")]
171 impl Extend<TokenTree> for TokenStream {
172 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
173 self.extend(trees.into_iter().map(TokenStream::from));
177 #[stable(feature = "token_stream_extend", since = "1.30.0")]
178 impl Extend<TokenStream> for TokenStream {
179 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
180 // FIXME(eddyb) Use an optimized implementation if/when possible.
181 *self = iter::once(mem::replace(self, Self::new())).chain(streams).collect();
185 /// Public implementation details for the `TokenStream` type, such as iterators.
186 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
187 pub mod token_stream {
188 use crate::{bridge, Group, Ident, Literal, Punct, TokenTree, TokenStream};
190 /// An iterator over `TokenStream`'s `TokenTree`s.
191 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
192 /// and returns whole groups as token trees.
194 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
195 pub struct IntoIter(bridge::client::TokenStreamIter);
197 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
198 impl Iterator for IntoIter {
199 type Item = TokenTree;
201 fn next(&mut self) -> Option<TokenTree> {
202 self.0.next().map(|tree| match tree {
203 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
204 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
205 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
206 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
211 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
212 impl IntoIterator for TokenStream {
213 type Item = TokenTree;
214 type IntoIter = IntoIter;
216 fn into_iter(self) -> IntoIter {
217 IntoIter(self.0.into_iter())
222 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
223 /// For example, `quote!(a + b)` will produce a expression, that, when evaluated, constructs
224 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
226 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
227 /// To quote `$` itself, use `$$`.
228 #[unstable(feature = "proc_macro_quote", issue = "54722")]
229 #[allow_internal_unstable(proc_macro_def_site)]
230 #[cfg_attr(not(bootstrap), rustc_builtin_macro)]
231 pub macro quote ($($t:tt)*) { /* compiler built-in */ }
233 #[unstable(feature = "proc_macro_internals", issue = "27812")]
237 /// A region of source code, along with macro expansion information.
238 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
239 #[derive(Copy, Clone)]
240 pub struct Span(bridge::client::Span);
242 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
243 impl !Send for Span {}
244 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
245 impl !Sync for Span {}
247 macro_rules! diagnostic_method {
248 ($name:ident, $level:expr) => (
249 /// Creates a new `Diagnostic` with the given `message` at the span
251 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
252 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
253 Diagnostic::spanned(self, $level, message)
259 /// A span that resolves at the macro definition site.
260 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
261 pub fn def_site() -> Span {
262 Span(bridge::client::Span::def_site())
265 /// The span of the invocation of the current procedural macro.
266 /// Identifiers created with this span will be resolved as if they were written
267 /// directly at the macro call location (call-site hygiene) and other code
268 /// at the macro call site will be able to refer to them as well.
269 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
270 pub fn call_site() -> Span {
271 Span(bridge::client::Span::call_site())
274 /// The original source file into which this span points.
275 #[unstable(feature = "proc_macro_span", issue = "54725")]
276 pub fn source_file(&self) -> SourceFile {
277 SourceFile(self.0.source_file())
280 /// The `Span` for the tokens in the previous macro expansion from which
281 /// `self` was generated from, if any.
282 #[unstable(feature = "proc_macro_span", issue = "54725")]
283 pub fn parent(&self) -> Option<Span> {
284 self.0.parent().map(Span)
287 /// The span for the origin source code that `self` was generated from. If
288 /// this `Span` wasn't generated from other macro expansions then the return
289 /// value is the same as `*self`.
290 #[unstable(feature = "proc_macro_span", issue = "54725")]
291 pub fn source(&self) -> Span {
292 Span(self.0.source())
295 /// Gets the starting line/column in the source file for this span.
296 #[unstable(feature = "proc_macro_span", issue = "54725")]
297 pub fn start(&self) -> LineColumn {
301 /// Gets the ending line/column in the source file for this span.
302 #[unstable(feature = "proc_macro_span", issue = "54725")]
303 pub fn end(&self) -> LineColumn {
307 /// Creates a new span encompassing `self` and `other`.
309 /// Returns `None` if `self` and `other` are from different files.
310 #[unstable(feature = "proc_macro_span", issue = "54725")]
311 pub fn join(&self, other: Span) -> Option<Span> {
312 self.0.join(other.0).map(Span)
315 /// Creates a new span with the same line/column information as `self` but
316 /// that resolves symbols as though it were at `other`.
317 #[unstable(feature = "proc_macro_span", issue = "54725")]
318 pub fn resolved_at(&self, other: Span) -> Span {
319 Span(self.0.resolved_at(other.0))
322 /// Creates a new span with the same name resolution behavior as `self` but
323 /// with the line/column information of `other`.
324 #[unstable(feature = "proc_macro_span", issue = "54725")]
325 pub fn located_at(&self, other: Span) -> Span {
326 other.resolved_at(*self)
329 /// Compares to spans to see if they're equal.
330 #[unstable(feature = "proc_macro_span", issue = "54725")]
331 pub fn eq(&self, other: &Span) -> bool {
335 /// Returns the source text behind a span. This preserves the original source
336 /// code, including spaces and comments. It only returns a result if the span
337 /// corresponds to real source code.
339 /// Note: The observable result of a macro should only rely on the tokens and
340 /// not on this source text. The result of this function is a best effort to
341 /// be used for diagnostics only.
342 #[unstable(feature = "proc_macro_span", issue = "54725")]
343 pub fn source_text(&self) -> Option<String> {
347 diagnostic_method!(error, Level::Error);
348 diagnostic_method!(warning, Level::Warning);
349 diagnostic_method!(note, Level::Note);
350 diagnostic_method!(help, Level::Help);
353 /// Prints a span in a form convenient for debugging.
354 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
355 impl fmt::Debug for Span {
356 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361 /// A line-column pair representing the start or end of a `Span`.
362 #[unstable(feature = "proc_macro_span", issue = "54725")]
363 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
364 pub struct LineColumn {
365 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
366 #[unstable(feature = "proc_macro_span", issue = "54725")]
368 /// The 0-indexed column (in UTF-8 characters) in the source file on which
369 /// the span starts or ends (inclusive).
370 #[unstable(feature = "proc_macro_span", issue = "54725")]
374 #[unstable(feature = "proc_macro_span", issue = "54725")]
375 impl !Send for LineColumn {}
376 #[unstable(feature = "proc_macro_span", issue = "54725")]
377 impl !Sync for LineColumn {}
379 /// The source file of a given `Span`.
380 #[unstable(feature = "proc_macro_span", issue = "54725")]
382 pub struct SourceFile(bridge::client::SourceFile);
385 /// Gets the path to this source file.
388 /// If the code span associated with this `SourceFile` was generated by an external macro, this
389 /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
391 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
392 /// the command line, the path as given may not actually be valid.
394 /// [`is_real`]: #method.is_real
395 #[unstable(feature = "proc_macro_span", issue = "54725")]
396 pub fn path(&self) -> PathBuf {
397 PathBuf::from(self.0.path())
400 /// Returns `true` if this source file is a real source file, and not generated by an external
401 /// macro's expansion.
402 #[unstable(feature = "proc_macro_span", issue = "54725")]
403 pub fn is_real(&self) -> bool {
404 // This is a hack until intercrate spans are implemented and we can have real source files
405 // for spans generated in external macros.
406 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
412 #[unstable(feature = "proc_macro_span", issue = "54725")]
413 impl fmt::Debug for SourceFile {
414 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415 f.debug_struct("SourceFile")
416 .field("path", &self.path())
417 .field("is_real", &self.is_real())
422 #[unstable(feature = "proc_macro_span", issue = "54725")]
423 impl PartialEq for SourceFile {
424 fn eq(&self, other: &Self) -> bool {
429 #[unstable(feature = "proc_macro_span", issue = "54725")]
430 impl Eq for SourceFile {}
432 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
433 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
436 /// A token stream surrounded by bracket delimiters.
437 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
439 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
443 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
445 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
448 /// A single punctuation character (`+`, `,`, `$`, etc.).
449 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
451 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
454 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
455 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
457 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
462 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
463 impl !Send for TokenTree {}
464 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
465 impl !Sync for TokenTree {}
468 /// Returns the span of this tree, delegating to the `span` method of
469 /// the contained token or a delimited stream.
470 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
471 pub fn span(&self) -> Span {
473 TokenTree::Group(ref t) => t.span(),
474 TokenTree::Ident(ref t) => t.span(),
475 TokenTree::Punct(ref t) => t.span(),
476 TokenTree::Literal(ref t) => t.span(),
480 /// Configures the span for *only this token*.
482 /// Note that if this token is a `Group` then this method will not configure
483 /// the span of each of the internal tokens, this will simply delegate to
484 /// the `set_span` method of each variant.
485 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
486 pub fn set_span(&mut self, span: Span) {
488 TokenTree::Group(ref mut t) => t.set_span(span),
489 TokenTree::Ident(ref mut t) => t.set_span(span),
490 TokenTree::Punct(ref mut t) => t.set_span(span),
491 TokenTree::Literal(ref mut t) => t.set_span(span),
496 /// Prints token tree in a form convenient for debugging.
497 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
498 impl fmt::Debug for TokenTree {
499 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500 // Each of these has the name in the struct type in the derived debug,
501 // so don't bother with an extra layer of indirection
503 TokenTree::Group(ref tt) => tt.fmt(f),
504 TokenTree::Ident(ref tt) => tt.fmt(f),
505 TokenTree::Punct(ref tt) => tt.fmt(f),
506 TokenTree::Literal(ref tt) => tt.fmt(f),
511 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
512 impl From<Group> for TokenTree {
513 fn from(g: Group) -> TokenTree {
518 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
519 impl From<Ident> for TokenTree {
520 fn from(g: Ident) -> TokenTree {
525 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
526 impl From<Punct> for TokenTree {
527 fn from(g: Punct) -> TokenTree {
532 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
533 impl From<Literal> for TokenTree {
534 fn from(g: Literal) -> TokenTree {
535 TokenTree::Literal(g)
539 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
540 // based on it (the reverse of the usual relationship between the two).
541 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
542 impl ToString for TokenTree {
543 fn to_string(&self) -> String {
545 TokenTree::Group(ref t) => t.to_string(),
546 TokenTree::Ident(ref t) => t.to_string(),
547 TokenTree::Punct(ref t) => t.to_string(),
548 TokenTree::Literal(ref t) => t.to_string(),
553 /// Prints the token tree as a string that is supposed to be losslessly convertible back
554 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
555 /// with `Delimiter::None` delimiters and negative numeric literals.
556 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
557 impl fmt::Display for TokenTree {
558 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
559 f.write_str(&self.to_string())
563 /// A delimited token stream.
565 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
567 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
568 pub struct Group(bridge::client::Group);
570 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
571 impl !Send for Group {}
572 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
573 impl !Sync for Group {}
575 /// Describes how a sequence of token trees is delimited.
576 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
577 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
580 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
583 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
586 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
589 /// An implicit delimiter, that may, for example, appear around tokens coming from a
590 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
591 /// `$var * 3` where `$var` is `1 + 2`.
592 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
593 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
598 /// Creates a new `Group` with the given delimiter and token stream.
600 /// This constructor will set the span for this group to
601 /// `Span::call_site()`. To change the span you can use the `set_span`
603 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
604 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
605 Group(bridge::client::Group::new(delimiter, stream.0))
608 /// Returns the delimiter of this `Group`
609 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
610 pub fn delimiter(&self) -> Delimiter {
614 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
616 /// Note that the returned token stream does not include the delimiter
618 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
619 pub fn stream(&self) -> TokenStream {
620 TokenStream(self.0.stream())
623 /// Returns the span for the delimiters of this token stream, spanning the
627 /// pub fn span(&self) -> Span {
630 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
631 pub fn span(&self) -> Span {
635 /// Returns the span pointing to the opening delimiter of this group.
638 /// pub fn span_open(&self) -> Span {
641 #[unstable(feature = "proc_macro_span", issue = "54725")]
642 pub fn span_open(&self) -> Span {
643 Span(self.0.span_open())
646 /// Returns the span pointing to the closing delimiter of this group.
649 /// pub fn span_close(&self) -> Span {
652 #[unstable(feature = "proc_macro_span", issue = "54725")]
653 pub fn span_close(&self) -> Span {
654 Span(self.0.span_close())
657 /// Configures the span for this `Group`'s delimiters, but not its internal
660 /// This method will **not** set the span of all the internal tokens spanned
661 /// by this group, but rather it will only set the span of the delimiter
662 /// tokens at the level of the `Group`.
663 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
664 pub fn set_span(&mut self, span: Span) {
665 self.0.set_span(span.0);
669 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
670 // based on it (the reverse of the usual relationship between the two).
671 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
672 impl ToString for Group {
673 fn to_string(&self) -> String {
674 TokenStream::from(TokenTree::from(self.clone())).to_string()
678 /// Prints the group as a string that should be losslessly convertible back
679 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
680 /// with `Delimiter::None` delimiters.
681 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
682 impl fmt::Display for Group {
683 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
684 f.write_str(&self.to_string())
688 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
689 impl fmt::Debug for Group {
690 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
691 f.debug_struct("Group")
692 .field("delimiter", &self.delimiter())
693 .field("stream", &self.stream())
694 .field("span", &self.span())
699 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
701 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
702 /// forms of `Spacing` returned.
703 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
705 pub struct Punct(bridge::client::Punct);
707 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
708 impl !Send for Punct {}
709 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
710 impl !Sync for Punct {}
712 /// Whether an `Punct` is followed immediately by another `Punct` or
713 /// followed by another token or whitespace.
714 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
715 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
717 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
718 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
720 /// e.g., `+` is `Joint` in `+=` or `'#`.
721 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
722 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
727 /// Creates a new `Punct` from the given character and spacing.
728 /// The `ch` argument must be a valid punctuation character permitted by the language,
729 /// otherwise the function will panic.
731 /// The returned `Punct` will have the default span of `Span::call_site()`
732 /// which can be further configured with the `set_span` method below.
733 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
734 pub fn new(ch: char, spacing: Spacing) -> Punct {
735 Punct(bridge::client::Punct::new(ch, spacing))
738 /// Returns the value of this punctuation character as `char`.
739 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
740 pub fn as_char(&self) -> char {
744 /// Returns the spacing of this punctuation character, indicating whether it's immediately
745 /// followed by another `Punct` in the token stream, so they can potentially be combined into
746 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
747 /// (`Alone`) so the operator has certainly ended.
748 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
749 pub fn spacing(&self) -> Spacing {
753 /// Returns the span for this punctuation character.
754 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
755 pub fn span(&self) -> Span {
759 /// Configure the span for this punctuation character.
760 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
761 pub fn set_span(&mut self, span: Span) {
762 self.0 = self.0.with_span(span.0);
766 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
767 // based on it (the reverse of the usual relationship between the two).
768 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
769 impl ToString for Punct {
770 fn to_string(&self) -> String {
771 TokenStream::from(TokenTree::from(self.clone())).to_string()
775 /// Prints the punctuation character as a string that should be losslessly convertible
776 /// back into the same character.
777 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
778 impl fmt::Display for Punct {
779 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
780 f.write_str(&self.to_string())
784 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
785 impl fmt::Debug for Punct {
786 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
787 f.debug_struct("Punct")
788 .field("ch", &self.as_char())
789 .field("spacing", &self.spacing())
790 .field("span", &self.span())
795 /// An identifier (`ident`).
797 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
798 pub struct Ident(bridge::client::Ident);
801 /// Creates a new `Ident` with the given `string` as well as the specified
803 /// The `string` argument must be a valid identifier permitted by the
804 /// language, otherwise the function will panic.
806 /// Note that `span`, currently in rustc, configures the hygiene information
807 /// for this identifier.
809 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
810 /// meaning that identifiers created with this span will be resolved as if they were written
811 /// directly at the location of the macro call, and other code at the macro call site will be
812 /// able to refer to them as well.
814 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
815 /// meaning that identifiers created with this span will be resolved at the location of the
816 /// macro definition and other code at the macro call site will not be able to refer to them.
818 /// Due to the current importance of hygiene this constructor, unlike other
819 /// tokens, requires a `Span` to be specified at construction.
820 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
821 pub fn new(string: &str, span: Span) -> Ident {
822 Ident(bridge::client::Ident::new(string, span.0, false))
825 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
826 #[unstable(feature = "proc_macro_raw_ident", issue = "54723")]
827 pub fn new_raw(string: &str, span: Span) -> Ident {
828 Ident(bridge::client::Ident::new(string, span.0, true))
831 /// Returns the span of this `Ident`, encompassing the entire string returned
833 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
834 pub fn span(&self) -> Span {
838 /// Configures the span of this `Ident`, possibly changing its hygiene context.
839 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
840 pub fn set_span(&mut self, span: Span) {
841 self.0 = self.0.with_span(span.0);
845 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
846 // based on it (the reverse of the usual relationship between the two).
847 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
848 impl ToString for Ident {
849 fn to_string(&self) -> String {
850 TokenStream::from(TokenTree::from(self.clone())).to_string()
854 /// Prints the identifier as a string that should be losslessly convertible
855 /// back into the same identifier.
856 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
857 impl fmt::Display for Ident {
858 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
859 f.write_str(&self.to_string())
863 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
864 impl fmt::Debug for Ident {
865 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
866 f.debug_struct("Ident")
867 .field("ident", &self.to_string())
868 .field("span", &self.span())
873 /// A literal string (`"hello"`), byte string (`b"hello"`),
874 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
875 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
876 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
878 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
879 pub struct Literal(bridge::client::Literal);
881 macro_rules! suffixed_int_literals {
882 ($($name:ident => $kind:ident,)*) => ($(
883 /// Creates a new suffixed integer literal with the specified value.
885 /// This function will create an integer like `1u32` where the integer
886 /// value specified is the first part of the token and the integral is
887 /// also suffixed at the end.
888 /// Literals created from negative numbers may not survive round-trips through
889 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
891 /// Literals created through this method have the `Span::call_site()`
892 /// span by default, which can be configured with the `set_span` method
894 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
895 pub fn $name(n: $kind) -> Literal {
896 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
901 macro_rules! unsuffixed_int_literals {
902 ($($name:ident => $kind:ident,)*) => ($(
903 /// Creates a new unsuffixed integer literal with the specified value.
905 /// This function will create an integer like `1` where the integer
906 /// value specified is the first part of the token. No suffix is
907 /// specified on this token, meaning that invocations like
908 /// `Literal::i8_unsuffixed(1)` are equivalent to
909 /// `Literal::u32_unsuffixed(1)`.
910 /// Literals created from negative numbers may not survive rountrips through
911 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
913 /// Literals created through this method have the `Span::call_site()`
914 /// span by default, which can be configured with the `set_span` method
916 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
917 pub fn $name(n: $kind) -> Literal {
918 Literal(bridge::client::Literal::integer(&n.to_string()))
924 suffixed_int_literals! {
929 u128_suffixed => u128,
930 usize_suffixed => usize,
935 i128_suffixed => i128,
936 isize_suffixed => isize,
939 unsuffixed_int_literals! {
941 u16_unsuffixed => u16,
942 u32_unsuffixed => u32,
943 u64_unsuffixed => u64,
944 u128_unsuffixed => u128,
945 usize_unsuffixed => usize,
947 i16_unsuffixed => i16,
948 i32_unsuffixed => i32,
949 i64_unsuffixed => i64,
950 i128_unsuffixed => i128,
951 isize_unsuffixed => isize,
954 /// Creates a new unsuffixed floating-point literal.
956 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
957 /// the float's value is emitted directly into the token but no suffix is
958 /// used, so it may be inferred to be a `f64` later in the compiler.
959 /// Literals created from negative numbers may not survive rountrips through
960 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
964 /// This function requires that the specified float is finite, for
965 /// example if it is infinity or NaN this function will panic.
966 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
967 pub fn f32_unsuffixed(n: f32) -> Literal {
969 panic!("Invalid float literal {}", n);
971 Literal(bridge::client::Literal::float(&n.to_string()))
974 /// Creates a new suffixed floating-point literal.
976 /// This constructor will create a literal like `1.0f32` where the value
977 /// specified is the preceding part of the token and `f32` is the suffix of
978 /// the token. This token will always be inferred to be an `f32` in the
980 /// Literals created from negative numbers may not survive rountrips through
981 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
985 /// This function requires that the specified float is finite, for
986 /// example if it is infinity or NaN this function will panic.
987 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
988 pub fn f32_suffixed(n: f32) -> Literal {
990 panic!("Invalid float literal {}", n);
992 Literal(bridge::client::Literal::f32(&n.to_string()))
995 /// Creates a new unsuffixed floating-point literal.
997 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
998 /// the float's value is emitted directly into the token but no suffix is
999 /// used, so it may be inferred to be a `f64` later in the compiler.
1000 /// Literals created from negative numbers may not survive rountrips through
1001 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1005 /// This function requires that the specified float is finite, for
1006 /// example if it is infinity or NaN this function will panic.
1007 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1008 pub fn f64_unsuffixed(n: f64) -> Literal {
1010 panic!("Invalid float literal {}", n);
1012 Literal(bridge::client::Literal::float(&n.to_string()))
1015 /// Creates a new suffixed floating-point literal.
1017 /// This constructor will create a literal like `1.0f64` where the value
1018 /// specified is the preceding part of the token and `f64` is the suffix of
1019 /// the token. This token will always be inferred to be an `f64` in the
1021 /// Literals created from negative numbers may not survive rountrips through
1022 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1026 /// This function requires that the specified float is finite, for
1027 /// example if it is infinity or NaN this function will panic.
1028 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1029 pub fn f64_suffixed(n: f64) -> Literal {
1031 panic!("Invalid float literal {}", n);
1033 Literal(bridge::client::Literal::f64(&n.to_string()))
1037 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1038 pub fn string(string: &str) -> Literal {
1039 Literal(bridge::client::Literal::string(string))
1042 /// Character literal.
1043 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1044 pub fn character(ch: char) -> Literal {
1045 Literal(bridge::client::Literal::character(ch))
1048 /// Byte string literal.
1049 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1050 pub fn byte_string(bytes: &[u8]) -> Literal {
1051 Literal(bridge::client::Literal::byte_string(bytes))
1054 /// Returns the span encompassing this literal.
1055 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1056 pub fn span(&self) -> Span {
1060 /// Configures the span associated for this literal.
1061 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1062 pub fn set_span(&mut self, span: Span) {
1063 self.0.set_span(span.0);
1066 /// Returns a `Span` that is a subset of `self.span()` containing only the
1067 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1068 /// span is outside the bounds of `self`.
1069 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1070 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1071 // occur elsewhere when the source text is printed.
1072 // FIXME(SergioBenitez): there is no way for the user to know what
1073 // `self.span()` actually maps to, so this method can currently only be
1074 // called blindly. For example, `to_string()` for the character 'c' returns
1075 // "'\u{63}'"; there is no way for the user to know whether the source text
1076 // was 'c' or whether it was '\u{63}'.
1077 #[unstable(feature = "proc_macro_span", issue = "54725")]
1078 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1079 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1080 fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1082 Bound::Included(x) => Bound::Included(x.clone()),
1083 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1084 Bound::Unbounded => Bound::Unbounded,
1089 cloned_bound(range.start_bound()),
1090 cloned_bound(range.end_bound()),
1095 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1096 // based on it (the reverse of the usual relationship between the two).
1097 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1098 impl ToString for Literal {
1099 fn to_string(&self) -> String {
1100 TokenStream::from(TokenTree::from(self.clone())).to_string()
1104 /// Prints the literal as a string that should be losslessly convertible
1105 /// back into the same literal (except for possible rounding for floating point literals).
1106 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1107 impl fmt::Display for Literal {
1108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109 f.write_str(&self.to_string())
1113 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1114 impl fmt::Debug for Literal {
1115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1116 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.