Coverage Report

Created: 2025-08-26 06:21

/rust/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.101/src/lib.rs
Line
Count
Source (jump to first uncovered line)
1
//! [![github]](https://github.com/dtolnay/proc-macro2) [![crates-io]](https://crates.io/crates/proc-macro2) [![docs-rs]](crate)
2
//!
3
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4
//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5
//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
6
//!
7
//! <br>
8
//!
9
//! A wrapper around the procedural macro API of the compiler's [`proc_macro`]
10
//! crate. This library serves two purposes:
11
//!
12
//! - **Bring proc-macro-like functionality to other contexts like build.rs and
13
//!   main.rs.** Types from `proc_macro` are entirely specific to procedural
14
//!   macros and cannot ever exist in code outside of a procedural macro.
15
//!   Meanwhile `proc_macro2` types may exist anywhere including non-macro code.
16
//!   By developing foundational libraries like [syn] and [quote] against
17
//!   `proc_macro2` rather than `proc_macro`, the procedural macro ecosystem
18
//!   becomes easily applicable to many other use cases and we avoid
19
//!   reimplementing non-macro equivalents of those libraries.
20
//!
21
//! - **Make procedural macros unit testable.** As a consequence of being
22
//!   specific to procedural macros, nothing that uses `proc_macro` can be
23
//!   executed from a unit test. In order for helper libraries or components of
24
//!   a macro to be testable in isolation, they must be implemented using
25
//!   `proc_macro2`.
26
//!
27
//! [syn]: https://github.com/dtolnay/syn
28
//! [quote]: https://github.com/dtolnay/quote
29
//!
30
//! # Usage
31
//!
32
//! The skeleton of a typical procedural macro typically looks like this:
33
//!
34
//! ```
35
//! extern crate proc_macro;
36
//!
37
//! # const IGNORE: &str = stringify! {
38
//! #[proc_macro_derive(MyDerive)]
39
//! # };
40
//! # #[cfg(wrap_proc_macro)]
41
//! pub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
42
//!     let input = proc_macro2::TokenStream::from(input);
43
//!
44
//!     let output: proc_macro2::TokenStream = {
45
//!         /* transform input */
46
//!         # input
47
//!     };
48
//!
49
//!     proc_macro::TokenStream::from(output)
50
//! }
51
//! ```
52
//!
53
//! If parsing with [Syn], you'll use [`parse_macro_input!`] instead to
54
//! propagate parse errors correctly back to the compiler when parsing fails.
55
//!
56
//! [`parse_macro_input!`]: https://docs.rs/syn/2.0/syn/macro.parse_macro_input.html
57
//!
58
//! # Unstable features
59
//!
60
//! The default feature set of proc-macro2 tracks the most recent stable
61
//! compiler API. Functionality in `proc_macro` that is not yet stable is not
62
//! exposed by proc-macro2 by default.
63
//!
64
//! To opt into the additional APIs available in the most recent nightly
65
//! compiler, the `procmacro2_semver_exempt` config flag must be passed to
66
//! rustc. We will polyfill those nightly-only APIs back to Rust 1.56.0. As
67
//! these are unstable APIs that track the nightly compiler, minor versions of
68
//! proc-macro2 may make breaking changes to them at any time.
69
//!
70
//! ```sh
71
//! RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build
72
//! ```
73
//!
74
//! Note that this must not only be done for your crate, but for any crate that
75
//! depends on your crate. This infectious nature is intentional, as it serves
76
//! as a reminder that you are outside of the normal semver guarantees.
77
//!
78
//! Semver exempt methods are marked as such in the proc-macro2 documentation.
79
//!
80
//! # Thread-Safety
81
//!
82
//! Most types in this crate are `!Sync` because the underlying compiler
83
//! types make use of thread-local memory, meaning they cannot be accessed from
84
//! a different thread.
85
86
// Proc-macro2 types in rustdoc of other crates get linked to here.
87
#![doc(html_root_url = "https://docs.rs/proc-macro2/1.0.101")]
88
#![cfg_attr(any(proc_macro_span, super_unstable), feature(proc_macro_span))]
89
#![cfg_attr(super_unstable, feature(proc_macro_def_site))]
90
#![cfg_attr(docsrs, feature(doc_cfg))]
91
#![deny(unsafe_op_in_unsafe_fn)]
92
#![allow(
93
    clippy::cast_lossless,
94
    clippy::cast_possible_truncation,
95
    clippy::checked_conversions,
96
    clippy::doc_markdown,
97
    clippy::elidable_lifetime_names,
98
    clippy::incompatible_msrv,
99
    clippy::items_after_statements,
100
    clippy::iter_without_into_iter,
101
    clippy::let_underscore_untyped,
102
    clippy::manual_assert,
103
    clippy::manual_range_contains,
104
    clippy::missing_panics_doc,
105
    clippy::missing_safety_doc,
106
    clippy::must_use_candidate,
107
    clippy::needless_doctest_main,
108
    clippy::needless_lifetimes,
109
    clippy::new_without_default,
110
    clippy::return_self_not_must_use,
111
    clippy::shadow_unrelated,
112
    clippy::trivially_copy_pass_by_ref,
113
    clippy::unnecessary_wraps,
114
    clippy::unused_self,
115
    clippy::used_underscore_binding,
116
    clippy::vec_init_then_push
