A huge work put into a derive macro for field data,types

This commit is contained in:
Dandaedre 2025-02-18 09:10:34 +01:00
parent d4723e828e
commit cef4741a0f
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
16 changed files with 209 additions and 109 deletions

View File

@ -1,7 +1,7 @@
# cargo-features = ["edition2024"]
[workspace]
members = [ "cli_parser", "config", "graphs", "make",
members = [ "cli_parser", "config", "graphs", "make", "more_fields", "more_fields_macro",
"ravenous-tools", "stats",
"tablegen", "weaponry",
]

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 16%"><title>test-coverage: 16%</title><linearGradient id="bms-e68af986cf1a8ea6" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-e68af986cf1a8ea6"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-e68af986cf1a8ea6)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#e05d44"/><rect width="122" height="18" fill="url(#bms-e68af986cf1a8ea6)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">16%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">16%</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 19%"><title>test-coverage: 19%</title><linearGradient id="bms-c9b3e75d692af7ab" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-c9b3e75d692af7ab"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-c9b3e75d692af7ab)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#e05d44"/><rect width="122" height="18" fill="url(#bms-c9b3e75d692af7ab)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">19%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">19%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

9
more_fields/Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
[package]
name = "more_fields"
edition = "2024"
version.workspace = true
[dependencies]
more_fields_macro = {path ="../more_fields_macro"}
pretty_assertions = "1.4.1"

50
more_fields/src/lib.rs Normal file
View File

@ -0,0 +1,50 @@
// Workspace: more_fields
// File: more_fields/src/lib.rs
//! Get all the fields as a Vec<("attribute", "type")>
//! Note that this map is implemented without self, allowing us to use it only as a generic,
//! however this limitation is completely artificial
pub use more_fields_macro::FieldsAsMap;
pub trait FieldsAsMap {
fn attributes_map() -> Vec<(&'static str, &'static str)>;
}
// fn iter(&self) -> std::vec::IntoIter<(&'static str, &'static str)>;
#[cfg(test)]
mod test {
use crate::FieldsAsMap;
use pretty_assertions::assert_eq;
#[allow(dead_code)]
#[derive(FieldsAsMap, Default)]
struct Bob {
#[TEXT]
field_ouane: u16,
#[INTEGER]
field_2: u16,
#[BLOB]
field_3: u16,
#[NULL]
field_4: u16,
#[REAL]
field_5: u16,
field_6: u16,
}
#[test]
fn test_derive_impl() {
println!("{:?}", Bob::attributes_map());
// assert!(
let b_hash = vec![
("field_ouane", "TEXT"),
("field_2", "INTEGER"),
("field_3", "BLOB"),
("field_4", "NULL"),
("field_5", "REAL"),
("field_6", "TEXT"),
];
assert_eq!(Bob::attributes_map(), b_hash);
}
}

View File

@ -0,0 +1,11 @@
[package]
name = "more_fields_macro"
edition = "2024"
version.workspace = true
[lib]
proc-macro = true
[dependencies]
quote = "1.0.38"
syn = "2.0.98"

View File

