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 #![cfg_attr(bootstrap, feature(const_fn))]
25 #![cfg_attr(not(bootstrap), feature(const_fn_trait_bound))]
26 #![feature(const_fn_fn_ptr_basics)]
27 #![feature(allow_internal_unstable)]
28 #![feature(decl_macro)]
29 #![feature(extern_types)]
30 #![feature(in_band_lifetimes)]
31 #![feature(negative_impls)]
32 #![feature(auto_traits)]
33 #![feature(restricted_std)]
34 #![feature(rustc_attrs)]
35 #![feature(min_specialization)]
36 #![recursion_limit = "256"]
38 #[unstable(feature = "proc_macro_internals", issue = "27812")]
44 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
45 pub use diagnostic::{Diagnostic, Level, MultiSpan};
47 use std::cmp::Ordering;
48 use std::ops::{Bound, RangeBounds};
49 use std::path::PathBuf;
50 use std::str::FromStr;
51 use std::{error, fmt, iter, mem};
53 /// Determines whether proc_macro has been made accessible to the currently
56 /// The proc_macro crate is only intended for use inside the implementation of
57 /// procedural macros. All the functions in this crate panic if invoked from
58 /// outside of a procedural macro, such as from a build script or unit test or
59 /// ordinary Rust binary.
61 /// With consideration for Rust libraries that are designed to support both
62 /// macro and non-macro use cases, `proc_macro::is_available()` provides a
63 /// non-panicking way to detect whether the infrastructure required to use the
64 /// API of proc_macro is presently available. Returns true if invoked from
65 /// inside of a procedural macro, false if invoked from any other binary.
66 #[unstable(feature = "proc_macro_is_available", issue = "71436")]
67 pub fn is_available() -> bool {
68 bridge::Bridge::is_available()
71 /// The main type provided by this crate, representing an abstract stream of
72 /// tokens, or, more specifically, a sequence of token trees.
73 /// The type provide interfaces for iterating over those token trees and, conversely,
74 /// collecting a number of token trees into one stream.
76 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
77 /// and `#[proc_macro_derive]` definitions.
78 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
80 pub struct TokenStream(bridge::client::TokenStream);
82 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
83 impl !Send for TokenStream {}
84 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
85 impl !Sync for TokenStream {}
87 /// Error returned from `TokenStream::from_str`.
88 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
96 LexError { _inner: () }
100 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
101 impl fmt::Display for LexError {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 f.write_str("cannot parse string into token stream")
107 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
108 impl error::Error for LexError {}
110 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
111 impl !Send for LexError {}
112 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
113 impl !Sync for LexError {}
116 /// Returns an empty `TokenStream` containing no token trees.
117 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
118 pub fn new() -> TokenStream {
119 TokenStream(bridge::client::TokenStream::new())
122 /// Checks if this `TokenStream` is empty.
123 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
124 pub fn is_empty(&self) -> bool {
129 /// Attempts to break the string into tokens and parse those tokens into a token stream.
130 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
131 /// or characters not existing in the language.
132 /// All tokens in the parsed stream get `Span::call_site()` spans.
134 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
135 /// change these errors into `LexError`s later.
136 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
137 impl FromStr for TokenStream {
140 fn from_str(src: &str) -> Result<TokenStream, LexError> {
141 Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
145 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
146 // based on it (the reverse of the usual relationship between the two).
147 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
148 impl ToString for TokenStream {
149 fn to_string(&self) -> String {
154 /// Prints the token stream as a string that is supposed to be losslessly convertible back
155 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
156 /// with `Delimiter::None` delimiters and negative numeric literals.
157 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
158 impl fmt::Display for TokenStream {
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 f.write_str(&self.to_string())
164 /// Prints token in a form convenient for debugging.
165 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
166 impl fmt::Debug for TokenStream {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 f.write_str("TokenStream ")?;
169 f.debug_list().entries(self.clone()).finish()
173 #[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
174 impl Default for TokenStream {
175 fn default() -> Self {
180 #[unstable(feature = "proc_macro_quote", issue = "54722")]
181 pub use quote::{quote, quote_span};
183 /// Creates a token stream containing a single token tree.
184 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
185 impl From<TokenTree> for TokenStream {
186 fn from(tree: TokenTree) -> TokenStream {
187 TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
188 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
189 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
190 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
191 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
196 /// Collects a number of token trees into a single stream.
197 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
198 impl iter::FromIterator<TokenTree> for TokenStream {
199 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
200 trees.into_iter().map(TokenStream::from).collect()
204 /// A "flattening" operation on token streams, collects token trees
205 /// from multiple token streams into a single stream.
206 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
207 impl iter::FromIterator<TokenStream> for TokenStream {
208 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
209 let mut builder = bridge::client::TokenStreamBuilder::new();
210 streams.into_iter().for_each(|stream| builder.push(stream.0));
211 TokenStream(builder.build())
215 #[stable(feature = "token_stream_extend", since = "1.30.0")]
216 impl Extend<TokenTree> for TokenStream {
217 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
218 self.extend(trees.into_iter().map(TokenStream::from));
222 #[stable(feature = "token_stream_extend", since = "1.30.0")]
223 impl Extend<TokenStream> for TokenStream {
224 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
225 // FIXME(eddyb) Use an optimized implementation if/when possible.
226 *self = iter::once(mem::replace(self, Self::new())).chain(streams).collect();
230 /// Public implementation details for the `TokenStream` type, such as iterators.
231 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
232 pub mod token_stream {
233 use crate::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree};
235 /// An iterator over `TokenStream`'s `TokenTree`s.
236 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
237 /// and returns whole groups as token trees.
239 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
240 pub struct IntoIter(bridge::client::TokenStreamIter);
242 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
243 impl Iterator for IntoIter {
244 type Item = TokenTree;
246 fn next(&mut self) -> Option<TokenTree> {
247 self.0.next().map(|tree| match tree {
248 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
249 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
250 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
251 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
256 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
257 impl IntoIterator for TokenStream {
258 type Item = TokenTree;
259 type IntoIter = IntoIter;
261 fn into_iter(self) -> IntoIter {
262 IntoIter(self.0.into_iter())
267 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
268 /// For example, `quote!(a + b)` will produce a expression, that, when evaluated, constructs
269 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
271 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
272 /// To quote `$` itself, use `$$`.
273 #[unstable(feature = "proc_macro_quote", issue = "54722")]
274 #[allow_internal_unstable(proc_macro_def_site, proc_macro_internals)]
275 #[rustc_builtin_macro]
276 pub macro quote($($t:tt)*) {
277 /* compiler built-in */
280 #[unstable(feature = "proc_macro_internals", issue = "27812")]
284 /// A region of source code, along with macro expansion information.
285 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
286 #[derive(Copy, Clone)]
287 pub struct Span(bridge::client::Span);
289 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
290 impl !Send for Span {}
291 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
292 impl !Sync for Span {}
294 macro_rules! diagnostic_method {
295 ($name:ident, $level:expr) => {
296 /// Creates a new `Diagnostic` with the given `message` at the span
298 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
299 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
300 Diagnostic::spanned(self, $level, message)
306 /// A span that resolves at the macro definition site.
307 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
308 pub fn def_site() -> Span {
309 Span(bridge::client::Span::def_site())
312 /// The span of the invocation of the current procedural macro.
313 /// Identifiers created with this span will be resolved as if they were written
314 /// directly at the macro call location (call-site hygiene) and other code
315 /// at the macro call site will be able to refer to them as well.
316 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
317 pub fn call_site() -> Span {
318 Span(bridge::client::Span::call_site())
321 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
322 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
323 /// call site (everything else).
324 /// The span location is taken from the call-site.
325 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
326 pub fn mixed_site() -> Span {
327 Span(bridge::client::Span::mixed_site())
330 /// The original source file into which this span points.
331 #[unstable(feature = "proc_macro_span", issue = "54725")]
332 pub fn source_file(&self) -> SourceFile {
333 SourceFile(self.0.source_file())
336 /// The `Span` for the tokens in the previous macro expansion from which
337 /// `self` was generated from, if any.
338 #[unstable(feature = "proc_macro_span", issue = "54725")]
339 pub fn parent(&self) -> Option<Span> {
340 self.0.parent().map(Span)
343 /// The span for the origin source code that `self` was generated from. If
344 /// this `Span` wasn't generated from other macro expansions then the return
345 /// value is the same as `*self`.
346 #[unstable(feature = "proc_macro_span", issue = "54725")]
347 pub fn source(&self) -> Span {
348 Span(self.0.source())
351 /// Gets the starting line/column in the source file for this span.
352 #[unstable(feature = "proc_macro_span", issue = "54725")]
353 pub fn start(&self) -> LineColumn {
357 /// Gets the ending line/column in the source file for this span.
358 #[unstable(feature = "proc_macro_span", issue = "54725")]
359 pub fn end(&self) -> LineColumn {
363 /// Creates a new span encompassing `self` and `other`.
365 /// Returns `None` if `self` and `other` are from different files.
366 #[unstable(feature = "proc_macro_span", issue = "54725")]
367 pub fn join(&self, other: Span) -> Option<Span> {
368 self.0.join(other.0).map(Span)
371 /// Creates a new span with the same line/column information as `self` but
372 /// that resolves symbols as though it were at `other`.
373 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
374 pub fn resolved_at(&self, other: Span) -> Span {
375 Span(self.0.resolved_at(other.0))
378 /// Creates a new span with the same name resolution behavior as `self` but
379 /// with the line/column information of `other`.
380 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
381 pub fn located_at(&self, other: Span) -> Span {
382 other.resolved_at(*self)
385 /// Compares to spans to see if they're equal.
386 #[unstable(feature = "proc_macro_span", issue = "54725")]
387 pub fn eq(&self, other: &Span) -> bool {
391 /// Returns the source text behind a span. This preserves the original source
392 /// code, including spaces and comments. It only returns a result if the span
393 /// corresponds to real source code.
395 /// Note: The observable result of a macro should only rely on the tokens and
396 /// not on this source text. The result of this function is a best effort to
397 /// be used for diagnostics only.
398 #[unstable(feature = "proc_macro_span", issue = "54725")]
399 pub fn source_text(&self) -> Option<String> {
403 // Used by the implementation of `Span::quote`
405 #[unstable(feature = "proc_macro_internals", issue = "27812")]
406 pub fn save_span(&self) -> usize {
410 // Used by the implementation of `Span::quote`
412 #[unstable(feature = "proc_macro_internals", issue = "27812")]
413 pub fn recover_proc_macro_span(id: usize) -> Span {
414 Span(bridge::client::Span::recover_proc_macro_span(id))
417 diagnostic_method!(error, Level::Error);
418 diagnostic_method!(warning, Level::Warning);
419 diagnostic_method!(note, Level::Note);
420 diagnostic_method!(help, Level::Help);
423 /// Prints a span in a form convenient for debugging.
424 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
425 impl fmt::Debug for Span {
426 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431 /// A line-column pair representing the start or end of a `Span`.
432 #[unstable(feature = "proc_macro_span", issue = "54725")]
433 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
434 pub struct LineColumn {
435 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
436 #[unstable(feature = "proc_macro_span", issue = "54725")]
438 /// The 0-indexed column (in UTF-8 characters) in the source file on which
439 /// the span starts or ends (inclusive).
440 #[unstable(feature = "proc_macro_span", issue = "54725")]
444 #[unstable(feature = "proc_macro_span", issue = "54725")]
445 impl !Send for LineColumn {}
446 #[unstable(feature = "proc_macro_span", issue = "54725")]
447 impl !Sync for LineColumn {}
449 #[unstable(feature = "proc_macro_span", issue = "54725")]
450 impl Ord for LineColumn {
451 fn cmp(&self, other: &Self) -> Ordering {
452 self.line.cmp(&other.line).then(self.column.cmp(&other.column))
456 #[unstable(feature = "proc_macro_span", issue = "54725")]
457 impl PartialOrd for LineColumn {
458 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
459 Some(self.cmp(other))
463 /// The source file of a given `Span`.
464 #[unstable(feature = "proc_macro_span", issue = "54725")]
466 pub struct SourceFile(bridge::client::SourceFile);
469 /// Gets the path to this source file.
472 /// If the code span associated with this `SourceFile` was generated by an external macro, this
473 /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
475 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
476 /// the command line, the path as given may not actually be valid.
478 /// [`is_real`]: Self::is_real
479 #[unstable(feature = "proc_macro_span", issue = "54725")]
480 pub fn path(&self) -> PathBuf {
481 PathBuf::from(self.0.path())
484 /// Returns `true` if this source file is a real source file, and not generated by an external
485 /// macro's expansion.
486 #[unstable(feature = "proc_macro_span", issue = "54725")]
487 pub fn is_real(&self) -> bool {
488 // This is a hack until intercrate spans are implemented and we can have real source files
489 // for spans generated in external macros.
490 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
495 #[unstable(feature = "proc_macro_span", issue = "54725")]
496 impl fmt::Debug for SourceFile {
497 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
498 f.debug_struct("SourceFile")
499 .field("path", &self.path())
500 .field("is_real", &self.is_real())
505 #[unstable(feature = "proc_macro_span", issue = "54725")]
506 impl PartialEq for SourceFile {
507 fn eq(&self, other: &Self) -> bool {
512 #[unstable(feature = "proc_macro_span", issue = "54725")]
513 impl Eq for SourceFile {}
515 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
516 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
519 /// A token stream surrounded by bracket delimiters.
520 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
521 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
523 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
524 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
525 /// A single punctuation character (`+`, `,`, `$`, etc.).
526 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
527 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
528 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
529 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
530 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
533 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
534 impl !Send for TokenTree {}
535 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
536 impl !Sync for TokenTree {}
539 /// Returns the span of this tree, delegating to the `span` method of
540 /// the contained token or a delimited stream.
541 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
542 pub fn span(&self) -> Span {
544 TokenTree::Group(ref t) => t.span(),
545 TokenTree::Ident(ref t) => t.span(),
546 TokenTree::Punct(ref t) => t.span(),
547 TokenTree::Literal(ref t) => t.span(),
551 /// Configures the span for *only this token*.
553 /// Note that if this token is a `Group` then this method will not configure
554 /// the span of each of the internal tokens, this will simply delegate to
555 /// the `set_span` method of each variant.
556 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
557 pub fn set_span(&mut self, span: Span) {
559 TokenTree::Group(ref mut t) => t.set_span(span),
560 TokenTree::Ident(ref mut t) => t.set_span(span),
561 TokenTree::Punct(ref mut t) => t.set_span(span),
562 TokenTree::Literal(ref mut t) => t.set_span(span),
567 /// Prints token tree in a form convenient for debugging.
568 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
569 impl fmt::Debug for TokenTree {
570 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571 // Each of these has the name in the struct type in the derived debug,
572 // so don't bother with an extra layer of indirection
574 TokenTree::Group(ref tt) => tt.fmt(f),
575 TokenTree::Ident(ref tt) => tt.fmt(f),
576 TokenTree::Punct(ref tt) => tt.fmt(f),
577 TokenTree::Literal(ref tt) => tt.fmt(f),
582 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
583 impl From<Group> for TokenTree {
584 fn from(g: Group) -> TokenTree {
589 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
590 impl From<Ident> for TokenTree {
591 fn from(g: Ident) -> TokenTree {
596 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
597 impl From<Punct> for TokenTree {
598 fn from(g: Punct) -> TokenTree {
603 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
604 impl From<Literal> for TokenTree {
605 fn from(g: Literal) -> TokenTree {
606 TokenTree::Literal(g)
610 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
611 // based on it (the reverse of the usual relationship between the two).
612 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
613 impl ToString for TokenTree {
614 fn to_string(&self) -> String {
616 TokenTree::Group(ref t) => t.to_string(),
617 TokenTree::Ident(ref t) => t.to_string(),
618 TokenTree::Punct(ref t) => t.to_string(),
619 TokenTree::Literal(ref t) => t.to_string(),
624 /// Prints the token tree as a string that is supposed to be losslessly convertible back
625 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
626 /// with `Delimiter::None` delimiters and negative numeric literals.
627 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
628 impl fmt::Display for TokenTree {
629 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
630 f.write_str(&self.to_string())
634 /// A delimited token stream.
636 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
638 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
639 pub struct Group(bridge::client::Group);
641 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
642 impl !Send for Group {}
643 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
644 impl !Sync for Group {}
646 /// Describes how a sequence of token trees is delimited.
647 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
648 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
651 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
654 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
657 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
660 /// An implicit delimiter, that may, for example, appear around tokens coming from a
661 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
662 /// `$var * 3` where `$var` is `1 + 2`.
663 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
664 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
669 /// Creates a new `Group` with the given delimiter and token stream.
671 /// This constructor will set the span for this group to
672 /// `Span::call_site()`. To change the span you can use the `set_span`
674 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
675 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
676 Group(bridge::client::Group::new(delimiter, stream.0))
679 /// Returns the delimiter of this `Group`
680 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
681 pub fn delimiter(&self) -> Delimiter {
685 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
687 /// Note that the returned token stream does not include the delimiter
689 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
690 pub fn stream(&self) -> TokenStream {
691 TokenStream(self.0.stream())
694 /// Returns the span for the delimiters of this token stream, spanning the
698 /// pub fn span(&self) -> Span {
701 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
702 pub fn span(&self) -> Span {
706 /// Returns the span pointing to the opening delimiter of this group.
709 /// pub fn span_open(&self) -> Span {
712 #[unstable(feature = "proc_macro_span", issue = "54725")]
713 pub fn span_open(&self) -> Span {
714 Span(self.0.span_open())
717 /// Returns the span pointing to the closing delimiter of this group.
720 /// pub fn span_close(&self) -> Span {
723 #[unstable(feature = "proc_macro_span", issue = "54725")]
724 pub fn span_close(&self) -> Span {
725 Span(self.0.span_close())
728 /// Configures the span for this `Group`'s delimiters, but not its internal
731 /// This method will **not** set the span of all the internal tokens spanned
732 /// by this group, but rather it will only set the span of the delimiter
733 /// tokens at the level of the `Group`.
734 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
735 pub fn set_span(&mut self, span: Span) {
736 self.0.set_span(span.0);
740 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
741 // based on it (the reverse of the usual relationship between the two).
742 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
743 impl ToString for Group {
744 fn to_string(&self) -> String {
745 TokenStream::from(TokenTree::from(self.clone())).to_string()
749 /// Prints the group as a string that should be losslessly convertible back
750 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
751 /// with `Delimiter::None` delimiters.
752 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
753 impl fmt::Display for Group {
754 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
755 f.write_str(&self.to_string())
759 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
760 impl fmt::Debug for Group {
761 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
762 f.debug_struct("Group")
763 .field("delimiter", &self.delimiter())
764 .field("stream", &self.stream())
765 .field("span", &self.span())
770 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
772 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
773 /// forms of `Spacing` returned.
774 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
776 pub struct Punct(bridge::client::Punct);
778 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
779 impl !Send for Punct {}
780 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
781 impl !Sync for Punct {}
783 /// Whether an `Punct` is followed immediately by another `Punct` or
784 /// followed by another token or whitespace.
785 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
786 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
788 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
789 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
791 /// e.g., `+` is `Joint` in `+=` or `'#`.
792 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
793 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
798 /// Creates a new `Punct` from the given character and spacing.
799 /// The `ch` argument must be a valid punctuation character permitted by the language,
800 /// otherwise the function will panic.
802 /// The returned `Punct` will have the default span of `Span::call_site()`
803 /// which can be further configured with the `set_span` method below.
804 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
805 pub fn new(ch: char, spacing: Spacing) -> Punct {
806 Punct(bridge::client::Punct::new(ch, spacing))
809 /// Returns the value of this punctuation character as `char`.
810 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
811 pub fn as_char(&self) -> char {
815 /// Returns the spacing of this punctuation character, indicating whether it's immediately
816 /// followed by another `Punct` in the token stream, so they can potentially be combined into
817 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
818 /// (`Alone`) so the operator has certainly ended.
819 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
820 pub fn spacing(&self) -> Spacing {
824 /// Returns the span for this punctuation character.
825 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
826 pub fn span(&self) -> Span {
830 /// Configure the span for this punctuation character.
831 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
832 pub fn set_span(&mut self, span: Span) {
833 self.0 = self.0.with_span(span.0);
837 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
838 // based on it (the reverse of the usual relationship between the two).
839 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
840 impl ToString for Punct {
841 fn to_string(&self) -> String {
842 TokenStream::from(TokenTree::from(self.clone())).to_string()
846 /// Prints the punctuation character as a string that should be losslessly convertible
847 /// back into the same character.
848 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
849 impl fmt::Display for Punct {
850 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
851 f.write_str(&self.to_string())
855 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
856 impl fmt::Debug for Punct {
857 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
858 f.debug_struct("Punct")
859 .field("ch", &self.as_char())
860 .field("spacing", &self.spacing())
861 .field("span", &self.span())
866 #[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
867 impl PartialEq<char> for Punct {
868 fn eq(&self, rhs: &char) -> bool {
869 self.as_char() == *rhs
873 #[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
874 impl PartialEq<Punct> for char {
875 fn eq(&self, rhs: &Punct) -> bool {
876 *self == rhs.as_char()
880 /// An identifier (`ident`).
882 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
883 pub struct Ident(bridge::client::Ident);
886 /// Creates a new `Ident` with the given `string` as well as the specified
888 /// The `string` argument must be a valid identifier permitted by the
889 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
891 /// Note that `span`, currently in rustc, configures the hygiene information
892 /// for this identifier.
894 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
895 /// meaning that identifiers created with this span will be resolved as if they were written
896 /// directly at the location of the macro call, and other code at the macro call site will be
897 /// able to refer to them as well.
899 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
900 /// meaning that identifiers created with this span will be resolved at the location of the
901 /// macro definition and other code at the macro call site will not be able to refer to them.
903 /// Due to the current importance of hygiene this constructor, unlike other
904 /// tokens, requires a `Span` to be specified at construction.
905 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
906 pub fn new(string: &str, span: Span) -> Ident {
907 Ident(bridge::client::Ident::new(string, span.0, false))
910 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
911 /// The `string` argument be a valid identifier permitted by the language
912 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
913 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
914 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
915 pub fn new_raw(string: &str, span: Span) -> Ident {
916 Ident(bridge::client::Ident::new(string, span.0, true))
919 /// Returns the span of this `Ident`, encompassing the entire string returned
920 /// by [`to_string`](Self::to_string).
921 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
922 pub fn span(&self) -> Span {
926 /// Configures the span of this `Ident`, possibly changing its hygiene context.
927 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
928 pub fn set_span(&mut self, span: Span) {
929 self.0 = self.0.with_span(span.0);
933 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
934 // based on it (the reverse of the usual relationship between the two).
935 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
936 impl ToString for Ident {
937 fn to_string(&self) -> String {
938 TokenStream::from(TokenTree::from(self.clone())).to_string()
942 /// Prints the identifier as a string that should be losslessly convertible
943 /// back into the same identifier.
944 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
945 impl fmt::Display for Ident {
946 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
947 f.write_str(&self.to_string())
951 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
952 impl fmt::Debug for Ident {
953 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
954 f.debug_struct("Ident")
955 .field("ident", &self.to_string())
956 .field("span", &self.span())
961 /// A literal string (`"hello"`), byte string (`b"hello"`),
962 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
963 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
964 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
966 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
967 pub struct Literal(bridge::client::Literal);
969 macro_rules! suffixed_int_literals {
970 ($($name:ident => $kind:ident,)*) => ($(
971 /// Creates a new suffixed integer literal with the specified value.
973 /// This function will create an integer like `1u32` where the integer
974 /// value specified is the first part of the token and the integral is
975 /// also suffixed at the end.
976 /// Literals created from negative numbers may not survive round-trips through
977 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
979 /// Literals created through this method have the `Span::call_site()`
980 /// span by default, which can be configured with the `set_span` method
982 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
983 pub fn $name(n: $kind) -> Literal {
984 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
989 macro_rules! unsuffixed_int_literals {
990 ($($name:ident => $kind:ident,)*) => ($(
991 /// Creates a new unsuffixed integer literal with the specified value.
993 /// This function will create an integer like `1` where the integer
994 /// value specified is the first part of the token. No suffix is
995 /// specified on this token, meaning that invocations like
996 /// `Literal::i8_unsuffixed(1)` are equivalent to
997 /// `Literal::u32_unsuffixed(1)`.
998 /// Literals created from negative numbers may not survive rountrips through
999 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1001 /// Literals created through this method have the `Span::call_site()`
1002 /// span by default, which can be configured with the `set_span` method
1004 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1005 pub fn $name(n: $kind) -> Literal {
1006 Literal(bridge::client::Literal::integer(&n.to_string()))
1012 suffixed_int_literals! {
1014 u16_suffixed => u16,
1015 u32_suffixed => u32,
1016 u64_suffixed => u64,
1017 u128_suffixed => u128,
1018 usize_suffixed => usize,
1020 i16_suffixed => i16,
1021 i32_suffixed => i32,
1022 i64_suffixed => i64,
1023 i128_suffixed => i128,
1024 isize_suffixed => isize,
1027 unsuffixed_int_literals! {
1028 u8_unsuffixed => u8,
1029 u16_unsuffixed => u16,
1030 u32_unsuffixed => u32,
1031 u64_unsuffixed => u64,
1032 u128_unsuffixed => u128,
1033 usize_unsuffixed => usize,
1034 i8_unsuffixed => i8,
1035 i16_unsuffixed => i16,
1036 i32_unsuffixed => i32,
1037 i64_unsuffixed => i64,
1038 i128_unsuffixed => i128,
1039 isize_unsuffixed => isize,
1042 /// Creates a new unsuffixed floating-point literal.
1044 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1045 /// the float's value is emitted directly into the token but no suffix is
1046 /// used, so it may be inferred to be a `f64` later in the compiler.
1047 /// Literals created from negative numbers may not survive rountrips through
1048 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1052 /// This function requires that the specified float is finite, for
1053 /// example if it is infinity or NaN this function will panic.
1054 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1055 pub fn f32_unsuffixed(n: f32) -> Literal {
1057 panic!("Invalid float literal {}", n);
1059 Literal(bridge::client::Literal::float(&n.to_string()))
1062 /// Creates a new suffixed floating-point literal.
1064 /// This constructor will create a literal like `1.0f32` where the value
1065 /// specified is the preceding part of the token and `f32` is the suffix of
1066 /// the token. This token will always be inferred to be an `f32` in the
1068 /// Literals created from negative numbers may not survive rountrips through
1069 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1073 /// This function requires that the specified float is finite, for
1074 /// example if it is infinity or NaN this function will panic.
1075 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1076 pub fn f32_suffixed(n: f32) -> Literal {
1078 panic!("Invalid float literal {}", n);
1080 Literal(bridge::client::Literal::f32(&n.to_string()))
1083 /// Creates a new unsuffixed floating-point literal.
1085 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1086 /// the float's value is emitted directly into the token but no suffix is
1087 /// used, so it may be inferred to be a `f64` later in the compiler.
1088 /// Literals created from negative numbers may not survive rountrips through
1089 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1093 /// This function requires that the specified float is finite, for
1094 /// example if it is infinity or NaN this function will panic.
1095 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1096 pub fn f64_unsuffixed(n: f64) -> Literal {
1098 panic!("Invalid float literal {}", n);
1100 Literal(bridge::client::Literal::float(&n.to_string()))
1103 /// Creates a new suffixed floating-point literal.
1105 /// This constructor will create a literal like `1.0f64` where the value
1106 /// specified is the preceding part of the token and `f64` is the suffix of
1107 /// the token. This token will always be inferred to be an `f64` in the
1109 /// Literals created from negative numbers may not survive rountrips through
1110 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1114 /// This function requires that the specified float is finite, for
1115 /// example if it is infinity or NaN this function will panic.
1116 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1117 pub fn f64_suffixed(n: f64) -> Literal {
1119 panic!("Invalid float literal {}", n);
1121 Literal(bridge::client::Literal::f64(&n.to_string()))
1125 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1126 pub fn string(string: &str) -> Literal {
1127 Literal(bridge::client::Literal::string(string))
1130 /// Character literal.
1131 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1132 pub fn character(ch: char) -> Literal {
1133 Literal(bridge::client::Literal::character(ch))
1136 /// Byte string literal.
1137 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1138 pub fn byte_string(bytes: &[u8]) -> Literal {
1139 Literal(bridge::client::Literal::byte_string(bytes))
1142 /// Returns the span encompassing this literal.
1143 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1144 pub fn span(&self) -> Span {
1148 /// Configures the span associated for this literal.
1149 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1150 pub fn set_span(&mut self, span: Span) {
1151 self.0.set_span(span.0);
1154 /// Returns a `Span` that is a subset of `self.span()` containing only the
1155 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1156 /// span is outside the bounds of `self`.
1157 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1158 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1159 // occur elsewhere when the source text is printed.
1160 // FIXME(SergioBenitez): there is no way for the user to know what
1161 // `self.span()` actually maps to, so this method can currently only be
1162 // called blindly. For example, `to_string()` for the character 'c' returns
1163 // "'\u{63}'"; there is no way for the user to know whether the source text
1164 // was 'c' or whether it was '\u{63}'.
1165 #[unstable(feature = "proc_macro_span", issue = "54725")]
1166 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1167 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1168 fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1170 Bound::Included(x) => Bound::Included(x.clone()),
1171 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1172 Bound::Unbounded => Bound::Unbounded,
1176 self.0.subspan(cloned_bound(range.start_bound()), cloned_bound(range.end_bound())).map(Span)
1180 /// Parse a single literal from its stringified representation.
1182 /// In order to parse successfully, the input string must not contain anything
1183 /// but the literal token. Specifically, it must not contain whitespace or
1184 /// comments in addition to the literal.
1186 /// The resulting literal token will have a `Span::call_site()` span.
1188 /// NOTE: some errors may cause panics instead of returning `LexError`. We
1189 /// reserve the right to change these errors into `LexError`s later.
1190 #[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1191 impl FromStr for Literal {
1192 type Err = LexError;
1194 fn from_str(src: &str) -> Result<Self, LexError> {
1195 match bridge::client::Literal::from_str(src) {
1196 Ok(literal) => Ok(Literal(literal)),
1197 Err(()) => Err(LexError::new()),
1202 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1203 // based on it (the reverse of the usual relationship between the two).
1204 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1205 impl ToString for Literal {
1206 fn to_string(&self) -> String {
1207 TokenStream::from(TokenTree::from(self.clone())).to_string()
1211 /// Prints the literal as a string that should be losslessly convertible
1212 /// back into the same literal (except for possible rounding for floating point literals).
1213 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1214 impl fmt::Display for Literal {
1215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1216 f.write_str(&self.to_string())
1220 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1221 impl fmt::Debug for Literal {
1222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1227 /// Tracked access to environment variables.
1228 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1229 pub mod tracked_env {
1230 use std::env::{self, VarError};
1231 use std::ffi::OsStr;
1233 /// Retrieve an environment variable and add it to build dependency info.
1234 /// Build system executing the compiler will know that the variable was accessed during
1235 /// compilation, and will be able to rerun the build when the value of that variable changes.
1236 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1237 /// standard library, except that the argument must be UTF-8.
1238 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1239 pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1240 let key: &str = key.as_ref();
1241 let value = env::var(key);
1242 crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());