Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(biome_deserialize_derive): adding a rest attribute #2757

Merged
Merged
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
74 changes: 55 additions & 19 deletions crates/biome_deserialize_macros/src/deserializable_derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,20 +71,34 @@ impl DeriveInput {
}
Data::Struct(data) => {
if data.fields.iter().all(|field| field.ident.is_some()) {
let mut rest_field = None;
let fields = data
.fields
.into_iter()
.filter_map(|field| {
field.ident.map(|ident| (ident, field.attrs, field.ty))
})
.map(|(ident, attrs, ty)| {
.filter_map(|(ident, attrs, ty)| {
let attrs = StructFieldAttrs::try_from(&attrs)
.expect("Could not parse field attributes");
let key = attrs
.rename
.unwrap_or_else(|| Case::Camel.convert(&ident.to_string()));

DeserializableFieldData {
if rest_field.is_some() && attrs.rest {
abort!(
ident,
"Cannot have multiple fields with #[deserializable(rest)]"
)
}
if attrs.rest {
rest_field = Some(ident.clone());
// If rest field, we don't return a field data, because we don't
// want to deserialize into the field directly.
return None;
}

Some(DeserializableFieldData {
bail_on_error: attrs.bail_on_error,
deprecated: attrs.deprecated,
ident,
Expand All @@ -93,12 +107,22 @@ impl DeriveInput {
required: attrs.required,
ty,
validate: attrs.validate,
}
})
})
.collect();

if rest_field.is_some()
&& matches!(attrs.unknown_fields, Some(UnknownFields::Deny))
{
abort!(
rest_field.unwrap(),
"Cannot have a field with #[deserializable(rest)] and #[deserializable(unknown_fields = \"deny\")]"
)
}

DeserializableData::Struct(DeserializableStructData {
fields,
rest_field,
with_validator: attrs.with_validator,
unknown_fields: attrs.unknown_fields.unwrap_or_default(),
})
Expand Down Expand Up @@ -151,6 +175,7 @@ pub struct DeserializableNewtypeData {
#[derive(Debug)]
pub struct DeserializableStructData {
fields: Vec<DeserializableFieldData>,
rest_field: Option<Ident>,
with_validator: bool,
unknown_fields: UnknownFields,
}
Expand Down Expand Up @@ -415,25 +440,36 @@ fn generate_deserializable_struct(
} else {
validator
};
let unknown_key_handler = match data.unknown_fields {
UnknownFields::Warn | UnknownFields::Deny => {
let with_customseverity = if data.unknown_fields == UnknownFields::Warn {
quote! { .with_custom_severity(biome_diagnostics::Severity::Warning) }
} else {
quote! {}
};
quote! {
unknown_key => {
const ALLOWED_KEYS: &[&str] = &[#(#allowed_keys),*];
diagnostics.push(DeserializationDiagnostic::new_unknown_key(
unknown_key,
key.range(),
ALLOWED_KEYS,
)#with_customseverity)
let unknown_key_handler = if let Some(rest_field) = data.rest_field {
quote! {
unknown_key => {
let key_text = Text::deserialize(&key, "", diagnostics)?;
if let Some(value) = Deserializable::deserialize(&value, key_text.text(), diagnostics) {
std::iter::Extend::extend(&mut result.#rest_field, [(key_text, value)]);
}
}
}
} else {
match data.unknown_fields {
UnknownFields::Warn | UnknownFields::Deny => {
let with_customseverity = if data.unknown_fields == UnknownFields::Warn {
quote! { .with_custom_severity(biome_diagnostics::Severity::Warning) }
} else {
quote! {}
};
quote! {
unknown_key => {
const ALLOWED_KEYS: &[&str] = &[#(#allowed_keys),*];
diagnostics.push(DeserializationDiagnostic::new_unknown_key(
unknown_key,
key.range(),
ALLOWED_KEYS,
)#with_customseverity)
}
}
}
UnknownFields::Allow => quote! { _ => {} },
}
UnknownFields::Allow => quote! { _ => {} },
};

let tuple_type = generate_generics_tuple(&generics);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ pub struct StructFieldAttrs {

/// Optional validation function to be called on the field value.
pub validate: Option<Path>,

/// Uses the field as a catch-all for unknown entries in the map
pub rest: bool,
}

#[derive(Clone, Debug, Eq, PartialEq)]
Expand Down Expand Up @@ -62,6 +65,8 @@ impl TryFrom<&Vec<Attribute>> for StructFieldAttrs {
opts.passthrough_name = true;
} else if path.is_ident("bail_on_error") {
opts.bail_on_error = true;
} else if path.is_ident("rest") {
opts.rest = true;
} else {
let path_str = path.to_token_stream().to_string();
return Err(Error::new(
Expand Down
16 changes: 16 additions & 0 deletions crates/biome_deserialize_macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,22 @@ use syn::{parse_macro_input, DeriveInput};
/// pub name: String,
/// }
/// ```
/// ### `rest`
///
/// If present, puts the remaining fields found in the serialized representation
/// into this field. The field must implement `Extend<K, V>` where `K` is the
/// `Text` type and `V` implements `Deserializable`.
///
/// Cannot be used with the container attribute `#[deserializable(unknown_fields = deny)]`
///
/// ```no_test
/// #[derive(Default, Deserializable)]
/// pub struct StructWithRest {
/// pub foo: String,
/// #[deserializable(rest)]
/// pub extra: HashMap<Text, serde_json::Value>,
/// }
/// ```
///
/// ### `validate`
///
Expand Down