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)),
386 fn size_hint(&self) -> (usize, Option<usize>) {
390 fn count(self) -> usize {
395 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
396 impl IntoIterator for TokenStream {
397 type Item = TokenTree;
398 type IntoIter = IntoIter;
400 fn into_iter(self) -> IntoIter {
401 IntoIter(self.0.map(|v| v.into_trees()).unwrap_or_default().into_iter())
406 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
407 /// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
408 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
410 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
411 /// To quote `$` itself, use `$$`.
412 #[unstable(feature = "proc_macro_quote", issue = "54722")]
413 #[allow_internal_unstable(proc_macro_def_site, proc_macro_internals)]
414 #[rustc_builtin_macro]
415 pub macro quote($($t:tt)*) {
416 /* compiler built-in */
419 #[unstable(feature = "proc_macro_internals", issue = "27812")]
423 /// A region of source code, along with macro expansion information.
424 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
425 #[derive(Copy, Clone)]
426 pub struct Span(bridge::client::Span);
428 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
429 impl !Send for Span {}
430 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
431 impl !Sync for Span {}
433 macro_rules! diagnostic_method {
434 ($name:ident, $level:expr) => {
435 /// Creates a new `Diagnostic` with the given `message` at the span
437 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
438 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
439 Diagnostic::spanned(self, $level, message)
445 /// A span that resolves at the macro definition site.
446 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
447 pub fn def_site() -> Span {
448 Span(bridge::client::Span::def_site())
451 /// The span of the invocation of the current procedural macro.
452 /// Identifiers created with this span will be resolved as if they were written
453 /// directly at the macro call location (call-site hygiene) and other code
454 /// at the macro call site will be able to refer to them as well.
455 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
456 pub fn call_site() -> Span {
457 Span(bridge::client::Span::call_site())
460 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
461 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
462 /// call site (everything else).
463 /// The span location is taken from the call-site.
464 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
465 pub fn mixed_site() -> Span {
466 Span(bridge::client::Span::mixed_site())
469 /// The original source file into which this span points.
470 #[unstable(feature = "proc_macro_span", issue = "54725")]
471 pub fn source_file(&self) -> SourceFile {
472 SourceFile(self.0.source_file())
475 /// The `Span` for the tokens in the previous macro expansion from which
476 /// `self` was generated from, if any.
477 #[unstable(feature = "proc_macro_span", issue = "54725")]
478 pub fn parent(&self) -> Option<Span> {
479 self.0.parent().map(Span)
482 /// The span for the origin source code that `self` was generated from. If
483 /// this `Span` wasn't generated from other macro expansions then the return
484 /// value is the same as `*self`.
485 #[unstable(feature = "proc_macro_span", issue = "54725")]
486 pub fn source(&self) -> Span {
487 Span(self.0.source())
490 /// Gets the starting line/column in the source file for this span.
491 #[unstable(feature = "proc_macro_span", issue = "54725")]
492 pub fn start(&self) -> LineColumn {
493 self.0.start().add_1_to_column()
496 /// Gets the ending line/column in the source file for this span.
497 #[unstable(feature = "proc_macro_span", issue = "54725")]
498 pub fn end(&self) -> LineColumn {
499 self.0.end().add_1_to_column()
502 /// Creates an empty span pointing to directly before this span.
503 #[unstable(feature = "proc_macro_span_shrink", issue = "87552")]
504 pub fn before(&self) -> Span {
505 Span(self.0.before())
508 /// Creates an empty span pointing to directly after this span.
509 #[unstable(feature = "proc_macro_span_shrink", issue = "87552")]
510 pub fn after(&self) -> Span {
514 /// Creates a new span encompassing `self` and `other`.
516 /// Returns `None` if `self` and `other` are from different files.
517 #[unstable(feature = "proc_macro_span", issue = "54725")]
518 pub fn join(&self, other: Span) -> Option<Span> {
519 self.0.join(other.0).map(Span)
522 /// Creates a new span with the same line/column information as `self` but
523 /// that resolves symbols as though it were at `other`.
524 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
525 pub fn resolved_at(&self, other: Span) -> Span {
526 Span(self.0.resolved_at(other.0))
529 /// Creates a new span with the same name resolution behavior as `self` but
530 /// with the line/column information of `other`.
531 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
532 pub fn located_at(&self, other: Span) -> Span {
533 other.resolved_at(*self)
536 /// Compares to spans to see if they're equal.
537 #[unstable(feature = "proc_macro_span", issue = "54725")]
538 pub fn eq(&self, other: &Span) -> bool {
542 /// Returns the source text behind a span. This preserves the original source
543 /// code, including spaces and comments. It only returns a result if the span
544 /// corresponds to real source code.
546 /// Note: The observable result of a macro should only rely on the tokens and
547 /// not on this source text. The result of this function is a best effort to
548 /// be used for diagnostics only.
549 #[unstable(feature = "proc_macro_span", issue = "54725")]
550 pub fn source_text(&self) -> Option<String> {
554 // Used by the implementation of `Span::quote`
556 #[unstable(feature = "proc_macro_internals", issue = "27812")]
557 pub fn save_span(&self) -> usize {
561 // Used by the implementation of `Span::quote`
563 #[unstable(feature = "proc_macro_internals", issue = "27812")]
564 pub fn recover_proc_macro_span(id: usize) -> Span {
565 Span(bridge::client::Span::recover_proc_macro_span(id))
568 diagnostic_method!(error, Level::Error);
569 diagnostic_method!(warning, Level::Warning);
570 diagnostic_method!(note, Level::Note);
571 diagnostic_method!(help, Level::Help);
574 /// Prints a span in a form convenient for debugging.
575 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
576 impl fmt::Debug for Span {
577 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
582 /// A line-column pair representing the start or end of a `Span`.
583 #[unstable(feature = "proc_macro_span", issue = "54725")]
584 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
585 pub struct LineColumn {
586 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
587 #[unstable(feature = "proc_macro_span", issue = "54725")]
589 /// The 1-indexed column (number of bytes in UTF-8 encoding) in the source
590 /// file on which the span starts or ends (inclusive).
591 #[unstable(feature = "proc_macro_span", issue = "54725")]
596 fn add_1_to_column(self) -> Self {
597 LineColumn { line: self.line, column: self.column + 1 }
601 #[unstable(feature = "proc_macro_span", issue = "54725")]
602 impl !Send for LineColumn {}
603 #[unstable(feature = "proc_macro_span", issue = "54725")]
604 impl !Sync for LineColumn {}
606 #[unstable(feature = "proc_macro_span", issue = "54725")]
607 impl Ord for LineColumn {
608 fn cmp(&self, other: &Self) -> Ordering {
609 self.line.cmp(&other.line).then(self.column.cmp(&other.column))
613 #[unstable(feature = "proc_macro_span", issue = "54725")]
614 impl PartialOrd for LineColumn {
615 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
616 Some(self.cmp(other))
620 /// The source file of a given `Span`.
621 #[unstable(feature = "proc_macro_span", issue = "54725")]
623 pub struct SourceFile(bridge::client::SourceFile);
626 /// Gets the path to this source file.
629 /// If the code span associated with this `SourceFile` was generated by an external macro, this
630 /// macro, this might not be an actual path on the filesystem. Use [`is_real`] to check.
632 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
633 /// the command line, the path as given might not actually be valid.
635 /// [`is_real`]: Self::is_real
636 #[unstable(feature = "proc_macro_span", issue = "54725")]
637 pub fn path(&self) -> PathBuf {
638 PathBuf::from(self.0.path())
641 /// Returns `true` if this source file is a real source file, and not generated by an external
642 /// macro's expansion.
643 #[unstable(feature = "proc_macro_span", issue = "54725")]
644 pub fn is_real(&self) -> bool {
645 // This is a hack until intercrate spans are implemented and we can have real source files
646 // for spans generated in external macros.
647 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
652 #[unstable(feature = "proc_macro_span", issue = "54725")]
653 impl fmt::Debug for SourceFile {
654 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655 f.debug_struct("SourceFile")
656 .field("path", &self.path())
657 .field("is_real", &self.is_real())
662 #[unstable(feature = "proc_macro_span", issue = "54725")]
663 impl PartialEq for SourceFile {
664 fn eq(&self, other: &Self) -> bool {
669 #[unstable(feature = "proc_macro_span", issue = "54725")]
670 impl Eq for SourceFile {}
672 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
673 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
676 /// A token stream surrounded by bracket delimiters.
677 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
678 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
680 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
681 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
682 /// A single punctuation character (`+`, `,`, `$`, etc.).
683 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
684 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
685 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
686 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
687 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
690 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
691 impl !Send for TokenTree {}
692 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
693 impl !Sync for TokenTree {}
696 /// Returns the span of this tree, delegating to the `span` method of
697 /// the contained token or a delimited stream.
698 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
699 pub fn span(&self) -> Span {
701 TokenTree::Group(ref t) => t.span(),
702 TokenTree::Ident(ref t) => t.span(),
703 TokenTree::Punct(ref t) => t.span(),
704 TokenTree::Literal(ref t) => t.span(),
708 /// Configures the span for *only this token*.
710 /// Note that if this token is a `Group` then this method will not configure
711 /// the span of each of the internal tokens, this will simply delegate to
712 /// the `set_span` method of each variant.
713 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
714 pub fn set_span(&mut self, span: Span) {
716 TokenTree::Group(ref mut t) => t.set_span(span),
717 TokenTree::Ident(ref mut t) => t.set_span(span),
718 TokenTree::Punct(ref mut t) => t.set_span(span),
719 TokenTree::Literal(ref mut t) => t.set_span(span),
724 /// Prints token tree in a form convenient for debugging.
725 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
726 impl fmt::Debug for TokenTree {
727 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
728 // Each of these has the name in the struct type in the derived debug,
729 // so don't bother with an extra layer of indirection
731 TokenTree::Group(ref tt) => tt.fmt(f),
732 TokenTree::Ident(ref tt) => tt.fmt(f),
733 TokenTree::Punct(ref tt) => tt.fmt(f),
734 TokenTree::Literal(ref tt) => tt.fmt(f),
739 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
740 impl From<Group> for TokenTree {
741 fn from(g: Group) -> TokenTree {
746 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
747 impl From<Ident> for TokenTree {
748 fn from(g: Ident) -> TokenTree {
753 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
754 impl From<Punct> for TokenTree {
755 fn from(g: Punct) -> TokenTree {
760 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
761 impl From<Literal> for TokenTree {
762 fn from(g: Literal) -> TokenTree {
763 TokenTree::Literal(g)
767 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
768 // based on it (the reverse of the usual relationship between the two).
769 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
770 impl ToString for TokenTree {
771 fn to_string(&self) -> String {
773 TokenTree::Group(ref t) => t.to_string(),
774 TokenTree::Ident(ref t) => t.to_string(),
775 TokenTree::Punct(ref t) => t.to_string(),
776 TokenTree::Literal(ref t) => t.to_string(),
781 /// Prints the token tree as a string that is supposed to be losslessly convertible back
782 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
783 /// with `Delimiter::None` delimiters and negative numeric literals.
784 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
785 impl fmt::Display for TokenTree {
786 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
787 f.write_str(&self.to_string())
791 /// A delimited token stream.
793 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
795 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
796 pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
798 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
799 impl !Send for Group {}
800 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
801 impl !Sync for Group {}
803 /// Describes how a sequence of token trees is delimited.
804 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
805 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
808 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
811 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
814 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
817 /// An invisible delimiter, that may, for example, appear around tokens coming from a
818 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
819 /// `$var * 3` where `$var` is `1 + 2`.
820 /// Invisible delimiters might not survive roundtrip of a token stream through a string.
821 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
826 /// Creates a new `Group` with the given delimiter and token stream.
828 /// This constructor will set the span for this group to
829 /// `Span::call_site()`. To change the span you can use the `set_span`
831 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
832 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
833 Group(bridge::Group {
836 span: bridge::DelimSpan::from_single(Span::call_site().0),
840 /// Returns the delimiter of this `Group`
841 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
842 pub fn delimiter(&self) -> Delimiter {
846 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
848 /// Note that the returned token stream does not include the delimiter
850 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
851 pub fn stream(&self) -> TokenStream {
852 TokenStream(self.0.stream.clone())
855 /// Returns the span for the delimiters of this token stream, spanning the
859 /// pub fn span(&self) -> Span {
862 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
863 pub fn span(&self) -> Span {
864 Span(self.0.span.entire)
867 /// Returns the span pointing to the opening delimiter of this group.
870 /// pub fn span_open(&self) -> Span {
873 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
874 pub fn span_open(&self) -> Span {
875 Span(self.0.span.open)
878 /// Returns the span pointing to the closing delimiter of this group.
881 /// pub fn span_close(&self) -> Span {
884 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
885 pub fn span_close(&self) -> Span {
886 Span(self.0.span.close)
889 /// Configures the span for this `Group`'s delimiters, but not its internal
892 /// This method will **not** set the span of all the internal tokens spanned
893 /// by this group, but rather it will only set the span of the delimiter
894 /// tokens at the level of the `Group`.
895 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
896 pub fn set_span(&mut self, span: Span) {
897 self.0.span = bridge::DelimSpan::from_single(span.0);
901 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
902 // based on it (the reverse of the usual relationship between the two).
903 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
904 impl ToString for Group {
905 fn to_string(&self) -> String {
906 TokenStream::from(TokenTree::from(self.clone())).to_string()
910 /// Prints the group as a string that should be losslessly convertible back
911 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
912 /// with `Delimiter::None` delimiters.
913 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
914 impl fmt::Display for Group {
915 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916 f.write_str(&self.to_string())
920 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
921 impl fmt::Debug for Group {
922 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
923 f.debug_struct("Group")
924 .field("delimiter", &self.delimiter())
925 .field("stream", &self.stream())
926 .field("span", &self.span())
931 /// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
933 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
934 /// forms of `Spacing` returned.
935 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
937 pub struct Punct(bridge::Punct<bridge::client::Span>);
939 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
940 impl !Send for Punct {}
941 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
942 impl !Sync for Punct {}
944 /// Describes whether a `Punct` is followed immediately by another `Punct` ([`Spacing::Joint`]) or
945 /// by a different token or whitespace ([`Spacing::Alone`]).
946 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
947 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
949 /// A `Punct` is not immediately followed by another `Punct`.
950 /// E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`.
951 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
953 /// A `Punct` is immediately followed by another `Punct`.
954 /// E.g. `+` is `Joint` in `+=` and `++`.
956 /// Additionally, single quote `'` can join with identifiers to form lifetimes: `'ident`.
957 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
962 /// Creates a new `Punct` from the given character and spacing.
963 /// The `ch` argument must be a valid punctuation character permitted by the language,
964 /// otherwise the function will panic.
966 /// The returned `Punct` will have the default span of `Span::call_site()`
967 /// which can be further configured with the `set_span` method below.
968 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
969 pub fn new(ch: char, spacing: Spacing) -> Punct {
970 const LEGAL_CHARS: &[char] = &[
971 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
972 ':', '#', '$', '?', '\'',
974 if !LEGAL_CHARS.contains(&ch) {
975 panic!("unsupported character `{:?}`", ch);
977 Punct(bridge::Punct {
979 joint: spacing == Spacing::Joint,
980 span: Span::call_site().0,
984 /// Returns the value of this punctuation character as `char`.
985 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
986 pub fn as_char(&self) -> char {
990 /// Returns the spacing of this punctuation character, indicating whether it's immediately
991 /// followed by another `Punct` in the token stream, so they can potentially be combined into
992 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
993 /// (`Alone`) so the operator has certainly ended.
994 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
995 pub fn spacing(&self) -> Spacing {
996 if self.0.joint { Spacing::Joint } else { Spacing::Alone }
999 /// Returns the span for this punctuation character.
1000 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1001 pub fn span(&self) -> Span {
1005 /// Configure the span for this punctuation character.
1006 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1007 pub fn set_span(&mut self, span: Span) {
1008 self.0.span = span.0;
1012 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1013 impl ToString for Punct {
1014 fn to_string(&self) -> String {
1015 self.as_char().to_string()
1019 /// Prints the punctuation character as a string that should be losslessly convertible
1020 /// back into the same character.
1021 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1022 impl fmt::Display for Punct {
1023 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1024 write!(f, "{}", self.as_char())
1028 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1029 impl fmt::Debug for Punct {
1030 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1031 f.debug_struct("Punct")
1032 .field("ch", &self.as_char())
1033 .field("spacing", &self.spacing())
1034 .field("span", &self.span())
1039 #[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1040 impl PartialEq<char> for Punct {
1041 fn eq(&self, rhs: &char) -> bool {
1042 self.as_char() == *rhs
1046 #[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1047 impl PartialEq<Punct> for char {
1048 fn eq(&self, rhs: &Punct) -> bool {
1049 *self == rhs.as_char()
1053 /// An identifier (`ident`).
1055 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1056 pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1059 /// Creates a new `Ident` with the given `string` as well as the specified
1061 /// The `string` argument must be a valid identifier permitted by the
1062 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
1064 /// Note that `span`, currently in rustc, configures the hygiene information
1065 /// for this identifier.
1067 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
1068 /// meaning that identifiers created with this span will be resolved as if they were written
1069 /// directly at the location of the macro call, and other code at the macro call site will be
1070 /// able to refer to them as well.
1072 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
1073 /// meaning that identifiers created with this span will be resolved at the location of the
1074 /// macro definition and other code at the macro call site will not be able to refer to them.
1076 /// Due to the current importance of hygiene this constructor, unlike other
1077 /// tokens, requires a `Span` to be specified at construction.
1078 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1079 pub fn new(string: &str, span: Span) -> Ident {
1080 Ident(bridge::Ident {
1081 sym: bridge::client::Symbol::new_ident(string, false),
1087 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
1088 /// The `string` argument be a valid identifier permitted by the language
1089 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
1090 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
1091 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1092 pub fn new_raw(string: &str, span: Span) -> Ident {
1093 Ident(bridge::Ident {
1094 sym: bridge::client::Symbol::new_ident(string, true),
1100 /// Returns the span of this `Ident`, encompassing the entire string returned
1101 /// by [`to_string`](ToString::to_string).
1102 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1103 pub fn span(&self) -> Span {
1107 /// Configures the span of this `Ident`, possibly changing its hygiene context.
1108 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1109 pub fn set_span(&mut self, span: Span) {
1110 self.0.span = span.0;
1114 /// Converts the identifier to a string that should be losslessly convertible
1115 /// back into the same identifier.
1116 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1117 impl ToString for Ident {
1118 fn to_string(&self) -> String {
1119 self.0.sym.with(|sym| if self.0.is_raw { ["r#", sym].concat() } else { sym.to_owned() })
1123 /// Prints the identifier as a string that should be losslessly convertible back
1124 /// into the same identifier.
1125 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1126 impl fmt::Display for Ident {
1127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1131 fmt::Display::fmt(&self.0.sym, f)
1135 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1136 impl fmt::Debug for Ident {
1137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1138 f.debug_struct("Ident")
1139 .field("ident", &self.to_string())
1140 .field("span", &self.span())
1145 /// A literal string (`"hello"`), byte string (`b"hello"`),
1146 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
1147 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1148 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
1150 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1151 pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1153 macro_rules! suffixed_int_literals {
1154 ($($name:ident => $kind:ident,)*) => ($(
1155 /// Creates a new suffixed integer literal with the specified value.
1157 /// This function will create an integer like `1u32` where the integer
1158 /// value specified is the first part of the token and the integral is
1159 /// also suffixed at the end.
1160 /// Literals created from negative numbers might not survive round-trips through
1161 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1163 /// Literals created through this method have the `Span::call_site()`
1164 /// span by default, which can be configured with the `set_span` method
1166 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1167 pub fn $name(n: $kind) -> Literal {
1168 Literal(bridge::Literal {
1169 kind: bridge::LitKind::Integer,
1170 symbol: bridge::client::Symbol::new(&n.to_string()),
1171 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1172 span: Span::call_site().0,
1178 macro_rules! unsuffixed_int_literals {
1179 ($($name:ident => $kind:ident,)*) => ($(
1180 /// Creates a new unsuffixed integer literal with the specified value.
1182 /// This function will create an integer like `1` where the integer
1183 /// value specified is the first part of the token. No suffix is
1184 /// specified on this token, meaning that invocations like
1185 /// `Literal::i8_unsuffixed(1)` are equivalent to
1186 /// `Literal::u32_unsuffixed(1)`.
1187 /// Literals created from negative numbers might not survive rountrips through
1188 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1190 /// Literals created through this method have the `Span::call_site()`
1191 /// span by default, which can be configured with the `set_span` method
1193 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1194 pub fn $name(n: $kind) -> Literal {
1195 Literal(bridge::Literal {
1196 kind: bridge::LitKind::Integer,
1197 symbol: bridge::client::Symbol::new(&n.to_string()),
1199 span: Span::call_site().0,
1206 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1207 Literal(bridge::Literal {
1209 symbol: bridge::client::Symbol::new(value),
1210 suffix: suffix.map(bridge::client::Symbol::new),
1211 span: Span::call_site().0,
1215 suffixed_int_literals! {
1217 u16_suffixed => u16,
1218 u32_suffixed => u32,
1219 u64_suffixed => u64,
1220 u128_suffixed => u128,
1221 usize_suffixed => usize,
1223 i16_suffixed => i16,
1224 i32_suffixed => i32,
1225 i64_suffixed => i64,
1226 i128_suffixed => i128,
1227 isize_suffixed => isize,
1230 unsuffixed_int_literals! {
1231 u8_unsuffixed => u8,
1232 u16_unsuffixed => u16,
1233 u32_unsuffixed => u32,
1234 u64_unsuffixed => u64,
1235 u128_unsuffixed => u128,
1236 usize_unsuffixed => usize,
1237 i8_unsuffixed => i8,
1238 i16_unsuffixed => i16,
1239 i32_unsuffixed => i32,
1240 i64_unsuffixed => i64,
1241 i128_unsuffixed => i128,
1242 isize_unsuffixed => isize,
1245 /// Creates a new unsuffixed floating-point literal.
1247 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1248 /// the float's value is emitted directly into the token but no suffix is
1249 /// used, so it may be inferred to be a `f64` later in the compiler.
1250 /// Literals created from negative numbers might not survive rountrips through
1251 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1255 /// This function requires that the specified float is finite, for
1256 /// example if it is infinity or NaN this function will panic.
1257 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1258 pub fn f32_unsuffixed(n: f32) -> Literal {
1260 panic!("Invalid float literal {n}");
1262 let mut repr = n.to_string();
1263 if !repr.contains('.') {
1264 repr.push_str(".0");
1266 Literal::new(bridge::LitKind::Float, &repr, None)
1269 /// Creates a new suffixed floating-point literal.
1271 /// This constructor will create a literal like `1.0f32` where the value
1272 /// specified is the preceding part of the token and `f32` is the suffix of
1273 /// the token. This token will always be inferred to be an `f32` in the
1275 /// Literals created from negative numbers might not survive rountrips through
1276 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1280 /// This function requires that the specified float is finite, for
1281 /// example if it is infinity or NaN this function will panic.
1282 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1283 pub fn f32_suffixed(n: f32) -> Literal {
1285 panic!("Invalid float literal {n}");
1287 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1290 /// Creates a new unsuffixed floating-point literal.
1292 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1293 /// the float's value is emitted directly into the token but no suffix is
1294 /// used, so it may be inferred to be a `f64` later in the compiler.
1295 /// Literals created from negative numbers might not survive rountrips through
1296 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1300 /// This function requires that the specified float is finite, for
1301 /// example if it is infinity or NaN this function will panic.
1302 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1303 pub fn f64_unsuffixed(n: f64) -> Literal {
1305 panic!("Invalid float literal {n}");
1307 let mut repr = n.to_string();
1308 if !repr.contains('.') {
1309 repr.push_str(".0");
1311 Literal::new(bridge::LitKind::Float, &repr, None)
1314 /// Creates a new suffixed floating-point literal.
1316 /// This constructor will create a literal like `1.0f64` where the value
1317 /// specified is the preceding part of the token and `f64` is the suffix of
1318 /// the token. This token will always be inferred to be an `f64` in the
1320 /// Literals created from negative numbers might not survive rountrips through
1321 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1325 /// This function requires that the specified float is finite, for
1326 /// example if it is infinity or NaN this function will panic.
1327 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1328 pub fn f64_suffixed(n: f64) -> Literal {
1330 panic!("Invalid float literal {n}");
1332 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1336 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1337 pub fn string(string: &str) -> Literal {
1338 let quoted = format!("{:?}", string);
1339 assert!(quoted.starts_with('"') && quoted.ends_with('"'));
1340 let symbol = "ed[1..quoted.len() - 1];
1341 Literal::new(bridge::LitKind::Str, symbol, None)
1344 /// Character literal.
1345 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1346 pub fn character(ch: char) -> Literal {
1347 let quoted = format!("{:?}", ch);
1348 assert!(quoted.starts_with('\'') && quoted.ends_with('\''));
1349 let symbol = "ed[1..quoted.len() - 1];
1350 Literal::new(bridge::LitKind::Char, symbol, None)
1353 /// Byte string literal.
1354 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1355 pub fn byte_string(bytes: &[u8]) -> Literal {
1359 .flat_map(std::ascii::escape_default)
1360 .map(Into::<char>::into)
1361 .collect::<String>();
1362 Literal::new(bridge::LitKind::ByteStr, &string, None)
1365 /// Returns the span encompassing this literal.
1366 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1367 pub fn span(&self) -> Span {
1371 /// Configures the span associated for this literal.
1372 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1373 pub fn set_span(&mut self, span: Span) {
1374 self.0.span = span.0;
1377 /// Returns a `Span` that is a subset of `self.span()` containing only the
1378 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1379 /// span is outside the bounds of `self`.
1380 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1381 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1382 // occur elsewhere when the source text is printed.
1383 // FIXME(SergioBenitez): there is no way for the user to know what
1384 // `self.span()` actually maps to, so this method can currently only be
1385 // called blindly. For example, `to_string()` for the character 'c' returns
1386 // "'\u{63}'"; there is no way for the user to know whether the source text
1387 // was 'c' or whether it was '\u{63}'.
1388 #[unstable(feature = "proc_macro_span", issue = "54725")]
1389 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1390 self.0.span.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span)
1393 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1394 self.0.symbol.with(|symbol| match self.0.suffix {
1395 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1396 None => f(symbol, ""),
1400 /// Invokes the callback with a `&[&str]` consisting of each part of the
1401 /// literal's representation. This is done to allow the `ToString` and
1402 /// `Display` implementations to borrow references to symbol values, and
1403 /// both be optimized to reduce overhead.
1404 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1405 /// Returns a string containing exactly `num` '#' characters.
1406 /// Uses a 256-character source string literal which is always safe to
1407 /// index with a `u8` index.
1408 fn get_hashes_str(num: u8) -> &'static str {
1409 const HASHES: &str = "\
1410 ################################################################\
1411 ################################################################\
1412 ################################################################\
1413 ################################################################\
1415 const _: () = assert!(HASHES.len() == 256);
1416 &HASHES[..num as usize]
1419 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1420 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1421 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1422 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1423 bridge::LitKind::StrRaw(n) => {
1424 let hashes = get_hashes_str(n);
1425 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1427 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1428 bridge::LitKind::ByteStrRaw(n) => {
1429 let hashes = get_hashes_str(n);
1430 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1432 _ => f(&[symbol, suffix]),
1437 /// Parse a single literal from its stringified representation.
1439 /// In order to parse successfully, the input string must not contain anything
1440 /// but the literal token. Specifically, it must not contain whitespace or
1441 /// comments in addition to the literal.
1443 /// The resulting literal token will have a `Span::call_site()` span.
1445 /// NOTE: some errors may cause panics instead of returning `LexError`. We
1446 /// reserve the right to change these errors into `LexError`s later.
1447 #[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1448 impl FromStr for Literal {
1449 type Err = LexError;
1451 fn from_str(src: &str) -> Result<Self, LexError> {
1452 match bridge::client::FreeFunctions::literal_from_str(src) {
1453 Ok(literal) => Ok(Literal(literal)),
1454 Err(()) => Err(LexError),
1459 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1460 impl ToString for Literal {
1461 fn to_string(&self) -> String {
1462 self.with_stringify_parts(|parts| parts.concat())
1466 /// Prints the literal as a string that should be losslessly convertible
1467 /// back into the same literal (except for possible rounding for floating point literals).
1468 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1469 impl fmt::Display for Literal {
1470 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1471 self.with_stringify_parts(|parts| {
1473 fmt::Display::fmt(part, f)?;
1480 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1481 impl fmt::Debug for Literal {
1482 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1483 f.debug_struct("Literal")
1484 // format the kind on one line even in {:#?} mode
1485 .field("kind", &format_args!("{:?}", &self.0.kind))
1486 .field("symbol", &self.0.symbol)
1487 // format `Some("...")` on one line even in {:#?} mode
1488 .field("suffix", &format_args!("{:?}", &self.0.suffix))
1489 .field("span", &self.0.span)
1494 /// Tracked access to environment variables.
1495 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1496 pub mod tracked_env {
1497 use std::env::{self, VarError};
1498 use std::ffi::OsStr;
1500 /// Retrieve an environment variable and add it to build dependency info.
1501 /// Build system executing the compiler will know that the variable was accessed during
1502 /// compilation, and will be able to rerun the build when the value of that variable changes.
1503 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1504 /// standard library, except that the argument must be UTF-8.
1505 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1506 pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1507 let key: &str = key.as_ref();
1508 let value = env::var(key);
1509 crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());
1514 /// Tracked access to additional files.
1515 #[unstable(feature = "track_path", issue = "99515")]
1516 pub mod tracked_path {
1518 /// Track a file explicitly.
1520 /// Commonly used for tracking asset preprocessing.
1521 #[unstable(feature = "track_path", issue = "99515")]
1522 pub fn path<P: AsRef<str>>(path: P) {
1523 let path: &str = path.as_ref();
1524 crate::bridge::client::FreeFunctions::track_path(path);