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