Restructure crates for correct proc macro usage

Signed-off-by: Lee Smet <lee.smet@hotmail.com>
This commit is contained in:
Lee Smet
2025-04-25 13:58:17 +02:00
parent 96a1ecd974
commit b8e1449ddb
20 changed files with 588 additions and 362 deletions

68
heromodels-derive/Cargo.lock generated Normal file
View File

@@ -0,0 +1,68 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "heromodels-derive"
version = "0.1.0"
dependencies = [
"proc-macro2",
"quote",
"serde",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.219"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.219"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "syn"
version = "2.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"

View File

@@ -0,0 +1,17 @@
[package]
name = "heromodels-derive"
version = "0.1.0"
edition = "2024"
description = "Derive macros for heromodels"
authors = ["Your Name <your.email@example.com>"]
[lib]
proc-macro = true
[dependencies]
syn = { version = "2.0", features = ["full", "extra-traits", "parsing"] }
quote = "1.0"
proc-macro2 = "1.0"
[dev-dependencies]
serde = { version = "1.0", features = ["derive"] }

View File

@@ -0,0 +1,198 @@
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{Data, DeriveInput, Fields, parse_macro_input};
/// Convert a string to snake_case
fn to_snake_case(s: &str) -> String {
let mut result = String::new();
for (i, c) in s.char_indices() {
if i > 0 && c.is_uppercase() {
result.push('_');
}
result.push(c.to_lowercase().next().unwrap());
}
result
}
/// Convert a string to PascalCase
// fn to_pascal_case(s: &str) -> String {
// let mut result = String::new();
// let mut capitalize_next = true;
//
// for c in s.chars() {
// if c == '_' {
// capitalize_next = true;
// } else if capitalize_next {
// result.push(c.to_uppercase().next().unwrap());
// capitalize_next = false;
// } else {
// result.push(c);
// }
// }
//
// result
// }
/// Implements the Model trait and generates Index trait implementations for fields marked with #[index].
#[proc_macro_attribute]
pub fn model(_attr: TokenStream, item: TokenStream) -> TokenStream {
// Parse the input tokens into a syntax tree
let mut input = parse_macro_input!(item as DeriveInput);
// Extract struct name
let struct_name = &input.ident;
// Convert struct name to snake_case for db_prefix
let name_str = struct_name.to_string();
let db_prefix = to_snake_case(&name_str);
// Extract fields with #[index] attribute
let mut indexed_fields = Vec::new();
let mut custom_index_names = std::collections::HashMap::new();
if let Data::Struct(ref mut data_struct) = input.data {
if let Fields::Named(ref mut fields_named) = data_struct.fields {
for field in &mut fields_named.named {
let mut attr_idx = None;
for (i, attr) in field.attrs.iter().enumerate() {
if attr.path().is_ident("index") {
attr_idx = Some(i);
if let Some(ref field_name) = field.ident {
// Check if the attribute has parameters
let mut custom_name = None;
// Parse attribute arguments if any
let meta = attr.meta.clone();
if let syn::Meta::List(list) = meta {
if let Ok(nested) = list.parse_args_with(syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated) {
for meta in nested {
if let syn::Meta::NameValue(name_value) = meta {
if name_value.path.is_ident("name") {
if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit_str), .. }) = name_value.value {
custom_name = Some(lit_str.value());
}
}
}
}
}
}
indexed_fields.push((field_name.clone(), field.ty.clone()));
if let Some(name) = custom_name {
custom_index_names.insert(field_name.to_string(), name);
}
}
}
}
if let Some(idx) = attr_idx {
field.attrs.remove(idx);
}
}
}
}
// Generate Model trait implementation
let db_keys_impl = if indexed_fields.is_empty() {
quote! {
fn db_keys(&self) -> Vec<heromodels_core::IndexKey> {
Vec::new()
}
}
} else {
let field_keys = indexed_fields.iter().map(|(field_name, _)| {
let name_str = custom_index_names
.get(&field_name.to_string())
.cloned()
.unwrap_or(field_name.to_string());
quote! {
heromodels_core::IndexKey {
name: #name_str,
value: self.#field_name.to_string(),
}
}
});
quote! {
fn db_keys(&self) -> Vec<heromodels_core::IndexKey> {
vec![
#(#field_keys),*
]
}
}
};
let model_impl = quote! {
impl heromodels_core::Model for #struct_name {
fn db_prefix() -> &'static str {
#db_prefix
}
fn get_id(&self) -> u32 {
self.base_data.id
}
fn base_data_mut(&mut self) -> &mut heromodels_core::BaseModelData {
&mut self.base_data
}
#db_keys_impl
}
};
// Generate Index trait implementations
let mut index_impls = proc_macro2::TokenStream::new();
for (field_name, field_type) in &indexed_fields {
let name_str = field_name.to_string();
// Get custom index name if specified, otherwise use field name
let index_key = match custom_index_names.get(&name_str) {
Some(custom_name) => custom_name.clone(),
None => name_str.clone(),
};
// Convert field name to PascalCase for struct name
// let struct_name_str = to_pascal_case(&name_str);
// let index_struct_name = format_ident!("{}", struct_name_str);
let index_struct_name = format_ident!("{}", &name_str);
// Default to str for key type
let index_impl = quote! {
pub struct #index_struct_name;
impl heromodels_core::Index for #index_struct_name {
type Model = super::#struct_name;
type Key = #field_type;
fn key() -> &'static str {
#index_key
}
}
};
index_impls.extend(index_impl);
}
if !index_impls.is_empty() {
let index_mod_name = format_ident!("{}_index", db_prefix);
index_impls = quote! {
pub mod #index_mod_name {
#index_impls
}
}
}
// Combine the original struct with the generated implementations
let expanded = quote! {
#input
#model_impl
#index_impls
};
// Return the generated code
expanded.into()
}

