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