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