117
)]
118
#![allow(unknown_lints, mismatched_lifetime_syntaxes)]
119
120
#[cfg(all(procmacro2_semver_exempt, wrap_proc_macro, not(super_unstable)))]
121
compile_error! {"\
122
    Something is not right. If you've tried to turn on \
123
    procmacro2_semver_exempt, you need to ensure that it \
124
    is turned on for the compilation of the proc-macro2 \
125
    build script as well.
126
"}
127
128
#[cfg(all(
129
    procmacro2_nightly_testing,
130
    feature = "proc-macro",
131
    not(proc_macro_span)
132
))]
133
compile_error! {"\
134
    Build script probe failed to compile.
135
"}
136
137
extern crate alloc;
138
139
#[cfg(feature = "proc-macro")]
140
extern crate proc_macro;
141
142
mod marker;
143
mod parse;
144
mod probe;
145
mod rcvec;
146
147
#[cfg(wrap_proc_macro)]
148
mod detection;
149
150
// Public for proc_macro2::fallback::force() and unforce(), but those are quite
151
// a niche use case so we omit it from rustdoc.
152
#[doc(hidden)]
153
pub mod fallback;
154
155
pub mod extra;
156
157
#[cfg(not(wrap_proc_macro))]
158
use crate::fallback as imp;
159
#[path = "wrapper.rs"]
160
#[cfg(wrap_proc_macro)]
161
mod imp;
162
163
#[cfg(span_locations)]
164
mod location;
165
166
use crate::extra::DelimSpan;
167
use crate::marker::{ProcMacroAutoTraits, MARKER};
168
use core::cmp::Ordering;
169
use core::fmt::{self, Debug, Display};
170
use core::hash::{Hash, Hasher};
171
#[cfg(span_locations)]
172
use core::ops::Range;
173
use core::ops::RangeBounds;
174
use core::str::FromStr;
175
use std::error::Error;
176
use std::ffi::CStr;
177
#[cfg(span_locations)]
178
use std::path::PathBuf;
179
180
#[cfg(span_locations)]
181
#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
182
pub use crate::location::LineColumn;
183
184
/// An abstract stream of tokens, or more concretely a sequence of token trees.
185
///
186
/// This type provides interfaces for iterating over token trees and for
187
/// collecting token trees into one stream.
188
///
189
/// Token stream is both the input and output of `#[proc_macro]`,
190
/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
191
#[derive(Clone)]
192
pub struct TokenStream {
193
    inner: imp::TokenStream,
194
    _marker: ProcMacroAutoTraits,
195
}
196
197
/// Error returned from `TokenStream::from_str`.
198
pub struct LexError {
199
    inner: imp::LexError,
200
    _marker: ProcMacroAutoTraits,
201
}
202
203
impl TokenStream {
204
110
    fn _new(inner: imp::TokenStream) -> Self {
205
110
        TokenStream {
206
110
            inner,
207
110
            _marker: MARKER,
208
110
        }
209
110
    }
210
211
0
    fn _new_fallback(inner: fallback::TokenStream) -> Self {
212
0
        TokenStream {
213
0
            inner: imp::TokenStream::from(inner),
214
0
            _marker: MARKER,
215
0
        }
216
0
    }
217
218
    /// Returns an empty `TokenStream` containing no token trees.
219
0
    pub fn new() -> Self {
220
0
        TokenStream::_new(imp::TokenStream::new())
221
0
    }
222
223
    /// Checks if this `TokenStream` is empty.
224
0
    pub fn is_empty(&self) -> bool {
225
0
        self.inner.is_empty()
226
0
    }
227
}
228
229
/// `TokenStream::default()` returns an empty stream,
230
/// i.e. this is equivalent with `TokenStream::new()`.
231
impl Default for TokenStream {
232
0
    fn default() -> Self {
233
0
        TokenStream::new()
234
0
    }
235
}
236
237
/// Attempts to break the string into tokens and parse those tokens into a token
238
/// stream.
239
///
240
/// May fail for a number of reasons, for example, if the string contains
241
/// unbalanced delimiters or characters not existing in the language.
242
///
243
/// NOTE: Some errors may cause panics instead of returning `LexError`. We
244
/// reserve the right to change these errors into `LexError`s later.
245
impl FromStr for TokenStream {
246
    type Err = LexError;
247
248
414
    fn from_str(src: &str) -> Result<TokenStream, LexError> {
249
414
        match imp::TokenStream::from_str_checked(src) {
250
110
            Ok(tokens) => Ok(TokenStream::_new(tokens)),
251
304
            Err(lex) => Err(LexError {
252
304
                inner: lex,
253
304
                _marker: MARKER,
254
304
            }),
255
        }
256
414
    }
257
}
258
259
#[cfg(feature = "proc-macro")]
260
#[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]
261
impl From<proc_macro::TokenStream> for TokenStream {
262
0
    fn from(inner: proc_macro::TokenStream) -> Self {
263
0
        TokenStream::_new(imp::TokenStream::from(inner))
264
0
    }
265
}
266
267
#[cfg(feature = "proc-macro")]
268
#[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]
269
impl From<TokenStream> for proc_macro::TokenStream {
270
0
    fn from(inner: TokenStream) -> Self {
271
0
        proc_macro::TokenStream::from(inner.inner)
272
0
    }
273
}
274
275
impl From<TokenTree> for TokenStream {
276
0
    fn from(token: TokenTree) -> Self {
277
0
        TokenStream::_new(imp::TokenStream::from(token))
278
0
    }
279
}
280
281
impl Extend<TokenTree> for TokenStream {
282
0
    fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
283
0
        self.inner.extend(streams);
284
0
    }
285
}
286
287
impl Extend<TokenStream> for TokenStream {
288
0
    fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
289
0
        self.inner
290
0
            .extend(streams.into_iter().map(|stream| stream.inner));
291
0
    }
292
}
293
294
/// Collects a number of token trees into a single stream.
295
impl FromIterator<TokenTree> for TokenStream {
296
0
    fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
297
0
        TokenStream::_new(streams.into_iter().collect())
298
0
    }
299
}
300
impl FromIterator<TokenStream> for TokenStream {
301
0
    fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
302
0
        TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())
303
0
    }
304
}
305
306
/// Prints the token stream as a string that is supposed to be losslessly
307
/// convertible back into the same token stream (modulo spans), except for
308
/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
309
/// numeric literals.
310
impl Display for TokenStream {
311
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
312
0
        Display::fmt(&self.inner, f)
313
0
    }
314
}
315
316
/// Prints token in a form convenient for debugging.
317
impl Debug for TokenStream {
318
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
319
0
        Debug::fmt(&self.inner, f)
320
0
    }
321
}
322
323
impl LexError {
324
0
    pub fn span(&self) -> Span {
325
0
        Span::_new(self.inner.span())
326
0
    }
327
}
328
329
impl Debug for LexError {
330
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
331
0
        Debug::fmt(&self.inner, f)
332
0
    }
333
}
334
335
impl Display for LexError {
336
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
337
0
        Display::fmt(&self.inner, f)
338
0
    }
