for TokenTree {
fn from(g: Literal) -> Self {
TokenTree::Literal(g)
}
}
/// Prints the token tree as a string that is supposed to be losslessly
/// convertible back into the same token tree (modulo spans), except for
/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
/// numeric literals.
impl Display for TokenTree {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
TokenTree::Group(t) => Display::fmt(t, f),
TokenTree::Ident(t) => Display::fmt(t, f),
TokenTree::Punct(t) => Display::fmt(t, f),
TokenTree::Literal(t) => Display::fmt(t, f),
}
}
}
/// Prints token tree in a form convenient for debugging.
impl Debug for TokenTree {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Each of these has the name in the struct type in the derived debug,
// so don't bother with an extra layer of indirection
match self {
TokenTree::Group(t) => Debug::fmt(t, f),
TokenTree::Ident(t) => {
let mut debug = f.debug_struct("Ident");
debug.field("sym", &format_args!("{}", t));
imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);
debug.finish()
}
TokenTree::Punct(t) => Debug::fmt(t, f),
TokenTree::Literal(t) => Debug::fmt(t, f),
}
}
}
/// A delimited token stream.
///
/// A `Group` internally contains a `TokenStream` which is surrounded by
/// `Delimiter`s.
#[derive(Clone)]
pub struct Group {
inner: imp::Group,
}
/// Describes how a sequence of token trees is delimited.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Delimiter {
/// `( ... )`
Parenthesis,
/// `{ ... }`
Brace,
/// `[ ... ]`
Bracket,
/// `∅ ... ∅`
///
/// An invisible delimiter, that may, for example, appear around tokens
/// coming from a "macro variable" `$var`. It is important to preserve
/// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
/// Invisible delimiters may not survive roundtrip of a token stream through
/// a string.
///
///
///
/// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
/// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
/// of a proc_macro macro are preserved, and only in very specific circumstances.
/// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
/// operator priorities as indicated above. The other `Delimiter` variants should be used
/// instead in this context. This is a rustc bug. For details, see
/// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
///
///
None,
}
impl Group {
fn _new(inner: imp::Group) -> Self {
Group { inner }
}
fn _new_fallback(inner: fallback::Group) -> Self {
Group {
inner: inner.into(),
}
}
/// Creates a new `Group` with the given delimiter and token stream.
///
/// This constructor will set the span for this group to
/// `Span::call_site()`. To change the span you can use the `set_span`
/// method below.
pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
Group {
inner: imp::Group::new(delimiter, stream.inner),
}
}
/// Returns the punctuation used as the delimiter for this group: a set of
/// parentheses, square brackets, or curly braces.
pub fn delimiter(&self) -> Delimiter {
self.inner.delimiter()
}
/// Returns the `TokenStream` of tokens that are delimited in this `Group`.
///
/// Note that the returned token stream does not include the delimiter
/// returned above.
pub fn stream(&self) -> TokenStream {
TokenStream::_new(self.inner.stream())
}
/// Returns the span for the delimiters of this token stream, spanning the
/// entire `Group`.
///
/// ```text
/// pub fn span(&self) -> Span {
/// ^^^^^^^
/// ```
pub fn span(&self) -> Span {
Span::_new(self.inner.span())
}
/// Returns the span pointing to the opening delimiter of this group.
///
/// ```text
/// pub fn span_open(&self) -> Span {
/// ^
/// ```
pub fn span_open(&self) -> Span {
Span::_new(self.inner.span_open())
}
/// Returns the span pointing to the closing delimiter of this group.
///
/// ```text
/// pub fn span_close(&self) -> Span {
/// ^
/// ```
pub fn span_close(&self) -> Span {
Span::_new(self.inner.span_close())
}
/// Returns an object that holds this group's `span_open()` and
/// `span_close()` together (in a more compact representation than holding
/// those 2 spans individually).
pub fn delim_span(&self) -> DelimSpan {
DelimSpan::new(&self.inner)
}
/// Configures the span for this `Group`'s delimiters, but not its internal
/// tokens.
///
/// This method will **not** set the span of all the internal tokens spanned
/// by this group, but rather it will only set the span of the delimiter
/// tokens at the level of the `Group`.
pub fn set_span(&mut self, span: Span) {
self.inner.set_span(span.inner);
}
}
/// Prints the group as a string that should be losslessly convertible back
/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
/// with `Delimiter::None` delimiters.
impl Display for Group {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&self.inner, formatter)
}
}
impl Debug for Group {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(&self.inner, formatter)
}
}
/// A `Punct` is a single punctuation character like `+`, `-` or `#`.
///
/// Multicharacter operators like `+=` are represented as two instances of
/// `Punct` with different forms of `Spacing` returned.
#[derive(Clone)]
pub struct Punct {
ch: char,
spacing: Spacing,
span: Span,
}
/// Whether a `Punct` is followed immediately by another `Punct` or followed by
/// another token or whitespace.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Spacing {
/// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
Alone,
/// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`.
///
/// Additionally, single quote `'` can join with identifiers to form
/// lifetimes `'ident`.
Joint,
}
impl Punct {
/// Creates a new `Punct` from the given character and spacing.
///
/// The `ch` argument must be a valid punctuation character permitted by the
/// language, otherwise the function will panic.
///
/// The returned `Punct` will have the default span of `Span::call_site()`
/// which can be further configured with the `set_span` method below.
pub fn new(ch: char, spacing: Spacing) -> Self {
Punct {
ch,
spacing,
span: Span::call_site(),
}
}
/// Returns the value of this punctuation character as `char`.
pub fn as_char(&self) -> char {
self.ch
}
/// Returns the spacing of this punctuation character, indicating whether
/// it's immediately followed by another `Punct` in the token stream, so
/// they can potentially be combined into a multicharacter operator
/// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
/// so the operator has certainly ended.
pub fn spacing(&self) -> Spacing {
self.spacing
}
/// Returns the span for this punctuation character.
pub fn span(&self) -> Span {
self.span
}
/// Configure the span for this punctuation character.
pub fn set_span(&mut self, span: Span) {
self.span = span;
}
}
/// Prints the punctuation character as a string that should be losslessly
/// convertible back into the same character.
impl Display for Punct {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&self.ch, f)
}
}
impl Debug for Punct {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let mut debug = fmt.debug_struct("Punct");
debug.field("char", &self.ch);
debug.field("spacing", &self.spacing);
imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);
debug.finish()
}
}
/// A word of Rust code, which may be a keyword or legal variable name.
///
/// An identifier consists of at least one Unicode code point, the first of
/// which has the XID_Start property and the rest of which have the XID_Continue
/// property.
///
/// - The empty string is not an identifier. Use `Option`.
/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
///
/// An identifier constructed with `Ident::new` is permitted to be a Rust
/// keyword, though parsing one through its [`Parse`] implementation rejects
/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
/// behaviour of `Ident::new`.
///
/// [`Parse`]: https://docs.rs/syn/2.0/syn/parse/trait.Parse.html
///
/// # Examples
///
/// A new ident can be created from a string using the `Ident::new` function.
/// A span must be provided explicitly which governs the name resolution
/// behavior of the resulting identifier.
///
/// ```
/// use proc_macro2::{Ident, Span};
///
/// fn main() {
/// let call_ident = Ident::new("calligraphy", Span::call_site());
///
/// println!("{}", call_ident);
/// }
/// ```
///
/// An ident can be interpolated into a token stream using the `quote!` macro.
///
/// ```
/// use proc_macro2::{Ident, Span};
/// use quote::quote;
///
/// fn main() {
/// let ident = Ident::new("demo", Span::call_site());
///
/// // Create a variable binding whose name is this ident.
/// let expanded = quote! { let #ident = 10; };
///
/// // Create a variable binding with a slightly different name.
/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
/// let expanded = quote! { let #temp_ident = 10; };
/// }
/// ```
///
/// A string representation of the ident is available through the `to_string()`
/// method.
///
/// ```
/// # use proc_macro2::{Ident, Span};
/// #
/// # let ident = Ident::new("another_identifier", Span::call_site());
/// #
/// // Examine the ident as a string.
/// let ident_string = ident.to_string();
/// if ident_string.len() > 60 {
/// println!("Very long identifier: {}", ident_string)
/// }
/// ```
#[derive(Clone)]
pub struct Ident {
inner: imp::Ident,
_marker: ProcMacroAutoTraits,
}
impl Ident {
fn _new(inner: imp::Ident) -> Self {
Ident {
inner,
_marker: MARKER,
}
}
/// Creates a new `Ident` with the given `string` as well as the specified
/// `span`.
///
/// The `string` argument must be a valid identifier permitted by the
/// language, otherwise the function will panic.
///
/// Note that `span`, currently in rustc, configures the hygiene information
/// for this identifier.
///
/// As of this time `Span::call_site()` explicitly opts-in to "call-site"
/// hygiene meaning that identifiers created with this span will be resolved
/// as if they were written directly at the location of the macro call, and
/// other code at the macro call site will be able to refer to them as well.
///
/// Later spans like `Span::def_site()` will allow to opt-in to
/// "definition-site" hygiene meaning that identifiers created with this
/// span will be resolved at the location of the macro definition and other
/// code at the macro call site will not be able to refer to them.
///
/// Due to the current importance of hygiene this constructor, unlike other
/// tokens, requires a `Span` to be specified at construction.
///
/// # Panics
///
/// Panics if the input string is neither a keyword nor a legal variable
/// name. If you are not sure whether the string contains an identifier and
/// need to handle an error case, use
/// syn::parse_str
::<Ident>
/// rather than `Ident::new`.
#[track_caller]
pub fn new(string: &str, span: Span) -> Self {
Ident::_new(imp::Ident::new_checked(string, span.inner))
}
/// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The
/// `string` argument must be a valid identifier permitted by the language
/// (including keywords, e.g. `fn`). Keywords which are usable in path
/// segments (e.g. `self`, `super`) are not supported, and will cause a
/// panic.
#[track_caller]
pub fn new_raw(string: &str, span: Span) -> Self {
Ident::_new(imp::Ident::new_raw_checked(string, span.inner))
}
/// Returns the span of this `Ident`.
pub fn span(&self) -> Span {
Span::_new(self.inner.span())
}
/// Configures the span of this `Ident`, possibly changing its hygiene
/// context.
pub fn set_span(&mut self, span: Span) {
self.inner.set_span(span.inner);
}
}
impl PartialEq for Ident {
fn eq(&self, other: &Ident) -> bool {
self.inner == other.inner
}
}
impl PartialEq for Ident
where
T: ?Sized + AsRef,
{
fn eq(&self, other: &T) -> bool {
self.inner == other
}
}
impl Eq for Ident {}
impl PartialOrd for Ident {
fn partial_cmp(&self, other: &Ident) -> Option {
Some(self.cmp(other))
}
}
impl Ord for Ident {
fn cmp(&self, other: &Ident) -> Ordering {
self.to_string().cmp(&other.to_string())
}
}
impl Hash for Ident {
fn hash(&self, hasher: &mut H) {
self.to_string().hash(hasher);
}
}
/// Prints the identifier as a string that should be losslessly convertible back
/// into the same identifier.
impl Display for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&self.inner, f)
}
}
impl Debug for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(&self.inner, f)
}
}
/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
/// byte character (`b'a'`), an integer or floating point number with or without
/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
///
/// Boolean literals like `true` and `false` do not belong here, they are
/// `Ident`s.
#[derive(Clone)]
pub struct Literal {
inner: imp::Literal,
_marker: ProcMacroAutoTraits,
}
macro_rules! suffixed_int_literals {
($($name:ident => $kind:ident,)*) => ($(
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end. Literals created from negative numbers may
/// not survive roundtrips through `TokenStream` or strings and may be
/// broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
pub fn $name(n: $kind) -> Literal {
Literal::_new(imp::Literal::$name(n))
}
)*)
}
macro_rules! unsuffixed_int_literals {
($($name:ident => $kind:ident,)*) => ($(
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
/// may not survive roundtrips through `TokenStream` or strings and may
/// be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
pub fn $name(n: $kind) -> Literal {
Literal::_new(imp::Literal::$name(n))
}
)*)
}
impl Literal {
fn _new(inner: imp::Literal) -> Self {
Literal {
inner,
_marker: MARKER,
}
}
fn _new_fallback(inner: fallback::Literal) -> Self {
Literal {
inner: inner.into(),
_marker: MARKER,
}
}
suffixed_int_literals! {
u8_suffixed => u8,
u16_suffixed => u16,
u32_suffixed => u32,
u64_suffixed => u64,
u128_suffixed => u128,
usize_suffixed => usize,
i8_suffixed => i8,
i16_suffixed => i16,
i32_suffixed => i32,
i64_suffixed => i64,
i128_suffixed => i128,
isize_suffixed => isize,
}
unsuffixed_int_literals! {
u8_unsuffixed => u8,
u16_unsuffixed => u16,
u32_unsuffixed => u32,
u64_unsuffixed => u64,
u128_unsuffixed => u128,
usize_unsuffixed => usize,
i8_unsuffixed => i8,
i16_unsuffixed => i16,
i32_unsuffixed => i32,
i64_unsuffixed => i64,
i128_unsuffixed => i128,
isize_unsuffixed => isize,
}
/// Creates a new unsuffixed floating-point literal.
///
/// This constructor is similar to those like `Literal::i8_unsuffixed` where
/// the float's value is emitted directly into the token but no suffix is
/// used, so it may be inferred to be a `f64` later in the compiler.
/// Literals created from negative numbers may not survive round-trips
/// through `TokenStream` or strings and may be broken into two tokens (`-`
/// and positive literal).
///
/// # Panics
///
/// This function requires that the specified float is finite, for example
/// if it is infinity or NaN this function will panic.
pub fn f64_unsuffixed(f: f64) -> Literal {
assert!(f.is_finite());
Literal::_new(imp::Literal::f64_unsuffixed(f))
}
/// Creates a new suffixed floating-point literal.
///
/// This constructor will create a literal like `1.0f64` where the value
/// specified is the preceding part of the token and `f64` is the suffix of
/// the token. This token will always be inferred to be an `f64` in the
/// compiler. Literals created from negative numbers may not survive
/// round-trips through `TokenStream` or strings and may be broken into two
/// tokens (`-` and positive literal).
///
/// # Panics
///
/// This function requires that the specified float is finite, for example
/// if it is infinity or NaN this function will panic.
pub fn f64_suffixed(f: f64) -> Literal {
assert!(f.is_finite());
Literal::_new(imp::Literal::f64_suffixed(f))
}
/// Creates a new unsuffixed floating-point literal.
///
/// This constructor is similar to those like `Literal::i8_unsuffixed` where
/// the float's value is emitted directly into the token but no suffix is
/// used, so it may be inferred to be a `f64` later in the compiler.
/// Literals created from negative numbers may not survive round-trips
/// through `TokenStream` or strings and may be broken into two tokens (`-`
/// and positive literal).
///
/// # Panics
///
/// This function requires that the specified float is finite, for example
/// if it is infinity or NaN this function will panic.
pub fn f32_unsuffixed(f: f32) -> Literal {
assert!(f.is_finite());
Literal::_new(imp::Literal::f32_unsuffixed(f))
}
/// Creates a new suffixed floating-point literal.
///
/// This constructor will create a literal like `1.0f32` where the value
/// specified is the preceding part of the token and `f32` is the suffix of
/// the token. This token will always be inferred to be an `f32` in the
/// compiler. Literals created from negative numbers may not survive
/// round-trips through `TokenStream` or strings and may be broken into two
/// tokens (`-` and positive literal).
///
/// # Panics
///
/// This function requires that the specified float is finite, for example
/// if it is infinity or NaN this function will panic.
pub fn f32_suffixed(f: f32) -> Literal {
assert!(f.is_finite());
Literal::_new(imp::Literal::f32_suffixed(f))
}
/// String literal.
pub fn string(string: &str) -> Literal {
Literal::_new(imp::Literal::string(string))
}
/// Character literal.
pub fn character(ch: char) -> Literal {
Literal::_new(imp::Literal::character(ch))
}
/// Byte character literal.
pub fn byte_character(byte: u8) -> Literal {
Literal::_new(imp::Literal::byte_character(byte))
}
/// Byte string literal.
pub fn byte_string(bytes: &[u8]) -> Literal {
Literal::_new(imp::Literal::byte_string(bytes))
}
/// C string literal.
pub fn c_string(string: &CStr) -> Literal {
Literal::_new(imp::Literal::c_string(string))
}
/// Returns the span encompassing this literal.
pub fn span(&self) -> Span {
Span::_new(self.inner.span())
}
/// Configures the span associated for this literal.
pub fn set_span(&mut self, span: Span) {
self.inner.set_span(span.inner);
}
/// Returns a `Span` that is a subset of `self.span()` containing only
/// the source bytes in range `range`. Returns `None` if the would-be
/// trimmed span is outside the bounds of `self`.
///
/// Warning: the underlying [`proc_macro::Literal::subspan`] method is
/// nightly-only. When called from within a procedural macro not using a
/// nightly compiler, this method will always return `None`.
///
/// [`proc_macro::Literal::subspan`]: https://doc.rust-lang.org/proc_macro/struct.Literal.html#method.subspan
pub fn subspan>(&self, range: R) -> Option {
self.inner.subspan(range).map(Span::_new)
}
// Intended for the `quote!` macro to use when constructing a proc-macro2
// token out of a macro_rules $:literal token, which is already known to be
// a valid literal. This avoids reparsing/validating the literal's string
// representation. This is not public API other than for quote.
#[doc(hidden)]
pub unsafe fn from_str_unchecked(repr: &str) -> Self {
Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) })
}
}
impl FromStr for Literal {
type Err = LexError;
fn from_str(repr: &str) -> Result {
repr.parse().map(Literal::_new).map_err(|inner| LexError {
inner,
_marker: MARKER,
})
}
}
impl Debug for Literal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(&self.inner, f)
}
}
impl Display for Literal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&self.inner, f)
}
}
/// Public implementation details for the `TokenStream` type, such as iterators.
pub mod token_stream {
use crate::marker::{ProcMacroAutoTraits, MARKER};
use crate::{imp, TokenTree};
use core::fmt::{self, Debug};
pub use crate::TokenStream;
/// An iterator over `TokenStream`'s `TokenTree`s.
///
/// The iteration is "shallow", e.g. the iterator doesn't recurse into
/// delimited groups, and returns whole groups as token trees.
#[derive(Clone)]
pub struct IntoIter {
inner: imp::TokenTreeIter,
_marker: ProcMacroAutoTraits,
}
impl Iterator for IntoIter {
type Item = TokenTree;
fn next(&mut self) -> Option {
self.inner.next()
}
fn size_hint(&self) -> (usize, Option) {
self.inner.size_hint()
}
}
impl Debug for IntoIter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("TokenStream ")?;
f.debug_list().entries(self.clone()).finish()
}
}
impl IntoIterator for TokenStream {
type Item = TokenTree;
type IntoIter = IntoIter;
fn into_iter(self) -> IntoIter {
IntoIter {
inner: self.inner.into_iter(),
_marker: MARKER,
}
}
}
}