1 //! A support library for macro authors when defining new macros.
3 //! This library, provided by the standard distribution, provides the types
4 //! consumed in the interfaces of procedurally defined macro definitions such as
5 //! function-like macros `#[proc_macro]`, macro attributes `#[proc_macro_attribute]` and
6 //! custom derive attributes`#[proc_macro_derive]`.
8 //! See [the book] for more.
10 //! [the book]: ../book/ch19-06-macros.html#procedural-macros-for-generating-code-from-attributes
12 #![stable(feature = "proc_macro_lib", since = "1.15.0")]
13 #![deny(missing_docs)]
14 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
15 html_playground_url = "https://play.rust-lang.org/",
16 issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
17 test(no_crate_inject, attr(deny(warnings))),
18 test(attr(allow(dead_code, deprecated, unused_variables, unused_mut))))]
21 #![feature(staged_api)]
22 #![feature(allow_internal_unstable)]
24 #![feature(decl_macro)]
25 #![feature(extern_types)]
26 #![feature(in_band_lifetimes)]
27 #![feature(optin_builtin_traits)]
28 #![feature(non_exhaustive)]
29 #![feature(rustc_attrs)]
30 #![feature(specialization)]
32 #![recursion_limit="256"]
34 #[unstable(feature = "proc_macro_internals", issue = "27812")]
40 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
41 pub use diagnostic::{Diagnostic, Level, MultiSpan};
43 use std::{fmt, iter, mem};
44 use std::ops::{Bound, RangeBounds};
45 use std::path::PathBuf;
46 use std::str::FromStr;
48 /// The main type provided by this crate, representing an abstract stream of
49 /// tokens, or, more specifically, a sequence of token trees.
50 /// The type provide interfaces for iterating over those token trees and, conversely,
51 /// collecting a number of token trees into one stream.
53 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
54 /// and `#[proc_macro_derive]` definitions.
55 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
57 pub struct TokenStream(bridge::client::TokenStream);
59 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
60 impl !Send for TokenStream {}
61 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
62 impl !Sync for TokenStream {}
64 /// Error returned from `TokenStream::from_str`.
65 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
71 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
72 impl !Send for LexError {}
73 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
74 impl !Sync for LexError {}
77 /// Returns an empty `TokenStream` containing no token trees.
78 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
79 pub fn new() -> TokenStream {
80 TokenStream(bridge::client::TokenStream::new())
83 /// Checks if this `TokenStream` is empty.
84 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
85 pub fn is_empty(&self) -> bool {
90 /// Attempts to break the string into tokens and parse those tokens into a token stream.
91 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
92 /// or characters not existing in the language.
93 /// All tokens in the parsed stream get `Span::call_site()` spans.
95 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
96 /// change these errors into `LexError`s later.
97 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
98 impl FromStr for TokenStream {
101 fn from_str(src: &str) -> Result<TokenStream, LexError> {
102 Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
106 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
107 // based on it (the reverse of the usual relationship between the two).
108 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
109 impl ToString for TokenStream {
110 fn to_string(&self) -> String {
115 /// Prints the token stream as a string that is supposed to be losslessly convertible back
116 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
117 /// with `Delimiter::None` delimiters and negative numeric literals.
118 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
119 impl fmt::Display for TokenStream {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 f.write_str(&self.to_string())
125 /// Prints token in a form convenient for debugging.
126 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
127 impl fmt::Debug for TokenStream {
128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129 f.write_str("TokenStream ")?;
130 f.debug_list().entries(self.clone()).finish()
134 #[unstable(feature = "proc_macro_quote", issue = "54722")]
135 pub use quote::{quote, quote_span};
137 /// Creates a token stream containing a single token tree.
138 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
139 impl From<TokenTree> for TokenStream {
140 fn from(tree: TokenTree) -> TokenStream {
141 TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
142 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
143 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
144 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
145 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0)
150 /// Collects a number of token trees into a single stream.
151 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
152 impl iter::FromIterator<TokenTree> for TokenStream {
153 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
154 trees.into_iter().map(TokenStream::from).collect()
158 /// A "flattening" operation on token streams, collects token trees
159 /// from multiple token streams into a single stream.
160 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
161 impl iter::FromIterator<TokenStream> for TokenStream {
162 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
163 let mut builder = bridge::client::TokenStreamBuilder::new();
164 streams.into_iter().for_each(|stream| builder.push(stream.0));
165 TokenStream(builder.build())
169 #[stable(feature = "token_stream_extend", since = "1.30.0")]
170 impl Extend<TokenTree> for TokenStream {
171 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
172 self.extend(trees.into_iter().map(TokenStream::from));
176 #[stable(feature = "token_stream_extend", since = "1.30.0")]
177 impl Extend<TokenStream> for TokenStream {
178 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
179 // FIXME(eddyb) Use an optimized implementation if/when possible.
180 *self = iter::once(mem::replace(self, Self::new())).chain(streams).collect();
184 /// Public implementation details for the `TokenStream` type, such as iterators.
185 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
186 pub mod token_stream {
187 use crate::{bridge, Group, Ident, Literal, Punct, TokenTree, TokenStream};
189 /// An iterator over `TokenStream`'s `TokenTree`s.
190 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
191 /// and returns whole groups as token trees.
193 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
194 pub struct IntoIter(bridge::client::TokenStreamIter);
196 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
197 impl Iterator for IntoIter {
198 type Item = TokenTree;
200 fn next(&mut self) -> Option<TokenTree> {
201 self.0.next().map(|tree| match tree {
202 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
203 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
204 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
205 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
210 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
211 impl IntoIterator for TokenStream {
212 type Item = TokenTree;
213 type IntoIter = IntoIter;
215 fn into_iter(self) -> IntoIter {
216 IntoIter(self.0.into_iter())
221 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
222 /// For example, `quote!(a + b)` will produce a expression, that, when evaluated, constructs
223 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
225 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
226 /// To quote `$` itself, use `$$`.
227 #[unstable(feature = "proc_macro_quote", issue = "54722")]
228 #[allow_internal_unstable(proc_macro_def_site)]
229 #[rustc_builtin_macro]
230 pub macro quote ($($t:tt)*) { /* compiler built-in */ }
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 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
274 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
275 /// call site (everything else).
276 /// The span location is taken from the call-site.
277 #[unstable(feature = "proc_macro_mixed_site", issue = "65049")]
278 pub fn mixed_site() -> Span {
279 Span(bridge::client::Span::mixed_site())
282 /// The original source file into which this span points.
283 #[unstable(feature = "proc_macro_span", issue = "54725")]
284 pub fn source_file(&self) -> SourceFile {
285 SourceFile(self.0.source_file())
288 /// The `Span` for the tokens in the previous macro expansion from which
289 /// `self` was generated from, if any.
290 #[unstable(feature = "proc_macro_span", issue = "54725")]
291 pub fn parent(&self) -> Option<Span> {
292 self.0.parent().map(Span)
295 /// The span for the origin source code that `self` was generated from. If
296 /// this `Span` wasn't generated from other macro expansions then the return
297 /// value is the same as `*self`.
298 #[unstable(feature = "proc_macro_span", issue = "54725")]
299 pub fn source(&self) -> Span {
300 Span(self.0.source())
303 /// Gets the starting line/column in the source file for this span.
304 #[unstable(feature = "proc_macro_span", issue = "54725")]
305 pub fn start(&self) -> LineColumn {
309 /// Gets the ending line/column in the source file for this span.
310 #[unstable(feature = "proc_macro_span", issue = "54725")]
311 pub fn end(&self) -> LineColumn {
315 /// Creates a new span encompassing `self` and `other`.
317 /// Returns `None` if `self` and `other` are from different files.
318 #[unstable(feature = "proc_macro_span", issue = "54725")]
319 pub fn join(&self, other: Span) -> Option<Span> {
320 self.0.join(other.0).map(Span)
323 /// Creates a new span with the same line/column information as `self` but
324 /// that resolves symbols as though it were at `other`.
325 #[unstable(feature = "proc_macro_span", issue = "54725")]
326 pub fn resolved_at(&self, other: Span) -> Span {
327 Span(self.0.resolved_at(other.0))
330 /// Creates a new span with the same name resolution behavior as `self` but
331 /// with the line/column information of `other`.
332 #[unstable(feature = "proc_macro_span", issue = "54725")]
333 pub fn located_at(&self, other: Span) -> Span {
334 other.resolved_at(*self)
337 /// Compares to spans to see if they're equal.
338 #[unstable(feature = "proc_macro_span", issue = "54725")]
339 pub fn eq(&self, other: &Span) -> bool {
343 /// Returns the source text behind a span. This preserves the original source
344 /// code, including spaces and comments. It only returns a result if the span
345 /// corresponds to real source code.
347 /// Note: The observable result of a macro should only rely on the tokens and
348 /// not on this source text. The result of this function is a best effort to
349 /// be used for diagnostics only.
350 #[unstable(feature = "proc_macro_span", issue = "54725")]
351 pub fn source_text(&self) -> Option<String> {
355 diagnostic_method!(error, Level::Error);
356 diagnostic_method!(warning, Level::Warning);
357 diagnostic_method!(note, Level::Note);
358 diagnostic_method!(help, Level::Help);
361 /// Prints a span in a form convenient for debugging.
362 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
363 impl fmt::Debug for Span {
364 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369 /// A line-column pair representing the start or end of a `Span`.
370 #[unstable(feature = "proc_macro_span", issue = "54725")]
371 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
372 pub struct LineColumn {
373 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
374 #[unstable(feature = "proc_macro_span", issue = "54725")]
376 /// The 0-indexed column (in UTF-8 characters) in the source file on which
377 /// the span starts or ends (inclusive).
378 #[unstable(feature = "proc_macro_span", issue = "54725")]
382 #[unstable(feature = "proc_macro_span", issue = "54725")]
383 impl !Send for LineColumn {}
384 #[unstable(feature = "proc_macro_span", issue = "54725")]
385 impl !Sync for LineColumn {}
387 /// The source file of a given `Span`.
388 #[unstable(feature = "proc_macro_span", issue = "54725")]
390 pub struct SourceFile(bridge::client::SourceFile);
393 /// Gets the path to this source file.
396 /// If the code span associated with this `SourceFile` was generated by an external macro, this
397 /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
399 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
400 /// the command line, the path as given may not actually be valid.
402 /// [`is_real`]: #method.is_real
403 #[unstable(feature = "proc_macro_span", issue = "54725")]
404 pub fn path(&self) -> PathBuf {
405 PathBuf::from(self.0.path())
408 /// Returns `true` if this source file is a real source file, and not generated by an external
409 /// macro's expansion.
410 #[unstable(feature = "proc_macro_span", issue = "54725")]
411 pub fn is_real(&self) -> bool {
412 // This is a hack until intercrate spans are implemented and we can have real source files
413 // for spans generated in external macros.
414 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
420 #[unstable(feature = "proc_macro_span", issue = "54725")]
421 impl fmt::Debug for SourceFile {
422 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423 f.debug_struct("SourceFile")
424 .field("path", &self.path())
425 .field("is_real", &self.is_real())
430 #[unstable(feature = "proc_macro_span", issue = "54725")]
431 impl PartialEq for SourceFile {
432 fn eq(&self, other: &Self) -> bool {
437 #[unstable(feature = "proc_macro_span", issue = "54725")]
438 impl Eq for SourceFile {}
440 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
441 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
444 /// A token stream surrounded by bracket delimiters.
445 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
447 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
451 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
453 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
456 /// A single punctuation character (`+`, `,`, `$`, etc.).
457 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
459 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
462 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
463 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
465 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
470 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
471 impl !Send for TokenTree {}
472 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
473 impl !Sync for TokenTree {}
476 /// Returns the span of this tree, delegating to the `span` method of
477 /// the contained token or a delimited stream.
478 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
479 pub fn span(&self) -> Span {
481 TokenTree::Group(ref t) => t.span(),
482 TokenTree::Ident(ref t) => t.span(),
483 TokenTree::Punct(ref t) => t.span(),
484 TokenTree::Literal(ref t) => t.span(),
488 /// Configures the span for *only this token*.
490 /// Note that if this token is a `Group` then this method will not configure
491 /// the span of each of the internal tokens, this will simply delegate to
492 /// the `set_span` method of each variant.
493 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
494 pub fn set_span(&mut self, span: Span) {
496 TokenTree::Group(ref mut t) => t.set_span(span),
497 TokenTree::Ident(ref mut t) => t.set_span(span),
498 TokenTree::Punct(ref mut t) => t.set_span(span),
499 TokenTree::Literal(ref mut t) => t.set_span(span),
504 /// Prints token tree in a form convenient for debugging.
505 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
506 impl fmt::Debug for TokenTree {
507 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
508 // Each of these has the name in the struct type in the derived debug,
509 // so don't bother with an extra layer of indirection
511 TokenTree::Group(ref tt) => tt.fmt(f),
512 TokenTree::Ident(ref tt) => tt.fmt(f),
513 TokenTree::Punct(ref tt) => tt.fmt(f),
514 TokenTree::Literal(ref tt) => tt.fmt(f),
519 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
520 impl From<Group> for TokenTree {
521 fn from(g: Group) -> TokenTree {
526 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
527 impl From<Ident> for TokenTree {
528 fn from(g: Ident) -> TokenTree {
533 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
534 impl From<Punct> for TokenTree {
535 fn from(g: Punct) -> TokenTree {
540 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
541 impl From<Literal> for TokenTree {
542 fn from(g: Literal) -> TokenTree {
543 TokenTree::Literal(g)
547 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
548 // based on it (the reverse of the usual relationship between the two).
549 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
550 impl ToString for TokenTree {
551 fn to_string(&self) -> String {
553 TokenTree::Group(ref t) => t.to_string(),
554 TokenTree::Ident(ref t) => t.to_string(),
555 TokenTree::Punct(ref t) => t.to_string(),
556 TokenTree::Literal(ref t) => t.to_string(),
561 /// Prints the token tree as a string that is supposed to be losslessly convertible back
562 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
563 /// with `Delimiter::None` delimiters and negative numeric literals.
564 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
565 impl fmt::Display for TokenTree {
566 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
567 f.write_str(&self.to_string())
571 /// A delimited token stream.
573 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
575 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
576 pub struct Group(bridge::client::Group);
578 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
579 impl !Send for Group {}
580 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
581 impl !Sync for Group {}
583 /// Describes how a sequence of token trees is delimited.
584 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
585 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
588 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
591 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
594 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
597 /// An implicit delimiter, that may, for example, appear around tokens coming from a
598 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
599 /// `$var * 3` where `$var` is `1 + 2`.
600 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
601 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
606 /// Creates a new `Group` with the given delimiter and token stream.
608 /// This constructor will set the span for this group to
609 /// `Span::call_site()`. To change the span you can use the `set_span`
611 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
612 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
613 Group(bridge::client::Group::new(delimiter, stream.0))
616 /// Returns the delimiter of this `Group`
617 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
618 pub fn delimiter(&self) -> Delimiter {
622 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
624 /// Note that the returned token stream does not include the delimiter
626 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
627 pub fn stream(&self) -> TokenStream {
628 TokenStream(self.0.stream())
631 /// Returns the span for the delimiters of this token stream, spanning the
635 /// pub fn span(&self) -> Span {
638 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
639 pub fn span(&self) -> Span {
643 /// Returns the span pointing to the opening delimiter of this group.
646 /// pub fn span_open(&self) -> Span {
649 #[unstable(feature = "proc_macro_span", issue = "54725")]
650 pub fn span_open(&self) -> Span {
651 Span(self.0.span_open())
654 /// Returns the span pointing to the closing delimiter of this group.
657 /// pub fn span_close(&self) -> Span {
660 #[unstable(feature = "proc_macro_span", issue = "54725")]
661 pub fn span_close(&self) -> Span {
662 Span(self.0.span_close())
665 /// Configures the span for this `Group`'s delimiters, but not its internal
668 /// This method will **not** set the span of all the internal tokens spanned
669 /// by this group, but rather it will only set the span of the delimiter
670 /// tokens at the level of the `Group`.
671 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
672 pub fn set_span(&mut self, span: Span) {
673 self.0.set_span(span.0);
677 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
678 // based on it (the reverse of the usual relationship between the two).
679 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
680 impl ToString for Group {
681 fn to_string(&self) -> String {
682 TokenStream::from(TokenTree::from(self.clone())).to_string()
686 /// Prints the group as a string that should be losslessly convertible back
687 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
688 /// with `Delimiter::None` delimiters.
689 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
690 impl fmt::Display for Group {
691 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
692 f.write_str(&self.to_string())
696 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
697 impl fmt::Debug for Group {
698 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
699 f.debug_struct("Group")
700 .field("delimiter", &self.delimiter())
701 .field("stream", &self.stream())
702 .field("span", &self.span())
707 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
709 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
710 /// forms of `Spacing` returned.
711 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
713 pub struct Punct(bridge::client::Punct);
715 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
716 impl !Send for Punct {}
717 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
718 impl !Sync for Punct {}
720 /// Whether an `Punct` is followed immediately by another `Punct` or
721 /// followed by another token or whitespace.
722 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
723 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
725 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
726 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
728 /// e.g., `+` is `Joint` in `+=` or `'#`.
729 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
730 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
735 /// Creates a new `Punct` from the given character and spacing.
736 /// The `ch` argument must be a valid punctuation character permitted by the language,
737 /// otherwise the function will panic.
739 /// The returned `Punct` will have the default span of `Span::call_site()`
740 /// which can be further configured with the `set_span` method below.
741 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
742 pub fn new(ch: char, spacing: Spacing) -> Punct {
743 Punct(bridge::client::Punct::new(ch, spacing))
746 /// Returns the value of this punctuation character as `char`.
747 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
748 pub fn as_char(&self) -> char {
752 /// Returns the spacing of this punctuation character, indicating whether it's immediately
753 /// followed by another `Punct` in the token stream, so they can potentially be combined into
754 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
755 /// (`Alone`) so the operator has certainly ended.
756 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
757 pub fn spacing(&self) -> Spacing {
761 /// Returns the span for this punctuation character.
762 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
763 pub fn span(&self) -> Span {
767 /// Configure the span for this punctuation character.
768 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
769 pub fn set_span(&mut self, span: Span) {
770 self.0 = self.0.with_span(span.0);
774 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
775 // based on it (the reverse of the usual relationship between the two).
776 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
777 impl ToString for Punct {
778 fn to_string(&self) -> String {
779 TokenStream::from(TokenTree::from(self.clone())).to_string()
783 /// Prints the punctuation character as a string that should be losslessly convertible
784 /// back into the same character.
785 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
786 impl fmt::Display for Punct {
787 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
788 f.write_str(&self.to_string())
792 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
793 impl fmt::Debug for Punct {
794 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
795 f.debug_struct("Punct")
796 .field("ch", &self.as_char())
797 .field("spacing", &self.spacing())
798 .field("span", &self.span())
803 /// An identifier (`ident`).
805 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
806 pub struct Ident(bridge::client::Ident);
809 /// Creates a new `Ident` with the given `string` as well as the specified
811 /// The `string` argument must be a valid identifier permitted by the
812 /// language, otherwise the function will panic.
814 /// Note that `span`, currently in rustc, configures the hygiene information
815 /// for this identifier.
817 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
818 /// meaning that identifiers created with this span will be resolved as if they were written
819 /// directly at the location of the macro call, and other code at the macro call site will be
820 /// able to refer to them as well.
822 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
823 /// meaning that identifiers created with this span will be resolved at the location of the
824 /// macro definition and other code at the macro call site will not be able to refer to them.
826 /// Due to the current importance of hygiene this constructor, unlike other
827 /// tokens, requires a `Span` to be specified at construction.
828 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
829 pub fn new(string: &str, span: Span) -> Ident {
830 Ident(bridge::client::Ident::new(string, span.0, false))
833 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
834 #[unstable(feature = "proc_macro_raw_ident", issue = "54723")]
835 pub fn new_raw(string: &str, span: Span) -> Ident {
836 Ident(bridge::client::Ident::new(string, span.0, true))
839 /// Returns the span of this `Ident`, encompassing the entire string returned
841 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
842 pub fn span(&self) -> Span {
846 /// Configures the span of this `Ident`, possibly changing its hygiene context.
847 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
848 pub fn set_span(&mut self, span: Span) {
849 self.0 = self.0.with_span(span.0);
853 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
854 // based on it (the reverse of the usual relationship between the two).
855 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
856 impl ToString for Ident {
857 fn to_string(&self) -> String {
858 TokenStream::from(TokenTree::from(self.clone())).to_string()
862 /// Prints the identifier as a string that should be losslessly convertible
863 /// back into the same identifier.
864 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
865 impl fmt::Display for Ident {
866 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
867 f.write_str(&self.to_string())
871 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
872 impl fmt::Debug for Ident {
873 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
874 f.debug_struct("Ident")
875 .field("ident", &self.to_string())
876 .field("span", &self.span())
881 /// A literal string (`"hello"`), byte string (`b"hello"`),
882 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
883 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
884 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
886 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
887 pub struct Literal(bridge::client::Literal);
889 macro_rules! suffixed_int_literals {
890 ($($name:ident => $kind:ident,)*) => ($(
891 /// Creates a new suffixed integer literal with the specified value.
893 /// This function will create an integer like `1u32` where the integer
894 /// value specified is the first part of the token and the integral is
895 /// also suffixed at the end.
896 /// Literals created from negative numbers may not survive round-trips through
897 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
899 /// Literals created through this method have the `Span::call_site()`
900 /// span by default, which can be configured with the `set_span` method
902 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
903 pub fn $name(n: $kind) -> Literal {
904 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
909 macro_rules! unsuffixed_int_literals {
910 ($($name:ident => $kind:ident,)*) => ($(
911 /// Creates a new unsuffixed integer literal with the specified value.
913 /// This function will create an integer like `1` where the integer
914 /// value specified is the first part of the token. No suffix is
915 /// specified on this token, meaning that invocations like
916 /// `Literal::i8_unsuffixed(1)` are equivalent to
917 /// `Literal::u32_unsuffixed(1)`.
918 /// Literals created from negative numbers may not survive rountrips through
919 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
921 /// Literals created through this method have the `Span::call_site()`
922 /// span by default, which can be configured with the `set_span` method
924 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
925 pub fn $name(n: $kind) -> Literal {
926 Literal(bridge::client::Literal::integer(&n.to_string()))
932 suffixed_int_literals! {
937 u128_suffixed => u128,
938 usize_suffixed => usize,
943 i128_suffixed => i128,
944 isize_suffixed => isize,
947 unsuffixed_int_literals! {
949 u16_unsuffixed => u16,
950 u32_unsuffixed => u32,
951 u64_unsuffixed => u64,
952 u128_unsuffixed => u128,
953 usize_unsuffixed => usize,
955 i16_unsuffixed => i16,
956 i32_unsuffixed => i32,
957 i64_unsuffixed => i64,
958 i128_unsuffixed => i128,
959 isize_unsuffixed => isize,
962 /// Creates a new unsuffixed floating-point literal.
964 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
965 /// the float's value is emitted directly into the token but no suffix is
966 /// used, so it may be inferred to be a `f64` later in the compiler.
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_unsuffixed(n: f32) -> Literal {
977 panic!("Invalid float literal {}", n);
979 Literal(bridge::client::Literal::float(&n.to_string()))
982 /// Creates a new suffixed floating-point literal.
984 /// This constructor will create a literal like `1.0f32` where the value
985 /// specified is the preceding part of the token and `f32` is the suffix of
986 /// the token. This token will always be inferred to be an `f32` in the
988 /// Literals created from negative numbers may not survive rountrips through
989 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
993 /// This function requires that the specified float is finite, for
994 /// example if it is infinity or NaN this function will panic.
995 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
996 pub fn f32_suffixed(n: f32) -> Literal {
998 panic!("Invalid float literal {}", n);
1000 Literal(bridge::client::Literal::f32(&n.to_string()))
1003 /// Creates a new unsuffixed floating-point literal.
1005 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1006 /// the float's value is emitted directly into the token but no suffix is
1007 /// used, so it may be inferred to be a `f64` later in the compiler.
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_unsuffixed(n: f64) -> Literal {
1018 panic!("Invalid float literal {}", n);
1020 Literal(bridge::client::Literal::float(&n.to_string()))
1023 /// Creates a new suffixed floating-point literal.
1025 /// This constructor will create a literal like `1.0f64` where the value
1026 /// specified is the preceding part of the token and `f64` is the suffix of
1027 /// the token. This token will always be inferred to be an `f64` in the
1029 /// Literals created from negative numbers may not survive rountrips through
1030 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1034 /// This function requires that the specified float is finite, for
1035 /// example if it is infinity or NaN this function will panic.
1036 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1037 pub fn f64_suffixed(n: f64) -> Literal {
1039 panic!("Invalid float literal {}", n);
1041 Literal(bridge::client::Literal::f64(&n.to_string()))
1045 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1046 pub fn string(string: &str) -> Literal {
1047 Literal(bridge::client::Literal::string(string))
1050 /// Character literal.
1051 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1052 pub fn character(ch: char) -> Literal {
1053 Literal(bridge::client::Literal::character(ch))
1056 /// Byte string literal.
1057 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1058 pub fn byte_string(bytes: &[u8]) -> Literal {
1059 Literal(bridge::client::Literal::byte_string(bytes))
1062 /// Returns the span encompassing this literal.
1063 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1064 pub fn span(&self) -> Span {
1068 /// Configures the span associated for this literal.
1069 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1070 pub fn set_span(&mut self, span: Span) {
1071 self.0.set_span(span.0);
1074 /// Returns a `Span` that is a subset of `self.span()` containing only the
1075 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1076 /// span is outside the bounds of `self`.
1077 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1078 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1079 // occur elsewhere when the source text is printed.
1080 // FIXME(SergioBenitez): there is no way for the user to know what
1081 // `self.span()` actually maps to, so this method can currently only be
1082 // called blindly. For example, `to_string()` for the character 'c' returns
1083 // "'\u{63}'"; there is no way for the user to know whether the source text
1084 // was 'c' or whether it was '\u{63}'.
1085 #[unstable(feature = "proc_macro_span", issue = "54725")]
1086 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1087 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1088 fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1090 Bound::Included(x) => Bound::Included(x.clone()),
1091 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1092 Bound::Unbounded => Bound::Unbounded,
1097 cloned_bound(range.start_bound()),
1098 cloned_bound(range.end_bound()),
1103 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1104 // based on it (the reverse of the usual relationship between the two).
1105 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1106 impl ToString for Literal {
1107 fn to_string(&self) -> String {
1108 TokenStream::from(TokenTree::from(self.clone())).to_string()
1112 /// Prints the literal as a string that should be losslessly convertible
1113 /// back into the same literal (except for possible rounding for floating point literals).
1114 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1115 impl fmt::Display for Literal {
1116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1117 f.write_str(&self.to_string())
1121 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1122 impl fmt::Debug for Literal {
1123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1124 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.