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_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 #![feature(rustc_allow_const_fn_unstable)]
22 #![feature(staged_api)]
23 #![feature(const_fn_trait_bound)]
24 #![feature(const_fn_fn_ptr_basics)]
25 #![feature(allow_internal_unstable)]
26 #![feature(decl_macro)]
27 #![feature(extern_types)]
28 #![feature(in_band_lifetimes)]
29 #![feature(negative_impls)]
30 #![feature(auto_traits)]
31 #![feature(restricted_std)]
32 #![feature(rustc_attrs)]
33 #![feature(min_specialization)]
34 #![recursion_limit = "256"]
36 #[unstable(feature = "proc_macro_internals", issue = "27812")]
42 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
43 pub use diagnostic::{Diagnostic, Level, MultiSpan};
45 use std::cmp::Ordering;
46 use std::ops::{Bound, RangeBounds};
47 use std::path::PathBuf;
48 use std::str::FromStr;
49 use std::{error, fmt, iter, mem};
51 /// Determines whether proc_macro has been made accessible to the currently
54 /// The proc_macro crate is only intended for use inside the implementation of
55 /// procedural macros. All the functions in this crate panic if invoked from
56 /// outside of a procedural macro, such as from a build script or unit test or
57 /// ordinary Rust binary.
59 /// With consideration for Rust libraries that are designed to support both
60 /// macro and non-macro use cases, `proc_macro::is_available()` provides a
61 /// non-panicking way to detect whether the infrastructure required to use the
62 /// API of proc_macro is presently available. Returns true if invoked from
63 /// inside of a procedural macro, false if invoked from any other binary.
64 #[unstable(feature = "proc_macro_is_available", issue = "71436")]
65 pub fn is_available() -> bool {
66 bridge::Bridge::is_available()
69 /// The main type provided by this crate, representing an abstract stream of
70 /// tokens, or, more specifically, a sequence of token trees.
71 /// The type provide interfaces for iterating over those token trees and, conversely,
72 /// collecting a number of token trees into one stream.
74 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
75 /// and `#[proc_macro_derive]` definitions.
76 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
78 pub struct TokenStream(bridge::client::TokenStream);
80 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
81 impl !Send for TokenStream {}
82 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
83 impl !Sync for TokenStream {}
85 /// Error returned from `TokenStream::from_str`.
86 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
94 LexError { _inner: () }
98 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
99 impl fmt::Display for LexError {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 f.write_str("cannot parse string into token stream")
105 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
106 impl error::Error for LexError {}
108 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
109 impl !Send for LexError {}
110 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
111 impl !Sync for LexError {}
114 /// Returns an empty `TokenStream` containing no token trees.
115 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
116 pub fn new() -> TokenStream {
117 TokenStream(bridge::client::TokenStream::new())
120 /// Checks if this `TokenStream` is empty.
121 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
122 pub fn is_empty(&self) -> bool {
127 /// Attempts to break the string into tokens and parse those tokens into a token stream.
128 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
129 /// or characters not existing in the language.
130 /// All tokens in the parsed stream get `Span::call_site()` spans.
132 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
133 /// change these errors into `LexError`s later.
134 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
135 impl FromStr for TokenStream {
138 fn from_str(src: &str) -> Result<TokenStream, LexError> {
139 Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
143 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
144 // based on it (the reverse of the usual relationship between the two).
145 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
146 impl ToString for TokenStream {
147 fn to_string(&self) -> String {
152 /// Prints the token stream as a string that is supposed to be losslessly convertible back
153 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
154 /// with `Delimiter::None` delimiters and negative numeric literals.
155 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
156 impl fmt::Display for TokenStream {
157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158 f.write_str(&self.to_string())
162 /// Prints token in a form convenient for debugging.
163 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
164 impl fmt::Debug for TokenStream {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 f.write_str("TokenStream ")?;
167 f.debug_list().entries(self.clone()).finish()
171 #[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
172 impl Default for TokenStream {
173 fn default() -> Self {
178 #[unstable(feature = "proc_macro_quote", issue = "54722")]
179 pub use quote::{quote, quote_span};
181 /// Creates a token stream containing a single token tree.
182 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
183 impl From<TokenTree> for TokenStream {
184 fn from(tree: TokenTree) -> TokenStream {
185 TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
186 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
187 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
188 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
189 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
194 /// Collects a number of token trees into a single stream.
195 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
196 impl iter::FromIterator<TokenTree> for TokenStream {
197 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
198 trees.into_iter().map(TokenStream::from).collect()
202 /// A "flattening" operation on token streams, collects token trees
203 /// from multiple token streams into a single stream.
204 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
205 impl iter::FromIterator<TokenStream> for TokenStream {
206 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
207 let mut builder = bridge::client::TokenStreamBuilder::new();
208 streams.into_iter().for_each(|stream| builder.push(stream.0));
209 TokenStream(builder.build())
213 #[stable(feature = "token_stream_extend", since = "1.30.0")]
214 impl Extend<TokenTree> for TokenStream {
215 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
216 self.extend(trees.into_iter().map(TokenStream::from));
220 #[stable(feature = "token_stream_extend", since = "1.30.0")]
221 impl Extend<TokenStream> for TokenStream {
222 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
223 // FIXME(eddyb) Use an optimized implementation if/when possible.
224 *self = iter::once(mem::replace(self, Self::new())).chain(streams).collect();
228 /// Public implementation details for the `TokenStream` type, such as iterators.
229 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
230 pub mod token_stream {
231 use crate::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree};
233 /// An iterator over `TokenStream`'s `TokenTree`s.
234 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
235 /// and returns whole groups as token trees.
237 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
238 pub struct IntoIter(bridge::client::TokenStreamIter);
240 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
241 impl Iterator for IntoIter {
242 type Item = TokenTree;
244 fn next(&mut self) -> Option<TokenTree> {
245 self.0.next().map(|tree| match tree {
246 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
247 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
248 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
249 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
254 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
255 impl IntoIterator for TokenStream {
256 type Item = TokenTree;
257 type IntoIter = IntoIter;
259 fn into_iter(self) -> IntoIter {
260 IntoIter(self.0.into_iter())
265 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
266 /// For example, `quote!(a + b)` will produce a expression, that, when evaluated, constructs
267 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
269 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
270 /// To quote `$` itself, use `$$`.
271 #[unstable(feature = "proc_macro_quote", issue = "54722")]
272 #[allow_internal_unstable(proc_macro_def_site, proc_macro_internals)]
273 #[rustc_builtin_macro]
274 pub macro quote($($t:tt)*) {
275 /* compiler built-in */
278 #[unstable(feature = "proc_macro_internals", issue = "27812")]
282 /// A region of source code, along with macro expansion information.
283 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
284 #[derive(Copy, Clone)]
285 pub struct Span(bridge::client::Span);
287 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
288 impl !Send for Span {}
289 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
290 impl !Sync for Span {}
292 macro_rules! diagnostic_method {
293 ($name:ident, $level:expr) => {
294 /// Creates a new `Diagnostic` with the given `message` at the span
296 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
297 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
298 Diagnostic::spanned(self, $level, message)
304 /// A span that resolves at the macro definition site.
305 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
306 pub fn def_site() -> Span {
307 Span(bridge::client::Span::def_site())
310 /// The span of the invocation of the current procedural macro.
311 /// Identifiers created with this span will be resolved as if they were written
312 /// directly at the macro call location (call-site hygiene) and other code
313 /// at the macro call site will be able to refer to them as well.
314 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
315 pub fn call_site() -> Span {
316 Span(bridge::client::Span::call_site())
319 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
320 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
321 /// call site (everything else).
322 /// The span location is taken from the call-site.
323 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
324 pub fn mixed_site() -> Span {
325 Span(bridge::client::Span::mixed_site())
328 /// The original source file into which this span points.
329 #[unstable(feature = "proc_macro_span", issue = "54725")]
330 pub fn source_file(&self) -> SourceFile {
331 SourceFile(self.0.source_file())
334 /// The `Span` for the tokens in the previous macro expansion from which
335 /// `self` was generated from, if any.
336 #[unstable(feature = "proc_macro_span", issue = "54725")]
337 pub fn parent(&self) -> Option<Span> {
338 self.0.parent().map(Span)
341 /// The span for the origin source code that `self` was generated from. If
342 /// this `Span` wasn't generated from other macro expansions then the return
343 /// value is the same as `*self`.
344 #[unstable(feature = "proc_macro_span", issue = "54725")]
345 pub fn source(&self) -> Span {
346 Span(self.0.source())
349 /// Gets the starting line/column in the source file for this span.
350 #[unstable(feature = "proc_macro_span", issue = "54725")]
351 pub fn start(&self) -> LineColumn {
355 /// Gets the ending line/column in the source file for this span.
356 #[unstable(feature = "proc_macro_span", issue = "54725")]
357 pub fn end(&self) -> LineColumn {
361 /// Creates a new span encompassing `self` and `other`.
363 /// Returns `None` if `self` and `other` are from different files.
364 #[unstable(feature = "proc_macro_span", issue = "54725")]
365 pub fn join(&self, other: Span) -> Option<Span> {
366 self.0.join(other.0).map(Span)
369 /// Creates a new span with the same line/column information as `self` but
370 /// that resolves symbols as though it were at `other`.
371 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
372 pub fn resolved_at(&self, other: Span) -> Span {
373 Span(self.0.resolved_at(other.0))
376 /// Creates a new span with the same name resolution behavior as `self` but
377 /// with the line/column information of `other`.
378 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
379 pub fn located_at(&self, other: Span) -> Span {
380 other.resolved_at(*self)
383 /// Compares to spans to see if they're equal.
384 #[unstable(feature = "proc_macro_span", issue = "54725")]
385 pub fn eq(&self, other: &Span) -> bool {
389 /// Returns the source text behind a span. This preserves the original source
390 /// code, including spaces and comments. It only returns a result if the span
391 /// corresponds to real source code.
393 /// Note: The observable result of a macro should only rely on the tokens and
394 /// not on this source text. The result of this function is a best effort to
395 /// be used for diagnostics only.
396 #[unstable(feature = "proc_macro_span", issue = "54725")]
397 pub fn source_text(&self) -> Option<String> {
401 // Used by the implementation of `Span::quote`
403 #[unstable(feature = "proc_macro_internals", issue = "27812")]
404 pub fn save_span(&self) -> usize {
408 // Used by the implementation of `Span::quote`
410 #[unstable(feature = "proc_macro_internals", issue = "27812")]
411 pub fn recover_proc_macro_span(id: usize) -> Span {
412 Span(bridge::client::Span::recover_proc_macro_span(id))
415 diagnostic_method!(error, Level::Error);
416 diagnostic_method!(warning, Level::Warning);
417 diagnostic_method!(note, Level::Note);
418 diagnostic_method!(help, Level::Help);
421 /// Prints a span in a form convenient for debugging.
422 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
423 impl fmt::Debug for Span {
424 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
429 /// A line-column pair representing the start or end of a `Span`.
430 #[unstable(feature = "proc_macro_span", issue = "54725")]
431 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
432 pub struct LineColumn {
433 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
434 #[unstable(feature = "proc_macro_span", issue = "54725")]
436 /// The 0-indexed column (in UTF-8 characters) in the source file on which
437 /// the span starts or ends (inclusive).
438 #[unstable(feature = "proc_macro_span", issue = "54725")]
442 #[unstable(feature = "proc_macro_span", issue = "54725")]
443 impl !Send for LineColumn {}
444 #[unstable(feature = "proc_macro_span", issue = "54725")]
445 impl !Sync for LineColumn {}
447 #[unstable(feature = "proc_macro_span", issue = "54725")]
448 impl Ord for LineColumn {
449 fn cmp(&self, other: &Self) -> Ordering {
450 self.line.cmp(&other.line).then(self.column.cmp(&other.column))
454 #[unstable(feature = "proc_macro_span", issue = "54725")]
455 impl PartialOrd for LineColumn {
456 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
457 Some(self.cmp(other))
461 /// The source file of a given `Span`.
462 #[unstable(feature = "proc_macro_span", issue = "54725")]
464 pub struct SourceFile(bridge::client::SourceFile);
467 /// Gets the path to this source file.
470 /// If the code span associated with this `SourceFile` was generated by an external macro, this
471 /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
473 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
474 /// the command line, the path as given may not actually be valid.
476 /// [`is_real`]: Self::is_real
477 #[unstable(feature = "proc_macro_span", issue = "54725")]
478 pub fn path(&self) -> PathBuf {
479 PathBuf::from(self.0.path())
482 /// Returns `true` if this source file is a real source file, and not generated by an external
483 /// macro's expansion.
484 #[unstable(feature = "proc_macro_span", issue = "54725")]
485 pub fn is_real(&self) -> bool {
486 // This is a hack until intercrate spans are implemented and we can have real source files
487 // for spans generated in external macros.
488 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
493 #[unstable(feature = "proc_macro_span", issue = "54725")]
494 impl fmt::Debug for SourceFile {
495 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
496 f.debug_struct("SourceFile")
497 .field("path", &self.path())
498 .field("is_real", &self.is_real())
503 #[unstable(feature = "proc_macro_span", issue = "54725")]
504 impl PartialEq for SourceFile {
505 fn eq(&self, other: &Self) -> bool {
510 #[unstable(feature = "proc_macro_span", issue = "54725")]
511 impl Eq for SourceFile {}
513 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
514 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
517 /// A token stream surrounded by bracket delimiters.
518 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
519 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
521 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
522 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
523 /// A single punctuation character (`+`, `,`, `$`, etc.).
524 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
525 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
526 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
527 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
528 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
531 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
532 impl !Send for TokenTree {}
533 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
534 impl !Sync for TokenTree {}
537 /// Returns the span of this tree, delegating to the `span` method of
538 /// the contained token or a delimited stream.
539 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
540 pub fn span(&self) -> Span {
542 TokenTree::Group(ref t) => t.span(),
543 TokenTree::Ident(ref t) => t.span(),
544 TokenTree::Punct(ref t) => t.span(),
545 TokenTree::Literal(ref t) => t.span(),
549 /// Configures the span for *only this token*.
551 /// Note that if this token is a `Group` then this method will not configure
552 /// the span of each of the internal tokens, this will simply delegate to
553 /// the `set_span` method of each variant.
554 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
555 pub fn set_span(&mut self, span: Span) {
557 TokenTree::Group(ref mut t) => t.set_span(span),
558 TokenTree::Ident(ref mut t) => t.set_span(span),
559 TokenTree::Punct(ref mut t) => t.set_span(span),
560 TokenTree::Literal(ref mut t) => t.set_span(span),
565 /// Prints token tree in a form convenient for debugging.
566 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
567 impl fmt::Debug for TokenTree {
568 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
569 // Each of these has the name in the struct type in the derived debug,
570 // so don't bother with an extra layer of indirection
572 TokenTree::Group(ref tt) => tt.fmt(f),
573 TokenTree::Ident(ref tt) => tt.fmt(f),
574 TokenTree::Punct(ref tt) => tt.fmt(f),
575 TokenTree::Literal(ref tt) => tt.fmt(f),
580 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
581 impl From<Group> for TokenTree {
582 fn from(g: Group) -> TokenTree {
587 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
588 impl From<Ident> for TokenTree {
589 fn from(g: Ident) -> TokenTree {
594 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
595 impl From<Punct> for TokenTree {
596 fn from(g: Punct) -> TokenTree {
601 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
602 impl From<Literal> for TokenTree {
603 fn from(g: Literal) -> TokenTree {
604 TokenTree::Literal(g)
608 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
609 // based on it (the reverse of the usual relationship between the two).
610 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
611 impl ToString for TokenTree {
612 fn to_string(&self) -> String {
614 TokenTree::Group(ref t) => t.to_string(),
615 TokenTree::Ident(ref t) => t.to_string(),
616 TokenTree::Punct(ref t) => t.to_string(),
617 TokenTree::Literal(ref t) => t.to_string(),
622 /// Prints the token tree as a string that is supposed to be losslessly convertible back
623 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
624 /// with `Delimiter::None` delimiters and negative numeric literals.
625 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
626 impl fmt::Display for TokenTree {
627 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
628 f.write_str(&self.to_string())
632 /// A delimited token stream.
634 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
636 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
637 pub struct Group(bridge::client::Group);
639 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
640 impl !Send for Group {}
641 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
642 impl !Sync for Group {}
644 /// Describes how a sequence of token trees is delimited.
645 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
646 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
649 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
652 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
655 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
658 /// An implicit delimiter, that may, for example, appear around tokens coming from a
659 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
660 /// `$var * 3` where `$var` is `1 + 2`.
661 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
662 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
667 /// Creates a new `Group` with the given delimiter and token stream.
669 /// This constructor will set the span for this group to
670 /// `Span::call_site()`. To change the span you can use the `set_span`
672 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
673 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
674 Group(bridge::client::Group::new(delimiter, stream.0))
677 /// Returns the delimiter of this `Group`
678 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
679 pub fn delimiter(&self) -> Delimiter {
683 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
685 /// Note that the returned token stream does not include the delimiter
687 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
688 pub fn stream(&self) -> TokenStream {
689 TokenStream(self.0.stream())
692 /// Returns the span for the delimiters of this token stream, spanning the
696 /// pub fn span(&self) -> Span {
699 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
700 pub fn span(&self) -> Span {
704 /// Returns the span pointing to the opening delimiter of this group.
707 /// pub fn span_open(&self) -> Span {
710 #[unstable(feature = "proc_macro_span", issue = "54725")]
711 pub fn span_open(&self) -> Span {
712 Span(self.0.span_open())
715 /// Returns the span pointing to the closing delimiter of this group.
718 /// pub fn span_close(&self) -> Span {
721 #[unstable(feature = "proc_macro_span", issue = "54725")]
722 pub fn span_close(&self) -> Span {
723 Span(self.0.span_close())
726 /// Configures the span for this `Group`'s delimiters, but not its internal
729 /// This method will **not** set the span of all the internal tokens spanned
730 /// by this group, but rather it will only set the span of the delimiter
731 /// tokens at the level of the `Group`.
732 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
733 pub fn set_span(&mut self, span: Span) {
734 self.0.set_span(span.0);
738 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
739 // based on it (the reverse of the usual relationship between the two).
740 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
741 impl ToString for Group {
742 fn to_string(&self) -> String {
743 TokenStream::from(TokenTree::from(self.clone())).to_string()
747 /// Prints the group as a string that should be losslessly convertible back
748 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
749 /// with `Delimiter::None` delimiters.
750 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
751 impl fmt::Display for Group {
752 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
753 f.write_str(&self.to_string())
757 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
758 impl fmt::Debug for Group {
759 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
760 f.debug_struct("Group")
761 .field("delimiter", &self.delimiter())
762 .field("stream", &self.stream())
763 .field("span", &self.span())
768 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
770 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
771 /// forms of `Spacing` returned.
772 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
774 pub struct Punct(bridge::client::Punct);
776 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
777 impl !Send for Punct {}
778 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
779 impl !Sync for Punct {}
781 /// Whether an `Punct` is followed immediately by another `Punct` or
782 /// followed by another token or whitespace.
783 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
784 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
786 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
787 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
789 /// e.g., `+` is `Joint` in `+=` or `'#`.
790 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
791 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
796 /// Creates a new `Punct` from the given character and spacing.
797 /// The `ch` argument must be a valid punctuation character permitted by the language,
798 /// otherwise the function will panic.
800 /// The returned `Punct` will have the default span of `Span::call_site()`
801 /// which can be further configured with the `set_span` method below.
802 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
803 pub fn new(ch: char, spacing: Spacing) -> Punct {
804 Punct(bridge::client::Punct::new(ch, spacing))
807 /// Returns the value of this punctuation character as `char`.
808 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
809 pub fn as_char(&self) -> char {
813 /// Returns the spacing of this punctuation character, indicating whether it's immediately
814 /// followed by another `Punct` in the token stream, so they can potentially be combined into
815 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
816 /// (`Alone`) so the operator has certainly ended.
817 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
818 pub fn spacing(&self) -> Spacing {
822 /// Returns the span for this punctuation character.
823 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
824 pub fn span(&self) -> Span {
828 /// Configure the span for this punctuation character.
829 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
830 pub fn set_span(&mut self, span: Span) {
831 self.0 = self.0.with_span(span.0);
835 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
836 // based on it (the reverse of the usual relationship between the two).
837 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
838 impl ToString for Punct {
839 fn to_string(&self) -> String {
840 TokenStream::from(TokenTree::from(self.clone())).to_string()
844 /// Prints the punctuation character as a string that should be losslessly convertible
845 /// back into the same character.
846 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
847 impl fmt::Display for Punct {
848 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849 f.write_str(&self.to_string())
853 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
854 impl fmt::Debug for Punct {
855 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
856 f.debug_struct("Punct")
857 .field("ch", &self.as_char())
858 .field("spacing", &self.spacing())
859 .field("span", &self.span())
864 #[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
865 impl PartialEq<char> for Punct {
866 fn eq(&self, rhs: &char) -> bool {
867 self.as_char() == *rhs
871 #[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
872 impl PartialEq<Punct> for char {
873 fn eq(&self, rhs: &Punct) -> bool {
874 *self == rhs.as_char()
878 /// An identifier (`ident`).
880 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
881 pub struct Ident(bridge::client::Ident);
884 /// Creates a new `Ident` with the given `string` as well as the specified
886 /// The `string` argument must be a valid identifier permitted by the
887 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
889 /// Note that `span`, currently in rustc, configures the hygiene information
890 /// for this identifier.
892 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
893 /// meaning that identifiers created with this span will be resolved as if they were written
894 /// directly at the location of the macro call, and other code at the macro call site will be
895 /// able to refer to them as well.
897 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
898 /// meaning that identifiers created with this span will be resolved at the location of the
899 /// macro definition and other code at the macro call site will not be able to refer to them.
901 /// Due to the current importance of hygiene this constructor, unlike other
902 /// tokens, requires a `Span` to be specified at construction.
903 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
904 pub fn new(string: &str, span: Span) -> Ident {
905 Ident(bridge::client::Ident::new(string, span.0, false))
908 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
909 /// The `string` argument be a valid identifier permitted by the language
910 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
911 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
912 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
913 pub fn new_raw(string: &str, span: Span) -> Ident {
914 Ident(bridge::client::Ident::new(string, span.0, true))
917 /// Returns the span of this `Ident`, encompassing the entire string returned
918 /// by [`to_string`](Self::to_string).
919 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
920 pub fn span(&self) -> Span {
924 /// Configures the span of this `Ident`, possibly changing its hygiene context.
925 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
926 pub fn set_span(&mut self, span: Span) {
927 self.0 = self.0.with_span(span.0);
931 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
932 // based on it (the reverse of the usual relationship between the two).
933 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
934 impl ToString for Ident {
935 fn to_string(&self) -> String {
936 TokenStream::from(TokenTree::from(self.clone())).to_string()
940 /// Prints the identifier as a string that should be losslessly convertible
941 /// back into the same identifier.
942 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
943 impl fmt::Display for Ident {
944 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
945 f.write_str(&self.to_string())
949 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
950 impl fmt::Debug for Ident {
951 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
952 f.debug_struct("Ident")
953 .field("ident", &self.to_string())
954 .field("span", &self.span())
959 /// A literal string (`"hello"`), byte string (`b"hello"`),
960 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
961 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
962 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
964 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
965 pub struct Literal(bridge::client::Literal);
967 macro_rules! suffixed_int_literals {
968 ($($name:ident => $kind:ident,)*) => ($(
969 /// Creates a new suffixed integer literal with the specified value.
971 /// This function will create an integer like `1u32` where the integer
972 /// value specified is the first part of the token and the integral is
973 /// also suffixed at the end.
974 /// Literals created from negative numbers may not survive round-trips through
975 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
977 /// Literals created through this method have the `Span::call_site()`
978 /// span by default, which can be configured with the `set_span` method
980 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
981 pub fn $name(n: $kind) -> Literal {
982 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
987 macro_rules! unsuffixed_int_literals {
988 ($($name:ident => $kind:ident,)*) => ($(
989 /// Creates a new unsuffixed integer literal with the specified value.
991 /// This function will create an integer like `1` where the integer
992 /// value specified is the first part of the token. No suffix is
993 /// specified on this token, meaning that invocations like
994 /// `Literal::i8_unsuffixed(1)` are equivalent to
995 /// `Literal::u32_unsuffixed(1)`.
996 /// Literals created from negative numbers may not survive rountrips through
997 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
999 /// Literals created through this method have the `Span::call_site()`
1000 /// span by default, which can be configured with the `set_span` method
1002 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1003 pub fn $name(n: $kind) -> Literal {
1004 Literal(bridge::client::Literal::integer(&n.to_string()))
1010 suffixed_int_literals! {
1012 u16_suffixed => u16,
1013 u32_suffixed => u32,
1014 u64_suffixed => u64,
1015 u128_suffixed => u128,
1016 usize_suffixed => usize,
1018 i16_suffixed => i16,
1019 i32_suffixed => i32,
1020 i64_suffixed => i64,
1021 i128_suffixed => i128,
1022 isize_suffixed => isize,
1025 unsuffixed_int_literals! {
1026 u8_unsuffixed => u8,
1027 u16_unsuffixed => u16,
1028 u32_unsuffixed => u32,
1029 u64_unsuffixed => u64,
1030 u128_unsuffixed => u128,
1031 usize_unsuffixed => usize,
1032 i8_unsuffixed => i8,
1033 i16_unsuffixed => i16,
1034 i32_unsuffixed => i32,
1035 i64_unsuffixed => i64,
1036 i128_unsuffixed => i128,
1037 isize_unsuffixed => isize,
1040 /// Creates a new unsuffixed floating-point literal.
1042 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1043 /// the float's value is emitted directly into the token but no suffix is
1044 /// used, so it may be inferred to be a `f64` later in the compiler.
1045 /// Literals created from negative numbers may not survive rountrips through
1046 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1050 /// This function requires that the specified float is finite, for
1051 /// example if it is infinity or NaN this function will panic.
1052 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1053 pub fn f32_unsuffixed(n: f32) -> Literal {
1055 panic!("Invalid float literal {}", n);
1057 Literal(bridge::client::Literal::float(&n.to_string()))
1060 /// Creates a new suffixed floating-point literal.
1062 /// This constructor will create a literal like `1.0f32` where the value
1063 /// specified is the preceding part of the token and `f32` is the suffix of
1064 /// the token. This token will always be inferred to be an `f32` in the
1066 /// Literals created from negative numbers may not survive rountrips through
1067 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1071 /// This function requires that the specified float is finite, for
1072 /// example if it is infinity or NaN this function will panic.
1073 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1074 pub fn f32_suffixed(n: f32) -> Literal {
1076 panic!("Invalid float literal {}", n);
1078 Literal(bridge::client::Literal::f32(&n.to_string()))
1081 /// Creates a new unsuffixed floating-point literal.
1083 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1084 /// the float's value is emitted directly into the token but no suffix is
1085 /// used, so it may be inferred to be a `f64` later in the compiler.
1086 /// Literals created from negative numbers may not survive rountrips through
1087 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1091 /// This function requires that the specified float is finite, for
1092 /// example if it is infinity or NaN this function will panic.
1093 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1094 pub fn f64_unsuffixed(n: f64) -> Literal {
1096 panic!("Invalid float literal {}", n);
1098 Literal(bridge::client::Literal::float(&n.to_string()))
1101 /// Creates a new suffixed floating-point literal.
1103 /// This constructor will create a literal like `1.0f64` where the value
1104 /// specified is the preceding part of the token and `f64` is the suffix of
1105 /// the token. This token will always be inferred to be an `f64` in the
1107 /// Literals created from negative numbers may not survive rountrips through
1108 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1112 /// This function requires that the specified float is finite, for
1113 /// example if it is infinity or NaN this function will panic.
1114 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1115 pub fn f64_suffixed(n: f64) -> Literal {
1117 panic!("Invalid float literal {}", n);
1119 Literal(bridge::client::Literal::f64(&n.to_string()))
1123 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1124 pub fn string(string: &str) -> Literal {
1125 Literal(bridge::client::Literal::string(string))
1128 /// Character literal.
1129 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1130 pub fn character(ch: char) -> Literal {
1131 Literal(bridge::client::Literal::character(ch))
1134 /// Byte string literal.
1135 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1136 pub fn byte_string(bytes: &[u8]) -> Literal {
1137 Literal(bridge::client::Literal::byte_string(bytes))
1140 /// Returns the span encompassing this literal.
1141 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1142 pub fn span(&self) -> Span {
1146 /// Configures the span associated for this literal.
1147 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1148 pub fn set_span(&mut self, span: Span) {
1149 self.0.set_span(span.0);
1152 /// Returns a `Span` that is a subset of `self.span()` containing only the
1153 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1154 /// span is outside the bounds of `self`.
1155 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1156 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1157 // occur elsewhere when the source text is printed.
1158 // FIXME(SergioBenitez): there is no way for the user to know what
1159 // `self.span()` actually maps to, so this method can currently only be
1160 // called blindly. For example, `to_string()` for the character 'c' returns
1161 // "'\u{63}'"; there is no way for the user to know whether the source text
1162 // was 'c' or whether it was '\u{63}'.
1163 #[unstable(feature = "proc_macro_span", issue = "54725")]
1164 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1165 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1166 fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1168 Bound::Included(x) => Bound::Included(x.clone()),
1169 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1170 Bound::Unbounded => Bound::Unbounded,
1174 self.0.subspan(cloned_bound(range.start_bound()), cloned_bound(range.end_bound())).map(Span)
1178 /// Parse a single literal from its stringified representation.
1180 /// In order to parse successfully, the input string must not contain anything
1181 /// but the literal token. Specifically, it must not contain whitespace or
1182 /// comments in addition to the literal.
1184 /// The resulting literal token will have a `Span::call_site()` span.
1186 /// NOTE: some errors may cause panics instead of returning `LexError`. We
1187 /// reserve the right to change these errors into `LexError`s later.
1188 #[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1189 impl FromStr for Literal {
1190 type Err = LexError;
1192 fn from_str(src: &str) -> Result<Self, LexError> {
1193 match bridge::client::Literal::from_str(src) {
1194 Ok(literal) => Ok(Literal(literal)),
1195 Err(()) => Err(LexError::new()),
1200 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1201 // based on it (the reverse of the usual relationship between the two).
1202 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1203 impl ToString for Literal {
1204 fn to_string(&self) -> String {
1205 TokenStream::from(TokenTree::from(self.clone())).to_string()
1209 /// Prints the literal as a string that should be losslessly convertible
1210 /// back into the same literal (except for possible rounding for floating point literals).
1211 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1212 impl fmt::Display for Literal {
1213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1214 f.write_str(&self.to_string())
1218 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1219 impl fmt::Debug for Literal {
1220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1225 /// Tracked access to environment variables.
1226 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1227 pub mod tracked_env {
1228 use std::env::{self, VarError};
1229 use std::ffi::OsStr;
1231 /// Retrieve an environment variable and add it to build dependency info.
1232 /// Build system executing the compiler will know that the variable was accessed during
1233 /// compilation, and will be able to rerun the build when the value of that variable changes.
1234 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1235 /// standard library, except that the argument must be UTF-8.
1236 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1237 pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1238 let key: &str = key.as_ref();
1239 let value = env::var(key);
1240 crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());