339
}
340
341
impl Error for LexError {}
342
343
/// A region of source code, along with macro expansion information.
344
#[derive(Copy, Clone)]
345
pub struct Span {
346
    inner: imp::Span,
347
    _marker: ProcMacroAutoTraits,
348
}
349
350
impl Span {
351
5.26M
    fn _new(inner: imp::Span) -> Self {
352
5.26M
        Span {
353
5.26M
            inner,
354
5.26M
            _marker: MARKER,
355
5.26M
        }
356
5.26M
    }
357
358
8.05M
    fn _new_fallback(inner: fallback::Span) -> Self {
359
8.05M
        Span {
360
8.05M
            inner: imp::Span::from(inner),
361
8.05M
            _marker: MARKER,
362
8.05M
        }
363
8.05M
    }
364
365
    /// The span of the invocation of the current procedural macro.
366
    ///
367
    /// Identifiers created with this span will be resolved as if they were
368
    /// written directly at the macro call location (call-site hygiene) and
369
    /// other code at the macro call site will be able to refer to them as well.
370
5.26M
    pub fn call_site() -> Self {
371
5.26M
        Span::_new(imp::Span::call_site())
372
5.26M
    }
373
374
    /// The span located at the invocation of the procedural macro, but with
375
    /// local variables, labels, and `$crate` resolved at the definition site
376
    /// of the macro. This is the same hygiene behavior as `macro_rules`.
377
0
    pub fn mixed_site() -> Self {
378
0
        Span::_new(imp::Span::mixed_site())
379
0
    }
380
381
    /// A span that resolves at the macro definition site.
382
    ///
383
    /// This method is semver exempt and not exposed by default.
384
    #[cfg(procmacro2_semver_exempt)]
385
    #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]
386
    pub fn def_site() -> Self {
387
        Span::_new(imp::Span::def_site())
388
    }
389
390
    /// Creates a new span with the same line/column information as `self` but
391
    /// that resolves symbols as though it were at `other`.
392
0
    pub fn resolved_at(&self, other: Span) -> Span {
393
0
        Span::_new(self.inner.resolved_at(other.inner))
394
0
    }
395
396
    /// Creates a new span with the same name resolution behavior as `self` but
397
    /// with the line/column information of `other`.
398
0
    pub fn located_at(&self, other: Span) -> Span {
399
0
        Span::_new(self.inner.located_at(other.inner))
400
0
    }
401
402
    /// Convert `proc_macro2::Span` to `proc_macro::Span`.
403
    ///
404
    /// This method is available when building with a nightly compiler, or when
405
    /// building with rustc 1.29+ *without* semver exempt features.
406
    ///
407
    /// # Panics
408
    ///
409
    /// Panics if called from outside of a procedural macro. Unlike
410
    /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within
411
    /// the context of a procedural macro invocation.
412
    #[cfg(wrap_proc_macro)]
413
0
    pub fn unwrap(self) -> proc_macro::Span {
414
0
        self.inner.unwrap()
415
0
    }
416
417
    // Soft deprecated. Please use Span::unwrap.
418
    #[cfg(wrap_proc_macro)]
419
    #[doc(hidden)]
420
0
    pub fn unstable(self) -> proc_macro::Span {
421
0
        self.unwrap()
422
0
    }
423
424
    /// Returns the span's byte position range in the source file.
425
    ///
426
    /// This method requires the `"span-locations"` feature to be enabled.
427
    ///
428
    /// When executing in a procedural macro context, the returned range is only
429
    /// accurate if compiled with a nightly toolchain. The stable toolchain does
430
    /// not have this information available. When executing outside of a
431
    /// procedural macro, such as main.rs or build.rs, the byte range is always
432
    /// accurate regardless of toolchain.
433
    #[cfg(span_locations)]
434
    #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
435
    pub fn byte_range(&self) -> Range<usize> {
436
        self.inner.byte_range()
437
    }
438
439
    /// Get the starting line/column in the source file for this span.
440
    ///
441
    /// This method requires the `"span-locations"` feature to be enabled.
442
    ///
443
    /// When executing in a procedural macro context, the returned line/column
444
    /// are only meaningful if compiled with a nightly toolchain. The stable
445
    /// toolchain does not have this information available. When executing
446
    /// outside of a procedural macro, such as main.rs or build.rs, the
447
    /// line/column are always meaningful regardless of toolchain.
448
    #[cfg(span_locations)]
449
    #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
450
    pub fn start(&self) -> LineColumn {
451
        self.inner.start()
452
    }
453
454
    /// Get the ending line/column in the source file for this span.
455
    ///
456
    /// This method requires the `"span-locations"` feature to be enabled.
457
    ///
458
    /// When executing in a procedural macro context, the returned line/column
459
    /// are only meaningful if compiled with a nightly toolchain. The stable
460
    /// toolchain does not have this information available. When executing
461
    /// outside of a procedural macro, such as main.rs or build.rs, the
462
    /// line/column are always meaningful regardless of toolchain.
463
    #[cfg(span_locations)]
464
    #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
465
    pub fn end(&self) -> LineColumn {
466
        self.inner.end()
467
    }
468
469
    /// The path to the source file in which this span occurs, for display
470
    /// purposes.
471
    ///
472
    /// This might not correspond to a valid file system path. It might be
473
    /// remapped, or might be an artificial path such as `"<macro expansion>"`.
474
    #[cfg(span_locations)]
475
    #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
476
    pub fn file(&self) -> String {
477
        self.inner.file()
478
    }
479
480
    /// The path to the source file in which this span occurs on disk.
481
    ///
482
    /// This is the actual path on disk. It is unaffected by path remapping.
483
    ///
484
    /// This path should not be embedded in the output of the macro; prefer
485
    /// `file()` instead.
486
    #[cfg(span_locations)]
487
    #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
488
    pub fn local_file(&self) -> Option<PathBuf> {
489
        self.inner.local_file()
490
    }
491
492
    /// Create a new span encompassing `self` and `other`.
493
    ///
494
    /// Returns `None` if `self` and `other` are from different files.
495
    ///
496
    /// Warning: the underlying [`proc_macro::Span::join`] method is
497
    /// nightly-only. When called from within a procedural macro not using a
498
    /// nightly compiler, this method will always return `None`.
499
0
    pub fn join(&self, other: Span) -> Option<Span> {
500
0
        self.inner.join(other.inner).map(Span::_new)
501
0
    }
502
503
    /// Compares two spans to see if they're equal.
504
    ///
505
    /// This method is semver exempt and not exposed by default.
506
    #[cfg(procmacro2_semver_exempt)]
507
    #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]
508
    pub fn eq(&self, other: &Span) -> bool {
509
        self.inner.eq(&other.inner)
510
    }
511
512
    /// Returns the source text behind a span. This preserves the original
513
    /// source code, including spaces and comments. It only returns a result if
514
    /// the span corresponds to real source code.
515
    ///
516
    /// Note: The observable result of a macro should only rely on the tokens
517
    /// and not on this source text. The result of this function is a best
518
    /// effort to be used for diagnostics only.
519
0
    pub fn source_text(&self) -> Option<String> {
520
0
        self.inner.source_text()
521
0
    }
522
}
523
524
/// Prints a span in a form convenient for debugging.
525
impl Debug for Span {
526
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
527
0
        Debug::fmt(&self.inner, f)
528
0
    }
