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))))]
20 #![deny(rust_2018_idioms)]
23 #![feature(staged_api)]
25 #![feature(extern_types)]
26 #![feature(in_band_lifetimes)]
27 #![feature(optin_builtin_traits)]
28 #![feature(non_exhaustive)]
29 #![feature(specialization)]
31 #![recursion_limit="256"]
33 #[unstable(feature = "proc_macro_internals", issue = "27812")]
39 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
40 pub use diagnostic::{Diagnostic, Level, MultiSpan};
42 use std::{fmt, iter, mem};
43 use std::ops::{Bound, RangeBounds};
44 use std::path::PathBuf;
45 use std::str::FromStr;
47 /// The main type provided by this crate, representing an abstract stream of
48 /// tokens, or, more specifically, a sequence of token trees.
49 /// The type provide interfaces for iterating over those token trees and, conversely,
50 /// collecting a number of token trees into one stream.
52 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
53 /// and `#[proc_macro_derive]` definitions.
54 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
56 pub struct TokenStream(bridge::client::TokenStream);
58 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
59 impl !Send for TokenStream {}
60 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
61 impl !Sync for TokenStream {}
63 /// Error returned from `TokenStream::from_str`.
64 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
70 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
71 impl !Send for LexError {}
72 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
73 impl !Sync for LexError {}
76 /// Returns an empty `TokenStream` containing no token trees.
77 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
78 pub fn new() -> TokenStream {
79 TokenStream(bridge::client::TokenStream::new())
82 /// Checks if this `TokenStream` is empty.
83 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
84 pub fn is_empty(&self) -> bool {
89 /// Attempts to break the string into tokens and parse those tokens into a token stream.
90 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
91 /// or characters not existing in the language.
92 /// All tokens in the parsed stream get `Span::call_site()` spans.
94 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
95 /// change these errors into `LexError`s later.
96 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
97 impl FromStr for TokenStream {
100 fn from_str(src: &str) -> Result<TokenStream, LexError> {
101 Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
105 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
106 // based on it (the reverse of the usual relationship between the two).
107 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
108 impl ToString for TokenStream {
109 fn to_string(&self) -> String {
114 /// Prints the token stream as a string that is supposed to be losslessly convertible back
115 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
116 /// with `Delimiter::None` delimiters and negative numeric literals.
117 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
118 impl fmt::Display for TokenStream {
119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120 f.write_str(&self.to_string())
124 /// Prints token in a form convenient for debugging.
125 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
126 impl fmt::Debug for TokenStream {
127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128 f.write_str("TokenStream ")?;
129 f.debug_list().entries(self.clone()).finish()
133 #[unstable(feature = "proc_macro_quote", issue = "54722")]
134 pub use quote::{quote, quote_span};
136 /// Creates a token stream containing a single token tree.
137 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
138 impl From<TokenTree> for TokenStream {
139 fn from(tree: TokenTree) -> TokenStream {
140 TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
141 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
142 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
143 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
144 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0)
149 /// Collects a number of token trees into a single stream.
150 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
151 impl iter::FromIterator<TokenTree> for TokenStream {
152 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
153 trees.into_iter().map(TokenStream::from).collect()
157 /// A "flattening" operation on token streams, collects token trees
158 /// from multiple token streams into a single stream.
159 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
160 impl iter::FromIterator<TokenStream> for TokenStream {
161 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
162 let mut builder = bridge::client::TokenStreamBuilder::new();
163 for stream in streams {
164 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 `$$`.
229 /// This is a dummy macro, the actual implementation is in `quote::quote`.`
230 #[unstable(feature = "proc_macro_quote", issue = "54722")]
232 macro_rules! quote { () => {} }
234 #[unstable(feature = "proc_macro_internals", issue = "27812")]
238 /// A region of source code, along with macro expansion information.
239 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
240 #[derive(Copy, Clone)]
241 pub struct Span(bridge::client::Span);
243 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
244 impl !Send for Span {}
245 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
246 impl !Sync for Span {}
248 macro_rules! diagnostic_method {
249 ($name:ident, $level:expr) => (
250 /// Creates a new `Diagnostic` with the given `message` at the span
252 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
253 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
254 Diagnostic::spanned(self, $level, message)
260 /// A span that resolves at the macro definition site.
261 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
262 pub fn def_site() -> Span {
263 Span(bridge::client::Span::def_site())
266 /// The span of the invocation of the current procedural macro.
267 /// Identifiers created with this span will be resolved as if they were written
268 /// directly at the macro call location (call-site hygiene) and other code
269 /// at the macro call site will be able to refer to them as well.
270 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
271 pub fn call_site() -> Span {
272 Span(bridge::client::Span::call_site())
275 /// The original source file into which this span points.
276 #[unstable(feature = "proc_macro_span", issue = "54725")]
277 pub fn source_file(&self) -> SourceFile {
278 SourceFile(self.0.source_file())
281 /// The `Span` for the tokens in the previous macro expansion from which
282 /// `self` was generated from, if any.
283 #[unstable(feature = "proc_macro_span", issue = "54725")]
284 pub fn parent(&self) -> Option<Span> {
285 self.0.parent().map(Span)
288 /// The span for the origin source code that `self` was generated from. If
289 /// this `Span` wasn't generated from other macro expansions then the return
290 /// value is the same as `*self`.
291 #[unstable(feature = "proc_macro_span", issue = "54725")]
292 pub fn source(&self) -> Span {
293 Span(self.0.source())
296 /// Gets the starting line/column in the source file for this span.
297 #[unstable(feature = "proc_macro_span", issue = "54725")]
298 pub fn start(&self) -> LineColumn {
302 /// Gets the ending line/column in the source file for this span.
303 #[unstable(feature = "proc_macro_span", issue = "54725")]
304 pub fn end(&self) -> LineColumn {
308 /// Creates a new span encompassing `self` and `other`.
310 /// Returns `None` if `self` and `other` are from different files.
311 #[unstable(feature = "proc_macro_span", issue = "54725")]
312 pub fn join(&self, other: Span) -> Option<Span> {
313 self.0.join(other.0).map(Span)
316 /// Creates a new span with the same line/column information as `self` but
317 /// that resolves symbols as though it were at `other`.
318 #[unstable(feature = "proc_macro_span", issue = "54725")]
319 pub fn resolved_at(&self, other: Span) -> Span {
320 Span(self.0.resolved_at(other.0))
323 /// Creates a new span with the same name resolution behavior as `self` but
324 /// with the line/column information of `other`.
325 #[unstable(feature = "proc_macro_span", issue = "54725")]
326 pub fn located_at(&self, other: Span) -> Span {
327 other.resolved_at(*self)
330 /// Compares to spans to see if they're equal.
331 #[unstable(feature = "proc_macro_span", issue = "54725")]
332 pub fn eq(&self, other: &Span) -> bool {
336 diagnostic_method!(error, Level::Error);
337 diagnostic_method!(warning, Level::Warning);
338 diagnostic_method!(note, Level::Note);
339 diagnostic_method!(help, Level::Help);
342 /// Prints a span in a form convenient for debugging.
343 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
344 impl fmt::Debug for Span {
345 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350 /// A line-column pair representing the start or end of a `Span`.
351 #[unstable(feature = "proc_macro_span", issue = "54725")]
352 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
353 pub struct LineColumn {
354 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
355 #[unstable(feature = "proc_macro_span", issue = "54725")]
357 /// The 0-indexed column (in UTF-8 characters) in the source file on which
358 /// the span starts or ends (inclusive).
359 #[unstable(feature = "proc_macro_span", issue = "54725")]
363 #[unstable(feature = "proc_macro_span", issue = "54725")]
364 impl !Send for LineColumn {}
365 #[unstable(feature = "proc_macro_span", issue = "54725")]
366 impl !Sync for LineColumn {}
368 /// The source file of a given `Span`.
369 #[unstable(feature = "proc_macro_span", issue = "54725")]
371 pub struct SourceFile(bridge::client::SourceFile);
374 /// Gets the path to this source file.
377 /// If the code span associated with this `SourceFile` was generated by an external macro, this
378 /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
380 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
381 /// the command line, the path as given may not actually be valid.
383 /// [`is_real`]: #method.is_real
384 #[unstable(feature = "proc_macro_span", issue = "54725")]
385 pub fn path(&self) -> PathBuf {
386 PathBuf::from(self.0.path())
389 /// Returns `true` if this source file is a real source file, and not generated by an external
390 /// macro's expansion.
391 #[unstable(feature = "proc_macro_span", issue = "54725")]
392 pub fn is_real(&self) -> bool {
393 // This is a hack until intercrate spans are implemented and we can have real source files
394 // for spans generated in external macros.
395 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
401 #[unstable(feature = "proc_macro_span", issue = "54725")]
402 impl fmt::Debug for SourceFile {
403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404 f.debug_struct("SourceFile")
405 .field("path", &self.path())
406 .field("is_real", &self.is_real())
411 #[unstable(feature = "proc_macro_span", issue = "54725")]
412 impl PartialEq for SourceFile {
413 fn eq(&self, other: &Self) -> bool {
418 #[unstable(feature = "proc_macro_span", issue = "54725")]
419 impl Eq for SourceFile {}
421 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
422 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
425 /// A token stream surrounded by bracket delimiters.
426 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
428 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
432 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
434 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
437 /// A single punctuation character (`+`, `,`, `$`, etc.).
438 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
440 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
443 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
444 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
446 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
451 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
452 impl !Send for TokenTree {}
453 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
454 impl !Sync for TokenTree {}
457 /// Returns the span of this tree, delegating to the `span` method of
458 /// the contained token or a delimited stream.
459 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
460 pub fn span(&self) -> Span {
462 TokenTree::Group(ref t) => t.span(),
463 TokenTree::Ident(ref t) => t.span(),
464 TokenTree::Punct(ref t) => t.span(),
465 TokenTree::Literal(ref t) => t.span(),
469 /// Configures the span for *only this token*.
471 /// Note that if this token is a `Group` then this method will not configure
472 /// the span of each of the internal tokens, this will simply delegate to
473 /// the `set_span` method of each variant.
474 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
475 pub fn set_span(&mut self, span: Span) {
477 TokenTree::Group(ref mut t) => t.set_span(span),
478 TokenTree::Ident(ref mut t) => t.set_span(span),
479 TokenTree::Punct(ref mut t) => t.set_span(span),
480 TokenTree::Literal(ref mut t) => t.set_span(span),
485 /// Prints token tree in a form convenient for debugging.
486 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
487 impl fmt::Debug for TokenTree {
488 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
489 // Each of these has the name in the struct type in the derived debug,
490 // so don't bother with an extra layer of indirection
492 TokenTree::Group(ref tt) => tt.fmt(f),
493 TokenTree::Ident(ref tt) => tt.fmt(f),
494 TokenTree::Punct(ref tt) => tt.fmt(f),
495 TokenTree::Literal(ref tt) => tt.fmt(f),
500 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
501 impl From<Group> for TokenTree {
502 fn from(g: Group) -> TokenTree {
507 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
508 impl From<Ident> for TokenTree {
509 fn from(g: Ident) -> TokenTree {
514 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
515 impl From<Punct> for TokenTree {
516 fn from(g: Punct) -> TokenTree {
521 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
522 impl From<Literal> for TokenTree {
523 fn from(g: Literal) -> TokenTree {
524 TokenTree::Literal(g)
528 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
529 // based on it (the reverse of the usual relationship between the two).
530 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
531 impl ToString for TokenTree {
532 fn to_string(&self) -> String {
534 TokenTree::Group(ref t) => t.to_string(),
535 TokenTree::Ident(ref t) => t.to_string(),
536 TokenTree::Punct(ref t) => t.to_string(),
537 TokenTree::Literal(ref t) => t.to_string(),
542 /// Prints the token tree as a string that is supposed to be losslessly convertible back
543 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
544 /// with `Delimiter::None` delimiters and negative numeric literals.
545 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
546 impl fmt::Display for TokenTree {
547 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
548 f.write_str(&self.to_string())
552 /// A delimited token stream.
554 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
556 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
557 pub struct Group(bridge::client::Group);
559 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
560 impl !Send for Group {}
561 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
562 impl !Sync for Group {}
564 /// Describes how a sequence of token trees is delimited.
565 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
566 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
569 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
572 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
575 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
578 /// An implicit delimiter, that may, for example, appear around tokens coming from a
579 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
580 /// `$var * 3` where `$var` is `1 + 2`.
581 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
582 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
587 /// Creates a new `Group` with the given delimiter and token stream.
589 /// This constructor will set the span for this group to
590 /// `Span::call_site()`. To change the span you can use the `set_span`
592 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
593 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
594 Group(bridge::client::Group::new(delimiter, stream.0))
597 /// Returns the delimiter of this `Group`
598 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
599 pub fn delimiter(&self) -> Delimiter {
603 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
605 /// Note that the returned token stream does not include the delimiter
607 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
608 pub fn stream(&self) -> TokenStream {
609 TokenStream(self.0.stream())
612 /// Returns the span for the delimiters of this token stream, spanning the
616 /// pub fn span(&self) -> Span {
619 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
620 pub fn span(&self) -> Span {
624 /// Returns the span pointing to the opening delimiter of this group.
627 /// pub fn span_open(&self) -> Span {
630 #[unstable(feature = "proc_macro_span", issue = "54725")]
631 pub fn span_open(&self) -> Span {
632 Span(self.0.span_open())
635 /// Returns the span pointing to the closing delimiter of this group.
638 /// pub fn span_close(&self) -> Span {
641 #[unstable(feature = "proc_macro_span", issue = "54725")]
642 pub fn span_close(&self) -> Span {
643 Span(self.0.span_close())
646 /// Configures the span for this `Group`'s delimiters, but not its internal
649 /// This method will **not** set the span of all the internal tokens spanned
650 /// by this group, but rather it will only set the span of the delimiter
651 /// tokens at the level of the `Group`.
652 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
653 pub fn set_span(&mut self, span: Span) {
654 self.0.set_span(span.0);
658 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
659 // based on it (the reverse of the usual relationship between the two).
660 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
661 impl ToString for Group {
662 fn to_string(&self) -> String {
663 TokenStream::from(TokenTree::from(self.clone())).to_string()
667 /// Prints the group as a string that should be losslessly convertible back
668 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
669 /// with `Delimiter::None` delimiters.
670 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
671 impl fmt::Display for Group {
672 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673 f.write_str(&self.to_string())
677 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
678 impl fmt::Debug for Group {
679 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
680 f.debug_struct("Group")
681 .field("delimiter", &self.delimiter())
682 .field("stream", &self.stream())
683 .field("span", &self.span())
688 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
690 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
691 /// forms of `Spacing` returned.
692 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
694 pub struct Punct(bridge::client::Punct);
696 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
697 impl !Send for Punct {}
698 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
699 impl !Sync for Punct {}
701 /// Whether an `Punct` is followed immediately by another `Punct` or
702 /// followed by another token or whitespace.
703 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
704 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
706 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
707 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
709 /// e.g., `+` is `Joint` in `+=` or `'#`.
710 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
711 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
716 /// Creates a new `Punct` from the given character and spacing.
717 /// The `ch` argument must be a valid punctuation character permitted by the language,
718 /// otherwise the function will panic.
720 /// The returned `Punct` will have the default span of `Span::call_site()`
721 /// which can be further configured with the `set_span` method below.
722 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
723 pub fn new(ch: char, spacing: Spacing) -> Punct {
724 Punct(bridge::client::Punct::new(ch, spacing))
727 /// Returns the value of this punctuation character as `char`.
728 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
729 pub fn as_char(&self) -> char {
733 /// Returns the spacing of this punctuation character, indicating whether it's immediately
734 /// followed by another `Punct` in the token stream, so they can potentially be combined into
735 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
736 /// (`Alone`) so the operator has certainly ended.
737 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
738 pub fn spacing(&self) -> Spacing {
742 /// Returns the span for this punctuation character.
743 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
744 pub fn span(&self) -> Span {
748 /// Configure the span for this punctuation character.
749 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
750 pub fn set_span(&mut self, span: Span) {
751 self.0 = self.0.with_span(span.0);
755 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
756 // based on it (the reverse of the usual relationship between the two).
757 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
758 impl ToString for Punct {
759 fn to_string(&self) -> String {
760 TokenStream::from(TokenTree::from(self.clone())).to_string()
764 /// Prints the punctuation character as a string that should be losslessly convertible
765 /// back into the same character.
766 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
767 impl fmt::Display for Punct {
768 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
769 f.write_str(&self.to_string())
773 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
774 impl fmt::Debug for Punct {
775 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
776 f.debug_struct("Punct")
777 .field("ch", &self.as_char())
778 .field("spacing", &self.spacing())
779 .field("span", &self.span())
784 /// An identifier (`ident`).
786 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
787 pub struct Ident(bridge::client::Ident);
790 /// Creates a new `Ident` with the given `string` as well as the specified
792 /// The `string` argument must be a valid identifier permitted by the
793 /// language, otherwise the function will panic.
795 /// Note that `span`, currently in rustc, configures the hygiene information
796 /// for this identifier.
798 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
799 /// meaning that identifiers created with this span will be resolved as if they were written
800 /// directly at the location of the macro call, and other code at the macro call site will be
801 /// able to refer to them as well.
803 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
804 /// meaning that identifiers created with this span will be resolved at the location of the
805 /// macro definition and other code at the macro call site will not be able to refer to them.
807 /// Due to the current importance of hygiene this constructor, unlike other
808 /// tokens, requires a `Span` to be specified at construction.
809 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
810 pub fn new(string: &str, span: Span) -> Ident {
811 Ident(bridge::client::Ident::new(string, span.0, false))
814 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
815 #[unstable(feature = "proc_macro_raw_ident", issue = "54723")]
816 pub fn new_raw(string: &str, span: Span) -> Ident {
817 Ident(bridge::client::Ident::new(string, span.0, true))
820 /// Returns the span of this `Ident`, encompassing the entire string returned
822 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
823 pub fn span(&self) -> Span {
827 /// Configures the span of this `Ident`, possibly changing its hygiene context.
828 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
829 pub fn set_span(&mut self, span: Span) {
830 self.0 = self.0.with_span(span.0);
834 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
835 // based on it (the reverse of the usual relationship between the two).
836 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
837 impl ToString for Ident {
838 fn to_string(&self) -> String {
839 TokenStream::from(TokenTree::from(self.clone())).to_string()
843 /// Prints the identifier as a string that should be losslessly convertible
844 /// back into the same identifier.
845 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
846 impl fmt::Display for Ident {
847 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
848 f.write_str(&self.to_string())
852 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
853 impl fmt::Debug for Ident {
854 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
855 f.debug_struct("Ident")
856 .field("ident", &self.to_string())
857 .field("span", &self.span())
862 /// A literal string (`"hello"`), byte string (`b"hello"`),
863 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
864 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
865 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
867 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
868 pub struct Literal(bridge::client::Literal);
870 macro_rules! suffixed_int_literals {
871 ($($name:ident => $kind:ident,)*) => ($(
872 /// Creates a new suffixed integer literal with the specified value.
874 /// This function will create an integer like `1u32` where the integer
875 /// value specified is the first part of the token and the integral is
876 /// also suffixed at the end.
877 /// Literals created from negative numbers may not survive round-trips through
878 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
880 /// Literals created through this method have the `Span::call_site()`
881 /// span by default, which can be configured with the `set_span` method
883 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
884 pub fn $name(n: $kind) -> Literal {
885 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
890 macro_rules! unsuffixed_int_literals {
891 ($($name:ident => $kind:ident,)*) => ($(
892 /// Creates a new unsuffixed integer literal with the specified value.
894 /// This function will create an integer like `1` where the integer
895 /// value specified is the first part of the token. No suffix is
896 /// specified on this token, meaning that invocations like
897 /// `Literal::i8_unsuffixed(1)` are equivalent to
898 /// `Literal::u32_unsuffixed(1)`.
899 /// Literals created from negative numbers may not survive rountrips through
900 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
902 /// Literals created through this method have the `Span::call_site()`
903 /// span by default, which can be configured with the `set_span` method
905 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
906 pub fn $name(n: $kind) -> Literal {
907 Literal(bridge::client::Literal::integer(&n.to_string()))
913 suffixed_int_literals! {
918 u128_suffixed => u128,
919 usize_suffixed => usize,
924 i128_suffixed => i128,
925 isize_suffixed => isize,
928 unsuffixed_int_literals! {
930 u16_unsuffixed => u16,
931 u32_unsuffixed => u32,
932 u64_unsuffixed => u64,
933 u128_unsuffixed => u128,
934 usize_unsuffixed => usize,
936 i16_unsuffixed => i16,
937 i32_unsuffixed => i32,
938 i64_unsuffixed => i64,
939 i128_unsuffixed => i128,
940 isize_unsuffixed => isize,
943 /// Creates a new unsuffixed floating-point literal.
945 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
946 /// the float's value is emitted directly into the token but no suffix is
947 /// used, so it may be inferred to be a `f64` later in the compiler.
948 /// Literals created from negative numbers may not survive rountrips through
949 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
953 /// This function requires that the specified float is finite, for
954 /// example if it is infinity or NaN this function will panic.
955 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
956 pub fn f32_unsuffixed(n: f32) -> Literal {
958 panic!("Invalid float literal {}", n);
960 Literal(bridge::client::Literal::float(&n.to_string()))
963 /// Creates a new suffixed floating-point literal.
965 /// This constructor will create a literal like `1.0f32` where the value
966 /// specified is the preceding part of the token and `f32` is the suffix of
967 /// the token. This token will always be inferred to be an `f32` in the
969 /// Literals created from negative numbers may not survive rountrips through
970 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
974 /// This function requires that the specified float is finite, for
975 /// example if it is infinity or NaN this function will panic.
976 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
977 pub fn f32_suffixed(n: f32) -> Literal {
979 panic!("Invalid float literal {}", n);
981 Literal(bridge::client::Literal::f32(&n.to_string()))
984 /// Creates a new unsuffixed floating-point literal.
986 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
987 /// the float's value is emitted directly into the token but no suffix is
988 /// used, so it may be inferred to be a `f64` later in the compiler.
989 /// Literals created from negative numbers may not survive rountrips through
990 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
994 /// This function requires that the specified float is finite, for
995 /// example if it is infinity or NaN this function will panic.
996 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
997 pub fn f64_unsuffixed(n: f64) -> Literal {
999 panic!("Invalid float literal {}", n);
1001 Literal(bridge::client::Literal::float(&n.to_string()))
1004 /// Creates a new suffixed floating-point literal.
1006 /// This constructor will create a literal like `1.0f64` where the value
1007 /// specified is the preceding part of the token and `f64` is the suffix of
1008 /// the token. This token will always be inferred to be an `f64` in the
1010 /// Literals created from negative numbers may not survive rountrips through
1011 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1015 /// This function requires that the specified float is finite, for
1016 /// example if it is infinity or NaN this function will panic.
1017 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1018 pub fn f64_suffixed(n: f64) -> Literal {
1020 panic!("Invalid float literal {}", n);
1022 Literal(bridge::client::Literal::f64(&n.to_string()))
1026 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1027 pub fn string(string: &str) -> Literal {
1028 Literal(bridge::client::Literal::string(string))
1031 /// Character literal.
1032 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1033 pub fn character(ch: char) -> Literal {
1034 Literal(bridge::client::Literal::character(ch))
1037 /// Byte string literal.
1038 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1039 pub fn byte_string(bytes: &[u8]) -> Literal {
1040 Literal(bridge::client::Literal::byte_string(bytes))
1043 /// Returns the span encompassing this literal.
1044 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1045 pub fn span(&self) -> Span {
1049 /// Configures the span associated for this literal.
1050 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1051 pub fn set_span(&mut self, span: Span) {
1052 self.0.set_span(span.0);
1055 /// Returns a `Span` that is a subset of `self.span()` containing only the
1056 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1057 /// span is outside the bounds of `self`.
1058 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1059 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1060 // occur elsewhere when the source text is printed.
1061 // FIXME(SergioBenitez): there is no way for the user to know what
1062 // `self.span()` actually maps to, so this method can currently only be
1063 // called blindly. For example, `to_string()` for the character 'c' returns
1064 // "'\u{63}'"; there is no way for the user to know whether the source text
1065 // was 'c' or whether it was '\u{63}'.
1066 #[unstable(feature = "proc_macro_span", issue = "54725")]
1067 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1068 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1069 fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1071 Bound::Included(x) => Bound::Included(x.clone()),
1072 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1073 Bound::Unbounded => Bound::Unbounded,
1078 cloned_bound(range.start_bound()),
1079 cloned_bound(range.end_bound()),
1084 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1085 // based on it (the reverse of the usual relationship between the two).
1086 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1087 impl ToString for Literal {
1088 fn to_string(&self) -> String {
1089 TokenStream::from(TokenTree::from(self.clone())).to_string()
1093 /// Prints the literal as a string that should be losslessly convertible
1094 /// back into the same literal (except for possible rounding for floating point literals).
1095 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1096 impl fmt::Display for Literal {
1097 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1098 f.write_str(&self.to_string())
1102 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1103 impl fmt::Debug for Literal {
1104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1105 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.