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_parser_round30.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":"Parser round 30: a const generic argument of a return-type alias pairs with its const parameter (type Page<const N, T>); error responses document their HeaderMap headers like the success side; a const argument of a nested generic type is part of its component name (Tree<Buf<u8, 4>> vs Tree<Buf<u8, 8>>); a const-only generic definition inlines with its length; a const parameter named in value_type / into attributes is pinned by the instantiation; value_type wins over schema(any) on the same field; flatten module docs state the flattened map limit with an opaque member; test name and assertion fixes.","date":"2026-11-19T00:00:00.000Z"}
2 changes: 1 addition & 1 deletion crates/vespera_macro/src/parser/extractor_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -784,7 +784,7 @@ mod tests {
&[],
)
.expect_err("should flag aliased non-Schema import");
assert!(err.to_string().contains('B'), "{err}");
assert!(err.to_string().contains("`Query<B>`"), "{err}");
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion crates/vespera_macro/src/parser/parameters/shared.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ pub(super) fn newtype_source(struct_item: &syn::ItemStruct) -> Option<Type> {
let constraints = extract_schema_constraints(&field.attrs);
if flags.skip
|| flags.skip_deserializing
|| constraints.is_any()
|| constraints.any_decides()
|| extract_field_codec(&field.attrs).custom_for(SerdeSide::Deserialize)
{
return None;
Expand Down
14 changes: 12 additions & 2 deletions crates/vespera_macro/src/parser/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,8 +495,10 @@ pub fn parse_return_type(
///
/// The error body is found like the success one: `(StatusCode, Json<E>)`,
/// `(HeaderMap, Json<E>)` and header arrays document `E`; a metadata-only
/// error (`StatusCode`, `(StatusCode, HeaderMap)`) has no content. The
/// default error status is `400`; an error that is a `Redirect` /
/// error (`StatusCode`, `(StatusCode, HeaderMap)`) has no content. A
/// `HeaderMap` the error sets (bare or in the tuple) documents `headers` on
/// its status, as the success side does. The default error status is `400`;
/// an error that is a `Redirect` /
/// `NoContent` is keyed like the success side (`3XX` / `204`), never
/// overwriting the success entry. An error documented without a body (an
/// outer `StatusCode`) takes the body of a later (inner) one, and several
Expand All @@ -515,6 +517,10 @@ fn insert_error_response(
"200" => "400",
key => key,
};
let shadows = Shadows {
known_schemas,
struct_definitions,
};
let response = responses
.entry(key.to_string())
.or_insert_with(|| Response {
Expand All @@ -530,6 +536,10 @@ fn insert_error_response(
content: None,
..Default::default()
});
response.headers = response
.headers
.take()
.or_else(|| has_header_map(err_ty, shadows).then(BTreeMap::new));
let Some(content) = response_content(err_ty, known_schemas, struct_definitions) else {
return;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
source: crates/vespera_macro/src/parser/response/tests_parts.rs
assertion_line: 63
assertion_line: 88
expression: responses_json(return_type)
---
{
Expand All @@ -16,6 +16,7 @@ expression: responses_json(return_type)
},
"400": {
"description": "Error response",
"headers": {},
"content": {
"application/json": {
"schema": {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
source: crates/vespera_macro/src/parser/response/tests_parts.rs
assertion_line: 88
expression: responses_json(return_type)
---
{
Expand All @@ -14,6 +15,7 @@ expression: responses_json(return_type)
}
},
"204": {
"description": "Successful response"
"description": "Successful response",
"headers": {}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
source: crates/vespera_macro/src/parser/response/tests_parts.rs
assertion_line: 63
assertion_line: 88
expression: responses_json(return_type)
---
{
Expand All @@ -15,6 +15,7 @@ expression: responses_json(return_type)
}
},
"400": {
"description": "Error response"
"description": "Error response",
"headers": {}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
source: crates/vespera_macro/src/parser/response/tests_parts.rs
assertion_line: 88
expression: responses_json(return_type)
---
{
Expand All @@ -14,6 +15,7 @@ expression: responses_json(return_type)
}
},
"400": {
"description": "Error response"
"description": "Error response",
"headers": {}
}
}
37 changes: 29 additions & 8 deletions crates/vespera_macro/src/parser/result_alias/expansion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,14 +130,7 @@ fn expand_alias(
}
let segment = last_path_segment(ty)?;
let mut args: Vec<Type> = match &segment.arguments {
syn::PathArguments::AngleBracketed(args) => args
.args
.iter()
.filter_map(|arg| match arg {
syn::GenericArgument::Type(ty) => Some(ty.clone()),
_ => None,
})
.collect(),
syn::PathArguments::AngleBracketed(args) => type_arguments(&alias.generics, args),
// `None` (and the `Fn(..)` sugar, which never reaches a return type).
_ => Vec::new(),
};
Expand Down Expand Up @@ -195,3 +188,31 @@ fn expand_alias(
let concrete: Vec<&Type> = values.iter().collect();
Some(substitute_type(&body, &names, &concrete))
}

/// The type arguments of a use site that fill the type parameters of an
/// alias with `generics` (`Page<LIMIT, User>` for `type Page<const MAX:
/// usize, T>`: `[User]`). Lifetimes are skipped on both sides and the rest
/// are paired by position, as rustc pairs them. An argument paired with a
/// const parameter is a value even when it parses as a type (a bare
/// identifier such as `LIMIT`), so it is not a type argument. This mirrors
/// `type_argument_types` in `schema/type_schema/conversion/schema_def.rs`.
fn type_arguments(
generics: &syn::Generics,
args: &syn::AngleBracketedGenericArguments,
) -> Vec<Type> {
let mut params = generics
.params
.iter()
.filter(|param| !matches!(param, syn::GenericParam::Lifetime(_)));
args.args
.iter()
.filter(|arg| !matches!(arg, syn::GenericArgument::Lifetime(_)))
.filter_map(|arg| {
let param = params.next();
let syn::GenericArgument::Type(ty) = arg else {
return None;
};
(!matches!(param, Some(syn::GenericParam::Const(_)))).then(|| ty.clone())
})
.collect()
}
27 changes: 27 additions & 0 deletions crates/vespera_macro/src/parser/result_alias/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,33 @@ fn expand(file_src: &str, ret: &str) -> String {
#[case::wrapper_untouched("type Json = Bad;", "-> Json<u8>", "-> Json < u8 >")]
#[case::too_many_args("type R<T> = Result<T, E>;", "-> R<A, B>", "-> R < A , B >")]
#[case::missing_arg_without_default("type R<T, E> = Result<T, E>;", "-> R<A>", "-> R < A >")]
// A const parameter takes its argument's slot, even when the argument is a
// bare identifier that parses as a type: `LIMIT` is a value, `User` the `T`.
#[case::bare_const_argument_takes_const_slot(
"type Page<const MAX: usize, T> = Json<Vec<T>>;",
"-> Page<LIMIT, User>",
"-> Json < Vec < User > >"
)]
#[case::literal_const_argument_takes_const_slot(
"type Page<const MAX: usize, T> = Json<Vec<T>>;",
"-> Page<3, User>",
"-> Json < Vec < User > >"
)]
#[case::lifetime_before_const_argument(
"type Page<'a, const MAX: usize, T> = Json<Vec<T>>;",
"-> Page<'static, LIMIT, User>",
"-> Json < Vec < User > >"
)]
#[case::const_parameter_after_type_parameter(
"type Page<T, const MAX: usize> = Json<Vec<T>>;",
"-> Page<User, LIMIT>",
"-> Json < Vec < User > >"
)]
#[case::extra_type_argument_after_const_slot_still_counts(
"type Page<const MAX: usize, T> = Json<Vec<T>>;",
"-> Page<LIMIT, A, B>",
"-> Page < LIMIT , A , B >"
)]
#[case::unknown_alias("", "-> ApiResult<User>", "-> ApiResult < User >")]
#[case::self_recursive_stops("type Result<T> = Result<T>;", "-> Result<u8>", "-> Result < u8 >")]
#[case::cycle_back_to_start("type A = B; type B = A;", "-> A", "-> A")]
Expand Down
13 changes: 12 additions & 1 deletion crates/vespera_macro/src/parser/schema/schema_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ pub struct SchemaConstraints {
/// "every-custom-type-must-derive-Schema" checking when the field
/// is intentionally arbitrary / opaque JSON. Bare form
/// `#[schema(any)]` sets it to `true`; an explicit
/// `#[schema(any = false)]` is also accepted.
/// `#[schema(any = false)]` is also accepted. A `value_type` on the same
/// field wins over it (see [`SchemaConstraints::any_decides`]).
pub any: Option<bool>,

/// `#[schema(value_type = T)]`: document the field (or, on a container,
Expand Down Expand Up @@ -161,6 +162,16 @@ impl SchemaConstraints {
self.any == Some(true)
}

/// `true` when `#[schema(any)]` decides the field's schema: it is set and
/// no `value_type` overrides it. The `value_type` wins over `any` (the
/// module doc of `wire_override`), so every check that `any` suppresses
/// (the emitted schema, the garde rules, the leaf assertion, the
/// parameter, the flattened member) asks this instead of [`Self::is_any`].
#[must_use]
pub fn any_decides(&self) -> bool {
self.is_any() && self.value_type.is_none()
}

/// `true` when at least one constraint produces a `garde` runtime rule
/// (excludes pure-OpenAPI annotations such as `example` / `read_only` /
/// `write_only` / `unique_items` / `exclusive_minimum` /
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,8 @@ mod tests {
}

// `extract_tag` / `extract_content` have no raw-token fallback: the
// structured walk matches a qualified key by its last segment.
// structured walk matches a qualified key by its last segment, and the
// malformed-value tests below pin what that walk returns.

/// A qualified `tag` key is matched by its last segment.
#[test]
Expand Down Expand Up @@ -466,7 +467,7 @@ mod tests {
#[case(r#"qualified::tag = "type""#, Some("type"))]
#[case("qualified::tag = value", None)]
#[case("qualified::tag", None)]
fn malformed_tag_fallback_is_exact(#[case] tokens: &str, #[case] expected: Option<&str>) {
fn malformed_tag_is_exact(#[case] tokens: &str, #[case] expected: Option<&str>) {
let attr = create_enum_attr_with_raw_tokens(tokens.parse().unwrap());
assert_eq!(extract_tag(&[attr]).as_deref(), expected);
}
Expand All @@ -475,7 +476,7 @@ mod tests {
#[case(r#"qualified::content = "data""#, Some("data"))]
#[case("qualified::content = value", None)]
#[case("qualified::content", None)]
fn malformed_content_fallback_is_exact(#[case] tokens: &str, #[case] expected: Option<&str>) {
fn malformed_content_is_exact(#[case] tokens: &str, #[case] expected: Option<&str>) {
let attr = create_enum_attr_with_raw_tokens(tokens.parse().unwrap());
assert_eq!(extract_content(&[attr]).as_deref(), expected);
}
Expand Down
15 changes: 7 additions & 8 deletions crates/vespera_macro/src/parser/schema/serde_attrs/fallback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,16 +194,15 @@ mod tests {
);
}

/// Test that the fallback's "default appears as a substring inside
/// another identifier" branch returns None (no false-positive
/// match). Exercises the trailing `None` arm of
/// `scan_default_from_raw_tokens` (substring found, but neither
/// `=` follows nor delimiter chars surround it).
/// Test that a "default" occurring as part of a longer identifier is not
/// a serde default: `scan_default_from_raw_tokens` skips it (the
/// `key_positions` candidates must be whole keys), so the scan finds
/// nothing and returns `None`.
#[test]
fn test_extract_default_substring_in_identifier_is_not_a_match() {
// `field_default` contains "default" but as a suffix of an
// identifier — `before_char` is `_`, not one of the valid
// delimiters, so the standalone check fails.
// `field_default` contains "default" only as a suffix of an
// identifier: the character before it is `_`, which is not a key
// boundary, so it is not a key candidate.
let tokens: TokenStream = "@bogus, field_default"
.parse()
.expect("token stream parses");
Expand Down
4 changes: 2 additions & 2 deletions crates/vespera_macro/src/parser/schema/struct_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,7 @@ fn positional_schema_with(
) -> SchemaRef {
let mut schema_ref =
field_schema_ref(field, constraints, side, known_schemas, struct_definitions);
if !constraints.is_any() {
if !constraints.any_decides() {
apply_garde_rules(
&mut schema_ref,
&field.ty,
Expand Down Expand Up @@ -672,7 +672,7 @@ fn positional_schema_with(
/// constraints `c` (explicit — they win). Shared by object properties and
/// query / path struct parameters.
pub fn apply_field_rules(schema_ref: &mut SchemaRef, field: &syn::Field, c: &SchemaConstraints) {
if !c.is_any() {
if !c.any_decides() {
apply_garde_rules(schema_ref, &field.ty, &extract_garde_rules(&field.attrs), c);
}
if !c.is_empty() {
Expand Down
23 changes: 17 additions & 6 deletions crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,16 @@
//! (`FlatMapAccess`) WITHOUT taking it: it types the outer object's
//! unlisted keys AND every key of a flattened member declared after it
//! (that member takes its keys only later), so in the request view those
//! members' properties must satisfy the map's value schema too;
//! members' properties must satisfy the map's value schema too. The one
//! exception is an opaque member that keeps the object open (see the
//! `allOf` paragraph below): the map's value schema is then not emitted at
//! all, because JSON Schema `additionalProperties` cannot see the keys that
//! member evaluates. The object stays open (nothing is rejected), but the
//! value type of the unlisted keys is not documented;
//! - a flattened `Option<T>` is `None` whenever `T` fails, so it never makes
//! a key required, and in the request view its keys reject nothing;
//! a key required; in the request view its keys reject nothing, except
//! when the outer `deny_unknown_fields` is set and `T` leaves its keys
//! (its properties are then `{not: {}}`, see [`request_member`]);
//! - a flattened unit struct reads nothing;
//! - a flattened externally tagged enum takes the FIRST buffered key naming
//! a variant (`FlatMapDeserializer::deserialize_enum`) and leaves any
Expand All @@ -41,9 +48,13 @@
//! which stays a `$ref` `allOf` member so its component is reused (see
//! `assemble`). Only members whose keys cannot be known (a flattened enum, an
//! unresolvable type) stay `allOf` members — and they keep the merged object
//! open. Such a member's resolved schema is inlined with every object inside
//! it reopened (see `embedded`: closed branches, map variants, `$ref`
//! branches): it never sees the outer keys, so it must not reject them. A
//! open, except in the request view of a `deny_unknown_fields` object when
//! the member leaves its keys (serde rejects them, so they do not open it;
//! see the bullets above). Keeping the object open also drops the flattened
//! map's value schema (see the map bullet). Such a member's resolved schema
//! is inlined with every object inside it reopened (see `embedded`: closed
//! branches, map variants, `$ref` branches): it never sees the outer keys, so
//! it must not reject them. A
//! newtype / transparent wrapper (`allOf: [$ref]`) and a recursive generic
//! instance (its materialised component) are merged like the struct or
//! flattened like the enum they name.
Expand Down Expand Up @@ -123,7 +134,7 @@ pub(super) fn flatten_part(
let optional = optional || omittable;
// `#[schema(value_type = T)]` documents a custom codec's wire shape,
// exactly as on a field that is not flattened.
let custom = constraints.is_any()
let custom = constraints.any_decides()
|| (constraints.value_type.is_none() && codec_applies(&field.attrs, side));
let leaves = !custom && leaves_keys(ty, struct_definitions, WRAPPER_DEPTH);
let schema = if custom {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ fn both_views(src: &str) -> String {
"flatten_two_maps",
"struct Req { #[serde(flatten)] a: HashMap<String, u8>, #[serde(flatten)] b: HashMap<String, u16> }"
)]
// The opaque enum keeps the object open, so the map's value type is not
// documented in either view (`additionalProperties` cannot see the enum's
// keys; see the flatten module doc). Nothing is rejected.
#[case::flatten_map_and_enum(
"flatten_map_and_enum",
"struct Req { id: i32, #[serde(flatten)] kind: Kind, #[serde(flatten)] extra: HashMap<String, String> }"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -669,9 +669,11 @@ fn parse_type_impl(
let const_exprs = const_argument_exprs(parsed.generics_mut(), args);

// Substitute generic parameters with concrete types in
// all fields. A lifetime-only definition (`Borrowed<'a>`)
// has no type to substitute: it is its own component.
if !generic_params.is_empty()
// all fields. A definition with neither a type nor a
// const argument (`Borrowed<'a>`) has nothing to
// substitute: it is its own component. A const-only
// definition (`Matrix<3>`) is inlined with its lengths.
if (!generic_params.is_empty() || !const_exprs.is_empty())
&& generic_params.len() == concrete_types.len()
{
// (named AND tuple fields — tuple structs now map
Expand Down
Loading
Loading