529
}
530
531
/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
532
#[derive(Clone)]
533
pub enum TokenTree {
534
    /// A token stream surrounded by bracket delimiters.
535
    Group(Group),
536
    /// An identifier.
537
    Ident(Ident),
538
    /// A single punctuation character (`+`, `,`, `$`, etc.).
539
    Punct(Punct),
540
    /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
541
    Literal(Literal),
542
}
543
544
impl TokenTree {
545
    /// Returns the span of this tree, delegating to the `span` method of
546
    /// the contained token or a delimited stream.
547
0
    pub fn span(&self) -> Span {
548
0
        match self {
549
0
            TokenTree::Group(t) => t.span(),
550
0
            TokenTree::Ident(t) => t.span(),
551
0
            TokenTree::Punct(t) => t.span(),
552
0
            TokenTree::Literal(t) => t.span(),
553
        }
554
0
    }
555
556
    /// Configures the span for *only this token*.
557
    ///
558
    /// Note that if this token is a `Group` then this method will not configure
559
    /// the span of each of the internal tokens, this will simply delegate to
560
    /// the `set_span` method of each variant.
561
8.02M
    pub fn set_span(&mut self, span: Span) {
562
8.02M
        match self {
563
0
            TokenTree::Group(t) => t.set_span(span),
564
1.85M
            TokenTree::Ident(t) => t.set_span(span),
565
5.19M
            TokenTree::Punct(t) => t.set_span(span),
566
969k
            TokenTree::Literal(t) => t.set_span(span),
567
        }
568
8.02M
    }
569
}
570
571
impl From<Group> for TokenTree {
572
0
    fn from(g: Group) -> Self {
573
0
        TokenTree::Group(g)
574
0
    }
575
}
576
577
impl From<Ident> for TokenTree {
578
0
    fn from(g: Ident) -> Self {
579
0
        TokenTree::Ident(g)
580
0
    }
581
}
582
583
impl From<Punct> for TokenTree {
584
0
    fn from(g: Punct) -> Self {
585
0
        TokenTree::Punct(g)
586
0
    }
587
}
588
589
impl From<Literal> for TokenTree {
590
0
    fn from(g: Literal) -> Self {
591
0
        TokenTree::Literal(g)
592
0
    }
593
}
594
595
/// Prints the token tree as a string that is supposed to be losslessly
596
/// convertible back into the same token tree (modulo spans), except for
597
/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
598
/// numeric literals.
599
impl Display for TokenTree {
600
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
601
0
        match self {
602
0
            TokenTree::Group(t) => Display::fmt(t, f),
603
0
            TokenTree::Ident(t) => Display::fmt(t, f),
604
0
            TokenTree::Punct(t) => Display::fmt(t, f),
605
0
            TokenTree::Literal(t) => Display::fmt(t, f),
606
        }
607
0
    }
608
}
609
610
/// Prints token tree in a form convenient for debugging.
611
impl Debug for TokenTree {
612
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
613
0
        // Each of these has the name in the struct type in the derived debug,
614
0
        // so don't bother with an extra layer of indirection
615
0
        match self {
616
0
            TokenTree::Group(t) => Debug::fmt(t, f),
617
0
            TokenTree::Ident(t) => {
618
0
                let mut debug = f.debug_struct("Ident");
619
0
                debug.field("sym", &format_args!("{}", t));
620
0
                imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);
621
0
                debug.finish()
622
            }
623
0
            TokenTree::Punct(t) => Debug::fmt(t, f),
624
0
            TokenTree::Literal(t) => Debug::fmt(t, f),
625
        }
626
0
    }
627
}
628
629
/// A delimited token stream.
630
///
631
/// A `Group` internally contains a `TokenStream` which is surrounded by
632
/// `Delimiter`s.
633
#[derive(Clone)]
634
pub struct Group {
635
    inner: imp::Group,
636
}
637
638
/// Describes how a sequence of token trees is delimited.
639
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
640
pub enum Delimiter {
641
    /// `( ... )`
642
    Parenthesis,
643
    /// `{ ... }`
644
    Brace,
645
    /// `[ ... ]`
646
    Bracket,
647
    /// `∅ ... ∅`
648
    ///
649
    /// An invisible delimiter, that may, for example, appear around tokens
650
    /// coming from a "macro variable" `$var`. It is important to preserve
651
    /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
652
    /// Invisible delimiters may not survive roundtrip of a token stream through
653
    /// a string.
654
    ///
655
    /// <div class="warning">
656
    ///
657
    /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
658
    /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
659
    /// of a proc_macro macro are preserved, and only in very specific circumstances.
660
    /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
661
    /// operator priorities as indicated above. The other `Delimiter` variants should be used
662
    /// instead in this context. This is a rustc bug. For details, see
663
    /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
664
    ///
665
    /// </div>
666
    None,
667
}
668
669
impl Group {
670
0
    fn _new(inner: imp::Group) -> Self {
671
0
        Group { inner }
672
0
    }
673
674
903k
    fn _new_fallback(inner: fallback::Group) -> Self {
675
903k
        Group {
676
903k
            inner: imp::Group::from(inner),
677
903k
        }
678
903k
    }
679
680
    /// Creates a new `Group` with the given delimiter and token stream.
681
    ///
682
    /// This constructor will set the span for this group to
683
    /// `Span::call_site()`. To change the span you can use the `set_span`
684
    /// method below.
685
0
    pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
686
0
        Group {
687
0
            inner: imp::Group::new(delimiter, stream.inner),
688
0
        }
689
0
    }
690
691
    /// Returns the punctuation used as the delimiter for this group: a set of
692
    /// parentheses, square brackets, or curly braces.
693
0
    pub fn delimiter(&self) -> Delimiter {
694
0
        self.inner.delimiter()
695
0
    }
696
697
    /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
698
    ///
699
    /// Note that the returned token stream does not include the delimiter
700
    /// returned above.
701
0
    pub fn stream(&self) -> TokenStream {
702
0
        TokenStream::_new(self.inner.stream())
703
0
    }
704
705
    /// Returns the span for the delimiters of this token stream, spanning the
706
    /// entire `Group`.
707
    ///
708
    /// ```text
709
    /// pub fn span(&self) -> Span {
