feat(macros): enhance Integrable derive with validation and versioning improvements
Some checks failed
ci/woodpecker/pr/server-audit Pipeline failed
ci/woodpecker/pr/server-vet Pipeline failed
ci/woodpecker/pr/server-lint Pipeline was successful
ci/woodpecker/pr/server-test Pipeline was successful

This commit is contained in:
CleverWild
2026-06-30 19:55:28 +02:00
parent 11a2d8c8f3
commit 0779d0db13
19 changed files with 314 additions and 52 deletions

View File

@@ -14,6 +14,7 @@ syn = { version = "2.0", features = ["derive", "fold", "full", "visit-mut"] }
[dev-dependencies]
arbiter-crypto = { path = "../arbiter-crypto" }
trybuild = { version = "1.0", features = ["diff"] }
[lints]
workspace = true

View File

@@ -53,32 +53,16 @@ struct FieldAccess {
fn collect_field_accesses(struct_data: &DataStruct) -> Vec<FieldAccess> {
match &struct_data.fields {
Fields::Named(fields) => {
// Keep deterministic alphabetical order for named fields.
// Do not remove this sort, because it keeps hash output stable regardless of source order.
let mut named_fields = fields
.named
.iter()
.map(|field| {
let name = field
.ident
.as_ref()
.expect("Fields::Named(fields) must have names")
.clone();
(name.to_string(), name)
})
.collect::<Vec<_>>();
named_fields.sort_by(|a, b| a.0.cmp(&b.0));
named_fields
.into_iter()
.map(|(_, name)| FieldAccess {
Fields::Named(fields) => crate::utils::sorted_named_fields(fields)
.into_iter()
.map(|field| {
let name = field.ident.as_ref().unwrap();
FieldAccess {
access: quote! { #name },
span: name.span(),
})
.collect()
}
}
})
.collect(),
Fields::Unnamed(fields) => fields
.unnamed
.iter()

View File

@@ -1,56 +1,128 @@
use crate::utils::INTEGRABLE_TRAIT_PATH;
use proc_macro2::TokenStream;
use quote::quote;
use syn::{DeriveInput, LitInt, LitStr};
use syn::{DeriveInput, LitStr, spanned::Spanned as _};
struct IntegrableAttr {
kind: String,
version: i32,
}
impl IntegrableAttr {
fn from_attrs(attrs: &[syn::Attribute], span: proc_macro2::Span) -> Result<Self, syn::Error> {
fn from_attrs(
attrs: &[syn::Attribute],
ident_span: proc_macro2::Span,
) -> Result<Self, syn::Error> {
let mut kind: Option<String> = None;
let mut version: i32 = 1;
let mut found = false;
for attr in attrs {
if !attr.path().is_ident("integrable") {
continue;
}
if found {
return Err(syn::Error::new(attr.span(), "duplicate #[integrable] attribute"));
}
found = true;
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("kind") {
let lit: LitStr = meta.value()?.parse()?;
kind = Some(lit.value());
} else if meta.path.is_ident("version") {
let lit: LitInt = meta.value()?.parse()?;
version = lit.base10_parse()?;
let v = lit.value();
if v.is_empty() {
return Err(syn::Error::new(lit.span(), "kind must not be empty"));
}
if !is_valid_kind(&v) {
return Err(syn::Error::new(
lit.span(),
"kind must be a valid schema name: start with a letter, contain only [a-zA-Z0-9_]",
));
}
kind = Some(v);
} else {
return Err(meta.error("unknown key; expected `kind` or `version`"));
return Err(meta.error("unknown key; expected `kind`"));
}
Ok(())
})?;
}
let kind = kind.ok_or_else(|| {
syn::Error::new(span, "#[integrable(kind = \"...\")] is required")
syn::Error::new(ident_span, "#[integrable(kind = \"...\")] is required")
})?;
Ok(Self { kind, version })
Ok(Self { kind })
}
}
pub(crate) fn derive(input: &DeriveInput) -> TokenStream {
let integrable_trait = INTEGRABLE_TRAIT_PATH.to_path();
let ident = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
fn is_valid_kind(s: &str) -> bool {
let mut chars = s.chars();
matches!(chars.next(), Some(c) if c.is_ascii_alphabetic())
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
let attr = match IntegrableAttr::from_attrs(&input.attrs, proc_macro2::Span::call_site()) {
fn fnv1a(data: &[u8], mut hash: u32) -> u32 {
const FNV_PRIME: u32 = 16_777_619;
for &b in data {
hash ^= u32::from(b);
hash = hash.wrapping_mul(FNV_PRIME);
}
hash
}
// Hashes field names and types using the same alphabetical sort order as Hashable,
// so that source-level field reordering never changes VERSION.
fn compute_version(fields: &syn::Fields) -> i32 {
const FNV_OFFSET: u32 = 2_166_136_261;
let mut hash = FNV_OFFSET;
match fields {
syn::Fields::Named(named) => {
for field in crate::utils::sorted_named_fields(named) {
let name = field.ident.as_ref().unwrap().to_string();
let ty = &field.ty;
hash = fnv1a(name.as_bytes(), hash);
hash = fnv1a(quote!(#ty).to_string().as_bytes(), hash);
}
}
syn::Fields::Unnamed(unnamed) => {
for (i, field) in unnamed.unnamed.iter().enumerate() {
let ty = &field.ty;
hash = fnv1a(i.to_string().as_bytes(), hash);
hash = fnv1a(quote!(#ty).to_string().as_bytes(), hash);
}
}
syn::Fields::Unit => {}
}
// Clear sign bit to guarantee a positive i32; substitute 0 → 1.
let v = (hash >> 1).cast_signed();
if v == 0 { 1 } else { v }
}
pub(crate) fn derive(input: &DeriveInput) -> TokenStream {
let syn::Data::Struct(ref data) = input.data else {
return syn::Error::new(
input.ident.span(),
"#[derive(Integrable)] is only supported on structs",
)
.to_compile_error();
};
let integrable_trait = INTEGRABLE_TRAIT_PATH.to_path();
let hashable_trait = crate::utils::HASHABLE_TRAIT_PATH.to_path();
let ident = &input.ident;
let mut generics = input.generics.clone();
for type_param in generics.type_params_mut() {
type_param.bounds.push(syn::parse_quote!(#hashable_trait));
}
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let attr = match IntegrableAttr::from_attrs(&input.attrs, input.ident.span()) {
Ok(a) => a,
Err(e) => return e.to_compile_error(),
};
let kind = attr.kind;
let version = attr.version;
let version = compute_version(&data.fields);
quote! {
#[automatically_derived]

View File

@@ -23,3 +23,13 @@ macro_rules! ensure_path {
ensure_path!(::arbiter_crypto::hashing::Hashable as HASHABLE_TRAIT_PATH);
ensure_path!(::arbiter_crypto::hashing::Digest as HMAC_DIGEST_PATH);
ensure_path!(::arbiter_crypto::integrity::Integrable as INTEGRABLE_TRAIT_PATH);
/// Returns named struct fields sorted alphabetically by name.
/// Both `Hashable` and `Integrable` derive macros must iterate fields in the
/// same deterministic order so that source-level reordering never changes
/// either the runtime hash or the compile-time VERSION.
pub(crate) fn sorted_named_fields(fields: &syn::FieldsNamed) -> Vec<&syn::Field> {
let mut v: Vec<&syn::Field> = fields.named.iter().collect();
v.sort_by_key(|f| f.ident.as_ref().unwrap().to_string());
v
}

View File

@@ -6,20 +6,48 @@ struct TestEntity {
value: i32,
}
#[derive(arbiter_macros::Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "other_entity")]
struct OtherEntity {
label: String,
count: u64,
}
#[test]
fn default_version_is_one() {
assert_eq!(<TestEntity as Integrable>::VERSION, 1, "default version must be 1");
fn kind_is_set_correctly() {
assert_eq!(<TestEntity as Integrable>::KIND, "test_entity");
assert_eq!(<OtherEntity as Integrable>::KIND, "other_entity");
}
#[test]
fn version_is_positive() {
const {
assert!(<TestEntity as Integrable>::VERSION > 0);
assert!(<OtherEntity as Integrable>::VERSION > 0);
}
}
#[test]
fn different_field_layouts_produce_different_versions() {
assert_ne!(
<TestEntity as Integrable>::VERSION,
<OtherEntity as Integrable>::VERSION,
);
}
#[derive(arbiter_macros::Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "versioned_entity", version = 3)]
struct VersionedEntity {
data: String,
#[integrable(kind = "generic_entity")]
struct GenericEntity<T> {
inner: T,
}
#[test]
fn explicit_version_attribute() {
assert_eq!(<VersionedEntity as Integrable>::VERSION, 3);
assert_eq!(<VersionedEntity as Integrable>::KIND, "versioned_entity");
fn generic_struct_derives_integrable() {
assert_eq!(
<GenericEntity<TestEntity> as Integrable>::KIND,
"generic_entity"
);
const {
assert!(<GenericEntity<TestEntity> as Integrable>::VERSION > 0);
}
}

View File

@@ -0,0 +1,5 @@
#[test]
fn integrable_compile_fail() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/ui/integrable/*.rs");
}

View File

@@ -0,0 +1,8 @@
#[derive(arbiter_macros::Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "entity_a")]
#[integrable(kind = "entity_b")]
struct DuplicateAttr {
value: i32,
}
fn main() {}

View File

@@ -0,0 +1,5 @@
error: duplicate #[integrable] attribute
--> tests/ui/integrable/duplicate_attr.rs:3:1
|
3 | #[integrable(kind = "entity_b")]
| ^

View File

@@ -0,0 +1,7 @@
#[derive(arbiter_macros::Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "")]
struct EmptyKind {
value: i32,
}
fn main() {}

View File

@@ -0,0 +1,5 @@
error: kind must not be empty
--> tests/ui/integrable/empty_kind.rs:2:21
|
2 | #[integrable(kind = "")]
| ^^

View File

@@ -0,0 +1,8 @@
#[derive(arbiter_macros::Integrable)]
#[integrable(kind = "my_enum")]
enum MyEnum {
A,
B,
}
fn main() {}

View File

@@ -0,0 +1,5 @@
error: #[derive(Integrable)] is only supported on structs
--> tests/ui/integrable/enum_not_supported.rs:3:6
|
3 | enum MyEnum {
| ^^^^^^

View File

@@ -0,0 +1,7 @@
#[derive(arbiter_macros::Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "bad kind!")]
struct InvalidKind {
value: i32,
}
fn main() {}

View File

@@ -0,0 +1,5 @@
error: kind must be a valid schema name: start with a letter, contain only [a-zA-Z0-9_]
--> tests/ui/integrable/invalid_kind.rs:2:21
|
2 | #[integrable(kind = "bad kind!")]
| ^^^^^^^^^^^

View File

@@ -0,0 +1,6 @@
#[derive(arbiter_macros::Hashable, arbiter_macros::Integrable)]
struct MissingAttr {
value: i32,
}
fn main() {}

View File

@@ -0,0 +1,5 @@
error: #[integrable(kind = "...")] is required
--> tests/ui/integrable/missing_attr.rs:2:8
|
2 | struct MissingAttr {
| ^^^^^^^^^^^