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