@ -0,0 +1,77 @@
// Workspace: more_fields_macro
// File: more_fields_macro/src/lib.rs
//! A very simple proc macro in chage of giving a field iterator over ("name","sql_type")
//! This macro is a fork of the excellent work of : https://crates.io/crates/struct_iterable
//!
//! Other ressources include:
//! - https://github.com/rust-lang/reference/blob/master/src/procedural-macros.md#attribute-macros
//! - https://docs.rs/syn/latest/syn/struct.Attribute.html
//! - https://docs.rs/syn/latest/syn/struct.Attribute.html#parsing-from-tokens-to-attribute
//! - https://docs.rs/syn/latest/syn/struct.Ident.html
//!
// use proc_macro::TokenStream;
// use quote::quote;
// use syn::{Data, DeriveInput, Fields, parse_macro_input};
extern crate proc_macro;
use proc_macro::{Span, TokenStream};
use quote::quote;
use syn::DeriveInput;
use syn::parse_macro_input;
use syn::{Data, Fields};
#[proc_macro_derive(FieldsAsMap, attributes(INTEGER, NULL, REAL, TEXT, BLOB))]
pub fn derive_iterable(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let struct_name = input.ident;
let fields = match input.data {
Data::Struct(data_struct) => {
// let list_attrs = input.attrs.iter().map(|v| v.path());
match data_struct.fields {
Fields::Named(fields_named) => fields_named.named,
_ => panic!("Only structs with named fields are supported"),
}
}
_ => panic!("Only structs are supported"),
};
let fields_iter = fields.iter().map(|field| {
let field_ident = &field.ident;
let val = field
.attrs
.iter()
.map(|v| v.path().get_ident())
.next()
.flatten()
.cloned()
.unwrap_or_else(|| syn::Ident::new("TEXT", Span::call_site().into()))
.to_string();
let field_name = field_ident.as_ref().unwrap().to_string();
quote! {
(#field_name, #val)
}
});
// static STATIC_FIELDS_OF_STRUCT_#struct_name: std::sync::LazyLock<Vec<(&'static str, &'static str)>> =
// std::sync::LazyLock::new(|| vec![]);
// const FIELD_NAMES_AS_SLICE: &'static [&'static str] = &[#(#fields_iter),*];
// and add Self::FIELD_NAMES_AS_SLICE
let expanded = quote! {
impl FieldsAsMap for #struct_name {
fn attributes_map<'a>() -> Vec<(&'static str, &'static str)> {
vec![
#(#fields_iter),*
]
}
}
};
TokenStream::from(expanded)
}
// As an hashmap (incorrect as of no ordering)
// let mut h = std::collections::HashMap::new();
// #(h.insert(#fields_iter);)*
// h

View File

@ -4,17 +4,16 @@ version = "0.1.0"
edition = "2024"
[dependencies]
more_fields = {path ="../more_fields"}
comfy-table = "7.1.4"
csv = "1.3.1"
fastrand = "2.3.0"
pretty_assertions = "1.4.1"
probability = "0.20.3"
# rayon = "1.10.0"
rusqlite = { version = "0.33.0", features = ["bundled"] }
serde = { version = "1.0.217", features = ["derive"] }
serde_rusqlite = "0.37.0"
serde_json = { version = "1.0.138", features = ["alloc"] }
struct-field-names-as-array = "0.3.0"
strum = { version = "0.27.0", features = ["derive"] }
thiserror = "2.0.11"

View File

@ -3,6 +3,7 @@
//! Database handiling module
//! Implements the basics deserialisation from a database to the weaponry components
//! Should dump whole database in a vec of structs from weaponry_structs
#![allow(dead_code)]
use rusqlite::{self};
use serde::de::DeserializeOwned;
use std::collections::HashMap;
@ -10,13 +11,12 @@ use std::collections::HashMap;
/// Public function to get data from db. Returns the result as a vec with structs
pub fn get_data<T>(
conn: &rusqlite::Connection,
fields: &[&str],
table_name: &str,
) -> Result<Vec<T>, serde_rusqlite::Error>
where
T: DeserializeOwned,
T: DeserializeOwned + more_fields::FieldsAsMap,
{
let mut query_result = conn.prepare(&generate_select_query(fields, table_name, None))?;
let mut query_result = conn.prepare(&generate_select_query::<T>(table_name, None))?;
Ok(serde_rusqlite::from_rows::<T>(query_result.query([])?)
.filter_map(|s| s.ok())
.collect())
@ -25,10 +25,17 @@ where
/// Generate a SELECT query with fields generated from a struct. Returns a String
/// filter MUST contain "WHERE" else the query will fail
#[inline]
fn generate_select_query(fields: &[&str], table_name: &str, filter: Option<&str>) -> String {
fn generate_select_query<T: more_fields::FieldsAsMap>(
table_name: &str,
filter: Option<&str>,
) -> String {
format!(
"SELECT {} FROM {} {};",
fields.join(", "),
T::attributes_map()
.into_iter()
.map(|(k, _v)| k)
.collect::<Vec<_>>()
.join(", "),
table_name,
filter.unwrap_or("")
)
@ -54,11 +61,11 @@ mod test {
use crate::{
interfaces::RecipeDatabase, weaponry_structs::equipement_impl_database::EquipementDatabase,
};
use more_fields::FieldsAsMap;
use pretty_assertions::assert_eq;
use serde::Deserialize;
use struct_field_names_as_array::FieldNamesAsArray;
#[derive(FieldNamesAsArray, Deserialize, Debug, PartialEq)]
#[derive(FieldsAsMap, Deserialize, Debug, PartialEq)]
struct TestStruct {
id: usize,
name: String,
@ -85,15 +92,11 @@ mod test {
#[test]
fn test_generate_query() {
assert_eq!(
generate_select_query(&TestStruct::FIELD_NAMES_AS_ARRAY, "TestStruct", None),
generate_select_query::<TestStruct>("TestStruct", None),
"SELECT id, name FROM TestStruct ;"
);
assert_eq!(
generate_select_query(
&TestStruct::FIELD_NAMES_AS_ARRAY,
"TestStruct",
Some("WHERE id=id")
),
generate_select_query::<TestStruct>("TestStruct", Some("WHERE id=id")),
"SELECT id, name FROM TestStruct WHERE id=id;"
);
}
@ -103,7 +106,7 @@ mod test {
let filename = "test.db";
let conn = mock_set_up(filename);
let result = conn
.serialize_vec_from_table::<TestStruct>("TestStruct", &TestStruct::FIELD_NAMES_AS_ARRAY)
.serialize_vec_from_table::<TestStruct>("TestStruct")
.unwrap();
tear_down(filename, conn.conn);
assert_eq!(

View File

@ -1,4 +0,0 @@
// Workspace: weaponry
// File: weaponry/src/export.rs
//! Export module in charge of transforming data structure into their tex counterpart through the appropriate traits
// TODO: Consider deletion

View File

@ -7,6 +7,7 @@
use std::{path::Path, rc::Rc};
use more_fields::FieldsAsMap;
use serde::de::DeserializeOwned;
use crate::error::{EquipementError, FatalEquipementError};
@ -164,22 +165,20 @@ pub trait RecipeDatabase {
Self: std::marker::Sized;
/// Serialize a vector of objects of the given type in the specified table of the underlying database
fn serialize_vec_from_table<T: DeserializeOwned>(
fn serialize_vec_from_table<T: DeserializeOwned + more_fields::FieldsAsMap>(
&self,
table: &str,
fields: &[&str],
) -> std::result::Result<Vec<T>, FatalEquipementError>;
/// Serialize a specified vector of objects of the given type with an additionnal restriction
fn serialize_vec_from_table_with_query<T: DeserializeOwned>(
&self,
table: &str,
fields: &[&str],
query: &str,
) -> std::result::Result<Vec<T>, FatalEquipementError>;
/// Initialize an empty database & table
fn initialize_empty_table<T>(table: &str) -> Result<(), EquipementError>;
fn initialize_empty_table<T: FieldsAsMap>(table: &str) -> Result<(), EquipementError>;
}
/// Trait implemented by any struct aiming to be a public recipe

View File

@ -7,7 +7,6 @@
mod database;
pub mod error;
mod export;
pub mod interfaces;
mod strategy;
pub mod weaponry_structs;

View File

@ -6,7 +6,6 @@
// use super::equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape};
// TODO: Migrate from database to here
use crate::database::get_data;
use crate::error::FatalEquipementError;
use crate::interfaces::RecipeDatabase;
@ -20,20 +19,20 @@ pub struct EquipementDatabase {
}
impl RecipeDatabase for EquipementDatabase {
fn serialize_vec_from_table<T: DeserializeOwned>(
fn serialize_vec_from_table<T: DeserializeOwned + more_fields::FieldsAsMap>(
&self,
table: &str,
fields: &[&str],
) -> Result<Vec<T>, crate::error::FatalEquipementError> {
Ok(get_data(&self.conn, fields, table)?)
Ok(get_data(&self.conn, table)?)
}
fn serialize_vec_from_table_with_query<T: DeserializeOwned>(
&self,
table: &str,
fields: &[&str],
query: &str,
) -> Result<Vec<T>, crate::error::FatalEquipementError> {
let _ = table;
let _ = query;
todo!()
}
@ -44,7 +43,13 @@ impl RecipeDatabase for EquipementDatabase {
})
}
fn initialize_empty_table<T>(table: &str) -> Result<(), crate::error::EquipementError> {
fn initialize_empty_table<T: more_fields::FieldsAsMap>(
table: &str,
) -> Result<(), crate::error::EquipementError> {
// A vector of <attribute, type>
let _attr_map = T::attributes_map();
let _ = table;
todo!()
}
}

View File

@ -9,8 +9,6 @@
#![allow(dead_code)]
use struct_field_names_as_array::FieldNamesAsArray;
use crate::{
error::{EquipementError, FatalEquipementError},
interfaces::{RecipeDatabase, Scenario, ViewTable},
@ -25,9 +23,7 @@ impl RecipeDatabase for DatabaseMock {
fn serialize_vec_from_table<T>(
&self,
table: &str,
fields: &[&str],
) -> std::result::Result<Vec<T>, crate::error::FatalEquipementError> {
let _ = fields;
let _ = table;
unimplemented!()
}
@ -35,10 +31,8 @@ impl RecipeDatabase for DatabaseMock {
fn serialize_vec_from_table_with_query<T>(
&self,
table: &str,
fields: &[&str],
query: &str,
) -> std::result::Result<Vec<T>, FatalEquipementError> {
let _ = fields;
let _ = table;
let _ = query;
unimplemented!()
@ -103,7 +97,6 @@ impl Scenario for CrossRecipeScenario {
.database
.serialize_vec_from_table_with_query::<InnerEquipementStats>(
"bob",
&InnerEquipementStats::FIELD_NAMES_AS_ARRAY,
"WHERE CATEGOTY == 'Bobitty'",
);
todo!()

View File

@ -2,12 +2,11 @@
// File: weaponry/src/weaponry_structs/equipement_structs.rs
//! Base equipement structures
use std::{collections::HashMap, rc::Rc, sync::LazyLock};
use serde::{Deserialize, Serialize};
use struct_field_names_as_array::FieldNamesAsArray;
use std::rc::Rc;
use crate::interfaces::{FilterFunction, FilterFunctionType};
use more_fields::FieldsAsMap;
use serde::{Deserialize, Serialize};
use super::{DamageType, SpecialCategory, WeaponCategory};
@ -56,77 +55,65 @@ impl<T> FilterFunction<T> {
/// The inner statistics of the equipement, used across all parts and final weapon
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone, Default, FieldNamesAsArray, Debug, Deserialize, Serialize)]
#[derive(Clone, Default, FieldsAsMap, Debug, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
pub struct InnerEquipementStats {
#[INTEGER]
pub id: Vec<u8>,
pub name: Vec<String>,
#[INTEGER]
pub(super) rarity: u8,
#[INTEGER]
pub(super) cost: u8,
#[INTEGER]
pub(super) difficulty: u8,
#[INTEGER]
pub(super) tier: u8,
#[INTEGER]
pub(super) damage: u8,
#[INTEGER]
pub(super) p_damage: u8,
#[INTEGER]
pub(super) precision: i8,
#[INTEGER]
pub(super) rmax: u8,
#[INTEGER]
pub(super) armor_break: u8,
#[INTEGER]
pub(super) armor_pierce: u8,
#[INTEGER]
pub(super) antimaterial: u8,
pub(super) damage_type: Option<DamageType>,
#[INTEGER]
pub(super) protection: u8,
#[INTEGER]
pub(super) integrity: u8,
#[INTEGER]
pub(super) torque_two_handed: u8,
#[INTEGER]
pub(super) torque_one_handed: u8,
#[INTEGER]
pub(super) dodge: u8,
#[INTEGER]
pub(super) parry: u8,
#[INTEGER]
pub(super) speed: u8,
#[INTEGER]
pub(super) stealth: u8,
pub(super) category: Option<WeaponCategory>,
pub(super) target: Option<WeaponCategory>,
pub(super) special: SpecialCategory,
#[INTEGER]
pub(super) action_cost: u8,
pub(super) reload_cost: Option<u8>,
#[INTEGER]
pub(super) range: u8,
#[INTEGER]
pub(super) agility_bonus: u8,
}
#[allow(dead_code)]
/// A manually implemented hashmap of all values
// TODO: ADD A PROC MACRO TO AUTO_DERIVE THIS
static INNER_EQ_HASHMAP: LazyLock<HashMap<String, String>> = LazyLock::new(|| {
HashMap::from([
("id".to_string(), "INTEGER UNIQUE".to_string()),
("name".to_string(), "TEXT".to_string()),
("rarity".to_string(), "INTEGER".to_string()),
("cost".to_string(), "INTEGER".to_string()),
("difficulty".to_string(), "INTEGER".to_string()),
("tier".to_string(), "INTEGER".to_string()),
("damage".to_string(), "INTEGER".to_string()),
("p_damage".to_string(), "INTEGER".to_string()),
("precision".to_string(), "INTEGER".to_string()),
("rmax".to_string(), "INTEGER".to_string()),
("armor_break".to_string(), "INTEGER".to_string()),
("armor_pierce".to_string(), "INTEGER".to_string()),
("antimaterial".to_string(), "INTEGER".to_string()),
("damage_type".to_string(), "INTEGER".to_string()),
("protection".to_string(), "INTEGER".to_string()),
("integrity".to_string(), "INTEGER".to_string()),
("torque_two_handed".to_string(), "INTEGER".to_string()),
("torque_one_handed".to_string(), "INTEGER".to_string()),
("dodge".to_string(), "INTEGER".to_string()),
("parry".to_string(), "INTEGER".to_string()),
("speed".to_string(), "INTEGER".to_string()),
("stealth".to_string(), "INTEGER".to_string()),
("category".to_string(), "TEXT".to_string()),
("target".to_string(), "INTEGER".to_string()),
("special".to_string(), "TEXT".to_string()),
("action_cost".to_string(), "INTEGER".to_string()),
("reload_cost".to_string(), "INTEGER".to_string()),
("range".to_string(), "INTEGER".to_string()),
("agility_bonus".to_string(), "INTEGER".to_string()),
])
});
#[doc(hidden)]
macro_rules! r {
() => {
@ -184,9 +171,7 @@ mod test {
EqFinishing, EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList,
InnerEquipementStats,
};
use crate::{
interfaces::RecipeCollection, weaponry_structs::equipement_structs::INNER_EQ_HASHMAP,
};
use crate::interfaces::RecipeCollection;
fn list_equip() -> Vec<Equipement> {
(0..10)
@ -224,11 +209,4 @@ mod test {
fn test_default_behaviour() {
unimplemented!()
}
#[test]
fn test_const_fields() {
let c = &INNER_EQ_HASHMAP;
assert!(!c.keys().len() > 0);
assert!(!c.values().len() > 0);
}
}

View File

@ -1,18 +0,0 @@
// Workspace: weaponry
// File: weaponry/src/weaponry_structs/equipement_tools.rs
//! Tools user facing, implement all that a end user would need
//!
//! This file implements all the functions the main runner will eventually launch
#![allow(dead_code)]
/// Tooling utility
fn load_database() {}
/// Export the data generated to tex
fn export_to_tex() {}
/// Export the data generated to csv
fn export_to_csv() {}
// TODO: Consider deletion

View File

@ -25,7 +25,6 @@ mod equipement_impl_logic;
mod equipement_impl_math;
mod equipement_scenario;
pub mod equipement_structs;
pub mod equipement_tools;
mod equipement_views;
// Republishes the most used symbols