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