710
    ///            ^^^^^^^
711
    /// ```
712
0
    pub fn span(&self) -> Span {
713
0
        Span::_new(self.inner.span())
714
0
    }
715
716
    /// Returns the span pointing to the opening delimiter of this group.
717
    ///
718
    /// ```text
719
    /// pub fn span_open(&self) -> Span {
720
    ///                 ^
721
    /// ```
722
0
    pub fn span_open(&self) -> Span {
723
0
        Span::_new(self.inner.span_open())
724
0
    }
725
726
    /// Returns the span pointing to the closing delimiter of this group.
727
    ///
728
    /// ```text
729
    /// pub fn span_close(&self) -> Span {
730
    ///                        ^
731
    /// ```
732
0
    pub fn span_close(&self) -> Span {
733
0
        Span::_new(self.inner.span_close())
734
0
    }
735
736
    /// Returns an object that holds this group's `span_open()` and
737
    /// `span_close()` together (in a more compact representation than holding
738
    /// those 2 spans individually).
739
0
    pub fn delim_span(&self) -> DelimSpan {
740
0
        DelimSpan::new(&self.inner)
741
0
    }
742
743
    /// Configures the span for this `Group`'s delimiters, but not its internal
744
    /// tokens.
745
    ///
746
    /// This method will **not** set the span of all the internal tokens spanned
747
    /// by this group, but rather it will only set the span of the delimiter
748
    /// tokens at the level of the `Group`.
749
24.0k
    pub fn set_span(&mut self, span: Span) {
750
24.0k
        self.inner.set_span(span.inner);
751
24.0k
    }
752
}
753
754
/// Prints the group as a string that should be losslessly convertible back
755
/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
756
/// with `Delimiter::None` delimiters.
757
impl Display for Group {
758
0
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
759
0
        Display::fmt(&self.inner, formatter)
760
0
    }
761
}
762
763
impl Debug for Group {
764
0
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
765
0
        Debug::fmt(&self.inner, formatter)
766
0
    }
767
}
768
769
/// A `Punct` is a single punctuation character like `+`, `-` or `#`.
770
///
771
/// Multicharacter operators like `+=` are represented as two instances of
772
/// `Punct` with different forms of `Spacing` returned.
773
#[derive(Clone)]
774
pub struct Punct {
775
    ch: char,
776
    spacing: Spacing,
777
    span: Span,
778
}
779
780
/// Whether a `Punct` is followed immediately by another `Punct` or followed by
781
/// another token or whitespace.
782
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
783
pub enum Spacing {
784
    /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
785
    Alone,
786
    /// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`.
787
    ///
788
    /// Additionally, single quote `'` can join with identifiers to form
789
    /// lifetimes `'ident`.
790
    Joint,
791
}
792
793
impl Punct {
794
    /// Creates a new `Punct` from the given character and spacing.
795
    ///
796
    /// The `ch` argument must be a valid punctuation character permitted by the
797
    /// language, otherwise the function will panic.
798
    ///
799
    /// The returned `Punct` will have the default span of `Span::call_site()`
800
    /// which can be further configured with the `set_span` method below.
801
5.26M
    pub fn new(ch: char, spacing: Spacing) -> Self {
802
5.26M
        if let '!' | '#' | '$' | '%' | '&' | '\'' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';'
803
5.26M
        | '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' = ch
804
        {
805
5.26M
            Punct {
806
5.26M
                ch,
807
5.26M
                spacing,
808
5.26M
                span: Span::call_site(),
809
5.26M
            }
810
        } else {
811
0
            panic!("unsupported proc macro punctuation character {:?}", ch);
812
        }
813
5.26M
    }
814
815
    /// Returns the value of this punctuation character as `char`.
816
0
    pub fn as_char(&self) -> char {
817
0
        self.ch
818
0
    }
819
820
    /// Returns the spacing of this punctuation character, indicating whether
821
    /// it's immediately followed by another `Punct` in the token stream, so
822
    /// they can potentially be combined into a multicharacter operator
823
    /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
824
    /// so the operator has certainly ended.
825
0
    pub fn spacing(&self) -> Spacing {
826
0
        self.spacing
827
0
    }
828
829
    /// Returns the span for this punctuation character.
830
0
    pub fn span(&self) -> Span {
831
0
        self.span
832
0
    }
833
834
    /// Configure the span for this punctuation character.
835
5.26M
    pub fn set_span(&mut self, span: Span) {
836
5.26M
        self.span = span;
837
5.26M
    }
838
}
839
840
/// Prints the punctuation character as a string that should be losslessly
841
/// convertible back into the same character.
842
impl Display for Punct {
843
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
844
0
        Display::fmt(&self.ch, f)
845
0
    }
846
}
847
848
impl Debug for Punct {
849
0
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
850
0
        let mut debug = fmt.debug_struct("Punct");
851
0
        debug.field("char", &self.ch);
852
0
        debug.field("spacing", &self.spacing);
853
0
        imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);
854
0
        debug.finish()
855
0
    }
