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 #[rustc_diagnostic_item = "TokenStream"]
78 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
80 pub struct TokenStream(Option<bridge::client::TokenStream>);
82 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
83 impl !Send for TokenStream {}
84 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
85 impl !Sync for TokenStream {}
87 /// Error returned from `TokenStream::from_str`.
88 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
93 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
94 impl fmt::Display for LexError {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 f.write_str("cannot parse string into token stream")
100 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
101 impl error::Error for LexError {}
103 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
104 impl !Send for LexError {}
105 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
106 impl !Sync for LexError {}
108 /// Error returned from `TokenStream::expand_expr`.
109 #[unstable(feature = "proc_macro_expand", issue = "90765")]
112 pub struct ExpandError;
114 #[unstable(feature = "proc_macro_expand", issue = "90765")]
115 impl fmt::Display for ExpandError {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.write_str("macro expansion failed")
121 #[unstable(feature = "proc_macro_expand", issue = "90765")]
122 impl error::Error for ExpandError {}
124 #[unstable(feature = "proc_macro_expand", issue = "90765")]
125 impl !Send for ExpandError {}
127 #[unstable(feature = "proc_macro_expand", issue = "90765")]
128 impl !Sync for ExpandError {}
131 /// Returns an empty `TokenStream` containing no token trees.
132 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
133 pub fn new() -> TokenStream {
137 /// Checks if this `TokenStream` is empty.
138 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
139 pub fn is_empty(&self) -> bool {
140 self.0.as_ref().map(|h| h.is_empty()).unwrap_or(true)
143 /// Parses this `TokenStream` as an expression and attempts to expand any
144 /// macros within it. Returns the expanded `TokenStream`.
146 /// Currently only expressions expanding to literals will succeed, although
147 /// this may be relaxed in the future.
149 /// NOTE: In error conditions, `expand_expr` may leave macros unexpanded,
150 /// report an error, failing compilation, and/or return an `Err(..)`. The
151 /// specific behavior for any error condition, and what conditions are
152 /// considered errors, is unspecified and may change in the future.
153 #[unstable(feature = "proc_macro_expand", issue = "90765")]
154 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
155 let stream = self.0.as_ref().ok_or(ExpandError)?;
156 match bridge::client::TokenStream::expand_expr(stream) {
157 Ok(stream) => Ok(TokenStream(Some(stream))),
158 Err(_) => Err(ExpandError),
163 /// Attempts to break the string into tokens and parse those tokens into a token stream.
164 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
165 /// or characters not existing in the language.
166 /// All tokens in the parsed stream get `Span::call_site()` spans.
168 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
169 /// change these errors into `LexError`s later.
170 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
171 impl FromStr for TokenStream {
174 fn from_str(src: &str) -> Result<TokenStream, LexError> {
175 Ok(TokenStream(Some(bridge::client::TokenStream::from_str(src))))
179 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
180 // based on it (the reverse of the usual relationship between the two).
181 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
182 impl ToString for TokenStream {
183 fn to_string(&self) -> String {
184 self.0.as_ref().map(|t| t.to_string()).unwrap_or_default()
188 /// Prints the token stream as a string that is supposed to be losslessly convertible back
189 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
190 /// with `Delimiter::None` delimiters and negative numeric literals.
191 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
192 impl fmt::Display for TokenStream {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 f.write_str(&self.to_string())
198 /// Prints token in a form convenient for debugging.
199 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
200 impl fmt::Debug for TokenStream {
201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202 f.write_str("TokenStream ")?;
203 f.debug_list().entries(self.clone()).finish()
207 #[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
208 impl Default for TokenStream {
209 fn default() -> Self {
214 #[unstable(feature = "proc_macro_quote", issue = "54722")]
215 pub use quote::{quote, quote_span};
217 fn tree_to_bridge_tree(
219 ) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
221 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
222 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
223 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
224 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
228 /// Creates a token stream containing a single token tree.
229 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
230 impl From<TokenTree> for TokenStream {
231 fn from(tree: TokenTree) -> TokenStream {
232 TokenStream(Some(bridge::client::TokenStream::from_token_tree(tree_to_bridge_tree(tree))))
236 /// Non-generic helper for implementing `FromIterator<TokenTree>` and
237 /// `Extend<TokenTree>` with less monomorphization in calling crates.
238 struct ConcatTreesHelper {
241 bridge::client::TokenStream,
242 bridge::client::Span,
243 bridge::client::Symbol,
248 impl ConcatTreesHelper {
249 fn new(capacity: usize) -> Self {
250 ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
253 fn push(&mut self, tree: TokenTree) {
254 self.trees.push(tree_to_bridge_tree(tree));
257 fn build(self) -> TokenStream {
258 if self.trees.is_empty() {
261 TokenStream(Some(bridge::client::TokenStream::concat_trees(None, self.trees)))
265 fn append_to(self, stream: &mut TokenStream) {
266 if self.trees.is_empty() {
269 stream.0 = Some(bridge::client::TokenStream::concat_trees(stream.0.take(), self.trees))
273 /// Non-generic helper for implementing `FromIterator<TokenStream>` and
274 /// `Extend<TokenStream>` with less monomorphization in calling crates.
275 struct ConcatStreamsHelper {
276 streams: Vec<bridge::client::TokenStream>,
279 impl ConcatStreamsHelper {
280 fn new(capacity: usize) -> Self {
281 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
284 fn push(&mut self, stream: TokenStream) {
285 if let Some(stream) = stream.0 {
286 self.streams.push(stream);
290 fn build(mut self) -> TokenStream {
291 if self.streams.len() <= 1 {
292 TokenStream(self.streams.pop())
294 TokenStream(Some(bridge::client::TokenStream::concat_streams(None, self.streams)))
298 fn append_to(mut self, stream: &mut TokenStream) {
299 if self.streams.is_empty() {
302 let base = stream.0.take();
303 if base.is_none() && self.streams.len() == 1 {
304 stream.0 = self.streams.pop();
306 stream.0 = Some(bridge::client::TokenStream::concat_streams(base, self.streams));
311 /// Collects a number of token trees into a single stream.
312 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
313 impl iter::FromIterator<TokenTree> for TokenStream {
314 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
315 let iter = trees.into_iter();
316 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
317 iter.for_each(|tree| builder.push(tree));
322 /// A "flattening" operation on token streams, collects token trees
323 /// from multiple token streams into a single stream.
324 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
325 impl iter::FromIterator<TokenStream> for TokenStream {
326 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
327 let iter = streams.into_iter();
328 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
329 iter.for_each(|stream| builder.push(stream));
334 #[stable(feature = "token_stream_extend", since = "1.30.0")]
335 impl Extend<TokenTree> for TokenStream {
336 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
337 let iter = trees.into_iter();
338 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
339 iter.for_each(|tree| builder.push(tree));
340 builder.append_to(self);
344 #[stable(feature = "token_stream_extend", since = "1.30.0")]
345 impl Extend<TokenStream> for TokenStream {
346 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
347 let iter = streams.into_iter();
348 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
349 iter.for_each(|stream| builder.push(stream));
350 builder.append_to(self);
354 /// Public implementation details for the `TokenStream` type, such as iterators.
355 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
356 pub mod token_stream {
357 use crate::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree};
359 /// An iterator over `TokenStream`'s `TokenTree`s.
360 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
361 /// and returns whole groups as token trees.
363 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
367 bridge::client::TokenStream,
368 bridge::client::Span,
369 bridge::client::Symbol,
374 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
375 impl Iterator for IntoIter {
376 type Item = TokenTree;
378 fn next(&mut self) -> Option<TokenTree> {
379 self.0.next().map(|tree| match tree {
380 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
381 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
382 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
383 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
387 fn size_hint(&self) -> (usize, Option<usize>) {
391 fn count(self) -> usize {
396 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
397 impl IntoIterator for TokenStream {
398 type Item = TokenTree;
399 type IntoIter = IntoIter;
401 fn into_iter(self) -> IntoIter {
402 IntoIter(self.0.map(|v| v.into_trees()).unwrap_or_default().into_iter())
407 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
408 /// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
409 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
411 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
412 /// To quote `$` itself, use `$$`.
413 #[unstable(feature = "proc_macro_quote", issue = "54722")]
414 #[allow_internal_unstable(proc_macro_def_site, proc_macro_internals)]
415 #[rustc_builtin_macro]
416 pub macro quote($($t:tt)*) {
417 /* compiler built-in */
420 #[unstable(feature = "proc_macro_internals", issue = "27812")]
424 /// A region of source code, along with macro expansion information.
425 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
426 #[derive(Copy, Clone)]
427 pub struct Span(bridge::client::Span);
429 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
430 impl !Send for Span {}
431 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
432 impl !Sync for Span {}
434 macro_rules! diagnostic_method {
435 ($name:ident, $level:expr) => {
436 /// Creates a new `Diagnostic` with the given `message` at the span
438 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
439 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
440 Diagnostic::spanned(self, $level, message)
446 /// A span that resolves at the macro definition site.
447 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
448 pub fn def_site() -> Span {
449 Span(bridge::client::Span::def_site())
452 /// The span of the invocation of the current procedural macro.
453 /// Identifiers created with this span will be resolved as if they were written
454 /// directly at the macro call location (call-site hygiene) and other code
455 /// at the macro call site will be able to refer to them as well.
456 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
457 pub fn call_site() -> Span {
458 Span(bridge::client::Span::call_site())
461 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
462 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
463 /// call site (everything else).
464 /// The span location is taken from the call-site.
465 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
466 pub fn mixed_site() -> Span {
467 Span(bridge::client::Span::mixed_site())
470 /// The original source file into which this span points.
471 #[unstable(feature = "proc_macro_span", issue = "54725")]
472 pub fn source_file(&self) -> SourceFile {
473 SourceFile(self.0.source_file())
476 /// The `Span` for the tokens in the previous macro expansion from which
477 /// `self` was generated from, if any.
478 #[unstable(feature = "proc_macro_span", issue = "54725")]
479 pub fn parent(&self) -> Option<Span> {
480 self.0.parent().map(Span)
483 /// The span for the origin source code that `self` was generated from. If
484 /// this `Span` wasn't generated from other macro expansions then the return
485 /// value is the same as `*self`.
486 #[unstable(feature = "proc_macro_span", issue = "54725")]
487 pub fn source(&self) -> Span {
488 Span(self.0.source())
491 /// Gets the starting line/column in the source file for this span.
492 #[unstable(feature = "proc_macro_span", issue = "54725")]
493 pub fn start(&self) -> LineColumn {
494 self.0.start().add_1_to_column()
497 /// Gets the ending line/column in the source file for this span.
498 #[unstable(feature = "proc_macro_span", issue = "54725")]
499 pub fn end(&self) -> LineColumn {
500 self.0.end().add_1_to_column()
503 /// Creates an empty span pointing to directly before this span.
504 #[unstable(feature = "proc_macro_span_shrink", issue = "87552")]
505 pub fn before(&self) -> Span {
506 Span(self.0.before())
509 /// Creates an empty span pointing to directly after this span.
510 #[unstable(feature = "proc_macro_span_shrink", issue = "87552")]
511 pub fn after(&self) -> Span {
515 /// Creates a new span encompassing `self` and `other`.
517 /// Returns `None` if `self` and `other` are from different files.
518 #[unstable(feature = "proc_macro_span", issue = "54725")]
519 pub fn join(&self, other: Span) -> Option<Span> {
520 self.0.join(other.0).map(Span)
523 /// Creates a new span with the same line/column information as `self` but
524 /// that resolves symbols as though it were at `other`.
525 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
526 pub fn resolved_at(&self, other: Span) -> Span {
527 Span(self.0.resolved_at(other.0))
530 /// Creates a new span with the same name resolution behavior as `self` but
531 /// with the line/column information of `other`.
532 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
533 pub fn located_at(&self, other: Span) -> Span {
534 other.resolved_at(*self)
537 /// Compares two spans to see if they're equal.
538 #[unstable(feature = "proc_macro_span", issue = "54725")]
539 pub fn eq(&self, other: &Span) -> bool {
543 /// Returns the source text behind a span. This preserves the original source
544 /// code, including spaces and comments. It only returns a result if the span
545 /// corresponds to real source code.
547 /// Note: The observable result of a macro should only rely on the tokens and
548 /// not on this source text. The result of this function is a best effort to
549 /// be used for diagnostics only.
550 #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
551 pub fn source_text(&self) -> Option<String> {
555 // Used by the implementation of `Span::quote`
557 #[unstable(feature = "proc_macro_internals", issue = "27812")]
558 pub fn save_span(&self) -> usize {
562 // Used by the implementation of `Span::quote`
564 #[unstable(feature = "proc_macro_internals", issue = "27812")]
565 pub fn recover_proc_macro_span(id: usize) -> Span {
566 Span(bridge::client::Span::recover_proc_macro_span(id))
569 diagnostic_method!(error, Level::Error);
570 diagnostic_method!(warning, Level::Warning);
571 diagnostic_method!(note, Level::Note);
572 diagnostic_method!(help, Level::Help);
575 /// Prints a span in a form convenient for debugging.
576 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
577 impl fmt::Debug for Span {
578 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
583 /// A line-column pair representing the start or end of a `Span`.
584 #[unstable(feature = "proc_macro_span", issue = "54725")]
585 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
586 pub struct LineColumn {
587 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
588 #[unstable(feature = "proc_macro_span", issue = "54725")]
590 /// The 1-indexed column (number of bytes in UTF-8 encoding) in the source
591 /// file on which the span starts or ends (inclusive).
592 #[unstable(feature = "proc_macro_span", issue = "54725")]
597 fn add_1_to_column(self) -> Self {
598 LineColumn { line: self.line, column: self.column + 1 }
602 #[unstable(feature = "proc_macro_span", issue = "54725")]
603 impl !Send for LineColumn {}
604 #[unstable(feature = "proc_macro_span", issue = "54725")]
605 impl !Sync for LineColumn {}
607 #[unstable(feature = "proc_macro_span", issue = "54725")]
608 impl Ord for LineColumn {
609 fn cmp(&self, other: &Self) -> Ordering {
610 self.line.cmp(&other.line).then(self.column.cmp(&other.column))
614 #[unstable(feature = "proc_macro_span", issue = "54725")]
615 impl PartialOrd for LineColumn {
616 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
617 Some(self.cmp(other))
621 /// The source file of a given `Span`.
622 #[unstable(feature = "proc_macro_span", issue = "54725")]
624 pub struct SourceFile(bridge::client::SourceFile);
627 /// Gets the path to this source file.
630 /// If the code span associated with this `SourceFile` was generated by an external macro, this
631 /// macro, this might not be an actual path on the filesystem. Use [`is_real`] to check.
633 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
634 /// the command line, the path as given might not actually be valid.
636 /// [`is_real`]: Self::is_real
637 #[unstable(feature = "proc_macro_span", issue = "54725")]
638 pub fn path(&self) -> PathBuf {
639 PathBuf::from(self.0.path())
642 /// Returns `true` if this source file is a real source file, and not generated by an external
643 /// macro's expansion.
644 #[unstable(feature = "proc_macro_span", issue = "54725")]
645 pub fn is_real(&self) -> bool {
646 // This is a hack until intercrate spans are implemented and we can have real source files
647 // for spans generated in external macros.
648 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
653 #[unstable(feature = "proc_macro_span", issue = "54725")]
654 impl fmt::Debug for SourceFile {
655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656 f.debug_struct("SourceFile")
657 .field("path", &self.path())
658 .field("is_real", &self.is_real())
663 #[unstable(feature = "proc_macro_span", issue = "54725")]
664 impl PartialEq for SourceFile {
665 fn eq(&self, other: &Self) -> bool {
670 #[unstable(feature = "proc_macro_span", issue = "54725")]
671 impl Eq for SourceFile {}
673 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
674 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
677 /// A token stream surrounded by bracket delimiters.
678 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
679 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
681 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
682 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
683 /// A single punctuation character (`+`, `,`, `$`, etc.).
684 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
685 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
686 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
687 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
688 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
691 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
692 impl !Send for TokenTree {}
693 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
694 impl !Sync for TokenTree {}
697 /// Returns the span of this tree, delegating to the `span` method of
698 /// the contained token or a delimited stream.
699 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
700 pub fn span(&self) -> Span {
702 TokenTree::Group(ref t) => t.span(),
703 TokenTree::Ident(ref t) => t.span(),
704 TokenTree::Punct(ref t) => t.span(),
705 TokenTree::Literal(ref t) => t.span(),
709 /// Configures the span for *only this token*.
711 /// Note that if this token is a `Group` then this method will not configure
712 /// the span of each of the internal tokens, this will simply delegate to
713 /// the `set_span` method of each variant.
714 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
715 pub fn set_span(&mut self, span: Span) {
717 TokenTree::Group(ref mut t) => t.set_span(span),
718 TokenTree::Ident(ref mut t) => t.set_span(span),
719 TokenTree::Punct(ref mut t) => t.set_span(span),
720 TokenTree::Literal(ref mut t) => t.set_span(span),
725 /// Prints token tree in a form convenient for debugging.
726 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
727 impl fmt::Debug for TokenTree {
728 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
729 // Each of these has the name in the struct type in the derived debug,
730 // so don't bother with an extra layer of indirection
732 TokenTree::Group(ref tt) => tt.fmt(f),
733 TokenTree::Ident(ref tt) => tt.fmt(f),
734 TokenTree::Punct(ref tt) => tt.fmt(f),
735 TokenTree::Literal(ref tt) => tt.fmt(f),
740 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
741 impl From<Group> for TokenTree {
742 fn from(g: Group) -> TokenTree {
747 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
748 impl From<Ident> for TokenTree {
749 fn from(g: Ident) -> TokenTree {
754 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
755 impl From<Punct> for TokenTree {
756 fn from(g: Punct) -> TokenTree {
761 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
762 impl From<Literal> for TokenTree {
763 fn from(g: Literal) -> TokenTree {
764 TokenTree::Literal(g)
768 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
769 // based on it (the reverse of the usual relationship between the two).
770 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
771 impl ToString for TokenTree {
772 fn to_string(&self) -> String {
774 TokenTree::Group(ref t) => t.to_string(),
775 TokenTree::Ident(ref t) => t.to_string(),
776 TokenTree::Punct(ref t) => t.to_string(),
777 TokenTree::Literal(ref t) => t.to_string(),
782 /// Prints the token tree as a string that is supposed to be losslessly convertible back
783 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
784 /// with `Delimiter::None` delimiters and negative numeric literals.
785 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
786 impl fmt::Display for TokenTree {
787 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
788 f.write_str(&self.to_string())
792 /// A delimited token stream.
794 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
796 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
797 pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
799 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
800 impl !Send for Group {}
801 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
802 impl !Sync for Group {}
804 /// Describes how a sequence of token trees is delimited.
805 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
806 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
809 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
812 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
815 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
818 /// An invisible delimiter, that may, for example, appear around tokens coming from a
819 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
820 /// `$var * 3` where `$var` is `1 + 2`.
821 /// Invisible delimiters might not survive roundtrip of a token stream through a string.
822 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
827 /// Creates a new `Group` with the given delimiter and token stream.
829 /// This constructor will set the span for this group to
830 /// `Span::call_site()`. To change the span you can use the `set_span`
832 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
833 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
834 Group(bridge::Group {
837 span: bridge::DelimSpan::from_single(Span::call_site().0),
841 /// Returns the delimiter of this `Group`
842 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
843 pub fn delimiter(&self) -> Delimiter {
847 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
849 /// Note that the returned token stream does not include the delimiter
851 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
852 pub fn stream(&self) -> TokenStream {
853 TokenStream(self.0.stream.clone())
856 /// Returns the span for the delimiters of this token stream, spanning the
860 /// pub fn span(&self) -> Span {
863 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
864 pub fn span(&self) -> Span {
865 Span(self.0.span.entire)
868 /// Returns the span pointing to the opening delimiter of this group.
871 /// pub fn span_open(&self) -> Span {
874 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
875 pub fn span_open(&self) -> Span {
876 Span(self.0.span.open)
879 /// Returns the span pointing to the closing delimiter of this group.
882 /// pub fn span_close(&self) -> Span {
885 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
886 pub fn span_close(&self) -> Span {
887 Span(self.0.span.close)
890 /// Configures the span for this `Group`'s delimiters, but not its internal
893 /// This method will **not** set the span of all the internal tokens spanned
894 /// by this group, but rather it will only set the span of the delimiter
895 /// tokens at the level of the `Group`.
896 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
897 pub fn set_span(&mut self, span: Span) {
898 self.0.span = bridge::DelimSpan::from_single(span.0);
902 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
903 // based on it (the reverse of the usual relationship between the two).
904 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
905 impl ToString for Group {
906 fn to_string(&self) -> String {
907 TokenStream::from(TokenTree::from(self.clone())).to_string()
911 /// Prints the group as a string that should be losslessly convertible back
912 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
913 /// with `Delimiter::None` delimiters.
914 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
915 impl fmt::Display for Group {
916 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
917 f.write_str(&self.to_string())
921 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
922 impl fmt::Debug for Group {
923 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
924 f.debug_struct("Group")
925 .field("delimiter", &self.delimiter())
926 .field("stream", &self.stream())
927 .field("span", &self.span())
932 /// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
934 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
935 /// forms of `Spacing` returned.
936 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
938 pub struct Punct(bridge::Punct<bridge::client::Span>);
940 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
941 impl !Send for Punct {}
942 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
943 impl !Sync for Punct {}
945 /// Describes whether a `Punct` is followed immediately by another `Punct` ([`Spacing::Joint`]) or
946 /// by a different token or whitespace ([`Spacing::Alone`]).
947 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
948 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
950 /// A `Punct` is not immediately followed by another `Punct`.
951 /// E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`.
952 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
954 /// A `Punct` is immediately followed by another `Punct`.
955 /// E.g. `+` is `Joint` in `+=` and `++`.
957 /// Additionally, single quote `'` can join with identifiers to form lifetimes: `'ident`.
958 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
963 /// Creates a new `Punct` from the given character and spacing.
964 /// The `ch` argument must be a valid punctuation character permitted by the language,
965 /// otherwise the function will panic.
967 /// The returned `Punct` will have the default span of `Span::call_site()`
968 /// which can be further configured with the `set_span` method below.
969 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
970 pub fn new(ch: char, spacing: Spacing) -> Punct {
971 const LEGAL_CHARS: &[char] = &[
972 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
973 ':', '#', '$', '?', '\'',
975 if !LEGAL_CHARS.contains(&ch) {
976 panic!("unsupported character `{:?}`", ch);
978 Punct(bridge::Punct {
980 joint: spacing == Spacing::Joint,
981 span: Span::call_site().0,
985 /// Returns the value of this punctuation character as `char`.
986 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
987 pub fn as_char(&self) -> char {
991 /// Returns the spacing of this punctuation character, indicating whether it's immediately
992 /// followed by another `Punct` in the token stream, so they can potentially be combined into
993 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
994 /// (`Alone`) so the operator has certainly ended.
995 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
996 pub fn spacing(&self) -> Spacing {
997 if self.0.joint { Spacing::Joint } else { Spacing::Alone }
1000 /// Returns the span for this punctuation character.
1001 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1002 pub fn span(&self) -> Span {
1006 /// Configure the span for this punctuation character.
1007 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1008 pub fn set_span(&mut self, span: Span) {
1009 self.0.span = span.0;
1013 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1014 impl ToString for Punct {
1015 fn to_string(&self) -> String {
1016 self.as_char().to_string()
1020 /// Prints the punctuation character as a string that should be losslessly convertible
1021 /// back into the same character.
1022 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1023 impl fmt::Display for Punct {
1024 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1025 write!(f, "{}", self.as_char())
1029 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1030 impl fmt::Debug for Punct {
1031 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1032 f.debug_struct("Punct")
1033 .field("ch", &self.as_char())
1034 .field("spacing", &self.spacing())
1035 .field("span", &self.span())
1040 #[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1041 impl PartialEq<char> for Punct {
1042 fn eq(&self, rhs: &char) -> bool {
1043 self.as_char() == *rhs
1047 #[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1048 impl PartialEq<Punct> for char {
1049 fn eq(&self, rhs: &Punct) -> bool {
1050 *self == rhs.as_char()
1054 /// An identifier (`ident`).
1056 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1057 pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1060 /// Creates a new `Ident` with the given `string` as well as the specified
1062 /// The `string` argument must be a valid identifier permitted by the
1063 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
1065 /// Note that `span`, currently in rustc, configures the hygiene information
1066 /// for this identifier.
1068 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
1069 /// meaning that identifiers created with this span will be resolved as if they were written
1070 /// directly at the location of the macro call, and other code at the macro call site will be
1071 /// able to refer to them as well.
1073 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
1074 /// meaning that identifiers created with this span will be resolved at the location of the
1075 /// macro definition and other code at the macro call site will not be able to refer to them.
1077 /// Due to the current importance of hygiene this constructor, unlike other
1078 /// tokens, requires a `Span` to be specified at construction.
1079 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1080 pub fn new(string: &str, span: Span) -> Ident {
1081 Ident(bridge::Ident {
1082 sym: bridge::client::Symbol::new_ident(string, false),
1088 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
1089 /// The `string` argument be a valid identifier permitted by the language
1090 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
1091 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
1092 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1093 pub fn new_raw(string: &str, span: Span) -> Ident {
1094 Ident(bridge::Ident {
1095 sym: bridge::client::Symbol::new_ident(string, true),
1101 /// Returns the span of this `Ident`, encompassing the entire string returned
1102 /// by [`to_string`](ToString::to_string).
1103 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1104 pub fn span(&self) -> Span {
1108 /// Configures the span of this `Ident`, possibly changing its hygiene context.
1109 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1110 pub fn set_span(&mut self, span: Span) {
1111 self.0.span = span.0;
1115 /// Converts the identifier to a string that should be losslessly convertible
1116 /// back into the same identifier.
1117 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1118 impl ToString for Ident {
1119 fn to_string(&self) -> String {
1120 self.0.sym.with(|sym| if self.0.is_raw { ["r#", sym].concat() } else { sym.to_owned() })
1124 /// Prints the identifier as a string that should be losslessly convertible back
1125 /// into the same identifier.
1126 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1127 impl fmt::Display for Ident {
1128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1132 fmt::Display::fmt(&self.0.sym, f)
1136 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1137 impl fmt::Debug for Ident {
1138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1139 f.debug_struct("Ident")
1140 .field("ident", &self.to_string())
1141 .field("span", &self.span())
1146 /// A literal string (`"hello"`), byte string (`b"hello"`),
1147 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
1148 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1149 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
1151 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1152 pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1154 macro_rules! suffixed_int_literals {
1155 ($($name:ident => $kind:ident,)*) => ($(
1156 /// Creates a new suffixed integer literal with the specified value.
1158 /// This function will create an integer like `1u32` where the integer
1159 /// value specified is the first part of the token and the integral is
1160 /// also suffixed at the end.
1161 /// Literals created from negative numbers might not survive round-trips through
1162 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1164 /// Literals created through this method have the `Span::call_site()`
1165 /// span by default, which can be configured with the `set_span` method
1167 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1168 pub fn $name(n: $kind) -> Literal {
1169 Literal(bridge::Literal {
1170 kind: bridge::LitKind::Integer,
1171 symbol: bridge::client::Symbol::new(&n.to_string()),
1172 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1173 span: Span::call_site().0,
1179 macro_rules! unsuffixed_int_literals {
1180 ($($name:ident => $kind:ident,)*) => ($(
1181 /// Creates a new unsuffixed integer literal with the specified value.
1183 /// This function will create an integer like `1` where the integer
1184 /// value specified is the first part of the token. No suffix is
1185 /// specified on this token, meaning that invocations like
1186 /// `Literal::i8_unsuffixed(1)` are equivalent to
1187 /// `Literal::u32_unsuffixed(1)`.
1188 /// Literals created from negative numbers might not survive rountrips through
1189 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1191 /// Literals created through this method have the `Span::call_site()`
1192 /// span by default, which can be configured with the `set_span` method
1194 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1195 pub fn $name(n: $kind) -> Literal {
1196 Literal(bridge::Literal {
1197 kind: bridge::LitKind::Integer,
1198 symbol: bridge::client::Symbol::new(&n.to_string()),
1200 span: Span::call_site().0,
1207 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1208 Literal(bridge::Literal {
1210 symbol: bridge::client::Symbol::new(value),
1211 suffix: suffix.map(bridge::client::Symbol::new),
1212 span: Span::call_site().0,
1216 suffixed_int_literals! {
1218 u16_suffixed => u16,
1219 u32_suffixed => u32,
1220 u64_suffixed => u64,
1221 u128_suffixed => u128,
1222 usize_suffixed => usize,
1224 i16_suffixed => i16,
1225 i32_suffixed => i32,
1226 i64_suffixed => i64,
1227 i128_suffixed => i128,
1228 isize_suffixed => isize,
1231 unsuffixed_int_literals! {
1232 u8_unsuffixed => u8,
1233 u16_unsuffixed => u16,
1234 u32_unsuffixed => u32,
1235 u64_unsuffixed => u64,
1236 u128_unsuffixed => u128,
1237 usize_unsuffixed => usize,
1238 i8_unsuffixed => i8,
1239 i16_unsuffixed => i16,
1240 i32_unsuffixed => i32,
1241 i64_unsuffixed => i64,
1242 i128_unsuffixed => i128,
1243 isize_unsuffixed => isize,
1246 /// Creates a new unsuffixed floating-point literal.
1248 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1249 /// the float's value is emitted directly into the token but no suffix is
1250 /// used, so it may be inferred to be a `f64` later in the compiler.
1251 /// Literals created from negative numbers might not survive rountrips through
1252 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1256 /// This function requires that the specified float is finite, for
1257 /// example if it is infinity or NaN this function will panic.
1258 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1259 pub fn f32_unsuffixed(n: f32) -> Literal {
1261 panic!("Invalid float literal {n}");
1263 let mut repr = n.to_string();
1264 if !repr.contains('.') {
1265 repr.push_str(".0");
1267 Literal::new(bridge::LitKind::Float, &repr, None)
1270 /// Creates a new suffixed floating-point literal.
1272 /// This constructor will create a literal like `1.0f32` where the value
1273 /// specified is the preceding part of the token and `f32` is the suffix of
1274 /// the token. This token will always be inferred to be an `f32` in the
1276 /// Literals created from negative numbers might not survive rountrips through
1277 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1281 /// This function requires that the specified float is finite, for
1282 /// example if it is infinity or NaN this function will panic.
1283 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1284 pub fn f32_suffixed(n: f32) -> Literal {
1286 panic!("Invalid float literal {n}");
1288 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1291 /// Creates a new unsuffixed floating-point literal.
1293 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1294 /// the float's value is emitted directly into the token but no suffix is
1295 /// used, so it may be inferred to be a `f64` later in the compiler.
1296 /// Literals created from negative numbers might not survive rountrips through
1297 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1301 /// This function requires that the specified float is finite, for
1302 /// example if it is infinity or NaN this function will panic.
1303 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1304 pub fn f64_unsuffixed(n: f64) -> Literal {
1306 panic!("Invalid float literal {n}");
1308 let mut repr = n.to_string();
1309 if !repr.contains('.') {
1310 repr.push_str(".0");
1312 Literal::new(bridge::LitKind::Float, &repr, None)
1315 /// Creates a new suffixed floating-point literal.
1317 /// This constructor will create a literal like `1.0f64` where the value
1318 /// specified is the preceding part of the token and `f64` is the suffix of
1319 /// the token. This token will always be inferred to be an `f64` in the
1321 /// Literals created from negative numbers might not survive rountrips through
1322 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1326 /// This function requires that the specified float is finite, for
1327 /// example if it is infinity or NaN this function will panic.
1328 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1329 pub fn f64_suffixed(n: f64) -> Literal {
1331 panic!("Invalid float literal {n}");
1333 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1337 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1338 pub fn string(string: &str) -> Literal {
1339 let quoted = format!("{:?}", string);
1340 assert!(quoted.starts_with('"') && quoted.ends_with('"'));
1341 let symbol = "ed[1..quoted.len() - 1];
1342 Literal::new(bridge::LitKind::Str, symbol, None)
1345 /// Character literal.
1346 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1347 pub fn character(ch: char) -> Literal {
1348 let quoted = format!("{:?}", ch);
1349 assert!(quoted.starts_with('\'') && quoted.ends_with('\''));
1350 let symbol = "ed[1..quoted.len() - 1];
1351 Literal::new(bridge::LitKind::Char, symbol, None)
1354 /// Byte string literal.
1355 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1356 pub fn byte_string(bytes: &[u8]) -> Literal {
1357 let string = bytes.escape_ascii().to_string();
1358 Literal::new(bridge::LitKind::ByteStr, &string, None)
1361 /// Returns the span encompassing this literal.
1362 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1363 pub fn span(&self) -> Span {
1367 /// Configures the span associated for this literal.
1368 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1369 pub fn set_span(&mut self, span: Span) {
1370 self.0.span = span.0;
1373 /// Returns a `Span` that is a subset of `self.span()` containing only the
1374 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1375 /// span is outside the bounds of `self`.
1376 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1377 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1378 // occur elsewhere when the source text is printed.
1379 // FIXME(SergioBenitez): there is no way for the user to know what
1380 // `self.span()` actually maps to, so this method can currently only be
1381 // called blindly. For example, `to_string()` for the character 'c' returns
1382 // "'\u{63}'"; there is no way for the user to know whether the source text
1383 // was 'c' or whether it was '\u{63}'.
1384 #[unstable(feature = "proc_macro_span", issue = "54725")]
1385 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1386 self.0.span.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span)
1389 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1390 self.0.symbol.with(|symbol| match self.0.suffix {
1391 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1392 None => f(symbol, ""),
1396 /// Invokes the callback with a `&[&str]` consisting of each part of the
1397 /// literal's representation. This is done to allow the `ToString` and
1398 /// `Display` implementations to borrow references to symbol values, and
1399 /// both be optimized to reduce overhead.
1400 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1401 /// Returns a string containing exactly `num` '#' characters.
1402 /// Uses a 256-character source string literal which is always safe to
1403 /// index with a `u8` index.
1404 fn get_hashes_str(num: u8) -> &'static str {
1405 const HASHES: &str = "\
1406 ################################################################\
1407 ################################################################\
1408 ################################################################\
1409 ################################################################\
1411 const _: () = assert!(HASHES.len() == 256);
1412 &HASHES[..num as usize]
1415 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1416 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1417 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1418 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1419 bridge::LitKind::StrRaw(n) => {
1420 let hashes = get_hashes_str(n);
1421 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1423 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1424 bridge::LitKind::ByteStrRaw(n) => {
1425 let hashes = get_hashes_str(n);
1426 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1428 _ => f(&[symbol, suffix]),
1433 /// Parse a single literal from its stringified representation.
1435 /// In order to parse successfully, the input string must not contain anything
1436 /// but the literal token. Specifically, it must not contain whitespace or
1437 /// comments in addition to the literal.
1439 /// The resulting literal token will have a `Span::call_site()` span.
1441 /// NOTE: some errors may cause panics instead of returning `LexError`. We
1442 /// reserve the right to change these errors into `LexError`s later.
1443 #[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1444 impl FromStr for Literal {
1445 type Err = LexError;
1447 fn from_str(src: &str) -> Result<Self, LexError> {
1448 match bridge::client::FreeFunctions::literal_from_str(src) {
1449 Ok(literal) => Ok(Literal(literal)),
1450 Err(()) => Err(LexError),
1455 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1456 impl ToString for Literal {
1457 fn to_string(&self) -> String {
1458 self.with_stringify_parts(|parts| parts.concat())
1462 /// Prints the literal as a string that should be losslessly convertible
1463 /// back into the same literal (except for possible rounding for floating point literals).
1464 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1465 impl fmt::Display for Literal {
1466 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1467 self.with_stringify_parts(|parts| {
1469 fmt::Display::fmt(part, f)?;
1476 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1477 impl fmt::Debug for Literal {
1478 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1479 f.debug_struct("Literal")
1480 // format the kind on one line even in {:#?} mode
1481 .field("kind", &format_args!("{:?}", &self.0.kind))
1482 .field("symbol", &self.0.symbol)
1483 // format `Some("...")` on one line even in {:#?} mode
1484 .field("suffix", &format_args!("{:?}", &self.0.suffix))
1485 .field("span", &self.0.span)
1490 /// Tracked access to environment variables.
1491 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1492 pub mod tracked_env {
1493 use std::env::{self, VarError};
1494 use std::ffi::OsStr;
1496 /// Retrieve an environment variable and add it to build dependency info.
1497 /// The build system executing the compiler will know that the variable was accessed during
1498 /// compilation, and will be able to rerun the build when the value of that variable changes.
1499 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1500 /// standard library, except that the argument must be UTF-8.
1501 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1502 pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1503 let key: &str = key.as_ref();
1504 let value = env::var(key);
1505 crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());
1510 /// Tracked access to additional files.
1511 #[unstable(feature = "track_path", issue = "99515")]
1512 pub mod tracked_path {
1514 /// Track a file explicitly.
1516 /// Commonly used for tracking asset preprocessing.
1517 #[unstable(feature = "track_path", issue = "99515")]
1518 pub fn path<P: AsRef<str>>(path: P) {
1519 let path: &str = path.as_ref();
1520 crate::bridge::client::FreeFunctions::track_path(path);