diff --git a/.changepacks/changepack_log_schema_round41.json b/.changepacks/changepack_log_schema_round41.json new file mode 100644 index 00000000..b66b6be0 --- /dev/null +++ b/.changepacks/changepack_log_schema_round41.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":"schema_type! readability: a source container serde default fn, a related model's serde default paths in an inline relation type, and a one-name type reached through an import, a glob or a private module are refused with the spanned private-item error instead of E0603 in the generated DTO; the DTO no longer refuses a serde(transparent) source for a multipart DTO; an empty schema name is a compile error; a Schema-derived struct's stale variant check and a custom test root's helper modules resolve as the compiler sees them.","date":"2026-11-24T00:00:00.000Z"} diff --git a/crates/vespera_macro/src/schema_impl.rs b/crates/vespera_macro/src/schema_impl.rs index 44a5f8dd..f6cd70f7 100644 --- a/crates/vespera_macro/src/schema_impl.rs +++ b/crates/vespera_macro/src/schema_impl.rs @@ -462,6 +462,12 @@ fn collect_schema_attribute_summary( return Err(meta.error("duplicate `name` in `#[schema(..)]`")); } let lit: syn::LitStr = meta.value()?.parse()?; + if lit.value().is_empty() { + return Err(syn::Error::new_spanned( + &lit, + "`#[schema(name = ..)]` is the OpenAPI component name: it must not be empty", + )); + } attr_name = Some(lit.value()); } else if meta.path.is_ident("ref") { summary.has_ref_override = true; diff --git a/crates/vespera_macro/src/schema_impl/stale.rs b/crates/vespera_macro/src/schema_impl/stale.rs index 64665fcd..c225b4b6 100644 --- a/crates/vespera_macro/src/schema_impl/stale.rs +++ b/crates/vespera_macro/src/schema_impl/stale.rs @@ -90,17 +90,25 @@ fn module_chain(file: &Path, line: usize) -> Vec { crate::schema_macro::module_scope::inline_chain_at(file, line) } +/// The items the inline module `chain` declares directly (child inline modules +/// are other modules and are left out); empty when `chain` is not in `items`. +fn module_own_items(items: &[syn::Item], chain: &[String]) -> Vec { + super::default_fns::inline_module_items(items.to_vec(), chain).map_or_else(Vec::new, |module| { + module + .into_iter() + .filter(|item| !matches!(item, syn::Item::Mod(_))) + .collect() + }) +} + /// How many `ident` items `items` declares directly in the inline module /// `chain`. Child inline modules are other modules and do not count, so a /// same-named item of a sibling module never keeps this one alive. fn declared_in_module(items: &[syn::Item], chain: &[String], ident: &str) -> usize { - super::default_fns::inline_module_items(items.to_vec(), chain).map_or(0, |module| { - module - .iter() - .filter(|item| !matches!(item, syn::Item::Mod(_))) - .map(|item| super::count_items_named(std::slice::from_ref(item), ident)) - .sum() - }) + module_own_items(items, chain) + .iter() + .map(|item| super::count_items_named(std::slice::from_ref(item), ident)) + .sum() } /// The lines of `ident` tokens in a `schema_type!` invocation's tokens (groups @@ -146,11 +154,23 @@ fn schema_type_lines(items: &[syn::Item], ident: &str) -> Vec { found.lines } -/// [`schema_type_lines`] of the file at `path`; `None` when it is unreadable -/// or does not parse (then nothing is pruned). -fn schema_type_lines_of(path: &Path, ident: &str) -> Option> { +/// The lines of the `schema_type!` invocations that name `ident` in the scope +/// of `items`: the whole file, or only the inline module `chain` (R41-SM0-L1: +/// a same-named invocation of a sibling module on the same line is not it). +fn invoked_lines(items: &[syn::Item], chain: &[String], ident: &str, scope: Scope) -> Vec { + match scope { + Scope::File => schema_type_lines(items, ident), + Scope::Module => schema_type_lines(&module_own_items(items, chain), ident), + } +} + +/// [`invoked_lines`] of the file at `path`; `None` when it is unreadable or +/// does not parse (then nothing is pruned). +fn schema_type_lines_of(path: &Path, ident: &str, chain: &[String]) -> Option> { let content = get_file_content(path)?; - with_fallback_parse(&content, |parsed| schema_type_lines(&parsed.items, ident)) + with_fallback_parse(&content, |parsed| { + invoked_lines(&parsed.items, chain, ident, Scope::Module) + }) } /// Whether `ident` is still declared in the given scope of `items`, or a @@ -170,7 +190,7 @@ fn still_declared( // Only a generated DTO has no textual declaration to check: a derived item // that left its position is not kept by a `schema_type!` naming it there // (SM0-L1, round 40). - textual > 0 || (generated && schema_type_lines(items, ident).contains(&line)) + textual > 0 || (generated && invoked_lines(items, chain, ident, scope).contains(&line)) } /// Remember the current fingerprint of `identity`'s file and item module. @@ -205,7 +225,7 @@ pub(super) fn record(identity: Option<&str>) { || lines.contains(&line_of(old)) }), None => { - if let Some(invoked) = schema_type_lines_of(path, ident) { + if let Some(invoked) = schema_type_lines_of(path, ident, &chain) { records.retain(|old, recorded| { file_and_ident(old) != Some((file, ident)) || !recorded.generated diff --git a/crates/vespera_macro/src/schema_impl/tests.rs b/crates/vespera_macro/src/schema_impl/tests.rs index 2902bb07..3fa20e0e 100644 --- a/crates/vespera_macro/src/schema_impl/tests.rs +++ b/crates/vespera_macro/src/schema_impl/tests.rs @@ -910,3 +910,17 @@ fn cached_default_functions_reuses_the_cached_arc_for_unchanged_files() { fn identity_without_file_component_is_never_a_move() { assert!(!is_same_item_moved(Some("User@1:7"), Some("User@3:7"))); } + +/// SM3-03: an empty `#[schema(name = "")]` is no OpenAPI component name and is +/// a spanned compile error, as a malformed one is. +#[test] +fn empty_schema_name_is_compile_error() { + let input: syn::DeriveInput = syn::parse_quote! { + #[schema(name = "")] + struct User { id: i32 } + }; + let Err(err) = collect_schema_attribute_summary(&input.attrs) else { + panic!("an empty `name` must be refused"); + }; + assert!(err.to_string().contains("must not be empty"), "{err}"); +} diff --git a/crates/vespera_macro/src/schema_impl/tests_stale.rs b/crates/vespera_macro/src/schema_impl/tests_stale.rs index 5846156b..17715d92 100644 --- a/crates/vespera_macro/src/schema_impl/tests_stale.rs +++ b/crates/vespera_macro/src/schema_impl/tests_stale.rs @@ -378,3 +378,41 @@ fn derive_replaced_by_schema_type_in_its_module_has_left_the_module() { bump_epoch(); assert!(!super::stale::left_its_module(&stored)); } + +/// R41-SM0-L1: a variant of `a` is not kept by a `schema_type!` naming the same +/// item in a sibling module `b` on the line `a`'s invocation was recorded at. +#[test] +fn sibling_module_invocation_on_the_same_line_does_not_keep_a_variant() { + let dir = tempfile::TempDir::new().unwrap(); + let file = dir.path().join("sibling_line.rs"); + std::fs::write( + &file, + "mod a {\n schema_type!(User from Model);\n}\nmod b {\n schema_type!(User from Model);\n}\n", + ) + .unwrap(); + bump_epoch(); + let identity = identity(&file, 2); + super::stale::record(Some(&identity)); + let stored = StructMetadata { + source_identity: Some(identity), + ..StructMetadata::new("User".to_string(), String::new()) + }; + + // `a`'s invocation is gone; `b`'s now sits on the line `a`'s was recorded at. + std::fs::write( + &file, + "mod a {}\nmod b { schema_type!(User from Model); }\n", + ) + .unwrap(); + bump_epoch(); + assert!(super::stale::left_its_module(&stored)); + + // `a`'s own invocation back on that line: still a variant of `a`. + std::fs::write( + &file, + "mod a {\n schema_type!(User from Model);\n}\nmod b {}\n", + ) + .unwrap(); + bump_epoch(); + assert!(!super::stale::left_its_module(&stored)); +} diff --git a/crates/vespera_macro/src/schema_macro/crate_layout.rs b/crates/vespera_macro/src/schema_macro/crate_layout.rs index a66a069f..ba45f46c 100644 --- a/crates/vespera_macro/src/schema_macro/crate_layout.rs +++ b/crates/vespera_macro/src/schema_macro/crate_layout.rs @@ -163,7 +163,6 @@ pub fn layout_for(manifest_dir: &Path, call_site: Option<&Path>) -> CrateLayout } _ => None, }; - let custom_target = target.is_none(); if let Some((dir, target_name, entry)) = target && let Some(root) = target_root(&dir, target_name.as_deref(), entry) { @@ -176,9 +175,11 @@ pub fn layout_for(manifest_dir: &Path, call_site: Option<&Path>) -> CrateLayout // A custom `[[test]]` / `[[bench]]` / `[[example]]` / `[[bin]]` `path` outside // the default directories (R28-SM1-L1) is rooted at the file rustc compiles. // Under `src/` (R32-SM1-L3) the same holds unless that file is the library - // or main root, which the library layout below already covers. - if custom_target - && let Some(call_site) = call_site + // or main root, which the library layout below already covers. A call site + // under a target directory with no named root (a helper of a custom + // `[[test]] name = "integration" path = "tests/main.rs"`, R41-SM1-1) is + // rooted at the compiler's root too, not at the library. + if let Some(call_site) = call_site && let Some(layout) = compiler_root_layout(call_site) && (relative_to(call_site, &src).is_none() || !is_default_src_root(&layout.roots, &src)) { @@ -564,6 +565,33 @@ mod tests { assert_eq!(layout.module_path_of(&file).join("::"), module); } + /// R41-SM1-1: a helper under a custom `[[test]] name = "integration" + /// path = "tests/main.rs"` has no `tests/integration.rs` / `tests/common.rs` + /// root in its target directory. It is rooted at the file rustc compiles + /// (`tests/main.rs`), so `crate::` resolves from `tests/`, not from `src/`, + /// and the helper's module path is `crate::common`. + #[test] + fn custom_test_root_helper_module() { + let dir = temp_crate(); + std::fs::write(dir.path().join("tests/main.rs"), "").unwrap(); + let _crate = crate::env_access::test_env::set_var("CARGO_CRATE_NAME", "integration"); + let _args = crate::env_access::test_env::set_var( + crate::env_access::COMPILER_ARGS_KEY, + format!("rustc\n{}", dir.path().join("tests/main.rs").display()), + ); + let file = dir.path().join("tests/common/mod.rs"); + let layout = layout_for(dir.path(), Some(&file)); + assert!( + same_path(&layout.module_dir, &dir.path().join("tests")), + "{layout:?}" + ); + assert!( + same_path(&layout.roots[0], &dir.path().join("tests/main.rs")), + "{layout:?}" + ); + assert_eq!(layout.module_path_of(&file).join("::"), "crate::common"); + } + /// A cwd-relative call-site path (what rustc reports for workspace /// members) resolves like the absolute one. #[test] diff --git a/crates/vespera_macro/src/schema_macro/generate_type.rs b/crates/vespera_macro/src/schema_macro/generate_type.rs index 10ab6fb5..3a163079 100644 --- a/crates/vespera_macro/src/schema_macro/generate_type.rs +++ b/crates/vespera_macro/src/schema_macro/generate_type.rs @@ -398,6 +398,7 @@ pub fn generate_schema_type_code( &source_module_path, input.schema_name.as_deref(), ) { + inline_type.check_serde_path()?; let inline_type_def = generate_inline_type_definition(&inline_type); inline_type_definitions .push(assignments::gate_items(&field_cfg, inline_type_def)); @@ -454,6 +455,7 @@ pub fn generate_schema_type_code( &source_module_path, input.schema_name.as_deref(), ) { + inline_type.check_serde_path()?; // Generate inline type definition let inline_type_def = generate_inline_type_definition(&inline_type); inline_type_definitions @@ -807,6 +809,7 @@ pub fn generate_schema_type_code( // readable from the call site (a private field of another module is // E0616; the `From` is left out instead). let buildable = input.add.is_none() && !has_relation_fields && all_readable; + checks::check_container_default_path(&parsed_struct.attrs, buildable, &source_module_path)?; // In multipart mode, skip From and from_model impls entirely let source_type: &syn::Type = &input.source_type; diff --git a/crates/vespera_macro/src/schema_macro/generate_type/checks.rs b/crates/vespera_macro/src/schema_macro/generate_type/checks.rs index 59d19bb1..e458189f 100644 --- a/crates/vespera_macro/src/schema_macro/generate_type/checks.rs +++ b/crates/vespera_macro/src/schema_macro/generate_type/checks.rs @@ -123,6 +123,22 @@ pub(super) fn check_emitted( ) } +/// The source container's serde function path (`#[serde(default = "f")]`) +/// must name an item the call site can read when the DTO carries it: the +/// default helper calls `f` from the DTO's module (R41-B2-01). `carried` is +/// whether the DTO is built from the source (the helper is emitted only then). +pub(super) fn check_container_default_path( + attrs: &[syn::Attribute], + carried: bool, + source_module: &[String], +) -> syn::Result<()> { + if !carried { + return Ok(()); + } + let call_site = super::super::file_lookup::call_site_module(); + unreadable_serde_path(attrs, source_module, call_site.as_deref()).map_or(Ok(()), Err) +} + /// The serde function paths of the emitted fields must name items the call /// site can read (a private `default_name` of the source module is `E0603` in /// the DTO emitted elsewhere). @@ -162,8 +178,9 @@ pub(super) fn check_transparent( attr.parse_args_with(Punctuated::::parse_terminated) .is_ok_and(|items| items.iter().any(|meta| meta.path().is_ident("transparent"))) }); + // A multipart DTO carries no `serde(transparent)` (R41-B2-04): nothing to keep. let field_count = emitted + input.add.as_ref().map_or(0, Vec::len); - if transparent && field_count != 1 { + if transparent && !input.multipart && field_count != 1 { return Err(syn::Error::new( input.new_type.span(), format!( @@ -199,6 +216,13 @@ mod tests { )] #[case::not_transparent(r"#[serde(deny_unknown_fields)]", "Dto from Src", 3, true)] #[case::not_serde(r"#[transparent]", "Dto from Src", 3, true)] + // R41-B2-04: a multipart DTO never keeps the attribute, whatever its count. + #[case::multipart_carries_no_transparent( + r"#[serde(transparent)]", + "Dto from Src, multipart", + 2, + true + )] fn transparent_needs_exactly_one_field( #[case] attr: &str, #[case] dsl: &str, diff --git a/crates/vespera_macro/src/schema_macro/inline_types.rs b/crates/vespera_macro/src/schema_macro/inline_types.rs index 33a8d745..d6772589 100644 --- a/crates/vespera_macro/src/schema_macro/inline_types.rs +++ b/crates/vespera_macro/src/schema_macro/inline_types.rs @@ -14,7 +14,7 @@ use super::{ file_lookup::{call_site_module, find_model_from_schema_path}, module_scope::readable_from, seaorm::{RelationFieldInfo, convert_type_with_chrono}, - transformation::{RenameAll, reroot_serde_paths, serde_only_attrs}, + transformation::{RenameAll, reroot_serde_paths, serde_only_attrs, unreadable_serde_path}, type_utils::{is_seaorm_relation_type, snake_to_pascal_case}, }; use crate::parser::{extract_rename_all, extract_skip}; @@ -23,6 +23,10 @@ use crate::parser::{extract_rename_all, extract_skip}; pub struct InlineRelationType { /// Name of the inline type (e.g., `MemoResponseRel_User`) pub type_name: syn::Ident, + /// The first kept field's serde function path the call site cannot read + /// (a private `default_title` of the related model's module): the type + /// is emitted at the call site, so the caller refuses it (R41-B2-02). + pub serde_path_error: Option, /// Fields to include (excluding circular references) pub fields: Vec, /// The target model's `rename_all`, per serde side (camelCase when it @@ -30,6 +34,14 @@ pub struct InlineRelationType { pub rename_all: RenameAll, } +impl InlineRelationType { + /// Refuses the type when a kept field's serde path is unreadable from the + /// call site, where the type is emitted (R41-B2-02). + pub fn check_serde_path(&self) -> syn::Result<()> { + self.serde_path_error.clone().map_or(Ok(()), Err) + } +} + /// A field in an inline relation type pub struct InlineField { pub name: syn::Ident, @@ -207,6 +219,7 @@ fn generate_inline_type_core( // Collect fields, excluding circular ones and/or relation types let mut fields = Vec::with_capacity(8); let call_site = call_site_module(); + let mut serde_path_error: Option = None; if let syn::Fields::Named(fields_named) = &parsed_model.fields { for field in &fields_named.named { let field_ident = field.ident.as_ref()?; @@ -260,6 +273,9 @@ fn generate_inline_type_core( .any(|key| path.is_ident(key)) }) .collect(); + serde_path_error = serde_path_error.or_else(|| { + unreadable_serde_path(&field.attrs, effective_module_path, call_site.as_deref()) + }); let carried = carried_field_attrs(&field.attrs, true, effective_module_path, false); let cfg_attrs = carried.cfg_serde_attrs().into_iter(); kept_attrs.extend( @@ -283,6 +299,7 @@ fn generate_inline_type_core( type_name: inline_type_name, fields, rename_all, + serde_path_error, }) } 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 a028a128..bca7b3ee 100644 --- a/crates/vespera_macro/src/schema_macro/inline_types/tests.rs +++ b/crates/vespera_macro/src/schema_macro/inline_types/tests.rs @@ -30,6 +30,7 @@ fn inline(name: &str, rename_all: &str, fields: Vec) -> InlineRelat serialize: Some(rename_all.to_string()), deserialize: Some(rename_all.to_string()), }, + serde_path_error: None, } } diff --git a/crates/vespera_macro/src/schema_macro/input.rs b/crates/vespera_macro/src/schema_macro/input.rs index f6c4d7d5..e0d97b9d 100644 --- a/crates/vespera_macro/src/schema_macro/input.rs +++ b/crates/vespera_macro/src/schema_macro/input.rs @@ -454,6 +454,12 @@ impl Parse for SchemaTypeInput { // name = "CustomSchemaName" - custom OpenAPI schema name input.parse::()?; let name_lit: LitStr = input.parse()?; + if name_lit.value().is_empty() { + return Err(syn::Error::new_spanned( + &name_lit, + "schema_type!: `name` is the OpenAPI component name: it must not be empty", + )); + } schema_name = Some(name_lit.value()); } "rename_all" => { diff --git a/crates/vespera_macro/src/schema_macro/mod.rs b/crates/vespera_macro/src/schema_macro/mod.rs index baf8e0fb..9c2a875f 100644 --- a/crates/vespera_macro/src/schema_macro/mod.rs +++ b/crates/vespera_macro/src/schema_macro/mod.rs @@ -27,6 +27,8 @@ mod same_file_override; mod seaorm; #[cfg(test)] mod tests_round40; +#[cfg(test)] +mod tests_round41; mod transformation; pub mod type_utils; mod validation; diff --git a/crates/vespera_macro/src/schema_macro/tests_round41.rs b/crates/vespera_macro/src/schema_macro/tests_round41.rs new file mode 100644 index 00000000..32966283 --- /dev/null +++ b/crates/vespera_macro/src/schema_macro/tests_round41.rs @@ -0,0 +1,231 @@ +//! Round-41 `schema_type!` fixes: a source container's private serde default fn +//! (B2-01) and a related model's private serde path in an inline relation type +//! (B2-02) are refused from another module like a field's; a one-name type +//! reached through an import, a glob or a private module of its source is +//! refused by the same readability rule as a written path (SM3-02, SM4-01); an +//! empty `name` is refused at parse time (SM3-03). + +use std::collections::HashMap; + +use super::file_lookup::set_test_call_site_module; +use super::generate_type::generate_schema_type_code; +use super::input::SchemaTypeInput; + +/// A crate with the given `src` files (`path`, `content`). +fn crate_with(files: &[(&str, &str)]) -> tempfile::TempDir { + let dir = tempfile::TempDir::new().unwrap(); + for (path, content) in files { + let file = dir.path().join("src").join(path); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(file, content).unwrap(); + } + dir +} + +/// The DTO `dsl` generates for a call site in `call_site`, as its tokens. +fn dto_tokens(dir: &tempfile::TempDir, call_site: &str, dsl: &str) -> syn::Result { + let _env = crate::env_access::test_env::set_var("CARGO_MANIFEST_DIR", dir.path()); + crate::schema_macro::file_cache::bump_epoch(); + let _call_site = set_test_call_site_module(call_site); + let input: SchemaTypeInput = syn::parse_str(dsl)?; + generate_schema_type_code(&input, &HashMap::new()).map(|(tokens, _)| tokens.to_string()) +} + +/// `models/memo.rs`: a `Model` whose container default is the private +/// `default_memo` fn of its own module. +const MEMO_CONTAINER_DEFAULT: &str = "#[serde(default = \"default_memo\")]\n\ + #[sea_orm(table_name = \"memos\")]\n\ + pub struct Model {\n pub id: i32,\n}\n\ + fn default_memo() -> Model {\n Model { id: 0 }\n}\n"; + +const MEMO_DSL: &str = "MemoSchema from crate::models::memo::Model"; + +/// B2-01: the source container's private default fn is `E0603` in the default +/// helper of a DTO emitted in another module, so the DTO is refused. +#[test] +fn private_container_default_fn_is_refused_from_another_module() { + let dir = crate_with(&[("models/memo.rs", MEMO_CONTAINER_DEFAULT)]); + let err = dto_tokens(&dir, "crate::routes", MEMO_DSL).unwrap_err(); + assert!( + err.to_string() + .contains("serde path `default_memo` names an item private"), + "{err}" + ); + // Readable from the source module, where the helper is emitted too. + assert!( + dto_tokens(&dir, "crate::models::memo", MEMO_DSL) + .unwrap() + .contains("default_memo"), + ); +} + +/// B2-01: a DTO that is not built from the source (`add`) drops the container +/// default, so the private fn is never named and nothing is refused. +#[test] +fn private_container_default_fn_is_ignored_when_the_dto_is_not_built() { + let dir = crate_with(&[("models/memo.rs", MEMO_CONTAINER_DEFAULT)]); + let dsl = "MemoSchema from crate::models::memo::Model, add = [(\"extra\": i32)]"; + let tokens = dto_tokens(&dir, "crate::routes", dsl).unwrap(); + assert!(!tokens.contains("default_memo"), "{tokens}"); +} + +/// B2-02 (`HasMany`, picked): the inline type of the related `memos` keeps the +/// memo's `title`, whose private serde default fn is `E0603` at the call site. +#[test] +fn private_serde_default_of_a_picked_has_many_item_is_refused() { + let dir = crate_with(&[ + ( + "models/memo.rs", + "#[sea_orm(table_name = \"memos\")]\npub struct Model {\n pub id: i32,\n pub user_id: i32,\n #[serde(default = \"default_title\")]\n pub title: String,\n}\nfn default_title() -> String {\n String::new()\n}\n", + ), + ( + "models/user.rs", + "pub struct Model {\n pub id: i32,\n pub memos: HasMany,\n}\n", + ), + ]); + let dsl = r#"UserSchema from crate::models::user::Model, pick = ["id", "memos"]"#; + let err = dto_tokens(&dir, "crate::routes", dsl).unwrap_err(); + assert!( + err.to_string() + .contains("serde path `default_title` names an item private"), + "{err}" + ); + assert!(dto_tokens(&dir, "crate::models::memo", dsl).is_ok()); +} + +/// B2-02 (circular `HasOne` back to the parent): the inline `UserSchema_Memo` +/// keeps the memo's `title` with the same private default fn, so it is refused. +#[test] +fn private_serde_default_of_a_circular_inline_type_is_refused() { + let dir = crate_with(&[ + ( + "models/memo.rs", + "#[sea_orm(table_name = \"memos\")]\npub struct Model {\n pub id: i32,\n pub user_id: i32,\n #[serde(default = \"default_title\")]\n pub title: String,\n #[sea_orm(belongs_to = \"super::user::Entity\", from = \"user_id\", to = \"id\", relation_enum = \"Author\")]\n pub user: BelongsTo,\n}\nfn default_title() -> String {\n String::new()\n}\n", + ), + ( + "models/user.rs", + "pub struct Model {\n pub id: i32,\n pub memo: HasOne,\n}\n", + ), + ]); + let dsl = "UserSchema from crate::models::user::Model"; + let err = dto_tokens(&dir, "crate::routes", dsl).unwrap_err(); + assert!( + err.to_string() + .contains("serde path `default_title` names an item private"), + "{err}" + ); +} + +/// B2-04: a `serde(transparent)` source gives a multipart DTO no such +/// attribute, so a multipart DTO with two fields is not refused for it. +#[test] +fn transparent_source_is_not_refused_for_a_multipart_dto() { + let model = "#[serde(transparent)]\n#[sea_orm(table_name = \"memos\")]\npub struct Model {\n pub file: String,\n}\n"; + let dir = crate_with(&[("models/memo.rs", model)]); + let dsl = "UploadDto from crate::models::memo::Model, multipart, add = [(\"title\": String)]"; + assert!(dto_tokens(&dir, "crate::routes", dsl).is_ok()); +} + +/// SM3-02: a `pub(super)` enum reached through `use super::memo::MemoStatus;` +/// is refused by the spanned error, as the written path is, instead of an +/// E0603 in the emitted DTO. +#[test] +fn pub_super_enum_reached_through_an_import_is_refused() { + let dir = crate_with(&[ + ( + "models/memo.rs", + "#[sea_orm(table_name = \"memos\")]\npub struct Model {\n pub id: i32,\n}\npub(super) enum MemoStatus {\n Draft,\n}\n", + ), + ( + "models/dto.rs", + "use super::memo::MemoStatus;\npub struct Model {\n pub id: i32,\n pub status: MemoStatus,\n}\n", + ), + ]); + let dsl = "DtoSchema from crate::models::dto::Model"; + let tokens = dto_tokens(&dir, "crate::routes", dsl).unwrap(); + assert!( + tokens.contains("is private to `crate::models::memo`"), + "{tokens}" + ); +} + +/// SM3-02 (glob): the same `pub(super)` enum reached through `use super::memo::*;`. +#[test] +fn pub_super_enum_reached_through_a_glob_is_refused() { + let dir = crate_with(&[ + ( + "models/memo.rs", + "#[sea_orm(table_name = \"memos\")]\npub struct Model {\n pub id: i32,\n}\npub(super) enum MemoStatus {\n Draft,\n}\n", + ), + ( + "models/dto.rs", + "use super::memo::*;\npub struct Model {\n pub id: i32,\n pub status: MemoStatus,\n}\n", + ), + ]); + let dsl = "DtoSchema from crate::models::dto::Model"; + let error = dto_tokens(&dir, "crate::routes", dsl).unwrap(); + assert!( + error.contains("is private to `crate::models::memo`"), + "{error}" + ); +} + +/// SM4-01 (import): a `pub` enum of a private `mod enums;` reached through an +/// import is refused, as `enums::Status` written in full is. +#[test] +fn pub_enum_of_a_private_module_reached_through_an_import_is_refused() { + let dir = crate_with(&[ + ("models.rs", "mod enums;\npub mod user;\n"), + ("models/enums.rs", "pub enum Status {\n Active,\n}\n"), + ( + "models/user.rs", + "use super::enums::Status;\npub struct Model {\n pub id: i32,\n pub status: Status,\n}\n", + ), + ]); + let dsl = "UserDto from crate::models::user::Model"; + let error = dto_tokens(&dir, "crate::routes", dsl).unwrap(); + assert!(error.contains("is private to"), "{error}"); + // The same type named in full is refused the same way. + let written = crate_with(&[ + ("models.rs", "mod enums;\npub mod user;\n"), + ("models/enums.rs", "pub enum Status {\n Active,\n}\n"), + ( + "models/user.rs", + "pub struct Model {\n pub id: i32,\n pub status: super::enums::Status,\n}\n", + ), + ]); + let written = dto_tokens(&written, "crate::routes", dsl).unwrap(); + assert!(written.contains("is private to"), "{written}"); +} + +/// SM4-01 (local): a `pub` enum of a private `mod user;` (named by its own +/// module, not by an import) is refused from another module. +#[test] +fn pub_local_of_a_private_module_is_refused() { + let dir = crate_with(&[ + ("models.rs", "mod user;\n"), + ( + "models/user.rs", + "pub enum Status {\n Active,\n}\npub struct Model {\n pub id: i32,\n pub status: Status,\n}\n", + ), + ]); + let dsl = "UserDto from crate::models::user::Model"; + let error = dto_tokens(&dir, "crate::routes", dsl).unwrap(); + assert!( + error.contains("`Status` is private to `crate::models::user`"), + "{error}" + ); + // Readable from the module that holds it. + assert!(dto_tokens(&dir, "crate::models", dsl).is_ok()); +} + +/// SM3-03: an empty `name` is no OpenAPI component name, so it is refused at +/// parse time instead of registering the component `""`. +#[test] +fn empty_schema_type_name_is_refused() { + let Err(error) = syn::parse_str::("Dto from User, name = \"\"") else { + panic!("an empty `name` must be refused"); + }; + assert!(error.to_string().contains("must not be empty"), "{error}"); + assert!(syn::parse_str::("Dto from User, name = \"Dto\"").is_ok()); +} diff --git a/crates/vespera_macro/src/schema_macro/type_utils.rs b/crates/vespera_macro/src/schema_macro/type_utils.rs index 26f5100f..89b818cd 100644 --- a/crates/vespera_macro/src/schema_macro/type_utils.rs +++ b/crates/vespera_macro/src/schema_macro/type_utils.rs @@ -4,7 +4,6 @@ use proc_macro2::TokenStream; use quote::quote; -use serde_json; use syn::{GenericArgument, PathArguments, Type}; use super::file_lookup::call_site_module; @@ -13,6 +12,9 @@ use super::module_scope::{ segment_ident, }; +mod type_default; +pub use type_default::get_type_default; + /// SeaORM relation wrapper kind. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SeaOrmRelationKind { @@ -463,25 +465,18 @@ impl TypeResolver<'_> { { return converted; } - // Through a glob-imported first segment too (`resolve_name`). - let resolved = resolve_name(std::slice::from_ref(&name), self.module); - let path = path_tokens(if let Resolved::Path(path) = &resolved { - path - } else { - import - }); - return quote! { #path #args }; + return self.imported(ident, &name, import, &args); } if scope.locals.contains(&name) { - if !scope.item_readable_from(&name, self.call_site.as_deref()) { - return unreadable(ident, self.module); - } - return self.module_qualified(ident, &args); + return self.local_item(scope, &name, ident, &args); } } // A crate-internal glob naming it (`use crate::types::*;` defining // `Value`) wins over the alias, like an explicit import does. if let Resolved::Path(path) = resolve_name(std::slice::from_ref(&name), self.module) { + if let Some(refusal) = refuse_unreadable(ident, &path, self.call_site.as_deref()) { + return refusal; + } if first_named(&path) == Some("sea_orm") && let Some(converted) = self.alias(&name, &segment.arguments, true) { @@ -594,6 +589,51 @@ impl TypeResolver<'_> { root.is_some_and(|root| ALIAS_CRATES.contains(&root.as_str())) } + /// A name the source module imports, emitted as the crate path it resolves + /// to (also through a glob-imported first segment, `resolve_name`), or as + /// the import itself when it resolves to no crate path. Refused when the + /// call site cannot read that path (R41-SM3-02). + fn imported( + &self, + ident: &syn::Ident, + name: &str, + import: &[String], + args: &TokenStream, + ) -> TokenStream { + let resolved = resolve_name(&[name.to_string()], self.module); + if let Resolved::Path(path) = &resolved + && let Some(refusal) = refuse_unreadable(ident, path, self.call_site.as_deref()) + { + return refusal; + } + let path = path_tokens(if let Resolved::Path(path) = &resolved { + path + } else { + import + }); + quote! { #path #args } + } + + /// A name the source module defines itself, emitted through the module path + /// once the item and every module along it can be named from the call site + /// (R41-SM4-01): a `pub` item of a private `mod user;` is not nameable + /// elsewhere. + fn local_item( + &self, + scope: &ModuleScope, + name: &str, + ident: &syn::Ident, + args: &TokenStream, + ) -> TokenStream { + if !scope.item_readable_from(name, self.call_site.as_deref()) { + return unreadable(ident, self.module); + } + let mut item = self.module.to_vec(); + item.push(name.to_string()); + refuse_unreadable(ident, &item, self.call_site.as_deref()) + .unwrap_or_else(|| self.module_qualified(ident, args)) + } + fn module_qualified(&self, ident: &syn::Ident, args: &TokenStream) -> TokenStream { let module = path_tokens(self.module); quote! { #module :: #ident #args } @@ -694,6 +734,21 @@ const SEA_ORM_PRELUDE_NAMES: &[&str] = &[ "BigDecimal", ]; +/// The spanned refusal for a one-name type that resolved to the crate path +/// `path` (through an import, a glob or the module's own items) when the call +/// site cannot read every item along it (R41-SM3-02, R41-SM4-01): the +/// `path()` rule, which checks each module the path crosses. +fn refuse_unreadable( + ident: &syn::Ident, + path: &[String], + call_site: Option<&[String]>, +) -> Option { + (!path_readable_from(path, call_site)).then(|| { + let owner = &path[..path.len().saturating_sub(1)]; + unreadable(ident, owner) + }) +} + /// The error for a name the emitted type cannot read: an item of `owner` that /// is private there, named from the call site (`E0603`). fn unreadable(ident: &syn::Ident, owner: &[String]) -> TokenStream { @@ -855,130 +910,6 @@ pub fn is_primitive_like(ty: &Type) -> bool { is_primitive_or_known_type(&extract_type_name(ty).unwrap_or_default()) } -/// Names whose default below is the value of an ecosystem type (SeaORM / -/// chrono / rust_decimal / uuid), which a crate may also define itself. -const ECOSYSTEM_DEFAULT_NAMES: &[&str] = &[ - "Decimal", - "Uuid", - "Date", - "Time", - "DateTime", - "DateTimeUtc", - "DateTimeWithTimeZone", - "NaiveDate", - "NaiveTime", - "NaiveDateTime", -]; - -/// Whether the path `segments`, written in the module `source_module` (the -/// module of the struct the field is declared in), names an ecosystem type. -/// A crate-local type of the same name (`struct Decimal(i64)`) advertised -/// `"0"` / `"1970-01-01"` before. Without a known module (`source_module` is -/// empty) the name is taken as the ecosystem type, as before. -fn names_ecosystem_type(segments: &[String], source_module: &[String]) -> bool { - use super::module_scope::{Resolved, resolve_name}; - let mut path = match resolve_name(segments, source_module) { - Resolved::Path(path) => path, - Resolved::Unknown => return true, - }; - // A crate-internal re-export (`pub use rust_decimal::Decimal;` in - // `crate::types`, reached through `use crate::types::Decimal;`) names the - // external root one module further in: follow the chain (R34-SM4-L2). - for _ in 0..8 { - let Some((name, module)) = path - .split_last() - .filter(|(_, module)| module.first().map(String::as_str) == Some("crate")) - else { - break; - }; - match resolve_name(std::slice::from_ref(name), module) { - Resolved::Path(next) if next != path => path = next, - _ => break, - } - } - matches!( - path.first().map(String::as_str), - Some("sea_orm" | "chrono" | "rust_decimal" | "uuid" | "time") - ) -} - -/// Get type-specific default value for simple #[serde(default)]. -/// -/// `source_module` is the absolute module (`crate::..`) the field's type is -/// written in; it resolves an ecosystem-looking name (`Decimal`, `Date`). -/// Empty when unknown. -pub fn get_type_default(ty: &Type, source_module: &[String]) -> Option { - match ty { - Type::Path(type_path) => type_path.path.segments.last().and_then(|segment| { - let name = segment.ident.to_string(); - if ECOSYSTEM_DEFAULT_NAMES.contains(&name.as_str()) { - let segments: Vec = type_path - .path - .segments - .iter() - .map(|segment| segment.ident.to_string()) - .collect(); - if !names_ecosystem_type(&segments, source_module) { - return None; - } - } - match name.as_str() { - "String" => Some(serde_json::Value::String(String::new())), - "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "u8" | "u16" | "u32" | "u64" - | "u128" | "usize" => Some(serde_json::Value::Number(serde_json::Number::from(0))), - "Vec" | "VecDeque" | "HashSet" | "BTreeSet" => { - Some(serde_json::Value::Array(Vec::new())) - } - "HashMap" | "BTreeMap" => Some(serde_json::Value::Object(serde_json::Map::new())), - // `rust_decimal` serializes as a string. - "Decimal" => Some(serde_json::Value::String("0".to_string())), - "f32" | "f64" => Some(serde_json::Value::Number( - serde_json::Number::from_f64(0.0) - .unwrap_or_else(|| serde_json::Number::from(0)), - )), - "bool" => Some(serde_json::Value::Bool(false)), - "Option" => Some(serde_json::Value::Null), - "Uuid" => Some(serde_json::Value::String( - "00000000-0000-0000-0000-000000000000".to_string(), - )), - // chrono's epoch as each zone serializes it (`Local` depends - // on the machine: no documented value). - "DateTimeUtc" => Some(serde_json::Value::String( - "1970-01-01T00:00:00Z".to_string(), - )), - "DateTimeWithTimeZone" => Some(serde_json::Value::String( - "1970-01-01T00:00:00+00:00".to_string(), - )), - "DateTime" => match first_generic_type_arg(segment) - .and_then(last_path_segment) - .map(|zone| zone.ident.to_string()) - .as_deref() - { - Some("Utc") => Some(serde_json::Value::String( - "1970-01-01T00:00:00Z".to_string(), - )), - Some("FixedOffset") => Some(serde_json::Value::String( - "1970-01-01T00:00:00+00:00".to_string(), - )), - // The bare name is SeaORM's `NaiveDateTime` alias. - None if segment.arguments.is_none() => { - Some(serde_json::Value::String("1970-01-01T00:00:00".to_string())) - } - _ => None, - }, - "NaiveDateTime" => { - Some(serde_json::Value::String("1970-01-01T00:00:00".to_string())) - } - // `Date` is SeaORM's `NaiveDate` alias. - "NaiveDate" | "Date" => Some(serde_json::Value::String("1970-01-01".to_string())), - "NaiveTime" | "Time" => Some(serde_json::Value::String("00:00:00".to_string())), - _ => None, - } - }), - _ => None, - } -} - #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/vespera_macro/src/schema_macro/type_utils/type_default.rs b/crates/vespera_macro/src/schema_macro/type_utils/type_default.rs new file mode 100644 index 00000000..f40655cd --- /dev/null +++ b/crates/vespera_macro/src/schema_macro/type_utils/type_default.rs @@ -0,0 +1,131 @@ +//! The default value a `#[serde(default)]` field of a type gets without an +//! explicit `default = "fn"` ([`get_type_default`]): the zero of a primitive or +//! ecosystem type, decided by how the type path resolves in its module. + +use syn::Type; + +use super::{first_generic_type_arg, last_path_segment}; + +/// Names whose default below is the value of an ecosystem type (SeaORM / +/// chrono / rust_decimal / uuid), which a crate may also define itself. +const ECOSYSTEM_DEFAULT_NAMES: &[&str] = &[ + "Decimal", + "Uuid", + "Date", + "Time", + "DateTime", + "DateTimeUtc", + "DateTimeWithTimeZone", + "NaiveDate", + "NaiveTime", + "NaiveDateTime", +]; + +/// Whether the path `segments`, written in the module `source_module` (the +/// module of the struct the field is declared in), names an ecosystem type. +/// A crate-local type of the same name (`struct Decimal(i64)`) advertised +/// `"0"` / `"1970-01-01"` before. Without a known module (`source_module` is +/// empty) the name is taken as the ecosystem type, as before. +fn names_ecosystem_type(segments: &[String], source_module: &[String]) -> bool { + use crate::schema_macro::module_scope::{Resolved, resolve_name}; + let mut path = match resolve_name(segments, source_module) { + Resolved::Path(path) => path, + Resolved::Unknown => return true, + }; + // A crate-internal re-export (`pub use rust_decimal::Decimal;` in + // `crate::types`, reached through `use crate::types::Decimal;`) names the + // external root one module further in: follow the chain (R34-SM4-L2). + for _ in 0..8 { + let Some((name, module)) = path + .split_last() + .filter(|(_, module)| module.first().map(String::as_str) == Some("crate")) + else { + break; + }; + match resolve_name(std::slice::from_ref(name), module) { + Resolved::Path(next) if next != path => path = next, + _ => break, + } + } + matches!( + path.first().map(String::as_str), + Some("sea_orm" | "chrono" | "rust_decimal" | "uuid" | "time") + ) +} + +/// Get type-specific default value for simple #[serde(default)]. +/// +/// `source_module` is the absolute module (`crate::..`) the field's type is +/// written in; it resolves an ecosystem-looking name (`Decimal`, `Date`). +/// Empty when unknown. +pub fn get_type_default(ty: &Type, source_module: &[String]) -> Option { + match ty { + Type::Path(type_path) => type_path.path.segments.last().and_then(|segment| { + let name = segment.ident.to_string(); + if ECOSYSTEM_DEFAULT_NAMES.contains(&name.as_str()) { + let segments: Vec = type_path + .path + .segments + .iter() + .map(|segment| segment.ident.to_string()) + .collect(); + if !names_ecosystem_type(&segments, source_module) { + return None; + } + } + match name.as_str() { + "String" => Some(serde_json::Value::String(String::new())), + "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "u8" | "u16" | "u32" | "u64" + | "u128" | "usize" => Some(serde_json::Value::Number(serde_json::Number::from(0))), + "Vec" | "VecDeque" | "HashSet" | "BTreeSet" => { + Some(serde_json::Value::Array(Vec::new())) + } + "HashMap" | "BTreeMap" => Some(serde_json::Value::Object(serde_json::Map::new())), + // `rust_decimal` serializes as a string. + "Decimal" => Some(serde_json::Value::String("0".to_string())), + "f32" | "f64" => Some(serde_json::Value::Number( + serde_json::Number::from_f64(0.0) + .unwrap_or_else(|| serde_json::Number::from(0)), + )), + "bool" => Some(serde_json::Value::Bool(false)), + "Option" => Some(serde_json::Value::Null), + "Uuid" => Some(serde_json::Value::String( + "00000000-0000-0000-0000-000000000000".to_string(), + )), + // chrono's epoch as each zone serializes it (`Local` depends + // on the machine: no documented value). + "DateTimeUtc" => Some(serde_json::Value::String( + "1970-01-01T00:00:00Z".to_string(), + )), + "DateTimeWithTimeZone" => Some(serde_json::Value::String( + "1970-01-01T00:00:00+00:00".to_string(), + )), + "DateTime" => match first_generic_type_arg(segment) + .and_then(last_path_segment) + .map(|zone| zone.ident.to_string()) + .as_deref() + { + Some("Utc") => Some(serde_json::Value::String( + "1970-01-01T00:00:00Z".to_string(), + )), + Some("FixedOffset") => Some(serde_json::Value::String( + "1970-01-01T00:00:00+00:00".to_string(), + )), + // The bare name is SeaORM's `NaiveDateTime` alias. + None if segment.arguments.is_none() => { + Some(serde_json::Value::String("1970-01-01T00:00:00".to_string())) + } + _ => None, + }, + "NaiveDateTime" => { + Some(serde_json::Value::String("1970-01-01T00:00:00".to_string())) + } + // `Date` is SeaORM's `NaiveDate` alias. + "NaiveDate" | "Date" => Some(serde_json::Value::String("1970-01-01".to_string())), + "NaiveTime" | "Time" => Some(serde_json::Value::String("00:00:00".to_string())), + _ => None, + } + }), + _ => None, + } +}