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)]
15 html_root_url = "https://doc.rust-lang.org/nightly/",
16 html_playground_url = "https://play.rust-lang.org/",
17 issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
18 test(no_crate_inject, attr(deny(warnings))),
19 test(attr(allow(dead_code, deprecated, unused_variables, unused_mut)))
22 #![feature(staged_api)]
23 #![feature(allow_internal_unstable)]
24 #![feature(decl_macro)]
25 #![feature(extern_types)]
26 #![feature(in_band_lifetimes)]
27 #![feature(optin_builtin_traits)]
28 #![feature(rustc_attrs)]
29 #![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::ops::{Bound, RangeBounds};
42 use std::path::PathBuf;
43 use std::str::FromStr;
44 use std::{fmt, iter, mem};
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, TokenStream, TokenTree};
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 `$$`.
225 #[unstable(feature = "proc_macro_quote", issue = "54722")]
226 #[allow_internal_unstable(proc_macro_def_site)]
227 #[rustc_builtin_macro]
228 pub macro quote($($t:tt)*) {
229 /* 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
419 #[unstable(feature = "proc_macro_span", issue = "54725")]
420 impl fmt::Debug for SourceFile {
421 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
422 f.debug_struct("SourceFile")
423 .field("path", &self.path())
424 .field("is_real", &self.is_real())
429 #[unstable(feature = "proc_macro_span", issue = "54725")]
430 impl PartialEq for SourceFile {
431 fn eq(&self, other: &Self) -> bool {
436 #[unstable(feature = "proc_macro_span", issue = "54725")]
437 impl Eq for SourceFile {}
439 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
440 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
443 /// A token stream surrounded by bracket delimiters.
444 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
445 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
447 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
448 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
449 /// A single punctuation character (`+`, `,`, `$`, etc.).
450 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
451 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
452 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
453 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
454 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
457 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
458 impl !Send for TokenTree {}
459 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
460 impl !Sync for TokenTree {}
463 /// Returns the span of this tree, delegating to the `span` method of
464 /// the contained token or a delimited stream.
465 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
466 pub fn span(&self) -> Span {
468 TokenTree::Group(ref t) => t.span(),
469 TokenTree::Ident(ref t) => t.span(),
470 TokenTree::Punct(ref t) => t.span(),
471 TokenTree::Literal(ref t) => t.span(),
475 /// Configures the span for *only this token*.
477 /// Note that if this token is a `Group` then this method will not configure
478 /// the span of each of the internal tokens, this will simply delegate to
479 /// the `set_span` method of each variant.
480 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
481 pub fn set_span(&mut self, span: Span) {
483 TokenTree::Group(ref mut t) => t.set_span(span),
484 TokenTree::Ident(ref mut t) => t.set_span(span),
485 TokenTree::Punct(ref mut t) => t.set_span(span),
486 TokenTree::Literal(ref mut t) => t.set_span(span),
491 /// Prints token tree in a form convenient for debugging.
492 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
493 impl fmt::Debug for TokenTree {
494 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
495 // Each of these has the name in the struct type in the derived debug,
496 // so don't bother with an extra layer of indirection
498 TokenTree::Group(ref tt) => tt.fmt(f),
499 TokenTree::Ident(ref tt) => tt.fmt(f),
500 TokenTree::Punct(ref tt) => tt.fmt(f),
501 TokenTree::Literal(ref tt) => tt.fmt(f),
506 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
507 impl From<Group> for TokenTree {
508 fn from(g: Group) -> TokenTree {
513 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
514 impl From<Ident> for TokenTree {
515 fn from(g: Ident) -> TokenTree {
520 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
521 impl From<Punct> for TokenTree {
522 fn from(g: Punct) -> TokenTree {
527 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
528 impl From<Literal> for TokenTree {
529 fn from(g: Literal) -> TokenTree {
530 TokenTree::Literal(g)
534 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
535 // based on it (the reverse of the usual relationship between the two).
536 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
537 impl ToString for TokenTree {
538 fn to_string(&self) -> String {
540 TokenTree::Group(ref t) => t.to_string(),
541 TokenTree::Ident(ref t) => t.to_string(),
542 TokenTree::Punct(ref t) => t.to_string(),
543 TokenTree::Literal(ref t) => t.to_string(),
548 /// Prints the token tree as a string that is supposed to be losslessly convertible back
549 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
550 /// with `Delimiter::None` delimiters and negative numeric literals.
551 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
552 impl fmt::Display for TokenTree {
553 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
554 f.write_str(&self.to_string())
558 /// A delimited token stream.
560 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
562 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
563 pub struct Group(bridge::client::Group);
565 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
566 impl !Send for Group {}
567 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
568 impl !Sync for Group {}
570 /// Describes how a sequence of token trees is delimited.
571 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
572 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
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 /// An implicit delimiter, that may, for example, appear around tokens coming from a
585 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
586 /// `$var * 3` where `$var` is `1 + 2`.
587 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
588 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
593 /// Creates a new `Group` with the given delimiter and token stream.
595 /// This constructor will set the span for this group to
596 /// `Span::call_site()`. To change the span you can use the `set_span`
598 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
599 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
600 Group(bridge::client::Group::new(delimiter, stream.0))
603 /// Returns the delimiter of this `Group`
604 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
605 pub fn delimiter(&self) -> Delimiter {
609 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
611 /// Note that the returned token stream does not include the delimiter
613 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
614 pub fn stream(&self) -> TokenStream {
615 TokenStream(self.0.stream())
618 /// Returns the span for the delimiters of this token stream, spanning the
622 /// pub fn span(&self) -> Span {
625 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
626 pub fn span(&self) -> Span {
630 /// Returns the span pointing to the opening delimiter of this group.
633 /// pub fn span_open(&self) -> Span {
636 #[unstable(feature = "proc_macro_span", issue = "54725")]
637 pub fn span_open(&self) -> Span {
638 Span(self.0.span_open())
641 /// Returns the span pointing to the closing delimiter of this group.
644 /// pub fn span_close(&self) -> Span {
647 #[unstable(feature = "proc_macro_span", issue = "54725")]
648 pub fn span_close(&self) -> Span {
649 Span(self.0.span_close())
652 /// Configures the span for this `Group`'s delimiters, but not its internal
655 /// This method will **not** set the span of all the internal tokens spanned
656 /// by this group, but rather it will only set the span of the delimiter
657 /// tokens at the level of the `Group`.
658 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
659 pub fn set_span(&mut self, span: Span) {
660 self.0.set_span(span.0);
664 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
665 // based on it (the reverse of the usual relationship between the two).
666 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
667 impl ToString for Group {
668 fn to_string(&self) -> String {
669 TokenStream::from(TokenTree::from(self.clone())).to_string()
673 /// Prints the group as a string that should be losslessly convertible back
674 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
675 /// with `Delimiter::None` delimiters.
676 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
677 impl fmt::Display for Group {
678 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
679 f.write_str(&self.to_string())
683 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
684 impl fmt::Debug for Group {
685 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
686 f.debug_struct("Group")
687 .field("delimiter", &self.delimiter())
688 .field("stream", &self.stream())
689 .field("span", &self.span())
694 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
696 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
697 /// forms of `Spacing` returned.
698 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
700 pub struct Punct(bridge::client::Punct);
702 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
703 impl !Send for Punct {}
704 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
705 impl !Sync for Punct {}
707 /// Whether an `Punct` is followed immediately by another `Punct` or
708 /// followed by another token or whitespace.
709 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
710 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
712 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
713 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
715 /// e.g., `+` is `Joint` in `+=` or `'#`.
716 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
717 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
722 /// Creates a new `Punct` from the given character and spacing.
723 /// The `ch` argument must be a valid punctuation character permitted by the language,
724 /// otherwise the function will panic.
726 /// The returned `Punct` will have the default span of `Span::call_site()`
727 /// which can be further configured with the `set_span` method below.
728 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
729 pub fn new(ch: char, spacing: Spacing) -> Punct {
730 Punct(bridge::client::Punct::new(ch, spacing))
733 /// Returns the value of this punctuation character as `char`.
734 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
735 pub fn as_char(&self) -> char {
739 /// Returns the spacing of this punctuation character, indicating whether it's immediately
740 /// followed by another `Punct` in the token stream, so they can potentially be combined into
741 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
742 /// (`Alone`) so the operator has certainly ended.
743 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
744 pub fn spacing(&self) -> Spacing {
748 /// Returns the span for this punctuation character.
749 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
750 pub fn span(&self) -> Span {
754 /// Configure the span for this punctuation character.
755 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
756 pub fn set_span(&mut self, span: Span) {
757 self.0 = self.0.with_span(span.0);
761 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
762 // based on it (the reverse of the usual relationship between the two).
763 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
764 impl ToString for Punct {
765 fn to_string(&self) -> String {
766 TokenStream::from(TokenTree::from(self.clone())).to_string()
770 /// Prints the punctuation character as a string that should be losslessly convertible
771 /// back into the same character.
772 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
773 impl fmt::Display for Punct {
774 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
775 f.write_str(&self.to_string())
779 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
780 impl fmt::Debug for Punct {
781 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
782 f.debug_struct("Punct")
783 .field("ch", &self.as_char())
784 .field("spacing", &self.spacing())
785 .field("span", &self.span())
790 /// An identifier (`ident`).
792 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
793 pub struct Ident(bridge::client::Ident);
796 /// Creates a new `Ident` with the given `string` as well as the specified
798 /// The `string` argument must be a valid identifier permitted by the
799 /// language, otherwise the function will panic.
801 /// Note that `span`, currently in rustc, configures the hygiene information
802 /// for this identifier.
804 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
805 /// meaning that identifiers created with this span will be resolved as if they were written
806 /// directly at the location of the macro call, and other code at the macro call site will be
807 /// able to refer to them as well.
809 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
810 /// meaning that identifiers created with this span will be resolved at the location of the
811 /// macro definition and other code at the macro call site will not be able to refer to them.
813 /// Due to the current importance of hygiene this constructor, unlike other
814 /// tokens, requires a `Span` to be specified at construction.
815 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
816 pub fn new(string: &str, span: Span) -> Ident {
817 Ident(bridge::client::Ident::new(string, span.0, false))
820 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
821 #[unstable(feature = "proc_macro_raw_ident", issue = "54723")]
822 pub fn new_raw(string: &str, span: Span) -> Ident {
823 Ident(bridge::client::Ident::new(string, span.0, true))
826 /// Returns the span of this `Ident`, encompassing the entire string returned
828 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
829 pub fn span(&self) -> Span {
833 /// Configures the span of this `Ident`, possibly changing its hygiene context.
834 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
835 pub fn set_span(&mut self, span: Span) {
836 self.0 = self.0.with_span(span.0);
840 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
841 // based on it (the reverse of the usual relationship between the two).
842 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
843 impl ToString for Ident {
844 fn to_string(&self) -> String {
845 TokenStream::from(TokenTree::from(self.clone())).to_string()
849 /// Prints the identifier as a string that should be losslessly convertible
850 /// back into the same identifier.
851 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
852 impl fmt::Display for Ident {
853 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
854 f.write_str(&self.to_string())
858 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
859 impl fmt::Debug for Ident {
860 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
861 f.debug_struct("Ident")
862 .field("ident", &self.to_string())
863 .field("span", &self.span())
868 /// A literal string (`"hello"`), byte string (`b"hello"`),
869 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
870 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
871 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
873 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
874 pub struct Literal(bridge::client::Literal);
876 macro_rules! suffixed_int_literals {
877 ($($name:ident => $kind:ident,)*) => ($(
878 /// Creates a new suffixed integer literal with the specified value.
880 /// This function will create an integer like `1u32` where the integer
881 /// value specified is the first part of the token and the integral is
882 /// also suffixed at the end.
883 /// Literals created from negative numbers may not survive round-trips through
884 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
886 /// Literals created through this method have the `Span::call_site()`
887 /// span by default, which can be configured with the `set_span` method
889 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
890 pub fn $name(n: $kind) -> Literal {
891 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
896 macro_rules! unsuffixed_int_literals {
897 ($($name:ident => $kind:ident,)*) => ($(
898 /// Creates a new unsuffixed integer literal with the specified value.
900 /// This function will create an integer like `1` where the integer
901 /// value specified is the first part of the token. No suffix is
902 /// specified on this token, meaning that invocations like
903 /// `Literal::i8_unsuffixed(1)` are equivalent to
904 /// `Literal::u32_unsuffixed(1)`.
905 /// Literals created from negative numbers may not survive rountrips through
906 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
908 /// Literals created through this method have the `Span::call_site()`
909 /// span by default, which can be configured with the `set_span` method
911 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
912 pub fn $name(n: $kind) -> Literal {
913 Literal(bridge::client::Literal::integer(&n.to_string()))
919 suffixed_int_literals! {
924 u128_suffixed => u128,
925 usize_suffixed => usize,
930 i128_suffixed => i128,
931 isize_suffixed => isize,
934 unsuffixed_int_literals! {
936 u16_unsuffixed => u16,
937 u32_unsuffixed => u32,
938 u64_unsuffixed => u64,
939 u128_unsuffixed => u128,
940 usize_unsuffixed => usize,
942 i16_unsuffixed => i16,
943 i32_unsuffixed => i32,
944 i64_unsuffixed => i64,
945 i128_unsuffixed => i128,
946 isize_unsuffixed => isize,
949 /// Creates a new unsuffixed floating-point literal.
951 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
952 /// the float's value is emitted directly into the token but no suffix is
953 /// used, so it may be inferred to be a `f64` later in the compiler.
954 /// Literals created from negative numbers may not survive rountrips through
955 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
959 /// This function requires that the specified float is finite, for
960 /// example if it is infinity or NaN this function will panic.
961 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
962 pub fn f32_unsuffixed(n: f32) -> Literal {
964 panic!("Invalid float literal {}", n);
966 Literal(bridge::client::Literal::float(&n.to_string()))
969 /// Creates a new suffixed floating-point literal.
971 /// This constructor will create a literal like `1.0f32` where the value
972 /// specified is the preceding part of the token and `f32` is the suffix of
973 /// the token. This token will always be inferred to be an `f32` in the
975 /// Literals created from negative numbers may not survive rountrips through
976 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
980 /// This function requires that the specified float is finite, for
981 /// example if it is infinity or NaN this function will panic.
982 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
983 pub fn f32_suffixed(n: f32) -> Literal {
985 panic!("Invalid float literal {}", n);
987 Literal(bridge::client::Literal::f32(&n.to_string()))
990 /// Creates a new unsuffixed floating-point literal.
992 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
993 /// the float's value is emitted directly into the token but no suffix is
994 /// used, so it may be inferred to be a `f64` later in the compiler.
995 /// Literals created from negative numbers may not survive rountrips through
996 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1000 /// This function requires that the specified float is finite, for
1001 /// example if it is infinity or NaN this function will panic.
1002 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1003 pub fn f64_unsuffixed(n: f64) -> Literal {
1005 panic!("Invalid float literal {}", n);
1007 Literal(bridge::client::Literal::float(&n.to_string()))
1010 /// Creates a new suffixed floating-point literal.
1012 /// This constructor will create a literal like `1.0f64` where the value
1013 /// specified is the preceding part of the token and `f64` is the suffix of
1014 /// the token. This token will always be inferred to be an `f64` in the
1016 /// Literals created from negative numbers may not survive rountrips through
1017 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1021 /// This function requires that the specified float is finite, for
1022 /// example if it is infinity or NaN this function will panic.
1023 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1024 pub fn f64_suffixed(n: f64) -> Literal {
1026 panic!("Invalid float literal {}", n);
1028 Literal(bridge::client::Literal::f64(&n.to_string()))
1032 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1033 pub fn string(string: &str) -> Literal {
1034 Literal(bridge::client::Literal::string(string))
1037 /// Character literal.
1038 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1039 pub fn character(ch: char) -> Literal {
1040 Literal(bridge::client::Literal::character(ch))
1043 /// Byte string literal.
1044 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1045 pub fn byte_string(bytes: &[u8]) -> Literal {
1046 Literal(bridge::client::Literal::byte_string(bytes))
1049 /// Returns the span encompassing this literal.
1050 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1051 pub fn span(&self) -> Span {
1055 /// Configures the span associated for this literal.
1056 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1057 pub fn set_span(&mut self, span: Span) {
1058 self.0.set_span(span.0);
1061 /// Returns a `Span` that is a subset of `self.span()` containing only the
1062 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1063 /// span is outside the bounds of `self`.
1064 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1065 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1066 // occur elsewhere when the source text is printed.
1067 // FIXME(SergioBenitez): there is no way for the user to know what
1068 // `self.span()` actually maps to, so this method can currently only be
1069 // called blindly. For example, `to_string()` for the character 'c' returns
1070 // "'\u{63}'"; there is no way for the user to know whether the source text
1071 // was 'c' or whether it was '\u{63}'.
1072 #[unstable(feature = "proc_macro_span", issue = "54725")]
1073 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1074 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1075 fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1077 Bound::Included(x) => Bound::Included(x.clone()),
1078 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1079 Bound::Unbounded => Bound::Unbounded,
1083 self.0.subspan(cloned_bound(range.start_bound()), cloned_bound(range.end_bound())).map(Span)
1087 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1088 // based on it (the reverse of the usual relationship between the two).
1089 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1090 impl ToString for Literal {
1091 fn to_string(&self) -> String {
1092 TokenStream::from(TokenTree::from(self.clone())).to_string()
1096 /// Prints the literal as a string that should be losslessly convertible
1097 /// back into the same literal (except for possible rounding for floating point literals).
1098 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1099 impl fmt::Display for Literal {
1100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1101 f.write_str(&self.to_string())
1105 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1106 impl fmt::Debug for Literal {
1107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1108 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.