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