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
11
12#![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#![cfg_attr(bootstrap, feature(maybe_uninit_write_slice))]
26#![feature(negative_impls)]
27#![feature(panic_can_unwind)]
28#![feature(restricted_std)]
29#![feature(rustc_attrs)]
30#![feature(extend_one)]
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)]
38
39#[unstable(feature = "proc_macro_internals", issue = "27812")]
40#[doc(hidden)]
41pub mod bridge;
42
43mod diagnostic;
44mod escape;
45mod to_tokens;
46
47use core::ops::BitOr;
48use std::ffi::CStr;
49use std::ops::{Range, RangeBounds};
50use std::path::PathBuf;
51use std::str::FromStr;
52use std::{error, fmt};
53
54#[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::{MixedUnit, unescape_byte_str, unescape_c_str, unescape_str};
59#[unstable(feature = "proc_macro_totokens", issue = "130977")]
60pub use to_tokens::ToTokens;
61
62use crate::escape::{EscapeOptions, escape_bytes};
63
64/// Errors returned when trying to retrieve a literal unescaped value.
65#[unstable(feature = "proc_macro_value", issue = "136652")]
66#[derive(Debug, PartialEq, Eq)]
67pub enum ConversionErrorKind {
68 /// The literal failed to be escaped, take a look at [`EscapeError`] for more information.
69 FailedToUnescape(EscapeError),
70 /// Trying to convert a literal with the wrong type.
71 InvalidLiteralKind,
72}
73
74/// Determines whether proc_macro has been made accessible to the currently
75/// running program.
76///
77/// The proc_macro crate is only intended for use inside the implementation of
78/// procedural macros. All the functions in this crate panic if invoked from
79/// outside of a procedural macro, such as from a build script or unit test or
80/// ordinary Rust binary.
81///
82/// With consideration for Rust libraries that are designed to support both
83/// macro and non-macro use cases, `proc_macro::is_available()` provides a
84/// non-panicking way to detect whether the infrastructure required to use the
85/// API of proc_macro is presently available. Returns true if invoked from
86/// inside of a procedural macro, false if invoked from any other binary.
87#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
88pub fn is_available() -> bool {
89 bridge::client::is_available()
90}
91
92/// The main type provided by this crate, representing an abstract stream of
93/// tokens, or, more specifically, a sequence of token trees.
94/// The type provides interfaces for iterating over those token trees and, conversely,
95/// collecting a number of token trees into one stream.
96///
97/// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
98/// and `#[proc_macro_derive]` definitions.
99#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
100#[stable(feature = "proc_macro_lib", since = "1.15.0")]
101#[derive(Clone)]
102pub struct TokenStream(Option<bridge::client::TokenStream>);
103
104#[stable(feature = "proc_macro_lib", since = "1.15.0")]
105impl !Send for TokenStream {}
106#[stable(feature = "proc_macro_lib", since = "1.15.0")]
107impl !Sync for TokenStream {}
108
109/// Error returned from `TokenStream::from_str`.
110#[stable(feature = "proc_macro_lib", since = "1.15.0")]
111#[non_exhaustive]
112#[derive(Debug)]
113pub struct LexError;
114
115#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
116impl fmt::Display for LexError {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 f.write_str(data:"cannot parse string into token stream")
119 }
120}
121
122#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
123impl error::Error for LexError {}
124
125#[stable(feature = "proc_macro_lib", since = "1.15.0")]
126impl !Send for LexError {}
127#[stable(feature = "proc_macro_lib", since = "1.15.0")]
128impl !Sync for LexError {}
129
130/// Error returned from `TokenStream::expand_expr`.
131#[unstable(feature = "proc_macro_expand", issue = "90765")]
132#[non_exhaustive]
133#[derive(Debug)]
134pub struct ExpandError;
135
136#[unstable(feature = "proc_macro_expand", issue = "90765")]
137impl fmt::Display for ExpandError {
138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139 f.write_str(data:"macro expansion failed")
140 }
141}
142
143#[unstable(feature = "proc_macro_expand", issue = "90765")]
144impl error::Error for ExpandError {}
145
146#[unstable(feature = "proc_macro_expand", issue = "90765")]
147impl !Send for ExpandError {}
148
149#[unstable(feature = "proc_macro_expand", issue = "90765")]
150impl !Sync for ExpandError {}
151
152impl TokenStream {
153 /// Returns an empty `TokenStream` containing no token trees.
154 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
155 pub fn new() -> TokenStream {
156 TokenStream(None)
157 }
158
159 /// Checks if this `TokenStream` is empty.
160 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
161 pub fn is_empty(&self) -> bool {
162 self.0.as_ref().map(|h| h.is_empty()).unwrap_or(true)
163 }
164
165 /// Parses this `TokenStream` as an expression and attempts to expand any
166 /// macros within it. Returns the expanded `TokenStream`.
167 ///
168 /// Currently only expressions expanding to literals will succeed, although
169 /// this may be relaxed in the future.
170 ///
171 /// NOTE: In error conditions, `expand_expr` may leave macros unexpanded,
172 /// report an error, failing compilation, and/or return an `Err(..)`. The
173 /// specific behavior for any error condition, and what conditions are
174 /// considered errors, is unspecified and may change in the future.
175 #[unstable(feature = "proc_macro_expand", issue = "90765")]
176 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
177 let stream = self.0.as_ref().ok_or(ExpandError)?;
178 match bridge::client::TokenStream::expand_expr(stream) {
179 Ok(stream) => Ok(TokenStream(Some(stream))),
180 Err(_) => Err(ExpandError),
181 }
182 }
183}
184
185/// Attempts to break the string into tokens and parse those tokens into a token stream.
186/// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
187/// or characters not existing in the language.
188/// All tokens in the parsed stream get `Span::call_site()` spans.
189///
190/// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
191/// change these errors into `LexError`s later.
192#[stable(feature = "proc_macro_lib", since = "1.15.0")]
193impl FromStr for TokenStream {
194 type Err = LexError;
195
196 fn from_str(src: &str) -> Result<TokenStream, LexError> {
197 Ok(TokenStream(Some(bridge::client::TokenStream::from_str(src))))
198 }
199}
200
201/// Prints the token stream as a string that is supposed to be losslessly convertible back
202/// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
203/// with `Delimiter::None` delimiters and negative numeric literals.
204///
205/// Note: the exact form of the output is subject to change, e.g. there might
206/// be changes in the whitespace used between tokens. Therefore, you should
207/// *not* do any kind of simple substring matching on the output string (as
208/// produced by `to_string`) to implement a proc macro, because that matching
209/// might stop working if such changes happen. Instead, you should work at the
210/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
211/// `TokenTree::Punct`, or `TokenTree::Literal`.
212#[stable(feature = "proc_macro_lib", since = "1.15.0")]
213impl fmt::Display for TokenStream {
214 #[allow(clippy::recursive_format_impl)] // clippy doesn't see the specialization
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 match &self.0 {
217 Some(ts: &TokenStream) => write!(f, "{}", ts.to_string()),
218 None => Ok(()),
219 }
220 }
221}
222
223/// Prints token in a form convenient for debugging.
224#[stable(feature = "proc_macro_lib", since = "1.15.0")]
225impl fmt::Debug for TokenStream {
226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227 f.write_str(data:"TokenStream ")?;
228 f.debug_list().entries(self.clone()).finish()
229 }
230}
231
232#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
233impl Default for TokenStream {
234 fn default() -> Self {
235 TokenStream::new()
236 }
237}
238
239#[unstable(feature = "proc_macro_quote", issue = "54722")]
240pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
241
242fn tree_to_bridge_tree(
243 tree: TokenTree,
244) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
245 match tree {
246 TokenTree::Group(tt: Group) => bridge::TokenTree::Group(tt.0),
247 TokenTree::Punct(tt: Punct) => bridge::TokenTree::Punct(tt.0),
248 TokenTree::Ident(tt: Ident) => bridge::TokenTree::Ident(tt.0),
249 TokenTree::Literal(tt: Literal) => bridge::TokenTree::Literal(tt.0),
250 }
251}
252
253/// Creates a token stream containing a single token tree.
254#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
255impl From<TokenTree> for TokenStream {
256 fn from(tree: TokenTree) -> TokenStream {
257 TokenStream(Some(bridge::client::TokenStream::from_token_tree(tree_to_bridge_tree(tree))))
258 }
259}
260
261/// Non-generic helper for implementing `FromIterator<TokenTree>` and
262/// `Extend<TokenTree>` with less monomorphization in calling crates.
263struct ConcatTreesHelper {
264 trees: Vec<
265 bridge::TokenTree<
266 bridge::client::TokenStream,
267 bridge::client::Span,
268 bridge::client::Symbol,
269 >,
270 >,
271}
272
273impl ConcatTreesHelper {
274 fn new(capacity: usize) -> Self {
275 ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
276 }
277
278 fn push(&mut self, tree: TokenTree) {
279 self.trees.push(tree_to_bridge_tree(tree));
280 }
281
282 fn build(self) -> TokenStream {
283 if self.trees.is_empty() {
284 TokenStream(None)
285 } else {
286 TokenStream(Some(bridge::client::TokenStream::concat_trees(base:None, self.trees)))
287 }
288 }
289
290 fn append_to(self, stream: &mut TokenStream) {
291 if self.trees.is_empty() {
292 return;
293 }
294 stream.0 = Some(bridge::client::TokenStream::concat_trees(base:stream.0.take(), self.trees))
295 }
296}
297
298/// Non-generic helper for implementing `FromIterator<TokenStream>` and
299/// `Extend<TokenStream>` with less monomorphization in calling crates.
300struct ConcatStreamsHelper {
301 streams: Vec<bridge::client::TokenStream>,
302}
303
304impl ConcatStreamsHelper {
305 fn new(capacity: usize) -> Self {
306 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
307 }
308
309 fn push(&mut self, stream: TokenStream) {
310 if let Some(stream) = stream.0 {
311 self.streams.push(stream);
312 }
313 }
314
315 fn build(mut self) -> TokenStream {
316 if self.streams.len() <= 1 {
317 TokenStream(self.streams.pop())
318 } else {
319 TokenStream(Some(bridge::client::TokenStream::concat_streams(None, self.streams)))
320 }
321 }
322
323 fn append_to(mut self, stream: &mut TokenStream) {
324 if self.streams.is_empty() {
325 return;
326 }
327 let base = stream.0.take();
328 if base.is_none() && self.streams.len() == 1 {
329 stream.0 = self.streams.pop();
330 } else {
331 stream.0 = Some(bridge::client::TokenStream::concat_streams(base, self.streams));
332 }
333 }
334}
335
336/// Collects a number of token trees into a single stream.
337#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
338impl FromIterator<TokenTree> for TokenStream {
339 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
340 let iter: ::IntoIter = trees.into_iter();
341 let mut builder: ConcatTreesHelper = ConcatTreesHelper::new(capacity:iter.size_hint().0);
342 iter.for_each(|tree: TokenTree| builder.push(tree));
343 builder.build()
344 }
345}
346
347/// A "flattening" operation on token streams, collects token trees
348/// from multiple token streams into a single stream.
349#[stable(feature = "proc_macro_lib", since = "1.15.0")]
350impl FromIterator<TokenStream> for TokenStream {
351 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
352 let iter: ::IntoIter = streams.into_iter();
353 let mut builder: ConcatStreamsHelper = ConcatStreamsHelper::new(capacity:iter.size_hint().0);
354 iter.for_each(|stream: TokenStream| builder.push(stream));
355 builder.build()
356 }
357}
358
359#[stable(feature = "token_stream_extend", since = "1.30.0")]
360impl Extend<TokenTree> for TokenStream {
361 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
362 let iter: ::IntoIter = trees.into_iter();
363 let mut builder: ConcatTreesHelper = ConcatTreesHelper::new(capacity:iter.size_hint().0);
364 iter.for_each(|tree: TokenTree| builder.push(tree));
365 builder.append_to(self);
366 }
367}
368
369#[stable(feature = "token_stream_extend", since = "1.30.0")]
370impl Extend<TokenStream> for TokenStream {
371 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
372 let iter: ::IntoIter = streams.into_iter();
373 let mut builder: ConcatStreamsHelper = ConcatStreamsHelper::new(capacity:iter.size_hint().0);
374 iter.for_each(|stream: TokenStream| builder.push(stream));
375 builder.append_to(self);
376 }
377}
378
379macro_rules! extend_items {
380 ($($item:ident)*) => {
381 $(
382 #[stable(feature = "token_stream_extend_tt_items", since = "1.92.0")]
383 impl Extend<$item> for TokenStream {
384 fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
385 self.extend(iter.into_iter().map(TokenTree::$item));
386 }
387 }
388 )*
389 };
390}
391
392extend_items!(Group Literal Punct Ident);
393
394/// Public implementation details for the `TokenStream` type, such as iterators.
395#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
396pub mod token_stream {
397 use crate::{Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
398
399 /// An iterator over `TokenStream`'s `TokenTree`s.
400 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
401 /// and returns whole groups as token trees.
402 #[derive(Clone)]
403 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
404 pub struct IntoIter(
405 std::vec::IntoIter<
406 bridge::TokenTree<
407 bridge::client::TokenStream,
408 bridge::client::Span,
409 bridge::client::Symbol,
410 >,
411 >,
412 );
413
414 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
415 impl Iterator for IntoIter {
416 type Item = TokenTree;
417
418 fn next(&mut self) -> Option<TokenTree> {
419 self.0.next().map(|tree| match tree {
420 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
421 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
422 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
423 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
424 })
425 }
426
427 fn size_hint(&self) -> (usize, Option<usize>) {
428 self.0.size_hint()
429 }
430
431 fn count(self) -> usize {
432 self.0.count()
433 }
434 }
435
436 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
437 impl IntoIterator for TokenStream {
438 type Item = TokenTree;
439 type IntoIter = IntoIter;
440
441 fn into_iter(self) -> IntoIter {
442 IntoIter(self.0.map(|v| v.into_trees()).unwrap_or_default().into_iter())
443 }
444 }
445}
446
447/// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
448/// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
449/// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
450///
451/// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
452/// To quote `$` itself, use `$$`.
453#[unstable(feature = "proc_macro_quote", issue = "54722")]
454#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
455#[rustc_builtin_macro]
456pub macro quote($($t:tt)*) {
457 /* compiler built-in */
458}
459
460#[unstable(feature = "proc_macro_internals", issue = "27812")]
461#[doc(hidden)]
462mod quote;
463
464/// A region of source code, along with macro expansion information.
465#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
466#[derive(Copy, Clone)]
467pub struct Span(bridge::client::Span);
468
469#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
470impl !Send for Span {}
471#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
472impl !Sync for Span {}
473
474macro_rules! diagnostic_method {
475 ($name:ident, $level:expr) => {
476 /// Creates a new `Diagnostic` with the given `message` at the span
477 /// `self`.
478 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
479 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
480 Diagnostic::spanned(self, $level, message)
481 }
482 };
483}
484
485impl Span {
486 /// A span that resolves at the macro definition site.
487 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
488 pub fn def_site() -> Span {
489 Span(bridge::client::Span::def_site())
490 }
491
492 /// The span of the invocation of the current procedural macro.
493 /// Identifiers created with this span will be resolved as if they were written
494 /// directly at the macro call location (call-site hygiene) and other code
495 /// at the macro call site will be able to refer to them as well.
496 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
497 pub fn call_site() -> Span {
498 Span(bridge::client::Span::call_site())
499 }
500
501 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
502 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
503 /// call site (everything else).
504 /// The span location is taken from the call-site.
505 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
506 pub fn mixed_site() -> Span {
507 Span(bridge::client::Span::mixed_site())
508 }
509
510 /// The `Span` for the tokens in the previous macro expansion from which
511 /// `self` was generated from, if any.
512 #[unstable(feature = "proc_macro_span", issue = "54725")]
513 pub fn parent(&self) -> Option<Span> {
514 self.0.parent().map(Span)
515 }
516
517 /// The span for the origin source code that `self` was generated from. If
518 /// this `Span` wasn't generated from other macro expansions then the return
519 /// value is the same as `*self`.
520 #[unstable(feature = "proc_macro_span", issue = "54725")]
521 pub fn source(&self) -> Span {
522 Span(self.0.source())
523 }
524
525 /// Returns the span's byte position range in the source file.
526 #[unstable(feature = "proc_macro_span", issue = "54725")]
527 pub fn byte_range(&self) -> Range<usize> {
528 self.0.byte_range()
529 }
530
531 /// Creates an empty span pointing to directly before this span.
532 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
533 pub fn start(&self) -> Span {
534 Span(self.0.start())
535 }
536
537 /// Creates an empty span pointing to directly after this span.
538 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
539 pub fn end(&self) -> Span {
540 Span(self.0.end())
541 }
542
543 /// The one-indexed line of the source file where the span starts.
544 ///
545 /// To obtain the line of the span's end, use `span.end().line()`.
546 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
547 pub fn line(&self) -> usize {
548 self.0.line()
549 }
550
551 /// The one-indexed column of the source file where the span starts.
552 ///
553 /// To obtain the column of the span's end, use `span.end().column()`.
554 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
555 pub fn column(&self) -> usize {
556 self.0.column()
557 }
558
559 /// The path to the source file in which this span occurs, for display purposes.
560 ///
561 /// This might not correspond to a valid file system path.
562 /// It might be remapped (e.g. `"/src/lib.rs"`) or an artificial path (e.g. `"<command line>"`).
563 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
564 pub fn file(&self) -> String {
565 self.0.file()
566 }
567
568 /// The path to the source file in which this span occurs on the local file system.
569 ///
570 /// This is the actual path on disk. It is unaffected by path remapping.
571 ///
572 /// This path should not be embedded in the output of the macro; prefer `file()` instead.
573 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
574 pub fn local_file(&self) -> Option<PathBuf> {
575 self.0.local_file().map(|s| PathBuf::from(s))
576 }
577
578 /// Creates a new span encompassing `self` and `other`.
579 ///
580 /// Returns `None` if `self` and `other` are from different files.
581 #[unstable(feature = "proc_macro_span", issue = "54725")]
582 pub fn join(&self, other: Span) -> Option<Span> {
583 self.0.join(other.0).map(Span)
584 }
585
586 /// Creates a new span with the same line/column information as `self` but
587 /// that resolves symbols as though it were at `other`.
588 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
589 pub fn resolved_at(&self, other: Span) -> Span {
590 Span(self.0.resolved_at(other.0))
591 }
592
593 /// Creates a new span with the same name resolution behavior as `self` but
594 /// with the line/column information of `other`.
595 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
596 pub fn located_at(&self, other: Span) -> Span {
597 other.resolved_at(*self)
598 }
599
600 /// Compares two spans to see if they're equal.
601 #[unstable(feature = "proc_macro_span", issue = "54725")]
602 pub fn eq(&self, other: &Span) -> bool {
603 self.0 == other.0
604 }
605
606 /// Returns the source text behind a span. This preserves the original source
607 /// code, including spaces and comments. It only returns a result if the span
608 /// corresponds to real source code.
609 ///
610 /// Note: The observable result of a macro should only rely on the tokens and
611 /// not on this source text. The result of this function is a best effort to
612 /// be used for diagnostics only.
613 #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
614 pub fn source_text(&self) -> Option<String> {
615 self.0.source_text()
616 }
617
618 // Used by the implementation of `Span::quote`
619 #[doc(hidden)]
620 #[unstable(feature = "proc_macro_internals", issue = "27812")]
621 pub fn save_span(&self) -> usize {
622 self.0.save_span()
623 }
624
625 // Used by the implementation of `Span::quote`
626 #[doc(hidden)]
627 #[unstable(feature = "proc_macro_internals", issue = "27812")]
628 pub fn recover_proc_macro_span(id: usize) -> Span {
629 Span(bridge::client::Span::recover_proc_macro_span(id))
630 }
631
632 diagnostic_method!(error, Level::Error);
633 diagnostic_method!(warning, Level::Warning);
634 diagnostic_method!(note, Level::Note);
635 diagnostic_method!(help, Level::Help);
636}
637
638/// Prints a span in a form convenient for debugging.
639#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
640impl fmt::Debug for Span {
641 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
642 self.0.fmt(f)
643 }
644}
645
646/// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
647#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
648#[derive(Clone)]
649pub enum TokenTree {
650 /// A token stream surrounded by bracket delimiters.
651 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
652 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
653 /// An identifier.
654 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
655 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
656 /// A single punctuation character (`+`, `,`, `$`, etc.).
657 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
658 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
659 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
660 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
661 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
662}
663
664#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
665impl !Send for TokenTree {}
666#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
667impl !Sync for TokenTree {}
668
669impl TokenTree {
670 /// Returns the span of this tree, delegating to the `span` method of
671 /// the contained token or a delimited stream.
672 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
673 pub fn span(&self) -> Span {
674 match *self {
675 TokenTree::Group(ref t) => t.span(),
676 TokenTree::Ident(ref t) => t.span(),
677 TokenTree::Punct(ref t) => t.span(),
678 TokenTree::Literal(ref t) => t.span(),
679 }
680 }
681
682 /// Configures the span for *only this token*.
683 ///
684 /// Note that if this token is a `Group` then this method will not configure
685 /// the span of each of the internal tokens, this will simply delegate to
686 /// the `set_span` method of each variant.
687 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
688 pub fn set_span(&mut self, span: Span) {
689 match *self {
690 TokenTree::Group(ref mut t) => t.set_span(span),
691 TokenTree::Ident(ref mut t) => t.set_span(span),
692 TokenTree::Punct(ref mut t) => t.set_span(span),
693 TokenTree::Literal(ref mut t) => t.set_span(span),
694 }
695 }
696}
697
698/// Prints token tree in a form convenient for debugging.
699#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
700impl fmt::Debug for TokenTree {
701 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
702 // Each of these has the name in the struct type in the derived debug,
703 // so don't bother with an extra layer of indirection
704 match *self {
705 TokenTree::Group(ref tt: &Group) => tt.fmt(f),
706 TokenTree::Ident(ref tt: &Ident) => tt.fmt(f),
707 TokenTree::Punct(ref tt: &Punct) => tt.fmt(f),
708 TokenTree::Literal(ref tt: &Literal) => tt.fmt(f),
709 }
710 }
711}
712
713#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
714impl From<Group> for TokenTree {
715 fn from(g: Group) -> TokenTree {
716 TokenTree::Group(g)
717 }
718}
719
720#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
721impl From<Ident> for TokenTree {
722 fn from(g: Ident) -> TokenTree {
723 TokenTree::Ident(g)
724 }
725}
726
727#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
728impl From<Punct> for TokenTree {
729 fn from(g: Punct) -> TokenTree {
730 TokenTree::Punct(g)
731 }
732}
733
734#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
735impl From<Literal> for TokenTree {
736 fn from(g: Literal) -> TokenTree {
737 TokenTree::Literal(g)
738 }
739}
740
741/// Prints the token tree as a string that is supposed to be losslessly convertible back
742/// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
743/// with `Delimiter::None` delimiters and negative numeric literals.
744///
745/// Note: the exact form of the output is subject to change, e.g. there might
746/// be changes in the whitespace used between tokens. Therefore, you should
747/// *not* do any kind of simple substring matching on the output string (as
748/// produced by `to_string`) to implement a proc macro, because that matching
749/// might stop working if such changes happen. Instead, you should work at the
750/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
751/// `TokenTree::Punct`, or `TokenTree::Literal`.
752#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
753impl fmt::Display for TokenTree {
754 #[allow(clippy::recursive_format_impl)] // clippy doesn't see the specialization
755 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
756 match self {
757 TokenTree::Group(t: &Group) => write!(f, "{t}"),
758 TokenTree::Ident(t: &Ident) => write!(f, "{t}"),
759 TokenTree::Punct(t: &Punct) => write!(f, "{t}"),
760 TokenTree::Literal(t: &Literal) => write!(f, "{t}"),
761 }
762 }
763}
764
765/// A delimited token stream.
766///
767/// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
768#[derive(Clone)]
769#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
770pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
771
772#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
773impl !Send for Group {}
774#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
775impl !Sync for Group {}
776
777/// Describes how a sequence of token trees is delimited.
778#[derive(Copy, Clone, Debug, PartialEq, Eq)]
779#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
780pub enum Delimiter {
781 /// `( ... )`
782 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
783 Parenthesis,
784 /// `{ ... }`
785 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
786 Brace,
787 /// `[ ... ]`
788 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
789 Bracket,
790 /// `∅ ... ∅`
791 /// An invisible delimiter, that may, for example, appear around tokens coming from a
792 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
793 /// `$var * 3` where `$var` is `1 + 2`.
794 /// Invisible delimiters might not survive roundtrip of a token stream through a string.
795 ///
796 /// <div class="warning">
797 ///
798 /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
799 /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
800 /// of a proc_macro macro are preserved, and only in very specific circumstances.
801 /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
802 /// operator priorities as indicated above. The other `Delimiter` variants should be used
803 /// instead in this context. This is a rustc bug. For details, see
804 /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
805 ///
806 /// </div>
807 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
808 None,
809}
810
811impl Group {
812 /// Creates a new `Group` with the given delimiter and token stream.
813 ///
814 /// This constructor will set the span for this group to
815 /// `Span::call_site()`. To change the span you can use the `set_span`
816 /// method below.
817 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
818 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
819 Group(bridge::Group {
820 delimiter,
821 stream: stream.0,
822 span: bridge::DelimSpan::from_single(Span::call_site().0),
823 })
824 }
825
826 /// Returns the delimiter of this `Group`
827 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
828 pub fn delimiter(&self) -> Delimiter {
829 self.0.delimiter
830 }
831
832 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
833 ///
834 /// Note that the returned token stream does not include the delimiter
835 /// returned above.
836 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
837 pub fn stream(&self) -> TokenStream {
838 TokenStream(self.0.stream.clone())
839 }
840
841 /// Returns the span for the delimiters of this token stream, spanning the
842 /// entire `Group`.
843 ///
844 /// ```text
845 /// pub fn span(&self) -> Span {
846 /// ^^^^^^^
847 /// ```
848 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
849 pub fn span(&self) -> Span {
850 Span(self.0.span.entire)
851 }
852
853 /// Returns the span pointing to the opening delimiter of this group.
854 ///
855 /// ```text
856 /// pub fn span_open(&self) -> Span {
857 /// ^
858 /// ```
859 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
860 pub fn span_open(&self) -> Span {
861 Span(self.0.span.open)
862 }
863
864 /// Returns the span pointing to the closing delimiter of this group.
865 ///
866 /// ```text
867 /// pub fn span_close(&self) -> Span {
868 /// ^
869 /// ```
870 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
871 pub fn span_close(&self) -> Span {
872 Span(self.0.span.close)
873 }
874
875 /// Configures the span for this `Group`'s delimiters, but not its internal
876 /// tokens.
877 ///
878 /// This method will **not** set the span of all the internal tokens spanned
879 /// by this group, but rather it will only set the span of the delimiter
880 /// tokens at the level of the `Group`.
881 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
882 pub fn set_span(&mut self, span: Span) {
883 self.0.span = bridge::DelimSpan::from_single(span.0);
884 }
885}
886
887/// Prints the group as a string that should be losslessly convertible back
888/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
889/// with `Delimiter::None` delimiters.
890#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
891impl fmt::Display for Group {
892 #[allow(clippy::recursive_format_impl)] // clippy doesn't see the specialization
893 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
894 write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))
895 }
896}
897
898#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
899impl fmt::Debug for Group {
900 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
901 f&mut DebugStruct<'_, '_>.debug_struct("Group")
902 .field("delimiter", &self.delimiter())
903 .field("stream", &self.stream())
904 .field(name:"span", &self.span())
905 .finish()
906 }
907}
908
909/// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
910///
911/// Multi-character operators like `+=` are represented as two instances of `Punct` with different
912/// forms of `Spacing` returned.
913#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
914#[derive(Clone)]
915pub struct Punct(bridge::Punct<bridge::client::Span>);
916
917#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
918impl !Send for Punct {}
919#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
920impl !Sync for Punct {}
921
922/// Indicates whether a `Punct` token can join with the following token
923/// to form a multi-character operator.
924#[derive(Copy, Clone, Debug, PartialEq, Eq)]
925#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
926pub enum Spacing {
927 /// A `Punct` token can join with the following token to form a multi-character operator.
928 ///
929 /// In token streams constructed using proc macro interfaces, `Joint` punctuation tokens can be
930 /// followed by any other tokens. However, in token streams parsed from source code, the
931 /// compiler will only set spacing to `Joint` in the following cases.
932 /// - When a `Punct` is immediately followed by another `Punct` without a whitespace. E.g. `+`
933 /// is `Joint` in `+=` and `++`.
934 /// - When a single quote `'` is immediately followed by an identifier without a whitespace.
935 /// E.g. `'` is `Joint` in `'lifetime`.
936 ///
937 /// This list may be extended in the future to enable more token combinations.
938 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
939 Joint,
940 /// A `Punct` token cannot join with the following token to form a multi-character operator.
941 ///
942 /// `Alone` punctuation tokens can be followed by any other tokens. In token streams parsed
943 /// from source code, the compiler will set spacing to `Alone` in all cases not covered by the
944 /// conditions for `Joint` above. E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`. In
945 /// particular, tokens not followed by anything will be marked as `Alone`.
946 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
947 Alone,
948}
949
950impl Punct {
951 /// Creates a new `Punct` from the given character and spacing.
952 /// The `ch` argument must be a valid punctuation character permitted by the language,
953 /// otherwise the function will panic.
954 ///
955 /// The returned `Punct` will have the default span of `Span::call_site()`
956 /// which can be further configured with the `set_span` method below.
957 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
958 pub fn new(ch: char, spacing: Spacing) -> Punct {
959 const LEGAL_CHARS: &[char] = &[
960 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
961 ':', '#', '$', '?', '\'',
962 ];
963 if !LEGAL_CHARS.contains(&ch) {
964 panic!("unsupported character `{:?}`", ch);
965 }
966 Punct(bridge::Punct {
967 ch: ch as u8,
968 joint: spacing == Spacing::Joint,
969 span: Span::call_site().0,
970 })
971 }
972
973 /// Returns the value of this punctuation character as `char`.
974 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
975 pub fn as_char(&self) -> char {
976 self.0.ch as char
977 }
978
979 /// Returns the spacing of this punctuation character, indicating whether it can be potentially
980 /// combined into a multi-character operator with the following token (`Joint`), or whether the
981 /// operator has definitely ended (`Alone`).
982 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
983 pub fn spacing(&self) -> Spacing {
984 if self.0.joint { Spacing::Joint } else { Spacing::Alone }
985 }
986
987 /// Returns the span for this punctuation character.
988 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
989 pub fn span(&self) -> Span {
990 Span(self.0.span)
991 }
992
993 /// Configure the span for this punctuation character.
994 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
995 pub fn set_span(&mut self, span: Span) {
996 self.0.span = span.0;
997 }
998}
999
1000/// Prints the punctuation character as a string that should be losslessly convertible
1001/// back into the same character.
1002#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1003impl fmt::Display for Punct {
1004 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1005 write!(f, "{}", self.as_char())
1006 }
1007}
1008
1009#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1010impl fmt::Debug for Punct {
1011 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1012 f&mut DebugStruct<'_, '_>.debug_struct("Punct")
1013 .field("ch", &self.as_char())
1014 .field("spacing", &self.spacing())
1015 .field(name:"span", &self.span())
1016 .finish()
1017 }
1018}
1019
1020#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1021impl PartialEq<char> for Punct {
1022 fn eq(&self, rhs: &char) -> bool {
1023 self.as_char() == *rhs
1024 }
1025}
1026
1027#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1028impl PartialEq<Punct> for char {
1029 fn eq(&self, rhs: &Punct) -> bool {
1030 *self == rhs.as_char()
1031 }
1032}
1033
1034/// An identifier (`ident`).
1035#[derive(Clone)]
1036#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1037pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1038
1039impl Ident {
1040 /// Creates a new `Ident` with the given `string` as well as the specified
1041 /// `span`.
1042 /// The `string` argument must be a valid identifier permitted by the
1043 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
1044 ///
1045 /// Note that `span`, currently in rustc, configures the hygiene information
1046 /// for this identifier.
1047 ///
1048 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
1049 /// meaning that identifiers created with this span will be resolved as if they were written
1050 /// directly at the location of the macro call, and other code at the macro call site will be
1051 /// able to refer to them as well.
1052 ///
1053 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
1054 /// meaning that identifiers created with this span will be resolved at the location of the
1055 /// macro definition and other code at the macro call site will not be able to refer to them.
1056 ///
1057 /// Due to the current importance of hygiene this constructor, unlike other
1058 /// tokens, requires a `Span` to be specified at construction.
1059 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1060 pub fn new(string: &str, span: Span) -> Ident {
1061 Ident(bridge::Ident {
1062 sym: bridge::client::Symbol::new_ident(string, false),
1063 is_raw: false,
1064 span: span.0,
1065 })
1066 }
1067
1068 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
1069 /// The `string` argument be a valid identifier permitted by the language
1070 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
1071 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
1072 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1073 pub fn new_raw(string: &str, span: Span) -> Ident {
1074 Ident(bridge::Ident {
1075 sym: bridge::client::Symbol::new_ident(string, true),
1076 is_raw: true,
1077 span: span.0,
1078 })
1079 }
1080
1081 /// Returns the span of this `Ident`, encompassing the entire string returned
1082 /// by [`to_string`](ToString::to_string).
1083 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1084 pub fn span(&self) -> Span {
1085 Span(self.0.span)
1086 }
1087
1088 /// Configures the span of this `Ident`, possibly changing its hygiene context.
1089 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1090 pub fn set_span(&mut self, span: Span) {
1091 self.0.span = span.0;
1092 }
1093}
1094
1095/// Prints the identifier as a string that should be losslessly convertible back
1096/// into the same identifier.
1097#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1098impl fmt::Display for Ident {
1099 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1100 if self.0.is_raw {
1101 f.write_str(data:"r#")?;
1102 }
1103 fmt::Display::fmt(&self.0.sym, f)
1104 }
1105}
1106
1107#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1108impl fmt::Debug for Ident {
1109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1110 f&mut DebugStruct<'_, '_>.debug_struct("Ident")
1111 .field("ident", &self.to_string())
1112 .field(name:"span", &self.span())
1113 .finish()
1114 }
1115}
1116
1117/// A literal string (`"hello"`), byte string (`b"hello"`), C string (`c"hello"`),
1118/// character (`'a'`), byte character (`b'a'`), an integer or floating point number
1119/// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1120/// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
1121#[derive(Clone)]
1122#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1123pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1124
1125macro_rules! suffixed_int_literals {
1126 ($($name:ident => $kind:ident,)*) => ($(
1127 /// Creates a new suffixed integer literal with the specified value.
1128 ///
1129 /// This function will create an integer like `1u32` where the integer
1130 /// value specified is the first part of the token and the integral is
1131 /// also suffixed at the end.
1132 /// Literals created from negative numbers might not survive round-trips through
1133 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1134 ///
1135 /// Literals created through this method have the `Span::call_site()`
1136 /// span by default, which can be configured with the `set_span` method
1137 /// below.
1138 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1139 pub fn $name(n: $kind) -> Literal {
1140 Literal(bridge::Literal {
1141 kind: bridge::LitKind::Integer,
1142 symbol: bridge::client::Symbol::new(&n.to_string()),
1143 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1144 span: Span::call_site().0,
1145 })
1146 }
1147 )*)
1148}
1149
1150macro_rules! unsuffixed_int_literals {
1151 ($($name:ident => $kind:ident,)*) => ($(
1152 /// Creates a new unsuffixed integer literal with the specified value.
1153 ///
1154 /// This function will create an integer like `1` where the integer
1155 /// value specified is the first part of the token. No suffix is
1156 /// specified on this token, meaning that invocations like
1157 /// `Literal::i8_unsuffixed(1)` are equivalent to
1158 /// `Literal::u32_unsuffixed(1)`.
1159 /// Literals created from negative numbers might not survive rountrips through
1160 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1161 ///
1162 /// Literals created through this method have the `Span::call_site()`
1163 /// span by default, which can be configured with the `set_span` method
1164 /// below.
1165 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1166 pub fn $name(n: $kind) -> Literal {
1167 Literal(bridge::Literal {
1168 kind: bridge::LitKind::Integer,
1169 symbol: bridge::client::Symbol::new(&n.to_string()),
1170 suffix: None,
1171 span: Span::call_site().0,
1172 })
1173 }
1174 )*)
1175}
1176
1177impl Literal {
1178 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1179 Literal(bridge::Literal {
1180 kind,
1181 symbol: bridge::client::Symbol::new(value),
1182 suffix: suffix.map(bridge::client::Symbol::new),
1183 span: Span::call_site().0,
1184 })
1185 }
1186
1187 suffixed_int_literals! {
1188 u8_suffixed => u8,
1189 u16_suffixed => u16,
1190 u32_suffixed => u32,
1191 u64_suffixed => u64,
1192 u128_suffixed => u128,
1193 usize_suffixed => usize,
1194 i8_suffixed => i8,
1195 i16_suffixed => i16,
1196 i32_suffixed => i32,
1197 i64_suffixed => i64,
1198 i128_suffixed => i128,
1199 isize_suffixed => isize,
1200 }
1201
1202 unsuffixed_int_literals! {
1203 u8_unsuffixed => u8,
1204 u16_unsuffixed => u16,
1205 u32_unsuffixed => u32,
1206 u64_unsuffixed => u64,
1207 u128_unsuffixed => u128,
1208 usize_unsuffixed => usize,
1209 i8_unsuffixed => i8,
1210 i16_unsuffixed => i16,
1211 i32_unsuffixed => i32,
1212 i64_unsuffixed => i64,
1213 i128_unsuffixed => i128,
1214 isize_unsuffixed => isize,
1215 }
1216
1217 /// Creates a new unsuffixed floating-point literal.
1218 ///
1219 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1220 /// the float's value is emitted directly into the token but no suffix is
1221 /// used, so it may be inferred to be a `f64` later in the compiler.
1222 /// Literals created from negative numbers might not survive rountrips through
1223 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1224 ///
1225 /// # Panics
1226 ///
1227 /// This function requires that the specified float is finite, for
1228 /// example if it is infinity or NaN this function will panic.
1229 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1230 pub fn f32_unsuffixed(n: f32) -> Literal {
1231 if !n.is_finite() {
1232 panic!("Invalid float literal {n}");
1233 }
1234 let mut repr = n.to_string();
1235 if !repr.contains('.') {
1236 repr.push_str(".0");
1237 }
1238 Literal::new(bridge::LitKind::Float, &repr, None)
1239 }
1240
1241 /// Creates a new suffixed floating-point literal.
1242 ///
1243 /// This constructor will create a literal like `1.0f32` where the value
1244 /// specified is the preceding part of the token and `f32` is the suffix of
1245 /// the token. This token will always be inferred to be an `f32` in the
1246 /// compiler.
1247 /// Literals created from negative numbers might not survive rountrips through
1248 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1249 ///
1250 /// # Panics
1251 ///
1252 /// This function requires that the specified float is finite, for
1253 /// example if it is infinity or NaN this function will panic.
1254 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1255 pub fn f32_suffixed(n: f32) -> Literal {
1256 if !n.is_finite() {
1257 panic!("Invalid float literal {n}");
1258 }
1259 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1260 }
1261
1262 /// Creates a new unsuffixed floating-point literal.
1263 ///
1264 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1265 /// the float's value is emitted directly into the token but no suffix is
1266 /// used, so it may be inferred to be a `f64` later in the compiler.
1267 /// Literals created from negative numbers might not survive rountrips through
1268 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1269 ///
1270 /// # Panics
1271 ///
1272 /// This function requires that the specified float is finite, for
1273 /// example if it is infinity or NaN this function will panic.
1274 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1275 pub fn f64_unsuffixed(n: f64) -> Literal {
1276 if !n.is_finite() {
1277 panic!("Invalid float literal {n}");
1278 }
1279 let mut repr = n.to_string();
1280 if !repr.contains('.') {
1281 repr.push_str(".0");
1282 }
1283 Literal::new(bridge::LitKind::Float, &repr, None)
1284 }
1285
1286 /// Creates a new suffixed floating-point literal.
1287 ///
1288 /// This constructor will create a literal like `1.0f64` where the value
1289 /// specified is the preceding part of the token and `f64` is the suffix of
1290 /// the token. This token will always be inferred to be an `f64` in the
1291 /// compiler.
1292 /// Literals created from negative numbers might not survive rountrips through
1293 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1294 ///
1295 /// # Panics
1296 ///
1297 /// This function requires that the specified float is finite, for
1298 /// example if it is infinity or NaN this function will panic.
1299 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1300 pub fn f64_suffixed(n: f64) -> Literal {
1301 if !n.is_finite() {
1302 panic!("Invalid float literal {n}");
1303 }
1304 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1305 }
1306
1307 /// String literal.
1308 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1309 pub fn string(string: &str) -> Literal {
1310 let escape = EscapeOptions {
1311 escape_single_quote: false,
1312 escape_double_quote: true,
1313 escape_nonascii: false,
1314 };
1315 let repr = escape_bytes(string.as_bytes(), escape);
1316 Literal::new(bridge::LitKind::Str, &repr, None)
1317 }
1318
1319 /// Character literal.
1320 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1321 pub fn character(ch: char) -> Literal {
1322 let escape = EscapeOptions {
1323 escape_single_quote: true,
1324 escape_double_quote: false,
1325 escape_nonascii: false,
1326 };
1327 let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1328 Literal::new(bridge::LitKind::Char, &repr, None)
1329 }
1330
1331 /// Byte character literal.
1332 #[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1333 pub fn byte_character(byte: u8) -> Literal {
1334 let escape = EscapeOptions {
1335 escape_single_quote: true,
1336 escape_double_quote: false,
1337 escape_nonascii: true,
1338 };
1339 let repr = escape_bytes(&[byte], escape);
1340 Literal::new(bridge::LitKind::Byte, &repr, None)
1341 }
1342
1343 /// Byte string literal.
1344 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1345 pub fn byte_string(bytes: &[u8]) -> Literal {
1346 let escape = EscapeOptions {
1347 escape_single_quote: false,
1348 escape_double_quote: true,
1349 escape_nonascii: true,
1350 };
1351 let repr = escape_bytes(bytes, escape);
1352 Literal::new(bridge::LitKind::ByteStr, &repr, None)
1353 }
1354
1355 /// C string literal.
1356 #[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1357 pub fn c_string(string: &CStr) -> Literal {
1358 let escape = EscapeOptions {
1359 escape_single_quote: false,
1360 escape_double_quote: true,
1361 escape_nonascii: false,
1362 };
1363 let repr = escape_bytes(string.to_bytes(), escape);
1364 Literal::new(bridge::LitKind::CStr, &repr, None)
1365 }
1366
1367 /// Returns the span encompassing this literal.
1368 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1369 pub fn span(&self) -> Span {
1370 Span(self.0.span)
1371 }
1372
1373 /// Configures the span associated for this literal.
1374 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1375 pub fn set_span(&mut self, span: Span) {
1376 self.0.span = span.0;
1377 }
1378
1379 /// Returns a `Span` that is a subset of `self.span()` containing only the
1380 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1381 /// span is outside the bounds of `self`.
1382 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1383 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1384 // occur elsewhere when the source text is printed.
1385 // FIXME(SergioBenitez): there is no way for the user to know what
1386 // `self.span()` actually maps to, so this method can currently only be
1387 // called blindly. For example, `to_string()` for the character 'c' returns
1388 // "'\u{63}'"; there is no way for the user to know whether the source text
1389 // was 'c' or whether it was '\u{63}'.
1390 #[unstable(feature = "proc_macro_span", issue = "54725")]
1391 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1392 self.0.span.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span)
1393 }
1394
1395 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1396 self.0.symbol.with(|symbol| match self.0.suffix {
1397 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1398 None => f(symbol, ""),
1399 })
1400 }
1401
1402 /// Invokes the callback with a `&[&str]` consisting of each part of the
1403 /// literal's representation. This is done to allow the `ToString` and
1404 /// `Display` implementations to borrow references to symbol values, and
1405 /// both be optimized to reduce overhead.
1406 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1407 /// Returns a string containing exactly `num` '#' characters.
1408 /// Uses a 256-character source string literal which is always safe to
1409 /// index with a `u8` index.
1410 fn get_hashes_str(num: u8) -> &'static str {
1411 const HASHES: &str = "\
1412 ################################################################\
1413 ################################################################\
1414 ################################################################\
1415 ################################################################\
1416 ";
1417 const _: () = assert!(HASHES.len() == 256);
1418 &HASHES[..num as usize]
1419 }
1420
1421 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1422 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1423 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1424 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1425 bridge::LitKind::StrRaw(n) => {
1426 let hashes = get_hashes_str(n);
1427 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1428 }
1429 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1430 bridge::LitKind::ByteStrRaw(n) => {
1431 let hashes = get_hashes_str(n);
1432 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1433 }
1434 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1435 bridge::LitKind::CStrRaw(n) => {
1436 let hashes = get_hashes_str(n);
1437 f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1438 }
1439
1440 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1441 f(&[symbol, suffix])
1442 }
1443 })
1444 }
1445
1446 /// Returns the unescaped string value if the current literal is a string or a string literal.
1447 #[unstable(feature = "proc_macro_value", issue = "136652")]
1448 pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1449 self.0.symbol.with(|symbol| match self.0.kind {
1450 bridge::LitKind::Str => {
1451 if symbol.contains('\\') {
1452 let mut buf = String::with_capacity(symbol.len());
1453 let mut error = None;
1454 // Force-inlining here is aggressive but the closure is
1455 // called on every char in the string, so it can be hot in
1456 // programs with many long strings containing escapes.
1457 unescape_str(
1458 symbol,
1459 #[inline(always)]
1460 |_, c| match c {
1461 Ok(c) => buf.push(c),
1462 Err(err) => {
1463 if err.is_fatal() {
1464 error = Some(ConversionErrorKind::FailedToUnescape(err));
1465 }
1466 }
1467 },
1468 );
1469 if let Some(error) = error { Err(error) } else { Ok(buf) }
1470 } else {
1471 Ok(symbol.to_string())
1472 }
1473 }
1474 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1475 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1476 })
1477 }
1478
1479 /// Returns the unescaped string value if the current literal is a c-string or a c-string
1480 /// literal.
1481 #[unstable(feature = "proc_macro_value", issue = "136652")]
1482 pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1483 self.0.symbol.with(|symbol| match self.0.kind {
1484 bridge::LitKind::CStr => {
1485 let mut error = None;
1486 let mut buf = Vec::with_capacity(symbol.len());
1487
1488 unescape_c_str(symbol, |_span, res| match res {
1489 Ok(MixedUnit::Char(c)) => {
1490 buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1491 }
1492 Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1493 Err(err) => {
1494 if err.is_fatal() {
1495 error = Some(ConversionErrorKind::FailedToUnescape(err));
1496 }
1497 }
1498 });
1499 if let Some(error) = error {
1500 Err(error)
1501 } else {
1502 buf.push(0);
1503 Ok(buf)
1504 }
1505 }
1506 bridge::LitKind::CStrRaw(_) => {
1507 // Raw strings have no escapes so we can convert the symbol
1508 // directly to a `Lrc<u8>` after appending the terminating NUL
1509 // char.
1510 let mut buf = symbol.to_owned().into_bytes();
1511 buf.push(0);
1512 Ok(buf)
1513 }
1514 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1515 })
1516 }
1517
1518 /// Returns the unescaped string value if the current literal is a byte string or a byte string
1519 /// literal.
1520 #[unstable(feature = "proc_macro_value", issue = "136652")]
1521 pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1522 self.0.symbol.with(|symbol| match self.0.kind {
1523 bridge::LitKind::ByteStr => {
1524 let mut buf = Vec::with_capacity(symbol.len());
1525 let mut error = None;
1526
1527 unescape_byte_str(symbol, |_, res| match res {
1528 Ok(b) => buf.push(b),
1529 Err(err) => {
1530 if err.is_fatal() {
1531 error = Some(ConversionErrorKind::FailedToUnescape(err));
1532 }
1533 }
1534 });
1535 if let Some(error) = error { Err(error) } else { Ok(buf) }
1536 }
1537 bridge::LitKind::ByteStrRaw(_) => {
1538 // Raw strings have no escapes so we can convert the symbol
1539 // directly to a `Lrc<u8>`.
1540 Ok(symbol.to_owned().into_bytes())
1541 }
1542 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1543 })
1544 }
1545}
1546
1547/// Parse a single literal from its stringified representation.
1548///
1549/// In order to parse successfully, the input string must not contain anything
1550/// but the literal token. Specifically, it must not contain whitespace or
1551/// comments in addition to the literal.
1552///
1553/// The resulting literal token will have a `Span::call_site()` span.
1554///
1555/// NOTE: some errors may cause panics instead of returning `LexError`. We
1556/// reserve the right to change these errors into `LexError`s later.
1557#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1558impl FromStr for Literal {
1559 type Err = LexError;
1560
1561 fn from_str(src: &str) -> Result<Self, LexError> {
1562 match bridge::client::FreeFunctions::literal_from_str(src) {
1563 Ok(literal: Literal) => Ok(Literal(literal)),
1564 Err(()) => Err(LexError),
1565 }
1566 }
1567}
1568
1569/// Prints the literal as a string that should be losslessly convertible
1570/// back into the same literal (except for possible rounding for floating point literals).
1571#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1572impl fmt::Display for Literal {
1573 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1574 self.with_stringify_parts(|parts: &[&str]| {
1575 for part: &&str in parts {
1576 fmt::Display::fmt(self:part, f)?;
1577 }
1578 Ok(())
1579 })
1580 }
1581}
1582
1583#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1584impl fmt::Debug for Literal {
1585 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1586 f&mut DebugStruct<'_, '_>.debug_struct("Literal")
1587 // format the kind on one line even in {:#?} mode
1588 .field("kind", &format_args!("{:?}", self.0.kind))
1589 .field("symbol", &self.0.symbol)
1590 // format `Some("...")` on one line even in {:#?} mode
1591 .field("suffix", &format_args!("{:?}", self.0.suffix))
1592 .field(name:"span", &self.0.span)
1593 .finish()
1594 }
1595}
1596
1597/// Tracked access to environment variables.
1598#[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1599pub mod tracked_env {
1600 use std::env::{self, VarError};
1601 use std::ffi::OsStr;
1602
1603 /// Retrieve an environment variable and add it to build dependency info.
1604 /// The build system executing the compiler will know that the variable was accessed during
1605 /// compilation, and will be able to rerun the build when the value of that variable changes.
1606 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1607 /// standard library, except that the argument must be UTF-8.
1608 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1609 pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1610 let key: &str = key.as_ref();
1611 let value: Result = crate::bridge::client::FreeFunctions::injected_env_var(key)
1612 .map_or_else(|| env::var(key), f:Ok);
1613 crate::bridge::client::FreeFunctions::track_env_var(var:key, value.as_deref().ok());
1614 value
1615 }
1616}
1617
1618/// Tracked access to additional files.
1619#[unstable(feature = "track_path", issue = "99515")]
1620pub mod tracked_path {
1621
1622 /// Track a file explicitly.
1623 ///
1624 /// Commonly used for tracking asset preprocessing.
1625 #[unstable(feature = "track_path", issue = "99515")]
1626 pub fn path<P: AsRef<str>>(path: P) {
1627 let path: &str = path.as_ref();
1628 crate::bridge::client::FreeFunctions::track_path(path);
1629 }
1630}
1631