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