From e721564c59a5d5fd004a62857473166fa8a3f9dc Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 24 Jun 2025 17:51:59 +0200 Subject: [PATCH] Add new `Literal::str_value`, `Literal::cstr_value` and `Literal::byte_str_value` methods --- Cargo.toml | 2 +- src/lib.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index e35be01..88e252a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,7 +45,7 @@ default = ["proc-macro"] # of a token. span-locations = [] -# This feature no longer means anything. +# Used for unstable `Literal` API. nightly = [] [workspace] diff --git a/src/lib.rs b/src/lib.rs index 0875aa5..43fba5b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -116,6 +116,7 @@ clippy::vec_init_then_push )] #![allow(unknown_lints, mismatched_lifetime_syntaxes)] +#![cfg_attr(feature = "nightly", feature(proc_macro_value))] #[cfg(all(procmacro2_semver_exempt, wrap_proc_macro, not(super_unstable)))] compile_error! {"\ @@ -1273,6 +1274,35 @@ impl Literal { pub unsafe fn from_str_unchecked(repr: &str) -> Self { Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) }) } + + /// Returns the unescaped string value if the current literal is a string or a string literal. + #[cfg(feature = "nightly")] + pub fn str_value(&self) -> Result { + let imp::Literal::Compiler(ref compiler_lit) = self.inner else { + panic!("method only supported on compiler literals"); + }; + compiler_lit.str_value() + } + + /// Returns the unescaped string value if the current literal is a c-string or a c-string + /// literal. + #[cfg(feature = "nightly")] + pub fn cstr_value(&self) -> Result, proc_macro::ConversionErrorKind> { + let imp::Literal::Compiler(ref compiler_lit) = self.inner else { + panic!("method only supported on compiler literals"); + }; + compiler_lit.cstr_value() + } + + /// Returns the unescaped string value if the current literal is a byte string or a byte string + /// literal. + #[cfg(feature = "nightly")] + pub fn byte_str_value(&self) -> Result, proc_macro::ConversionErrorKind> { + let imp::Literal::Compiler(ref compiler_lit) = self.inner else { + panic!("method only supported on compiler literals"); + }; + compiler_lit.byte_str_value() + } } impl FromStr for Literal {