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(negative_impls)]
28 #![feature(optin_builtin_traits)]
29 #![feature(rustc_attrs)]
30 #![feature(min_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::cmp::Ordering;
43 use std::ops::{Bound, RangeBounds};
44 use std::path::PathBuf;
45 use std::str::FromStr;
46 use std::{error, fmt, iter, mem};
48 /// Determines whether proc_macro has been made accessible to the currently
51 /// The proc_macro crate is only intended for use inside the implementation of
52 /// procedural macros. All the functions in this crate panic if invoked from
53 /// outside of a procedural macro, such as from a build script or unit test or
54 /// ordinary Rust binary.
56 /// With consideration for Rust libraries that are designed to support both
57 /// macro and non-macro use cases, `proc_macro::is_available()` provides a
58 /// non-panicking way to detect whether the infrastructure required to use the
59 /// API of proc_macro is presently available. Returns true if invoked from
60 /// inside of a procedural macro, false if invoked from any other binary.
61 #[unstable(feature = "proc_macro_is_available", issue = "71436")]
62 pub fn is_available() -> bool {
63 bridge::Bridge::is_available()
66 /// The main type provided by this crate, representing an abstract stream of
67 /// tokens, or, more specifically, a sequence of token trees.
68 /// The type provide interfaces for iterating over those token trees and, conversely,
69 /// collecting a number of token trees into one stream.
71 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
72 /// and `#[proc_macro_derive]` definitions.
73 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
75 pub struct TokenStream(bridge::client::TokenStream);
77 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
78 impl !Send for TokenStream {}
79 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
80 impl !Sync for TokenStream {}
82 /// Error returned from `TokenStream::from_str`.
83 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
89 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
90 impl fmt::Display for LexError {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 f.write_str("cannot parse string into token stream")
96 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
97 impl error::Error for LexError {}
99 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
100 impl !Send for LexError {}
101 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
102 impl !Sync for LexError {}
105 /// Returns an empty `TokenStream` containing no token trees.
106 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
107 pub fn new() -> TokenStream {
108 TokenStream(bridge::client::TokenStream::new())
111 /// Checks if this `TokenStream` is empty.
112 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
113 pub fn is_empty(&self) -> bool {
118 /// Attempts to break the string into tokens and parse those tokens into a token stream.
119 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
120 /// or characters not existing in the language.
121 /// All tokens in the parsed stream get `Span::call_site()` spans.
123 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
124 /// change these errors into `LexError`s later.
125 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
126 impl FromStr for TokenStream {
129 fn from_str(src: &str) -> Result<TokenStream, LexError> {
130 Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
134 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
135 // based on it (the reverse of the usual relationship between the two).
136 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
137 impl ToString for TokenStream {
138 fn to_string(&self) -> String {
143 /// Prints the token stream as a string that is supposed to be losslessly convertible back
144 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
145 /// with `Delimiter::None` delimiters and negative numeric literals.
146 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
147 impl fmt::Display for TokenStream {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 f.write_str(&self.to_string())
153 /// Prints token in a form convenient for debugging.
154 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
155 impl fmt::Debug for TokenStream {
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 f.write_str("TokenStream ")?;
158 f.debug_list().entries(self.clone()).finish()
162 #[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
163 impl Default for TokenStream {
164 fn default() -> Self {
169 #[unstable(feature = "proc_macro_quote", issue = "54722")]
170 pub use quote::{quote, quote_span};
172 /// Creates a token stream containing a single token tree.
173 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
174 impl From<TokenTree> for TokenStream {
175 fn from(tree: TokenTree) -> TokenStream {
176 TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
177 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
178 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
179 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
180 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
185 /// Collects a number of token trees into a single stream.
186 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
187 impl iter::FromIterator<TokenTree> for TokenStream {
188 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
189 trees.into_iter().map(TokenStream::from).collect()
193 /// A "flattening" operation on token streams, collects token trees
194 /// from multiple token streams into a single stream.
195 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
196 impl iter::FromIterator<TokenStream> for TokenStream {
197 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
198 let mut builder = bridge::client::TokenStreamBuilder::new();
199 streams.into_iter().for_each(|stream| builder.push(stream.0));
200 TokenStream(builder.build())
204 #[stable(feature = "token_stream_extend", since = "1.30.0")]
205 impl Extend<TokenTree> for TokenStream {
206 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
207 self.extend(trees.into_iter().map(TokenStream::from));
211 #[stable(feature = "token_stream_extend", since = "1.30.0")]
212 impl Extend<TokenStream> for TokenStream {
213 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
214 // FIXME(eddyb) Use an optimized implementation if/when possible.
215 *self = iter::once(mem::replace(self, Self::new())).chain(streams).collect();
219 /// Public implementation details for the `TokenStream` type, such as iterators.
220 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
221 pub mod token_stream {
222 use crate::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree};
224 /// An iterator over `TokenStream`'s `TokenTree`s.
225 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
226 /// and returns whole groups as token trees.
228 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
229 pub struct IntoIter(bridge::client::TokenStreamIter);
231 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
232 impl Iterator for IntoIter {
233 type Item = TokenTree;
235 fn next(&mut self) -> Option<TokenTree> {
236 self.0.next().map(|tree| match tree {
237 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
238 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
239 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
240 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
245 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
246 impl IntoIterator for TokenStream {
247 type Item = TokenTree;
248 type IntoIter = IntoIter;
250 fn into_iter(self) -> IntoIter {
251 IntoIter(self.0.into_iter())
256 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
257 /// For example, `quote!(a + b)` will produce a expression, that, when evaluated, constructs
258 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
260 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
261 /// To quote `$` itself, use `$$`.
262 #[unstable(feature = "proc_macro_quote", issue = "54722")]
263 #[allow_internal_unstable(proc_macro_def_site)]
264 #[rustc_builtin_macro]
265 pub macro quote($($t:tt)*) {
266 /* compiler built-in */
269 #[unstable(feature = "proc_macro_internals", issue = "27812")]
273 /// A region of source code, along with macro expansion information.
274 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
275 #[derive(Copy, Clone)]
276 pub struct Span(bridge::client::Span);
278 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
279 impl !Send for Span {}
280 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
281 impl !Sync for Span {}
283 macro_rules! diagnostic_method {
284 ($name:ident, $level:expr) => {
285 /// Creates a new `Diagnostic` with the given `message` at the span
287 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
288 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
289 Diagnostic::spanned(self, $level, message)
295 /// A span that resolves at the macro definition site.
296 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
297 pub fn def_site() -> Span {
298 Span(bridge::client::Span::def_site())
301 /// The span of the invocation of the current procedural macro.
302 /// Identifiers created with this span will be resolved as if they were written
303 /// directly at the macro call location (call-site hygiene) and other code
304 /// at the macro call site will be able to refer to them as well.
305 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
306 pub fn call_site() -> Span {
307 Span(bridge::client::Span::call_site())
310 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
311 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
312 /// call site (everything else).
313 /// The span location is taken from the call-site.
314 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
315 pub fn mixed_site() -> Span {
316 Span(bridge::client::Span::mixed_site())
319 /// The original source file into which this span points.
320 #[unstable(feature = "proc_macro_span", issue = "54725")]
321 pub fn source_file(&self) -> SourceFile {
322 SourceFile(self.0.source_file())
325 /// The `Span` for the tokens in the previous macro expansion from which
326 /// `self` was generated from, if any.
327 #[unstable(feature = "proc_macro_span", issue = "54725")]
328 pub fn parent(&self) -> Option<Span> {
329 self.0.parent().map(Span)
332 /// The span for the origin source code that `self` was generated from. If
333 /// this `Span` wasn't generated from other macro expansions then the return
334 /// value is the same as `*self`.
335 #[unstable(feature = "proc_macro_span", issue = "54725")]
336 pub fn source(&self) -> Span {
337 Span(self.0.source())
340 /// Gets the starting line/column in the source file for this span.
341 #[unstable(feature = "proc_macro_span", issue = "54725")]
342 pub fn start(&self) -> LineColumn {
346 /// Gets the ending line/column in the source file for this span.
347 #[unstable(feature = "proc_macro_span", issue = "54725")]
348 pub fn end(&self) -> LineColumn {
352 /// Creates a new span encompassing `self` and `other`.
354 /// Returns `None` if `self` and `other` are from different files.
355 #[unstable(feature = "proc_macro_span", issue = "54725")]
356 pub fn join(&self, other: Span) -> Option<Span> {
357 self.0.join(other.0).map(Span)
360 /// Creates a new span with the same line/column information as `self` but
361 /// that resolves symbols as though it were at `other`.
362 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
363 pub fn resolved_at(&self, other: Span) -> Span {
364 Span(self.0.resolved_at(other.0))
367 /// Creates a new span with the same name resolution behavior as `self` but
368 /// with the line/column information of `other`.
369 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
370 pub fn located_at(&self, other: Span) -> Span {
371 other.resolved_at(*self)
374 /// Compares to spans to see if they're equal.
375 #[unstable(feature = "proc_macro_span", issue = "54725")]
376 pub fn eq(&self, other: &Span) -> bool {
380 /// Returns the source text behind a span. This preserves the original source
381 /// code, including spaces and comments. It only returns a result if the span
382 /// corresponds to real source code.
384 /// Note: The observable result of a macro should only rely on the tokens and
385 /// not on this source text. The result of this function is a best effort to
386 /// be used for diagnostics only.
387 #[unstable(feature = "proc_macro_span", issue = "54725")]
388 pub fn source_text(&self) -> Option<String> {
392 diagnostic_method!(error, Level::Error);
393 diagnostic_method!(warning, Level::Warning);
394 diagnostic_method!(note, Level::Note);
395 diagnostic_method!(help, Level::Help);
398 /// Prints a span in a form convenient for debugging.
399 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
400 impl fmt::Debug for Span {
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406 /// A line-column pair representing the start or end of a `Span`.
407 #[unstable(feature = "proc_macro_span", issue = "54725")]
408 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
409 pub struct LineColumn {
410 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
411 #[unstable(feature = "proc_macro_span", issue = "54725")]
413 /// The 0-indexed column (in UTF-8 characters) in the source file on which
414 /// the span starts or ends (inclusive).
415 #[unstable(feature = "proc_macro_span", issue = "54725")]
419 #[unstable(feature = "proc_macro_span", issue = "54725")]
420 impl !Send for LineColumn {}
421 #[unstable(feature = "proc_macro_span", issue = "54725")]
422 impl !Sync for LineColumn {}
424 #[unstable(feature = "proc_macro_span", issue = "54725")]
425 impl Ord for LineColumn {
426 fn cmp(&self, other: &Self) -> Ordering {
427 self.line.cmp(&other.line).then(self.column.cmp(&other.column))
431 #[unstable(feature = "proc_macro_span", issue = "54725")]
432 impl PartialOrd for LineColumn {
433 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
434 Some(self.cmp(other))
438 /// The source file of a given `Span`.
439 #[unstable(feature = "proc_macro_span", issue = "54725")]
441 pub struct SourceFile(bridge::client::SourceFile);
444 /// Gets the path to this source file.
447 /// If the code span associated with this `SourceFile` was generated by an external macro, this
448 /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
450 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
451 /// the command line, the path as given may not actually be valid.
453 /// [`is_real`]: #method.is_real
454 #[unstable(feature = "proc_macro_span", issue = "54725")]
455 pub fn path(&self) -> PathBuf {
456 PathBuf::from(self.0.path())
459 /// Returns `true` if this source file is a real source file, and not generated by an external
460 /// macro's expansion.
461 #[unstable(feature = "proc_macro_span", issue = "54725")]
462 pub fn is_real(&self) -> bool {
463 // This is a hack until intercrate spans are implemented and we can have real source files
464 // for spans generated in external macros.
465 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
470 #[unstable(feature = "proc_macro_span", issue = "54725")]
471 impl fmt::Debug for SourceFile {
472 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
473 f.debug_struct("SourceFile")
474 .field("path", &self.path())
475 .field("is_real", &self.is_real())
480 #[unstable(feature = "proc_macro_span", issue = "54725")]
481 impl PartialEq for SourceFile {
482 fn eq(&self, other: &Self) -> bool {
487 #[unstable(feature = "proc_macro_span", issue = "54725")]
488 impl Eq for SourceFile {}
490 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
491 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
494 /// A token stream surrounded by bracket delimiters.
495 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
496 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
498 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
499 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
500 /// A single punctuation character (`+`, `,`, `$`, etc.).
501 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
502 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
503 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
504 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
505 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
508 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
509 impl !Send for TokenTree {}
510 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
511 impl !Sync for TokenTree {}
514 /// Returns the span of this tree, delegating to the `span` method of
515 /// the contained token or a delimited stream.
516 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
517 pub fn span(&self) -> Span {
519 TokenTree::Group(ref t) => t.span(),
520 TokenTree::Ident(ref t) => t.span(),
521 TokenTree::Punct(ref t) => t.span(),
522 TokenTree::Literal(ref t) => t.span(),
526 /// Configures the span for *only this token*.
528 /// Note that if this token is a `Group` then this method will not configure
529 /// the span of each of the internal tokens, this will simply delegate to
530 /// the `set_span` method of each variant.
531 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
532 pub fn set_span(&mut self, span: Span) {
534 TokenTree::Group(ref mut t) => t.set_span(span),
535 TokenTree::Ident(ref mut t) => t.set_span(span),
536 TokenTree::Punct(ref mut t) => t.set_span(span),
537 TokenTree::Literal(ref mut t) => t.set_span(span),
542 /// Prints token tree in a form convenient for debugging.
543 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
544 impl fmt::Debug for TokenTree {
545 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
546 // Each of these has the name in the struct type in the derived debug,
547 // so don't bother with an extra layer of indirection
549 TokenTree::Group(ref tt) => tt.fmt(f),
550 TokenTree::Ident(ref tt) => tt.fmt(f),
551 TokenTree::Punct(ref tt) => tt.fmt(f),
552 TokenTree::Literal(ref tt) => tt.fmt(f),
557 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
558 impl From<Group> for TokenTree {
559 fn from(g: Group) -> TokenTree {
564 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
565 impl From<Ident> for TokenTree {
566 fn from(g: Ident) -> TokenTree {
571 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
572 impl From<Punct> for TokenTree {
573 fn from(g: Punct) -> TokenTree {
578 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
579 impl From<Literal> for TokenTree {
580 fn from(g: Literal) -> TokenTree {
581 TokenTree::Literal(g)
585 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
586 // based on it (the reverse of the usual relationship between the two).
587 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
588 impl ToString for TokenTree {
589 fn to_string(&self) -> String {
591 TokenTree::Group(ref t) => t.to_string(),
592 TokenTree::Ident(ref t) => t.to_string(),
593 TokenTree::Punct(ref t) => t.to_string(),
594 TokenTree::Literal(ref t) => t.to_string(),
599 /// Prints the token tree as a string that is supposed to be losslessly convertible back
600 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
601 /// with `Delimiter::None` delimiters and negative numeric literals.
602 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
603 impl fmt::Display for TokenTree {
604 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
605 f.write_str(&self.to_string())
609 /// A delimited token stream.
611 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
613 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
614 pub struct Group(bridge::client::Group);
616 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
617 impl !Send for Group {}
618 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
619 impl !Sync for Group {}
621 /// Describes how a sequence of token trees is delimited.
622 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
623 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
626 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
629 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
632 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
635 /// An implicit delimiter, that may, for example, appear around tokens coming from a
636 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
637 /// `$var * 3` where `$var` is `1 + 2`.
638 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
639 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
644 /// Creates a new `Group` with the given delimiter and token stream.
646 /// This constructor will set the span for this group to
647 /// `Span::call_site()`. To change the span you can use the `set_span`
649 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
650 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
651 Group(bridge::client::Group::new(delimiter, stream.0))
654 /// Returns the delimiter of this `Group`
655 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
656 pub fn delimiter(&self) -> Delimiter {
660 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
662 /// Note that the returned token stream does not include the delimiter
664 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
665 pub fn stream(&self) -> TokenStream {
666 TokenStream(self.0.stream())
669 /// Returns the span for the delimiters of this token stream, spanning the
673 /// pub fn span(&self) -> Span {
676 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
677 pub fn span(&self) -> Span {
681 /// Returns the span pointing to the opening delimiter of this group.
684 /// pub fn span_open(&self) -> Span {
687 #[unstable(feature = "proc_macro_span", issue = "54725")]
688 pub fn span_open(&self) -> Span {
689 Span(self.0.span_open())
692 /// Returns the span pointing to the closing delimiter of this group.
695 /// pub fn span_close(&self) -> Span {
698 #[unstable(feature = "proc_macro_span", issue = "54725")]
699 pub fn span_close(&self) -> Span {
700 Span(self.0.span_close())
703 /// Configures the span for this `Group`'s delimiters, but not its internal
706 /// This method will **not** set the span of all the internal tokens spanned
707 /// by this group, but rather it will only set the span of the delimiter
708 /// tokens at the level of the `Group`.
709 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
710 pub fn set_span(&mut self, span: Span) {
711 self.0.set_span(span.0);
715 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
716 // based on it (the reverse of the usual relationship between the two).
717 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
718 impl ToString for Group {
719 fn to_string(&self) -> String {
720 TokenStream::from(TokenTree::from(self.clone())).to_string()
724 /// Prints the group as a string that should be losslessly convertible back
725 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
726 /// with `Delimiter::None` delimiters.
727 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
728 impl fmt::Display for Group {
729 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
730 f.write_str(&self.to_string())
734 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
735 impl fmt::Debug for Group {
736 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
737 f.debug_struct("Group")
738 .field("delimiter", &self.delimiter())
739 .field("stream", &self.stream())
740 .field("span", &self.span())
745 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
747 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
748 /// forms of `Spacing` returned.
749 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
751 pub struct Punct(bridge::client::Punct);
753 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
754 impl !Send for Punct {}
755 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
756 impl !Sync for Punct {}
758 /// Whether an `Punct` is followed immediately by another `Punct` or
759 /// followed by another token or whitespace.
760 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
761 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
763 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
764 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
766 /// e.g., `+` is `Joint` in `+=` or `'#`.
767 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
768 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
773 /// Creates a new `Punct` from the given character and spacing.
774 /// The `ch` argument must be a valid punctuation character permitted by the language,
775 /// otherwise the function will panic.
777 /// The returned `Punct` will have the default span of `Span::call_site()`
778 /// which can be further configured with the `set_span` method below.
779 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
780 pub fn new(ch: char, spacing: Spacing) -> Punct {
781 Punct(bridge::client::Punct::new(ch, spacing))
784 /// Returns the value of this punctuation character as `char`.
785 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
786 pub fn as_char(&self) -> char {
790 /// Returns the spacing of this punctuation character, indicating whether it's immediately
791 /// followed by another `Punct` in the token stream, so they can potentially be combined into
792 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
793 /// (`Alone`) so the operator has certainly ended.
794 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
795 pub fn spacing(&self) -> Spacing {
799 /// Returns the span for this punctuation character.
800 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
801 pub fn span(&self) -> Span {
805 /// Configure the span for this punctuation character.
806 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
807 pub fn set_span(&mut self, span: Span) {
808 self.0 = self.0.with_span(span.0);
812 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
813 // based on it (the reverse of the usual relationship between the two).
814 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
815 impl ToString for Punct {
816 fn to_string(&self) -> String {
817 TokenStream::from(TokenTree::from(self.clone())).to_string()
821 /// Prints the punctuation character as a string that should be losslessly convertible
822 /// back into the same character.
823 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
824 impl fmt::Display for Punct {
825 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
826 f.write_str(&self.to_string())
830 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
831 impl fmt::Debug for Punct {
832 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
833 f.debug_struct("Punct")
834 .field("ch", &self.as_char())
835 .field("spacing", &self.spacing())
836 .field("span", &self.span())
841 /// An identifier (`ident`).
843 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
844 pub struct Ident(bridge::client::Ident);
847 /// Creates a new `Ident` with the given `string` as well as the specified
849 /// The `string` argument must be a valid identifier permitted by the
850 /// language, otherwise the function will panic.
852 /// Note that `span`, currently in rustc, configures the hygiene information
853 /// for this identifier.
855 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
856 /// meaning that identifiers created with this span will be resolved as if they were written
857 /// directly at the location of the macro call, and other code at the macro call site will be
858 /// able to refer to them as well.
860 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
861 /// meaning that identifiers created with this span will be resolved at the location of the
862 /// macro definition and other code at the macro call site will not be able to refer to them.
864 /// Due to the current importance of hygiene this constructor, unlike other
865 /// tokens, requires a `Span` to be specified at construction.
866 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
867 pub fn new(string: &str, span: Span) -> Ident {
868 Ident(bridge::client::Ident::new(string, span.0, false))
871 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
872 #[unstable(feature = "proc_macro_raw_ident", issue = "54723")]
873 pub fn new_raw(string: &str, span: Span) -> Ident {
874 Ident(bridge::client::Ident::new(string, span.0, true))
877 /// Returns the span of this `Ident`, encompassing the entire string returned
879 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
880 pub fn span(&self) -> Span {
884 /// Configures the span of this `Ident`, possibly changing its hygiene context.
885 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
886 pub fn set_span(&mut self, span: Span) {
887 self.0 = self.0.with_span(span.0);
891 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
892 // based on it (the reverse of the usual relationship between the two).
893 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
894 impl ToString for Ident {
895 fn to_string(&self) -> String {
896 TokenStream::from(TokenTree::from(self.clone())).to_string()
900 /// Prints the identifier as a string that should be losslessly convertible
901 /// back into the same identifier.
902 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
903 impl fmt::Display for Ident {
904 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
905 f.write_str(&self.to_string())
909 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
910 impl fmt::Debug for Ident {
911 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
912 f.debug_struct("Ident")
913 .field("ident", &self.to_string())
914 .field("span", &self.span())
919 /// A literal string (`"hello"`), byte string (`b"hello"`),
920 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
921 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
922 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
924 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
925 pub struct Literal(bridge::client::Literal);
927 macro_rules! suffixed_int_literals {
928 ($($name:ident => $kind:ident,)*) => ($(
929 /// Creates a new suffixed integer literal with the specified value.
931 /// This function will create an integer like `1u32` where the integer
932 /// value specified is the first part of the token and the integral is
933 /// also suffixed at the end.
934 /// Literals created from negative numbers may not survive round-trips through
935 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
937 /// Literals created through this method have the `Span::call_site()`
938 /// span by default, which can be configured with the `set_span` method
940 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
941 pub fn $name(n: $kind) -> Literal {
942 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
947 macro_rules! unsuffixed_int_literals {
948 ($($name:ident => $kind:ident,)*) => ($(
949 /// Creates a new unsuffixed integer literal with the specified value.
951 /// This function will create an integer like `1` where the integer
952 /// value specified is the first part of the token. No suffix is
953 /// specified on this token, meaning that invocations like
954 /// `Literal::i8_unsuffixed(1)` are equivalent to
955 /// `Literal::u32_unsuffixed(1)`.
956 /// Literals created from negative numbers may not survive rountrips through
957 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
959 /// Literals created through this method have the `Span::call_site()`
960 /// span by default, which can be configured with the `set_span` method
962 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
963 pub fn $name(n: $kind) -> Literal {
964 Literal(bridge::client::Literal::integer(&n.to_string()))
970 suffixed_int_literals! {
975 u128_suffixed => u128,
976 usize_suffixed => usize,
981 i128_suffixed => i128,
982 isize_suffixed => isize,
985 unsuffixed_int_literals! {
987 u16_unsuffixed => u16,
988 u32_unsuffixed => u32,
989 u64_unsuffixed => u64,
990 u128_unsuffixed => u128,
991 usize_unsuffixed => usize,
993 i16_unsuffixed => i16,
994 i32_unsuffixed => i32,
995 i64_unsuffixed => i64,
996 i128_unsuffixed => i128,
997 isize_unsuffixed => isize,
1000 /// Creates a new unsuffixed floating-point literal.
1002 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1003 /// the float's value is emitted directly into the token but no suffix is
1004 /// used, so it may be inferred to be a `f64` later in the compiler.
1005 /// Literals created from negative numbers may not survive rountrips through
1006 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1010 /// This function requires that the specified float is finite, for
1011 /// example if it is infinity or NaN this function will panic.
1012 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1013 pub fn f32_unsuffixed(n: f32) -> Literal {
1015 panic!("Invalid float literal {}", n);
1017 Literal(bridge::client::Literal::float(&n.to_string()))
1020 /// Creates a new suffixed floating-point literal.
1022 /// This constructor will create a literal like `1.0f32` where the value
1023 /// specified is the preceding part of the token and `f32` is the suffix of
1024 /// the token. This token will always be inferred to be an `f32` in the
1026 /// Literals created from negative numbers may not survive rountrips through
1027 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1031 /// This function requires that the specified float is finite, for
1032 /// example if it is infinity or NaN this function will panic.
1033 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1034 pub fn f32_suffixed(n: f32) -> Literal {
1036 panic!("Invalid float literal {}", n);
1038 Literal(bridge::client::Literal::f32(&n.to_string()))
1041 /// Creates a new unsuffixed floating-point literal.
1043 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1044 /// the float's value is emitted directly into the token but no suffix is
1045 /// used, so it may be inferred to be a `f64` later in the compiler.
1046 /// Literals created from negative numbers may not survive rountrips through
1047 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1051 /// This function requires that the specified float is finite, for
1052 /// example if it is infinity or NaN this function will panic.
1053 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1054 pub fn f64_unsuffixed(n: f64) -> Literal {
1056 panic!("Invalid float literal {}", n);
1058 Literal(bridge::client::Literal::float(&n.to_string()))
1061 /// Creates a new suffixed floating-point literal.
1063 /// This constructor will create a literal like `1.0f64` where the value
1064 /// specified is the preceding part of the token and `f64` is the suffix of
1065 /// the token. This token will always be inferred to be an `f64` in the
1067 /// Literals created from negative numbers may not survive rountrips through
1068 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1072 /// This function requires that the specified float is finite, for
1073 /// example if it is infinity or NaN this function will panic.
1074 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1075 pub fn f64_suffixed(n: f64) -> Literal {
1077 panic!("Invalid float literal {}", n);
1079 Literal(bridge::client::Literal::f64(&n.to_string()))
1083 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1084 pub fn string(string: &str) -> Literal {
1085 Literal(bridge::client::Literal::string(string))
1088 /// Character literal.
1089 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1090 pub fn character(ch: char) -> Literal {
1091 Literal(bridge::client::Literal::character(ch))
1094 /// Byte string literal.
1095 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1096 pub fn byte_string(bytes: &[u8]) -> Literal {
1097 Literal(bridge::client::Literal::byte_string(bytes))
1100 /// Returns the span encompassing this literal.
1101 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1102 pub fn span(&self) -> Span {
1106 /// Configures the span associated for this literal.
1107 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1108 pub fn set_span(&mut self, span: Span) {
1109 self.0.set_span(span.0);
1112 /// Returns a `Span` that is a subset of `self.span()` containing only the
1113 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1114 /// span is outside the bounds of `self`.
1115 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1116 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1117 // occur elsewhere when the source text is printed.
1118 // FIXME(SergioBenitez): there is no way for the user to know what
1119 // `self.span()` actually maps to, so this method can currently only be
1120 // called blindly. For example, `to_string()` for the character 'c' returns
1121 // "'\u{63}'"; there is no way for the user to know whether the source text
1122 // was 'c' or whether it was '\u{63}'.
1123 #[unstable(feature = "proc_macro_span", issue = "54725")]
1124 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1125 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1126 fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1128 Bound::Included(x) => Bound::Included(x.clone()),
1129 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1130 Bound::Unbounded => Bound::Unbounded,
1134 self.0.subspan(cloned_bound(range.start_bound()), cloned_bound(range.end_bound())).map(Span)
1138 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1139 // based on it (the reverse of the usual relationship between the two).
1140 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1141 impl ToString for Literal {
1142 fn to_string(&self) -> String {
1143 TokenStream::from(TokenTree::from(self.clone())).to_string()
1147 /// Prints the literal as a string that should be losslessly convertible
1148 /// back into the same literal (except for possible rounding for floating point literals).
1149 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1150 impl fmt::Display for Literal {
1151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1152 f.write_str(&self.to_string())
1156 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1157 impl fmt::Debug for Literal {
1158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {