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)]
24 #![feature(allow_internal_unstable)]
25 #![feature(decl_macro)]
26 #![feature(extern_types)]
27 #![feature(in_band_lifetimes)]
28 #![feature(negative_impls)]
29 #![feature(optin_builtin_traits)]
30 #![feature(restricted_std)]
31 #![feature(rustc_attrs)]
32 #![feature(min_specialization)]
33 #![recursion_limit = "256"]
35 #[unstable(feature = "proc_macro_internals", issue = "27812")]
41 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
42 pub use diagnostic::{Diagnostic, Level, MultiSpan};
44 use std::cmp::Ordering;
45 use std::ops::{Bound, RangeBounds};
46 use std::path::PathBuf;
47 use std::str::FromStr;
48 use std::{error, fmt, iter, mem};
50 /// Determines whether proc_macro has been made accessible to the currently
53 /// The proc_macro crate is only intended for use inside the implementation of
54 /// procedural macros. All the functions in this crate panic if invoked from
55 /// outside of a procedural macro, such as from a build script or unit test or
56 /// ordinary Rust binary.
58 /// With consideration for Rust libraries that are designed to support both
59 /// macro and non-macro use cases, `proc_macro::is_available()` provides a
60 /// non-panicking way to detect whether the infrastructure required to use the
61 /// API of proc_macro is presently available. Returns true if invoked from
62 /// inside of a procedural macro, false if invoked from any other binary.
63 #[unstable(feature = "proc_macro_is_available", issue = "71436")]
64 pub fn is_available() -> bool {
65 bridge::Bridge::is_available()
68 /// The main type provided by this crate, representing an abstract stream of
69 /// tokens, or, more specifically, a sequence of token trees.
70 /// The type provide interfaces for iterating over those token trees and, conversely,
71 /// collecting a number of token trees into one stream.
73 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
74 /// and `#[proc_macro_derive]` definitions.
75 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
77 pub struct TokenStream(bridge::client::TokenStream);
79 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
80 impl !Send for TokenStream {}
81 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
82 impl !Sync for TokenStream {}
84 /// Error returned from `TokenStream::from_str`.
85 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
91 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
92 impl fmt::Display for LexError {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 f.write_str("cannot parse string into token stream")
98 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
99 impl error::Error for LexError {}
101 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
102 impl !Send for LexError {}
103 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
104 impl !Sync for LexError {}
107 /// Returns an empty `TokenStream` containing no token trees.
108 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
109 pub fn new() -> TokenStream {
110 TokenStream(bridge::client::TokenStream::new())
113 /// Checks if this `TokenStream` is empty.
114 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
115 pub fn is_empty(&self) -> bool {
120 /// Attempts to break the string into tokens and parse those tokens into a token stream.
121 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
122 /// or characters not existing in the language.
123 /// All tokens in the parsed stream get `Span::call_site()` spans.
125 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
126 /// change these errors into `LexError`s later.
127 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
128 impl FromStr for TokenStream {
131 fn from_str(src: &str) -> Result<TokenStream, LexError> {
132 Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
136 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
137 // based on it (the reverse of the usual relationship between the two).
138 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
139 impl ToString for TokenStream {
140 fn to_string(&self) -> String {
145 /// Prints the token stream as a string that is supposed to be losslessly convertible back
146 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
147 /// with `Delimiter::None` delimiters and negative numeric literals.
148 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
149 impl fmt::Display for TokenStream {
150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151 f.write_str(&self.to_string())
155 /// Prints token in a form convenient for debugging.
156 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
157 impl fmt::Debug for TokenStream {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 f.write_str("TokenStream ")?;
160 f.debug_list().entries(self.clone()).finish()
164 #[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
165 impl Default for TokenStream {
166 fn default() -> Self {
171 #[unstable(feature = "proc_macro_quote", issue = "54722")]
172 pub use quote::{quote, quote_span};
174 /// Creates a token stream containing a single token tree.
175 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
176 impl From<TokenTree> for TokenStream {
177 fn from(tree: TokenTree) -> TokenStream {
178 TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
179 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
180 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
181 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
182 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
187 /// Collects a number of token trees into a single stream.
188 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
189 impl iter::FromIterator<TokenTree> for TokenStream {
190 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
191 trees.into_iter().map(TokenStream::from).collect()
195 /// A "flattening" operation on token streams, collects token trees
196 /// from multiple token streams into a single stream.
197 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
198 impl iter::FromIterator<TokenStream> for TokenStream {
199 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
200 let mut builder = bridge::client::TokenStreamBuilder::new();
201 streams.into_iter().for_each(|stream| builder.push(stream.0));
202 TokenStream(builder.build())
206 #[stable(feature = "token_stream_extend", since = "1.30.0")]
207 impl Extend<TokenTree> for TokenStream {
208 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
209 self.extend(trees.into_iter().map(TokenStream::from));
213 #[stable(feature = "token_stream_extend", since = "1.30.0")]
214 impl Extend<TokenStream> for TokenStream {
215 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
216 // FIXME(eddyb) Use an optimized implementation if/when possible.
217 *self = iter::once(mem::replace(self, Self::new())).chain(streams).collect();
221 /// Public implementation details for the `TokenStream` type, such as iterators.
222 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
223 pub mod token_stream {
224 use crate::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree};
226 /// An iterator over `TokenStream`'s `TokenTree`s.
227 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
228 /// and returns whole groups as token trees.
230 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
231 pub struct IntoIter(bridge::client::TokenStreamIter);
233 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
234 impl Iterator for IntoIter {
235 type Item = TokenTree;
237 fn next(&mut self) -> Option<TokenTree> {
238 self.0.next().map(|tree| match tree {
239 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
240 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
241 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
242 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
247 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
248 impl IntoIterator for TokenStream {
249 type Item = TokenTree;
250 type IntoIter = IntoIter;
252 fn into_iter(self) -> IntoIter {
253 IntoIter(self.0.into_iter())
258 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
259 /// For example, `quote!(a + b)` will produce a expression, that, when evaluated, constructs
260 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
262 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
263 /// To quote `$` itself, use `$$`.
264 #[unstable(feature = "proc_macro_quote", issue = "54722")]
265 #[allow_internal_unstable(proc_macro_def_site)]
266 #[rustc_builtin_macro]
267 pub macro quote($($t:tt)*) {
268 /* compiler built-in */
271 #[unstable(feature = "proc_macro_internals", issue = "27812")]
275 /// A region of source code, along with macro expansion information.
276 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
277 #[derive(Copy, Clone)]
278 pub struct Span(bridge::client::Span);
280 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
281 impl !Send for Span {}
282 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
283 impl !Sync for Span {}
285 macro_rules! diagnostic_method {
286 ($name:ident, $level:expr) => {
287 /// Creates a new `Diagnostic` with the given `message` at the span
289 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
290 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
291 Diagnostic::spanned(self, $level, message)
297 /// A span that resolves at the macro definition site.
298 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
299 pub fn def_site() -> Span {
300 Span(bridge::client::Span::def_site())
303 /// The span of the invocation of the current procedural macro.
304 /// Identifiers created with this span will be resolved as if they were written
305 /// directly at the macro call location (call-site hygiene) and other code
306 /// at the macro call site will be able to refer to them as well.
307 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
308 pub fn call_site() -> Span {
309 Span(bridge::client::Span::call_site())
312 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
313 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
314 /// call site (everything else).
315 /// The span location is taken from the call-site.
316 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
317 pub fn mixed_site() -> Span {
318 Span(bridge::client::Span::mixed_site())
321 /// The original source file into which this span points.
322 #[unstable(feature = "proc_macro_span", issue = "54725")]
323 pub fn source_file(&self) -> SourceFile {
324 SourceFile(self.0.source_file())
327 /// The `Span` for the tokens in the previous macro expansion from which
328 /// `self` was generated from, if any.
329 #[unstable(feature = "proc_macro_span", issue = "54725")]
330 pub fn parent(&self) -> Option<Span> {
331 self.0.parent().map(Span)
334 /// The span for the origin source code that `self` was generated from. If
335 /// this `Span` wasn't generated from other macro expansions then the return
336 /// value is the same as `*self`.
337 #[unstable(feature = "proc_macro_span", issue = "54725")]
338 pub fn source(&self) -> Span {
339 Span(self.0.source())
342 /// Gets the starting line/column in the source file for this span.
343 #[unstable(feature = "proc_macro_span", issue = "54725")]
344 pub fn start(&self) -> LineColumn {
348 /// Gets the ending line/column in the source file for this span.
349 #[unstable(feature = "proc_macro_span", issue = "54725")]
350 pub fn end(&self) -> LineColumn {
354 /// Creates a new span encompassing `self` and `other`.
356 /// Returns `None` if `self` and `other` are from different files.
357 #[unstable(feature = "proc_macro_span", issue = "54725")]
358 pub fn join(&self, other: Span) -> Option<Span> {
359 self.0.join(other.0).map(Span)
362 /// Creates a new span with the same line/column information as `self` but
363 /// that resolves symbols as though it were at `other`.
364 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
365 pub fn resolved_at(&self, other: Span) -> Span {
366 Span(self.0.resolved_at(other.0))
369 /// Creates a new span with the same name resolution behavior as `self` but
370 /// with the line/column information of `other`.
371 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
372 pub fn located_at(&self, other: Span) -> Span {
373 other.resolved_at(*self)
376 /// Compares to spans to see if they're equal.
377 #[unstable(feature = "proc_macro_span", issue = "54725")]
378 pub fn eq(&self, other: &Span) -> bool {
382 /// Returns the source text behind a span. This preserves the original source
383 /// code, including spaces and comments. It only returns a result if the span
384 /// corresponds to real source code.
386 /// Note: The observable result of a macro should only rely on the tokens and
387 /// not on this source text. The result of this function is a best effort to
388 /// be used for diagnostics only.
389 #[unstable(feature = "proc_macro_span", issue = "54725")]
390 pub fn source_text(&self) -> Option<String> {
394 diagnostic_method!(error, Level::Error);
395 diagnostic_method!(warning, Level::Warning);
396 diagnostic_method!(note, Level::Note);
397 diagnostic_method!(help, Level::Help);
400 /// Prints a span in a form convenient for debugging.
401 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
402 impl fmt::Debug for Span {
403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
408 /// A line-column pair representing the start or end of a `Span`.
409 #[unstable(feature = "proc_macro_span", issue = "54725")]
410 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
411 pub struct LineColumn {
412 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
413 #[unstable(feature = "proc_macro_span", issue = "54725")]
415 /// The 0-indexed column (in UTF-8 characters) in the source file on which
416 /// the span starts or ends (inclusive).
417 #[unstable(feature = "proc_macro_span", issue = "54725")]
421 #[unstable(feature = "proc_macro_span", issue = "54725")]
422 impl !Send for LineColumn {}
423 #[unstable(feature = "proc_macro_span", issue = "54725")]
424 impl !Sync for LineColumn {}
426 #[unstable(feature = "proc_macro_span", issue = "54725")]
427 impl Ord for LineColumn {
428 fn cmp(&self, other: &Self) -> Ordering {
429 self.line.cmp(&other.line).then(self.column.cmp(&other.column))
433 #[unstable(feature = "proc_macro_span", issue = "54725")]
434 impl PartialOrd for LineColumn {
435 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
436 Some(self.cmp(other))
440 /// The source file of a given `Span`.
441 #[unstable(feature = "proc_macro_span", issue = "54725")]
443 pub struct SourceFile(bridge::client::SourceFile);
446 /// Gets the path to this source file.
449 /// If the code span associated with this `SourceFile` was generated by an external macro, this
450 /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
452 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
453 /// the command line, the path as given may not actually be valid.
455 /// [`is_real`]: Self::is_real
456 #[unstable(feature = "proc_macro_span", issue = "54725")]
457 pub fn path(&self) -> PathBuf {
458 PathBuf::from(self.0.path())
461 /// Returns `true` if this source file is a real source file, and not generated by an external
462 /// macro's expansion.
463 #[unstable(feature = "proc_macro_span", issue = "54725")]
464 pub fn is_real(&self) -> bool {
465 // This is a hack until intercrate spans are implemented and we can have real source files
466 // for spans generated in external macros.
467 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
472 #[unstable(feature = "proc_macro_span", issue = "54725")]
473 impl fmt::Debug for SourceFile {
474 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475 f.debug_struct("SourceFile")
476 .field("path", &self.path())
477 .field("is_real", &self.is_real())
482 #[unstable(feature = "proc_macro_span", issue = "54725")]
483 impl PartialEq for SourceFile {
484 fn eq(&self, other: &Self) -> bool {
489 #[unstable(feature = "proc_macro_span", issue = "54725")]
490 impl Eq for SourceFile {}
492 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
493 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
496 /// A token stream surrounded by bracket delimiters.
497 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
498 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
500 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
501 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
502 /// A single punctuation character (`+`, `,`, `$`, etc.).
503 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
504 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
505 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
506 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
507 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
510 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
511 impl !Send for TokenTree {}
512 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
513 impl !Sync for TokenTree {}
516 /// Returns the span of this tree, delegating to the `span` method of
517 /// the contained token or a delimited stream.
518 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
519 pub fn span(&self) -> Span {
521 TokenTree::Group(ref t) => t.span(),
522 TokenTree::Ident(ref t) => t.span(),
523 TokenTree::Punct(ref t) => t.span(),
524 TokenTree::Literal(ref t) => t.span(),
528 /// Configures the span for *only this token*.
530 /// Note that if this token is a `Group` then this method will not configure
531 /// the span of each of the internal tokens, this will simply delegate to
532 /// the `set_span` method of each variant.
533 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
534 pub fn set_span(&mut self, span: Span) {
536 TokenTree::Group(ref mut t) => t.set_span(span),
537 TokenTree::Ident(ref mut t) => t.set_span(span),
538 TokenTree::Punct(ref mut t) => t.set_span(span),
539 TokenTree::Literal(ref mut t) => t.set_span(span),
544 /// Prints token tree in a form convenient for debugging.
545 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
546 impl fmt::Debug for TokenTree {
547 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
548 // Each of these has the name in the struct type in the derived debug,
549 // so don't bother with an extra layer of indirection
551 TokenTree::Group(ref tt) => tt.fmt(f),
552 TokenTree::Ident(ref tt) => tt.fmt(f),
553 TokenTree::Punct(ref tt) => tt.fmt(f),
554 TokenTree::Literal(ref tt) => tt.fmt(f),
559 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
560 impl From<Group> for TokenTree {
561 fn from(g: Group) -> TokenTree {
566 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
567 impl From<Ident> for TokenTree {
568 fn from(g: Ident) -> TokenTree {
573 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
574 impl From<Punct> for TokenTree {
575 fn from(g: Punct) -> TokenTree {
580 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
581 impl From<Literal> for TokenTree {
582 fn from(g: Literal) -> TokenTree {
583 TokenTree::Literal(g)
587 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
588 // based on it (the reverse of the usual relationship between the two).
589 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
590 impl ToString for TokenTree {
591 fn to_string(&self) -> String {
593 TokenTree::Group(ref t) => t.to_string(),
594 TokenTree::Ident(ref t) => t.to_string(),
595 TokenTree::Punct(ref t) => t.to_string(),
596 TokenTree::Literal(ref t) => t.to_string(),
601 /// Prints the token tree as a string that is supposed to be losslessly convertible back
602 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
603 /// with `Delimiter::None` delimiters and negative numeric literals.
604 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
605 impl fmt::Display for TokenTree {
606 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
607 f.write_str(&self.to_string())
611 /// A delimited token stream.
613 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
615 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
616 pub struct Group(bridge::client::Group);
618 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
619 impl !Send for Group {}
620 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
621 impl !Sync for Group {}
623 /// Describes how a sequence of token trees is delimited.
624 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
625 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
628 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
631 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
634 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
637 /// An implicit delimiter, that may, for example, appear around tokens coming from a
638 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
639 /// `$var * 3` where `$var` is `1 + 2`.
640 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
641 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
646 /// Creates a new `Group` with the given delimiter and token stream.
648 /// This constructor will set the span for this group to
649 /// `Span::call_site()`. To change the span you can use the `set_span`
651 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
652 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
653 Group(bridge::client::Group::new(delimiter, stream.0))
656 /// Returns the delimiter of this `Group`
657 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
658 pub fn delimiter(&self) -> Delimiter {
662 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
664 /// Note that the returned token stream does not include the delimiter
666 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
667 pub fn stream(&self) -> TokenStream {
668 TokenStream(self.0.stream())
671 /// Returns the span for the delimiters of this token stream, spanning the
675 /// pub fn span(&self) -> Span {
678 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
679 pub fn span(&self) -> Span {
683 /// Returns the span pointing to the opening delimiter of this group.
686 /// pub fn span_open(&self) -> Span {
689 #[unstable(feature = "proc_macro_span", issue = "54725")]
690 pub fn span_open(&self) -> Span {
691 Span(self.0.span_open())
694 /// Returns the span pointing to the closing delimiter of this group.
697 /// pub fn span_close(&self) -> Span {
700 #[unstable(feature = "proc_macro_span", issue = "54725")]
701 pub fn span_close(&self) -> Span {
702 Span(self.0.span_close())
705 /// Configures the span for this `Group`'s delimiters, but not its internal
708 /// This method will **not** set the span of all the internal tokens spanned
709 /// by this group, but rather it will only set the span of the delimiter
710 /// tokens at the level of the `Group`.
711 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
712 pub fn set_span(&mut self, span: Span) {
713 self.0.set_span(span.0);
717 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
718 // based on it (the reverse of the usual relationship between the two).
719 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
720 impl ToString for Group {
721 fn to_string(&self) -> String {
722 TokenStream::from(TokenTree::from(self.clone())).to_string()
726 /// Prints the group as a string that should be losslessly convertible back
727 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
728 /// with `Delimiter::None` delimiters.
729 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
730 impl fmt::Display for Group {
731 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
732 f.write_str(&self.to_string())
736 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
737 impl fmt::Debug for Group {
738 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
739 f.debug_struct("Group")
740 .field("delimiter", &self.delimiter())
741 .field("stream", &self.stream())
742 .field("span", &self.span())
747 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
749 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
750 /// forms of `Spacing` returned.
751 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
753 pub struct Punct(bridge::client::Punct);
755 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
756 impl !Send for Punct {}
757 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
758 impl !Sync for Punct {}
760 /// Whether an `Punct` is followed immediately by another `Punct` or
761 /// followed by another token or whitespace.
762 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
763 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
765 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
766 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
768 /// e.g., `+` is `Joint` in `+=` or `'#`.
769 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
770 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
775 /// Creates a new `Punct` from the given character and spacing.
776 /// The `ch` argument must be a valid punctuation character permitted by the language,
777 /// otherwise the function will panic.
779 /// The returned `Punct` will have the default span of `Span::call_site()`
780 /// which can be further configured with the `set_span` method below.
781 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
782 pub fn new(ch: char, spacing: Spacing) -> Punct {
783 Punct(bridge::client::Punct::new(ch, spacing))
786 /// Returns the value of this punctuation character as `char`.
787 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
788 pub fn as_char(&self) -> char {
792 /// Returns the spacing of this punctuation character, indicating whether it's immediately
793 /// followed by another `Punct` in the token stream, so they can potentially be combined into
794 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
795 /// (`Alone`) so the operator has certainly ended.
796 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
797 pub fn spacing(&self) -> Spacing {
801 /// Returns the span for this punctuation character.
802 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
803 pub fn span(&self) -> Span {
807 /// Configure the span for this punctuation character.
808 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
809 pub fn set_span(&mut self, span: Span) {
810 self.0 = self.0.with_span(span.0);
814 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
815 // based on it (the reverse of the usual relationship between the two).
816 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
817 impl ToString for Punct {
818 fn to_string(&self) -> String {
819 TokenStream::from(TokenTree::from(self.clone())).to_string()
823 /// Prints the punctuation character as a string that should be losslessly convertible
824 /// back into the same character.
825 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
826 impl fmt::Display for Punct {
827 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
828 f.write_str(&self.to_string())
832 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
833 impl fmt::Debug for Punct {
834 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
835 f.debug_struct("Punct")
836 .field("ch", &self.as_char())
837 .field("spacing", &self.spacing())
838 .field("span", &self.span())
843 /// An identifier (`ident`).
845 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
846 pub struct Ident(bridge::client::Ident);
849 /// Creates a new `Ident` with the given `string` as well as the specified
851 /// The `string` argument must be a valid identifier permitted by the
852 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
854 /// Note that `span`, currently in rustc, configures the hygiene information
855 /// for this identifier.
857 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
858 /// meaning that identifiers created with this span will be resolved as if they were written
859 /// directly at the location of the macro call, and other code at the macro call site will be
860 /// able to refer to them as well.
862 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
863 /// meaning that identifiers created with this span will be resolved at the location of the
864 /// macro definition and other code at the macro call site will not be able to refer to them.
866 /// Due to the current importance of hygiene this constructor, unlike other
867 /// tokens, requires a `Span` to be specified at construction.
868 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
869 pub fn new(string: &str, span: Span) -> Ident {
870 Ident(bridge::client::Ident::new(string, span.0, false))
873 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
874 /// The `string` argument be a valid identifier permitted by the language
875 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
876 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
877 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
878 pub fn new_raw(string: &str, span: Span) -> Ident {
879 Ident(bridge::client::Ident::new(string, span.0, true))
882 /// Returns the span of this `Ident`, encompassing the entire string returned
884 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
885 pub fn span(&self) -> Span {
889 /// Configures the span of this `Ident`, possibly changing its hygiene context.
890 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
891 pub fn set_span(&mut self, span: Span) {
892 self.0 = self.0.with_span(span.0);
896 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
897 // based on it (the reverse of the usual relationship between the two).
898 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
899 impl ToString for Ident {
900 fn to_string(&self) -> String {
901 TokenStream::from(TokenTree::from(self.clone())).to_string()
905 /// Prints the identifier as a string that should be losslessly convertible
906 /// back into the same identifier.
907 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
908 impl fmt::Display for Ident {
909 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
910 f.write_str(&self.to_string())
914 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
915 impl fmt::Debug for Ident {
916 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
917 f.debug_struct("Ident")
918 .field("ident", &self.to_string())
919 .field("span", &self.span())
924 /// A literal string (`"hello"`), byte string (`b"hello"`),
925 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
926 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
927 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
929 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
930 pub struct Literal(bridge::client::Literal);
932 macro_rules! suffixed_int_literals {
933 ($($name:ident => $kind:ident,)*) => ($(
934 /// Creates a new suffixed integer literal with the specified value.
936 /// This function will create an integer like `1u32` where the integer
937 /// value specified is the first part of the token and the integral is
938 /// also suffixed at the end.
939 /// Literals created from negative numbers may not survive round-trips through
940 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
942 /// Literals created through this method have the `Span::call_site()`
943 /// span by default, which can be configured with the `set_span` method
945 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
946 pub fn $name(n: $kind) -> Literal {
947 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
952 macro_rules! unsuffixed_int_literals {
953 ($($name:ident => $kind:ident,)*) => ($(
954 /// Creates a new unsuffixed integer literal with the specified value.
956 /// This function will create an integer like `1` where the integer
957 /// value specified is the first part of the token. No suffix is
958 /// specified on this token, meaning that invocations like
959 /// `Literal::i8_unsuffixed(1)` are equivalent to
960 /// `Literal::u32_unsuffixed(1)`.
961 /// Literals created from negative numbers may not survive rountrips through
962 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
964 /// Literals created through this method have the `Span::call_site()`
965 /// span by default, which can be configured with the `set_span` method
967 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
968 pub fn $name(n: $kind) -> Literal {
969 Literal(bridge::client::Literal::integer(&n.to_string()))
975 suffixed_int_literals! {
980 u128_suffixed => u128,
981 usize_suffixed => usize,
986 i128_suffixed => i128,
987 isize_suffixed => isize,
990 unsuffixed_int_literals! {
992 u16_unsuffixed => u16,
993 u32_unsuffixed => u32,
994 u64_unsuffixed => u64,
995 u128_unsuffixed => u128,
996 usize_unsuffixed => usize,
998 i16_unsuffixed => i16,
999 i32_unsuffixed => i32,
1000 i64_unsuffixed => i64,
1001 i128_unsuffixed => i128,
1002 isize_unsuffixed => isize,
1005 /// Creates a new unsuffixed floating-point literal.
1007 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1008 /// the float's value is emitted directly into the token but no suffix is
1009 /// used, so it may be inferred to be a `f64` later in the compiler.
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 f32_unsuffixed(n: f32) -> Literal {
1020 panic!("Invalid float literal {}", n);
1022 Literal(bridge::client::Literal::float(&n.to_string()))
1025 /// Creates a new suffixed floating-point literal.
1027 /// This constructor will create a literal like `1.0f32` where the value
1028 /// specified is the preceding part of the token and `f32` is the suffix of
1029 /// the token. This token will always be inferred to be an `f32` in the
1031 /// Literals created from negative numbers may not survive rountrips through
1032 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1036 /// This function requires that the specified float is finite, for
1037 /// example if it is infinity or NaN this function will panic.
1038 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1039 pub fn f32_suffixed(n: f32) -> Literal {
1041 panic!("Invalid float literal {}", n);
1043 Literal(bridge::client::Literal::f32(&n.to_string()))
1046 /// Creates a new unsuffixed floating-point literal.
1048 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1049 /// the float's value is emitted directly into the token but no suffix is
1050 /// used, so it may be inferred to be a `f64` later in the compiler.
1051 /// Literals created from negative numbers may not survive rountrips through
1052 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1056 /// This function requires that the specified float is finite, for
1057 /// example if it is infinity or NaN this function will panic.
1058 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1059 pub fn f64_unsuffixed(n: f64) -> Literal {
1061 panic!("Invalid float literal {}", n);
1063 Literal(bridge::client::Literal::float(&n.to_string()))
1066 /// Creates a new suffixed floating-point literal.
1068 /// This constructor will create a literal like `1.0f64` where the value
1069 /// specified is the preceding part of the token and `f64` is the suffix of
1070 /// the token. This token will always be inferred to be an `f64` in the
1072 /// Literals created from negative numbers may not survive rountrips through
1073 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1077 /// This function requires that the specified float is finite, for
1078 /// example if it is infinity or NaN this function will panic.
1079 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1080 pub fn f64_suffixed(n: f64) -> Literal {
1082 panic!("Invalid float literal {}", n);
1084 Literal(bridge::client::Literal::f64(&n.to_string()))
1088 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1089 pub fn string(string: &str) -> Literal {
1090 Literal(bridge::client::Literal::string(string))
1093 /// Character literal.
1094 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1095 pub fn character(ch: char) -> Literal {
1096 Literal(bridge::client::Literal::character(ch))
1099 /// Byte string literal.
1100 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1101 pub fn byte_string(bytes: &[u8]) -> Literal {
1102 Literal(bridge::client::Literal::byte_string(bytes))
1105 /// Returns the span encompassing this literal.
1106 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1107 pub fn span(&self) -> Span {
1111 /// Configures the span associated for this literal.
1112 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1113 pub fn set_span(&mut self, span: Span) {
1114 self.0.set_span(span.0);
1117 /// Returns a `Span` that is a subset of `self.span()` containing only the
1118 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1119 /// span is outside the bounds of `self`.
1120 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1121 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1122 // occur elsewhere when the source text is printed.
1123 // FIXME(SergioBenitez): there is no way for the user to know what
1124 // `self.span()` actually maps to, so this method can currently only be
1125 // called blindly. For example, `to_string()` for the character 'c' returns
1126 // "'\u{63}'"; there is no way for the user to know whether the source text
1127 // was 'c' or whether it was '\u{63}'.
1128 #[unstable(feature = "proc_macro_span", issue = "54725")]
1129 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1130 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1131 fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1133 Bound::Included(x) => Bound::Included(x.clone()),
1134 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1135 Bound::Unbounded => Bound::Unbounded,
1139 self.0.subspan(cloned_bound(range.start_bound()), cloned_bound(range.end_bound())).map(Span)
1143 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1144 // based on it (the reverse of the usual relationship between the two).
1145 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1146 impl ToString for Literal {
1147 fn to_string(&self) -> String {
1148 TokenStream::from(TokenTree::from(self.clone())).to_string()
1152 /// Prints the literal as a string that should be losslessly convertible
1153 /// back into the same literal (except for possible rounding for floating point literals).
1154 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1155 impl fmt::Display for Literal {
1156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1157 f.write_str(&self.to_string())
1161 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1162 impl fmt::Debug for Literal {
1163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1168 /// Tracked access to environment variables.
1169 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1170 pub mod tracked_env {
1171 use std::env::{self, VarError};
1172 use std::ffi::OsStr;
1174 /// Retrieve an environment variable and add it to build dependency info.
1175 /// Build system executing the compiler will know that the variable was accessed during
1176 /// compilation, and will be able to rerun the build when the value of that variable changes.
1177 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1178 /// standard library, except that the argument must be UTF-8.
1179 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1180 pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1181 let key: &str = key.as_ref();
1182 let value = env::var(key);
1183 crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());