]> git.lizzy.rs Git - rust.git/blob - library/proc_macro/src/lib.rs
Auto merge of #94799 - lcnr:list-ty-perf, r=petrochenkov
[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 are not directly writable in normal Rust code except as comments.
711     /// Therefore, they might not survive a roundtrip of a token stream through a string.
712     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
713     None,
714 }
715
716 impl Group {
717     /// Creates a new `Group` with the given delimiter and token stream.
718     ///
719     /// This constructor will set the span for this group to
720     /// `Span::call_site()`. To change the span you can use the `set_span`
721     /// method below.
722     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
723     pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
724         Group(bridge::client::Group::new(delimiter, stream.0))
725     }
726
727     /// Returns the delimiter of this `Group`
728     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
729     pub fn delimiter(&self) -> Delimiter {
730         self.0.delimiter()
731     }
732
733     /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
734     ///
735     /// Note that the returned token stream does not include the delimiter
736     /// returned above.
737     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
738     pub fn stream(&self) -> TokenStream {
739         TokenStream(self.0.stream())
740     }
741
742     /// Returns the span for the delimiters of this token stream, spanning the
743     /// entire `Group`.
744     ///
745     /// ```text
746     /// pub fn span(&self) -> Span {
747     ///            ^^^^^^^
748     /// ```
749     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
750     pub fn span(&self) -> Span {
751         Span(self.0.span())
752     }
753
754     /// Returns the span pointing to the opening delimiter of this group.
755     ///
756     /// ```text
757     /// pub fn span_open(&self) -> Span {
758     ///                 ^
759     /// ```
760     #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
761     pub fn span_open(&self) -> Span {
762         Span(self.0.span_open())
763     }
764
765     /// Returns the span pointing to the closing delimiter of this group.
766     ///
767     /// ```text
768     /// pub fn span_close(&self) -> Span {
769     ///                        ^
770     /// ```
771     #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
772     pub fn span_close(&self) -> Span {
773         Span(self.0.span_close())
774     }
775
776     /// Configures the span for this `Group`'s delimiters, but not its internal
777     /// tokens.
778     ///
779     /// This method will **not** set the span of all the internal tokens spanned
780     /// by this group, but rather it will only set the span of the delimiter
781     /// tokens at the level of the `Group`.
782     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
783     pub fn set_span(&mut self, span: Span) {
784         self.0.set_span(span.0);
785     }
786 }
787
788 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
789 // based on it (the reverse of the usual relationship between the two).
790 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
791 impl ToString for Group {
792     fn to_string(&self) -> String {
793         TokenStream::from(TokenTree::from(self.clone())).to_string()
794     }
795 }
796
797 /// Prints the group as a string that should be losslessly convertible back
798 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
799 /// with `Delimiter::None` delimiters.
800 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
801 impl fmt::Display for Group {
802     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
803         f.write_str(&self.to_string())
804     }
805 }
806
807 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
808 impl fmt::Debug for Group {
809     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
810         f.debug_struct("Group")
811             .field("delimiter", &self.delimiter())
812             .field("stream", &self.stream())
813             .field("span", &self.span())
814             .finish()
815     }
816 }
817
818 /// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
819 ///
820 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
821 /// forms of `Spacing` returned.
822 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
823 #[derive(Clone)]
824 pub struct Punct(bridge::client::Punct);
825
826 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
827 impl !Send for Punct {}
828 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
829 impl !Sync for Punct {}
830
831 /// Describes whether a `Punct` is followed immediately by another `Punct` ([`Spacing::Joint`]) or
832 /// by a different token or whitespace ([`Spacing::Alone`]).
833 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
834 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
835 pub enum Spacing {
836     /// A `Punct` is not immediately followed by another `Punct`.
837     /// E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`.
838     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
839     Alone,
840     /// A `Punct` is immediately followed by another `Punct`.
841     /// E.g. `+` is `Joint` in `+=` and `++`.
842     ///
843     /// Additionally, single quote `'` can join with identifiers to form lifetimes: `'ident`.
844     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
845     Joint,
846 }
847
848 impl Punct {
849     /// Creates a new `Punct` from the given character and spacing.
850     /// The `ch` argument must be a valid punctuation character permitted by the language,
851     /// otherwise the function will panic.
852     ///
853     /// The returned `Punct` will have the default span of `Span::call_site()`
854     /// which can be further configured with the `set_span` method below.
855     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
856     pub fn new(ch: char, spacing: Spacing) -> Punct {
857         Punct(bridge::client::Punct::new(ch, spacing))
858     }
859
860     /// Returns the value of this punctuation character as `char`.
861     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
862     pub fn as_char(&self) -> char {
863         self.0.as_char()
864     }
865
866     /// Returns the spacing of this punctuation character, indicating whether it's immediately
867     /// followed by another `Punct` in the token stream, so they can potentially be combined into
868     /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
869     /// (`Alone`) so the operator has certainly ended.
870     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
871     pub fn spacing(&self) -> Spacing {
872         self.0.spacing()
873     }
874
875     /// Returns the span for this punctuation character.
876     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
877     pub fn span(&self) -> Span {
878         Span(self.0.span())
879     }
880
881     /// Configure the span for this punctuation character.
882     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
883     pub fn set_span(&mut self, span: Span) {
884         self.0 = self.0.with_span(span.0);
885     }
886 }
887
888 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
889 // based on it (the reverse of the usual relationship between the two).
890 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
891 impl ToString for Punct {
892     fn to_string(&self) -> String {
893         TokenStream::from(TokenTree::from(self.clone())).to_string()
894     }
895 }
896
897 /// Prints the punctuation character as a string that should be losslessly convertible
898 /// back into the same character.
899 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
900 impl fmt::Display for Punct {
901     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
902         f.write_str(&self.to_string())
903     }
904 }
905
906 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
907 impl fmt::Debug for Punct {
908     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
909         f.debug_struct("Punct")
910             .field("ch", &self.as_char())
911             .field("spacing", &self.spacing())
912             .field("span", &self.span())
913             .finish()
914     }
915 }
916
917 #[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
918 impl PartialEq<char> for Punct {
919     fn eq(&self, rhs: &char) -> bool {
920         self.as_char() == *rhs
921     }
922 }
923
924 #[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
925 impl PartialEq<Punct> for char {
926     fn eq(&self, rhs: &Punct) -> bool {
927         *self == rhs.as_char()
928     }
929 }
930
931 /// An identifier (`ident`).
932 #[derive(Clone)]
933 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
934 pub struct Ident(bridge::client::Ident);
935
936 impl Ident {
937     /// Creates a new `Ident` with the given `string` as well as the specified
938     /// `span`.
939     /// The `string` argument must be a valid identifier permitted by the
940     /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
941     ///
942     /// Note that `span`, currently in rustc, configures the hygiene information
943     /// for this identifier.
944     ///
945     /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
946     /// meaning that identifiers created with this span will be resolved as if they were written
947     /// directly at the location of the macro call, and other code at the macro call site will be
948     /// able to refer to them as well.
949     ///
950     /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
951     /// meaning that identifiers created with this span will be resolved at the location of the
952     /// macro definition and other code at the macro call site will not be able to refer to them.
953     ///
954     /// Due to the current importance of hygiene this constructor, unlike other
955     /// tokens, requires a `Span` to be specified at construction.
956     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
957     pub fn new(string: &str, span: Span) -> Ident {
958         Ident(bridge::client::Ident::new(string, span.0, false))
959     }
960
961     /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
962     /// The `string` argument be a valid identifier permitted by the language
963     /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
964     /// (e.g. `self`, `super`) are not supported, and will cause a panic.
965     #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
966     pub fn new_raw(string: &str, span: Span) -> Ident {
967         Ident(bridge::client::Ident::new(string, span.0, true))
968     }
969
970     /// Returns the span of this `Ident`, encompassing the entire string returned
971     /// by [`to_string`](Self::to_string).
972     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
973     pub fn span(&self) -> Span {
974         Span(self.0.span())
975     }
976
977     /// Configures the span of this `Ident`, possibly changing its hygiene context.
978     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
979     pub fn set_span(&mut self, span: Span) {
980         self.0 = self.0.with_span(span.0);
981     }
982 }
983
984 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
985 // based on it (the reverse of the usual relationship between the two).
986 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
987 impl ToString for Ident {
988     fn to_string(&self) -> String {
989         TokenStream::from(TokenTree::from(self.clone())).to_string()
990     }
991 }
992
993 /// Prints the identifier as a string that should be losslessly convertible
994 /// back into the same identifier.
995 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
996 impl fmt::Display for Ident {
997     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
998         f.write_str(&self.to_string())
999     }
1000 }
1001
1002 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1003 impl fmt::Debug for Ident {
1004     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1005         f.debug_struct("Ident")
1006             .field("ident", &self.to_string())
1007             .field("span", &self.span())
1008             .finish()
1009     }
1010 }
1011
1012 /// A literal string (`"hello"`), byte string (`b"hello"`),
1013 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
1014 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1015 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
1016 #[derive(Clone)]
1017 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1018 pub struct Literal(bridge::client::Literal);
1019
1020 macro_rules! suffixed_int_literals {
1021     ($($name:ident => $kind:ident,)*) => ($(
1022         /// Creates a new suffixed integer literal with the specified value.
1023         ///
1024         /// This function will create an integer like `1u32` where the integer
1025         /// value specified is the first part of the token and the integral is
1026         /// also suffixed at the end.
1027         /// Literals created from negative numbers might not survive round-trips through
1028         /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1029         ///
1030         /// Literals created through this method have the `Span::call_site()`
1031         /// span by default, which can be configured with the `set_span` method
1032         /// below.
1033         #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1034         pub fn $name(n: $kind) -> Literal {
1035             Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
1036         }
1037     )*)
1038 }
1039
1040 macro_rules! unsuffixed_int_literals {
1041     ($($name:ident => $kind:ident,)*) => ($(
1042         /// Creates a new unsuffixed integer literal with the specified value.
1043         ///
1044         /// This function will create an integer like `1` where the integer
1045         /// value specified is the first part of the token. No suffix is
1046         /// specified on this token, meaning that invocations like
1047         /// `Literal::i8_unsuffixed(1)` are equivalent to
1048         /// `Literal::u32_unsuffixed(1)`.
1049         /// Literals created from negative numbers might not survive rountrips through
1050         /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1051         ///
1052         /// Literals created through this method have the `Span::call_site()`
1053         /// span by default, which can be configured with the `set_span` method
1054         /// below.
1055         #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1056         pub fn $name(n: $kind) -> Literal {
1057             Literal(bridge::client::Literal::integer(&n.to_string()))
1058         }
1059     )*)
1060 }
1061
1062 impl Literal {
1063     suffixed_int_literals! {
1064         u8_suffixed => u8,
1065         u16_suffixed => u16,
1066         u32_suffixed => u32,
1067         u64_suffixed => u64,
1068         u128_suffixed => u128,
1069         usize_suffixed => usize,
1070         i8_suffixed => i8,
1071         i16_suffixed => i16,
1072         i32_suffixed => i32,
1073         i64_suffixed => i64,
1074         i128_suffixed => i128,
1075         isize_suffixed => isize,
1076     }
1077
1078     unsuffixed_int_literals! {
1079         u8_unsuffixed => u8,
1080         u16_unsuffixed => u16,
1081         u32_unsuffixed => u32,
1082         u64_unsuffixed => u64,
1083         u128_unsuffixed => u128,
1084         usize_unsuffixed => usize,
1085         i8_unsuffixed => i8,
1086         i16_unsuffixed => i16,
1087         i32_unsuffixed => i32,
1088         i64_unsuffixed => i64,
1089         i128_unsuffixed => i128,
1090         isize_unsuffixed => isize,
1091     }
1092
1093     /// Creates a new unsuffixed floating-point literal.
1094     ///
1095     /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1096     /// the float's value is emitted directly into the token but no suffix is
1097     /// used, so it may be inferred to be a `f64` later in the compiler.
1098     /// Literals created from negative numbers might not survive rountrips through
1099     /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1100     ///
1101     /// # Panics
1102     ///
1103     /// This function requires that the specified float is finite, for
1104     /// example if it is infinity or NaN this function will panic.
1105     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1106     pub fn f32_unsuffixed(n: f32) -> Literal {
1107         if !n.is_finite() {
1108             panic!("Invalid float literal {n}");
1109         }
1110         let mut repr = n.to_string();
1111         if !repr.contains('.') {
1112             repr.push_str(".0");
1113         }
1114         Literal(bridge::client::Literal::float(&repr))
1115     }
1116
1117     /// Creates a new suffixed floating-point literal.
1118     ///
1119     /// This constructor will create a literal like `1.0f32` where the value
1120     /// specified is the preceding part of the token and `f32` is the suffix of
1121     /// the token. This token will always be inferred to be an `f32` in the
1122     /// compiler.
1123     /// Literals created from negative numbers might not survive rountrips through
1124     /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1125     ///
1126     /// # Panics
1127     ///
1128     /// This function requires that the specified float is finite, for
1129     /// example if it is infinity or NaN this function will panic.
1130     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1131     pub fn f32_suffixed(n: f32) -> Literal {
1132         if !n.is_finite() {
1133             panic!("Invalid float literal {n}");
1134         }
1135         Literal(bridge::client::Literal::f32(&n.to_string()))
1136     }
1137
1138     /// Creates a new unsuffixed floating-point literal.
1139     ///
1140     /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1141     /// the float's value is emitted directly into the token but no suffix is
1142     /// used, so it may be inferred to be a `f64` later in the compiler.
1143     /// Literals created from negative numbers might not survive rountrips through
1144     /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1145     ///
1146     /// # Panics
1147     ///
1148     /// This function requires that the specified float is finite, for
1149     /// example if it is infinity or NaN this function will panic.
1150     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1151     pub fn f64_unsuffixed(n: f64) -> Literal {
1152         if !n.is_finite() {
1153             panic!("Invalid float literal {n}");
1154         }
1155         let mut repr = n.to_string();
1156         if !repr.contains('.') {
1157             repr.push_str(".0");
1158         }
1159         Literal(bridge::client::Literal::float(&repr))
1160     }
1161
1162     /// Creates a new suffixed floating-point literal.
1163     ///
1164     /// This constructor will create a literal like `1.0f64` where the value
1165     /// specified is the preceding part of the token and `f64` is the suffix of
1166     /// the token. This token will always be inferred to be an `f64` in the
1167     /// compiler.
1168     /// Literals created from negative numbers might not survive rountrips through
1169     /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1170     ///
1171     /// # Panics
1172     ///
1173     /// This function requires that the specified float is finite, for
1174     /// example if it is infinity or NaN this function will panic.
1175     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1176     pub fn f64_suffixed(n: f64) -> Literal {
1177         if !n.is_finite() {
1178             panic!("Invalid float literal {n}");
1179         }
1180         Literal(bridge::client::Literal::f64(&n.to_string()))
1181     }
1182
1183     /// String literal.
1184     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1185     pub fn string(string: &str) -> Literal {
1186         Literal(bridge::client::Literal::string(string))
1187     }
1188
1189     /// Character literal.
1190     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1191     pub fn character(ch: char) -> Literal {
1192         Literal(bridge::client::Literal::character(ch))
1193     }
1194
1195     /// Byte string literal.
1196     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1197     pub fn byte_string(bytes: &[u8]) -> Literal {
1198         Literal(bridge::client::Literal::byte_string(bytes))
1199     }
1200
1201     /// Returns the span encompassing this literal.
1202     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1203     pub fn span(&self) -> Span {
1204         Span(self.0.span())
1205     }
1206
1207     /// Configures the span associated for this literal.
1208     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1209     pub fn set_span(&mut self, span: Span) {
1210         self.0.set_span(span.0);
1211     }
1212
1213     /// Returns a `Span` that is a subset of `self.span()` containing only the
1214     /// source bytes in range `range`. Returns `None` if the would-be trimmed
1215     /// span is outside the bounds of `self`.
1216     // FIXME(SergioBenitez): check that the byte range starts and ends at a
1217     // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1218     // occur elsewhere when the source text is printed.
1219     // FIXME(SergioBenitez): there is no way for the user to know what
1220     // `self.span()` actually maps to, so this method can currently only be
1221     // called blindly. For example, `to_string()` for the character 'c' returns
1222     // "'\u{63}'"; there is no way for the user to know whether the source text
1223     // was 'c' or whether it was '\u{63}'.
1224     #[unstable(feature = "proc_macro_span", issue = "54725")]
1225     pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1226         self.0.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span)
1227     }
1228 }
1229
1230 /// Parse a single literal from its stringified representation.
1231 ///
1232 /// In order to parse successfully, the input string must not contain anything
1233 /// but the literal token. Specifically, it must not contain whitespace or
1234 /// comments in addition to the literal.
1235 ///
1236 /// The resulting literal token will have a `Span::call_site()` span.
1237 ///
1238 /// NOTE: some errors may cause panics instead of returning `LexError`. We
1239 /// reserve the right to change these errors into `LexError`s later.
1240 #[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1241 impl FromStr for Literal {
1242     type Err = LexError;
1243
1244     fn from_str(src: &str) -> Result<Self, LexError> {
1245         match bridge::client::Literal::from_str(src) {
1246             Ok(literal) => Ok(Literal(literal)),
1247             Err(()) => Err(LexError),
1248         }
1249     }
1250 }
1251
1252 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1253 // based on it (the reverse of the usual relationship between the two).
1254 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1255 impl ToString for Literal {
1256     fn to_string(&self) -> String {
1257         self.0.to_string()
1258     }
1259 }
1260
1261 /// Prints the literal as a string that should be losslessly convertible
1262 /// back into the same literal (except for possible rounding for floating point literals).
1263 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1264 impl fmt::Display for Literal {
1265     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1266         f.write_str(&self.to_string())
1267     }
1268 }
1269
1270 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1271 impl fmt::Debug for Literal {
1272     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1273         self.0.fmt(f)
1274     }
1275 }
1276
1277 /// Tracked access to environment variables.
1278 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1279 pub mod tracked_env {
1280     use std::env::{self, VarError};
1281     use std::ffi::OsStr;
1282
1283     /// Retrieve an environment variable and add it to build dependency info.
1284     /// Build system executing the compiler will know that the variable was accessed during
1285     /// compilation, and will be able to rerun the build when the value of that variable changes.
1286     /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1287     /// standard library, except that the argument must be UTF-8.
1288     #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1289     pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1290         let key: &str = key.as_ref();
1291         let value = env::var(key);
1292         crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());
1293         value
1294     }
1295 }
1296
1297 /// Tracked access to additional files.
1298 #[unstable(feature = "track_path", issue = "73921")]
1299 pub mod tracked_path {
1300
1301     /// Track a file explicitly.
1302     ///
1303     /// Commonly used for tracking asset preprocessing.
1304     #[unstable(feature = "track_path", issue = "73921")]
1305     pub fn path<P: AsRef<str>>(path: P) {
1306         let path: &str = path.as_ref();
1307         crate::bridge::client::FreeFunctions::track_path(path);
1308     }
1309 }