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