Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .changepacks/changepack_log_schema_macro_round20.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"changes":{"crates/vespera/Cargo.toml":"Patch","crates/vespera_core/Cargo.toml":"Patch","crates/vespera_macro/Cargo.toml":"Patch","crates/vespera_inprocess/Cargo.toml":"Patch","crates/vespera_jni/Cargo.toml":"Patch","libs/vespera-bridge/build.gradle.kts":"Patch","libs/vespera-bridge-gradle-plugin/build.gradle.kts":"Patch"},"note":"vespera_macro schema macros (round 20 fixes): a raw field name shadowing a bare default function is renamed in multipart derives; count_items_named ignores items under a false cfg on fn / impl / trait / const / static; a literal sea_orm default_value on a non-primitive field no longer advertises an OpenAPI default serde does not fill; schema_type! omit_default and the relation shape agree with generate_type; a same-file adapter that is not Schema-derived yields to the stored Schema; a text default with an unspaced parenthesis is a literal; an explicitly imported bare name of an underived item is rejected; super::super paths and const generic arguments are re-rooted; external glob imports supply names the module does not define; raw path keywords are rejected as field names.","date":"2026-11-17T00:00:00.000Z"}
41 changes: 34 additions & 7 deletions crates/vespera_macro/src/multipart_impl/fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,22 +307,27 @@ pub(super) fn shadowed_locals<'a>(
.filter_map(|field| crate::parser::extract_default(&field.attrs).flatten())
.chain(container_fn.map(ToString::to_string))
.filter_map(|path| syn::parse_str::<syn::Ident>(&path).ok())
.map(|ident| ident.to_string())
.map(|ident| crate::parser::strip_raw_prefix_owned(ident.to_string()))
.collect();
// Both sides without the `r#` prefix (S20-0-3, round 20): `r#tags` is the
// same name as the one-segment function `tags`.
fields
.filter_map(|field| field.ident.as_ref().map(ToString::to_string))
.filter_map(|field| {
field
.ident
.as_ref()
.map(|ident| crate::parser::strip_raw_prefix_owned(ident.to_string()))
})
.filter(|name| bare.contains(name))
.collect()
}

