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