use proc_macro::TokenStream;
use proc_macro2::Ident;
use quote::quote;
use std::collections::BTreeMap;
use syn::{parse_macro_input, Data, DeriveInput, Fields, Type};
fn to_snake_case(ident: &Ident) -> (Ident, String) {
let s = ident.to_string();
let chars: Vec<char> = s.chars().collect();
let mut result = String::with_capacity(s.len() + 4);
for i in 0..chars.len() {
let c = chars[i];
if c.is_uppercase() {
if i > 0 {
let prev = chars[i - 1];
if prev.is_lowercase() || (i + 1 < chars.len() && chars[i + 1].is_lowercase()) {
result.push('_');
}
}
result.extend(c.to_lowercase());
} else {
result.push(c);
}
}
let span = ident.span();
if is_rust_keyword(&result) {
(Ident::new_raw(&result, span), result)
} else {
(Ident::new(&result, span), result)
}
}
fn is_rust_keyword(s: &str) -> bool {
matches!(
s,
"abstract"
| "as"
| "async"
| "await"
| "become"
| "box"
| "break"
| "const"
| "continue"
| "crate"
| "do"
| "dyn"
| "else"
| "enum"
| "extern"
| "false"
| "final"
| "fn"
| "for"
| "if"
| "impl"
| "in"
| "let"
| "loop"
| "macro"
| "match"
| "mod"
| "move"
| "mut"
| "override"
| "priv"
| "pub"
| "ref"
| "return"
| "self"
| "Self"
| "static"
| "struct"
| "super"
| "trait"
| "true"
| "try"
| "type"
| "typeof"
| "union"
| "unsafe"
| "unsized"
| "use"
| "virtual"
| "where"
| "while"
| "yield"
)
}
fn method_idents(base_name: &str, span: proc_macro2::Span) -> (Ident, Ident, Ident) {
let mut_name = Ident::new(&format!("{base_name}_mut"), span);
let into_name = Ident::new(&format!("into_{base_name}"), span);
let is_name = Ident::new(&format!("is_{base_name}"), span);
(mut_name, into_name, is_name)
}
fn generate_unit_methods(
variant_ident: &Ident,
method_ident: &Ident,
base_name: &str,
) -> proc_macro2::TokenStream {
let (method_mut, into_method, is_method) = method_idents(base_name, method_ident.span());
let v = variant_ident.to_string();
let doc_ref = format!("Returns `Some(())` if this value is `{v}`, otherwise `None`.");
let doc_mut = format!("Returns `Some(())` if this value is `{v}`, otherwise `None`.");
let doc_into =
format!("Consumes `self` and returns `Some(())` if this value is `{v}`, otherwise `None`.");
let doc_is = format!("Returns `true` if this value is `{v}`.");
quote! {
#[doc = #doc_ref]
pub fn #method_ident(&self) -> Option<()> {
match self {
Self::#variant_ident => Some(()),
_ => None,
}
}
#[doc = #doc_mut]
pub fn #method_mut(&mut self) -> Option<()> {
match self {
Self::#variant_ident => Some(()),
_ => None,
}
}
#[doc = #doc_into]
pub fn #into_method(self) -> Option<()> {
match self {
Self::#variant_ident => Some(()),
_ => None,
}
}
#[doc = #doc_is]
pub fn #is_method(&self) -> bool {
matches!(self, Self::#variant_ident)
}
}
}
fn generate_unnamed_methods(
fields: &syn::FieldsUnnamed,
variant_ident: &Ident,
method_ident: &Ident,
base_name: &str,
) -> proc_macro2::TokenStream {
let field_count = fields.unnamed.len();
let pat_vars: Vec<Ident> = (0..field_count)
.map(|i| {
let name = if field_count == 1 {
"v".to_string()
} else {
format!("v{i}")
};
Ident::new(&name, variant_ident.span())
})
.collect();
let field_tys: Vec<&Type> = fields.unnamed.iter().map(|f| &f.ty).collect();
let (method_mut, into_method, is_method) = method_idents(base_name, method_ident.span());
let v = variant_ident.to_string();
let doc_ref = format!("Returns `Some(...)` if this value is `{v}`, otherwise `None`.");
let doc_mut = format!("Returns `Some(...)` if this value is `{v}`, otherwise `None`.");
let doc_into = format!(
"Consumes `self` and returns `Some(...)` if this value is `{v}`, otherwise `None`."
);
let doc_is = format!("Returns `true` if this value is `{v}`.");
let ref_tys: Vec<_> = field_tys.iter().map(|ty| quote! { &#ty }).collect();
let mut_tys: Vec<_> = field_tys.iter().map(|ty| quote! { &mut #ty }).collect();
quote! {
#[doc = #doc_ref]
pub fn #method_ident(&self) -> Option<(#(#ref_tys),*)> {
match self { Self::#variant_ident(#(#pat_vars),*) => Some((#(#pat_vars),*)), _ => None }
}
#[doc = #doc_mut]
pub fn #method_mut(&mut self) -> Option<(#(#mut_tys),*)> {
match self { Self::#variant_ident(#(#pat_vars),*) => Some((#(#pat_vars),*)), _ => None }
}
#[doc = #doc_into]
pub fn #into_method(self) -> Option<(#(#field_tys),*)> {
match self { Self::#variant_ident(#(#pat_vars),*) => Some((#(#pat_vars),*)), _ => None }
}
#[doc = #doc_is]
pub fn #is_method(&self) -> bool {
matches!(self, Self::#variant_ident(..))
}
}
}
fn generate_named_single_methods(
fields: &syn::FieldsNamed,
variant_ident: &Ident,
method_ident: &Ident,
base_name: &str,
) -> proc_macro2::TokenStream {
let field_idents: Vec<&Ident> = fields
.named
.iter()
.map(|f| f.ident.as_ref().unwrap())
.collect();
let field_tys: Vec<&Type> = fields.named.iter().map(|f| &f.ty).collect();
let (method_mut, into_method, is_method) = method_idents(base_name, method_ident.span());
let v = variant_ident.to_string();
let doc_ref = format!("Returns `Some(...)` if this value is `{v}`, otherwise `None`.");
let doc_mut = format!("Returns `Some(...)` if this value is `{v}`, otherwise `None`.");
let doc_into = format!(
"Consumes `self` and returns `Some(...)` if this value is `{v}`, otherwise `None`."
);
let doc_is = format!("Returns `true` if this value is `{v}`.");
let ref_tys: Vec<_> = field_tys.iter().map(|ty| quote! { &#ty }).collect();
let mut_tys: Vec<_> = field_tys.iter().map(|ty| quote! { &mut #ty }).collect();
quote! {
#[doc = #doc_ref]
pub fn #method_ident(&self) -> Option<(#(#ref_tys),*)> {
match self { Self::#variant_ident { #(#field_idents),* } => Some((#(#field_idents),*)), _ => None }
}
#[doc = #doc_mut]
pub fn #method_mut(&mut self) -> Option<(#(#mut_tys),*)> {
match self { Self::#variant_ident { #(#field_idents),* } => Some((#(#field_idents),*)), _ => None }
}
#[doc = #doc_into]
pub fn #into_method(self) -> Option<(#(#field_tys),*)> {
match self { Self::#variant_ident { #(#field_idents),* } => Some((#(#field_idents),*)), _ => None }
}
#[doc = #doc_is]
pub fn #is_method(&self) -> bool {
matches!(self, Self::#variant_ident { .. })
}
}
}
fn generate_named_multi_methods(
fields: &syn::FieldsNamed,
variant_ident: &Ident,
method_ident: &Ident,
base_name: &str,
enum_generics: &syn::Generics,
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
let field_idents: Vec<&Ident> = fields
.named
.iter()
.map(|f| f.ident.as_ref().unwrap())
.collect();
let field_tys: Vec<&Type> = fields.named.iter().map(|f| &f.ty).collect();
let (method_mut, into_method, is_method) = method_idents(base_name, method_ident.span());
let v = variant_ident.to_string();
let doc_ref = format!("Returns `Some(...)` if this value is `{v}`, otherwise `None`.");
let doc_mut = format!("Returns `Some(...)` if this value is `{v}`, otherwise `None`.");
let doc_into = format!(
"Consumes `self` and returns `Some(...)` if this value is `{v}`, otherwise `None`."
);
let doc_is = format!("Returns `true` if this value is `{v}`.");
let ref_struct_name = Ident::new(&format!("{v}Ref"), variant_ident.span());
let ref_mut_struct_name = Ident::new(&format!("{v}RefMut"), variant_ident.span());
let owned_struct_name = Ident::new(&format!("{v}Owned"), variant_ident.span());
let gen_params = &enum_generics.params;
let (_impl_gen, ty_gen, _where) = enum_generics.split_for_impl();
let struct_defs = quote! {
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq)]
pub struct #ref_struct_name <'a, #gen_params> {
#(pub #field_idents: &'a #field_tys),*
}
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq)]
pub struct #ref_mut_struct_name <'a, #gen_params> {
#(pub #field_idents: &'a mut #field_tys),*
}
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq)]
pub struct #owned_struct_name #ty_gen {
#(pub #field_idents: #field_tys),*
}
};
let methods = quote! {
#[doc = #doc_ref]
pub fn #method_ident(&self) -> Option<#ref_struct_name<'_, #gen_params>> {
match self {
Self::#variant_ident { #(#field_idents),* } => {
Some(#ref_struct_name { #(#field_idents),* })
}
_ => None,
}
}
#[doc = #doc_mut]
pub fn #method_mut(&mut self) -> Option<#ref_mut_struct_name<'_, #gen_params>> {
match self {
Self::#variant_ident { #(#field_idents),* } => {
Some(#ref_mut_struct_name { #(#field_idents),* })
}
_ => None,
}
}
#[doc = #doc_into]
pub fn #into_method(self) -> Option<#owned_struct_name #ty_gen> {
match self {
Self::#variant_ident { #(#field_idents),* } => {
Some(#owned_struct_name { #(#field_idents),* })
}
_ => None,
}
}
#[doc = #doc_is]
pub fn #is_method(&self) -> bool {
matches!(self, Self::#variant_ident { .. })
}
};
(struct_defs, methods)
}
fn check_method_conflicts(variants: &[(&syn::Ident, &str)]) -> Result<(), Vec<syn::Error>> {
let mut name_map: BTreeMap<String, Vec<&syn::Ident>> = BTreeMap::new();
for (variant_ident, base_name) in variants {
name_map
.entry(base_name.to_string())
.or_default()
.push(variant_ident);
name_map
.entry(format!("{base_name}_mut"))
.or_default()
.push(variant_ident);
name_map
.entry(format!("into_{base_name}"))
.or_default()
.push(variant_ident);
name_map
.entry(format!("is_{base_name}"))
.or_default()
.push(variant_ident);
}
let errors: Vec<syn::Error> = name_map
.iter()
.filter(|(_, idents)| idents.len() > 1)
.map(|(name, idents)| {
let v0 = idents[0];
let v1 = idents[1];
let msg = format!(
"OneOf generates duplicated method `{name}` from variants `{v0}` and `{v1}`.\n\
Rename one of the variants to resolve the conflict."
);
syn::Error::new(v0.span(), msg)
})
.collect();
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
#[proc_macro_derive(OneOf)]
pub fn derive_one_of(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
match &input.data {
Data::Enum(enum_data) => {
let enum_name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let variant_bases: Vec<(&syn::Ident, String)> = enum_data
.variants
.iter()
.map(|v| {
let (_, base_name) = to_snake_case(&v.ident);
(&v.ident, base_name)
})
.collect();
let variant_refs: Vec<(&syn::Ident, &str)> = variant_bases
.iter()
.map(|(id, s)| (*id, s.as_str()))
.collect();
if let Err(errors) = check_method_conflicts(&variant_refs) {
return errors
.into_iter()
.map(|e| e.to_compile_error())
.fold(proc_macro2::TokenStream::new(), |mut acc, ts| {
acc.extend(ts);
acc
})
.into();
}
let mut struct_defs = proc_macro2::TokenStream::new();
let variant_methods: Vec<_> = enum_data
.variants
.iter()
.map(|variant| {
let variant_ident = &variant.ident;
let (method_ident, base_name) = to_snake_case(variant_ident);
match &variant.fields {
Fields::Unit => {
generate_unit_methods(variant_ident, &method_ident, &base_name)
}
Fields::Unnamed(fields) => generate_unnamed_methods(
fields,
variant_ident,
&method_ident,
&base_name,
),
Fields::Named(fields) if fields.named.len() > 1 => {
let (structs, methods) = generate_named_multi_methods(
fields,
variant_ident,
&method_ident,
&base_name,
&input.generics,
);
struct_defs.extend(structs);
methods
}
Fields::Named(fields) => generate_named_single_methods(
fields,
variant_ident,
&method_ident,
&base_name,
),
}
})
.collect();
let expanded = quote! {
#struct_defs
impl #impl_generics #enum_name #ty_generics #where_clause {
#(#variant_methods)*
}
};
expanded.into()
}
Data::Struct(_) | Data::Union(_) => {
syn::Error::new(input.ident.span(), "OneOf can only be derived on enums")
.to_compile_error()
.into()
}
}
}