pub trait FromLit: Sized {
// Required method
fn from_lit(lit: Literal) -> Result<Self, TokenStream>;
// Provided methods
fn from_ident(ident: Ident) -> Result<Self, TokenStream> { ... }
fn from_negative_lit(lit: Literal) -> Result<Self, TokenStream> { ... }
}Expand description
Converts literal tokens into typed values.
This trait is the core extension point for litext. Implementing it enables
litext!(input as MyType) to work for custom types.
§Implementations
The trait is automatically implemented for all built-in literal types:
- Strings:
String,LitStr - Integers:
i8–i128,isize,u8–u128,usize,LitInt<T> - Floats:
f32,f64,LitFloat<T> - Characters:
char,LitChar - Booleans:
bool,LitBool - Bytes:
u8,LitByte,Vec<u8>,LitByteStr - C Strings:
CString,LitCStr
§Method Overview
from_lithandles literal tokens ("hello",42,3.14)from_identhandles identifier tokens (true,false)from_negative_lithandles negative literals (-42)
Override from_ident for types represented as identifiers (like bool).
Override from_negative_lit for signed numeric types. The default
implementations return errors, which is correct for non-numeric types.
§Example
use litext::literal::FromLit;
use proc_macro2::{Literal, TokenStream};
pub struct UpperString(String);
impl FromLit for UpperString {
fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
let s = String::from_lit(lit)?;
Ok(UpperString(s.to_uppercase()))
}
}
// Then in your macro:
// let val: UpperString = litext!(input as UpperString);§See Also
crate::extractfor the function that drives extractionToTokensfor the reverse direction
Required Methods§
Provided Methods§
Sourcefn from_ident(ident: Ident) -> Result<Self, TokenStream>
fn from_ident(ident: Ident) -> Result<Self, TokenStream>
Attempts to extract a value from an Ident token.
Most types will never receive an ident, the default implementation
returns an error. Override this for types like bool where the
literal representation is an identifier (true, false).
§Errors
Errors to this function is in the form of a compile_error!() token stream, the cause
completely up to the implementer.
Sourcefn from_negative_lit(lit: Literal) -> Result<Self, TokenStream>
fn from_negative_lit(lit: Literal) -> Result<Self, TokenStream>
Attempts to extract a value from a negative Literal token.
A ‘negative Literal’ token in this case is the negative number, a dash punctuation followed by a number. Most types won’t accept or receive a negative literal. Override this for signed integer / float types where it accepts negatives as a value.
§Errors
Errors to this function is in the form of a compile_error!() token stream, the cause
completely up to the implementer.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.