1//! A support library for macro authors when defining new macros.
2//!
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]`.
7//!
8//! See [the book] for more.
9//!
10//! [the book]: ../book/ch19-06-macros.html#procedural-macros-for-generating-code-from-attributes
1112#![stable(feature = "proc_macro_lib", since = "1.15.0")]
13#![deny(missing_docs)]
14#![doc(
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)))
19)]
20#![doc(rust_logo)]
21#![feature(rustdoc_internals)]
22#![feature(staged_api)]
23#![feature(allow_internal_unstable)]
24#![feature(decl_macro)]
25#![feature(negative_impls)]
26#![feature(panic_can_unwind)]
27#![feature(restricted_std)]
28#![feature(rustc_attrs)]
29#![feature(extend_one)]
30#![feature(mem_conjure_zst)]
31#![recursion_limit = "256"]
32#![allow(internal_features)]
33#![deny(ffi_unwind_calls)]
34#![allow(rustc::internal)] // Can't use FxHashMap when compiled as part of the standard library
35#![warn(rustdoc::unescaped_backticks)]
36#![warn(unreachable_pub)]
37#![deny(unsafe_op_in_unsafe_fn)]
3839#[unstable(feature = "proc_macro_internals", issue = "27812")]
40#[doc(hidden)]
41pub mod bridge;
4243mod diagnostic;
44mod escape;
45mod to_tokens;
4647use core::ops::BitOr;
48use std::ffi::CStr;
49use std::ops::{Range, RangeBounds};
50use std::path::PathBuf;
51use std::str::FromStr;
52use std::{error, fmt};
5354#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
55pub use diagnostic::{Diagnostic, Level, MultiSpan};
56#[unstable(feature = "proc_macro_value", issue = "136652")]
57pub use rustc_literal_escaper::EscapeError;
58use rustc_literal_escaper::{
59MixedUnit, unescape_byte, unescape_byte_str, unescape_c_str, unescape_char, unescape_str,
60};
61#[unstable(feature = "proc_macro_totokens", issue = "130977")]
62pub use to_tokens::ToTokens;
6364use crate::bridge::client::Methodsas BridgeMethods;
65use crate::escape::{EscapeOptions, escape_bytes};
6667/// Errors returned when trying to retrieve a literal unescaped value.
68#[unstable(feature = "proc_macro_value", issue = "136652")]
69#[derive(#[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::fmt::Debug for ConversionErrorKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ConversionErrorKind::FailedToUnescape(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"FailedToUnescape", &__self_0),
ConversionErrorKind::InvalidLiteralKind =>
::core::fmt::Formatter::write_str(f, "InvalidLiteralKind"),
}
}
}Debug, #[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::cmp::PartialEq for ConversionErrorKind {
#[inline]
fn eq(&self, other: &ConversionErrorKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ConversionErrorKind::FailedToUnescape(__self_0),
ConversionErrorKind::FailedToUnescape(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::cmp::Eq for ConversionErrorKind {
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<EscapeError>;
}
}Eq)]
70pub enum ConversionErrorKind {
71/// The literal failed to be escaped, take a look at [`EscapeError`] for more information.
72FailedToUnescape(EscapeError),
73/// Trying to convert a literal with the wrong type.
74InvalidLiteralKind,
75}
7677/// Determines whether proc_macro has been made accessible to the currently
78/// running program.
79///
80/// The proc_macro crate is only intended for use inside the implementation of
81/// procedural macros. All the functions in this crate panic if invoked from
82/// outside of a procedural macro, such as from a build script or unit test or
83/// ordinary Rust binary.
84///
85/// With consideration for Rust libraries that are designed to support both
86/// macro and non-macro use cases, `proc_macro::is_available()` provides a
87/// non-panicking way to detect whether the infrastructure required to use the
88/// API of proc_macro is presently available. Returns true if invoked from
89/// inside of a procedural macro, false if invoked from any other binary.
90#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
91pub fn is_available() -> bool {
92 bridge::client::is_available()
93}
9495/// The main type provided by this crate, representing an abstract stream of
96/// tokens, or, more specifically, a sequence of token trees.
97/// The type provides interfaces for iterating over those token trees and, conversely,
98/// collecting a number of token trees into one stream.
99///
100/// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
101/// and `#[proc_macro_derive]` definitions.
102#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
103#[stable(feature = "proc_macro_lib", since = "1.15.0")]
104#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib", since = "1.15.0")]
impl ::core::clone::Clone for TokenStream {
#[inline]
fn clone(&self) -> TokenStream {
TokenStream(::core::clone::Clone::clone(&self.0))
}
}Clone)]
105pub struct TokenStream(Option<bridge::client::TokenStream>);
106107#[stable(feature = "proc_macro_lib", since = "1.15.0")]
108impl !Sendfor TokenStream {}
109#[stable(feature = "proc_macro_lib", since = "1.15.0")]
110impl !Syncfor TokenStream {}
111112/// Error returned from `TokenStream::from_str`.
113///
114/// The contained error message is explicitly not guaranteed to be stable in any way,
115/// and may change between Rust versions or across compilations.
116#[stable(feature = "proc_macro_lib", since = "1.15.0")]
117#[non_exhaustive]
118#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib", since = "1.15.0")]
impl ::core::fmt::Debug for LexError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "LexError",
&&self.0)
}
}Debug)]
119pub struct LexError(String);
120121#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
122impl fmt::Displayfor LexError {
123fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124f.write_str(&self.0)
125 }
126}
127128#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
129impl error::Errorfor LexError {}
130131#[stable(feature = "proc_macro_lib", since = "1.15.0")]
132impl !Sendfor LexError {}
133#[stable(feature = "proc_macro_lib", since = "1.15.0")]
134impl !Syncfor LexError {}
135136/// Error returned from `TokenStream::expand_expr`.
137#[unstable(feature = "proc_macro_expand", issue = "90765")]
138#[non_exhaustive]
139#[derive(#[automatically_derived]
#[unstable(feature = "proc_macro_expand", issue = "90765")]
impl ::core::fmt::Debug for ExpandError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "ExpandError")
}
}Debug)]
140pub struct ExpandError;
141142#[unstable(feature = "proc_macro_expand", issue = "90765")]
143impl fmt::Displayfor ExpandError {
144fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145f.write_str("macro expansion failed")
146 }
147}
148149#[unstable(feature = "proc_macro_expand", issue = "90765")]
150impl error::Errorfor ExpandError {}
151152#[unstable(feature = "proc_macro_expand", issue = "90765")]
153impl !Sendfor ExpandError {}
154155#[unstable(feature = "proc_macro_expand", issue = "90765")]
156impl !Syncfor ExpandError {}
157158impl TokenStream {
159/// Returns an empty `TokenStream` containing no token trees.
160#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
161pub fn new() -> TokenStream {
162TokenStream(None)
163 }
164165/// Checks if this `TokenStream` is empty.
166#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
167pub fn is_empty(&self) -> bool {
168self.0.as_ref().map(|h| BridgeMethods::ts_is_empty(h)).unwrap_or(true)
169 }
170171/// Parses this `TokenStream` as an expression and attempts to expand any
172 /// macros within it. Returns the expanded `TokenStream`.
173 ///
174 /// Currently only expressions expanding to literals will succeed, although
175 /// this may be relaxed in the future.
176 ///
177 /// NOTE: In error conditions, `expand_expr` may leave macros unexpanded,
178 /// report an error, failing compilation, and/or return an `Err(..)`. The
179 /// specific behavior for any error condition, and what conditions are
180 /// considered errors, is unspecified and may change in the future.
181#[unstable(feature = "proc_macro_expand", issue = "90765")]
182pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
183let stream = self.0.as_ref().ok_or(ExpandError)?;
184match BridgeMethods::ts_expand_expr(stream) {
185Ok(stream) => Ok(TokenStream(Some(stream))),
186Err(_) => Err(ExpandError),
187 }
188 }
189}
190191/// Attempts to break the string into tokens and parse those tokens into a token stream.
192/// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
193/// or characters not existing in the language.
194/// All tokens in the parsed stream get `Span::call_site()` spans.
195///
196/// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
197/// change these errors into `LexError`s later.
198#[stable(feature = "proc_macro_lib", since = "1.15.0")]
199impl FromStrfor TokenStream {
200type Err = LexError;
201202fn from_str(src: &str) -> Result<TokenStream, LexError> {
203Ok(TokenStream(Some(BridgeMethods::ts_from_str(src).map_err(LexError)?)))
204 }
205}
206207/// Prints the token stream as a string that is supposed to be losslessly convertible back
208/// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
209/// with `Delimiter::None` delimiters and negative numeric literals.
210///
211/// Note: the exact form of the output is subject to change, e.g. there might
212/// be changes in the whitespace used between tokens. Therefore, you should
213/// *not* do any kind of simple substring matching on the output string (as
214/// produced by `to_string`) to implement a proc macro, because that matching
215/// might stop working if such changes happen. Instead, you should work at the
216/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
217/// `TokenTree::Punct`, or `TokenTree::Literal`.
218#[stable(feature = "proc_macro_lib", since = "1.15.0")]
219impl fmt::Displayfor TokenStream {
220fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221match &self.0 {
222Some(ts) => f.write_fmt(format_args!("{0}", BridgeMethods::ts_to_string(ts)))write!(f, "{}", BridgeMethods::ts_to_string(ts)),
223None => Ok(()),
224 }
225 }
226}
227228/// Prints tokens in a form convenient for debugging.
229#[stable(feature = "proc_macro_lib", since = "1.15.0")]
230impl fmt::Debugfor TokenStream {
231fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232f.write_str("TokenStream ")?;
233f.debug_list().entries(self.clone()).finish()
234 }
235}
236237#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
238impl Defaultfor TokenStream {
239fn default() -> Self {
240TokenStream::new()
241 }
242}
243244#[unstable(feature = "proc_macro_quote", issue = "54722")]
245pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
246247fn tree_to_bridge_tree(
248 tree: TokenTree,
249) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
250match tree {
251 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
252 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
253 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
254 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
255 }
256}
257258/// Creates a token stream containing a single token tree.
259#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
260impl From<TokenTree> for TokenStream {
261fn from(tree: TokenTree) -> TokenStream {
262TokenStream(Some(BridgeMethods::ts_from_token_tree(tree_to_bridge_tree(tree))))
263 }
264}
265266/// Non-generic helper for implementing `FromIterator<TokenTree>` and
267/// `Extend<TokenTree>` with less monomorphization in calling crates.
268struct ConcatTreesHelper {
269 trees: Vec<
270 bridge::TokenTree<
271 bridge::client::TokenStream,
272 bridge::client::Span,
273 bridge::client::Symbol,
274 >,
275 >,
276}
277278impl ConcatTreesHelper {
279fn new(capacity: usize) -> Self {
280ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
281 }
282283fn push(&mut self, tree: TokenTree) {
284self.trees.push(tree_to_bridge_tree(tree));
285 }
286287fn build(self) -> TokenStream {
288if self.trees.is_empty() {
289TokenStream(None)
290 } else {
291TokenStream(Some(BridgeMethods::ts_concat_trees(None, self.trees)))
292 }
293 }
294295fn append_to(self, stream: &mut TokenStream) {
296if self.trees.is_empty() {
297return;
298 }
299stream.0 = Some(BridgeMethods::ts_concat_trees(stream.0.take(), self.trees))
300 }
301}
302303/// Non-generic helper for implementing `FromIterator<TokenStream>` and
304/// `Extend<TokenStream>` with less monomorphization in calling crates.
305struct ConcatStreamsHelper {
306 streams: Vec<bridge::client::TokenStream>,
307}
308309impl ConcatStreamsHelper {
310fn new(capacity: usize) -> Self {
311ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
312 }
313314fn push(&mut self, stream: TokenStream) {
315if let Some(stream) = stream.0 {
316self.streams.push(stream);
317 }
318 }
319320fn build(mut self) -> TokenStream {
321if self.streams.len() <= 1 {
322TokenStream(self.streams.pop())
323 } else {
324TokenStream(Some(BridgeMethods::ts_concat_streams(None, self.streams)))
325 }
326 }
327328fn append_to(mut self, stream: &mut TokenStream) {
329if self.streams.is_empty() {
330return;
331 }
332let base = stream.0.take();
333if base.is_none() && self.streams.len() == 1 {
334stream.0 = self.streams.pop();
335 } else {
336stream.0 = Some(BridgeMethods::ts_concat_streams(base, self.streams));
337 }
338 }
339}
340341/// Collects a number of token trees into a single stream.
342#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
343impl FromIterator<TokenTree> for TokenStream {
344fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
345let iter = trees.into_iter();
346let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
347iter.for_each(|tree| builder.push(tree));
348builder.build()
349 }
350}
351352/// A "flattening" operation on token streams, collects token trees
353/// from multiple token streams into a single stream.
354#[stable(feature = "proc_macro_lib", since = "1.15.0")]
355impl FromIterator<TokenStream> for TokenStream {
356fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
357let iter = streams.into_iter();
358let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
359iter.for_each(|stream| builder.push(stream));
360builder.build()
361 }
362}
363364#[stable(feature = "token_stream_extend", since = "1.30.0")]
365impl Extend<TokenTree> for TokenStream {
366fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
367let iter = trees.into_iter();
368let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
369iter.for_each(|tree| builder.push(tree));
370builder.append_to(self);
371 }
372}
373374#[stable(feature = "token_stream_extend", since = "1.30.0")]
375impl Extend<TokenStream> for TokenStream {
376fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
377let iter = streams.into_iter();
378let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
379iter.for_each(|stream| builder.push(stream));
380builder.append_to(self);
381 }
382}
383384macro_rules!extend_items {
385 ($($item:ident)*) => {
386 $(
387#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
388impl Extend<$item> for TokenStream {
389fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
390self.extend(iter.into_iter().map(TokenTree::$item));
391 }
392 }
393 )*
394 };
395}
396397#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
impl Extend<Ident> for TokenStream {
fn extend<T: IntoIterator<Item = Ident>>(&mut self, iter: T) {
self.extend(iter.into_iter().map(TokenTree::Ident));
}
}extend_items!(Group Literal Punct Ident);
398399/// Public implementation details for the `TokenStream` type, such as iterators.
400#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
401pub mod token_stream {
402use crate::{BridgeMethods, Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
403404/// An iterator over `TokenStream`'s `TokenTree`s.
405 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
406 /// and returns whole groups as token trees.
407#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for IntoIter {
#[inline]
fn clone(&self) -> IntoIter {
IntoIter(::core::clone::Clone::clone(&self.0))
}
}Clone)]
408 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
409pub struct IntoIter(
410 std::vec::IntoIter<
411 bridge::TokenTree<
412 bridge::client::TokenStream,
413 bridge::client::Span,
414 bridge::client::Symbol,
415 >,
416 >,
417 );
418419#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
420impl Iteratorfor IntoIter {
421type Item = TokenTree;
422423fn next(&mut self) -> Option<TokenTree> {
424self.0.next().map(|tree| match tree {
425 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
426 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
427 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
428 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
429 })
430 }
431432fn size_hint(&self) -> (usize, Option<usize>) {
433self.0.size_hint()
434 }
435436fn count(self) -> usize {
437self.0.count()
438 }
439 }
440441#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
442impl IntoIteratorfor TokenStream {
443type Item = TokenTree;
444type IntoIter = IntoIter;
445446fn into_iter(self) -> IntoIter {
447IntoIter(
448self.0.map(|v| BridgeMethods::ts_into_trees(v)).unwrap_or_default().into_iter(),
449 )
450 }
451 }
452}
453454/// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
455/// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
456/// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
457///
458/// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
459/// To quote `$` itself, use `$$`.
460#[unstable(feature = "proc_macro_quote", issue = "54722")]
461#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
462#[rustc_builtin_macro]
463pub macro quote($($t:tt)*) {
464/* compiler built-in */
465}
466467#[unstable(feature = "proc_macro_internals", issue = "27812")]
468#[doc(hidden)]
469mod quote;
470471/// A region of source code, along with macro expansion information.
472#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
473#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::marker::Copy for Span { }Copy, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Span {
#[inline]
fn clone(&self) -> Span {
let _: ::core::clone::AssertParamIsClone<bridge::client::Span>;
*self
}
}Clone)]
474pub struct Span(bridge::client::Span);
475476#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
477impl !Sendfor Span {}
478#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
479impl !Syncfor Span {}
480481macro_rules!diagnostic_method {
482 ($name:ident, $level:expr) => {
483/// Creates a new `Diagnostic` with the given `message` at the span
484 /// `self`.
485#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
486pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
487 Diagnostic::spanned(self, $level, message)
488 }
489 };
490}
491492impl Span {
493/// A span that resolves at the macro definition site.
494#[unstable(feature = "proc_macro_def_site", issue = "54724")]
495pub fn def_site() -> Span {
496Span(bridge::client::Span::def_site())
497 }
498499/// The span of the invocation of the current procedural macro.
500 /// Identifiers created with this span will be resolved as if they were written
501 /// directly at the macro call location (call-site hygiene) and other code
502 /// at the macro call site will be able to refer to them as well.
503#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
504pub fn call_site() -> Span {
505Span(bridge::client::Span::call_site())
506 }
507508/// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
509 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
510 /// call site (everything else).
511 /// The span location is taken from the call-site.
512#[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
513pub fn mixed_site() -> Span {
514Span(bridge::client::Span::mixed_site())
515 }
516517/// The `Span` for the tokens in the previous macro expansion from which
518 /// `self` was generated from, if any.
519#[unstable(feature = "proc_macro_span", issue = "54725")]
520pub fn parent(&self) -> Option<Span> {
521BridgeMethods::span_parent(self.0).map(Span)
522 }
523524/// The span for the origin source code that `self` was generated from. If
525 /// this `Span` wasn't generated from other macro expansions then the return
526 /// value is the same as `*self`.
527#[unstable(feature = "proc_macro_span", issue = "54725")]
528pub fn source(&self) -> Span {
529Span(BridgeMethods::span_source(self.0))
530 }
531532/// Returns the span's byte position range in the source file.
533#[unstable(feature = "proc_macro_span", issue = "54725")]
534pub fn byte_range(&self) -> Range<usize> {
535BridgeMethods::span_byte_range(self.0)
536 }
537538/// Creates an empty span pointing to directly before this span.
539#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
540pub fn start(&self) -> Span {
541Span(BridgeMethods::span_start(self.0))
542 }
543544/// Creates an empty span pointing to directly after this span.
545#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
546pub fn end(&self) -> Span {
547Span(BridgeMethods::span_end(self.0))
548 }
549550/// The one-indexed line of the source file where the span starts.
551 ///
552 /// To obtain the line of the span's end, use `span.end().line()`.
553#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
554pub fn line(&self) -> usize {
555BridgeMethods::span_line(self.0)
556 }
557558/// The one-indexed column of the source file where the span starts.
559 ///
560 /// To obtain the column of the span's end, use `span.end().column()`.
561#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
562pub fn column(&self) -> usize {
563BridgeMethods::span_column(self.0)
564 }
565566/// The path to the source file in which this span occurs, for display purposes.
567 ///
568 /// This might not correspond to a valid file system path.
569 /// It might be remapped (e.g. `"/src/lib.rs"`) or an artificial path (e.g. `"<command line>"`).
570#[stable(feature = "proc_macro_span_file", since = "1.88.0")]
571pub fn file(&self) -> String {
572BridgeMethods::span_file(self.0)
573 }
574575/// The path to the source file in which this span occurs on the local file system.
576 ///
577 /// This is the actual path on disk. It is unaffected by path remapping.
578 ///
579 /// This path should not be embedded in the output of the macro; prefer `file()` instead.
580#[stable(feature = "proc_macro_span_file", since = "1.88.0")]
581pub fn local_file(&self) -> Option<PathBuf> {
582BridgeMethods::span_local_file(self.0).map(PathBuf::from)
583 }
584585/// Creates a new span encompassing `self` and `other`.
586 ///
587 /// Returns `None` if `self` and `other` are from different files.
588#[unstable(feature = "proc_macro_span", issue = "54725")]
589pub fn join(&self, other: Span) -> Option<Span> {
590BridgeMethods::span_join(self.0, other.0).map(Span)
591 }
592593/// Creates a new span with the same line/column information as `self` but
594 /// that resolves symbols as though it were at `other`.
595#[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
596pub fn resolved_at(&self, other: Span) -> Span {
597Span(BridgeMethods::span_resolved_at(self.0, other.0))
598 }
599600/// Creates a new span with the same name resolution behavior as `self` but
601 /// with the line/column information of `other`.
602#[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
603pub fn located_at(&self, other: Span) -> Span {
604other.resolved_at(*self)
605 }
606607/// Compares two spans to see if they're equal.
608#[unstable(feature = "proc_macro_span", issue = "54725")]
609pub fn eq(&self, other: &Span) -> bool {
610self.0 == other.0
611}
612613/// Returns the source text behind a span. This preserves the original source
614 /// code, including spaces and comments. It only returns a result if the span
615 /// corresponds to real source code.
616 ///
617 /// Note: The observable result of a macro should only rely on the tokens and
618 /// not on this source text. The result of this function is a best effort to
619 /// be used for diagnostics only.
620#[stable(feature = "proc_macro_source_text", since = "1.66.0")]
621pub fn source_text(&self) -> Option<String> {
622BridgeMethods::span_source_text(self.0)
623 }
624625// Used by the implementation of `Span::quote`
626#[doc(hidden)]
627 #[unstable(feature = "proc_macro_internals", issue = "27812")]
628pub fn save_span(&self) -> usize {
629BridgeMethods::span_save_span(self.0)
630 }
631632// Used by the implementation of `Span::quote`
633#[doc(hidden)]
634 #[unstable(feature = "proc_macro_internals", issue = "27812")]
635pub fn recover_proc_macro_span(id: usize) -> Span {
636Span(BridgeMethods::span_recover_proc_macro_span(id))
637 }
638639String
Self
self
T
message
Diagnostic
Diagnostic::spanned(self, Level::Error, message);diagnostic_method!(error, Level::Error);
640String
Self
self
T
message
Diagnostic
Diagnostic::spanned(self, Level::Warning, message);diagnostic_method!(warning, Level::Warning);
641String
Self
self
T
message
Diagnostic
Diagnostic::spanned(self, Level::Note, message);diagnostic_method!(note, Level::Note);
642String
Self
self
T
message
Diagnostic
Diagnostic::spanned(self, Level::Help, message);diagnostic_method!(help, Level::Help);
643}
644645/// Prints a span in a form convenient for debugging.
646#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
647impl fmt::Debugfor Span {
648fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
649self.0.fmt(f)
650 }
651}
652653/// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
654#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
655#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for TokenTree {
#[inline]
fn clone(&self) -> TokenTree {
match self {
TokenTree::Group(__self_0) =>
TokenTree::Group(::core::clone::Clone::clone(__self_0)),
TokenTree::Ident(__self_0) =>
TokenTree::Ident(::core::clone::Clone::clone(__self_0)),
TokenTree::Punct(__self_0) =>
TokenTree::Punct(::core::clone::Clone::clone(__self_0)),
TokenTree::Literal(__self_0) =>
TokenTree::Literal(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
656pub enum TokenTree {
657/// A token stream surrounded by bracket delimiters.
658#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
659Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
660/// An identifier.
661#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
662Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
663/// A single punctuation character (`+`, `,`, `$`, etc.).
664#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
665Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
666/// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
667#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
668Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
669}
670671#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
672impl !Sendfor TokenTree {}
673#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
674impl !Syncfor TokenTree {}
675676impl TokenTree {
677/// Returns the span of this tree, delegating to the `span` method of
678 /// the contained token or a delimited stream.
679#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
680pub fn span(&self) -> Span {
681match *self {
682 TokenTree::Group(ref t) => t.span(),
683 TokenTree::Ident(ref t) => t.span(),
684 TokenTree::Punct(ref t) => t.span(),
685 TokenTree::Literal(ref t) => t.span(),
686 }
687 }
688689/// Configures the span for *only this token*.
690 ///
691 /// Note that if this token is a `Group` then this method will not configure
692 /// the span of each of the internal tokens, this will simply delegate to
693 /// the `set_span` method of each variant.
694#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
695pub fn set_span(&mut self, span: Span) {
696match *self {
697 TokenTree::Group(ref mut t) => t.set_span(span),
698 TokenTree::Ident(ref mut t) => t.set_span(span),
699 TokenTree::Punct(ref mut t) => t.set_span(span),
700 TokenTree::Literal(ref mut t) => t.set_span(span),
701 }
702 }
703}
704705/// Prints token tree in a form convenient for debugging.
706#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
707impl fmt::Debugfor TokenTree {
708fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
709// Each of these has the name in the struct type in the derived debug,
710 // so don't bother with an extra layer of indirection
711match *self {
712 TokenTree::Group(ref tt) => tt.fmt(f),
713 TokenTree::Ident(ref tt) => tt.fmt(f),
714 TokenTree::Punct(ref tt) => tt.fmt(f),
715 TokenTree::Literal(ref tt) => tt.fmt(f),
716 }
717 }
718}
719720#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
721impl From<Group> for TokenTree {
722fn from(g: Group) -> TokenTree {
723 TokenTree::Group(g)
724 }
725}
726727#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
728impl From<Ident> for TokenTree {
729fn from(g: Ident) -> TokenTree {
730 TokenTree::Ident(g)
731 }
732}
733734#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
735impl From<Punct> for TokenTree {
736fn from(g: Punct) -> TokenTree {
737 TokenTree::Punct(g)
738 }
739}
740741#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
742impl From<Literal> for TokenTree {
743fn from(g: Literal) -> TokenTree {
744 TokenTree::Literal(g)
745 }
746}
747748/// Prints the token tree as a string that is supposed to be losslessly convertible back
749/// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
750/// with `Delimiter::None` delimiters and negative numeric literals.
751///
752/// Note: the exact form of the output is subject to change, e.g. there might
753/// be changes in the whitespace used between tokens. Therefore, you should
754/// *not* do any kind of simple substring matching on the output string (as
755/// produced by `to_string`) to implement a proc macro, because that matching
756/// might stop working if such changes happen. Instead, you should work at the
757/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
758/// `TokenTree::Punct`, or `TokenTree::Literal`.
759#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
760impl fmt::Displayfor TokenTree {
761fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
762match self {
763 TokenTree::Group(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
764 TokenTree::Ident(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
765 TokenTree::Punct(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
766 TokenTree::Literal(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
767 }
768 }
769}
770771/// A delimited token stream.
772///
773/// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
774#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Group {
#[inline]
fn clone(&self) -> Group { Group(::core::clone::Clone::clone(&self.0)) }
}Clone)]
775#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
776pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
777778#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
779impl !Sendfor Group {}
780#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
781impl !Syncfor Group {}
782783/// Describes how a sequence of token trees is delimited.
784#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::marker::Copy for Delimiter { }Copy, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Delimiter {
#[inline]
fn clone(&self) -> Delimiter { *self }
}Clone, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::fmt::Debug for Delimiter {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Delimiter::Parenthesis => "Parenthesis",
Delimiter::Brace => "Brace",
Delimiter::Bracket => "Bracket",
Delimiter::None => "None",
})
}
}Debug, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::PartialEq for Delimiter {
#[inline]
fn eq(&self, other: &Delimiter) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::Eq for Delimiter {
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
785#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
786pub enum Delimiter {
787/// `( ... )`
788#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
789Parenthesis,
790/// `{ ... }`
791#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
792Brace,
793/// `[ ... ]`
794#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
795Bracket,
796/// `∅ ... ∅`
797 /// An invisible delimiter, that may, for example, appear around tokens coming from a
798 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
799 /// `$var * 3` where `$var` is `1 + 2`.
800 /// Invisible delimiters might not survive roundtrip of a token stream through a string.
801 ///
802 /// <div class="warning">
803 ///
804 /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
805 /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
806 /// of a proc_macro macro are preserved, and only in very specific circumstances.
807 /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
808 /// operator priorities as indicated above. The other `Delimiter` variants should be used
809 /// instead in this context. This is a rustc bug. For details, see
810 /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
811 ///
812 /// </div>
813#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
814None,
815}
816817impl Group {
818/// Creates a new `Group` with the given delimiter and token stream.
819 ///
820 /// This constructor will set the span for this group to
821 /// `Span::call_site()`. To change the span you can use the `set_span`
822 /// method below.
823#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
824pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
825Group(bridge::Group {
826delimiter,
827 stream: stream.0,
828 span: bridge::DelimSpan::from_single(Span::call_site().0),
829 })
830 }
831832/// Returns the delimiter of this `Group`
833#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
834pub fn delimiter(&self) -> Delimiter {
835self.0.delimiter
836 }
837838/// Returns the `TokenStream` of tokens that are delimited in this `Group`.
839 ///
840 /// Note that the returned token stream does not include the delimiter
841 /// returned above.
842#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
843pub fn stream(&self) -> TokenStream {
844TokenStream(self.0.stream.clone())
845 }
846847/// Returns the span for the delimiters of this token stream, spanning the
848 /// entire `Group`.
849 ///
850 /// ```text
851 /// pub fn span(&self) -> Span {
852 /// ^^^^^^^
853 /// ```
854#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
855pub fn span(&self) -> Span {
856Span(self.0.span.entire)
857 }
858859/// Returns the span pointing to the opening delimiter of this group.
860 ///
861 /// ```text
862 /// pub fn span_open(&self) -> Span {
863 /// ^
864 /// ```
865#[stable(feature = "proc_macro_group_span", since = "1.55.0")]
866pub fn span_open(&self) -> Span {
867Span(self.0.span.open)
868 }
869870/// Returns the span pointing to the closing delimiter of this group.
871 ///
872 /// ```text
873 /// pub fn span_close(&self) -> Span {
874 /// ^
875 /// ```
876#[stable(feature = "proc_macro_group_span", since = "1.55.0")]
877pub fn span_close(&self) -> Span {
878Span(self.0.span.close)
879 }
880881/// Configures the span for this `Group`'s delimiters, but not its internal
882 /// tokens.
883 ///
884 /// This method will **not** set the span of all the internal tokens spanned
885 /// by this group, but rather it will only set the span of the delimiter
886 /// tokens at the level of the `Group`.
887#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
888pub fn set_span(&mut self, span: Span) {
889self.0.span = bridge::DelimSpan::from_single(span.0);
890 }
891}
892893/// Prints the group as a string that should be losslessly convertible back
894/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
895/// with `Delimiter::None` delimiters.
896#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
897impl fmt::Displayfor Group {
898fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
899f.write_fmt(format_args!("{0}",
TokenStream::from(TokenTree::from(self.clone()))))write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))900 }
901}
902903#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
904impl fmt::Debugfor Group {
905fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
906f.debug_struct("Group")
907 .field("delimiter", &self.delimiter())
908 .field("stream", &self.stream())
909 .field("span", &self.span())
910 .finish()
911 }
912}
913914/// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
915///
916/// Multi-character operators like `+=` are represented as two instances of `Punct` with different
917/// forms of `Spacing` returned.
918#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
919#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Punct {
#[inline]
fn clone(&self) -> Punct { Punct(::core::clone::Clone::clone(&self.0)) }
}Clone)]
920pub struct Punct(bridge::Punct<bridge::client::Span>);
921922#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
923impl !Sendfor Punct {}
924#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
925impl !Syncfor Punct {}
926927/// Indicates whether a `Punct` token can join with the following token
928/// to form a multi-character operator.
929#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::marker::Copy for Spacing { }Copy, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Spacing {
#[inline]
fn clone(&self) -> Spacing { *self }
}Clone, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::fmt::Debug for Spacing {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Spacing::Joint => "Joint",
Spacing::Alone => "Alone",
})
}
}Debug, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::PartialEq for Spacing {
#[inline]
fn eq(&self, other: &Spacing) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::Eq for Spacing {
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
930#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
931pub enum Spacing {
932/// A `Punct` token can join with the following token to form a multi-character operator.
933 ///
934 /// In token streams constructed using proc macro interfaces, `Joint` punctuation tokens can be
935 /// followed by any other tokens. However, in token streams parsed from source code, the
936 /// compiler will only set spacing to `Joint` in the following cases.
937 /// - When a `Punct` is immediately followed by another `Punct` without a whitespace. E.g. `+`
938 /// is `Joint` in `+=` and `++`.
939 /// - When a single quote `'` is immediately followed by an identifier without a whitespace.
940 /// E.g. `'` is `Joint` in `'lifetime`.
941 ///
942 /// This list may be extended in the future to enable more token combinations.
943#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
944Joint,
945/// A `Punct` token cannot join with the following token to form a multi-character operator.
946 ///
947 /// `Alone` punctuation tokens can be followed by any other tokens. In token streams parsed
948 /// from source code, the compiler will set spacing to `Alone` in all cases not covered by the
949 /// conditions for `Joint` above. E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`. In
950 /// particular, tokens not followed by anything will be marked as `Alone`.
951#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
952Alone,
953}
954955impl Punct {
956/// Creates a new `Punct` from the given character and spacing.
957 /// The `ch` argument must be a valid punctuation character permitted by the language,
958 /// otherwise the function will panic.
959 ///
960 /// The returned `Punct` will have the default span of `Span::call_site()`
961 /// which can be further configured with the `set_span` method below.
962#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
963pub fn new(ch: char, spacing: Spacing) -> Punct {
964const LEGAL_CHARS: &[char] = &[
965'=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
966':', '#', '$', '?', '\'',
967 ];
968if !LEGAL_CHARS.contains(&ch) {
969{
::core::panicking::panic_fmt(format_args!("unsupported character `{0:?}`",
ch));
};panic!("unsupported character `{:?}`", ch);
970 }
971Punct(bridge::Punct {
972 ch: chas u8,
973 joint: spacing == Spacing::Joint,
974 span: Span::call_site().0,
975 })
976 }
977978/// Returns the value of this punctuation character as `char`.
979#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
980pub fn as_char(&self) -> char {
981self.0.ch as char982 }
983984/// Returns the spacing of this punctuation character, indicating whether it can be potentially
985 /// combined into a multi-character operator with the following token (`Joint`), or whether the
986 /// operator has definitely ended (`Alone`).
987#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
988pub fn spacing(&self) -> Spacing {
989if self.0.joint { Spacing::Joint } else { Spacing::Alone }
990 }
991992/// Returns the span for this punctuation character.
993#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
994pub fn span(&self) -> Span {
995Span(self.0.span)
996 }
997998/// Configure the span for this punctuation character.
999#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1000pub fn set_span(&mut self, span: Span) {
1001self.0.span = span.0;
1002 }
1003}
10041005/// Prints the punctuation character as a string that should be losslessly convertible
1006/// back into the same character.
1007#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1008impl fmt::Displayfor Punct {
1009fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1010f.write_fmt(format_args!("{0}", self.as_char()))write!(f, "{}", self.as_char())1011 }
1012}
10131014#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1015impl fmt::Debugfor Punct {
1016fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1017f.debug_struct("Punct")
1018 .field("ch", &self.as_char())
1019 .field("spacing", &self.spacing())
1020 .field("span", &self.span())
1021 .finish()
1022 }
1023}
10241025#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1026impl PartialEq<char> for Punct {
1027fn eq(&self, rhs: &char) -> bool {
1028self.as_char() == *rhs1029 }
1030}
10311032#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1033impl PartialEq<Punct> for char {
1034fn eq(&self, rhs: &Punct) -> bool {
1035*self == rhs.as_char()
1036 }
1037}
10381039/// An identifier (`ident`).
1040#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Ident {
#[inline]
fn clone(&self) -> Ident { Ident(::core::clone::Clone::clone(&self.0)) }
}Clone)]
1041#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1042pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
10431044impl Ident {
1045/// Creates a new `Ident` with the given `string` as well as the specified
1046 /// `span`.
1047 /// The `string` argument must be a valid identifier permitted by the
1048 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
1049 ///
1050 /// The constructed identifier will be NFC-normalized. See the [Reference] for more info.
1051 ///
1052 /// Note that `span`, currently in rustc, configures the hygiene information
1053 /// for this identifier.
1054 ///
1055 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
1056 /// meaning that identifiers created with this span will be resolved as if they were written
1057 /// directly at the location of the macro call, and other code at the macro call site will be
1058 /// able to refer to them as well.
1059 ///
1060 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
1061 /// meaning that identifiers created with this span will be resolved at the location of the
1062 /// macro definition and other code at the macro call site will not be able to refer to them.
1063 ///
1064 /// Due to the current importance of hygiene this constructor, unlike other
1065 /// tokens, requires a `Span` to be specified at construction.
1066 ///
1067 /// [Reference]: https://doc.rust-lang.org/nightly/reference/identifiers.html#r-ident.normalization
1068#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1069pub fn new(string: &str, span: Span) -> Ident {
1070Ident(bridge::Ident {
1071 sym: bridge::client::Symbol::new_ident(string, false),
1072 is_raw: false,
1073 span: span.0,
1074 })
1075 }
10761077/// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
1078 /// The `string` argument be a valid identifier permitted by the language
1079 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
1080 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
1081#[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1082pub fn new_raw(string: &str, span: Span) -> Ident {
1083Ident(bridge::Ident {
1084 sym: bridge::client::Symbol::new_ident(string, true),
1085 is_raw: true,
1086 span: span.0,
1087 })
1088 }
10891090/// Returns the span of this `Ident`, encompassing the entire string returned
1091 /// by [`to_string`](ToString::to_string).
1092#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1093pub fn span(&self) -> Span {
1094Span(self.0.span)
1095 }
10961097/// Configures the span of this `Ident`, possibly changing its hygiene context.
1098#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1099pub fn set_span(&mut self, span: Span) {
1100self.0.span = span.0;
1101 }
1102}
11031104/// Prints the identifier as a string that should be losslessly convertible back
1105/// into the same identifier.
1106#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1107impl fmt::Displayfor Ident {
1108fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109if self.0.is_raw {
1110f.write_str("r#")?;
1111 }
1112 fmt::Display::fmt(&self.0.sym, f)
1113 }
1114}
11151116#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1117impl fmt::Debugfor Ident {
1118fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1119f.debug_struct("Ident")
1120 .field("ident", &self.to_string())
1121 .field("span", &self.span())
1122 .finish()
1123 }
1124}
11251126/// A literal string (`"hello"`), byte string (`b"hello"`), C string (`c"hello"`),
1127/// character (`'a'`), byte character (`b'a'`), an integer or floating point number
1128/// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1129/// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
1130#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Literal {
#[inline]
fn clone(&self) -> Literal {
Literal(::core::clone::Clone::clone(&self.0))
}
}Clone)]
1131#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1132pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
11331134macro_rules!suffixed_int_literals {
1135 ($($name:ident => $kind:ident,)*) => ($(
1136/// Creates a new suffixed integer literal with the specified value.
1137 ///
1138 /// This function will create an integer like `1u32` where the integer
1139 /// value specified is the first part of the token and the integral is
1140 /// also suffixed at the end.
1141 /// Literals created from negative numbers might not survive round-trips through
1142 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1143 ///
1144 /// Literals created through this method have the `Span::call_site()`
1145 /// span by default, which can be configured with the `set_span` method
1146 /// below.
1147#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1148pub fn $name(n: $kind) -> Literal {
1149 Literal(bridge::Literal {
1150 kind: bridge::LitKind::Integer,
1151 symbol: bridge::client::Symbol::new(&n.to_string()),
1152 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1153 span: Span::call_site().0,
1154 })
1155 }
1156 )*)
1157}
11581159macro_rules!unsuffixed_int_literals {
1160 ($($name:ident => $kind:ident,)*) => ($(
1161/// Creates a new unsuffixed integer literal with the specified value.
1162 ///
1163 /// This function will create an integer like `1` where the integer
1164 /// value specified is the first part of the token. No suffix is
1165 /// specified on this token, meaning that invocations like
1166 /// `Literal::i8_unsuffixed(1)` are equivalent to
1167 /// `Literal::u32_unsuffixed(1)`.
1168 /// Literals created from negative numbers might not survive rountrips through
1169 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1170 ///
1171 /// Literals created through this method have the `Span::call_site()`
1172 /// span by default, which can be configured with the `set_span` method
1173 /// below.
1174#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1175pub fn $name(n: $kind) -> Literal {
1176 Literal(bridge::Literal {
1177 kind: bridge::LitKind::Integer,
1178 symbol: bridge::client::Symbol::new(&n.to_string()),
1179 suffix: None,
1180 span: Span::call_site().0,
1181 })
1182 }
1183 )*)
1184}
11851186impl Literal {
1187fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1188Literal(bridge::Literal {
1189kind,
1190 symbol: bridge::client::Symbol::new(value),
1191 suffix: suffix.map(bridge::client::Symbol::new),
1192 span: Span::call_site().0,
1193 })
1194 }
11951196n
Literal
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("isize")),
span: Span::call_site().0,
});suffixed_int_literals! {
1197 u8_suffixed => u8,
1198 u16_suffixed => u16,
1199 u32_suffixed => u32,
1200 u64_suffixed => u64,
1201 u128_suffixed => u128,
1202 usize_suffixed => usize,
1203 i8_suffixed => i8,
1204 i16_suffixed => i16,
1205 i32_suffixed => i32,
1206 i64_suffixed => i64,
1207 i128_suffixed => i128,
1208 isize_suffixed => isize,
1209 }12101211n
Literal
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
});unsuffixed_int_literals! {
1212 u8_unsuffixed => u8,
1213 u16_unsuffixed => u16,
1214 u32_unsuffixed => u32,
1215 u64_unsuffixed => u64,
1216 u128_unsuffixed => u128,
1217 usize_unsuffixed => usize,
1218 i8_unsuffixed => i8,
1219 i16_unsuffixed => i16,
1220 i32_unsuffixed => i32,
1221 i64_unsuffixed => i64,
1222 i128_unsuffixed => i128,
1223 isize_unsuffixed => isize,
1224 }12251226/// Creates a new unsuffixed floating-point literal.
1227 ///
1228 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1229 /// the float's value is emitted directly into the token but no suffix is
1230 /// used, so it may be inferred to be a `f64` later in the compiler.
1231 /// Literals created from negative numbers might not survive rountrips through
1232 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1233 ///
1234 /// # Panics
1235 ///
1236 /// This function requires that the specified float is finite, for
1237 /// example if it is infinity or NaN this function will panic.
1238#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1239pub fn f32_unsuffixed(n: f32) -> Literal {
1240if !n.is_finite() {
1241{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1242 }
1243let mut repr = n.to_string();
1244if !repr.contains('.') {
1245repr.push_str(".0");
1246 }
1247Literal::new(bridge::LitKind::Float, &repr, None)
1248 }
12491250/// Creates a new suffixed floating-point literal.
1251 ///
1252 /// This constructor will create a literal like `1.0f32` where the value
1253 /// specified is the preceding part of the token and `f32` is the suffix of
1254 /// the token. This token will always be inferred to be an `f32` in the
1255 /// compiler.
1256 /// Literals created from negative numbers might not survive rountrips through
1257 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1258 ///
1259 /// # Panics
1260 ///
1261 /// This function requires that the specified float is finite, for
1262 /// example if it is infinity or NaN this function will panic.
1263#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1264pub fn f32_suffixed(n: f32) -> Literal {
1265if !n.is_finite() {
1266{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1267 }
1268Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1269 }
12701271/// Creates a new unsuffixed floating-point literal.
1272 ///
1273 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1274 /// the float's value is emitted directly into the token but no suffix is
1275 /// used, so it may be inferred to be a `f64` later in the compiler.
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).
1278 ///
1279 /// # Panics
1280 ///
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")]
1284pub fn f64_unsuffixed(n: f64) -> Literal {
1285if !n.is_finite() {
1286{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1287 }
1288let mut repr = n.to_string();
1289if !repr.contains('.') {
1290repr.push_str(".0");
1291 }
1292Literal::new(bridge::LitKind::Float, &repr, None)
1293 }
12941295/// Creates a new suffixed floating-point literal.
1296 ///
1297 /// This constructor will create a literal like `1.0f64` where the value
1298 /// specified is the preceding part of the token and `f64` is the suffix of
1299 /// the token. This token will always be inferred to be an `f64` in the
1300 /// compiler.
1301 /// Literals created from negative numbers might not survive rountrips through
1302 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1303 ///
1304 /// # Panics
1305 ///
1306 /// This function requires that the specified float is finite, for
1307 /// example if it is infinity or NaN this function will panic.
1308#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1309pub fn f64_suffixed(n: f64) -> Literal {
1310if !n.is_finite() {
1311{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1312 }
1313Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1314 }
13151316/// String literal.
1317#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1318pub fn string(string: &str) -> Literal {
1319let escape = EscapeOptions {
1320 escape_single_quote: false,
1321 escape_double_quote: true,
1322 escape_nonascii: false,
1323 };
1324let repr = escape_bytes(string.as_bytes(), escape);
1325Literal::new(bridge::LitKind::Str, &repr, None)
1326 }
13271328/// Character literal.
1329#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1330pub fn character(ch: char) -> Literal {
1331let escape = EscapeOptions {
1332 escape_single_quote: true,
1333 escape_double_quote: false,
1334 escape_nonascii: false,
1335 };
1336let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1337Literal::new(bridge::LitKind::Char, &repr, None)
1338 }
13391340/// Byte character literal.
1341#[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1342pub fn byte_character(byte: u8) -> Literal {
1343let escape = EscapeOptions {
1344 escape_single_quote: true,
1345 escape_double_quote: false,
1346 escape_nonascii: true,
1347 };
1348let repr = escape_bytes(&[byte], escape);
1349Literal::new(bridge::LitKind::Byte, &repr, None)
1350 }
13511352/// Byte string literal.
1353#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1354pub fn byte_string(bytes: &[u8]) -> Literal {
1355let escape = EscapeOptions {
1356 escape_single_quote: false,
1357 escape_double_quote: true,
1358 escape_nonascii: true,
1359 };
1360let repr = escape_bytes(bytes, escape);
1361Literal::new(bridge::LitKind::ByteStr, &repr, None)
1362 }
13631364/// C string literal.
1365#[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1366pub fn c_string(string: &CStr) -> Literal {
1367let escape = EscapeOptions {
1368 escape_single_quote: false,
1369 escape_double_quote: true,
1370 escape_nonascii: false,
1371 };
1372let repr = escape_bytes(string.to_bytes(), escape);
1373Literal::new(bridge::LitKind::CStr, &repr, None)
1374 }
13751376/// Returns the span encompassing this literal.
1377#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1378pub fn span(&self) -> Span {
1379Span(self.0.span)
1380 }
13811382/// Configures the span associated for this literal.
1383#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1384pub fn set_span(&mut self, span: Span) {
1385self.0.span = span.0;
1386 }
13871388/// Returns a `Span` that is a subset of `self.span()` containing only the
1389 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1390 /// span is outside the bounds of `self`.
1391// FIXME(SergioBenitez): check that the byte range starts and ends at a
1392 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1393 // occur elsewhere when the source text is printed.
1394 // FIXME(SergioBenitez): there is no way for the user to know what
1395 // `self.span()` actually maps to, so this method can currently only be
1396 // called blindly. For example, `to_string()` for the character 'c' returns
1397 // "'\u{63}'"; there is no way for the user to know whether the source text
1398 // was 'c' or whether it was '\u{63}'.
1399#[unstable(feature = "proc_macro_span", issue = "54725")]
1400pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1401BridgeMethods::span_subspan(
1402self.0.span,
1403range.start_bound().cloned(),
1404range.end_bound().cloned(),
1405 )
1406 .map(Span)
1407 }
14081409fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1410self.0.symbol.with(|symbol| match self.0.suffix {
1411Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1412None => f(symbol, ""),
1413 })
1414 }
14151416/// Invokes the callback with a `&[&str]` consisting of each part of the
1417 /// literal's representation. This is done to allow the `ToString` and
1418 /// `Display` implementations to borrow references to symbol values, and
1419 /// both be optimized to reduce overhead.
1420fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1421/// Returns a string containing exactly `num` '#' characters.
1422 /// Uses a 256-character source string literal which is always safe to
1423 /// index with a `u8` index.
1424fn get_hashes_str(num: u8) -> &'static str {
1425const HASHES: &str = "\
1426 ################################################################\
1427 ################################################################\
1428 ################################################################\
1429 ################################################################\
1430 ";
1431const _: () = if !(HASHES.len() == 256) {
::core::panicking::panic("assertion failed: HASHES.len() == 256")
}assert!(HASHES.len() == 256);
1432&HASHES[..num as usize]
1433 }
14341435self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1436 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1437 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1438 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1439 bridge::LitKind::StrRaw(n) => {
1440let hashes = get_hashes_str(n);
1441f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1442 }
1443 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1444 bridge::LitKind::ByteStrRaw(n) => {
1445let hashes = get_hashes_str(n);
1446f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1447 }
1448 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1449 bridge::LitKind::CStrRaw(n) => {
1450let hashes = get_hashes_str(n);
1451f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1452 }
14531454 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1455f(&[symbol, suffix])
1456 }
1457 })
1458 }
14591460/// Returns the unescaped character value if the current literal is a byte character literal.
1461#[unstable(feature = "proc_macro_value", issue = "136652")]
1462pub fn byte_character_value(&self) -> Result<u8, ConversionErrorKind> {
1463self.0.symbol.with(|symbol| match self.0.kind {
1464 bridge::LitKind::Char => {
1465unescape_byte(symbol).map_err(ConversionErrorKind::FailedToUnescape)
1466 }
1467_ => Err(ConversionErrorKind::InvalidLiteralKind),
1468 })
1469 }
14701471/// Returns the unescaped character value if the current literal is a character literal.
1472#[unstable(feature = "proc_macro_value", issue = "136652")]
1473pub fn character_value(&self) -> Result<char, ConversionErrorKind> {
1474self.0.symbol.with(|symbol| match self.0.kind {
1475 bridge::LitKind::Char => {
1476unescape_char(symbol).map_err(ConversionErrorKind::FailedToUnescape)
1477 }
1478_ => Err(ConversionErrorKind::InvalidLiteralKind),
1479 })
1480 }
14811482/// Returns the unescaped string value if the current literal is a string or a string literal.
1483#[unstable(feature = "proc_macro_value", issue = "136652")]
1484pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1485self.0.symbol.with(|symbol| match self.0.kind {
1486 bridge::LitKind::Str => {
1487if symbol.contains('\\') {
1488let mut buf = String::with_capacity(symbol.len());
1489let mut error = None;
1490// Force-inlining here is aggressive but the closure is
1491 // called on every char in the string, so it can be hot in
1492 // programs with many long strings containing escapes.
1493unescape_str(
1494symbol,
1495#[inline(always)]
1496|_, c| match c {
1497Ok(c) => buf.push(c),
1498Err(err) => {
1499if err.is_fatal() {
1500error = Some(ConversionErrorKind::FailedToUnescape(err));
1501 }
1502 }
1503 },
1504 );
1505if let Some(error) = error { Err(error) } else { Ok(buf) }
1506 } else {
1507Ok(symbol.to_string())
1508 }
1509 }
1510 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1511_ => Err(ConversionErrorKind::InvalidLiteralKind),
1512 })
1513 }
15141515/// Returns the unescaped string value if the current literal is a c-string or a c-string
1516 /// literal.
1517#[unstable(feature = "proc_macro_value", issue = "136652")]
1518pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1519self.0.symbol.with(|symbol| match self.0.kind {
1520 bridge::LitKind::CStr => {
1521let mut error = None;
1522let mut buf = Vec::with_capacity(symbol.len());
15231524unescape_c_str(symbol, |_span, res| match res {
1525Ok(MixedUnit::Char(c)) => {
1526buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1527 }
1528Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1529Err(err) => {
1530if err.is_fatal() {
1531error = Some(ConversionErrorKind::FailedToUnescape(err));
1532 }
1533 }
1534 });
1535if let Some(error) = error {
1536Err(error)
1537 } else {
1538buf.push(0);
1539Ok(buf)
1540 }
1541 }
1542 bridge::LitKind::CStrRaw(_) => {
1543// Raw strings have no escapes so we can convert the symbol
1544 // directly to a `Lrc<u8>` after appending the terminating NUL
1545 // char.
1546let mut buf = symbol.to_owned().into_bytes();
1547buf.push(0);
1548Ok(buf)
1549 }
1550_ => Err(ConversionErrorKind::InvalidLiteralKind),
1551 })
1552 }
15531554/// Returns the unescaped string value if the current literal is a byte string or a byte string
1555 /// literal.
1556#[unstable(feature = "proc_macro_value", issue = "136652")]
1557pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1558self.0.symbol.with(|symbol| match self.0.kind {
1559 bridge::LitKind::ByteStr => {
1560let mut buf = Vec::with_capacity(symbol.len());
1561let mut error = None;
15621563unescape_byte_str(symbol, |_, res| match res {
1564Ok(b) => buf.push(b),
1565Err(err) => {
1566if err.is_fatal() {
1567error = Some(ConversionErrorKind::FailedToUnescape(err));
1568 }
1569 }
1570 });
1571if let Some(error) = error { Err(error) } else { Ok(buf) }
1572 }
1573 bridge::LitKind::ByteStrRaw(_) => {
1574// Raw strings have no escapes so we can convert the symbol
1575 // directly to a `Lrc<u8>`.
1576Ok(symbol.to_owned().into_bytes())
1577 }
1578_ => Err(ConversionErrorKind::InvalidLiteralKind),
1579 })
1580 }
1581}
15821583/// Parse a single literal from its stringified representation.
1584///
1585/// In order to parse successfully, the input string must not contain anything
1586/// but the literal token. Specifically, it must not contain whitespace or
1587/// comments in addition to the literal.
1588///
1589/// The resulting literal token will have a `Span::call_site()` span.
1590///
1591/// NOTE: some errors may cause panics instead of returning `LexError`. We
1592/// reserve the right to change these errors into `LexError`s later.
1593#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1594impl FromStrfor Literal {
1595type Err = LexError;
15961597fn from_str(src: &str) -> Result<Self, LexError> {
1598match BridgeMethods::literal_from_str(src) {
1599Ok(literal) => Ok(Literal(literal)),
1600Err(msg) => Err(LexError(msg)),
1601 }
1602 }
1603}
16041605/// Prints the literal as a string that should be losslessly convertible
1606/// back into the same literal (except for possible rounding for floating point literals).
1607#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1608impl fmt::Displayfor Literal {
1609fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1610self.with_stringify_parts(|parts| {
1611for part in parts {
1612 fmt::Display::fmt(part, f)?;
1613 }
1614Ok(())
1615 })
1616 }
1617}
16181619#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1620impl fmt::Debugfor Literal {
1621fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1622f.debug_struct("Literal")
1623// format the kind on one line even in {:#?} mode
1624 .field("kind", &format_args!("{0:?}", self.0.kind)format_args!("{:?}", self.0.kind))
1625 .field("symbol", &self.0.symbol)
1626// format `Some("...")` on one line even in {:#?} mode
1627 .field("suffix", &format_args!("{0:?}", self.0.suffix)format_args!("{:?}", self.0.suffix))
1628 .field("span", &self.0.span)
1629 .finish()
1630 }
1631}
16321633#[unstable(
1634 feature = "proc_macro_tracked_path",
1635 issue = "99515",
1636 implied_by = "proc_macro_tracked_env"
1637)]
1638/// Functionality for adding environment state to the build dependency info.
1639pub mod tracked {
1640use std::env::{self, VarError};
1641use std::ffi::OsStr;
1642use std::path::Path;
16431644use crate::BridgeMethods;
16451646/// Retrieve an environment variable and add it to build dependency info.
1647 /// The build system executing the compiler will know that the variable was accessed during
1648 /// compilation, and will be able to rerun the build when the value of that variable changes.
1649 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1650 /// standard library, except that the argument must be UTF-8.
1651#[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1652pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1653let key: &str = key.as_ref();
1654let value = BridgeMethods::injected_env_var(key).map_or_else(|| env::var(key), Ok);
1655BridgeMethods::track_env_var(key, value.as_deref().ok());
1656value1657 }
16581659/// Track a file or directory explicitly.
1660 ///
1661 /// Commonly used for tracking asset preprocessing.
1662#[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1663pub fn path<P: AsRef<Path>>(path: P) {
1664let path: &str = path.as_ref().to_str().unwrap();
1665BridgeMethods::track_path(path);
1666 }
1667}