From cef4741a0faef70b4eaece897046537dd758b9a3 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 18 Feb 2025 09:10:34 +0100 Subject: [PATCH] A huge work put into a derive macro for field data,types --- Cargo.toml | 2 +- badges/coverage.svg | 2 +- more_fields/Cargo.toml | 9 +++ more_fields/src/lib.rs | 50 ++++++++++++ more_fields_macro/Cargo.toml | 11 +++ more_fields_macro/src/lib.rs | 77 ++++++++++++++++++ weaponry/Cargo.toml | 3 +- weaponry/src/database.rs | 31 ++++---- weaponry/src/export.rs | 4 - weaponry/src/interfaces.rs | 7 +- weaponry/src/lib.rs | 1 - .../equipement_impl_database.rs | 17 ++-- .../weaponry_structs/equipement_scenario.rs | 7 -- .../weaponry_structs/equipement_structs.rs | 78 +++++++------------ .../src/weaponry_structs/equipement_tools.rs | 18 ----- weaponry/src/weaponry_structs/mod.rs | 1 - 16 files changed, 209 insertions(+), 109 deletions(-) create mode 100644 more_fields/Cargo.toml create mode 100644 more_fields/src/lib.rs create mode 100644 more_fields_macro/Cargo.toml create mode 100644 more_fields_macro/src/lib.rs delete mode 100644 weaponry/src/export.rs delete mode 100644 weaponry/src/weaponry_structs/equipement_tools.rs diff --git a/Cargo.toml b/Cargo.toml index e71620f..b294bf4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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", ] diff --git a/badges/coverage.svg b/badges/coverage.svg index 6fdcf57..ea72a13 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 16%test-coverage16% +test-coverage: 19%test-coverage19% diff --git a/more_fields/Cargo.toml b/more_fields/Cargo.toml new file mode 100644 index 0000000..5783c92 --- /dev/null +++ b/more_fields/Cargo.toml @@ -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" + diff --git a/more_fields/src/lib.rs b/more_fields/src/lib.rs new file mode 100644 index 0000000..8e1408c --- /dev/null +++ b/more_fields/src/lib.rs @@ -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); + } +} diff --git a/more_fields_macro/Cargo.toml b/more_fields_macro/Cargo.toml new file mode 100644 index 0000000..aee9a23 --- /dev/null +++ b/more_fields_macro/Cargo.toml @@ -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" diff --git a/more_fields_macro/src/lib.rs b/more_fields_macro/src/lib.rs new file mode 100644 index 0000000..ee2ec15 --- /dev/null +++ b/more_fields_macro/src/lib.rs @@ -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> = + // 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 diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index f76b28e..184e041 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -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" diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 9cd1bd8..bca6039 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -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( conn: &rusqlite::Connection, - fields: &[&str], table_name: &str, ) -> Result, 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::(table_name, None))?; Ok(serde_rusqlite::from_rows::(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( + table_name: &str, + filter: Option<&str>, +) -> String { format!( "SELECT {} FROM {} {};", - fields.join(", "), + T::attributes_map() + .into_iter() + .map(|(k, _v)| k) + .collect::>() + .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", 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", 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::FIELD_NAMES_AS_ARRAY) + .serialize_vec_from_table::("TestStruct") .unwrap(); tear_down(filename, conn.conn); assert_eq!( diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs deleted file mode 100644 index 8b93802..0000000 --- a/weaponry/src/export.rs +++ /dev/null @@ -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 diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index eb02d7b..229aa9d 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -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( + fn serialize_vec_from_table( &self, table: &str, - fields: &[&str], ) -> std::result::Result, FatalEquipementError>; /// Serialize a specified vector of objects of the given type with an additionnal restriction fn serialize_vec_from_table_with_query( &self, table: &str, - fields: &[&str], query: &str, ) -> std::result::Result, FatalEquipementError>; /// Initialize an empty database & table - fn initialize_empty_table(table: &str) -> Result<(), EquipementError>; + fn initialize_empty_table(table: &str) -> Result<(), EquipementError>; } /// Trait implemented by any struct aiming to be a public recipe diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index e78998c..cf331bd 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -7,7 +7,6 @@ mod database; pub mod error; -mod export; pub mod interfaces; mod strategy; pub mod weaponry_structs; diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index efbb39a..a0c7ebc 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -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( + fn serialize_vec_from_table( &self, table: &str, - fields: &[&str], ) -> Result, crate::error::FatalEquipementError> { - Ok(get_data(&self.conn, fields, table)?) + Ok(get_data(&self.conn, table)?) } fn serialize_vec_from_table_with_query( &self, table: &str, - fields: &[&str], query: &str, ) -> Result, crate::error::FatalEquipementError> { + let _ = table; + let _ = query; todo!() } @@ -44,7 +43,13 @@ impl RecipeDatabase for EquipementDatabase { }) } - fn initialize_empty_table(table: &str) -> Result<(), crate::error::EquipementError> { + fn initialize_empty_table( + table: &str, + ) -> Result<(), crate::error::EquipementError> { + // A vector of + let _attr_map = T::attributes_map(); + + let _ = table; todo!() } } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 1869c30..c343129 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -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( &self, table: &str, - fields: &[&str], ) -> std::result::Result, crate::error::FatalEquipementError> { - let _ = fields; let _ = table; unimplemented!() } @@ -35,10 +31,8 @@ impl RecipeDatabase for DatabaseMock { fn serialize_vec_from_table_with_query( &self, table: &str, - fields: &[&str], query: &str, ) -> std::result::Result, FatalEquipementError> { - let _ = fields; let _ = table; let _ = query; unimplemented!() @@ -103,7 +97,6 @@ impl Scenario for CrossRecipeScenario { .database .serialize_vec_from_table_with_query::( "bob", - &InnerEquipementStats::FIELD_NAMES_AS_ARRAY, "WHERE CATEGOTY == 'Bobitty'", ); todo!() diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 581440d..cdaa074 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -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 FilterFunction { /// 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, pub name: Vec, + #[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, + #[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, pub(super) target: Option, pub(super) special: SpecialCategory, + #[INTEGER] pub(super) action_cost: u8, pub(super) reload_cost: Option, + #[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> = 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 { (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); - } } diff --git a/weaponry/src/weaponry_structs/equipement_tools.rs b/weaponry/src/weaponry_structs/equipement_tools.rs deleted file mode 100644 index fe2c698..0000000 --- a/weaponry/src/weaponry_structs/equipement_tools.rs +++ /dev/null @@ -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 diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 7208fd6..dfdbad8 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -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