/// The derived fn's local holding the field `ident`: the field's own name,
/// unless it is `shadowed` (then `__vespera_local_<name>`).
fn local_ident(ident: &syn::Ident, shadowed: &HashSet<String>) -> syn::Ident {
if shadowed.contains(&ident.to_string()) {
quote::format_ident!(
"__vespera_local_{}",
crate::parser::strip_raw_prefix_owned(ident.to_string())
)
let name = crate::parser::strip_raw_prefix_owned(ident.to_string());
if shadowed.contains(&name) {
quote::format_ident!("__vespera_local_{}", name)
} else {
ident.clone()
}
Expand Down Expand Up @@ -578,4 +583,26 @@ mod tests {
assert!(code.contains("unwrap_or_else (make)"), "{code}");
assert!(!code.contains("self ::"), "{code}");
}

/// S20-0-3 (round 20): a raw identifier that is not a keyword (`r#tags`)
/// is the same name as the bare default function `tags`, so its local is
/// renamed too (the `r#` prefix used to keep it apart: E0618 in the
/// generated derive).
#[test]
fn raw_non_keyword_field_shadows_a_bare_default_fn() {
let input = parse_fields_from(
r#"struct T {
#[serde(default = "tags")] pub other: Vec<String>,
pub r#tags: String,
}"#,
);
let fields = get_named_fields(&input);
let shadowed = shadowed_locals(fields.iter(), None);
assert!(shadowed.contains("tags"), "{shadowed:?}");
let cg = process_fields(fields.iter(), None, false, false, &shadowed);
let (post_loop, idents) = (&cg.post_loop, &cg.idents);
let code = quote::quote!(#(#post_loop)* Self { #(#idents),* }).to_string();
assert!(code.contains("(tags) ()"), "{code}");
assert!(code.contains("__vespera_local_tags"), "{code}");
}
}
31 changes: 31 additions & 0 deletions crates/vespera_macro/src/schema_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,34 @@ fn count_items_named(items: &[syn::Item], ident: &str) -> usize {
syn::visit::visit_item_mod(self, item);
}
}
// Items whose bodies can declare more items (S20-0-2, round 20): a
// `#[cfg]` that is false on the fn / impl / trait / const / static
// hides everything inside it too.
fn visit_item_fn(&mut self, item: &'ast syn::ItemFn) {
if !statically_inactive(&item.attrs) {
syn::visit::visit_item_fn(self, item);
}
}
fn visit_item_impl(&mut self, item: &'ast syn::ItemImpl) {
if !statically_inactive(&item.attrs) {
syn::visit::visit_item_impl(self, item);
}
}
fn visit_item_trait(&mut self, item: &'ast syn::ItemTrait) {
if !statically_inactive(&item.attrs) {
syn::visit::visit_item_trait(self, item);
}
}
fn visit_item_const(&mut self, item: &'ast syn::ItemConst) {
if !statically_inactive(&item.attrs) {
syn::visit::visit_item_const(self, item);
}
}
fn visit_item_static(&mut self, item: &'ast syn::ItemStatic) {
if !statically_inactive(&item.attrs) {
syn::visit::visit_item_static(self, item);
}
}
}
let mut counter = Counter { ident, count: 0 };
for item in items {
Expand Down Expand Up @@ -673,6 +701,9 @@ pub mod variants;
#[path = "schema_impl/tests.rs"]
mod tests;

#[cfg(test)]
mod tests_identity;

#[cfg(test)]
mod tests_wire_override;

Expand Down
124 changes: 1 addition & 123 deletions crates/vespera_macro/src/schema_impl/tests.rs
Original file line number Diff line number Diff line change
@@ -1,127 +1,5 @@
use super::*;

#[test]
fn build_struct_metadata_omits_identity_without_call_site_file() {
let input: syn::DeriveInput = syn::parse_quote! {
struct User { id: i32 }
};

let metadata = build_struct_metadata(&input, "UserSchema".to_string(), None);

assert_eq!(metadata.name, "UserSchema");
assert!(metadata.definition.contains("struct User"));
assert_eq!(metadata.source_identity, None);
}

#[test]
fn build_struct_metadata_attaches_identity_from_call_site_file() {
let input: syn::DeriveInput = syn::parse_quote! {
struct User { id: i32 }
};
let call_site_file = Path::new("some/path.rs");

let metadata = build_struct_metadata(&input, "UserSchema".to_string(), Some(call_site_file));

assert_eq!(metadata.name, "UserSchema");
let identity = metadata.source_identity.expect("identity");
assert!(
identity.starts_with("some/path.rs::User@"),
"identity carries the ident position: {identity}"
);
}

/// Same-named structs in two inline `mod`s of ONE file get distinct
/// identities (span position), so the second registration is rejected as a
/// duplicate instead of silently replacing the first.
#[test]
fn same_named_structs_in_inline_mods_of_one_file_conflict() {
let dir = tempfile::TempDir::new().unwrap();
let file = dir.path().join("models.rs");
let source =
"mod a {\n struct User { id: i32 }\n}\nmod b {\n struct User { name: String }\n}\n";
std::fs::write(&file, source).unwrap();
let parsed: syn::File = syn::parse_str(source).unwrap();
let structs: Vec<syn::DeriveInput> = parsed
.items
.iter()
.filter_map(|item| match item {
syn::Item::Mod(module) => module.content.as_ref().map(|(_, items)| &items[0]),
_ => None,
})
.map(|item| syn::parse2(quote::quote!(#item)).unwrap())
.collect();
let key = "__test_inline_mod_duplicate__".to_string();
remove_current_crate_schema(&key);

let first = build_struct_metadata(&structs[0], key.clone(), Some(&file));
let second = build_struct_metadata(&structs[1], key.clone(), Some(&file));
assert_ne!(first.source_identity, second.source_identity);
assert!(register_schema(key.clone(), first).is_ok());
assert!(
register_schema(key.clone(), second).is_err(),
"two different `User` structs in one file must conflict"
);
remove_current_crate_schema(&key);
}

/// A single item whose position changed (IDE edit) is still a replacement;
/// when the file holds zero (not locatable) or several items of that name,
/// the move is ambiguous and the strict `line:column` identity applies.
#[rstest::rstest]
#[case::single_item("\n\nstruct User { id: i64 }\n", true)]
#[case::not_found("\n\nstruct Other { id: i64 }\n", false)]
#[case::second_in_fn_body("fn f() { struct User; }\nstruct User { id: i64 }\n", false)]
fn moved_item_replacement(#[case] source: &str, #[case] replaced: bool) {
let dir = tempfile::TempDir::new().unwrap();
let file = dir.path().join("models.rs");
std::fs::write(&file, source).unwrap();
let path = file.display();
let key = format!("__test_moved_item_{replaced}_{}__", source.len());
remove_current_crate_schema(&key);

assert!(
register_schema(
key.clone(),
StructMetadata::new(key.clone(), "struct User { id: i32 }".to_string())
.with_source_identity(format!("{path}::User@1:7")),
)
.is_ok()
);
let second = register_schema(
key.clone(),
StructMetadata::new(key.clone(), "struct User { id: i64 }".to_string())
.with_source_identity(format!("{path}::User@3:7")),
);
assert_eq!(second.is_ok(), replaced);
assert_eq!(
current_crate_schemas()[&key].definition.contains("i64"),
replaced
);
remove_current_crate_schema(&key);
}

#[rstest::rstest]
#[case::nested_mods("mod a { struct X; mod b { enum X {} } } struct X;", 3)]
#[case::other_names("struct Y; mod a { struct Z; }", 0)]
#[case::external_mod("mod a; struct X;", 1)]
#[case::fn_body("fn f() { struct X; } struct X;", 2)]
#[case::impl_and_const("impl T { fn g() { enum X {} } } const C: () = { struct X; };", 2)]
#[case::static_and_nested_block("static S: u8 = { if true { struct X; } 0 };", 1)]
// L5 (round 18): a twin (or module) `#[cfg]` rules out is not counted;
// an unknown predicate still is.
#[case::inactive_twin(
"#[cfg(any())] struct X; #[cfg(not(any()))] struct X; #[cfg(unix)] enum X {}",
2
)]
#[case::inactive_module(
"#[cfg(any())] mod a { struct X; } #[cfg(all())] mod b { struct X; }",
1
)]
fn count_items_named_descends_into_nested_items(#[case] source: &str, #[case] expected: usize) {
let parsed: syn::File = syn::parse_str(source).unwrap();
assert_eq!(count_items_named(&parsed.items, "X"), expected);
}

