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