Skip to content

Commit

Permalink
Fix untagged enum unit variant support (#545)
Browse files Browse the repository at this point in the history
Prior to this commit untagged enums with unit variants caused compile
error because they where counted as unnamed field variants. However this
is incorrect behavior and they need to rendered as unit structs that
render to `null` according to serde.

This commit fixes this by allowing use of `#[serde(untagged)]` attribute
on enums with unit type fields.
```rust
 #[derive(ToSchema)]
 #[serde(untagged)]
 enum ComputeRequest {
     Aggregation(AggregationRequest),
     Breakdown,
 }
```
  • Loading branch information
juhaku authored Mar 26, 2023
1 parent 282c1b3 commit 7b505fb
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 15 deletions.
20 changes: 7 additions & 13 deletions utoipa-gen/src/component/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -884,7 +884,7 @@ fn regular_enum_to_tokens<T: self::enum_variant::Variant>(
.map(|variant| (Cow::Borrowed(tag.as_str()), variant)),
)
.to_token_stream(),
SerdeEnumRepr::Untagged => UntaggedEnum.to_token_stream(),
SerdeEnumRepr::Untagged => UntaggedEnum::new().to_token_stream(),
SerdeEnumRepr::AdjacentlyTagged { tag, content } => {
AdjacentlyTaggedEnum::new(enum_values.into_iter().map(|variant| {
(
Expand Down Expand Up @@ -1063,20 +1063,14 @@ impl ComplexEnum<'_> {
.to_token_stream()
}
Fields::Unit => {
let unnamed_struct_features = variant
.attrs
.parse_features::<EnumUnnamedFieldVariantFeatures>()
.into_inner()
let mut unit_features =
features::parse_schema_features_with(&variant.attrs, |input| {
Ok(parse_features!(input as super::features::Title))
})
.unwrap_or_default();
let title = pop_feature!(unit_features => Feature::Title(_));

UnnamedStructSchema {
struct_name: Cow::Borrowed(&*self.enum_name),
attributes: &variant.attrs,
features: Some(unnamed_struct_features),
fields: &Punctuated::default(),
schema_as: None,
}
.to_token_stream()
UntaggedEnum::with_title(title).to_token_stream()
}
}
}
Expand Down
24 changes: 22 additions & 2 deletions utoipa-gen/src/component/schema/enum_variant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse_quote, TypePath};

use crate::component::features::Feature;
use crate::schema_type::SchemaType;
use crate::Array;

Expand Down Expand Up @@ -224,11 +225,30 @@ impl<'t, V: Variant> FromIterator<(Cow<'t, str>, V)> for TaggedEnum<V> {
}
}

pub struct UntaggedEnum;
pub struct UntaggedEnum {
title: Option<Feature>,
}

impl UntaggedEnum {
pub fn new() -> Self {
Self { title: None }
}

pub fn with_title(title: Option<Feature>) -> Self {
Self { title }
}
}

impl ToTokens for UntaggedEnum {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.extend(quote!(utoipa::openapi::schema::empty()));
let title = &self.title;

tokens.extend(quote! {
utoipa::openapi::schema::ObjectBuilder::new()
.nullable(true)
.default(Some(serde_json::Value::Null))
#title
})
}
}

Expand Down
31 changes: 31 additions & 0 deletions utoipa-gen/tests/schema_derive_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4313,3 +4313,34 @@ fn derive_nullable_tuple() {
})
)
}

#[test]
fn derive_unit_type_untagged_enum() {
#[derive(Serialize)]
struct AggregationRequest;

let value = api_doc! {
#[derive(Serialize)]
#[serde(untagged)]
enum ComputeRequest {
Aggregation(AggregationRequest),
Breakdown,
}
};

assert_json_eq!(
value,
json!({
"oneOf": [
{
"$ref": "#/components/schemas/AggregationRequest"
},
{
"type": "object",
"nullable": true,
"default": null,
}
]
})
)
}

0 comments on commit 7b505fb

Please sign in to comment.