]> git.lizzy.rs Git - rust.git/blob - library/proc_macro/src/lib.rs
Rollup merge of #91987 - jsha:docdocgoose, r=jyn514
[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 #![feature(rustc_allow_const_fn_unstable)]
21 #![feature(nll)]
22 #![feature(staged_api)]
23 #![feature(const_fn_trait_bound)]
24 #![feature(const_fn_fn_ptr_basics)]
25 #![feature(allow_internal_unstable)]
26 #![feature(decl_macro)]
27 #![feature(extern_types)]
28 #![feature(negative_impls)]
29 #![feature(auto_traits)]
30 #![feature(restricted_std)]
31 #![feature(rustc_attrs)]
32 #![feature(min_specialization)]
33 #![recursion_limit = "256"]
34
35 #[unstable(feature = "proc_macro_internals", issue = "27812")]
36 #[doc(hidden)]
37 pub mod bridge;
38
39 mod diagnostic;
40
41 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
42 pub use diagnostic::{Diagnostic, Level, MultiSpan};
43
44 use std::cmp::Ordering;
45 use std::ops::RangeBounds;
46 use std::path::PathBuf;
47 use std::str::FromStr;
48 use std::{error, fmt, iter, mem};
49
50 /// Determines whether proc_macro has been made accessible to the currently
51 /// running program.
52 ///
53 /// The proc_macro crate is only intended for use inside the implementation of
54 /// procedural macros. All the functions in this crate panic if invoked from
55 /// outside of a procedural macro, such as from a build script or unit test or
56 /// ordinary Rust binary.
57 ///
58 /// With consideration for Rust libraries that are designed to support both
59 /// macro and non-macro use cases, `proc_macro::is_available()` provides a
60 /// non-panicking way to detect whether the infrastructure required to use the
61 /// API of proc_macro is presently available. Returns true if invoked from
62 /// inside of a procedural macro, false if invoked from any other binary.
63 #[stable(feature = "proc_macro_is_available", since = "1.57.0")]
64 pub fn is_available() -> bool {
65     bridge::Bridge::is_available()
66 }
67
68 /// The main type provided by this crate, representing an abstract stream of
69 /// tokens, or, more specifically, a sequence of token trees.
70 /// The type provide interfaces for iterating over those token trees and, conversely,
71 /// collecting a number of token trees into one stream.
72 ///
73 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
74 /// and `#[proc_macro_derive]` definitions.
75 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
76 #[derive(Clone)]
77 pub struct TokenStream(bridge::client::TokenStream);
78
79 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
80 impl !Send for TokenStream {}
81 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
82 impl !Sync for TokenStream {}
83
84 /// Error returned from `TokenStream::from_str`.
85 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
86 #[non_exhaustive]
87 #[derive(Debug)]
88 pub struct LexError;
89
90 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
91 impl fmt::Display for LexError {
92     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93         f.write_str("cannot parse string into token stream")
94     }
95 }
96
97 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
98 impl error::Error for LexError {}
99
100 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
101 impl !Send for LexError {}
102 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
103 impl !Sync for LexError {}
104
105 /// Error returned from `TokenStream::expand_expr`.
106 #[unstable(feature = "proc_macro_expand", issue = "90765")]
107 #[non_exhaustive]
108 #[derive(Debug)]
109 pub struct ExpandError;
110
111 #[unstable(feature = "proc_macro_expand", issue = "90765")]
112 impl fmt::Display for ExpandError {
113     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114         f.write_str("macro expansion failed")
115     }
116 }
117
118 #[unstable(feature = "proc_macro_expand", issue = "90765")]
119 impl error::Error for ExpandError {}
120
121 #[unstable(feature = "proc_macro_expand", issue = "90765")]
122 impl !Send for ExpandError {}
123
124 #[unstable(feature = "proc_macro_expand", issue = "90765")]
125 impl !Sync for ExpandError {}
126
127 impl TokenStream {
128     /// Returns an empty `TokenStream` containing no token trees.
129     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
130     pub fn new() -> TokenStream {
131         TokenStream(bridge::client::TokenStream::new())
132     }
133
134     /// Checks if this `TokenStream` is empty.
135     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
136     pub fn is_empty(&self) -> bool {
137         self.0.is_empty()
138     }
139
140     /// Parses this `TokenStream` as an expression and attempts to expand any
141     /// macros within it. Returns the expanded `TokenStream`.
142     ///
143     /// Currently only expressions expanding to literals will succeed, although
144     /// this may be relaxed in the future.
145     ///
146     /// NOTE: In error conditions, `expand_expr` may leave macros unexpanded,
147     /// report an error, failing compilation, and/or return an `Err(..)`. The
148     /// specific behavior for any error condition, and what conditions are
149     /// considered errors, is unspecified and may change in the future.
150     #[unstable(feature = "proc_macro_expand", issue = "90765")]
151     pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
152         match bridge::client::TokenStream::expand_expr(&self.0) {
153             Ok(stream) => Ok(TokenStream(stream)),
154             Err(_) => Err(ExpandError),
155         }
156     }
157 }
158
159 /// Attempts to break the string into tokens and parse those tokens into a token stream.
160 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
161 /// or characters not existing in the language.
162 /// All tokens in the parsed stream get `Span::call_site()` spans.
163 ///
164 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
165 /// change these errors into `LexError`s later.
166 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
167 impl FromStr for TokenStream {
168     type Err = LexError;
169
170     fn from_str(src: &str) -> Result<TokenStream, LexError> {
171         Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
172     }
173 }
174
175 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
176 // based on it (the reverse of the usual relationship between the two).
177 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
178 impl ToString for TokenStream {
179     fn to_string(&self) -> String {
180         self.0.to_string()
181     }
182 }
183
184 /// Prints the token stream as a string that is supposed to be losslessly convertible back
185 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
186 /// with `Delimiter::None` delimiters and negative numeric literals.
187 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
188 impl fmt::Display for TokenStream {
189     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190         f.write_str(&self.to_string())
191     }
192 }
193
194 /// Prints token in a form convenient for debugging.
195 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
196 impl fmt::Debug for TokenStream {
197     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198         f.write_str("TokenStream ")?;
199         f.debug_list().entries(self.clone()).finish()
200     }
201 }
202
203 #[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
204 impl Default for TokenStream {
205     fn default() -> Self {
206         TokenStream::new()
207     }
208 }
209
210 #[unstable(feature = "proc_macro_quote", issue = "54722")]
211 pub use quote::{quote, quote_span};
212
213 /// Creates a token stream containing a single token tree.
214 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
215 impl From<TokenTree> for TokenStream {
216     fn from(tree: TokenTree) -> TokenStream {
217         TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
218             TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
219             TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
220             TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
221             TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
222         }))
223     }
224 }
225
226 /// Collects a number of token trees into a single stream.
227 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
228 impl iter::FromIterator<TokenTree> for TokenStream {
229     fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
230         trees.into_iter().map(TokenStream::from).collect()
231     }
232 }
233
234 /// A "flattening" operation on token streams, collects token trees
235 /// from multiple token streams into a single stream.
236 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
237 impl iter::FromIterator<TokenStream> for TokenStream {
238     fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
239         let mut builder = bridge::client::TokenStreamBuilder::new();
240         streams.into_iter().for_each(|stream| builder.push(stream.0));
241         TokenStream(builder.build())
242     }
243 }
244
245 #[stable(feature = "token_stream_extend", since = "1.30.0")]
246 impl Extend<TokenTree> for TokenStream {
247     fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
248         self.extend(trees.into_iter().map(TokenStream::from));
249     }
250 }
251
252 #[stable(feature = "token_stream_extend", since = "1.30.0")]
253 impl Extend<TokenStream> for TokenStream {
254     fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
255         // FIXME(eddyb) Use an optimized implementation if/when possible.
256         *self = iter::once(mem::replace(self, Self::new())).chain(streams).collect();
257     }
258 }
259
260 /// Public implementation details for the `TokenStream` type, such as iterators.
261 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
262 pub mod token_stream {
263     use crate::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree};
264
265     /// An iterator over `TokenStream`'s `TokenTree`s.
266     /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
267     /// and returns whole groups as token trees.
268     #[derive(Clone)]
269     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
270     pub struct IntoIter(bridge::client::TokenStreamIter);
271
272     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
273     impl Iterator for IntoIter {
274         type Item = TokenTree;
275
276         fn next(&mut self) -> Option<TokenTree> {
277             self.0.next().map(|tree| match tree {
278                 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
279                 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
280                 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
281                 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
282             })
283         }
284     }
285
286     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
287     impl IntoIterator for TokenStream {
288         type Item = TokenTree;
289         type IntoIter = IntoIter;
290
291         fn into_iter(self) -> IntoIter {
292             IntoIter(self.0.into_iter())
293         }
294     }
295 }
296
297 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
298 /// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
299 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
300 ///
301 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
302 /// To quote `$` itself, use `$$`.
303 #[unstable(feature = "proc_macro_quote", issue = "54722")]
304 #[allow_internal_unstable(proc_macro_def_site, proc_macro_internals)]
305 #[rustc_builtin_macro]
306 pub macro quote($($t:tt)*) {
307     /* compiler built-in */
308 }
309
310 #[unstable(feature = "proc_macro_internals", issue = "27812")]
311 #[doc(hidden)]
312 mod quote;
313
314 /// A region of source code, along with macro expansion information.
315 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
316 #[derive(Copy, Clone)]
317 pub struct Span(bridge::client::Span);
318
319 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
320 impl !Send for Span {}
321 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
322 impl !Sync for Span {}
323
324 macro_rules! diagnostic_method {
325     ($name:ident, $level:expr) => {
326         /// Creates a new `Diagnostic` with the given `message` at the span
327         /// `self`.
328         #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
329         pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
330             Diagnostic::spanned(self, $level, message)
331         }
332     };
333 }
334
335 impl Span {
336     /// A span that resolves at the macro definition site.
337     #[unstable(feature = "proc_macro_def_site", issue = "54724")]
338     pub fn def_site() -> Span {
339         Span(bridge::client::Span::def_site())
340     }
341
342     /// The span of the invocation of the current procedural macro.
343     /// Identifiers created with this span will be resolved as if they were written
344     /// directly at the macro call location (call-site hygiene) and other code
345     /// at the macro call site will be able to refer to them as well.
346     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
347     pub fn call_site() -> Span {
348         Span(bridge::client::Span::call_site())
349     }
350
351     /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
352     /// definition site (local variables, labels, `$crate`) and sometimes at the macro
353     /// call site (everything else).
354     /// The span location is taken from the call-site.
355     #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
356     pub fn mixed_site() -> Span {
357         Span(bridge::client::Span::mixed_site())
358     }
359
360     /// The original source file into which this span points.
361     #[unstable(feature = "proc_macro_span", issue = "54725")]
362     pub fn source_file(&self) -> SourceFile {
363         SourceFile(self.0.source_file())
364     }
365
366     /// The `Span` for the tokens in the previous macro expansion from which
367     /// `self` was generated from, if any.
368     #[unstable(feature = "proc_macro_span", issue = "54725")]
369     pub fn parent(&self) -> Option<Span> {
370         self.0.parent().map(Span)
371     }
372
373     /// The span for the origin source code that `self` was generated from. If
374     /// this `Span` wasn't generated from other macro expansions then the return
375     /// value is the same as `*self`.
376     #[unstable(feature = "proc_macro_span", issue = "54725")]
377     pub fn source(&self) -> Span {
378         Span(self.0.source())
379     }
380
381     /// Gets the starting line/column in the source file for this span.
382     #[unstable(feature = "proc_macro_span", issue = "54725")]
383     pub fn start(&self) -> LineColumn {
384         self.0.start().add_1_to_column()
385     }
386
387     /// Gets the ending line/column in the source file for this span.
388     #[unstable(feature = "proc_macro_span", issue = "54725")]
389     pub fn end(&self) -> LineColumn {
390         self.0.end().add_1_to_column()
391     }
392
393     /// Creates an empty span pointing to directly before this span.
394     #[unstable(feature = "proc_macro_span_shrink", issue = "87552")]
395     pub fn before(&self) -> Span {
396         Span(self.0.before())
397     }
398
399     /// Creates an empty span pointing to directly after this span.
400     #[unstable(feature = "proc_macro_span_shrink", issue = "87552")]
401     pub fn after(&self) -> Span {
402         Span(self.0.after())
403     }
404
405     /// Creates a new span encompassing `self` and `other`.
406     ///
407     /// Returns `None` if `self` and `other` are from different files.
408     #[unstable(feature = "proc_macro_span", issue = "54725")]
409     pub fn join(&self, other: Span) -> Option<Span> {
410         self.0.join(other.0).map(Span)
411     }
412
413     /// Creates a new span with the same line/column information as `self` but
414     /// that resolves symbols as though it were at `other`.
415     #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
416     pub fn resolved_at(&self, other: Span) -> Span {
417         Span(self.0.resolved_at(other.0))
418     }
419
420     /// Creates a new span with the same name resolution behavior as `self` but
421     /// with the line/column information of `other`.
422     #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
423     pub fn located_at(&self, other: Span) -> Span {
424         other.resolved_at(*self)
425     }
426
427     /// Compares to spans to see if they're equal.
428     #[unstable(feature = "proc_macro_span", issue = "54725")]
429     pub fn eq(&self, other: &Span) -> bool {
430         self.0 == other.0
431     }
432
433     /// Returns the source text behind a span. This preserves the original source
434     /// code, including spaces and comments. It only returns a result if the span
435     /// corresponds to real source code.
436     ///
437     /// Note: The observable result of a macro should only rely on the tokens and
438     /// not on this source text. The result of this function is a best effort to
439     /// be used for diagnostics only.
440     #[unstable(feature = "proc_macro_span", issue = "54725")]
441     pub fn source_text(&self) -> Option<String> {
442         self.0.source_text()
443     }
444
445     // Used by the implementation of `Span::quote`
446     #[doc(hidden)]
447     #[unstable(feature = "proc_macro_internals", issue = "27812")]
448     pub fn save_span(&self) -> usize {
449         self.0.save_span()
450     }
451
452     // Used by the implementation of `Span::quote`
453     #[doc(hidden)]
454     #[unstable(feature = "proc_macro_internals", issue = "27812")]
455     pub fn recover_proc_macro_span(id: usize) -> Span {
456         Span(bridge::client::Span::recover_proc_macro_span(id))
457     }
458
459     diagnostic_method!(error, Level::Error);
460     diagnostic_method!(warning, Level::Warning);
461     diagnostic_method!(note, Level::Note);
462     diagnostic_method!(help, Level::Help);
463 }
464
465 /// Prints a span in a form convenient for debugging.
466 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
467 impl fmt::Debug for Span {
468     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
469         self.0.fmt(f)
470     }
471 }
472
473 /// A line-column pair representing the start or end of a `Span`.
474 #[unstable(feature = "proc_macro_span", issue = "54725")]
475 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
476 pub struct LineColumn {
477     /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
478     #[unstable(feature = "proc_macro_span", issue = "54725")]
479     pub line: usize,
480     /// The 1-indexed column (number of bytes in UTF-8 encoding) in the source
481     /// file on which the span starts or ends (inclusive).
482     #[unstable(feature = "proc_macro_span", issue = "54725")]
483     pub column: usize,
484 }
485
486 impl LineColumn {
487     fn add_1_to_column(self) -> Self {
488         LineColumn { line: self.line, column: self.column + 1 }
489     }
490 }
491
492 #[unstable(feature = "proc_macro_span", issue = "54725")]
493 impl !Send for LineColumn {}
494 #[unstable(feature = "proc_macro_span", issue = "54725")]
495 impl !Sync for LineColumn {}
496
497 #[unstable(feature = "proc_macro_span", issue = "54725")]
498 impl Ord for LineColumn {
499     fn cmp(&self, other: &Self) -> Ordering {
500         self.line.cmp(&other.line).then(self.column.cmp(&other.column))
501     }
502 }
503
504 #[unstable(feature = "proc_macro_span", issue = "54725")]
505 impl PartialOrd for LineColumn {
506     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
507         Some(self.cmp(other))
508     }
509 }
510
511 /// The source file of a given `Span`.
512 #[unstable(feature = "proc_macro_span", issue = "54725")]
513 #[derive(Clone)]
514 pub struct SourceFile(bridge::client::SourceFile);
515
516 impl SourceFile {
517     /// Gets the path to this source file.
518     ///
519     /// ### Note
520     /// If the code span associated with this `SourceFile` was generated by an external macro, this
521     /// macro, this might not be an actual path on the filesystem. Use [`is_real`] to check.
522     ///
523     /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
524     /// the command line, the path as given might not actually be valid.
525     ///
526     /// [`is_real`]: Self::is_real
527     #[unstable(feature = "proc_macro_span", issue = "54725")]
528     pub fn path(&self) -> PathBuf {
529         PathBuf::from(self.0.path())
530     }
531
532     /// Returns `true` if this source file is a real source file, and not generated by an external
533     /// macro's expansion.
534     #[unstable(feature = "proc_macro_span", issue = "54725")]
535     pub fn is_real(&self) -> bool {
536         // This is a hack until intercrate spans are implemented and we can have real source files
537         // for spans generated in external macros.
538         // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
539         self.0.is_real()
540     }
541 }
542
543 #[unstable(feature = "proc_macro_span", issue = "54725")]
544 impl fmt::Debug for SourceFile {
545     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
546         f.debug_struct("SourceFile")
547             .field("path", &self.path())
548             .field("is_real", &self.is_real())
549             .finish()
550     }
551 }
552
553 #[unstable(feature = "proc_macro_span", issue = "54725")]
554 impl PartialEq for SourceFile {
555     fn eq(&self, other: &Self) -> bool {
556         self.0.eq(&other.0)
557     }
558 }
559
560 #[unstable(feature = "proc_macro_span", issue = "54725")]
561 impl Eq for SourceFile {}
562
563 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
564 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
565 #[derive(Clone)]
566 pub enum TokenTree {
567     /// A token stream surrounded by bracket delimiters.
568     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
569     Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
570     /// An identifier.
571     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
572     Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
573     /// A single punctuation character (`+`, `,`, `$`, etc.).
574     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
575     Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
576     /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
577     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
578     Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
579 }
580
581 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
582 impl !Send for TokenTree {}
583 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
584 impl !Sync for TokenTree {}
585
586 impl TokenTree {
587     /// Returns the span of this tree, delegating to the `span` method of
588     /// the contained token or a delimited stream.
589     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
590     pub fn span(&self) -> Span {
591         match *self {
592             TokenTree::Group(ref t) => t.span(),
593             TokenTree::Ident(ref t) => t.span(),
594             TokenTree::Punct(ref t) => t.span(),
595             TokenTree::Literal(ref t) => t.span(),
596         }
597     }
598
599     /// Configures the span for *only this token*.
600     ///
601     /// Note that if this token is a `Group` then this method will not configure
602     /// the span of each of the internal tokens, this will simply delegate to
603     /// the `set_span` method of each variant.
604     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
605     pub fn set_span(&mut self, span: Span) {
606         match *self {
607             TokenTree::Group(ref mut t) => t.set_span(span),
608             TokenTree::Ident(ref mut t) => t.set_span(span),
609             TokenTree::Punct(ref mut t) => t.set_span(span),
610             TokenTree::Literal(ref mut t) => t.set_span(span),
611         }
612     }
613 }
614
615 /// Prints token tree in a form convenient for debugging.
616 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
617 impl fmt::Debug for TokenTree {
618     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
619         // Each of these has the name in the struct type in the derived debug,
620         // so don't bother with an extra layer of indirection
621         match *self {
622             TokenTree::Group(ref tt) => tt.fmt(f),
623             TokenTree::Ident(ref tt) => tt.fmt(f),
624             TokenTree::Punct(ref tt) => tt.fmt(f),
625             TokenTree::Literal(ref tt) => tt.fmt(f),
626         }
627     }
628 }
629
630 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
631 impl From<Group> for TokenTree {
632     fn from(g: Group) -> TokenTree {
633         TokenTree::Group(g)
634     }
635 }
636
637 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
638 impl From<Ident> for TokenTree {
639     fn from(g: Ident) -> TokenTree {
640         TokenTree::Ident(g)
641     }
642 }
643
644 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
645 impl From<Punct> for TokenTree {
646     fn from(g: Punct) -> TokenTree {
647         TokenTree::Punct(g)
648     }
649 }
650
651 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
652 impl From<Literal> for TokenTree {
653     fn from(g: Literal) -> TokenTree {
654         TokenTree::Literal(g)
655     }
656 }
657
658 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
659 // based on it (the reverse of the usual relationship between the two).
660 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
661 impl ToString for TokenTree {
662     fn to_string(&self) -> String {
663         match *self {
664             TokenTree::Group(ref t) => t.to_string(),
665             TokenTree::Ident(ref t) => t.to_string(),
666             TokenTree::Punct(ref t) => t.to_string(),
667             TokenTree::Literal(ref t) => t.to_string(),
668         }
669     }
670 }
671
672 /// Prints the token tree as a string that is supposed to be losslessly convertible back
673 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
674 /// with `Delimiter::None` delimiters and negative numeric literals.
675 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
676 impl fmt::Display for TokenTree {
677     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
678         f.write_str(&self.to_string())
679     }
680 }
681
682 /// A delimited token stream.
683 ///
684 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
685 #[derive(Clone)]
686 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
687 pub struct Group(bridge::client::Group);
688
689 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
690 impl !Send for Group {}
691 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
692 impl !Sync for Group {}
693
694 /// Describes how a sequence of token trees is delimited.
695 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
696 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
697 pub enum Delimiter {
698     /// `( ... )`
699     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
700     Parenthesis,
701     /// `{ ... }`
702     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
703     Brace,
704     /// `[ ... ]`
705     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
706     Bracket,
707     /// `Ø ... Ã˜`
708     /// An implicit delimiter, that may, for example, appear around tokens coming from a
709     /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
710     /// `$var * 3` where `$var` is `1 + 2`.
711     /// Implicit delimiters might not survive 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 }