856
}
857
858
/// A word of Rust code, which may be a keyword or legal variable name.
859
///
860
/// An identifier consists of at least one Unicode code point, the first of
861
/// which has the XID_Start property and the rest of which have the XID_Continue
862
/// property.
863
///
864
/// - The empty string is not an identifier. Use `Option<Ident>`.
865
/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
866
///
867
/// An identifier constructed with `Ident::new` is permitted to be a Rust
868
/// keyword, though parsing one through its [`Parse`] implementation rejects
869
/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
870
/// behaviour of `Ident::new`.
871
///
872
/// [`Parse`]: https://docs.rs/syn/2.0/syn/parse/trait.Parse.html
873
///
874
/// # Examples
875
///
876
/// A new ident can be created from a string using the `Ident::new` function.
877
/// A span must be provided explicitly which governs the name resolution
878
/// behavior of the resulting identifier.
879
///
880
/// ```
881
/// use proc_macro2::{Ident, Span};
882
///
883
/// fn main() {
884
///     let call_ident = Ident::new("calligraphy", Span::call_site());
885
///
886
///     println!("{}", call_ident);
887
/// }
888
/// ```
889
///
890
/// An ident can be interpolated into a token stream using the `quote!` macro.
891
///
892
/// ```
893
/// use proc_macro2::{Ident, Span};
894
/// use quote::quote;
895
///
896
/// fn main() {
897
///     let ident = Ident::new("demo", Span::call_site());
898
///
899
///     // Create a variable binding whose name is this ident.
900
///     let expanded = quote! { let #ident = 10; };
901
///
902
///     // Create a variable binding with a slightly different name.
903
///     let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
904
///     let expanded = quote! { let #temp_ident = 10; };
905
/// }
906
/// ```
907
///
908
/// A string representation of the ident is available through the `to_string()`
909
/// method.
910
///
911
/// ```
912
/// # use proc_macro2::{Ident, Span};
913
/// #
914
/// # let ident = Ident::new("another_identifier", Span::call_site());
915
/// #
916
/// // Examine the ident as a string.
917
/// let ident_string = ident.to_string();
918
/// if ident_string.len() > 60 {
919
///     println!("Very long identifier: {}", ident_string)
920
/// }
921
/// ```
922
#[derive(Clone)]
923
pub struct Ident {
924
    inner: imp::Ident,
925
    _marker: ProcMacroAutoTraits,
926
}
927
928
impl Ident {
929
0
    fn _new(inner: imp::Ident) -> Self {
930
0
        Ident {
931
0
            inner,
932
0
            _marker: MARKER,
933
0
        }
934
0
    }
935
936
1.88M
    fn _new_fallback(inner: fallback::Ident) -> Self {
937
1.88M
        Ident {
938
1.88M
            inner: imp::Ident::from(inner),
939
1.88M
            _marker: MARKER,
940
1.88M
        }
941
1.88M
    }
942
943
    /// Creates a new `Ident` with the given `string` as well as the specified
944
    /// `span`.
945
    ///
946
    /// The `string` argument must be a valid identifier permitted by the
947
    /// language, otherwise the function will panic.
948
    ///
949
    /// Note that `span`, currently in rustc, configures the hygiene information
950
    /// for this identifier.
951
    ///
952
    /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
953
    /// hygiene meaning that identifiers created with this span will be resolved
954
    /// as if they were written directly at the location of the macro call, and
955
    /// other code at the macro call site will be able to refer to them as well.
956
    ///
957
    /// Later spans like `Span::def_site()` will allow to opt-in to
958
    /// "definition-site" hygiene meaning that identifiers created with this
959
    /// span will be resolved at the location of the macro definition and other
960
    /// code at the macro call site will not be able to refer to them.
961
    ///
962
    /// Due to the current importance of hygiene this constructor, unlike other
963
    /// tokens, requires a `Span` to be specified at construction.
964
    ///
965
    /// # Panics
966
    ///
967
    /// Panics if the input string is neither a keyword nor a legal variable
968
    /// name. If you are not sure whether the string contains an identifier and
969
    /// need to handle an error case, use
970
    /// <a href="https://docs.rs/syn/2.0/syn/fn.parse_str.html"><code
971
    ///   style="padding-right:0;">syn::parse_str</code></a><code
972
    ///   style="padding-left:0;">::&lt;Ident&gt;</code>
973
    /// rather than `Ident::new`.
974
    #[track_caller]
975
0
    pub fn new(string: &str, span: Span) -> Self {
976
0
        Ident::_new(imp::Ident::new_checked(string, span.inner))
977
0
    }
978
979
    /// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The
980
    /// `string` argument must be a valid identifier permitted by the language
981
    /// (including keywords, e.g. `fn`). Keywords which are usable in path
982
    /// segments (e.g. `self`, `super`) are not supported, and will cause a
983
    /// panic.
984
    #[track_caller]
985
0
    pub fn new_raw(string: &str, span: Span) -> Self {
986
0
        Ident::_new(imp::Ident::new_raw_checked(string, span.inner))
987
0
    }
988
989
    /// Returns the span of this `Ident`.
990
0
    pub fn span(&self) -> Span {
991
0
        Span::_new(self.inner.span())
992
0
    }
993
994
    /// Configures the span of this `Ident`, possibly changing its hygiene
995
    /// context.
996
1.85M
    pub fn set_span(&mut self, span: Span) {
997
1.85M
        self.inner.set_span(span.inner);
998
1.85M
    }
999
}
1000
1001
impl PartialEq for Ident {
1002
0
    fn eq(&self, other: &Ident) -> bool {
1003
0
        self.inner == other.inner
1004
0
    }
1005
}
1006
1007
impl<T> PartialEq<T> for Ident
1008
where
1009
    T: ?Sized + AsRef<str>,
1010
{
1011
0
    fn eq(&self, other: &T) -> bool {
1012
0
        self.inner == other
1013
0
    }
1014
}
1015
1016
impl Eq for Ident {}
1017
1018
impl PartialOrd for Ident {
1019
0
    fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
1020
0
        Some(self.cmp(other))
1021
0
    }
1022
}
1023
1024
impl Ord for Ident {
1025
0
    fn cmp(&self, other: &Ident) -> Ordering {
1026
0
        self.to_string().cmp(&other.to_string())
1027
0
    }
1028
}
1029
1030
impl Hash for Ident {
1031
0
    fn hash<H: Hasher>(&self, hasher: &mut H) {
1032
0
        self.to_string().hash(hasher);
1033
0
    }
1034
}
1035
1036
/// Prints the identifier as a string that should be losslessly convertible back
1037
/// into the same identifier.
1038
impl Display for Ident {
1039
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1040
0
        Display::fmt(&self.inner, f)
1041
0
    }
1042
}
1043
1044
impl Debug for Ident {
1045
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1046
0
        Debug::fmt(&self.inner, f)
1047
0
    }
