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