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(local_key_cell_methods)]
28 #![feature(maybe_uninit_write_slice)]
29 #![feature(negative_impls)]
30 #![feature(new_uninit)]
31 #![feature(restricted_std)]
32 #![feature(rustc_attrs)]
33 #![feature(min_specialization)]
34 #![feature(strict_provenance)]
35 #![recursion_limit = "256"]
37 #[unstable(feature = "proc_macro_internals", issue = "27812")]
43 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
44 pub use diagnostic::{Diagnostic, Level, MultiSpan};
46 use std::cmp::Ordering;
47 use std::ops::RangeBounds;
48 use std::path::PathBuf;
49 use std::str::FromStr;
50 use std::{error, fmt, iter};
52 /// Determines whether proc_macro has been made accessible to the currently
55 /// The proc_macro crate is only intended for use inside the implementation of
56 /// procedural macros. All the functions in this crate panic if invoked from
57 /// outside of a procedural macro, such as from a build script or unit test or
58 /// ordinary Rust binary.
60 /// With consideration for Rust libraries that are designed to support both
61 /// macro and non-macro use cases, `proc_macro::is_available()` provides a
62 /// non-panicking way to detect whether the infrastructure required to use the
63 /// API of proc_macro is presently available. Returns true if invoked from
64 /// inside of a procedural macro, false if invoked from any other binary.
65 #[stable(feature = "proc_macro_is_available", since = "1.57.0")]
66 pub fn is_available() -> bool {
67 bridge::client::is_available()
70 /// The main type provided by this crate, representing an abstract stream of
71 /// tokens, or, more specifically, a sequence of token trees.
72 /// The type provide interfaces for iterating over those token trees and, conversely,
73 /// collecting a number of token trees into one stream.
75 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
76 /// and `#[proc_macro_derive]` definitions.
77 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
79 pub struct TokenStream(Option<bridge::client::TokenStream>);
81 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
82 impl !Send for TokenStream {}
83 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
84 impl !Sync for TokenStream {}
86 /// Error returned from `TokenStream::from_str`.
87 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
92 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
93 impl fmt::Display for LexError {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 f.write_str("cannot parse string into token stream")
99 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
100 impl error::Error for LexError {}
102 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
103 impl !Send for LexError {}
104 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
105 impl !Sync for LexError {}
107 /// Error returned from `TokenStream::expand_expr`.
108 #[unstable(feature = "proc_macro_expand", issue = "90765")]
111 pub struct ExpandError;
113 #[unstable(feature = "proc_macro_expand", issue = "90765")]
114 impl fmt::Display for ExpandError {
115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 f.write_str("macro expansion failed")
120 #[unstable(feature = "proc_macro_expand", issue = "90765")]
121 impl error::Error for ExpandError {}
123 #[unstable(feature = "proc_macro_expand", issue = "90765")]
124 impl !Send for ExpandError {}
126 #[unstable(feature = "proc_macro_expand", issue = "90765")]
127 impl !Sync for ExpandError {}
130 /// Returns an empty `TokenStream` containing no token trees.
131 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
132 pub fn new() -> TokenStream {
136 /// Checks if this `TokenStream` is empty.
137 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
138 pub fn is_empty(&self) -> bool {
139 self.0.as_ref().map(|h| h.is_empty()).unwrap_or(true)
142 /// Parses this `TokenStream` as an expression and attempts to expand any
143 /// macros within it. Returns the expanded `TokenStream`.
145 /// Currently only expressions expanding to literals will succeed, although
146 /// this may be relaxed in the future.
148 /// NOTE: In error conditions, `expand_expr` may leave macros unexpanded,
149 /// report an error, failing compilation, and/or return an `Err(..)`. The
150 /// specific behavior for any error condition, and what conditions are
151 /// considered errors, is unspecified and may change in the future.
152 #[unstable(feature = "proc_macro_expand", issue = "90765")]
153 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
154 let stream = self.0.as_ref().ok_or(ExpandError)?;
155 match bridge::client::TokenStream::expand_expr(stream) {
156 Ok(stream) => Ok(TokenStream(Some(stream))),
157 Err(_) => Err(ExpandError),
162 /// Attempts to break the string into tokens and parse those tokens into a token stream.
163 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
164 /// or characters not existing in the language.
165 /// All tokens in the parsed stream get `Span::call_site()` spans.
167 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
168 /// change these errors into `LexError`s later.
169 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
170 impl FromStr for TokenStream {
173 fn from_str(src: &str) -> Result<TokenStream, LexError> {
174 Ok(TokenStream(Some(bridge::client::TokenStream::from_str(src))))
178 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
179 // based on it (the reverse of the usual relationship between the two).
180 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
181 impl ToString for TokenStream {
182 fn to_string(&self) -> String {
183 self.0.as_ref().map(|t| t.to_string()).unwrap_or_default()
187 /// Prints the token stream as a string that is supposed to be losslessly convertible back
188 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
189 /// with `Delimiter::None` delimiters and negative numeric literals.
190 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
191 impl fmt::Display for TokenStream {
192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193 f.write_str(&self.to_string())
197 /// Prints token in a form convenient for debugging.
198 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
199 impl fmt::Debug for TokenStream {
200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201 f.write_str("TokenStream ")?;
202 f.debug_list().entries(self.clone()).finish()
206 #[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
207 impl Default for TokenStream {
208 fn default() -> Self {
213 #[unstable(feature = "proc_macro_quote", issue = "54722")]
214 pub use quote::{quote, quote_span};
216 fn tree_to_bridge_tree(
218 ) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
220 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
221 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
222 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
223 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
227 /// Creates a token stream containing a single token tree.
228 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
229 impl From<TokenTree> for TokenStream {
230 fn from(tree: TokenTree) -> TokenStream {
231 TokenStream(Some(bridge::client::TokenStream::from_token_tree(tree_to_bridge_tree(tree))))
235 /// Non-generic helper for implementing `FromIterator<TokenTree>` and
236 /// `Extend<TokenTree>` with less monomorphization in calling crates.
237 struct ConcatTreesHelper {
240 bridge::client::TokenStream,
241 bridge::client::Span,
242 bridge::client::Symbol,
247 impl ConcatTreesHelper {
248 fn new(capacity: usize) -> Self {
249 ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
252 fn push(&mut self, tree: TokenTree) {
253 self.trees.push(tree_to_bridge_tree(tree));
256 fn build(self) -> TokenStream {
257 if self.trees.is_empty() {
260 TokenStream(Some(bridge::client::TokenStream::concat_trees(None, self.trees)))
264 fn append_to(self, stream: &mut TokenStream) {
265 if self.trees.is_empty() {
268 stream.0 = Some(bridge::client::TokenStream::concat_trees(stream.0.take(), self.trees))
272 /// Non-generic helper for implementing `FromIterator<TokenStream>` and
273 /// `Extend<TokenStream>` with less monomorphization in calling crates.
274 struct ConcatStreamsHelper {
275 streams: Vec<bridge::client::TokenStream>,
278 impl ConcatStreamsHelper {
279 fn new(capacity: usize) -> Self {
280 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
283 fn push(&mut self, stream: TokenStream) {
284 if let Some(stream) = stream.0 {
285 self.streams.push(stream);
289 fn build(mut self) -> TokenStream {
290 if self.streams.len() <= 1 {
291 TokenStream(self.streams.pop())
293 TokenStream(Some(bridge::client::TokenStream::concat_streams(None, self.streams)))
297 fn append_to(mut self, stream: &mut TokenStream) {
298 if self.streams.is_empty() {
301 let base = stream.0.take();
302 if base.is_none() && self.streams.len() == 1 {
303 stream.0 = self.streams.pop();
305 stream.0 = Some(bridge::client::TokenStream::concat_streams(base, self.streams));
310 /// Collects a number of token trees into a single stream.
311 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
312 impl iter::FromIterator<TokenTree> for TokenStream {
313 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
314 let iter = trees.into_iter();
315 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
316 iter.for_each(|tree| builder.push(tree));
321 /// A "flattening" operation on token streams, collects token trees
322 /// from multiple token streams into a single stream.
323 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
324 impl iter::FromIterator<TokenStream> for TokenStream {
325 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
326 let iter = streams.into_iter();
327 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
328 iter.for_each(|stream| builder.push(stream));
333 #[stable(feature = "token_stream_extend", since = "1.30.0")]
334 impl Extend<TokenTree> for TokenStream {
335 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
336 let iter = trees.into_iter();
337 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
338 iter.for_each(|tree| builder.push(tree));
339 builder.append_to(self);
343 #[stable(feature = "token_stream_extend", since = "1.30.0")]
344 impl Extend<TokenStream> for TokenStream {
345 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
346 let iter = streams.into_iter();
347 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
348 iter.for_each(|stream| builder.push(stream));
349 builder.append_to(self);
353 /// Public implementation details for the `TokenStream` type, such as iterators.
354 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
355 pub mod token_stream {
356 use crate::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree};
358 /// An iterator over `TokenStream`'s `TokenTree`s.
359 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
360 /// and returns whole groups as token trees.
362 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
366 bridge::client::TokenStream,
367 bridge::client::Span,
368 bridge::client::Symbol,
373 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
374 impl Iterator for IntoIter {
375 type Item = TokenTree;
377 fn next(&mut self) -> Option<TokenTree> {
378 self.0.next().map(|tree| match tree {
379 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
380 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
381 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
382 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
387 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
388 impl IntoIterator for TokenStream {
389 type Item = TokenTree;
390 type IntoIter = IntoIter;
392 fn into_iter(self) -> IntoIter {
393 IntoIter(self.0.map(|v| v.into_trees()).unwrap_or_default().into_iter())
398 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
399 /// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
400 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
402 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
403 /// To quote `$` itself, use `$$`.
404 #[unstable(feature = "proc_macro_quote", issue = "54722")]
405 #[allow_internal_unstable(proc_macro_def_site, proc_macro_internals)]
406 #[rustc_builtin_macro]
407 pub macro quote($($t:tt)*) {
408 /* compiler built-in */
411 #[unstable(feature = "proc_macro_internals", issue = "27812")]
415 /// A region of source code, along with macro expansion information.
416 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
417 #[derive(Copy, Clone)]
418 pub struct Span(bridge::client::Span);
420 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
421 impl !Send for Span {}
422 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
423 impl !Sync for Span {}
425 macro_rules! diagnostic_method {
426 ($name:ident, $level:expr) => {
427 /// Creates a new `Diagnostic` with the given `message` at the span
429 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
430 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
431 Diagnostic::spanned(self, $level, message)
437 /// A span that resolves at the macro definition site.
438 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
439 pub fn def_site() -> Span {
440 Span(bridge::client::Span::def_site())
443 /// The span of the invocation of the current procedural macro.
444 /// Identifiers created with this span will be resolved as if they were written
445 /// directly at the macro call location (call-site hygiene) and other code
446 /// at the macro call site will be able to refer to them as well.
447 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
448 pub fn call_site() -> Span {
449 Span(bridge::client::Span::call_site())
452 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
453 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
454 /// call site (everything else).
455 /// The span location is taken from the call-site.
456 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
457 pub fn mixed_site() -> Span {
458 Span(bridge::client::Span::mixed_site())
461 /// The original source file into which this span points.
462 #[unstable(feature = "proc_macro_span", issue = "54725")]
463 pub fn source_file(&self) -> SourceFile {
464 SourceFile(self.0.source_file())
467 /// The `Span` for the tokens in the previous macro expansion from which
468 /// `self` was generated from, if any.
469 #[unstable(feature = "proc_macro_span", issue = "54725")]
470 pub fn parent(&self) -> Option<Span> {
471 self.0.parent().map(Span)
474 /// The span for the origin source code that `self` was generated from. If
475 /// this `Span` wasn't generated from other macro expansions then the return
476 /// value is the same as `*self`.
477 #[unstable(feature = "proc_macro_span", issue = "54725")]
478 pub fn source(&self) -> Span {
479 Span(self.0.source())
482 /// Gets the starting line/column in the source file for this span.
483 #[unstable(feature = "proc_macro_span", issue = "54725")]
484 pub fn start(&self) -> LineColumn {
485 self.0.start().add_1_to_column()
488 /// Gets the ending line/column in the source file for this span.
489 #[unstable(feature = "proc_macro_span", issue = "54725")]
490 pub fn end(&self) -> LineColumn {
491 self.0.end().add_1_to_column()
494 /// Creates an empty span pointing to directly before this span.
495 #[unstable(feature = "proc_macro_span_shrink", issue = "87552")]
496 pub fn before(&self) -> Span {
497 Span(self.0.before())
500 /// Creates an empty span pointing to directly after this span.
501 #[unstable(feature = "proc_macro_span_shrink", issue = "87552")]
502 pub fn after(&self) -> Span {
506 /// Creates a new span encompassing `self` and `other`.
508 /// Returns `None` if `self` and `other` are from different files.
509 #[unstable(feature = "proc_macro_span", issue = "54725")]
510 pub fn join(&self, other: Span) -> Option<Span> {
511 self.0.join(other.0).map(Span)
514 /// Creates a new span with the same line/column information as `self` but
515 /// that resolves symbols as though it were at `other`.
516 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
517 pub fn resolved_at(&self, other: Span) -> Span {
518 Span(self.0.resolved_at(other.0))
521 /// Creates a new span with the same name resolution behavior as `self` but
522 /// with the line/column information of `other`.
523 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
524 pub fn located_at(&self, other: Span) -> Span {
525 other.resolved_at(*self)
528 /// Compares to spans to see if they're equal.
529 #[unstable(feature = "proc_macro_span", issue = "54725")]
530 pub fn eq(&self, other: &Span) -> bool {
534 /// Returns the source text behind a span. This preserves the original source
535 /// code, including spaces and comments. It only returns a result if the span
536 /// corresponds to real source code.
538 /// Note: The observable result of a macro should only rely on the tokens and
539 /// not on this source text. The result of this function is a best effort to
540 /// be used for diagnostics only.
541 #[unstable(feature = "proc_macro_span", issue = "54725")]
542 pub fn source_text(&self) -> Option<String> {
546 // Used by the implementation of `Span::quote`
548 #[unstable(feature = "proc_macro_internals", issue = "27812")]
549 pub fn save_span(&self) -> usize {
553 // Used by the implementation of `Span::quote`
555 #[unstable(feature = "proc_macro_internals", issue = "27812")]
556 pub fn recover_proc_macro_span(id: usize) -> Span {
557 Span(bridge::client::Span::recover_proc_macro_span(id))
560 diagnostic_method!(error, Level::Error);
561 diagnostic_method!(warning, Level::Warning);
562 diagnostic_method!(note, Level::Note);
563 diagnostic_method!(help, Level::Help);
566 /// Prints a span in a form convenient for debugging.
567 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
568 impl fmt::Debug for Span {
569 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
574 /// A line-column pair representing the start or end of a `Span`.
575 #[unstable(feature = "proc_macro_span", issue = "54725")]
576 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
577 pub struct LineColumn {
578 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
579 #[unstable(feature = "proc_macro_span", issue = "54725")]
581 /// The 1-indexed column (number of bytes in UTF-8 encoding) in the source
582 /// file on which the span starts or ends (inclusive).
583 #[unstable(feature = "proc_macro_span", issue = "54725")]
588 fn add_1_to_column(self) -> Self {
589 LineColumn { line: self.line, column: self.column + 1 }
593 #[unstable(feature = "proc_macro_span", issue = "54725")]
594 impl !Send for LineColumn {}
595 #[unstable(feature = "proc_macro_span", issue = "54725")]
596 impl !Sync for LineColumn {}
598 #[unstable(feature = "proc_macro_span", issue = "54725")]
599 impl Ord for LineColumn {
600 fn cmp(&self, other: &Self) -> Ordering {
601 self.line.cmp(&other.line).then(self.column.cmp(&other.column))
605 #[unstable(feature = "proc_macro_span", issue = "54725")]
606 impl PartialOrd for LineColumn {
607 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
608 Some(self.cmp(other))
612 /// The source file of a given `Span`.
613 #[unstable(feature = "proc_macro_span", issue = "54725")]
615 pub struct SourceFile(bridge::client::SourceFile);
618 /// Gets the path to this source file.
621 /// If the code span associated with this `SourceFile` was generated by an external macro, this
622 /// macro, this might not be an actual path on the filesystem. Use [`is_real`] to check.
624 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
625 /// the command line, the path as given might not actually be valid.
627 /// [`is_real`]: Self::is_real
628 #[unstable(feature = "proc_macro_span", issue = "54725")]
629 pub fn path(&self) -> PathBuf {
630 PathBuf::from(self.0.path())
633 /// Returns `true` if this source file is a real source file, and not generated by an external
634 /// macro's expansion.
635 #[unstable(feature = "proc_macro_span", issue = "54725")]
636 pub fn is_real(&self) -> bool {
637 // This is a hack until intercrate spans are implemented and we can have real source files
638 // for spans generated in external macros.
639 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
644 #[unstable(feature = "proc_macro_span", issue = "54725")]
645 impl fmt::Debug for SourceFile {
646 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
647 f.debug_struct("SourceFile")
648 .field("path", &self.path())
649 .field("is_real", &self.is_real())
654 #[unstable(feature = "proc_macro_span", issue = "54725")]
655 impl PartialEq for SourceFile {
656 fn eq(&self, other: &Self) -> bool {
661 #[unstable(feature = "proc_macro_span", issue = "54725")]
662 impl Eq for SourceFile {}
664 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
665 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
668 /// A token stream surrounded by bracket delimiters.
669 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
670 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
672 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
673 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
674 /// A single punctuation character (`+`, `,`, `$`, etc.).
675 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
676 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
677 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
678 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
679 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
682 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
683 impl !Send for TokenTree {}
684 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
685 impl !Sync for TokenTree {}
688 /// Returns the span of this tree, delegating to the `span` method of
689 /// the contained token or a delimited stream.
690 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
691 pub fn span(&self) -> Span {
693 TokenTree::Group(ref t) => t.span(),
694 TokenTree::Ident(ref t) => t.span(),
695 TokenTree::Punct(ref t) => t.span(),
696 TokenTree::Literal(ref t) => t.span(),
700 /// Configures the span for *only this token*.
702 /// Note that if this token is a `Group` then this method will not configure
703 /// the span of each of the internal tokens, this will simply delegate to
704 /// the `set_span` method of each variant.
705 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
706 pub fn set_span(&mut self, span: Span) {
708 TokenTree::Group(ref mut t) => t.set_span(span),
709 TokenTree::Ident(ref mut t) => t.set_span(span),
710 TokenTree::Punct(ref mut t) => t.set_span(span),
711 TokenTree::Literal(ref mut t) => t.set_span(span),
716 /// Prints token tree in a form convenient for debugging.
717 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
718 impl fmt::Debug for TokenTree {
719 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
720 // Each of these has the name in the struct type in the derived debug,
721 // so don't bother with an extra layer of indirection
723 TokenTree::Group(ref tt) => tt.fmt(f),
724 TokenTree::Ident(ref tt) => tt.fmt(f),
725 TokenTree::Punct(ref tt) => tt.fmt(f),
726 TokenTree::Literal(ref tt) => tt.fmt(f),
731 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
732 impl From<Group> for TokenTree {
733 fn from(g: Group) -> TokenTree {
738 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
739 impl From<Ident> for TokenTree {
740 fn from(g: Ident) -> TokenTree {
745 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
746 impl From<Punct> for TokenTree {
747 fn from(g: Punct) -> TokenTree {
752 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
753 impl From<Literal> for TokenTree {
754 fn from(g: Literal) -> TokenTree {
755 TokenTree::Literal(g)
759 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
760 // based on it (the reverse of the usual relationship between the two).
761 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
762 impl ToString for TokenTree {
763 fn to_string(&self) -> String {
765 TokenTree::Group(ref t) => t.to_string(),
766 TokenTree::Ident(ref t) => t.to_string(),
767 TokenTree::Punct(ref t) => t.to_string(),
768 TokenTree::Literal(ref t) => t.to_string(),
773 /// Prints the token tree as a string that is supposed to be losslessly convertible back
774 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
775 /// with `Delimiter::None` delimiters and negative numeric literals.
776 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
777 impl fmt::Display for TokenTree {
778 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
779 f.write_str(&self.to_string())
783 /// A delimited token stream.
785 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
787 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
788 pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
790 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
791 impl !Send for Group {}
792 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
793 impl !Sync for Group {}
795 /// Describes how a sequence of token trees is delimited.
796 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
797 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
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 /// An invisible delimiter, that may, for example, appear around tokens coming from a
810 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
811 /// `$var * 3` where `$var` is `1 + 2`.
812 /// Invisible delimiters might not survive roundtrip of a token stream through a string.
813 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
818 /// Creates a new `Group` with the given delimiter and token stream.
820 /// This constructor will set the span for this group to
821 /// `Span::call_site()`. To change the span you can use the `set_span`
823 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
824 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
825 Group(bridge::Group {
828 span: bridge::DelimSpan::from_single(Span::call_site().0),
832 /// Returns the delimiter of this `Group`
833 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
834 pub fn delimiter(&self) -> Delimiter {
838 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
840 /// Note that the returned token stream does not include the delimiter
842 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
843 pub fn stream(&self) -> TokenStream {
844 TokenStream(self.0.stream.clone())
847 /// Returns the span for the delimiters of this token stream, spanning the
851 /// pub fn span(&self) -> Span {
854 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
855 pub fn span(&self) -> Span {
856 Span(self.0.span.entire)
859 /// Returns the span pointing to the opening delimiter of this group.
862 /// pub fn span_open(&self) -> Span {
865 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
866 pub fn span_open(&self) -> Span {
867 Span(self.0.span.open)
870 /// Returns the span pointing to the closing delimiter of this group.
873 /// pub fn span_close(&self) -> Span {
876 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
877 pub fn span_close(&self) -> Span {
878 Span(self.0.span.close)
881 /// Configures the span for this `Group`'s delimiters, but not its internal
884 /// This method will **not** set the span of all the internal tokens spanned
885 /// by this group, but rather it will only set the span of the delimiter
886 /// tokens at the level of the `Group`.
887 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
888 pub fn set_span(&mut self, span: Span) {
889 self.0.span = bridge::DelimSpan::from_single(span.0);
893 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
894 // based on it (the reverse of the usual relationship between the two).
895 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
896 impl ToString for Group {
897 fn to_string(&self) -> String {
898 TokenStream::from(TokenTree::from(self.clone())).to_string()
902 /// Prints the group as a string that should be losslessly convertible back
903 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
904 /// with `Delimiter::None` delimiters.
905 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
906 impl fmt::Display for Group {
907 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
908 f.write_str(&self.to_string())
912 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
913 impl fmt::Debug for Group {
914 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
915 f.debug_struct("Group")
916 .field("delimiter", &self.delimiter())
917 .field("stream", &self.stream())
918 .field("span", &self.span())
923 /// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
925 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
926 /// forms of `Spacing` returned.
927 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
929 pub struct Punct(bridge::Punct<bridge::client::Span>);
931 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
932 impl !Send for Punct {}
933 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
934 impl !Sync for Punct {}
936 /// Describes whether a `Punct` is followed immediately by another `Punct` ([`Spacing::Joint`]) or
937 /// by a different token or whitespace ([`Spacing::Alone`]).
938 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
939 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
941 /// A `Punct` is not immediately followed by another `Punct`.
942 /// E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`.
943 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
945 /// A `Punct` is immediately followed by another `Punct`.
946 /// E.g. `+` is `Joint` in `+=` and `++`.
948 /// Additionally, single quote `'` can join with identifiers to form lifetimes: `'ident`.
949 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
954 /// Creates a new `Punct` from the given character and spacing.
955 /// The `ch` argument must be a valid punctuation character permitted by the language,
956 /// otherwise the function will panic.
958 /// The returned `Punct` will have the default span of `Span::call_site()`
959 /// which can be further configured with the `set_span` method below.
960 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
961 pub fn new(ch: char, spacing: Spacing) -> Punct {
962 const LEGAL_CHARS: &[char] = &[
963 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
964 ':', '#', '$', '?', '\'',
966 if !LEGAL_CHARS.contains(&ch) {
967 panic!("unsupported character `{:?}`", ch);
969 Punct(bridge::Punct {
971 joint: spacing == Spacing::Joint,
972 span: Span::call_site().0,
976 /// Returns the value of this punctuation character as `char`.
977 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
978 pub fn as_char(&self) -> char {
982 /// Returns the spacing of this punctuation character, indicating whether it's immediately
983 /// followed by another `Punct` in the token stream, so they can potentially be combined into
984 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
985 /// (`Alone`) so the operator has certainly ended.
986 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
987 pub fn spacing(&self) -> Spacing {
988 if self.0.joint { Spacing::Joint } else { Spacing::Alone }
991 /// Returns the span for this punctuation character.
992 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
993 pub fn span(&self) -> Span {
997 /// Configure the span for this punctuation character.
998 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
999 pub fn set_span(&mut self, span: Span) {
1000 self.0.span = span.0;
1004 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1005 impl ToString for Punct {
1006 fn to_string(&self) -> String {
1007 self.as_char().to_string()
1011 /// Prints the punctuation character as a string that should be losslessly convertible
1012 /// back into the same character.
1013 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1014 impl fmt::Display for Punct {
1015 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1016 write!(f, "{}", self.as_char())
1020 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1021 impl fmt::Debug for Punct {
1022 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1023 f.debug_struct("Punct")
1024 .field("ch", &self.as_char())
1025 .field("spacing", &self.spacing())
1026 .field("span", &self.span())
1031 #[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1032 impl PartialEq<char> for Punct {
1033 fn eq(&self, rhs: &char) -> bool {
1034 self.as_char() == *rhs
1038 #[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1039 impl PartialEq<Punct> for char {
1040 fn eq(&self, rhs: &Punct) -> bool {
1041 *self == rhs.as_char()
1045 /// An identifier (`ident`).
1047 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1048 pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1051 /// Creates a new `Ident` with the given `string` as well as the specified
1053 /// The `string` argument must be a valid identifier permitted by the
1054 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
1056 /// Note that `span`, currently in rustc, configures the hygiene information
1057 /// for this identifier.
1059 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
1060 /// meaning that identifiers created with this span will be resolved as if they were written
1061 /// directly at the location of the macro call, and other code at the macro call site will be
1062 /// able to refer to them as well.
1064 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
1065 /// meaning that identifiers created with this span will be resolved at the location of the
1066 /// macro definition and other code at the macro call site will not be able to refer to them.
1068 /// Due to the current importance of hygiene this constructor, unlike other
1069 /// tokens, requires a `Span` to be specified at construction.
1070 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1071 pub fn new(string: &str, span: Span) -> Ident {
1072 Ident(bridge::Ident {
1073 sym: bridge::client::Symbol::new_ident(string, false),
1079 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
1080 /// The `string` argument be a valid identifier permitted by the language
1081 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
1082 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
1083 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1084 pub fn new_raw(string: &str, span: Span) -> Ident {
1085 Ident(bridge::Ident {
1086 sym: bridge::client::Symbol::new_ident(string, true),
1092 /// Returns the span of this `Ident`, encompassing the entire string returned
1093 /// by [`to_string`](ToString::to_string).
1094 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1095 pub fn span(&self) -> Span {
1099 /// Configures the span of this `Ident`, possibly changing its hygiene context.
1100 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1101 pub fn set_span(&mut self, span: Span) {
1102 self.0.span = span.0;
1106 /// Converts the identifier to a string that should be losslessly convertible
1107 /// back into the same identifier.
1108 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1109 impl ToString for Ident {
1110 fn to_string(&self) -> String {
1111 self.0.sym.with(|sym| if self.0.is_raw { ["r#", sym].concat() } else { sym.to_owned() })
1115 /// Prints the identifier as a string that should be losslessly convertible back
1116 /// into the same identifier.
1117 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1118 impl fmt::Display for Ident {
1119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1123 fmt::Display::fmt(&self.0.sym, f)
1127 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1128 impl fmt::Debug for Ident {
1129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1130 f.debug_struct("Ident")
1131 .field("ident", &self.to_string())
1132 .field("span", &self.span())
1137 /// A literal string (`"hello"`), byte string (`b"hello"`),
1138 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
1139 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1140 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
1142 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1143 pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1145 macro_rules! suffixed_int_literals {
1146 ($($name:ident => $kind:ident,)*) => ($(
1147 /// Creates a new suffixed integer literal with the specified value.
1149 /// This function will create an integer like `1u32` where the integer
1150 /// value specified is the first part of the token and the integral is
1151 /// also suffixed at the end.
1152 /// Literals created from negative numbers might not survive round-trips through
1153 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1155 /// Literals created through this method have the `Span::call_site()`
1156 /// span by default, which can be configured with the `set_span` method
1158 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1159 pub fn $name(n: $kind) -> Literal {
1160 Literal(bridge::Literal {
1161 kind: bridge::LitKind::Integer,
1162 symbol: bridge::client::Symbol::new(&n.to_string()),
1163 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1164 span: Span::call_site().0,
1170 macro_rules! unsuffixed_int_literals {
1171 ($($name:ident => $kind:ident,)*) => ($(
1172 /// Creates a new unsuffixed integer literal with the specified value.
1174 /// This function will create an integer like `1` where the integer
1175 /// value specified is the first part of the token. No suffix is
1176 /// specified on this token, meaning that invocations like
1177 /// `Literal::i8_unsuffixed(1)` are equivalent to
1178 /// `Literal::u32_unsuffixed(1)`.
1179 /// Literals created from negative numbers might not survive rountrips through
1180 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1182 /// Literals created through this method have the `Span::call_site()`
1183 /// span by default, which can be configured with the `set_span` method
1185 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1186 pub fn $name(n: $kind) -> Literal {
1187 Literal(bridge::Literal {
1188 kind: bridge::LitKind::Integer,
1189 symbol: bridge::client::Symbol::new(&n.to_string()),
1191 span: Span::call_site().0,
1198 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1199 Literal(bridge::Literal {
1201 symbol: bridge::client::Symbol::new(value),
1202 suffix: suffix.map(bridge::client::Symbol::new),
1203 span: Span::call_site().0,
1207 suffixed_int_literals! {
1209 u16_suffixed => u16,
1210 u32_suffixed => u32,
1211 u64_suffixed => u64,
1212 u128_suffixed => u128,
1213 usize_suffixed => usize,
1215 i16_suffixed => i16,
1216 i32_suffixed => i32,
1217 i64_suffixed => i64,
1218 i128_suffixed => i128,
1219 isize_suffixed => isize,
1222 unsuffixed_int_literals! {
1223 u8_unsuffixed => u8,
1224 u16_unsuffixed => u16,
1225 u32_unsuffixed => u32,
1226 u64_unsuffixed => u64,
1227 u128_unsuffixed => u128,
1228 usize_unsuffixed => usize,
1229 i8_unsuffixed => i8,
1230 i16_unsuffixed => i16,
1231 i32_unsuffixed => i32,
1232 i64_unsuffixed => i64,
1233 i128_unsuffixed => i128,
1234 isize_unsuffixed => isize,
1237 /// Creates a new unsuffixed floating-point literal.
1239 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1240 /// the float's value is emitted directly into the token but no suffix is
1241 /// used, so it may be inferred to be a `f64` later in the compiler.
1242 /// Literals created from negative numbers might not survive rountrips through
1243 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1247 /// This function requires that the specified float is finite, for
1248 /// example if it is infinity or NaN this function will panic.
1249 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1250 pub fn f32_unsuffixed(n: f32) -> Literal {
1252 panic!("Invalid float literal {n}");
1254 let mut repr = n.to_string();
1255 if !repr.contains('.') {
1256 repr.push_str(".0");
1258 Literal::new(bridge::LitKind::Float, &repr, None)
1261 /// Creates a new suffixed floating-point literal.
1263 /// This constructor will create a literal like `1.0f32` where the value
1264 /// specified is the preceding part of the token and `f32` is the suffix of
1265 /// the token. This token will always be inferred to be an `f32` in the
1267 /// Literals created from negative numbers might not survive rountrips through
1268 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1272 /// This function requires that the specified float is finite, for
1273 /// example if it is infinity or NaN this function will panic.
1274 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1275 pub fn f32_suffixed(n: f32) -> Literal {
1277 panic!("Invalid float literal {n}");
1279 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1282 /// Creates a new unsuffixed floating-point literal.
1284 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1285 /// the float's value is emitted directly into the token but no suffix is
1286 /// used, so it may be inferred to be a `f64` later in the compiler.
1287 /// Literals created from negative numbers might not survive rountrips through
1288 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1292 /// This function requires that the specified float is finite, for
1293 /// example if it is infinity or NaN this function will panic.
1294 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1295 pub fn f64_unsuffixed(n: f64) -> Literal {
1297 panic!("Invalid float literal {n}");
1299 let mut repr = n.to_string();
1300 if !repr.contains('.') {
1301 repr.push_str(".0");
1303 Literal::new(bridge::LitKind::Float, &repr, None)
1306 /// Creates a new suffixed floating-point literal.
1308 /// This constructor will create a literal like `1.0f64` where the value
1309 /// specified is the preceding part of the token and `f64` is the suffix of
1310 /// the token. This token will always be inferred to be an `f64` in the
1312 /// Literals created from negative numbers might not survive rountrips through
1313 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1317 /// This function requires that the specified float is finite, for
1318 /// example if it is infinity or NaN this function will panic.
1319 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1320 pub fn f64_suffixed(n: f64) -> Literal {
1322 panic!("Invalid float literal {n}");
1324 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1328 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1329 pub fn string(string: &str) -> Literal {
1330 let quoted = format!("{:?}", string);
1331 assert!(quoted.starts_with('"') && quoted.ends_with('"'));
1332 let symbol = "ed[1..quoted.len() - 1];
1333 Literal::new(bridge::LitKind::Str, symbol, None)
1336 /// Character literal.
1337 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1338 pub fn character(ch: char) -> Literal {
1339 let quoted = format!("{:?}", ch);
1340 assert!(quoted.starts_with('\'') && quoted.ends_with('\''));
1341 let symbol = "ed[1..quoted.len() - 1];
1342 Literal::new(bridge::LitKind::Char, symbol, None)
1345 /// Byte string literal.
1346 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1347 pub fn byte_string(bytes: &[u8]) -> Literal {
1351 .flat_map(std::ascii::escape_default)
1352 .map(Into::<char>::into)
1353 .collect::<String>();
1354 Literal::new(bridge::LitKind::ByteStr, &string, None)
1357 /// Returns the span encompassing this literal.
1358 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1359 pub fn span(&self) -> Span {
1363 /// Configures the span associated for this literal.
1364 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1365 pub fn set_span(&mut self, span: Span) {
1366 self.0.span = span.0;
1369 /// Returns a `Span` that is a subset of `self.span()` containing only the
1370 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1371 /// span is outside the bounds of `self`.
1372 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1373 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1374 // occur elsewhere when the source text is printed.
1375 // FIXME(SergioBenitez): there is no way for the user to know what
1376 // `self.span()` actually maps to, so this method can currently only be
1377 // called blindly. For example, `to_string()` for the character 'c' returns
1378 // "'\u{63}'"; there is no way for the user to know whether the source text
1379 // was 'c' or whether it was '\u{63}'.
1380 #[unstable(feature = "proc_macro_span", issue = "54725")]
1381 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1382 self.0.span.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span)
1385 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1386 self.0.symbol.with(|symbol| match self.0.suffix {
1387 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1388 None => f(symbol, ""),
1392 /// Invokes the callback with a `&[&str]` consisting of each part of the
1393 /// literal's representation. This is done to allow the `ToString` and
1394 /// `Display` implementations to borrow references to symbol values, and
1395 /// both be optimized to reduce overhead.
1396 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1397 /// Returns a string containing exactly `num` '#' characters.
1398 /// Uses a 256-character source string literal which is always safe to
1399 /// index with a `u8` index.
1400 fn get_hashes_str(num: u8) -> &'static str {
1401 const HASHES: &str = "\
1402 ################################################################\
1403 ################################################################\
1404 ################################################################\
1405 ################################################################\
1407 const _: () = assert!(HASHES.len() == 256);
1408 &HASHES[..num as usize]
1411 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1412 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1413 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1414 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1415 bridge::LitKind::StrRaw(n) => {
1416 let hashes = get_hashes_str(n);
1417 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1419 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1420 bridge::LitKind::ByteStrRaw(n) => {
1421 let hashes = get_hashes_str(n);
1422 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1424 _ => f(&[symbol, suffix]),
1429 /// Parse a single literal from its stringified representation.
1431 /// In order to parse successfully, the input string must not contain anything
1432 /// but the literal token. Specifically, it must not contain whitespace or
1433 /// comments in addition to the literal.
1435 /// The resulting literal token will have a `Span::call_site()` span.
1437 /// NOTE: some errors may cause panics instead of returning `LexError`. We
1438 /// reserve the right to change these errors into `LexError`s later.
1439 #[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1440 impl FromStr for Literal {
1441 type Err = LexError;
1443 fn from_str(src: &str) -> Result<Self, LexError> {
1444 match bridge::client::FreeFunctions::literal_from_str(src) {
1445 Ok(literal) => Ok(Literal(literal)),
1446 Err(()) => Err(LexError),
1451 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1452 impl ToString for Literal {
1453 fn to_string(&self) -> String {
1454 self.with_stringify_parts(|parts| parts.concat())
1458 /// Prints the literal as a string that should be losslessly convertible
1459 /// back into the same literal (except for possible rounding for floating point literals).
1460 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1461 impl fmt::Display for Literal {
1462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1463 self.with_stringify_parts(|parts| {
1465 fmt::Display::fmt(part, f)?;
1472 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1473 impl fmt::Debug for Literal {
1474 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1475 f.debug_struct("Literal")
1476 // format the kind on one line even in {:#?} mode
1477 .field("kind", &format_args!("{:?}", &self.0.kind))
1478 .field("symbol", &self.0.symbol)
1479 // format `Some("...")` on one line even in {:#?} mode
1480 .field("suffix", &format_args!("{:?}", &self.0.suffix))
1481 .field("span", &self.0.span)
1486 /// Tracked access to environment variables.
1487 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1488 pub mod tracked_env {
1489 use std::env::{self, VarError};
1490 use std::ffi::OsStr;
1492 /// Retrieve an environment variable and add it to build dependency info.
1493 /// Build system executing the compiler will know that the variable was accessed during
1494 /// compilation, and will be able to rerun the build when the value of that variable changes.
1495 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1496 /// standard library, except that the argument must be UTF-8.
1497 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1498 pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1499 let key: &str = key.as_ref();
1500 let value = env::var(key);
1501 crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());
1506 /// Tracked access to additional files.
1507 #[unstable(feature = "track_path", issue = "99515")]
1508 pub mod tracked_path {
1510 /// Track a file explicitly.
1512 /// Commonly used for tracking asset preprocessing.
1513 #[unstable(feature = "track_path", issue = "99515")]
1514 pub fn path<P: AsRef<str>>(path: P) {
1515 let path: &str = path.as_ref();
1516 crate::bridge::client::FreeFunctions::track_path(path);