diff --git a/.changepacks/changepack_log_schema_macro_round20.json b/.changepacks/changepack_log_schema_macro_round20.json new file mode 100644 index 00000000..2f2e2ec1 --- /dev/null +++ b/.changepacks/changepack_log_schema_macro_round20.json @@ -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"} diff --git a/crates/vespera_macro/src/multipart_impl/fields.rs b/crates/vespera_macro/src/multipart_impl/fields.rs index ab34aa59..ce0e43a3 100644 --- a/crates/vespera_macro/src/multipart_impl/fields.rs +++ b/crates/vespera_macro/src/multipart_impl/fields.rs @@ -307,10 +307,17 @@ 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::(&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() } @@ -318,11 +325,9 @@ pub(super) fn shadowed_locals<'a>( /// The derived fn's local holding the field `ident`: the field's own name, /// unless it is `shadowed` (then `__vespera_local_`). fn local_ident(ident: &syn::Ident, shadowed: &HashSet) -> 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() } @@ -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, + 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}"); + } } diff --git a/crates/vespera_macro/src/schema_impl.rs b/crates/vespera_macro/src/schema_impl.rs index 82ab5af0..2c4d5251 100644 --- a/crates/vespera_macro/src/schema_impl.rs +++ b/crates/vespera_macro/src/schema_impl.rs @@ -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 { @@ -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; diff --git a/crates/vespera_macro/src/schema_impl/tests.rs b/crates/vespera_macro/src/schema_impl/tests.rs index e3c6538c..f5c2b208 100644 --- a/crates/vespera_macro/src/schema_impl/tests.rs +++ b/crates/vespera_macro/src/schema_impl/tests.rs @@ -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 = 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! { @@ -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); diff --git a/crates/vespera_macro/src/schema_impl/tests_identity.rs b/crates/vespera_macro/src/schema_impl/tests_identity.rs new file mode 100644 index 00000000..0542ec19 --- /dev/null +++ b/crates/vespera_macro/src/schema_impl/tests_identity.rs @@ -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 = 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); +} diff --git a/crates/vespera_macro/src/schema_macro/defaults.rs b/crates/vespera_macro/src/schema_macro/defaults.rs index a9f2a6f0..07d487c0 100644 --- a/crates/vespera_macro/src/schema_macro/defaults.rs +++ b/crates/vespera_macro/src/schema_macro/defaults.rs @@ -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)); diff --git a/crates/vespera_macro/src/schema_macro/defaults/tests.rs b/crates/vespera_macro/src/schema_macro/defaults/tests.rs index 8fbdab2e..f0e98b1c 100644 --- a/crates/vespera_macro/src/schema_macro/defaults/tests.rs +++ b/crates/vespera_macro/src/schema_macro/defaults/tests.rs @@ -135,10 +135,11 @@ fn test_sea_orm_default_attrs_primary_key_generates_defaults() { serde_str.contains("serde"), "primary_key should generate serde default: {serde_str}" ); - let schema_str = schema.to_string(); - assert!( - schema_str.contains('0'), - "primary_key i32 should have schema default 0: {schema_str}" + // Exact: `contains('0')` also passed for "10" or "0.0" (R20-L2, round 20). + assert_eq!( + schema.to_string(), + "# [schema (default = \"0\")]", + "primary_key i32 should have schema default 0" ); assert_eq!(fns.len(), 1, "should generate a default function"); } @@ -245,14 +246,11 @@ fn test_sea_orm_default_attrs_non_parseable_type() { 1, &mut fns, ); - // serde attr empty (non-parseable type) + // No serde default for a non-primitive type, so no schema default either: + // the OpenAPI document must not promise a value serde never fills (R20-L1, + // round 20; before the fix the schema attribute was emitted here). assert!(serde.is_empty()); - // schema attr still generated - let schema_str = schema.to_string(); - assert!( - schema_str.contains("schema"), - "should have schema attr: {schema_str}" - ); + assert!(schema.is_empty(), "no advertised default: {schema}"); assert!(fns.is_empty()); } @@ -956,3 +954,28 @@ fn pointer_sized_defaults_are_checked_at_the_target_width( None => assert!(guard.is_empty(), "{guard}"), } } + +/// R20-SM3-02 (round 20): a text default with an unspaced parenthesis is a +/// literal, so the schema default and the serde default carry the text (it +/// used to be classified as a SQL call: the schema default became `""`). +#[test] +fn unspaced_parenthesised_text_default_is_a_literal() { + let attrs: Vec = + vec![syn::parse_quote!(#[sea_orm(default_value = "Draft(WIP)")])]; + let struct_name = syn::Ident::new("Test", proc_macro2::Span::call_site()); + let ty: syn::Type = syn::parse_str("String").unwrap(); + let mut fns = Vec::new(); + let (serde, schema) = generate_sea_orm_default_attrs( + &attrs, + &struct_name, + "status", + &ty, + &ty, + false, + 1, + &mut fns, + ); + assert_eq!(schema.to_string(), "# [schema (default = \"Draft(WIP)\")]"); + assert!(serde.to_string().contains("default_Test_status"), "{serde}"); + assert_eq!(fns.len(), 1); +} diff --git a/crates/vespera_macro/src/schema_macro/from_model/target_shape.rs b/crates/vespera_macro/src/schema_macro/from_model/target_shape.rs index d9d9b83a..da329ef4 100644 --- a/crates/vespera_macro/src/schema_macro/from_model/target_shape.rs +++ b/crates/vespera_macro/src/schema_macro/from_model/target_shape.rs @@ -4,7 +4,9 @@ use crate::schema_macro::generate_type::readable_from; use crate::schema_macro::input::SchemaTypeInput; -use crate::schema_macro::seaorm::has_sea_orm_database_default; +use crate::schema_macro::seaorm::{ + has_sea_orm_database_default, has_sea_orm_primary_key, primary_key_count, +}; use crate::schema_macro::transformation::{build_omit_set, build_pick_set, should_skip_field}; use crate::schema_macro::type_utils::{SeaOrmRelationKind, is_seaorm_model, seaorm_relation_kind}; @@ -94,6 +96,13 @@ fn compute_target_shape( // only when `pick`ed; every other kept field must be readable from the // module the DTO is emitted in (a private field of another module makes // `generate_type` leave both impls out). + // `omit_default` drops a primary key too (`generate_type`'s rule, through + // `has_sea_orm_primary_key` with the model's key count): the same predicate + // here, or a private dropped key made the shape `Neither` (R20-SM2-01). + let pk_count = match &model.fields { + syn::Fields::Named(named) => primary_key_count(named), + _ => 0, + }; let mut has_relation = false; let mut all_readable = true; for field in &model.fields { @@ -103,15 +112,18 @@ fn compute_target_shape( .map(|ident| crate::parser::strip_raw_prefix_owned(ident.to_string())) .unwrap_or_default(); if should_skip_field(&name, &omit, &pick) - || (input.omit_default && has_sea_orm_database_default(&field.attrs)) + || (input.omit_default + && (has_sea_orm_database_default(&field.attrs) + || has_sea_orm_primary_key(&field.attrs, &field.ty, pk_count))) { continue; } match seaorm_relation_kind(&field.ty) { - Some(kind) if kind != SeaOrmRelationKind::HasMany || pick.contains(&name) => { - has_relation = true; - } - _ => { + // An un-picked HasMany is dropped by `generate_type` before its + // readability is looked at. + Some(SeaOrmRelationKind::HasMany) if !pick.contains(&name) => {} + Some(_) => has_relation = true, + None => { all_readable &= readable_from(&field.vis, &source_module, Some(module)); } } @@ -180,7 +192,7 @@ mod tests { /// A crate whose `models::user` generates `Schema` from `source`, with a /// `legacy::Model` written as `legacy`. - fn write_crate(dir: &std::path::Path, legacy: &str, source: &str) { + fn write_crate(dir: &std::path::Path, legacy: &str, source: &str, args: &str) { let files = [ ( "src/lib.rs", @@ -190,7 +202,7 @@ mod tests { ("src/models.rs", "pub mod user;\n".to_string()), ( "src/models/user.rs", - format!("vespera::schema_type!(Schema from {source});\n{USER_MODEL}\n"), + format!("vespera::schema_type!(Schema from {source}{args});\n{USER_MODEL}\n"), ), ]; for (path, content) in files { @@ -221,13 +233,37 @@ mod tests { "Model", TargetShape::FromModel )] + // R20-SM2-01 (round 20): fields `generate_type` drops are not counted. + // An un-picked HasMany (private, so unreadable here) is dropped ... + #[case::unpicked_private_has_many( + "pub struct Model { pub id: i32, memos: HasMany }", + "crate::legacy::Model", + TargetShape::From + )] + // A tuple struct has no named fields to count keys of (`pk_count` is 0). + #[case::tuple_struct_source( + "pub struct Model(pub i32);", + "crate::legacy::Model", + TargetShape::From + )] + // ... and so is an `omit_default` primary key (private, so unreadable). + #[case::omit_default_private_primary_key( + "pub struct Model { #[sea_orm(primary_key)] id: i32, pub name: String }", + "crate::legacy::Model", + TargetShape::From + )] fn shape_follows_the_schema_type_source( #[case] legacy: &str, #[case] source: &str, #[case] expected: TargetShape, ) { + let args = if legacy.contains("primary_key") { + ", omit_default" + } else { + "" + }; let dir = tempfile::TempDir::new().unwrap(); - write_crate(dir.path(), legacy, source); + write_crate(dir.path(), legacy, source, args); let _manifest = crate::env_access::test_env::set_var("CARGO_MANIFEST_DIR", dir.path()); let module: Vec = ["crate", "models", "user"].map(String::from).to_vec(); assert_eq!( diff --git a/crates/vespera_macro/src/schema_macro/inline_types/tests.rs b/crates/vespera_macro/src/schema_macro/inline_types/tests.rs index 94a8f429..7dbe7d2f 100644 --- a/crates/vespera_macro/src/schema_macro/inline_types/tests.rs +++ b/crates/vespera_macro/src/schema_macro/inline_types/tests.rs @@ -165,17 +165,6 @@ fn generate_inline_type_definition_snapshot( ); } -#[test] -fn inline_field_struct_holds_constructor_inputs() { - let field = field( - "test_field", - quote!(Option), - vec![syn::parse_quote!(#[doc = "Test doc"])], - ); - assert_eq!(field.name.to_string(), "test_field"); - assert_eq!(field.attrs.len(), 1); -} - #[test] fn inline_relation_type_struct_holds_constructor_inputs() { let inline_type = inline("TestRelation", "SCREAMING_SNAKE_CASE", vec![]); diff --git a/crates/vespera_macro/src/schema_macro/mod.rs b/crates/vespera_macro/src/schema_macro/mod.rs index 90eb247a..859e9c9d 100644 --- a/crates/vespera_macro/src/schema_macro/mod.rs +++ b/crates/vespera_macro/src/schema_macro/mod.rs @@ -20,6 +20,8 @@ mod inline_types; mod input; mod instantiate; pub mod module_scope; +#[cfg(test)] +mod requested_variant_tests; mod same_file_override; mod seaorm; mod transformation; @@ -95,8 +97,12 @@ fn requested_variant( } let defined_in = storage_module_path(stored); let other_crate = module.first().map(String::as_str) != Some("crate"); + // A bare name the call site imports explicitly (`use crate::a::Page;`) is + // named as much as a qualified path is: the stored `Page` of another + // module is not it (R20-SM3-03, round 20). A glob import stays lenient. + let named_module = qualified || explicitly_imported(&name); if other_crate - || (qualified + || (named_module && defined_in .as_ref() .is_some_and(|defined| *defined != module)) @@ -134,6 +140,14 @@ fn bare_name_module(ty: &syn::Type) -> Option> { Some(reexported_item(&path, &defined).map_or(path, |(defined_in, _)| defined_in)) } +/// Whether the call site's module imports `name` with an explicit `use` +/// (glob imports are not in `ModuleScope::imports`). +fn explicitly_imported(name: &str) -> bool { + file_lookup::call_site_module() + .and_then(|call_site| module_scope::module_scope(&call_site)) + .is_some_and(|scope| scope.imports.contains_key(name)) +} + /// Generate schema code from a struct with optional field filtering pub fn generate_schema_code( input: &SchemaInput, diff --git a/crates/vespera_macro/src/schema_macro/requested_variant_tests.rs b/crates/vespera_macro/src/schema_macro/requested_variant_tests.rs new file mode 100644 index 00000000..050a42c0 --- /dev/null +++ b/crates/vespera_macro/src/schema_macro/requested_variant_tests.rs @@ -0,0 +1,40 @@ +//! `requested_variant` (R20-SM3-03, round 20): a bare name the call site +//! imports explicitly names that import's module; a glob import does not. + +use super::*; +use crate::metadata::StructMetadata; + +/// A crate with `a::Page` (no `#[derive(Schema)]`), `b::Page` (the stored, +/// derived one) and `routes` holding `routes_source` as its only `use`. +fn write_crate(dir: &std::path::Path, routes_source: &str) -> String { + let files = [ + ("src/lib.rs", "pub mod a;\npub mod b;\npub mod routes;\n"), + ("src/a.rs", "pub struct Page { pub x: i32 }\n"), + ("src/b.rs", "pub struct Page { pub y: i32 }\n"), + ("src/routes.rs", routes_source), + ]; + for (path, content) in files { + let path = dir.join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, content).unwrap(); + } + dir.join("src/b.rs").display().to_string() +} + +#[rstest::rstest] +#[case::explicit_import_of_an_underived_item("use crate::a::Page;\n", true)] +#[case::glob_import_stays_lenient("use crate::a::*;\n", false)] +fn bare_name_import_of_an_underived_item(#[case] routes_source: &str, #[case] rejected: bool) { + let dir = tempfile::TempDir::new().unwrap(); + let stored_file = write_crate(dir.path(), routes_source); + let _manifest = crate::env_access::test_env::set_var("CARGO_MANIFEST_DIR", dir.path()); + let _call_site = set_test_call_site_module("crate::routes"); + let stored = StructMetadata::new( + "Page".to_string(), + "pub struct Page { pub y: i32 }".to_string(), + ) + .with_source_identity(format!("{stored_file}::Page@1:1")); + let ty: syn::Type = syn::parse_quote!(Page); + let result = requested_variant(&ty, &stored); + assert_eq!(result.is_err(), rejected); +} diff --git a/crates/vespera_macro/src/schema_macro/same_file_override.rs b/crates/vespera_macro/src/schema_macro/same_file_override.rs index 3c796f85..5c282283 100644 --- a/crates/vespera_macro/src/schema_macro/same_file_override.rs +++ b/crates/vespera_macro/src/schema_macro/same_file_override.rs @@ -36,15 +36,51 @@ pub(super) fn find_same_file_struct_metadata<'a>( struct_name: &str, schema_storage: &'a HashMap, ) -> Option> { - if let Some(definition) = same_file_definition(struct_name) { - return Some(Cow::Owned(StructMetadata::new( - struct_name.to_string(), - definition, - ))); + choose_same_file( + struct_name, + same_file_definition(struct_name), + super::storage_entry(schema_storage, struct_name), + ) +} + +/// The file item wins over the stored entry only when it is a `Schema` +/// (the listed route-local DTO derives it). A plain struct of that name in +/// the file (not a DTO, e.g. a same-named helper) must not replace the +/// `Schema` the imports name in another module: the stored entry is used +/// then, and the file item only when nothing is stored (R20-SM3-01, round 20). +fn choose_same_file<'a>( + struct_name: &str, + file_definition: Option, + stored: Option<&'a StructMetadata>, +) -> Option> { + match file_definition { + Some(definition) if stored.is_none() || derives_schema(&definition) => Some(Cow::Owned( + StructMetadata::new(struct_name.to_string(), definition), + )), + // Cache hit: hand back a borrow so the (potentially large) struct + // definition string is not cloned per lookup. + _ => stored.map(Cow::Borrowed), } - // Cache hit: hand back a borrow so the (potentially large) struct - // definition string is not cloned per lookup. - super::storage_entry(schema_storage, struct_name).map(Cow::Borrowed) +} + +/// Whether the struct `definition` has `Schema` in one of its `derive`s. +fn derives_schema(definition: &str) -> bool { + let Ok(item) = file_cache::parse_struct_cached(definition) else { + return false; + }; + item.attrs + .iter() + .filter(|attr| attr.path().is_ident("derive")) + .any(|attr| { + attr.parse_args_with( + syn::punctuated::Punctuated::::parse_terminated, + ) + .is_ok_and(|paths| { + paths + .iter() + .any(|path| path.segments.last().is_some_and(|s| s.ident == "Schema")) + }) + }) } /// The definition of `struct_name` in the macro call-site file. @@ -485,10 +521,12 @@ mod tests { assert!(metadata.definition.contains("value")); } - /// A same-named struct in the crate-wide storage (another module's - /// `Schema`) must not replace the adapter the call-site file defines. + /// R20-SM3-01 (round 20): a plain (not `Schema`-derived) struct of the + /// adapter's name in the call-site file does not replace the `Schema` + /// the storage holds (the one the imports name); the file's own + /// `__VesperaAdapterFixture` (`id`, `name`) is ignored here. #[test] - fn explicit_adapter_prefers_the_call_site_file_over_storage() { + fn explicit_adapter_keeps_the_stored_schema_over_an_underived_file_struct() { let storage = to_storage(vec![create_test_struct_metadata( "__VesperaAdapterFixture", "struct __VesperaAdapterFixture { value: i32 }", @@ -500,7 +538,46 @@ mod tests { .iter() .filter_map(|field| field.ident.as_ref().map(ToString::to_string)) .collect(); - assert_eq!(fields, ["id", "name"]); + assert_eq!(fields, ["value"]); + } + + /// The file's `Schema`-derived DTO beats a same-named stored entry, and + /// a same-named file struct without `Schema` only fills an empty storage. + #[rstest::rstest] + #[case::derived_file_item_wins( + Some("#[derive(Serialize, vespera::Schema)] struct Dto { id: i32 }"), + "struct Dto { value: i32 }", + "id" + )] + #[case::underived_file_item_yields( + Some("#[derive(Serialize)] struct Dto { id: i32 }"), + "struct Dto { value: i32 }", + "value" + )] + #[case::unparseable_file_item_yields( + Some("struct Dto {"), + "struct Dto { value: i32 }", + "value" + )] + fn file_definition_beats_storage_only_when_it_is_a_schema( + #[case] file: Option<&str>, + #[case] stored: &str, + #[case] expected_field: &str, + ) { + let stored = create_test_struct_metadata("Dto", stored); + let chosen = choose_same_file("Dto", file.map(str::to_string), Some(&stored)).unwrap(); + assert!( + chosen.definition.contains(expected_field), + "{}", + chosen.definition + ); + } + + #[test] + fn underived_file_item_fills_an_empty_storage() { + let chosen = + choose_same_file("Dto", Some("struct Dto { id: i32 }".to_string()), None).unwrap(); + assert!(chosen.definition.contains("id")); } /// A name the call-site file does not define falls back to the storage. diff --git a/crates/vespera_macro/src/schema_macro/seaorm/attrs.rs b/crates/vespera_macro/src/schema_macro/seaorm/attrs.rs index 8c254d44..72698f95 100644 --- a/crates/vespera_macro/src/schema_macro/seaorm/attrs.rs +++ b/crates/vespera_macro/src/schema_macro/seaorm/attrs.rs @@ -171,11 +171,32 @@ pub fn has_sea_orm_database_default(attrs: &[syn::Attribute]) -> bool { || entry(&sea_orm_entries(attrs), "default_expr").is_some_and(|entry| entry.value.is_some()) } +/// SQL functions a `default_value` may spell with arguments (`nextval('seq')`): +/// the name (schema qualifier dropped, lower-cased) must be one of these. +const SQL_FUNCTION_NAMES: &[&str] = &[ + "clock_timestamp", + "current_date", + "current_time", + "current_timestamp", + "gen_random_uuid", + "localtime", + "localtimestamp", + "nextval", + "now", + "random", + "statement_timestamp", + "transaction_timestamp", + "uuid_generate_v4", +]; + /// Check if a `sea_orm(default_value)` is a SQL function call: a (possibly /// schema-qualified) identifier followed by a parenthesised argument list — /// `now()`, `gen_random_uuid()`, `nextval('seq')`. A text default that merely -/// contains a parenthesis (`"N/A (unknown)"`, `":)"`, `"Active (new)"`) is a -/// literal: a space before `(` only fits an empty call (`now ()`). +/// contains a parenthesis (`"N/A (unknown)"`, `":)"`, `"Active (new)"`, +/// `"Draft(WIP)"`) is a literal: a space before `(` only fits an empty call +/// (`now ()`), and a call with arguments must name one of +/// [`SQL_FUNCTION_NAMES`] (R20-SM3-02, round 20: `"Draft(WIP)"` used to be +/// taken as a function, so the column's literal default was dropped). pub fn is_sql_function_default(value: &str) -> bool { let value = value.trim(); let Some((name, args)) = value.split_once('(') else { @@ -184,12 +205,17 @@ pub fn is_sql_function_default(value: &str) -> bool { let spaced = name.ends_with(char::is_whitespace); let name = name.trim_end(); let mut chars = name.chars(); - chars + let well_formed = chars .next() .is_some_and(|first| first.is_ascii_alphabetic() || first == '_') && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.') - && args.ends_with(')') - && (!spaced || args.trim() == ")") + && args.ends_with(')'); + if !well_formed { + return false; + } + let empty_call = args.trim() == ")"; + let bare = name.rsplit('.').next().unwrap_or(name).to_ascii_lowercase(); + empty_call || (!spaced && SQL_FUNCTION_NAMES.contains(&bare.as_str())) } /// Check if a field is a database-generated primary key, mirroring @@ -495,6 +521,11 @@ mod tests { // an empty call (`now ()`), never an argument list. #[case("Active (new)", false)] #[case("Draft (WIP)", false)] + // R20-SM3-02 (round 20): an unspaced note is a literal too; an argument + // list needs a known SQL function name. + #[case("Draft(WIP)", false)] + #[case("Active(new)", false)] + #[case("pg_catalog.nextval('seq')", true)] #[case("(none)", false)] #[case(":)", false)] #[case("now(", false)] diff --git a/crates/vespera_macro/src/schema_macro/type_utils.rs b/crates/vespera_macro/src/schema_macro/type_utils.rs index e82d77dd..9ea038e7 100644 --- a/crates/vespera_macro/src/schema_macro/type_utils.rs +++ b/crates/vespera_macro/src/schema_macro/type_utils.rs @@ -337,6 +337,9 @@ impl TypeResolver<'_> { PathArguments::AngleBracketed(angle) => { let items = angle.args.iter().map(|arg| match arg { GenericArgument::Type(inner) => self.ty(inner), + // A const argument (`Digest<{ HASH_LEN }>`) is re-rooted + // like an array length (R20-S4-L3, round 20). + GenericArgument::Const(expr) => self.array_len(expr), other => quote! { #other }, }); let colon = &angle.colon2_token; @@ -366,28 +369,40 @@ impl TypeResolver<'_> { .collect(); if path.leading_colon.is_some() { segments[0].0.insert_str(0, "::"); - } else if let Resolved::Path(prefix) = - resolve_name(std::slice::from_ref(&segments[0].0), self.module) - { - let first_args = segments.remove(0).1; - let mut rooted: Vec<(String, TokenStream)> = prefix - .into_iter() - .map(|s| (s, TokenStream::new())) + } else { + // The whole leading `self` / `super` run is resolved at once: + // `super::super::x` resolved one `super` at a time left the second + // one in the emitted path (R20-S4-M1, round 20). + let run = leading_run_len(&segments); + let names: Vec = segments[..run] + .iter() + .map(|(name, _)| name.clone()) .collect(); - // A `use ::a::b;` import resolves to `["", "a", "b"]`: its empty - // root becomes the `::` prefix of the next segment (an empty - // segment has no identifier). - if rooted.first().is_some_and(|(name, _)| name.is_empty()) { - rooted.remove(0); - if let Some(next) = rooted.first_mut() { - next.0.insert_str(0, "::"); + if let Resolved::Path(prefix) = resolve_name(&names, self.module) { + let first_args = segments + .drain(..run) + .next_back() + .map(|(_, args)| args) + .unwrap_or_default(); + let mut rooted: Vec<(String, TokenStream)> = prefix + .into_iter() + .map(|s| (s, TokenStream::new())) + .collect(); + // A `use ::a::b;` import resolves to `["", "a", "b"]`: its empty + // root becomes the `::` prefix of the next segment (an empty + // segment has no identifier). + if rooted.first().is_some_and(|(name, _)| name.is_empty()) { + rooted.remove(0); + if let Some(next) = rooted.first_mut() { + next.0.insert_str(0, "::"); + } } + if let Some(last) = rooted.last_mut() { + last.1 = first_args; + } + rooted.extend(segments); + segments = rooted; } - if let Some(last) = rooted.last_mut() { - last.1 = first_args; - } - rooted.extend(segments); - segments = rooted; } Some(render_segments(&segments)) } @@ -430,6 +445,16 @@ impl TypeResolver<'_> { let path = path_tokens(&path); return quote! { #path #args }; } + // A name the source module neither defines nor imports, nor a std + // prelude name, comes from one of its external glob imports (it + // compiled there): emitted through that glob, not as a bare alias + // (`use toml::*;` `Value` was `serde_json::Value`) (R20-S4-L1, round 20). + if let Some(glob) = self.scope.and_then(external_glob) + && !is_prelude_name(&name) + { + let base = path_tokens(glob); + return quote! { #base :: #ident #args }; + } let sea_orm_scope = self.scope.is_some_and(ModuleScope::has_sea_orm_glob); if let Some(converted) = self.alias(&name, &segment.arguments, sea_orm_scope) { return converted; @@ -563,6 +588,32 @@ impl syn::visit_mut::VisitMut for LenPaths<'_, '_> { } } +/// How many leading segments of a type path resolve together: its leading +/// `self` / `super` run, or the first segment alone (at least one). +fn leading_run_len(segments: &[(String, TokenStream)]) -> usize { + segments + .iter() + .take_while(|(name, _)| name == "self" || name == "super") + .count() + .max(1) +} + +/// The first external glob import of `scope`: not `crate` / `self` / `super` +/// (resolved by name) and not a crate [`ALIAS_CRATES`] names (its aliases). +fn external_glob(scope: &ModuleScope) -> Option<&Vec> { + scope.globs.iter().find(|glob| { + first_named(glob).is_some_and(|root| { + !matches!(root, "crate" | "self" | "super") && !ALIAS_CRATES.contains(&root) + }) + }) +} + +/// Names a glob import never supplies: the primitives and the std prelude. +fn is_prelude_name(name: &str) -> bool { + PRIMITIVE_TYPE_NAMES.contains(&name) + || matches!(name, "Vec" | "Option" | "Result" | "Box" | "Self") +} + fn first_named(path: &[String]) -> Option<&str> { path.iter().find(|s| !s.is_empty()).map(String::as_str) } @@ -760,3 +811,5 @@ pub fn get_type_default(ty: &Type) -> Option { #[cfg(test)] mod tests; +#[cfg(test)] +mod tests_glob; diff --git a/crates/vespera_macro/src/schema_macro/type_utils/tests.rs b/crates/vespera_macro/src/schema_macro/type_utils/tests.rs index 6fd4f2f0..b8f83777 100644 --- a/crates/vespera_macro/src/schema_macro/type_utils/tests.rs +++ b/crates/vespera_macro/src/schema_macro/type_utils/tests.rs @@ -10,7 +10,7 @@ fn ecosystem_default_names_follow_the_call_site_scope() { std::fs::create_dir_all(dir.path().join("src")).unwrap(); std::fs::write( dir.path().join("src/lib.rs"), - "pub struct Decimal(pub i64);\nmod sea;\n", + "pub struct Decimal(pub i64);\nmod sea;\nmod own;\n", ) .unwrap(); std::fs::write( @@ -18,6 +18,13 @@ fn ecosystem_default_names_follow_the_call_site_scope() { "use sea_orm::prelude::Date;\npub struct Holder { pub d: Date }\n", ) .unwrap(); + // `Date` imported from a crate that is not an ecosystem one (R20-S4-L4, + // round 20): the call site's own `Date`, so no ecosystem default. + std::fs::write( + dir.path().join("src/own.rs"), + "use my_crate::Date;\npub struct Holder { pub d: Date }\n", + ) + .unwrap(); let _manifest = crate::env_access::test_env::set_var("CARGO_MANIFEST_DIR", dir.path()); let decimal: syn::Type = syn::parse_quote!(Decimal); let date: syn::Type = syn::parse_quote!(Date); @@ -31,11 +38,15 @@ fn ecosystem_default_names_follow_the_call_site_scope() { Some(serde_json::json!("1970-01-01")) ); } - let _site = crate::schema_macro::file_lookup::set_test_call_site_module("crate::sea"); - assert_eq!( - get_type_default(&date), - Some(serde_json::json!("1970-01-01")) - ); + { + let _site = crate::schema_macro::file_lookup::set_test_call_site_module("crate::sea"); + assert_eq!( + get_type_default(&date), + Some(serde_json::json!("1970-01-01")) + ); + } + let _site = crate::schema_macro::file_lookup::set_test_call_site_module("crate::own"); + assert_eq!(get_type_default(&date), None); } fn empty_type_path() -> syn::Type { @@ -669,6 +680,16 @@ fn chrono_names_resolve_bare_only(#[case] src: &str, #[case] expected: &str) { #[case::const_generic("[u8; HASH_LEN]", &["HASH_LEN"], "[u8 ; HASH_LEN]")] #[case::unknown("[u8; OTHER]", &[], "[u8 ; OTHER]")] #[case::leading_colon("[u8; ::lib::LEN]", &[], "[u8 ; :: lib :: LEN]")] +// R20-S4-M1 (round 20): a leading `super` run resolves as one prefix +// (`super::super` from `crate::models::file` is `crate`). +#[case::double_super_type("super::super::consts::Thing", &[], "crate :: consts :: Thing")] +// R20-S4-L3 (round 20): a const generic argument written as a block is +// re-rooted like an array length. +#[case::const_generic_block( + "Digest<{ HASH_LEN }>", + &[], + "crate :: models :: file :: Digest < { crate :: models :: file :: HASH_LEN } >" +)] fn array_length_constant_is_rerooted( #[case] ty: &str, #[case] generic_params: &[&str], diff --git a/crates/vespera_macro/src/schema_macro/type_utils/tests_glob.rs b/crates/vespera_macro/src/schema_macro/type_utils/tests_glob.rs new file mode 100644 index 00000000..c95a1cd2 --- /dev/null +++ b/crates/vespera_macro/src/schema_macro/type_utils/tests_glob.rs @@ -0,0 +1,54 @@ +//! External glob imports of the source module (R20-S4-L1, round 20): a name +//! the module neither defines nor imports comes from its glob. + +use rstest::rstest; + +use super::*; + +/// `models/toml_glob.rs` has `use toml::*;`, `models/std_glob.rs` has +/// `use std::collections::*;`, so each name has exactly one glob to come from. +fn glob_crate() -> tempfile::TempDir { + let dir = tempfile::TempDir::new().unwrap(); + let src = dir.path().join("src"); + std::fs::create_dir_all(src.join("models")).unwrap(); + std::fs::write(src.join("lib.rs"), "pub mod models;").unwrap(); + std::fs::write( + src.join("models.rs"), + "pub mod toml_glob;\npub mod std_glob;", + ) + .unwrap(); + std::fs::write( + src.join("models").join("toml_glob.rs"), + "use toml::*;\npub struct Holder { pub v: Value }", + ) + .unwrap(); + std::fs::write( + src.join("models").join("std_glob.rs"), + "use std::collections::*;\npub struct Holder { pub m: HashMap }", + ) + .unwrap(); + dir +} + +#[rstest] +#[case::toml_value("toml_glob", "Value", "toml :: Value")] +#[case::std_hash_map( + "std_glob", + "HashMap", + "std :: collections :: HashMap < String , i32 >" +)] +fn external_glob_supplies_names_the_module_does_not_define( + #[case] module: &str, + #[case] ty: &str, + #[case] expected: &str, +) { + let dir = glob_crate(); + let _guard = crate::env_access::test_env::set_var("CARGO_MANIFEST_DIR", dir.path()); + crate::schema_macro::file_cache::bump_epoch(); + let module = ["crate", "models", module].map(String::from); + let ty: syn::Type = syn::parse_str(ty).unwrap(); + assert_eq!( + resolve_type_with_params(&ty, &module, &[]).to_string(), + expected + ); +} diff --git a/crates/vespera_macro/src/schema_macro/validation.rs b/crates/vespera_macro/src/schema_macro/validation.rs index 1d1c0e89..ef440016 100644 --- a/crates/vespera_macro/src/schema_macro/validation.rs +++ b/crates/vespera_macro/src/schema_macro/validation.rs @@ -161,9 +161,16 @@ pub fn validate_omit_fields( /// `"a b"`, `""`, a leading digit) AND reserved keywords (`"type"`, /// `"match"`) — both of which would otherwise either panic /// `Ident::new` or emit a struct field that fails to compile. Raw -/// identifiers (`"r#type"`) are accepted. +/// identifiers (`"r#type"`) are accepted, but not the path keywords with a +/// raw prefix (`"r#self"`, `"r#super"`, `"r#crate"`, `"r#Self"`, `"r#_"`): +/// syn accepts those, and the emitted field would lose its `r#` (R20-S4-L2, +/// round 20). fn is_valid_field_ident(name: &str) -> bool { syn::parse_str::(name).is_ok() + && !matches!( + name.strip_prefix("r#").unwrap_or(name), + "self" | "Self" | "super" | "crate" | "_" + ) } /// Validates a `rename` pair list: every **source** field must exist in @@ -531,6 +538,23 @@ mod tests { assert!(result.is_ok()); } + /// R20-S4-L2 (round 20): a raw path keyword (`r#self`) is not a field + /// name: syn accepts it, but the emitted field would be a plain `self`. + #[rstest::rstest] + #[case::raw_self("r#self")] + #[case::raw_super("r#super")] + #[case::raw_crate("r#crate")] + #[case::raw_capital_self("r#Self")] + #[case::raw_underscore("r#_")] + fn test_validate_rename_fields_raw_path_keyword_rejected(#[case] target: &str) { + let source_fields = create_field_names(&["id"]); + let rename = Some(vec![("id".to_string(), target.to_string())]); + let ty: syn::Type = syn::parse2(quote!(User)).unwrap(); + + let result = validate_rename_fields(rename.as_ref(), &source_fields, &ty, "User"); + assert!(result.is_err(), "`{target}` must not be a field name"); + } + /// L15: a field renamed twice used to take the last target silently. #[test] fn test_validate_rename_fields_duplicate_source_rejected() { diff --git a/examples/axum-example/openapi.json b/examples/axum-example/openapi.json index 25ffc000..9d11b9de 100644 --- a/examples/axum-example/openapi.json +++ b/examples/axum-example/openapi.json @@ -5531,8 +5531,7 @@ "default": 0 }, "status": { - "$ref": "#/components/schemas/MemoStatus", - "default": "draft" + "$ref": "#/components/schemas/MemoStatus" }, "title": { "type": "string" @@ -5653,8 +5652,7 @@ } }, "status": { - "$ref": "#/components/schemas/MemoStatus", - "default": "draft" + "$ref": "#/components/schemas/MemoStatus" }, "title": { "type": "string" @@ -5708,8 +5706,7 @@ "default": 0 }, "status": { - "$ref": "#/components/schemas/MemoStatus", - "default": "draft" + "$ref": "#/components/schemas/MemoStatus" }, "title": { "type": "string" @@ -5795,8 +5792,7 @@ "default": 0 }, "status": { - "$ref": "#/components/schemas/MemoStatus", - "default": "draft" + "$ref": "#/components/schemas/MemoStatus" }, "title": { "type": "string" @@ -5836,8 +5832,7 @@ "default": 0 }, "status": { - "$ref": "#/components/schemas/MemoStatus", - "default": "draft" + "$ref": "#/components/schemas/MemoStatus" }, "title": { "type": "string" @@ -5918,8 +5913,7 @@ "type": "string" }, "status": { - "$ref": "#/components/schemas/MemoStatus", - "default": "draft" + "$ref": "#/components/schemas/MemoStatus" }, "title": { "type": "string" diff --git a/examples/axum-example/tests/snapshots/integration_test__openapi.snap b/examples/axum-example/tests/snapshots/integration_test__openapi.snap index 95ebaea7..f0044654 100644 --- a/examples/axum-example/tests/snapshots/integration_test__openapi.snap +++ b/examples/axum-example/tests/snapshots/integration_test__openapi.snap @@ -5536,8 +5536,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "default": 0 }, "status": { - "$ref": "#/components/schemas/MemoStatus", - "default": "draft" + "$ref": "#/components/schemas/MemoStatus" }, "title": { "type": "string" @@ -5658,8 +5657,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" } }, "status": { - "$ref": "#/components/schemas/MemoStatus", - "default": "draft" + "$ref": "#/components/schemas/MemoStatus" }, "title": { "type": "string" @@ -5713,8 +5711,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "default": 0 }, "status": { - "$ref": "#/components/schemas/MemoStatus", - "default": "draft" + "$ref": "#/components/schemas/MemoStatus" }, "title": { "type": "string" @@ -5800,8 +5797,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "default": 0 }, "status": { - "$ref": "#/components/schemas/MemoStatus", - "default": "draft" + "$ref": "#/components/schemas/MemoStatus" }, "title": { "type": "string" @@ -5841,8 +5837,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "default": 0 }, "status": { - "$ref": "#/components/schemas/MemoStatus", - "default": "draft" + "$ref": "#/components/schemas/MemoStatus" }, "title": { "type": "string" @@ -5923,8 +5918,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "type": "string" }, "status": { - "$ref": "#/components/schemas/MemoStatus", - "default": "draft" + "$ref": "#/components/schemas/MemoStatus" }, "title": { "type": "string"