View File

@@ -0,0 +1,106 @@
use heromodels_derive::model;
use serde::{Serialize, Deserialize};
// Define the necessary structs and traits for testing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BaseModelData {
pub id: u32,
pub created_at: i64,
pub modified_at: i64,
pub comments: Vec<u32>,
}
impl BaseModelData {
pub fn new(id: u32) -> Self {
let now = 1000; // Mock timestamp
Self {
id,
created_at: now,
modified_at: now,
comments: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexKey {
pub name: &'static str,
pub value: String,
}
pub trait Model: std::fmt::Debug + Clone {
fn db_prefix() -> &'static str;
fn get_id(&self) -> u32;
fn base_data_mut(&mut self) -> &mut BaseModelData;
fn db_keys(&self) -> Vec<IndexKey>;
}
pub trait Index {
type Model: Model;
type Key: ?Sized;
fn key() -> &'static str;
}
// Test struct using the model macro
#[derive(Debug, Clone, Serialize, Deserialize)]
#[model]
struct TestUser {
base_data: BaseModelData,
#[index]
username: String,
#[index]
is_active: bool,
}
// Test struct with custom index name
#[derive(Debug, Clone, Serialize, Deserialize)]
#[model]
struct TestUserWithCustomIndex {
base_data: BaseModelData,
#[index(name = "custom_username")]
username: String,
#[index]
is_active: bool,
}
#[test]
fn test_basic_model() {
assert_eq!(TestUser::db_prefix(), "test_user");
let user = TestUser {
base_data: BaseModelData::new(1),
username: "test".to_string(),
is_active: true,
};
let keys = user.db_keys();
assert_eq!(keys.len(), 2);
assert_eq!(keys[0].name, "username");
assert_eq!(keys[0].value, "test");
assert_eq!(keys[1].name, "is_active");
assert_eq!(keys[1].value, "true");
}
#[test]
fn test_custom_index_name() {
let user = TestUserWithCustomIndex {
base_data: BaseModelData::new(1),
username: "test".to_string(),
is_active: true,
};
// Check that the Username struct uses the custom index name
assert_eq!(Username::key(), "custom_username");
// Check that the db_keys method returns the correct keys
let keys = user.db_keys();
assert_eq!(keys.len(), 2);
assert_eq!(keys[0].name, "custom_username");
assert_eq!(keys[0].value, "test");
assert_eq!(keys[1].name, "is_active");
assert_eq!(keys[1].value, "true");
}