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