safe_proc_macro2/
lib.rs

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