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