#[test]
fn test_process_derive_schema_struct() {
let input: syn::DeriveInput = syn::parse_quote! {
Expand Down Expand Up @@ -471,7 +349,7 @@ fn test_process_derive_schema_definition_contains_fields() {
// ========== Coverage: SCHEMA_STORAGE direct usage ==========

/// Remove a schema entry from the current crate's bucket (test cleanup).
fn remove_current_crate_schema(key: &str) {
pub(super) fn remove_current_crate_schema(key: &str) {
let mut guard = SCHEMA_STORAGE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
Expand Down
137 changes: 137 additions & 0 deletions crates/vespera_macro/src/schema_impl/tests_identity.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
//! Item identity (`source_identity`) and item-count tests: a move within a
//! file is a replacement, same-named items of one file conflict, and
//! `count_items_named` ignores items a `#[cfg]` rules out.

use super::tests::remove_current_crate_schema;
use super::*;

#[test]
fn build_struct_metadata_omits_identity_without_call_site_file() {
let input: syn::DeriveInput = syn::parse_quote! {
struct User { id: i32 }
};

let metadata = build_struct_metadata(&input, "UserSchema".to_string(), None);

assert_eq!(metadata.name, "UserSchema");
assert!(metadata.definition.contains("struct User"));
assert_eq!(metadata.source_identity, None);
}

#[test]
fn build_struct_metadata_attaches_identity_from_call_site_file() {
let input: syn::DeriveInput = syn::parse_quote! {
struct User { id: i32 }
};
let call_site_file = Path::new("some/path.rs");

let metadata = build_struct_metadata(&input, "UserSchema".to_string(), Some(call_site_file));

assert_eq!(metadata.name, "UserSchema");
let identity = metadata.source_identity.expect("identity");
assert!(
identity.starts_with("some/path.rs::User@"),
"identity carries the ident position: {identity}"
);
}

/// Same-named structs in two inline `mod`s of ONE file get distinct
/// identities (span position), so the second registration is rejected as a
/// duplicate instead of silently replacing the first.
#[test]
fn same_named_structs_in_inline_mods_of_one_file_conflict() {
let dir = tempfile::TempDir::new().unwrap();
let file = dir.path().join("models.rs");
let source =
"mod a {\n struct User { id: i32 }\n}\nmod b {\n struct User { name: String }\n}\n";
std::fs::write(&file, source).unwrap();
let parsed: syn::File = syn::parse_str(source).unwrap();
let structs: Vec<syn::DeriveInput> = parsed
.items
.iter()
.filter_map(|item| match item {
syn::Item::Mod(module) => module.content.as_ref().map(|(_, items)| &items[0]),
_ => None,
})
.map(|item| syn::parse2(quote::quote!(#item)).unwrap())
.collect();
let key = "__test_inline_mod_duplicate__".to_string();
remove_current_crate_schema(&key);

let first = build_struct_metadata(&structs[0], key.clone(), Some(&file));
let second = build_struct_metadata(&structs[1], key.clone(), Some(&file));
assert_ne!(first.source_identity, second.source_identity);
assert!(register_schema(key.clone(), first).is_ok());
assert!(
register_schema(key.clone(), second).is_err(),
"two different `User` structs in one file must conflict"
);
remove_current_crate_schema(&key);
}

/// A single item whose position changed (IDE edit) is still a replacement;
/// when the file holds zero (not locatable) or several items of that name,
/// the move is ambiguous and the strict `line:column` identity applies.
#[rstest::rstest]
#[case::single_item("\n\nstruct User { id: i64 }\n", true)]
#[case::not_found("\n\nstruct Other { id: i64 }\n", false)]
#[case::second_in_fn_body("fn f() { struct User; }\nstruct User { id: i64 }\n", false)]
fn moved_item_replacement(#[case] source: &str, #[case] replaced: bool) {
let dir = tempfile::TempDir::new().unwrap();
let file = dir.path().join("models.rs");
std::fs::write(&file, source).unwrap();
let path = file.display();
let key = format!("__test_moved_item_{replaced}_{}__", source.len());
remove_current_crate_schema(&key);

assert!(
register_schema(
key.clone(),
StructMetadata::new(key.clone(), "struct User { id: i32 }".to_string())
.with_source_identity(format!("{path}::User@1:7")),
)
.is_ok()
);
let second = register_schema(
key.clone(),
StructMetadata::new(key.clone(), "struct User { id: i64 }".to_string())
.with_source_identity(format!("{path}::User@3:7")),
);
assert_eq!(second.is_ok(), replaced);
assert_eq!(
current_crate_schemas()[&key].definition.contains("i64"),
replaced
);
remove_current_crate_schema(&key);
}

#[rstest::rstest]
#[case::nested_mods("mod a { struct X; mod b { enum X {} } } struct X;", 3)]
#[case::other_names("struct Y; mod a { struct Z; }", 0)]
#[case::external_mod("mod a; struct X;", 1)]
#[case::fn_body("fn f() { struct X; } struct X;", 2)]
#[case::impl_and_const("impl T { fn g() { enum X {} } } const C: () = { struct X; };", 2)]
#[case::static_and_nested_block("static S: u8 = { if true { struct X; } 0 };", 1)]
// L5 (round 18): a twin (or module) `#[cfg]` rules out is not counted;
// an unknown predicate still is.
#[case::inactive_twin(
"#[cfg(any())] struct X; #[cfg(not(any()))] struct X; #[cfg(unix)] enum X {}",
2
)]
#[case::inactive_module(
"#[cfg(any())] mod a { struct X; } #[cfg(all())] mod b { struct X; }",
1
)]
// S20-0-2 (round 20): a `#[cfg]` that is false on a fn / impl / trait /
// const / static hides the items declared inside its body too.
// An active trait is walked too (its default method body holds an item).
#[case::active_trait("trait T { fn g() { struct X; } } struct X;", 2)]
#[case::inactive_fn("#[cfg(any())] fn f() { struct X; } struct X;", 1)]
#[case::inactive_impl("#[cfg(any())] impl T { fn g() { enum X {} } } struct X;", 1)]
#[case::inactive_trait("#[cfg(any())] trait T { fn g() { struct X; } } struct X;", 1)]
#[case::inactive_const("#[cfg(any())] const C: () = { struct X; }; struct X;", 1)]
#[case::inactive_static("#[cfg(any())] static S: u8 = { struct X; 0 }; struct X;", 1)]
fn count_items_named_descends_into_nested_items(#[case] source: &str, #[case] expected: usize) {
let parsed: syn::File = syn::parse_str(source).unwrap();
assert_eq!(count_items_named(&parsed.items, "X"), expected);
}
6 changes: 5 additions & 1 deletion crates/vespera_macro/src/schema_macro/defaults.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,12 @@ pub(super) fn generate_sea_orm_default_attrs(
Some(value) if !is_sql_function_default(value) => {
let schema_default_attr = quote! { #[schema(default = #value)] };

// No serde default can be generated for a non-primitive type, so
// the literal is not advertised either: an OpenAPI default for a
// field serde still requires (a missing key is a 422) was a lie
// (R20-L1, round 20).
if !is_parseable_type(original_ty) {
return (quote! {}, schema_default_attr);
return (quote! {}, quote! {});
}

let fn_name = format!("default_{}_{field_name}", unraw(struct_name));
Expand Down
Loading
Loading