1048
}
1049
1050
/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
1051
/// byte character (`b'a'`), an integer or floating point number with or without
1052
/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1053
///
1054
/// Boolean literals like `true` and `false` do not belong here, they are
1055
/// `Ident`s.
1056
#[derive(Clone)]
1057
pub struct Literal {
1058
    inner: imp::Literal,
1059
    _marker: ProcMacroAutoTraits,
1060
}
1061
1062
macro_rules! suffixed_int_literals {
1063
    ($($name:ident => $kind:ident,)*) => ($(
1064
        /// Creates a new suffixed integer literal with the specified value.
1065
        ///
1066
        /// This function will create an integer like `1u32` where the integer
1067
        /// value specified is the first part of the token and the integral is
1068
        /// also suffixed at the end. Literals created from negative numbers may
1069
        /// not survive roundtrips through `TokenStream` or strings and may be
1070
        /// broken into two tokens (`-` and positive literal).
1071
        ///
1072
        /// Literals created through this method have the `Span::call_site()`
1073
        /// span by default, which can be configured with the `set_span` method
1074
        /// below.
1075
0
        pub fn $name(n: $kind) -> Literal {
1076
0
            Literal::_new(imp::Literal::$name(n))
1077
0
        }
Unexecuted instantiation: <proc_macro2::Literal>::u8_suffixed
Unexecuted instantiation: <proc_macro2::Literal>::u16_suffixed
Unexecuted instantiation: <proc_macro2::Literal>::u32_suffixed
Unexecuted instantiation: <proc_macro2::Literal>::u64_suffixed
Unexecuted instantiation: <proc_macro2::Literal>::u128_suffixed
Unexecuted instantiation: <proc_macro2::Literal>::usize_suffixed
Unexecuted instantiation: <proc_macro2::Literal>::i8_suffixed
Unexecuted instantiation: <proc_macro2::Literal>::i16_suffixed
Unexecuted instantiation: <proc_macro2::Literal>::i32_suffixed
Unexecuted instantiation: <proc_macro2::Literal>::i64_suffixed
Unexecuted instantiation: <proc_macro2::Literal>::i128_suffixed
Unexecuted instantiation: <proc_macro2::Literal>::isize_suffixed
1078
    )*)
1079
}
1080
1081
macro_rules! unsuffixed_int_literals {
1082
    ($($name:ident => $kind:ident,)*) => ($(
1083
        /// Creates a new unsuffixed integer literal with the specified value.
1084
        ///
1085
        /// This function will create an integer like `1` where the integer
1086
        /// value specified is the first part of the token. No suffix is
1087
        /// specified on this token, meaning that invocations like
1088
        /// `Literal::i8_unsuffixed(1)` are equivalent to
1089
        /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
1090
        /// may not survive roundtrips through `TokenStream` or strings and may
1091
        /// be broken into two tokens (`-` and positive literal).
1092
        ///
1093
        /// Literals created through this method have the `Span::call_site()`
1094
        /// span by default, which can be configured with the `set_span` method
1095
        /// below.
1096
0
        pub fn $name(n: $kind) -> Literal {
1097
0
            Literal::_new(imp::Literal::$name(n))
1098
0
        }
Unexecuted instantiation: <proc_macro2::Literal>::u8_unsuffixed
Unexecuted instantiation: <proc_macro2::Literal>::u16_unsuffixed
Unexecuted instantiation: <proc_macro2::Literal>::u32_unsuffixed
Unexecuted instantiation: <proc_macro2::Literal>::u64_unsuffixed
Unexecuted instantiation: <proc_macro2::Literal>::u128_unsuffixed
Unexecuted instantiation: <proc_macro2::Literal>::usize_unsuffixed
Unexecuted instantiation: <proc_macro2::Literal>::i8_unsuffixed
Unexecuted instantiation: <proc_macro2::Literal>::i16_unsuffixed
Unexecuted instantiation: <proc_macro2::Literal>::i32_unsuffixed
Unexecuted instantiation: <proc_macro2::Literal>::i64_unsuffixed
Unexecuted instantiation: <proc_macro2::Literal>::i128_unsuffixed
Unexecuted instantiation: <proc_macro2::Literal>::isize_unsuffixed
1099
    )*)
1100
}
1101
1102
impl Literal {
1103
0
    fn _new(inner: imp::Literal) -> Self {
1104
0
        Literal {
1105
0
            inner,
1106
0
            _marker: MARKER,
1107
0
        }
1108
0
    }
1109
1110
993k
    fn _new_fallback(inner: fallback::Literal) -> Self {
1111
993k
        Literal {
1112
993k
            inner: imp::Literal::from(inner),
1113
993k
            _marker: MARKER,
1114
993k
        }
1115
993k
    }
1116
1117
    suffixed_int_literals! {
1118
        u8_suffixed => u8,
1119
        u16_suffixed => u16,
1120
        u32_suffixed => u32,
1121
        u64_suffixed => u64,
1122
        u128_suffixed => u128,
1123
        usize_suffixed => usize,
1124
        i8_suffixed => i8,
1125
        i16_suffixed => i16,
1126
        i32_suffixed => i32,
1127
        i64_suffixed => i64,
1128
        i128_suffixed => i128,
1129
        isize_suffixed => isize,
1130
    }
1131
1132
    unsuffixed_int_literals! {
1133
        u8_unsuffixed => u8,
1134
        u16_unsuffixed => u16,
1135
        u32_unsuffixed => u32,
1136
        u64_unsuffixed => u64,
1137
        u128_unsuffixed => u128,
1138
        usize_unsuffixed => usize,
1139
        i8_unsuffixed => i8,
1140
        i16_unsuffixed => i16,
1141
        i32_unsuffixed => i32,
1142
        i64_unsuffixed => i64,
1143
        i128_unsuffixed => i128,
1144
        isize_unsuffixed => isize,
1145
    }
1146
1147
    /// Creates a new unsuffixed floating-point literal.
1148
    ///
1149
    /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1150
    /// the float's value is emitted directly into the token but no suffix is
1151
    /// used, so it may be inferred to be a `f64` later in the compiler.
1152
    /// Literals created from negative numbers may not survive round-trips
1153
    /// through `TokenStream` or strings and may be broken into two tokens (`-`
1154
    /// and positive literal).
1155
    ///
1156
    /// # Panics
1157
    ///
1158
    /// This function requires that the specified float is finite, for example
1159
    /// if it is infinity or NaN this function will panic.
1160
0
    pub fn f64_unsuffixed(f: f64) -> Literal {
1161
0
        assert!(f.is_finite());
1162
0
        Literal::_new(imp::Literal::f64_unsuffixed(f))
1163
0
    }
1164
1165
    /// Creates a new suffixed floating-point literal.
1166
    ///
1167
    /// This constructor will create a literal like `1.0f64` where the value
1168
    /// specified is the preceding part of the token and `f64` is the suffix of
1169
    /// the token. This token will always be inferred to be an `f64` in the
1170
    /// compiler. Literals created from negative numbers may not survive
1171
    /// round-trips through `TokenStream` or strings and may be broken into two
1172
    /// tokens (`-` and positive literal).
1173
    ///
1174
    /// # Panics
1175
    ///
1176
    /// This function requires that the specified float is finite, for example
1177
    /// if it is infinity or NaN this function will panic.
1178
0
    pub fn f64_suffixed(f: f64) -> Literal {
1179
0
        assert!(f.is_finite());
1180
0
        Literal::_new(imp::Literal::f64_suffixed(f))
1181
0
    }
1182
1183
    /// Creates a new unsuffixed floating-point literal.
1184
    ///
1185
    /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1186
    /// the float's value is emitted directly into the token but no suffix is
1187
    /// used, so it may be inferred to be a `f64` later in the compiler.
1188
    /// Literals created from negative numbers may not survive round-trips
1189
    /// through `TokenStream` or strings and may be broken into two tokens (`-`
1190
    /// and positive literal).
1191
    ///
1192
    /// # Panics
1193
    ///
1194
    /// This function requires that the specified float is finite, for example
1195
    /// if it is infinity or NaN this function will panic.
1196
0
    pub fn f32_unsuffixed(f: f32) -> Literal {
1197
0
        assert!(f.is_finite());
1198
0
        Literal::_new(imp::Literal::f32_unsuffixed(f))
1199
0
    }
1200
1201
    /// Creates a new suffixed floating-point literal.
1202
    ///
1203
    /// This constructor will create a literal like `1.0f32` where the value
1204
    /// specified is the preceding part of the token and `f32` is the suffix of
1205
    /// the token. This token will always be inferred to be an `f32` in the
1206
    /// compiler. Literals created from negative numbers may not survive
1207
    /// round-trips through `TokenStream` or strings and may be broken into two
1208
    /// tokens (`-` and positive literal).
1209
    ///
1210
    /// # Panics
1211
    ///
1212
    /// This function requires that the specified float is finite, for example
1213
    /// if it is infinity or NaN this function will panic.
1214
0
    pub fn f32_suffixed(f: f32) -> Literal {
1215
0
        assert!(f.is_finite());
1216
0
        Literal::_new(imp::Literal::f32_suffixed(f))
1217
0
    }
1218
1219
    /// String literal.
1220
0
    pub fn string(string: &str) -> Literal {
1221
0
        Literal::_new(imp::Literal::string(string))
1222
0
    }
1223
1224
    /// Character literal.
1225
0
    pub fn character(ch: char) -> Literal {
1226
0
        Literal::_new(imp::Literal::character(ch))
1227
0
    }
1228
1229
    /// Byte character literal.
1230
0
    pub fn byte_character(byte: u8) -> Literal {
1231
0
        Literal::_new(imp::Literal::byte_character(byte))
1232
0
    }
1233
1234
    /// Byte string literal.
1235
0
    pub fn byte_string(bytes: &[u8]) -> Literal {
1236
0
        Literal::_new(imp::Literal::byte_string(bytes))
1237
0
    }
1238
1239
    /// C string literal.
1240
0
    pub fn c_string(string: &CStr) -> Literal {
1241
0
        Literal::_new(imp::Literal::c_string(string))
1242
0
    }
1243
1244
    /// Returns the span encompassing this literal.
1245
0
    pub fn span(&self) -> Span {
1246
0
        Span::_new(self.inner.span())
1247
0
    }
1248
1249
    /// Configures the span associated for this literal.
1250
993k
    pub fn set_span(&mut self, span: Span) {
1251
993k
        self.inner.set_span(span.inner);
1252
993k
    }
1253
1254
    /// Returns a `Span` that is a subset of `self.span()` containing only
1255
    /// the source bytes in range `range`. Returns `None` if the would-be
1256
    /// trimmed span is outside the bounds of `self`.
1257
    ///
1258
    /// Warning: the underlying [`proc_macro::Literal::subspan`] method is
1259
    /// nightly-only. When called from within a procedural macro not using a
1260
    /// nightly compiler, this method will always return `None`.
1261
0
    pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1262
0
        self.inner.subspan(range).map(Span::_new)
1263
0
    }
