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