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 // This library is copied into rust-analyzer to allow loading rustc compiled proc macros.
21 // Please avoid unstable features where possible to minimize the amount of changes necessary
22 // to make it compile with rust-analyzer on stable.
23 #![feature(rustc_allow_const_fn_unstable)]
24 #![feature(staged_api)]
25 #![feature(allow_internal_unstable)]
26 #![feature(decl_macro)]
27 #![feature(negative_impls)]
28 #![feature(restricted_std)]
29 #![feature(rustc_attrs)]
30 #![feature(min_specialization)]
31 #![recursion_limit = "256"]
33 #[unstable(feature = "proc_macro_internals", issue = "27812")]
39 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
40 pub use diagnostic::{Diagnostic, Level, MultiSpan};
42 use std::cmp::Ordering;
43 use std::ops::RangeBounds;
44 use std::path::PathBuf;
45 use std::str::FromStr;
46 use std::{error, fmt, iter};
48 /// Determines whether proc_macro has been made accessible to the currently
51 /// The proc_macro crate is only intended for use inside the implementation of
52 /// procedural macros. All the functions in this crate panic if invoked from
53 /// outside of a procedural macro, such as from a build script or unit test or
54 /// ordinary Rust binary.
56 /// With consideration for Rust libraries that are designed to support both
57 /// macro and non-macro use cases, `proc_macro::is_available()` provides a
58 /// non-panicking way to detect whether the infrastructure required to use the
59 /// API of proc_macro is presently available. Returns true if invoked from
60 /// inside of a procedural macro, false if invoked from any other binary.
61 #[stable(feature = "proc_macro_is_available", since = "1.57.0")]
62 pub fn is_available() -> bool {
63 bridge::Bridge::is_available()
66 /// The main type provided by this crate, representing an abstract stream of
67 /// tokens, or, more specifically, a sequence of token trees.
68 /// The type provide interfaces for iterating over those token trees and, conversely,
69 /// collecting a number of token trees into one stream.
71 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
72 /// and `#[proc_macro_derive]` definitions.
73 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
75 pub struct TokenStream(Option<bridge::client::TokenStream>);
77 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
78 impl !Send for TokenStream {}
79 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
80 impl !Sync for TokenStream {}
82 /// Error returned from `TokenStream::from_str`.
83 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
88 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
89 impl fmt::Display for LexError {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 f.write_str("cannot parse string into token stream")
95 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
96 impl error::Error for LexError {}
98 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
99 impl !Send for LexError {}
100 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
101 impl !Sync for LexError {}
103 /// Error returned from `TokenStream::expand_expr`.
104 #[unstable(feature = "proc_macro_expand", issue = "90765")]
107 pub struct ExpandError;
109 #[unstable(feature = "proc_macro_expand", issue = "90765")]
110 impl fmt::Display for ExpandError {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 f.write_str("macro expansion failed")
116 #[unstable(feature = "proc_macro_expand", issue = "90765")]
117 impl error::Error for ExpandError {}
119 #[unstable(feature = "proc_macro_expand", issue = "90765")]
120 impl !Send for ExpandError {}
122 #[unstable(feature = "proc_macro_expand", issue = "90765")]
123 impl !Sync for ExpandError {}
126 /// Returns an empty `TokenStream` containing no token trees.
127 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
128 pub fn new() -> TokenStream {
132 /// Checks if this `TokenStream` is empty.
133 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
134 pub fn is_empty(&self) -> bool {
135 self.0.as_ref().map(|h| h.is_empty()).unwrap_or(true)
138 /// Parses this `TokenStream` as an expression and attempts to expand any
139 /// macros within it. Returns the expanded `TokenStream`.
141 /// Currently only expressions expanding to literals will succeed, although
142 /// this may be relaxed in the future.
144 /// NOTE: In error conditions, `expand_expr` may leave macros unexpanded,
145 /// report an error, failing compilation, and/or return an `Err(..)`. The
146 /// specific behavior for any error condition, and what conditions are
147 /// considered errors, is unspecified and may change in the future.
148 #[unstable(feature = "proc_macro_expand", issue = "90765")]
149 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
150 let stream = self.0.as_ref().ok_or(ExpandError)?;
151 match bridge::client::TokenStream::expand_expr(stream) {
152 Ok(stream) => Ok(TokenStream(Some(stream))),
153 Err(_) => Err(ExpandError),
158 /// Attempts to break the string into tokens and parse those tokens into a token stream.
159 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
160 /// or characters not existing in the language.
161 /// All tokens in the parsed stream get `Span::call_site()` spans.
163 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
164 /// change these errors into `LexError`s later.
165 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
166 impl FromStr for TokenStream {
169 fn from_str(src: &str) -> Result<TokenStream, LexError> {
170 Ok(TokenStream(Some(bridge::client::TokenStream::from_str(src))))
174 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
175 // based on it (the reverse of the usual relationship between the two).
176 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
177 impl ToString for TokenStream {
178 fn to_string(&self) -> String {
179 self.0.as_ref().map(|t| t.to_string()).unwrap_or_default()
183 /// Prints the token stream as a string that is supposed to be losslessly convertible back
184 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
185 /// with `Delimiter::None` delimiters and negative numeric literals.
186 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
187 impl fmt::Display for TokenStream {
188 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189 f.write_str(&self.to_string())
193 /// Prints token in a form convenient for debugging.
194 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
195 impl fmt::Debug for TokenStream {
196 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197 f.write_str("TokenStream ")?;
198 f.debug_list().entries(self.clone()).finish()
202 #[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
203 impl Default for TokenStream {
204 fn default() -> Self {
209 #[unstable(feature = "proc_macro_quote", issue = "54722")]
210 pub use quote::{quote, quote_span};
212 fn tree_to_bridge_tree(
214 ) -> bridge::TokenTree<
215 bridge::client::Group,
216 bridge::client::Punct,
217 bridge::client::Ident,
218 bridge::client::Literal,
221 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
222 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
223 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
224 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
228 /// Creates a token stream containing a single token tree.
229 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
230 impl From<TokenTree> for TokenStream {
231 fn from(tree: TokenTree) -> TokenStream {
232 TokenStream(Some(bridge::client::TokenStream::from_token_tree(tree_to_bridge_tree(tree))))
236 /// Non-generic helper for implementing `FromIterator<TokenTree>` and
237 /// `Extend<TokenTree>` with less monomorphization in calling crates.
238 struct ConcatTreesHelper {
241 bridge::client::Group,
242 bridge::client::Punct,
243 bridge::client::Ident,
244 bridge::client::Literal,
249 impl ConcatTreesHelper {
250 fn new(capacity: usize) -> Self {
251 ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
254 fn push(&mut self, tree: TokenTree) {
255 self.trees.push(tree_to_bridge_tree(tree));
258 fn build(self) -> TokenStream {
259 if self.trees.is_empty() {
262 TokenStream(Some(bridge::client::TokenStream::concat_trees(None, self.trees)))
266 fn append_to(self, stream: &mut TokenStream) {
267 if self.trees.is_empty() {
270 stream.0 = Some(bridge::client::TokenStream::concat_trees(stream.0.take(), self.trees))
274 /// Non-generic helper for implementing `FromIterator<TokenStream>` and
275 /// `Extend<TokenStream>` with less monomorphization in calling crates.
276 struct ConcatStreamsHelper {
277 streams: Vec<bridge::client::TokenStream>,
280 impl ConcatStreamsHelper {
281 fn new(capacity: usize) -> Self {
282 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
285 fn push(&mut self, stream: TokenStream) {
286 if let Some(stream) = stream.0 {
287 self.streams.push(stream);
291 fn build(mut self) -> TokenStream {
292 if self.streams.len() <= 1 {
293 TokenStream(self.streams.pop())
295 TokenStream(Some(bridge::client::TokenStream::concat_streams(None, self.streams)))
299 fn append_to(mut self, stream: &mut TokenStream) {
300 if self.streams.is_empty() {
303 let base = stream.0.take();
304 if base.is_none() && self.streams.len() == 1 {
305 stream.0 = self.streams.pop();
307 stream.0 = Some(bridge::client::TokenStream::concat_streams(base, self.streams));
312 /// Collects a number of token trees into a single stream.
313 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
314 impl iter::FromIterator<TokenTree> for TokenStream {
315 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
316 let iter = trees.into_iter();
317 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
318 iter.for_each(|tree| builder.push(tree));
323 /// A "flattening" operation on token streams, collects token trees
324 /// from multiple token streams into a single stream.
325 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
326 impl iter::FromIterator<TokenStream> for TokenStream {
327 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
328 let iter = streams.into_iter();
329 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
330 iter.for_each(|stream| builder.push(stream));
335 #[stable(feature = "token_stream_extend", since = "1.30.0")]
336 impl Extend<TokenTree> for TokenStream {
337 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
338 let iter = trees.into_iter();
339 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
340 iter.for_each(|tree| builder.push(tree));
341 builder.append_to(self);
345 #[stable(feature = "token_stream_extend", since = "1.30.0")]
346 impl Extend<TokenStream> for TokenStream {
347 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
348 let iter = streams.into_iter();
349 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
350 iter.for_each(|stream| builder.push(stream));
351 builder.append_to(self);
355 /// Public implementation details for the `TokenStream` type, such as iterators.
356 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
357 pub mod token_stream {
358 use crate::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree};
360 /// An iterator over `TokenStream`'s `TokenTree`s.
361 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
362 /// and returns whole groups as token trees.
364 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
368 bridge::client::Group,
369 bridge::client::Punct,
370 bridge::client::Ident,
371 bridge::client::Literal,
376 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
377 impl Iterator for IntoIter {
378 type Item = TokenTree;
380 fn next(&mut self) -> Option<TokenTree> {
381 self.0.next().map(|tree| match tree {
382 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
383 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
384 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
385 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
390 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
391 impl IntoIterator for TokenStream {
392 type Item = TokenTree;
393 type IntoIter = IntoIter;
395 fn into_iter(self) -> IntoIter {
396 IntoIter(self.0.map(|v| v.into_trees()).unwrap_or_default().into_iter())
401 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
402 /// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
403 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
405 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
406 /// To quote `$` itself, use `$$`.
407 #[unstable(feature = "proc_macro_quote", issue = "54722")]
408 #[allow_internal_unstable(proc_macro_def_site, proc_macro_internals)]
409 #[rustc_builtin_macro]
410 pub macro quote($($t:tt)*) {
411 /* compiler built-in */
414 #[unstable(feature = "proc_macro_internals", issue = "27812")]
418 /// A region of source code, along with macro expansion information.
419 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
420 #[derive(Copy, Clone)]
421 pub struct Span(bridge::client::Span);
423 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
424 impl !Send for Span {}
425 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
426 impl !Sync for Span {}
428 macro_rules! diagnostic_method {
429 ($name:ident, $level:expr) => {
430 /// Creates a new `Diagnostic` with the given `message` at the span
432 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
433 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
434 Diagnostic::spanned(self, $level, message)
440 /// A span that resolves at the macro definition site.
441 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
442 pub fn def_site() -> Span {
443 Span(bridge::client::Span::def_site())
446 /// The span of the invocation of the current procedural macro.
447 /// Identifiers created with this span will be resolved as if they were written
448 /// directly at the macro call location (call-site hygiene) and other code
449 /// at the macro call site will be able to refer to them as well.
450 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
451 pub fn call_site() -> Span {
452 Span(bridge::client::Span::call_site())
455 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
456 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
457 /// call site (everything else).
458 /// The span location is taken from the call-site.
459 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
460 pub fn mixed_site() -> Span {
461 Span(bridge::client::Span::mixed_site())
464 /// The original source file into which this span points.
465 #[unstable(feature = "proc_macro_span", issue = "54725")]
466 pub fn source_file(&self) -> SourceFile {
467 SourceFile(self.0.source_file())
470 /// The `Span` for the tokens in the previous macro expansion from which
471 /// `self` was generated from, if any.
472 #[unstable(feature = "proc_macro_span", issue = "54725")]
473 pub fn parent(&self) -> Option<Span> {
474 self.0.parent().map(Span)
477 /// The span for the origin source code that `self` was generated from. If
478 /// this `Span` wasn't generated from other macro expansions then the return
479 /// value is the same as `*self`.
480 #[unstable(feature = "proc_macro_span", issue = "54725")]
481 pub fn source(&self) -> Span {
482 Span(self.0.source())
485 /// Gets the starting line/column in the source file for this span.
486 #[unstable(feature = "proc_macro_span", issue = "54725")]
487 pub fn start(&self) -> LineColumn {
488 self.0.start().add_1_to_column()
491 /// Gets the ending line/column in the source file for this span.
492 #[unstable(feature = "proc_macro_span", issue = "54725")]
493 pub fn end(&self) -> LineColumn {
494 self.0.end().add_1_to_column()
497 /// Creates an empty span pointing to directly before this span.
498 #[unstable(feature = "proc_macro_span_shrink", issue = "87552")]
499 pub fn before(&self) -> Span {
500 Span(self.0.before())
503 /// Creates an empty span pointing to directly after this span.
504 #[unstable(feature = "proc_macro_span_shrink", issue = "87552")]
505 pub fn after(&self) -> Span {
509 /// Creates a new span encompassing `self` and `other`.
511 /// Returns `None` if `self` and `other` are from different files.
512 #[unstable(feature = "proc_macro_span", issue = "54725")]
513 pub fn join(&self, other: Span) -> Option<Span> {
514 self.0.join(other.0).map(Span)
517 /// Creates a new span with the same line/column information as `self` but
518 /// that resolves symbols as though it were at `other`.
519 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
520 pub fn resolved_at(&self, other: Span) -> Span {
521 Span(self.0.resolved_at(other.0))
524 /// Creates a new span with the same name resolution behavior as `self` but
525 /// with the line/column information of `other`.
526 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
527 pub fn located_at(&self, other: Span) -> Span {
528 other.resolved_at(*self)
531 /// Compares to spans to see if they're equal.
532 #[unstable(feature = "proc_macro_span", issue = "54725")]
533 pub fn eq(&self, other: &Span) -> bool {
537 /// Returns the source text behind a span. This preserves the original source
538 /// code, including spaces and comments. It only returns a result if the span
539 /// corresponds to real source code.
541 /// Note: The observable result of a macro should only rely on the tokens and
542 /// not on this source text. The result of this function is a best effort to
543 /// be used for diagnostics only.
544 #[unstable(feature = "proc_macro_span", issue = "54725")]
545 pub fn source_text(&self) -> Option<String> {
549 // Used by the implementation of `Span::quote`
551 #[unstable(feature = "proc_macro_internals", issue = "27812")]
552 pub fn save_span(&self) -> usize {
556 // Used by the implementation of `Span::quote`
558 #[unstable(feature = "proc_macro_internals", issue = "27812")]
559 pub fn recover_proc_macro_span(id: usize) -> Span {
560 Span(bridge::client::Span::recover_proc_macro_span(id))
563 diagnostic_method!(error, Level::Error);
564 diagnostic_method!(warning, Level::Warning);
565 diagnostic_method!(note, Level::Note);
566 diagnostic_method!(help, Level::Help);
569 /// Prints a span in a form convenient for debugging.
570 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
571 impl fmt::Debug for Span {
572 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
577 /// A line-column pair representing the start or end of a `Span`.
578 #[unstable(feature = "proc_macro_span", issue = "54725")]
579 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
580 pub struct LineColumn {
581 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
582 #[unstable(feature = "proc_macro_span", issue = "54725")]
584 /// The 1-indexed column (number of bytes in UTF-8 encoding) in the source
585 /// file on which the span starts or ends (inclusive).
586 #[unstable(feature = "proc_macro_span", issue = "54725")]
591 fn add_1_to_column(self) -> Self {
592 LineColumn { line: self.line, column: self.column + 1 }
596 #[unstable(feature = "proc_macro_span", issue = "54725")]
597 impl !Send for LineColumn {}
598 #[unstable(feature = "proc_macro_span", issue = "54725")]
599 impl !Sync for LineColumn {}
601 #[unstable(feature = "proc_macro_span", issue = "54725")]
602 impl Ord for LineColumn {
603 fn cmp(&self, other: &Self) -> Ordering {
604 self.line.cmp(&other.line).then(self.column.cmp(&other.column))
608 #[unstable(feature = "proc_macro_span", issue = "54725")]
609 impl PartialOrd for LineColumn {
610 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
611 Some(self.cmp(other))
615 /// The source file of a given `Span`.
616 #[unstable(feature = "proc_macro_span", issue = "54725")]
618 pub struct SourceFile(bridge::client::SourceFile);
621 /// Gets the path to this source file.
624 /// If the code span associated with this `SourceFile` was generated by an external macro, this
625 /// macro, this might not be an actual path on the filesystem. Use [`is_real`] to check.
627 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
628 /// the command line, the path as given might not actually be valid.
630 /// [`is_real`]: Self::is_real
631 #[unstable(feature = "proc_macro_span", issue = "54725")]
632 pub fn path(&self) -> PathBuf {
633 PathBuf::from(self.0.path())
636 /// Returns `true` if this source file is a real source file, and not generated by an external
637 /// macro's expansion.
638 #[unstable(feature = "proc_macro_span", issue = "54725")]
639 pub fn is_real(&self) -> bool {
640 // This is a hack until intercrate spans are implemented and we can have real source files
641 // for spans generated in external macros.
642 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
647 #[unstable(feature = "proc_macro_span", issue = "54725")]
648 impl fmt::Debug for SourceFile {
649 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
650 f.debug_struct("SourceFile")
651 .field("path", &self.path())
652 .field("is_real", &self.is_real())
657 #[unstable(feature = "proc_macro_span", issue = "54725")]
658 impl PartialEq for SourceFile {
659 fn eq(&self, other: &Self) -> bool {
664 #[unstable(feature = "proc_macro_span", issue = "54725")]
665 impl Eq for SourceFile {}
667 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
668 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
671 /// A token stream surrounded by bracket delimiters.
672 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
673 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
675 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
676 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
677 /// A single punctuation character (`+`, `,`, `$`, etc.).
678 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
679 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
680 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
681 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
682 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
685 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
686 impl !Send for TokenTree {}
687 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
688 impl !Sync for TokenTree {}
691 /// Returns the span of this tree, delegating to the `span` method of
692 /// the contained token or a delimited stream.
693 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
694 pub fn span(&self) -> Span {
696 TokenTree::Group(ref t) => t.span(),
697 TokenTree::Ident(ref t) => t.span(),
698 TokenTree::Punct(ref t) => t.span(),
699 TokenTree::Literal(ref t) => t.span(),
703 /// Configures the span for *only this token*.
705 /// Note that if this token is a `Group` then this method will not configure
706 /// the span of each of the internal tokens, this will simply delegate to
707 /// the `set_span` method of each variant.
708 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
709 pub fn set_span(&mut self, span: Span) {
711 TokenTree::Group(ref mut t) => t.set_span(span),
712 TokenTree::Ident(ref mut t) => t.set_span(span),
713 TokenTree::Punct(ref mut t) => t.set_span(span),
714 TokenTree::Literal(ref mut t) => t.set_span(span),
719 /// Prints token tree in a form convenient for debugging.
720 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
721 impl fmt::Debug for TokenTree {
722 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
723 // Each of these has the name in the struct type in the derived debug,
724 // so don't bother with an extra layer of indirection
726 TokenTree::Group(ref tt) => tt.fmt(f),
727 TokenTree::Ident(ref tt) => tt.fmt(f),
728 TokenTree::Punct(ref tt) => tt.fmt(f),
729 TokenTree::Literal(ref tt) => tt.fmt(f),
734 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
735 impl From<Group> for TokenTree {
736 fn from(g: Group) -> TokenTree {
741 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
742 impl From<Ident> for TokenTree {
743 fn from(g: Ident) -> TokenTree {
748 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
749 impl From<Punct> for TokenTree {
750 fn from(g: Punct) -> TokenTree {
755 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
756 impl From<Literal> for TokenTree {
757 fn from(g: Literal) -> TokenTree {
758 TokenTree::Literal(g)
762 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
763 // based on it (the reverse of the usual relationship between the two).
764 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
765 impl ToString for TokenTree {
766 fn to_string(&self) -> String {
768 TokenTree::Group(ref t) => t.to_string(),
769 TokenTree::Ident(ref t) => t.to_string(),
770 TokenTree::Punct(ref t) => t.to_string(),
771 TokenTree::Literal(ref t) => t.to_string(),
776 /// Prints the token tree as a string that is supposed to be losslessly convertible back
777 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
778 /// with `Delimiter::None` delimiters and negative numeric literals.
779 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
780 impl fmt::Display for TokenTree {
781 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
782 f.write_str(&self.to_string())
786 /// A delimited token stream.
788 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
790 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
791 pub struct Group(bridge::client::Group);
793 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
794 impl !Send for Group {}
795 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
796 impl !Sync for Group {}
798 /// Describes how a sequence of token trees is delimited.
799 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
800 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
803 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
806 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
809 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
812 /// An invisible delimiter, that may, for example, appear around tokens coming from a
813 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
814 /// `$var * 3` where `$var` is `1 + 2`.
815 /// Invisible delimiters might not survive roundtrip of a token stream through a string.
816 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
821 /// Creates a new `Group` with the given delimiter and token stream.
823 /// This constructor will set the span for this group to
824 /// `Span::call_site()`. To change the span you can use the `set_span`
826 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
827 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
828 Group(bridge::client::Group::new(delimiter, stream.0))
831 /// Returns the delimiter of this `Group`
832 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
833 pub fn delimiter(&self) -> Delimiter {
837 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
839 /// Note that the returned token stream does not include the delimiter
841 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
842 pub fn stream(&self) -> TokenStream {
843 TokenStream(Some(self.0.stream()))
846 /// Returns the span for the delimiters of this token stream, spanning the
850 /// pub fn span(&self) -> Span {
853 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
854 pub fn span(&self) -> Span {
858 /// Returns the span pointing to the opening delimiter of this group.
861 /// pub fn span_open(&self) -> Span {
864 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
865 pub fn span_open(&self) -> Span {
866 Span(self.0.span_open())
869 /// Returns the span pointing to the closing delimiter of this group.
872 /// pub fn span_close(&self) -> Span {
875 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
876 pub fn span_close(&self) -> Span {
877 Span(self.0.span_close())
880 /// Configures the span for this `Group`'s delimiters, but not its internal
883 /// This method will **not** set the span of all the internal tokens spanned
884 /// by this group, but rather it will only set the span of the delimiter
885 /// tokens at the level of the `Group`.
886 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
887 pub fn set_span(&mut self, span: Span) {
888 self.0.set_span(span.0);
892 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
893 // based on it (the reverse of the usual relationship between the two).
894 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
895 impl ToString for Group {
896 fn to_string(&self) -> String {
897 TokenStream::from(TokenTree::from(self.clone())).to_string()
901 /// Prints the group as a string that should be losslessly convertible back
902 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
903 /// with `Delimiter::None` delimiters.
904 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
905 impl fmt::Display for Group {
906 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
907 f.write_str(&self.to_string())
911 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
912 impl fmt::Debug for Group {
913 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
914 f.debug_struct("Group")
915 .field("delimiter", &self.delimiter())
916 .field("stream", &self.stream())
917 .field("span", &self.span())
922 /// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
924 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
925 /// forms of `Spacing` returned.
926 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
928 pub struct Punct(bridge::client::Punct);
930 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
931 impl !Send for Punct {}
932 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
933 impl !Sync for Punct {}
935 /// Describes whether a `Punct` is followed immediately by another `Punct` ([`Spacing::Joint`]) or
936 /// by a different token or whitespace ([`Spacing::Alone`]).
937 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
938 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
940 /// A `Punct` is not immediately followed by another `Punct`.
941 /// E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`.
942 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
944 /// A `Punct` is immediately followed by another `Punct`.
945 /// E.g. `+` is `Joint` in `+=` and `++`.
947 /// Additionally, single quote `'` can join with identifiers to form lifetimes: `'ident`.
948 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
953 /// Creates a new `Punct` from the given character and spacing.
954 /// The `ch` argument must be a valid punctuation character permitted by the language,
955 /// otherwise the function will panic.
957 /// The returned `Punct` will have the default span of `Span::call_site()`
958 /// which can be further configured with the `set_span` method below.
959 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
960 pub fn new(ch: char, spacing: Spacing) -> Punct {
961 Punct(bridge::client::Punct::new(ch, spacing))
964 /// Returns the value of this punctuation character as `char`.
965 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
966 pub fn as_char(&self) -> char {
970 /// Returns the spacing of this punctuation character, indicating whether it's immediately
971 /// followed by another `Punct` in the token stream, so they can potentially be combined into
972 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
973 /// (`Alone`) so the operator has certainly ended.
974 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
975 pub fn spacing(&self) -> Spacing {
979 /// Returns the span for this punctuation character.
980 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
981 pub fn span(&self) -> Span {
985 /// Configure the span for this punctuation character.
986 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
987 pub fn set_span(&mut self, span: Span) {
988 self.0 = self.0.with_span(span.0);
992 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
993 // based on it (the reverse of the usual relationship between the two).
994 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
995 impl ToString for Punct {
996 fn to_string(&self) -> String {
997 TokenStream::from(TokenTree::from(self.clone())).to_string()
1001 /// Prints the punctuation character as a string that should be losslessly convertible
1002 /// back into the same character.
1003 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1004 impl fmt::Display for Punct {
1005 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1006 f.write_str(&self.to_string())
1010 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1011 impl fmt::Debug for Punct {
1012 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1013 f.debug_struct("Punct")
1014 .field("ch", &self.as_char())
1015 .field("spacing", &self.spacing())
1016 .field("span", &self.span())
1021 #[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1022 impl PartialEq<char> for Punct {
1023 fn eq(&self, rhs: &char) -> bool {
1024 self.as_char() == *rhs
1028 #[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1029 impl PartialEq<Punct> for char {
1030 fn eq(&self, rhs: &Punct) -> bool {
1031 *self == rhs.as_char()
1035 /// An identifier (`ident`).
1037 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1038 pub struct Ident(bridge::client::Ident);
1041 /// Creates a new `Ident` with the given `string` as well as the specified
1043 /// The `string` argument must be a valid identifier permitted by the
1044 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
1046 /// Note that `span`, currently in rustc, configures the hygiene information
1047 /// for this identifier.
1049 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
1050 /// meaning that identifiers created with this span will be resolved as if they were written
1051 /// directly at the location of the macro call, and other code at the macro call site will be
1052 /// able to refer to them as well.
1054 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
1055 /// meaning that identifiers created with this span will be resolved at the location of the
1056 /// macro definition and other code at the macro call site will not be able to refer to them.
1058 /// Due to the current importance of hygiene this constructor, unlike other
1059 /// tokens, requires a `Span` to be specified at construction.
1060 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1061 pub fn new(string: &str, span: Span) -> Ident {
1062 Ident(bridge::client::Ident::new(string, span.0, false))
1065 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
1066 /// The `string` argument be a valid identifier permitted by the language
1067 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
1068 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
1069 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1070 pub fn new_raw(string: &str, span: Span) -> Ident {
1071 Ident(bridge::client::Ident::new(string, span.0, true))
1074 /// Returns the span of this `Ident`, encompassing the entire string returned
1075 /// by [`to_string`](Self::to_string).
1076 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1077 pub fn span(&self) -> Span {
1081 /// Configures the span of this `Ident`, possibly changing its hygiene context.
1082 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1083 pub fn set_span(&mut self, span: Span) {
1084 self.0 = self.0.with_span(span.0);
1088 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1089 // based on it (the reverse of the usual relationship between the two).
1090 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1091 impl ToString for Ident {
1092 fn to_string(&self) -> String {
1093 TokenStream::from(TokenTree::from(self.clone())).to_string()
1097 /// Prints the identifier as a string that should be losslessly convertible
1098 /// back into the same identifier.
1099 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1100 impl fmt::Display for Ident {
1101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1102 f.write_str(&self.to_string())
1106 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1107 impl fmt::Debug for Ident {
1108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109 f.debug_struct("Ident")
1110 .field("ident", &self.to_string())
1111 .field("span", &self.span())
1116 /// A literal string (`"hello"`), byte string (`b"hello"`),
1117 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
1118 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1119 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
1121 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1122 pub struct Literal(bridge::client::Literal);
1124 macro_rules! suffixed_int_literals {
1125 ($($name:ident => $kind:ident,)*) => ($(
1126 /// Creates a new suffixed integer literal with the specified value.
1128 /// This function will create an integer like `1u32` where the integer
1129 /// value specified is the first part of the token and the integral is
1130 /// also suffixed at the end.
1131 /// Literals created from negative numbers might not survive round-trips through
1132 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1134 /// Literals created through this method have the `Span::call_site()`
1135 /// span by default, which can be configured with the `set_span` method
1137 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1138 pub fn $name(n: $kind) -> Literal {
1139 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
1144 macro_rules! unsuffixed_int_literals {
1145 ($($name:ident => $kind:ident,)*) => ($(
1146 /// Creates a new unsuffixed integer literal with the specified value.
1148 /// This function will create an integer like `1` where the integer
1149 /// value specified is the first part of the token. No suffix is
1150 /// specified on this token, meaning that invocations like
1151 /// `Literal::i8_unsuffixed(1)` are equivalent to
1152 /// `Literal::u32_unsuffixed(1)`.
1153 /// Literals created from negative numbers might not survive rountrips through
1154 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1156 /// Literals created through this method have the `Span::call_site()`
1157 /// span by default, which can be configured with the `set_span` method
1159 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1160 pub fn $name(n: $kind) -> Literal {
1161 Literal(bridge::client::Literal::integer(&n.to_string()))
1167 suffixed_int_literals! {
1169 u16_suffixed => u16,
1170 u32_suffixed => u32,
1171 u64_suffixed => u64,
1172 u128_suffixed => u128,
1173 usize_suffixed => usize,
1175 i16_suffixed => i16,
1176 i32_suffixed => i32,
1177 i64_suffixed => i64,
1178 i128_suffixed => i128,
1179 isize_suffixed => isize,
1182 unsuffixed_int_literals! {
1183 u8_unsuffixed => u8,
1184 u16_unsuffixed => u16,
1185 u32_unsuffixed => u32,
1186 u64_unsuffixed => u64,
1187 u128_unsuffixed => u128,
1188 usize_unsuffixed => usize,
1189 i8_unsuffixed => i8,
1190 i16_unsuffixed => i16,
1191 i32_unsuffixed => i32,
1192 i64_unsuffixed => i64,
1193 i128_unsuffixed => i128,
1194 isize_unsuffixed => isize,
1197 /// Creates a new unsuffixed floating-point literal.
1199 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1200 /// the float's value is emitted directly into the token but no suffix is
1201 /// used, so it may be inferred to be a `f64` later in the compiler.
1202 /// Literals created from negative numbers might not survive rountrips through
1203 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1207 /// This function requires that the specified float is finite, for
1208 /// example if it is infinity or NaN this function will panic.
1209 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1210 pub fn f32_unsuffixed(n: f32) -> Literal {
1212 panic!("Invalid float literal {n}");
1214 let mut repr = n.to_string();
1215 if !repr.contains('.') {
1216 repr.push_str(".0");
1218 Literal(bridge::client::Literal::float(&repr))
1221 /// Creates a new suffixed floating-point literal.
1223 /// This constructor will create a literal like `1.0f32` where the value
1224 /// specified is the preceding part of the token and `f32` is the suffix of
1225 /// the token. This token will always be inferred to be an `f32` in the
1227 /// Literals created from negative numbers might not survive rountrips through
1228 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1232 /// This function requires that the specified float is finite, for
1233 /// example if it is infinity or NaN this function will panic.
1234 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1235 pub fn f32_suffixed(n: f32) -> Literal {
1237 panic!("Invalid float literal {n}");
1239 Literal(bridge::client::Literal::f32(&n.to_string()))
1242 /// Creates a new unsuffixed floating-point literal.
1244 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1245 /// the float's value is emitted directly into the token but no suffix is
1246 /// used, so it may be inferred to be a `f64` later in the compiler.
1247 /// Literals created from negative numbers might not survive rountrips through
1248 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1252 /// This function requires that the specified float is finite, for
1253 /// example if it is infinity or NaN this function will panic.
1254 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1255 pub fn f64_unsuffixed(n: f64) -> Literal {
1257 panic!("Invalid float literal {n}");
1259 let mut repr = n.to_string();
1260 if !repr.contains('.') {
1261 repr.push_str(".0");
1263 Literal(bridge::client::Literal::float(&repr))
1266 /// Creates a new suffixed floating-point literal.
1268 /// This constructor will create a literal like `1.0f64` where the value
1269 /// specified is the preceding part of the token and `f64` is the suffix of
1270 /// the token. This token will always be inferred to be an `f64` in the
1272 /// Literals created from negative numbers might not survive rountrips through
1273 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1277 /// This function requires that the specified float is finite, for
1278 /// example if it is infinity or NaN this function will panic.
1279 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1280 pub fn f64_suffixed(n: f64) -> Literal {
1282 panic!("Invalid float literal {n}");
1284 Literal(bridge::client::Literal::f64(&n.to_string()))
1288 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1289 pub fn string(string: &str) -> Literal {
1290 Literal(bridge::client::Literal::string(string))
1293 /// Character literal.
1294 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1295 pub fn character(ch: char) -> Literal {
1296 Literal(bridge::client::Literal::character(ch))
1299 /// Byte string literal.
1300 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1301 pub fn byte_string(bytes: &[u8]) -> Literal {
1302 Literal(bridge::client::Literal::byte_string(bytes))
1305 /// Returns the span encompassing this literal.
1306 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1307 pub fn span(&self) -> Span {
1311 /// Configures the span associated for this literal.
1312 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1313 pub fn set_span(&mut self, span: Span) {
1314 self.0.set_span(span.0);
1317 /// Returns a `Span` that is a subset of `self.span()` containing only the
1318 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1319 /// span is outside the bounds of `self`.
1320 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1321 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1322 // occur elsewhere when the source text is printed.
1323 // FIXME(SergioBenitez): there is no way for the user to know what
1324 // `self.span()` actually maps to, so this method can currently only be
1325 // called blindly. For example, `to_string()` for the character 'c' returns
1326 // "'\u{63}'"; there is no way for the user to know whether the source text
1327 // was 'c' or whether it was '\u{63}'.
1328 #[unstable(feature = "proc_macro_span", issue = "54725")]
1329 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1330 self.0.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span)
1334 /// Parse a single literal from its stringified representation.
1336 /// In order to parse successfully, the input string must not contain anything
1337 /// but the literal token. Specifically, it must not contain whitespace or
1338 /// comments in addition to the literal.
1340 /// The resulting literal token will have a `Span::call_site()` span.
1342 /// NOTE: some errors may cause panics instead of returning `LexError`. We
1343 /// reserve the right to change these errors into `LexError`s later.
1344 #[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1345 impl FromStr for Literal {
1346 type Err = LexError;
1348 fn from_str(src: &str) -> Result<Self, LexError> {
1349 match bridge::client::Literal::from_str(src) {
1350 Ok(literal) => Ok(Literal(literal)),
1351 Err(()) => Err(LexError),
1356 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1357 // based on it (the reverse of the usual relationship between the two).
1358 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1359 impl ToString for Literal {
1360 fn to_string(&self) -> String {
1365 /// Prints the literal as a string that should be losslessly convertible
1366 /// back into the same literal (except for possible rounding for floating point literals).
1367 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1368 impl fmt::Display for Literal {
1369 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1370 f.write_str(&self.to_string())
1374 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1375 impl fmt::Debug for Literal {
1376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1381 /// Tracked access to environment variables.
1382 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1383 pub mod tracked_env {
1384 use std::env::{self, VarError};
1385 use std::ffi::OsStr;
1387 /// Retrieve an environment variable and add it to build dependency info.
1388 /// Build system executing the compiler will know that the variable was accessed during
1389 /// compilation, and will be able to rerun the build when the value of that variable changes.
1390 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1391 /// standard library, except that the argument must be UTF-8.
1392 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1393 pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1394 let key: &str = key.as_ref();
1395 let value = env::var(key);
1396 crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());
1401 /// Tracked access to additional files.
1402 #[unstable(feature = "track_path", issue = "73921")]
1403 pub mod tracked_path {
1405 /// Track a file explicitly.
1407 /// Commonly used for tracking asset preprocessing.
1408 #[unstable(feature = "track_path", issue = "73921")]
1409 pub fn path<P: AsRef<str>>(path: P) {
1410 let path: &str = path.as_ref();
1411 crate::bridge::client::FreeFunctions::track_path(path);