1264
1265
    // Intended for the `quote!` macro to use when constructing a proc-macro2
1266
    // token out of a macro_rules $:literal token, which is already known to be
1267
    // a valid literal. This avoids reparsing/validating the literal's string
1268
    // representation. This is not public API other than for quote.
1269
    #[doc(hidden)]
1270
0
    pub unsafe fn from_str_unchecked(repr: &str) -> Self {
1271
0
        Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) })
1272
0
    }
1273
}
1274
1275
impl FromStr for Literal {
1276
    type Err = LexError;
1277
1278
0
    fn from_str(repr: &str) -> Result<Self, LexError> {
1279
0
        match imp::Literal::from_str_checked(repr) {
1280
0
            Ok(lit) => Ok(Literal::_new(lit)),
1281
0
            Err(lex) => Err(LexError {
1282
0
                inner: lex,
1283
0
                _marker: MARKER,
1284
0
            }),
1285
        }
1286
0
    }
1287
}
1288
1289
impl Debug for Literal {
1290
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1291
0
        Debug::fmt(&self.inner, f)
1292
0
    }
1293
}
1294
1295
impl Display for Literal {
1296
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1297
0
        Display::fmt(&self.inner, f)
1298
0
    }
1299
}
1300
1301
/// Public implementation details for the `TokenStream` type, such as iterators.
1302
pub mod token_stream {
1303
    use crate::marker::{ProcMacroAutoTraits, MARKER};
1304
    use crate::{imp, TokenTree};
1305
    use core::fmt::{self, Debug};
1306
1307
    pub use crate::TokenStream;
1308
1309
    /// An iterator over `TokenStream`'s `TokenTree`s.
1310
    ///
1311
    /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1312
    /// delimited groups, and returns whole groups as token trees.
1313
    #[derive(Clone)]
1314
    pub struct IntoIter {
1315
        inner: imp::TokenTreeIter,
1316
        _marker: ProcMacroAutoTraits,
1317
    }
1318
1319
    impl Iterator for IntoIter {
1320
        type Item = TokenTree;
1321
1322
0
        fn next(&mut self) -> Option<TokenTree> {
1323
0
            self.inner.next()
1324
0
        }
1325
1326
0
        fn size_hint(&self) -> (usize, Option<usize>) {
1327
0
            self.inner.size_hint()
1328
0
        }
1329
    }
1330
1331
    impl Debug for IntoIter {
1332
0
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1333
0
            f.write_str("TokenStream ")?;
1334
0
            f.debug_list().entries(self.clone()).finish()
1335
0
        }
1336
    }
1337
1338
    impl IntoIterator for TokenStream {
1339
        type Item = TokenTree;
1340
        type IntoIter = IntoIter;
1341
1342
0
        fn into_iter(self) -> IntoIter {
1343
0
            IntoIter {
1344
0
                inner: self.inner.into_iter(),
1345
0
                _marker: MARKER,
1346
0
            }
1347
0
        }
1348
    }
1349
}