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)))
21 #![feature(rustc_allow_const_fn_unstable)]
23 #![feature(staged_api)]
24 #![feature(const_fn_trait_bound)]
25 #![feature(const_fn_fn_ptr_basics)]
26 #![feature(allow_internal_unstable)]
27 #![feature(decl_macro)]
28 #![feature(extern_types)]
29 #![feature(in_band_lifetimes)]
30 #![feature(negative_impls)]
31 #![feature(auto_traits)]
32 #![feature(restricted_std)]
33 #![feature(rustc_attrs)]
34 #![feature(min_specialization)]
35 #![recursion_limit = "256"]
37 #[unstable(feature = "proc_macro_internals", issue = "27812")]
43 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
44 pub use diagnostic::{Diagnostic, Level, MultiSpan};
46 use std::cmp::Ordering;
47 use std::ops::{Bound, RangeBounds};
48 use std::path::PathBuf;
49 use std::str::FromStr;
50 use std::{error, fmt, iter, mem};
52 /// Determines whether proc_macro has been made accessible to the currently
55 /// The proc_macro crate is only intended for use inside the implementation of
56 /// procedural macros. All the functions in this crate panic if invoked from
57 /// outside of a procedural macro, such as from a build script or unit test or
58 /// ordinary Rust binary.
60 /// With consideration for Rust libraries that are designed to support both
61 /// macro and non-macro use cases, `proc_macro::is_available()` provides a
62 /// non-panicking way to detect whether the infrastructure required to use the
63 /// API of proc_macro is presently available. Returns true if invoked from
64 /// inside of a procedural macro, false if invoked from any other binary.
65 #[unstable(feature = "proc_macro_is_available", issue = "71436")]
66 pub fn is_available() -> bool {
67 bridge::Bridge::is_available()
70 /// The main type provided by this crate, representing an abstract stream of
71 /// tokens, or, more specifically, a sequence of token trees.
72 /// The type provide interfaces for iterating over those token trees and, conversely,
73 /// collecting a number of token trees into one stream.
75 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
76 /// and `#[proc_macro_derive]` definitions.
77 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
79 pub struct TokenStream(bridge::client::TokenStream);
81 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
82 impl !Send for TokenStream {}
83 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
84 impl !Sync for TokenStream {}
86 /// Error returned from `TokenStream::from_str`.
87 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
95 LexError { _inner: () }
99 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
100 impl fmt::Display for LexError {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 f.write_str("cannot parse string into token stream")
106 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
107 impl error::Error for LexError {}
109 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
110 impl !Send for LexError {}
111 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
112 impl !Sync for LexError {}
115 /// Returns an empty `TokenStream` containing no token trees.
116 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
117 pub fn new() -> TokenStream {
118 TokenStream(bridge::client::TokenStream::new())
121 /// Checks if this `TokenStream` is empty.
122 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
123 pub fn is_empty(&self) -> bool {
128 /// Attempts to break the string into tokens and parse those tokens into a token stream.
129 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
130 /// or characters not existing in the language.
131 /// All tokens in the parsed stream get `Span::call_site()` spans.
133 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
134 /// change these errors into `LexError`s later.
135 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
136 impl FromStr for TokenStream {
139 fn from_str(src: &str) -> Result<TokenStream, LexError> {
140 Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
144 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
145 // based on it (the reverse of the usual relationship between the two).
146 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
147 impl ToString for TokenStream {
148 fn to_string(&self) -> String {
153 /// Prints the token stream as a string that is supposed to be losslessly convertible back
154 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
155 /// with `Delimiter::None` delimiters and negative numeric literals.
156 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
157 impl fmt::Display for TokenStream {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 f.write_str(&self.to_string())
163 /// Prints token in a form convenient for debugging.
164 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
165 impl fmt::Debug for TokenStream {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 f.write_str("TokenStream ")?;
168 f.debug_list().entries(self.clone()).finish()
172 #[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
173 impl Default for TokenStream {
174 fn default() -> Self {
179 #[unstable(feature = "proc_macro_quote", issue = "54722")]
180 pub use quote::{quote, quote_span};
182 /// Creates a token stream containing a single token tree.
183 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
184 impl From<TokenTree> for TokenStream {
185 fn from(tree: TokenTree) -> TokenStream {
186 TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
187 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
188 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
189 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
190 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
195 /// Collects a number of token trees into a single stream.
196 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
197 impl iter::FromIterator<TokenTree> for TokenStream {
198 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
199 trees.into_iter().map(TokenStream::from).collect()
203 /// A "flattening" operation on token streams, collects token trees
204 /// from multiple token streams into a single stream.
205 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
206 impl iter::FromIterator<TokenStream> for TokenStream {
207 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
208 let mut builder = bridge::client::TokenStreamBuilder::new();
209 streams.into_iter().for_each(|stream| builder.push(stream.0));
210 TokenStream(builder.build())
214 #[stable(feature = "token_stream_extend", since = "1.30.0")]
215 impl Extend<TokenTree> for TokenStream {
216 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
217 self.extend(trees.into_iter().map(TokenStream::from));
221 #[stable(feature = "token_stream_extend", since = "1.30.0")]
222 impl Extend<TokenStream> for TokenStream {
223 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
224 // FIXME(eddyb) Use an optimized implementation if/when possible.
225 *self = iter::once(mem::replace(self, Self::new())).chain(streams).collect();
229 /// Public implementation details for the `TokenStream` type, such as iterators.
230 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
231 pub mod token_stream {
232 use crate::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree};
234 /// An iterator over `TokenStream`'s `TokenTree`s.
235 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
236 /// and returns whole groups as token trees.
238 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
239 pub struct IntoIter(bridge::client::TokenStreamIter);
241 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
242 impl Iterator for IntoIter {
243 type Item = TokenTree;
245 fn next(&mut self) -> Option<TokenTree> {
246 self.0.next().map(|tree| match tree {
247 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
248 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
249 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
250 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
255 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
256 impl IntoIterator for TokenStream {
257 type Item = TokenTree;
258 type IntoIter = IntoIter;
260 fn into_iter(self) -> IntoIter {
261 IntoIter(self.0.into_iter())
266 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
267 /// For example, `quote!(a + b)` will produce a expression, that, when evaluated, constructs
268 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
270 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
271 /// To quote `$` itself, use `$$`.
272 #[unstable(feature = "proc_macro_quote", issue = "54722")]
273 #[allow_internal_unstable(proc_macro_def_site, proc_macro_internals)]
274 #[rustc_builtin_macro]
275 pub macro quote($($t:tt)*) {
276 /* compiler built-in */
279 #[unstable(feature = "proc_macro_internals", issue = "27812")]
283 /// A region of source code, along with macro expansion information.
284 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
285 #[derive(Copy, Clone)]
286 pub struct Span(bridge::client::Span);
288 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
289 impl !Send for Span {}
290 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
291 impl !Sync for Span {}
293 macro_rules! diagnostic_method {
294 ($name:ident, $level:expr) => {
295 /// Creates a new `Diagnostic` with the given `message` at the span
297 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
298 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
299 Diagnostic::spanned(self, $level, message)
305 /// A span that resolves at the macro definition site.
306 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
307 pub fn def_site() -> Span {
308 Span(bridge::client::Span::def_site())
311 /// The span of the invocation of the current procedural macro.
312 /// Identifiers created with this span will be resolved as if they were written
313 /// directly at the macro call location (call-site hygiene) and other code
314 /// at the macro call site will be able to refer to them as well.
315 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
316 pub fn call_site() -> Span {
317 Span(bridge::client::Span::call_site())
320 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
321 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
322 /// call site (everything else).
323 /// The span location is taken from the call-site.
324 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
325 pub fn mixed_site() -> Span {
326 Span(bridge::client::Span::mixed_site())
329 /// The original source file into which this span points.
330 #[unstable(feature = "proc_macro_span", issue = "54725")]
331 pub fn source_file(&self) -> SourceFile {
332 SourceFile(self.0.source_file())
335 /// The `Span` for the tokens in the previous macro expansion from which
336 /// `self` was generated from, if any.
337 #[unstable(feature = "proc_macro_span", issue = "54725")]
338 pub fn parent(&self) -> Option<Span> {
339 self.0.parent().map(Span)
342 /// The span for the origin source code that `self` was generated from. If
343 /// this `Span` wasn't generated from other macro expansions then the return
344 /// value is the same as `*self`.
345 #[unstable(feature = "proc_macro_span", issue = "54725")]
346 pub fn source(&self) -> Span {
347 Span(self.0.source())
350 /// Gets the starting line/column in the source file for this span.
351 #[unstable(feature = "proc_macro_span", issue = "54725")]
352 pub fn start(&self) -> LineColumn {
356 /// Gets the ending line/column in the source file for this span.
357 #[unstable(feature = "proc_macro_span", issue = "54725")]
358 pub fn end(&self) -> LineColumn {
362 /// Creates a new span encompassing `self` and `other`.
364 /// Returns `None` if `self` and `other` are from different files.
365 #[unstable(feature = "proc_macro_span", issue = "54725")]
366 pub fn join(&self, other: Span) -> Option<Span> {
367 self.0.join(other.0).map(Span)
370 /// Creates a new span with the same line/column information as `self` but
371 /// that resolves symbols as though it were at `other`.
372 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
373 pub fn resolved_at(&self, other: Span) -> Span {
374 Span(self.0.resolved_at(other.0))
377 /// Creates a new span with the same name resolution behavior as `self` but
378 /// with the line/column information of `other`.
379 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
380 pub fn located_at(&self, other: Span) -> Span {
381 other.resolved_at(*self)
384 /// Compares to spans to see if they're equal.
385 #[unstable(feature = "proc_macro_span", issue = "54725")]
386 pub fn eq(&self, other: &Span) -> bool {
390 /// Returns the source text behind a span. This preserves the original source
391 /// code, including spaces and comments. It only returns a result if the span
392 /// corresponds to real source code.
394 /// Note: The observable result of a macro should only rely on the tokens and
395 /// not on this source text. The result of this function is a best effort to
396 /// be used for diagnostics only.
397 #[unstable(feature = "proc_macro_span", issue = "54725")]
398 pub fn source_text(&self) -> Option<String> {
402 // Used by the implementation of `Span::quote`
404 #[unstable(feature = "proc_macro_internals", issue = "27812")]
405 pub fn save_span(&self) -> usize {
409 // Used by the implementation of `Span::quote`
411 #[unstable(feature = "proc_macro_internals", issue = "27812")]
412 pub fn recover_proc_macro_span(id: usize) -> Span {
413 Span(bridge::client::Span::recover_proc_macro_span(id))
416 diagnostic_method!(error, Level::Error);
417 diagnostic_method!(warning, Level::Warning);
418 diagnostic_method!(note, Level::Note);
419 diagnostic_method!(help, Level::Help);
422 /// Prints a span in a form convenient for debugging.
423 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
424 impl fmt::Debug for Span {
425 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
430 /// A line-column pair representing the start or end of a `Span`.
431 #[unstable(feature = "proc_macro_span", issue = "54725")]
432 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
433 pub struct LineColumn {
434 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
435 #[unstable(feature = "proc_macro_span", issue = "54725")]
437 /// The 0-indexed column (in UTF-8 characters) in the source file on which
438 /// the span starts or ends (inclusive).
439 #[unstable(feature = "proc_macro_span", issue = "54725")]
443 #[unstable(feature = "proc_macro_span", issue = "54725")]
444 impl !Send for LineColumn {}
445 #[unstable(feature = "proc_macro_span", issue = "54725")]
446 impl !Sync for LineColumn {}
448 #[unstable(feature = "proc_macro_span", issue = "54725")]
449 impl Ord for LineColumn {
450 fn cmp(&self, other: &Self) -> Ordering {
451 self.line.cmp(&other.line).then(self.column.cmp(&other.column))
455 #[unstable(feature = "proc_macro_span", issue = "54725")]
456 impl PartialOrd for LineColumn {
457 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
458 Some(self.cmp(other))
462 /// The source file of a given `Span`.
463 #[unstable(feature = "proc_macro_span", issue = "54725")]
465 pub struct SourceFile(bridge::client::SourceFile);
468 /// Gets the path to this source file.
471 /// If the code span associated with this `SourceFile` was generated by an external macro, this
472 /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
474 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
475 /// the command line, the path as given may not actually be valid.
477 /// [`is_real`]: Self::is_real
478 #[unstable(feature = "proc_macro_span", issue = "54725")]
479 pub fn path(&self) -> PathBuf {
480 PathBuf::from(self.0.path())
483 /// Returns `true` if this source file is a real source file, and not generated by an external
484 /// macro's expansion.
485 #[unstable(feature = "proc_macro_span", issue = "54725")]
486 pub fn is_real(&self) -> bool {
487 // This is a hack until intercrate spans are implemented and we can have real source files
488 // for spans generated in external macros.
489 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
494 #[unstable(feature = "proc_macro_span", issue = "54725")]
495 impl fmt::Debug for SourceFile {
496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
497 f.debug_struct("SourceFile")
498 .field("path", &self.path())
499 .field("is_real", &self.is_real())
504 #[unstable(feature = "proc_macro_span", issue = "54725")]
505 impl PartialEq for SourceFile {
506 fn eq(&self, other: &Self) -> bool {
511 #[unstable(feature = "proc_macro_span", issue = "54725")]
512 impl Eq for SourceFile {}
514 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
515 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
518 /// A token stream surrounded by bracket delimiters.
519 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
520 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
522 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
523 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
524 /// A single punctuation character (`+`, `,`, `$`, etc.).
525 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
526 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
527 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
528 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
529 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
532 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
533 impl !Send for TokenTree {}
534 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
535 impl !Sync for TokenTree {}
538 /// Returns the span of this tree, delegating to the `span` method of
539 /// the contained token or a delimited stream.
540 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
541 pub fn span(&self) -> Span {
543 TokenTree::Group(ref t) => t.span(),
544 TokenTree::Ident(ref t) => t.span(),
545 TokenTree::Punct(ref t) => t.span(),
546 TokenTree::Literal(ref t) => t.span(),
550 /// Configures the span for *only this token*.
552 /// Note that if this token is a `Group` then this method will not configure
553 /// the span of each of the internal tokens, this will simply delegate to
554 /// the `set_span` method of each variant.
555 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
556 pub fn set_span(&mut self, span: Span) {
558 TokenTree::Group(ref mut t) => t.set_span(span),
559 TokenTree::Ident(ref mut t) => t.set_span(span),
560 TokenTree::Punct(ref mut t) => t.set_span(span),
561 TokenTree::Literal(ref mut t) => t.set_span(span),
566 /// Prints token tree in a form convenient for debugging.
567 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
568 impl fmt::Debug for TokenTree {
569 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
570 // Each of these has the name in the struct type in the derived debug,
571 // so don't bother with an extra layer of indirection
573 TokenTree::Group(ref tt) => tt.fmt(f),
574 TokenTree::Ident(ref tt) => tt.fmt(f),
575 TokenTree::Punct(ref tt) => tt.fmt(f),
576 TokenTree::Literal(ref tt) => tt.fmt(f),
581 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
582 impl From<Group> for TokenTree {
583 fn from(g: Group) -> TokenTree {
588 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
589 impl From<Ident> for TokenTree {
590 fn from(g: Ident) -> TokenTree {
595 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
596 impl From<Punct> for TokenTree {
597 fn from(g: Punct) -> TokenTree {
602 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
603 impl From<Literal> for TokenTree {
604 fn from(g: Literal) -> TokenTree {
605 TokenTree::Literal(g)
609 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
610 // based on it (the reverse of the usual relationship between the two).
611 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
612 impl ToString for TokenTree {
613 fn to_string(&self) -> String {
615 TokenTree::Group(ref t) => t.to_string(),
616 TokenTree::Ident(ref t) => t.to_string(),
617 TokenTree::Punct(ref t) => t.to_string(),
618 TokenTree::Literal(ref t) => t.to_string(),
623 /// Prints the token tree as a string that is supposed to be losslessly convertible back
624 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
625 /// with `Delimiter::None` delimiters and negative numeric literals.
626 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
627 impl fmt::Display for TokenTree {
628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629 f.write_str(&self.to_string())
633 /// A delimited token stream.
635 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
637 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
638 pub struct Group(bridge::client::Group);
640 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
641 impl !Send for Group {}
642 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
643 impl !Sync for Group {}
645 /// Describes how a sequence of token trees is delimited.
646 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
647 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
650 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
653 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
656 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
659 /// An implicit delimiter, that may, for example, appear around tokens coming from a
660 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
661 /// `$var * 3` where `$var` is `1 + 2`.
662 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
663 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
668 /// Creates a new `Group` with the given delimiter and token stream.
670 /// This constructor will set the span for this group to
671 /// `Span::call_site()`. To change the span you can use the `set_span`
673 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
674 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
675 Group(bridge::client::Group::new(delimiter, stream.0))
678 /// Returns the delimiter of this `Group`
679 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
680 pub fn delimiter(&self) -> Delimiter {
684 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
686 /// Note that the returned token stream does not include the delimiter
688 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
689 pub fn stream(&self) -> TokenStream {
690 TokenStream(self.0.stream())
693 /// Returns the span for the delimiters of this token stream, spanning the
697 /// pub fn span(&self) -> Span {
700 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
701 pub fn span(&self) -> Span {
705 /// Returns the span pointing to the opening delimiter of this group.
708 /// pub fn span_open(&self) -> Span {
711 #[unstable(feature = "proc_macro_span", issue = "54725")]
712 pub fn span_open(&self) -> Span {
713 Span(self.0.span_open())
716 /// Returns the span pointing to the closing delimiter of this group.
719 /// pub fn span_close(&self) -> Span {
722 #[unstable(feature = "proc_macro_span", issue = "54725")]
723 pub fn span_close(&self) -> Span {
724 Span(self.0.span_close())
727 /// Configures the span for this `Group`'s delimiters, but not its internal
730 /// This method will **not** set the span of all the internal tokens spanned
731 /// by this group, but rather it will only set the span of the delimiter
732 /// tokens at the level of the `Group`.
733 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
734 pub fn set_span(&mut self, span: Span) {
735 self.0.set_span(span.0);
739 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
740 // based on it (the reverse of the usual relationship between the two).
741 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
742 impl ToString for Group {
743 fn to_string(&self) -> String {
744 TokenStream::from(TokenTree::from(self.clone())).to_string()
748 /// Prints the group as a string that should be losslessly convertible back
749 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
750 /// with `Delimiter::None` delimiters.
751 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
752 impl fmt::Display for Group {
753 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
754 f.write_str(&self.to_string())
758 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
759 impl fmt::Debug for Group {
760 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
761 f.debug_struct("Group")
762 .field("delimiter", &self.delimiter())
763 .field("stream", &self.stream())
764 .field("span", &self.span())
769 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
771 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
772 /// forms of `Spacing` returned.
773 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
775 pub struct Punct(bridge::client::Punct);
777 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
778 impl !Send for Punct {}
779 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
780 impl !Sync for Punct {}
782 /// Whether an `Punct` is followed immediately by another `Punct` or
783 /// followed by another token or whitespace.
784 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
785 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
787 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
788 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
790 /// e.g., `+` is `Joint` in `+=` or `'#`.
791 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
792 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
797 /// Creates a new `Punct` from the given character and spacing.
798 /// The `ch` argument must be a valid punctuation character permitted by the language,
799 /// otherwise the function will panic.
801 /// The returned `Punct` will have the default span of `Span::call_site()`
802 /// which can be further configured with the `set_span` method below.
803 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
804 pub fn new(ch: char, spacing: Spacing) -> Punct {
805 Punct(bridge::client::Punct::new(ch, spacing))
808 /// Returns the value of this punctuation character as `char`.
809 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
810 pub fn as_char(&self) -> char {
814 /// Returns the spacing of this punctuation character, indicating whether it's immediately
815 /// followed by another `Punct` in the token stream, so they can potentially be combined into
816 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
817 /// (`Alone`) so the operator has certainly ended.
818 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
819 pub fn spacing(&self) -> Spacing {
823 /// Returns the span for this punctuation character.
824 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
825 pub fn span(&self) -> Span {
829 /// Configure the span for this punctuation character.
830 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
831 pub fn set_span(&mut self, span: Span) {
832 self.0 = self.0.with_span(span.0);
836 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
837 // based on it (the reverse of the usual relationship between the two).
838 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
839 impl ToString for Punct {
840 fn to_string(&self) -> String {
841 TokenStream::from(TokenTree::from(self.clone())).to_string()
845 /// Prints the punctuation character as a string that should be losslessly convertible
846 /// back into the same character.
847 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
848 impl fmt::Display for Punct {
849 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
850 f.write_str(&self.to_string())
854 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
855 impl fmt::Debug for Punct {
856 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
857 f.debug_struct("Punct")
858 .field("ch", &self.as_char())
859 .field("spacing", &self.spacing())
860 .field("span", &self.span())
865 #[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
866 impl PartialEq<char> for Punct {
867 fn eq(&self, rhs: &char) -> bool {
868 self.as_char() == *rhs
872 #[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
873 impl PartialEq<Punct> for char {
874 fn eq(&self, rhs: &Punct) -> bool {
875 *self == rhs.as_char()
879 /// An identifier (`ident`).
881 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
882 pub struct Ident(bridge::client::Ident);
885 /// Creates a new `Ident` with the given `string` as well as the specified
887 /// The `string` argument must be a valid identifier permitted by the
888 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
890 /// Note that `span`, currently in rustc, configures the hygiene information
891 /// for this identifier.
893 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
894 /// meaning that identifiers created with this span will be resolved as if they were written
895 /// directly at the location of the macro call, and other code at the macro call site will be
896 /// able to refer to them as well.
898 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
899 /// meaning that identifiers created with this span will be resolved at the location of the
900 /// macro definition and other code at the macro call site will not be able to refer to them.
902 /// Due to the current importance of hygiene this constructor, unlike other
903 /// tokens, requires a `Span` to be specified at construction.
904 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
905 pub fn new(string: &str, span: Span) -> Ident {
906 Ident(bridge::client::Ident::new(string, span.0, false))
909 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
910 /// The `string` argument be a valid identifier permitted by the language
911 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
912 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
913 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
914 pub fn new_raw(string: &str, span: Span) -> Ident {
915 Ident(bridge::client::Ident::new(string, span.0, true))
918 /// Returns the span of this `Ident`, encompassing the entire string returned
919 /// by [`to_string`](Self::to_string).
920 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
921 pub fn span(&self) -> Span {
925 /// Configures the span of this `Ident`, possibly changing its hygiene context.
926 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
927 pub fn set_span(&mut self, span: Span) {
928 self.0 = self.0.with_span(span.0);
932 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
933 // based on it (the reverse of the usual relationship between the two).
934 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
935 impl ToString for Ident {
936 fn to_string(&self) -> String {
937 TokenStream::from(TokenTree::from(self.clone())).to_string()
941 /// Prints the identifier as a string that should be losslessly convertible
942 /// back into the same identifier.
943 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
944 impl fmt::Display for Ident {
945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
946 f.write_str(&self.to_string())
950 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
951 impl fmt::Debug for Ident {
952 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
953 f.debug_struct("Ident")
954 .field("ident", &self.to_string())
955 .field("span", &self.span())
960 /// A literal string (`"hello"`), byte string (`b"hello"`),
961 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
962 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
963 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
965 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
966 pub struct Literal(bridge::client::Literal);
968 macro_rules! suffixed_int_literals {
969 ($($name:ident => $kind:ident,)*) => ($(
970 /// Creates a new suffixed integer literal with the specified value.
972 /// This function will create an integer like `1u32` where the integer
973 /// value specified is the first part of the token and the integral is
974 /// also suffixed at the end.
975 /// Literals created from negative numbers may not survive round-trips through
976 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
978 /// Literals created through this method have the `Span::call_site()`
979 /// span by default, which can be configured with the `set_span` method
981 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
982 pub fn $name(n: $kind) -> Literal {
983 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
988 macro_rules! unsuffixed_int_literals {
989 ($($name:ident => $kind:ident,)*) => ($(
990 /// Creates a new unsuffixed integer literal with the specified value.
992 /// This function will create an integer like `1` where the integer
993 /// value specified is the first part of the token. No suffix is
994 /// specified on this token, meaning that invocations like
995 /// `Literal::i8_unsuffixed(1)` are equivalent to
996 /// `Literal::u32_unsuffixed(1)`.
997 /// Literals created from negative numbers may not survive rountrips through
998 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1000 /// Literals created through this method have the `Span::call_site()`
1001 /// span by default, which can be configured with the `set_span` method
1003 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1004 pub fn $name(n: $kind) -> Literal {
1005 Literal(bridge::client::Literal::integer(&n.to_string()))
1011 suffixed_int_literals! {
1013 u16_suffixed => u16,
1014 u32_suffixed => u32,
1015 u64_suffixed => u64,
1016 u128_suffixed => u128,
1017 usize_suffixed => usize,
1019 i16_suffixed => i16,
1020 i32_suffixed => i32,
1021 i64_suffixed => i64,
1022 i128_suffixed => i128,
1023 isize_suffixed => isize,
1026 unsuffixed_int_literals! {
1027 u8_unsuffixed => u8,
1028 u16_unsuffixed => u16,
1029 u32_unsuffixed => u32,
1030 u64_unsuffixed => u64,
1031 u128_unsuffixed => u128,
1032 usize_unsuffixed => usize,
1033 i8_unsuffixed => i8,
1034 i16_unsuffixed => i16,
1035 i32_unsuffixed => i32,
1036 i64_unsuffixed => i64,
1037 i128_unsuffixed => i128,
1038 isize_unsuffixed => isize,
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 f32_unsuffixed(n: f32) -> 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.0f32` where the value
1064 /// specified is the preceding part of the token and `f32` is the suffix of
1065 /// the token. This token will always be inferred to be an `f32` 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 f32_suffixed(n: f32) -> Literal {
1077 panic!("Invalid float literal {}", n);
1079 Literal(bridge::client::Literal::f32(&n.to_string()))
1082 /// Creates a new unsuffixed floating-point literal.
1084 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1085 /// the float's value is emitted directly into the token but no suffix is
1086 /// used, so it may be inferred to be a `f64` later in the compiler.
1087 /// Literals created from negative numbers may not survive rountrips through
1088 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1092 /// This function requires that the specified float is finite, for
1093 /// example if it is infinity or NaN this function will panic.
1094 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1095 pub fn f64_unsuffixed(n: f64) -> Literal {
1097 panic!("Invalid float literal {}", n);
1099 Literal(bridge::client::Literal::float(&n.to_string()))
1102 /// Creates a new suffixed floating-point literal.
1104 /// This constructor will create a literal like `1.0f64` where the value
1105 /// specified is the preceding part of the token and `f64` is the suffix of
1106 /// the token. This token will always be inferred to be an `f64` in the
1108 /// Literals created from negative numbers may not survive rountrips through
1109 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1113 /// This function requires that the specified float is finite, for
1114 /// example if it is infinity or NaN this function will panic.
1115 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1116 pub fn f64_suffixed(n: f64) -> Literal {
1118 panic!("Invalid float literal {}", n);
1120 Literal(bridge::client::Literal::f64(&n.to_string()))
1124 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1125 pub fn string(string: &str) -> Literal {
1126 Literal(bridge::client::Literal::string(string))
1129 /// Character literal.
1130 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1131 pub fn character(ch: char) -> Literal {
1132 Literal(bridge::client::Literal::character(ch))
1135 /// Byte string literal.
1136 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1137 pub fn byte_string(bytes: &[u8]) -> Literal {
1138 Literal(bridge::client::Literal::byte_string(bytes))
1141 /// Returns the span encompassing this literal.
1142 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1143 pub fn span(&self) -> Span {
1147 /// Configures the span associated for this literal.
1148 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1149 pub fn set_span(&mut self, span: Span) {
1150 self.0.set_span(span.0);
1153 /// Returns a `Span` that is a subset of `self.span()` containing only the
1154 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1155 /// span is outside the bounds of `self`.
1156 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1157 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1158 // occur elsewhere when the source text is printed.
1159 // FIXME(SergioBenitez): there is no way for the user to know what
1160 // `self.span()` actually maps to, so this method can currently only be
1161 // called blindly. For example, `to_string()` for the character 'c' returns
1162 // "'\u{63}'"; there is no way for the user to know whether the source text
1163 // was 'c' or whether it was '\u{63}'.
1164 #[unstable(feature = "proc_macro_span", issue = "54725")]
1165 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1166 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1167 fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1169 Bound::Included(x) => Bound::Included(x.clone()),
1170 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1171 Bound::Unbounded => Bound::Unbounded,
1175 self.0.subspan(cloned_bound(range.start_bound()), cloned_bound(range.end_bound())).map(Span)
1179 /// Parse a single literal from its stringified representation.
1181 /// In order to parse successfully, the input string must not contain anything
1182 /// but the literal token. Specifically, it must not contain whitespace or
1183 /// comments in addition to the literal.
1185 /// The resulting literal token will have a `Span::call_site()` span.
1187 /// NOTE: some errors may cause panics instead of returning `LexError`. We
1188 /// reserve the right to change these errors into `LexError`s later.
1189 #[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1190 impl FromStr for Literal {
1191 type Err = LexError;
1193 fn from_str(src: &str) -> Result<Self, LexError> {
1194 match bridge::client::Literal::from_str(src) {
1195 Ok(literal) => Ok(Literal(literal)),
1196 Err(()) => Err(LexError::new()),
1201 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1202 // based on it (the reverse of the usual relationship between the two).
1203 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1204 impl ToString for Literal {
1205 fn to_string(&self) -> String {
1206 TokenStream::from(TokenTree::from(self.clone())).to_string()
1210 /// Prints the literal as a string that should be losslessly convertible
1211 /// back into the same literal (except for possible rounding for floating point literals).
1212 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1213 impl fmt::Display for Literal {
1214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1215 f.write_str(&self.to_string())
1219 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1220 impl fmt::Debug for Literal {
1221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1226 /// Tracked access to environment variables.
1227 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1228 pub mod tracked_env {
1229 use std::env::{self, VarError};
1230 use std::ffi::OsStr;
1232 /// Retrieve an environment variable and add it to build dependency info.
1233 /// Build system executing the compiler will know that the variable was accessed during
1234 /// compilation, and will be able to rerun the build when the value of that variable changes.
1235 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1236 /// standard library, except that the argument must be UTF-8.
1237 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1238 pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1239 let key: &str = key.as_ref();
1240 let value = env::var(key);
1241 crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());