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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .changepacks/changepack_log_schema_round41.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"changes":{"crates/vespera/Cargo.toml":"Patch","crates/vespera_core/Cargo.toml":"Patch","crates/vespera_macro/Cargo.toml":"Patch","crates/vespera_inprocess/Cargo.toml":"Patch","crates/vespera_jni/Cargo.toml":"Patch","libs/vespera-bridge/build.gradle.kts":"Patch","libs/vespera-bridge-gradle-plugin/build.gradle.kts":"Patch"},"note":"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"}
6 changes: 6 additions & 0 deletions crates/vespera_macro/src/schema_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
46 changes: 33 additions & 13 deletions crates/vespera_macro/src/schema_impl/stale.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,17 +90,25 @@ fn module_chain(file: &Path, line: usize) -> Vec<String> {
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<syn::Item> {
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
Expand Down Expand Up @@ -146,11 +154,23 @@ fn schema_type_lines(items: &[syn::Item], ident: &str) -> Vec<usize> {
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<Vec<usize>> {
/// 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<usize> {
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<Vec<usize>> {
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
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions crates/vespera_macro/src/schema_impl/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
}
38 changes: 38 additions & 0 deletions crates/vespera_macro/src/schema_impl/tests_stale.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
36 changes: 32 additions & 4 deletions crates/vespera_macro/src/schema_macro/crate_layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand All @@ -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))
{
Expand Down Expand Up @@ -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]
Expand Down
3 changes: 3 additions & 0 deletions crates/vespera_macro/src/schema_macro/generate_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down
26 changes: 25 additions & 1 deletion crates/vespera_macro/src/schema_macro/generate_type/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -162,8 +178,9 @@ pub(super) fn check_transparent(
attr.parse_args_with(Punctuated::<syn::Meta, syn::Token![,]>::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!(
Expand Down Expand Up @@ -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,
Expand Down
19 changes: 18 additions & 1 deletion crates/vespera_macro/src/schema_macro/inline_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -23,13 +23,25 @@ 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<syn::Error>,
/// Fields to include (excluding circular references)
pub fields: Vec<InlineField>,
/// The target model's `rename_all`, per serde side (camelCase when it
/// has none)
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,
Expand Down Expand Up @@ -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<syn::Error> = None;
if let syn::Fields::Named(fields_named) = &parsed_model.fields {
for field in &fields_named.named {
let field_ident = field.ident.as_ref()?;
Expand Down Expand Up @@ -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(
Expand All @@ -283,6 +299,7 @@ fn generate_inline_type_core(
type_name: inline_type_name,
fields,
rename_all,
serde_path_error,
})
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ fn inline(name: &str, rename_all: &str, fields: Vec<InlineField>) -> InlineRelat
serialize: Some(rename_all.to_string()),
deserialize: Some(rename_all.to_string()),
},
serde_path_error: None,
}
}

Expand Down
6 changes: 6 additions & 0 deletions crates/vespera_macro/src/schema_macro/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,12 @@ impl Parse for SchemaTypeInput {
// name = "CustomSchemaName" - custom OpenAPI schema name
input.parse::<Token![=]>()?;
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" => {
Expand Down
2 changes: 2 additions & 0 deletions crates/vespera_macro/src/schema_macro/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading