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#![recursion_limit = "256"]
31#![allow(internal_features)]
32#![deny(ffi_unwind_calls)]
33#![allow(rustc::internal)] // Can't use FxHashMap when compiled as part of the standard library
34#![warn(rustdoc::unescaped_backticks)]
35#![warn(unreachable_pub)]
36#![deny(unsafe_op_in_unsafe_fn)]
3738#[unstable(feature = "proc_macro_internals", issue = "27812")]
39#[doc(hidden)]
40pub mod bridge;
4142mod diagnostic;
43mod escape;
44mod to_tokens;
4546use core::ops::BitOr;
47use std::ffi::CStr;
48use std::ops::{Range, RangeBounds};
49use std::path::PathBuf;
50use std::str::FromStr;
51use std::{error, fmt};
5253#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
54pub use diagnostic::{Diagnostic, Level, MultiSpan};
55#[unstable(feature = "proc_macro_value", issue = "136652")]
56pub use rustc_literal_escaper::EscapeError;
57use rustc_literal_escaper::{
58MixedUnit, unescape_byte, unescape_byte_str, unescape_c_str, unescape_char, unescape_str,
59};
60#[unstable(feature = "proc_macro_totokens", issue = "130977")]
61pub use to_tokens::ToTokens;
6263use crate::bridge::client::Methodsas BridgeMethods;
64use crate::escape::{EscapeOptions, escape_bytes};
6566/// Errors returned when trying to retrieve a literal unescaped value.
67#[unstable(feature = "proc_macro_value", issue = "136652")]
68#[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 {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<EscapeError>;
}
}Eq)]
69pub enum ConversionErrorKind {
70/// The literal failed to be escaped, take a look at [`EscapeError`] for more information.
71FailedToUnescape(EscapeError),
72/// Trying to convert a literal with the wrong type.
73InvalidLiteralKind,
74}
7576/// Determines whether proc_macro has been made accessible to the currently
77/// running program.
78///
79/// The proc_macro crate is only intended for use inside the implementation of
80/// procedural macros. All the functions in this crate panic if invoked from
81/// outside of a procedural macro, such as from a build script or unit test or
82/// ordinary Rust binary.
83///
84/// With consideration for Rust libraries that are designed to support both
85/// macro and non-macro use cases, `proc_macro::is_available()` provides a
86/// non-panicking way to detect whether the infrastructure required to use the
87/// API of proc_macro is presently available. Returns true if invoked from
88/// inside of a procedural macro, false if invoked from any other binary.
89#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
90pub fn is_available() -> bool {
91 bridge::client::is_available()
92}
9394/// The main type provided by this crate, representing an abstract stream of
95/// tokens, or, more specifically, a sequence of token trees.
96/// The type provides interfaces for iterating over those token trees and, conversely,
97/// collecting a number of token trees into one stream.
98///
99/// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
100/// and `#[proc_macro_derive]` definitions.
101#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
102#[stable(feature = "proc_macro_lib", since = "1.15.0")]
103#[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)]
104pub struct TokenStream(Option<bridge::client::TokenStream>);
105106#[stable(feature = "proc_macro_lib", since = "1.15.0")]
107impl !Sendfor TokenStream {}
108#[stable(feature = "proc_macro_lib", since = "1.15.0")]
109impl !Syncfor TokenStream {}
110111/// Error returned from `TokenStream::from_str`.
112#[stable(feature = "proc_macro_lib", since = "1.15.0")]
113#[non_exhaustive]
114#[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::write_str(f, "LexError")
}
}Debug)]
115pub struct LexError;
116117#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
118impl fmt::Displayfor LexError {
119fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120f.write_str("cannot parse string into token stream")
121 }
122}
123124#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
125impl error::Errorfor LexError {}
126127#[stable(feature = "proc_macro_lib", since = "1.15.0")]
128impl !Sendfor LexError {}
129#[stable(feature = "proc_macro_lib", since = "1.15.0")]
130impl !Syncfor LexError {}
131132/// Error returned from `TokenStream::expand_expr`.
133#[unstable(feature = "proc_macro_expand", issue = "90765")]
134#[non_exhaustive]
135#[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)]
136pub struct ExpandError;
137138#[unstable(feature = "proc_macro_expand", issue = "90765")]
139impl fmt::Displayfor ExpandError {
140fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141f.write_str("macro expansion failed")
142 }
143}
144145#[unstable(feature = "proc_macro_expand", issue = "90765")]
146impl error::Errorfor ExpandError {}
147148#[unstable(feature = "proc_macro_expand", issue = "90765")]
149impl !Sendfor ExpandError {}
150151#[unstable(feature = "proc_macro_expand", issue = "90765")]
152impl !Syncfor ExpandError {}
153154impl TokenStream {
155/// Returns an empty `TokenStream` containing no token trees.
156#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
157pub fn new() -> TokenStream {
158TokenStream(None)
159 }
160161/// Checks if this `TokenStream` is empty.
162#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
163pub fn is_empty(&self) -> bool {
164self.0.as_ref().map(|h| BridgeMethods::ts_is_empty(h)).unwrap_or(true)
165 }
166167/// Parses this `TokenStream` as an expression and attempts to expand any
168 /// macros within it. Returns the expanded `TokenStream`.
169 ///
170 /// Currently only expressions expanding to literals will succeed, although
171 /// this may be relaxed in the future.
172 ///
173 /// NOTE: In error conditions, `expand_expr` may leave macros unexpanded,
174 /// report an error, failing compilation, and/or return an `Err(..)`. The
175 /// specific behavior for any error condition, and what conditions are
176 /// considered errors, is unspecified and may change in the future.
177#[unstable(feature = "proc_macro_expand", issue = "90765")]
178pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
179let stream = self.0.as_ref().ok_or(ExpandError)?;
180match BridgeMethods::ts_expand_expr(stream) {
181Ok(stream) => Ok(TokenStream(Some(stream))),
182Err(_) => Err(ExpandError),
183 }
184 }
185}
186187/// Attempts to break the string into tokens and parse those tokens into a token stream.
188/// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
189/// or characters not existing in the language.
190/// All tokens in the parsed stream get `Span::call_site()` spans.
191///
192/// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
193/// change these errors into `LexError`s later.
194#[stable(feature = "proc_macro_lib", since = "1.15.0")]
195impl FromStrfor TokenStream {
196type Err = LexError;
197198fn from_str(src: &str) -> Result<TokenStream, LexError> {
199Ok(TokenStream(Some(BridgeMethods::ts_from_str(src))))
200 }
201}
202203/// Prints the token stream as a string that is supposed to be losslessly convertible back
204/// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
205/// with `Delimiter::None` delimiters and negative numeric literals.
206///
207/// Note: the exact form of the output is subject to change, e.g. there might
208/// be changes in the whitespace used between tokens. Therefore, you should
209/// *not* do any kind of simple substring matching on the output string (as
210/// produced by `to_string`) to implement a proc macro, because that matching
211/// might stop working if such changes happen. Instead, you should work at the
212/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
213/// `TokenTree::Punct`, or `TokenTree::Literal`.
214#[stable(feature = "proc_macro_lib", since = "1.15.0")]
215impl fmt::Displayfor TokenStream {
216fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217match &self.0 {
218Some(ts) => f.write_fmt(format_args!("{0}", BridgeMethods::ts_to_string(ts)))write!(f, "{}", BridgeMethods::ts_to_string(ts)),
219None => Ok(()),
220 }
221 }
222}
223224/// Prints tokens in a form convenient for debugging.
225#[stable(feature = "proc_macro_lib", since = "1.15.0")]
226impl fmt::Debugfor TokenStream {
227fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228f.write_str("TokenStream ")?;
229f.debug_list().entries(self.clone()).finish()
230 }
231}
232233#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
234impl Defaultfor TokenStream {
235fn default() -> Self {
236TokenStream::new()
237 }
238}
239240#[unstable(feature = "proc_macro_quote", issue = "54722")]
241pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
242243fn tree_to_bridge_tree(
244 tree: TokenTree,
245) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
246match tree {
247 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
248 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
249 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
250 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
251 }
252}
253254/// Creates a token stream containing a single token tree.
255#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
256impl From<TokenTree> for TokenStream {
257fn from(tree: TokenTree) -> TokenStream {
258TokenStream(Some(BridgeMethods::ts_from_token_tree(tree_to_bridge_tree(tree))))
259 }
260}
261262/// Non-generic helper for implementing `FromIterator<TokenTree>` and
263/// `Extend<TokenTree>` with less monomorphization in calling crates.
264struct ConcatTreesHelper {
265 trees: Vec<
266 bridge::TokenTree<
267 bridge::client::TokenStream,
268 bridge::client::Span,
269 bridge::client::Symbol,
270 >,
271 >,
272}
273274impl ConcatTreesHelper {
275fn new(capacity: usize) -> Self {
276ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
277 }
278279fn push(&mut self, tree: TokenTree) {
280self.trees.push(tree_to_bridge_tree(tree));
281 }
282283fn build(self) -> TokenStream {
284if self.trees.is_empty() {
285TokenStream(None)
286 } else {
287TokenStream(Some(BridgeMethods::ts_concat_trees(None, self.trees)))
288 }
289 }
290291fn append_to(self, stream: &mut TokenStream) {
292if self.trees.is_empty() {
293return;
294 }
295stream.0 = Some(BridgeMethods::ts_concat_trees(stream.0.take(), self.trees))
296 }
297}
298299/// Non-generic helper for implementing `FromIterator<TokenStream>` and
300/// `Extend<TokenStream>` with less monomorphization in calling crates.
301struct ConcatStreamsHelper {
302 streams: Vec<bridge::client::TokenStream>,
303}
304305impl ConcatStreamsHelper {
306fn new(capacity: usize) -> Self {
307ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
308 }
309310fn push(&mut self, stream: TokenStream) {
311if let Some(stream) = stream.0 {
312self.streams.push(stream);
313 }
314 }
315316fn build(mut self) -> TokenStream {
317if self.streams.len() <= 1 {
318TokenStream(self.streams.pop())
319 } else {
320TokenStream(Some(BridgeMethods::ts_concat_streams(None, self.streams)))
321 }
322 }
323324fn append_to(mut self, stream: &mut TokenStream) {
325if self.streams.is_empty() {
326return;
327 }
328let base = stream.0.take();
329if base.is_none() && self.streams.len() == 1 {
330stream.0 = self.streams.pop();
331 } else {
332stream.0 = Some(BridgeMethods::ts_concat_streams(base, self.streams));
333 }
334 }
335}
336337/// Collects a number of token trees into a single stream.
338#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
339impl FromIterator<TokenTree> for TokenStream {
340fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
341let iter = trees.into_iter();
342let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
343iter.for_each(|tree| builder.push(tree));
344builder.build()
345 }
346}
347348/// A "flattening" operation on token streams, collects token trees
349/// from multiple token streams into a single stream.
350#[stable(feature = "proc_macro_lib", since = "1.15.0")]
351impl FromIterator<TokenStream> for TokenStream {
352fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
353let iter = streams.into_iter();
354let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
355iter.for_each(|stream| builder.push(stream));
356builder.build()
357 }
358}
359360#[stable(feature = "token_stream_extend", since = "1.30.0")]
361impl Extend<TokenTree> for TokenStream {
362fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
363let iter = trees.into_iter();
364let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
365iter.for_each(|tree| builder.push(tree));
366builder.append_to(self);
367 }
368}
369370#[stable(feature = "token_stream_extend", since = "1.30.0")]
371impl Extend<TokenStream> for TokenStream {
372fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
373let iter = streams.into_iter();
374let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
375iter.for_each(|stream| builder.push(stream));
376builder.append_to(self);
377 }
378}
379380macro_rules!extend_items {
381 ($($item:ident)*) => {
382 $(
383#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
384impl Extend<$item> for TokenStream {
385fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
386self.extend(iter.into_iter().map(TokenTree::$item));
387 }
388 }
389 )*
390 };
391}
392393#[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);
394395/// Public implementation details for the `TokenStream` type, such as iterators.
396#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
397pub mod token_stream {
398use crate::{BridgeMethods, Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
399400/// An iterator over `TokenStream`'s `TokenTree`s.
401 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
402 /// and returns whole groups as token trees.
403#[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)]
404 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
405pub struct IntoIter(
406 std::vec::IntoIter<
407 bridge::TokenTree<
408 bridge::client::TokenStream,
409 bridge::client::Span,
410 bridge::client::Symbol,
411 >,
412 >,
413 );
414415#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
416impl Iteratorfor IntoIter {
417type Item = TokenTree;
418419fn next(&mut self) -> Option<TokenTree> {
420self.0.next().map(|tree| match tree {
421 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
422 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
423 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
424 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
425 })
426 }
427428fn size_hint(&self) -> (usize, Option<usize>) {
429self.0.size_hint()
430 }
431432fn count(self) -> usize {
433self.0.count()
434 }
435 }
436437#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
438impl IntoIteratorfor TokenStream {
439type Item = TokenTree;
440type IntoIter = IntoIter;
441442fn into_iter(self) -> IntoIter {
443IntoIter(
444self.0.map(|v| BridgeMethods::ts_into_trees(v)).unwrap_or_default().into_iter(),
445 )
446 }
447 }
448}
449450/// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
451/// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
452/// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
453///
454/// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
455/// To quote `$` itself, use `$$`.
456#[unstable(feature = "proc_macro_quote", issue = "54722")]
457#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
458#[rustc_builtin_macro]
459pub macro quote($($t:tt)*) {
460/* compiler built-in */
461}
462463#[unstable(feature = "proc_macro_internals", issue = "27812")]
464#[doc(hidden)]
465mod quote;
466467/// A region of source code, along with macro expansion information.
468#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
469#[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)]
470pub struct Span(bridge::client::Span);
471472#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
473impl !Sendfor Span {}
474#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
475impl !Syncfor Span {}
476477macro_rules!diagnostic_method {
478 ($name:ident, $level:expr) => {
479/// Creates a new `Diagnostic` with the given `message` at the span
480 /// `self`.
481#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
482pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
483 Diagnostic::spanned(self, $level, message)
484 }
485 };
486}
487488impl Span {
489/// A span that resolves at the macro definition site.
490#[unstable(feature = "proc_macro_def_site", issue = "54724")]
491pub fn def_site() -> Span {
492Span(bridge::client::Span::def_site())
493 }
494495/// The span of the invocation of the current procedural macro.
496 /// Identifiers created with this span will be resolved as if they were written
497 /// directly at the macro call location (call-site hygiene) and other code
498 /// at the macro call site will be able to refer to them as well.
499#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
500pub fn call_site() -> Span {
501Span(bridge::client::Span::call_site())
502 }
503504/// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
505 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
506 /// call site (everything else).
507 /// The span location is taken from the call-site.
508#[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
509pub fn mixed_site() -> Span {
510Span(bridge::client::Span::mixed_site())
511 }
512513/// The `Span` for the tokens in the previous macro expansion from which
514 /// `self` was generated from, if any.
515#[unstable(feature = "proc_macro_span", issue = "54725")]
516pub fn parent(&self) -> Option<Span> {
517BridgeMethods::span_parent(self.0).map(Span)
518 }
519520/// The span for the origin source code that `self` was generated from. If
521 /// this `Span` wasn't generated from other macro expansions then the return
522 /// value is the same as `*self`.
523#[unstable(feature = "proc_macro_span", issue = "54725")]
524pub fn source(&self) -> Span {
525Span(BridgeMethods::span_source(self.0))
526 }
527528/// Returns the span's byte position range in the source file.
529#[unstable(feature = "proc_macro_span", issue = "54725")]
530pub fn byte_range(&self) -> Range<usize> {
531BridgeMethods::span_byte_range(self.0)
532 }
533534/// Creates an empty span pointing to directly before this span.
535#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
536pub fn start(&self) -> Span {
537Span(BridgeMethods::span_start(self.0))
538 }
539540/// Creates an empty span pointing to directly after this span.
541#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
542pub fn end(&self) -> Span {
543Span(BridgeMethods::span_end(self.0))
544 }
545546/// The one-indexed line of the source file where the span starts.
547 ///
548 /// To obtain the line of the span's end, use `span.end().line()`.
549#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
550pub fn line(&self) -> usize {
551BridgeMethods::span_line(self.0)
552 }
553554/// The one-indexed column of the source file where the span starts.
555 ///
556 /// To obtain the column of the span's end, use `span.end().column()`.
557#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
558pub fn column(&self) -> usize {
559BridgeMethods::span_column(self.0)
560 }
561562/// The path to the source file in which this span occurs, for display purposes.
563 ///
564 /// This might not correspond to a valid file system path.
565 /// It might be remapped (e.g. `"/src/lib.rs"`) or an artificial path (e.g. `"<command line>"`).
566#[stable(feature = "proc_macro_span_file", since = "1.88.0")]
567pub fn file(&self) -> String {
568BridgeMethods::span_file(self.0)
569 }
570571/// The path to the source file in which this span occurs on the local file system.
572 ///
573 /// This is the actual path on disk. It is unaffected by path remapping.
574 ///
575 /// This path should not be embedded in the output of the macro; prefer `file()` instead.
576#[stable(feature = "proc_macro_span_file", since = "1.88.0")]
577pub fn local_file(&self) -> Option<PathBuf> {
578BridgeMethods::span_local_file(self.0).map(PathBuf::from)
579 }
580581/// Creates a new span encompassing `self` and `other`.
582 ///
583 /// Returns `None` if `self` and `other` are from different files.
584#[unstable(feature = "proc_macro_span", issue = "54725")]
585pub fn join(&self, other: Span) -> Option<Span> {
586BridgeMethods::span_join(self.0, other.0).map(Span)
587 }
588589/// Creates a new span with the same line/column information as `self` but
590 /// that resolves symbols as though it were at `other`.
591#[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
592pub fn resolved_at(&self, other: Span) -> Span {
593Span(BridgeMethods::span_resolved_at(self.0, other.0))
594 }
595596/// Creates a new span with the same name resolution behavior as `self` but
597 /// with the line/column information of `other`.
598#[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
599pub fn located_at(&self, other: Span) -> Span {
600other.resolved_at(*self)
601 }
602603/// Compares two spans to see if they're equal.
604#[unstable(feature = "proc_macro_span", issue = "54725")]
605pub fn eq(&self, other: &Span) -> bool {
606self.0 == other.0
607}
608609/// Returns the source text behind a span. This preserves the original source
610 /// code, including spaces and comments. It only returns a result if the span
611 /// corresponds to real source code.
612 ///
613 /// Note: The observable result of a macro should only rely on the tokens and
614 /// not on this source text. The result of this function is a best effort to
615 /// be used for diagnostics only.
616#[stable(feature = "proc_macro_source_text", since = "1.66.0")]
617pub fn source_text(&self) -> Option<String> {
618BridgeMethods::span_source_text(self.0)
619 }
620621// Used by the implementation of `Span::quote`
622#[doc(hidden)]
623 #[unstable(feature = "proc_macro_internals", issue = "27812")]
624pub fn save_span(&self) -> usize {
625BridgeMethods::span_save_span(self.0)
626 }
627628// Used by the implementation of `Span::quote`
629#[doc(hidden)]
630 #[unstable(feature = "proc_macro_internals", issue = "27812")]
631pub fn recover_proc_macro_span(id: usize) -> Span {
632Span(BridgeMethods::span_recover_proc_macro_span(id))
633 }
634635String
Self
self
T
message
Diagnostic
Diagnostic::spanned(self, Level::Error, message);diagnostic_method!(error, Level::Error);
636String
Self
self
T
message
Diagnostic
Diagnostic::spanned(self, Level::Warning, message);diagnostic_method!(warning, Level::Warning);
637String
Self
self
T
message
Diagnostic
Diagnostic::spanned(self, Level::Note, message);diagnostic_method!(note, Level::Note);
638String
Self
self
T
message
Diagnostic
Diagnostic::spanned(self, Level::Help, message);diagnostic_method!(help, Level::Help);
639}
640641/// Prints a span in a form convenient for debugging.
642#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
643impl fmt::Debugfor Span {
644fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
645self.0.fmt(f)
646 }
647}
648649/// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
650#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
651#[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)]
652pub enum TokenTree {
653/// A token stream surrounded by bracket delimiters.
654#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
655Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
656/// An identifier.
657#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
658Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
659/// A single punctuation character (`+`, `,`, `$`, etc.).
660#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
661Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
662/// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
663#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
664Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
665}
666667#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
668impl !Sendfor TokenTree {}
669#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
670impl !Syncfor TokenTree {}
671672impl TokenTree {
673/// Returns the span of this tree, delegating to the `span` method of
674 /// the contained token or a delimited stream.
675#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
676pub fn span(&self) -> Span {
677match *self {
678 TokenTree::Group(ref t) => t.span(),
679 TokenTree::Ident(ref t) => t.span(),
680 TokenTree::Punct(ref t) => t.span(),
681 TokenTree::Literal(ref t) => t.span(),
682 }
683 }
684685/// Configures the span for *only this token*.
686 ///
687 /// Note that if this token is a `Group` then this method will not configure
688 /// the span of each of the internal tokens, this will simply delegate to
689 /// the `set_span` method of each variant.
690#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
691pub fn set_span(&mut self, span: Span) {
692match *self {
693 TokenTree::Group(ref mut t) => t.set_span(span),
694 TokenTree::Ident(ref mut t) => t.set_span(span),
695 TokenTree::Punct(ref mut t) => t.set_span(span),
696 TokenTree::Literal(ref mut t) => t.set_span(span),
697 }
698 }
699}
700701/// Prints token tree in a form convenient for debugging.
702#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
703impl fmt::Debugfor TokenTree {
704fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
705// Each of these has the name in the struct type in the derived debug,
706 // so don't bother with an extra layer of indirection
707match *self {
708 TokenTree::Group(ref tt) => tt.fmt(f),
709 TokenTree::Ident(ref tt) => tt.fmt(f),
710 TokenTree::Punct(ref tt) => tt.fmt(f),
711 TokenTree::Literal(ref tt) => tt.fmt(f),
712 }
713 }
714}
715716#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
717impl From<Group> for TokenTree {
718fn from(g: Group) -> TokenTree {
719 TokenTree::Group(g)
720 }
721}
722723#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
724impl From<Ident> for TokenTree {
725fn from(g: Ident) -> TokenTree {
726 TokenTree::Ident(g)
727 }
728}
729730#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
731impl From<Punct> for TokenTree {
732fn from(g: Punct) -> TokenTree {
733 TokenTree::Punct(g)
734 }
735}
736737#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
738impl From<Literal> for TokenTree {
739fn from(g: Literal) -> TokenTree {
740 TokenTree::Literal(g)
741 }
742}
743744/// Prints the token tree as a string that is supposed to be losslessly convertible back
745/// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
746/// with `Delimiter::None` delimiters and negative numeric literals.
747///
748/// Note: the exact form of the output is subject to change, e.g. there might
749/// be changes in the whitespace used between tokens. Therefore, you should
750/// *not* do any kind of simple substring matching on the output string (as
751/// produced by `to_string`) to implement a proc macro, because that matching
752/// might stop working if such changes happen. Instead, you should work at the
753/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
754/// `TokenTree::Punct`, or `TokenTree::Literal`.
755#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
756impl fmt::Displayfor TokenTree {
757fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
758match self {
759 TokenTree::Group(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
760 TokenTree::Ident(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
761 TokenTree::Punct(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
762 TokenTree::Literal(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
763 }
764 }
765}
766767/// A delimited token stream.
768///
769/// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
770#[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)]
771#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
772pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
773774#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
775impl !Sendfor Group {}
776#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
777impl !Syncfor Group {}
778779/// Describes how a sequence of token trees is delimited.
780#[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 {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq)]
781#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
782pub enum Delimiter {
783/// `( ... )`
784#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
785Parenthesis,
786/// `{ ... }`
787#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
788Brace,
789/// `[ ... ]`
790#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
791Bracket,
792/// `∅ ... ∅`
793 /// An invisible delimiter, that may, for example, appear around tokens coming from a
794 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
795 /// `$var * 3` where `$var` is `1 + 2`.
796 /// Invisible delimiters might not survive roundtrip of a token stream through a string.
797 ///
798 /// <div class="warning">
799 ///
800 /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
801 /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
802 /// of a proc_macro macro are preserved, and only in very specific circumstances.
803 /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
804 /// operator priorities as indicated above. The other `Delimiter` variants should be used
805 /// instead in this context. This is a rustc bug. For details, see
806 /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
807 ///
808 /// </div>
809#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
810None,
811}
812813impl Group {
814/// Creates a new `Group` with the given delimiter and token stream.
815 ///
816 /// This constructor will set the span for this group to
817 /// `Span::call_site()`. To change the span you can use the `set_span`
818 /// method below.
819#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
820pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
821Group(bridge::Group {
822delimiter,
823 stream: stream.0,
824 span: bridge::DelimSpan::from_single(Span::call_site().0),
825 })
826 }
827828/// Returns the delimiter of this `Group`
829#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
830pub fn delimiter(&self) -> Delimiter {
831self.0.delimiter
832 }
833834/// Returns the `TokenStream` of tokens that are delimited in this `Group`.
835 ///
836 /// Note that the returned token stream does not include the delimiter
837 /// returned above.
838#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
839pub fn stream(&self) -> TokenStream {
840TokenStream(self.0.stream.clone())
841 }
842843/// Returns the span for the delimiters of this token stream, spanning the
844 /// entire `Group`.
845 ///
846 /// ```text
847 /// pub fn span(&self) -> Span {
848 /// ^^^^^^^
849 /// ```
850#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
851pub fn span(&self) -> Span {
852Span(self.0.span.entire)
853 }
854855/// Returns the span pointing to the opening delimiter of this group.
856 ///
857 /// ```text
858 /// pub fn span_open(&self) -> Span {
859 /// ^
860 /// ```
861#[stable(feature = "proc_macro_group_span", since = "1.55.0")]
862pub fn span_open(&self) -> Span {
863Span(self.0.span.open)
864 }
865866/// Returns the span pointing to the closing delimiter of this group.
867 ///
868 /// ```text
869 /// pub fn span_close(&self) -> Span {
870 /// ^
871 /// ```
872#[stable(feature = "proc_macro_group_span", since = "1.55.0")]
873pub fn span_close(&self) -> Span {
874Span(self.0.span.close)
875 }
876877/// Configures the span for this `Group`'s delimiters, but not its internal
878 /// tokens.
879 ///
880 /// This method will **not** set the span of all the internal tokens spanned
881 /// by this group, but rather it will only set the span of the delimiter
882 /// tokens at the level of the `Group`.
883#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
884pub fn set_span(&mut self, span: Span) {
885self.0.span = bridge::DelimSpan::from_single(span.0);
886 }
887}
888889/// Prints the group as a string that should be losslessly convertible back
890/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
891/// with `Delimiter::None` delimiters.
892#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
893impl fmt::Displayfor Group {
894fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
895f.write_fmt(format_args!("{0}",
TokenStream::from(TokenTree::from(self.clone()))))write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))896 }
897}
898899#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
900impl fmt::Debugfor Group {
901fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
902f.debug_struct("Group")
903 .field("delimiter", &self.delimiter())
904 .field("stream", &self.stream())
905 .field("span", &self.span())
906 .finish()
907 }
908}
909910/// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
911///
912/// Multi-character operators like `+=` are represented as two instances of `Punct` with different
913/// forms of `Spacing` returned.
914#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
915#[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)]
916pub struct Punct(bridge::Punct<bridge::client::Span>);
917918#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
919impl !Sendfor Punct {}
920#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
921impl !Syncfor Punct {}
922923/// Indicates whether a `Punct` token can join with the following token
924/// to form a multi-character operator.
925#[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 {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq)]
926#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
927pub enum Spacing {
928/// A `Punct` token can join with the following token to form a multi-character operator.
929 ///
930 /// In token streams constructed using proc macro interfaces, `Joint` punctuation tokens can be
931 /// followed by any other tokens. However, in token streams parsed from source code, the
932 /// compiler will only set spacing to `Joint` in the following cases.
933 /// - When a `Punct` is immediately followed by another `Punct` without a whitespace. E.g. `+`
934 /// is `Joint` in `+=` and `++`.
935 /// - When a single quote `'` is immediately followed by an identifier without a whitespace.
936 /// E.g. `'` is `Joint` in `'lifetime`.
937 ///
938 /// This list may be extended in the future to enable more token combinations.
939#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
940Joint,
941/// A `Punct` token cannot join with the following token to form a multi-character operator.
942 ///
943 /// `Alone` punctuation tokens can be followed by any other tokens. In token streams parsed
944 /// from source code, the compiler will set spacing to `Alone` in all cases not covered by the
945 /// conditions for `Joint` above. E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`. In
946 /// particular, tokens not followed by anything will be marked as `Alone`.
947#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
948Alone,
949}
950951impl Punct {
952/// Creates a new `Punct` from the given character and spacing.
953 /// The `ch` argument must be a valid punctuation character permitted by the language,
954 /// otherwise the function will panic.
955 ///
956 /// The returned `Punct` will have the default span of `Span::call_site()`
957 /// which can be further configured with the `set_span` method below.
958#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
959pub fn new(ch: char, spacing: Spacing) -> Punct {
960const LEGAL_CHARS: &[char] = &[
961'=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
962':', '#', '$', '?', '\'',
963 ];
964if !LEGAL_CHARS.contains(&ch) {
965{
::core::panicking::panic_fmt(format_args!("unsupported character `{0:?}`",
ch));
};panic!("unsupported character `{:?}`", ch);
966 }
967Punct(bridge::Punct {
968 ch: chas u8,
969 joint: spacing == Spacing::Joint,
970 span: Span::call_site().0,
971 })
972 }
973974/// Returns the value of this punctuation character as `char`.
975#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
976pub fn as_char(&self) -> char {
977self.0.ch as char978 }
979980/// Returns the spacing of this punctuation character, indicating whether it can be potentially
981 /// combined into a multi-character operator with the following token (`Joint`), or whether the
982 /// operator has definitely ended (`Alone`).
983#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
984pub fn spacing(&self) -> Spacing {
985if self.0.joint { Spacing::Joint } else { Spacing::Alone }
986 }
987988/// Returns the span for this punctuation character.
989#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
990pub fn span(&self) -> Span {
991Span(self.0.span)
992 }
993994/// Configure the span for this punctuation character.
995#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
996pub fn set_span(&mut self, span: Span) {
997self.0.span = span.0;
998 }
999}
10001001/// Prints the punctuation character as a string that should be losslessly convertible
1002/// back into the same character.
1003#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1004impl fmt::Displayfor Punct {
1005fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1006f.write_fmt(format_args!("{0}", self.as_char()))write!(f, "{}", self.as_char())1007 }
1008}
10091010#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1011impl fmt::Debugfor Punct {
1012fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1013f.debug_struct("Punct")
1014 .field("ch", &self.as_char())
1015 .field("spacing", &self.spacing())
1016 .field("span", &self.span())
1017 .finish()
1018 }
1019}
10201021#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1022impl PartialEq<char> for Punct {
1023fn eq(&self, rhs: &char) -> bool {
1024self.as_char() == *rhs1025 }
1026}
10271028#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1029impl PartialEq<Punct> for char {
1030fn eq(&self, rhs: &Punct) -> bool {
1031*self == rhs.as_char()
1032 }
1033}
10341035/// An identifier (`ident`).
1036#[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)]
1037#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1038pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
10391040impl Ident {
1041/// Creates a new `Ident` with the given `string` as well as the specified
1042 /// `span`.
1043 /// The `string` argument must be a valid identifier permitted by the
1044 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
1045 ///
1046 /// The constructed identifier will be NFC-normalized. See the [Reference] for more info.
1047 ///
1048 /// Note that `span`, currently in rustc, configures the hygiene information
1049 /// for this identifier.
1050 ///
1051 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
1052 /// meaning that identifiers created with this span will be resolved as if they were written
1053 /// directly at the location of the macro call, and other code at the macro call site will be
1054 /// able to refer to them as well.
1055 ///
1056 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
1057 /// meaning that identifiers created with this span will be resolved at the location of the
1058 /// macro definition and other code at the macro call site will not be able to refer to them.
1059 ///
1060 /// Due to the current importance of hygiene this constructor, unlike other
1061 /// tokens, requires a `Span` to be specified at construction.
1062 ///
1063 /// [Reference]: https://doc.rust-lang.org/nightly/reference/identifiers.html#r-ident.normalization
1064#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1065pub fn new(string: &str, span: Span) -> Ident {
1066Ident(bridge::Ident {
1067 sym: bridge::client::Symbol::new_ident(string, false),
1068 is_raw: false,
1069 span: span.0,
1070 })
1071 }
10721073/// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
1074 /// The `string` argument be a valid identifier permitted by the language
1075 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
1076 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
1077#[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1078pub fn new_raw(string: &str, span: Span) -> Ident {
1079Ident(bridge::Ident {
1080 sym: bridge::client::Symbol::new_ident(string, true),
1081 is_raw: true,
1082 span: span.0,
1083 })
1084 }
10851086/// Returns the span of this `Ident`, encompassing the entire string returned
1087 /// by [`to_string`](ToString::to_string).
1088#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1089pub fn span(&self) -> Span {
1090Span(self.0.span)
1091 }
10921093/// Configures the span of this `Ident`, possibly changing its hygiene context.
1094#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1095pub fn set_span(&mut self, span: Span) {
1096self.0.span = span.0;
1097 }
1098}
10991100/// Prints the identifier as a string that should be losslessly convertible back
1101/// into the same identifier.
1102#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1103impl fmt::Displayfor Ident {
1104fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1105if self.0.is_raw {
1106f.write_str("r#")?;
1107 }
1108 fmt::Display::fmt(&self.0.sym, f)
1109 }
1110}
11111112#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1113impl fmt::Debugfor Ident {
1114fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1115f.debug_struct("Ident")
1116 .field("ident", &self.to_string())
1117 .field("span", &self.span())
1118 .finish()
1119 }
1120}
11211122/// A literal string (`"hello"`), byte string (`b"hello"`), C string (`c"hello"`),
1123/// character (`'a'`), byte character (`b'a'`), an integer or floating point number
1124/// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1125/// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
1126#[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)]
1127#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1128pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
11291130macro_rules!suffixed_int_literals {
1131 ($($name:ident => $kind:ident,)*) => ($(
1132/// Creates a new suffixed integer literal with the specified value.
1133 ///
1134 /// This function will create an integer like `1u32` where the integer
1135 /// value specified is the first part of the token and the integral is
1136 /// also suffixed at the end.
1137 /// Literals created from negative numbers might not survive round-trips through
1138 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1139 ///
1140 /// Literals created through this method have the `Span::call_site()`
1141 /// span by default, which can be configured with the `set_span` method
1142 /// below.
1143#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1144pub fn $name(n: $kind) -> Literal {
1145 Literal(bridge::Literal {
1146 kind: bridge::LitKind::Integer,
1147 symbol: bridge::client::Symbol::new(&n.to_string()),
1148 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1149 span: Span::call_site().0,
1150 })
1151 }
1152 )*)
1153}
11541155macro_rules!unsuffixed_int_literals {
1156 ($($name:ident => $kind:ident,)*) => ($(
1157/// Creates a new unsuffixed integer literal with the specified value.
1158 ///
1159 /// This function will create an integer like `1` where the integer
1160 /// value specified is the first part of the token. No suffix is
1161 /// specified on this token, meaning that invocations like
1162 /// `Literal::i8_unsuffixed(1)` are equivalent to
1163 /// `Literal::u32_unsuffixed(1)`.
1164 /// Literals created from negative numbers might not survive rountrips through
1165 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1166 ///
1167 /// Literals created through this method have the `Span::call_site()`
1168 /// span by default, which can be configured with the `set_span` method
1169 /// below.
1170#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1171pub fn $name(n: $kind) -> Literal {
1172 Literal(bridge::Literal {
1173 kind: bridge::LitKind::Integer,
1174 symbol: bridge::client::Symbol::new(&n.to_string()),
1175 suffix: None,
1176 span: Span::call_site().0,
1177 })
1178 }
1179 )*)
1180}
11811182impl Literal {
1183fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1184Literal(bridge::Literal {
1185kind,
1186 symbol: bridge::client::Symbol::new(value),
1187 suffix: suffix.map(bridge::client::Symbol::new),
1188 span: Span::call_site().0,
1189 })
1190 }
11911192n
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! {
1193 u8_suffixed => u8,
1194 u16_suffixed => u16,
1195 u32_suffixed => u32,
1196 u64_suffixed => u64,
1197 u128_suffixed => u128,
1198 usize_suffixed => usize,
1199 i8_suffixed => i8,
1200 i16_suffixed => i16,
1201 i32_suffixed => i32,
1202 i64_suffixed => i64,
1203 i128_suffixed => i128,
1204 isize_suffixed => isize,
1205 }12061207n
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! {
1208 u8_unsuffixed => u8,
1209 u16_unsuffixed => u16,
1210 u32_unsuffixed => u32,
1211 u64_unsuffixed => u64,
1212 u128_unsuffixed => u128,
1213 usize_unsuffixed => usize,
1214 i8_unsuffixed => i8,
1215 i16_unsuffixed => i16,
1216 i32_unsuffixed => i32,
1217 i64_unsuffixed => i64,
1218 i128_unsuffixed => i128,
1219 isize_unsuffixed => isize,
1220 }12211222/// Creates a new unsuffixed floating-point literal.
1223 ///
1224 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1225 /// the float's value is emitted directly into the token but no suffix is
1226 /// used, so it may be inferred to be a `f64` later in the compiler.
1227 /// Literals created from negative numbers might not survive rountrips through
1228 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1229 ///
1230 /// # Panics
1231 ///
1232 /// This function requires that the specified float is finite, for
1233 /// example if it is infinity or NaN this function will panic.
1234#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1235pub fn f32_unsuffixed(n: f32) -> Literal {
1236if !n.is_finite() {
1237{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1238 }
1239let mut repr = n.to_string();
1240if !repr.contains('.') {
1241repr.push_str(".0");
1242 }
1243Literal::new(bridge::LitKind::Float, &repr, None)
1244 }
12451246/// Creates a new suffixed floating-point literal.
1247 ///
1248 /// This constructor will create a literal like `1.0f32` where the value
1249 /// specified is the preceding part of the token and `f32` is the suffix of
1250 /// the token. This token will always be inferred to be an `f32` in the
1251 /// compiler.
1252 /// Literals created from negative numbers might not survive rountrips through
1253 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1254 ///
1255 /// # Panics
1256 ///
1257 /// This function requires that the specified float is finite, for
1258 /// example if it is infinity or NaN this function will panic.
1259#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1260pub fn f32_suffixed(n: f32) -> Literal {
1261if !n.is_finite() {
1262{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1263 }
1264Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1265 }
12661267/// Creates a new unsuffixed floating-point literal.
1268 ///
1269 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1270 /// the float's value is emitted directly into the token but no suffix is
1271 /// used, so it may be inferred to be a `f64` later in the compiler.
1272 /// Literals created from negative numbers might not survive rountrips through
1273 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1274 ///
1275 /// # Panics
1276 ///
1277 /// This function requires that the specified float is finite, for
1278 /// example if it is infinity or NaN this function will panic.
1279#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1280pub fn f64_unsuffixed(n: f64) -> Literal {
1281if !n.is_finite() {
1282{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1283 }
1284let mut repr = n.to_string();
1285if !repr.contains('.') {
1286repr.push_str(".0");
1287 }
1288Literal::new(bridge::LitKind::Float, &repr, None)
1289 }
12901291/// Creates a new suffixed floating-point literal.
1292 ///
1293 /// This constructor will create a literal like `1.0f64` where the value
1294 /// specified is the preceding part of the token and `f64` is the suffix of
1295 /// the token. This token will always be inferred to be an `f64` in the
1296 /// compiler.
1297 /// Literals created from negative numbers might not survive rountrips through
1298 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1299 ///
1300 /// # Panics
1301 ///
1302 /// This function requires that the specified float is finite, for
1303 /// example if it is infinity or NaN this function will panic.
1304#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1305pub fn f64_suffixed(n: f64) -> Literal {
1306if !n.is_finite() {
1307{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1308 }
1309Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1310 }
13111312/// String literal.
1313#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1314pub fn string(string: &str) -> Literal {
1315let escape = EscapeOptions {
1316 escape_single_quote: false,
1317 escape_double_quote: true,
1318 escape_nonascii: false,
1319 };
1320let repr = escape_bytes(string.as_bytes(), escape);
1321Literal::new(bridge::LitKind::Str, &repr, None)
1322 }
13231324/// Character literal.
1325#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1326pub fn character(ch: char) -> Literal {
1327let escape = EscapeOptions {
1328 escape_single_quote: true,
1329 escape_double_quote: false,
1330 escape_nonascii: false,
1331 };
1332let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1333Literal::new(bridge::LitKind::Char, &repr, None)
1334 }
13351336/// Byte character literal.
1337#[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1338pub fn byte_character(byte: u8) -> Literal {
1339let escape = EscapeOptions {
1340 escape_single_quote: true,
1341 escape_double_quote: false,
1342 escape_nonascii: true,
1343 };
1344let repr = escape_bytes(&[byte], escape);
1345Literal::new(bridge::LitKind::Byte, &repr, None)
1346 }
13471348/// Byte string literal.
1349#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1350pub fn byte_string(bytes: &[u8]) -> Literal {
1351let escape = EscapeOptions {
1352 escape_single_quote: false,
1353 escape_double_quote: true,
1354 escape_nonascii: true,
1355 };
1356let repr = escape_bytes(bytes, escape);
1357Literal::new(bridge::LitKind::ByteStr, &repr, None)
1358 }
13591360/// C string literal.
1361#[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1362pub fn c_string(string: &CStr) -> Literal {
1363let escape = EscapeOptions {
1364 escape_single_quote: false,
1365 escape_double_quote: true,
1366 escape_nonascii: false,
1367 };
1368let repr = escape_bytes(string.to_bytes(), escape);
1369Literal::new(bridge::LitKind::CStr, &repr, None)
1370 }
13711372/// Returns the span encompassing this literal.
1373#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1374pub fn span(&self) -> Span {
1375Span(self.0.span)
1376 }
13771378/// Configures the span associated for this literal.
1379#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1380pub fn set_span(&mut self, span: Span) {
1381self.0.span = span.0;
1382 }
13831384/// Returns a `Span` that is a subset of `self.span()` containing only the
1385 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1386 /// span is outside the bounds of `self`.
1387// FIXME(SergioBenitez): check that the byte range starts and ends at a
1388 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1389 // occur elsewhere when the source text is printed.
1390 // FIXME(SergioBenitez): there is no way for the user to know what
1391 // `self.span()` actually maps to, so this method can currently only be
1392 // called blindly. For example, `to_string()` for the character 'c' returns
1393 // "'\u{63}'"; there is no way for the user to know whether the source text
1394 // was 'c' or whether it was '\u{63}'.
1395#[unstable(feature = "proc_macro_span", issue = "54725")]
1396pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1397BridgeMethods::span_subspan(
1398self.0.span,
1399range.start_bound().cloned(),
1400range.end_bound().cloned(),
1401 )
1402 .map(Span)
1403 }
14041405fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1406self.0.symbol.with(|symbol| match self.0.suffix {
1407Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1408None => f(symbol, ""),
1409 })
1410 }
14111412/// Invokes the callback with a `&[&str]` consisting of each part of the
1413 /// literal's representation. This is done to allow the `ToString` and
1414 /// `Display` implementations to borrow references to symbol values, and
1415 /// both be optimized to reduce overhead.
1416fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1417/// Returns a string containing exactly `num` '#' characters.
1418 /// Uses a 256-character source string literal which is always safe to
1419 /// index with a `u8` index.
1420fn get_hashes_str(num: u8) -> &'static str {
1421const HASHES: &str = "\
1422 ################################################################\
1423 ################################################################\
1424 ################################################################\
1425 ################################################################\
1426 ";
1427const _: () = if !(HASHES.len() == 256) {
::core::panicking::panic("assertion failed: HASHES.len() == 256")
}assert!(HASHES.len() == 256);
1428&HASHES[..num as usize]
1429 }
14301431self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1432 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1433 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1434 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1435 bridge::LitKind::StrRaw(n) => {
1436let hashes = get_hashes_str(n);
1437f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1438 }
1439 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1440 bridge::LitKind::ByteStrRaw(n) => {
1441let hashes = get_hashes_str(n);
1442f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1443 }
1444 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1445 bridge::LitKind::CStrRaw(n) => {
1446let hashes = get_hashes_str(n);
1447f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1448 }
14491450 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1451f(&[symbol, suffix])
1452 }
1453 })
1454 }
14551456/// Returns the unescaped character value if the current literal is a byte character literal.
1457#[unstable(feature = "proc_macro_value", issue = "136652")]
1458pub fn byte_character_value(&self) -> Result<u8, ConversionErrorKind> {
1459self.0.symbol.with(|symbol| match self.0.kind {
1460 bridge::LitKind::Char => {
1461unescape_byte(symbol).map_err(ConversionErrorKind::FailedToUnescape)
1462 }
1463_ => Err(ConversionErrorKind::InvalidLiteralKind),
1464 })
1465 }
14661467/// Returns the unescaped character value if the current literal is a character literal.
1468#[unstable(feature = "proc_macro_value", issue = "136652")]
1469pub fn character_value(&self) -> Result<char, ConversionErrorKind> {
1470self.0.symbol.with(|symbol| match self.0.kind {
1471 bridge::LitKind::Char => {
1472unescape_char(symbol).map_err(ConversionErrorKind::FailedToUnescape)
1473 }
1474_ => Err(ConversionErrorKind::InvalidLiteralKind),
1475 })
1476 }
14771478/// Returns the unescaped string value if the current literal is a string or a string literal.
1479#[unstable(feature = "proc_macro_value", issue = "136652")]
1480pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1481self.0.symbol.with(|symbol| match self.0.kind {
1482 bridge::LitKind::Str => {
1483if symbol.contains('\\') {
1484let mut buf = String::with_capacity(symbol.len());
1485let mut error = None;
1486// Force-inlining here is aggressive but the closure is
1487 // called on every char in the string, so it can be hot in
1488 // programs with many long strings containing escapes.
1489unescape_str(
1490symbol,
1491#[inline(always)]
1492|_, c| match c {
1493Ok(c) => buf.push(c),
1494Err(err) => {
1495if err.is_fatal() {
1496error = Some(ConversionErrorKind::FailedToUnescape(err));
1497 }
1498 }
1499 },
1500 );
1501if let Some(error) = error { Err(error) } else { Ok(buf) }
1502 } else {
1503Ok(symbol.to_string())
1504 }
1505 }
1506 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1507_ => Err(ConversionErrorKind::InvalidLiteralKind),
1508 })
1509 }
15101511/// Returns the unescaped string value if the current literal is a c-string or a c-string
1512 /// literal.
1513#[unstable(feature = "proc_macro_value", issue = "136652")]
1514pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1515self.0.symbol.with(|symbol| match self.0.kind {
1516 bridge::LitKind::CStr => {
1517let mut error = None;
1518let mut buf = Vec::with_capacity(symbol.len());
15191520unescape_c_str(symbol, |_span, res| match res {
1521Ok(MixedUnit::Char(c)) => {
1522buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1523 }
1524Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1525Err(err) => {
1526if err.is_fatal() {
1527error = Some(ConversionErrorKind::FailedToUnescape(err));
1528 }
1529 }
1530 });
1531if let Some(error) = error {
1532Err(error)
1533 } else {
1534buf.push(0);
1535Ok(buf)
1536 }
1537 }
1538 bridge::LitKind::CStrRaw(_) => {
1539// Raw strings have no escapes so we can convert the symbol
1540 // directly to a `Lrc<u8>` after appending the terminating NUL
1541 // char.
1542let mut buf = symbol.to_owned().into_bytes();
1543buf.push(0);
1544Ok(buf)
1545 }
1546_ => Err(ConversionErrorKind::InvalidLiteralKind),
1547 })
1548 }
15491550/// Returns the unescaped string value if the current literal is a byte string or a byte string
1551 /// literal.
1552#[unstable(feature = "proc_macro_value", issue = "136652")]
1553pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1554self.0.symbol.with(|symbol| match self.0.kind {
1555 bridge::LitKind::ByteStr => {
1556let mut buf = Vec::with_capacity(symbol.len());
1557let mut error = None;
15581559unescape_byte_str(symbol, |_, res| match res {
1560Ok(b) => buf.push(b),
1561Err(err) => {
1562if err.is_fatal() {
1563error = Some(ConversionErrorKind::FailedToUnescape(err));
1564 }
1565 }
1566 });
1567if let Some(error) = error { Err(error) } else { Ok(buf) }
1568 }
1569 bridge::LitKind::ByteStrRaw(_) => {
1570// Raw strings have no escapes so we can convert the symbol
1571 // directly to a `Lrc<u8>`.
1572Ok(symbol.to_owned().into_bytes())
1573 }
1574_ => Err(ConversionErrorKind::InvalidLiteralKind),
1575 })
1576 }
1577}
15781579/// Parse a single literal from its stringified representation.
1580///
1581/// In order to parse successfully, the input string must not contain anything
1582/// but the literal token. Specifically, it must not contain whitespace or
1583/// comments in addition to the literal.
1584///
1585/// The resulting literal token will have a `Span::call_site()` span.
1586///
1587/// NOTE: some errors may cause panics instead of returning `LexError`. We
1588/// reserve the right to change these errors into `LexError`s later.
1589#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1590impl FromStrfor Literal {
1591type Err = LexError;
15921593fn from_str(src: &str) -> Result<Self, LexError> {
1594match BridgeMethods::literal_from_str(src) {
1595Ok(literal) => Ok(Literal(literal)),
1596Err(()) => Err(LexError),
1597 }
1598 }
1599}
16001601/// Prints the literal as a string that should be losslessly convertible
1602/// back into the same literal (except for possible rounding for floating point literals).
1603#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1604impl fmt::Displayfor Literal {
1605fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1606self.with_stringify_parts(|parts| {
1607for part in parts {
1608 fmt::Display::fmt(part, f)?;
1609 }
1610Ok(())
1611 })
1612 }
1613}
16141615#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1616impl fmt::Debugfor Literal {
1617fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1618f.debug_struct("Literal")
1619// format the kind on one line even in {:#?} mode
1620 .field("kind", &format_args!("{0:?}", self.0.kind)format_args!("{:?}", self.0.kind))
1621 .field("symbol", &self.0.symbol)
1622// format `Some("...")` on one line even in {:#?} mode
1623 .field("suffix", &format_args!("{0:?}", self.0.suffix)format_args!("{:?}", self.0.suffix))
1624 .field("span", &self.0.span)
1625 .finish()
1626 }
1627}
16281629#[unstable(
1630 feature = "proc_macro_tracked_path",
1631 issue = "99515",
1632 implied_by = "proc_macro_tracked_env"
1633)]
1634/// Functionality for adding environment state to the build dependency info.
1635pub mod tracked {
1636use std::env::{self, VarError};
1637use std::ffi::OsStr;
1638use std::path::Path;
16391640use crate::BridgeMethods;
16411642/// Retrieve an environment variable and add it to build dependency info.
1643 /// The build system executing the compiler will know that the variable was accessed during
1644 /// compilation, and will be able to rerun the build when the value of that variable changes.
1645 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1646 /// standard library, except that the argument must be UTF-8.
1647#[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1648pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1649let key: &str = key.as_ref();
1650let value = BridgeMethods::injected_env_var(key).map_or_else(|| env::var(key), Ok);
1651BridgeMethods::track_env_var(key, value.as_deref().ok());
1652value1653 }
16541655/// Track a file or directory explicitly.
1656 ///
1657 /// Commonly used for tracking asset preprocessing.
1658#[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1659pub fn path<P: AsRef<Path>>(path: P) {
1660let path: &str = path.as_ref().to_str().unwrap();
1661BridgeMethods::track_path(path);
1662 }
1663}