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

Enable serializeHierarchy for tuple structs #797

Closed
Closed
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
62 changes: 62 additions & 0 deletions crates/serialize_hierarchy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,17 @@ mod tests {
field: bool,
}

#[derive(Deserialize, Serialize, SerializeHierarchy)]
struct TupleStruct(bool, f32, Inner, Outer);

#[derive(Deserialize, Serialize, SerializeHierarchy)]
struct NestedTupleStruct(bool, Inner, TupleStruct);

#[derive(Deserialize, Serialize, SerializeHierarchy)]
struct OuterWithTupleStruct {
tuple_struct: TupleStruct,
}

#[test]
fn primitive_fields_are_empty() {
assert_eq!(bool::get_fields(), Default::default());
Expand All @@ -72,4 +83,55 @@ mod tests {
["inner".to_string(), "inner.field".to_string()].into()
);
}

#[test]
fn tuple_struct_fields_contain_fields() {
assert_eq!(
TupleStruct::get_fields(),
["0", "1", "2", "2.field", "3", "3.inner", "3.inner.field"]
.map(|s| s.to_string())
.into()
);
}

#[test]
fn nested_tuple_struct_fields_contain_fields() {
assert_eq!(
NestedTupleStruct::get_fields(),
[
"0",
"1",
"1.field",
"2",
"2.0",
"2.1",
"2.2",
"2.2.field",
"2.3",
"2.3.inner",
"2.3.inner.field"
]
.map(|s| s.to_string())
.into()
);
}

#[test]
fn flat_struct_contains_tuple_struct_fields() {
assert_eq!(
OuterWithTupleStruct::get_fields(),
[
"tuple_struct",
"tuple_struct.0",
"tuple_struct.1",
"tuple_struct.2",
"tuple_struct.2.field",
"tuple_struct.3",
"tuple_struct.3.inner",
"tuple_struct.3.inner.field"
]
.map(|s| s.to_string())
.into()
);
}
}
134 changes: 96 additions & 38 deletions crates/serialize_hierarchy_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use proc_macro2::TokenStream;
use proc_macro_error::{abort, proc_macro_error};
use quote::{quote, ToTokens};
use syn::{
parse_macro_input, punctuated::Punctuated, Data, DataStruct, DeriveInput, Generics, Ident, Lit,
Meta, MetaNameValue, NestedMeta, Token, Type, WherePredicate,
parse_macro_input, punctuated::Punctuated, Data, DataStruct, DeriveInput, Generics, Ident,
Index, Lit, Meta, MetaNameValue, NestedMeta, Token, Type, WherePredicate,
};

#[proc_macro_derive(SerializeHierarchy, attributes(serialize_hierarchy))]
Expand Down Expand Up @@ -165,52 +165,91 @@ fn generate_path_serializations(fields: &[&Field]) -> Vec<TokenStream> {
fields
.iter()
.filter(|field| !field.attributes.contains(&FieldAttribute::Leaf))
.map(|field| {
let identifier = &field.identifier;
let pattern = identifier.to_string();
quote! {
#pattern => self.#identifier.serialize_path(suffix, serializer)
.map(|field| match &field.identifier {
IdentOrTupleIndex::Ident(identifier) => {
let pattern = identifier.to_string();
quote! {
#pattern => self.#identifier.serialize_path(suffix, serializer)
}
}
IdentOrTupleIndex::TupleIndex(index) => {
let pattern = index.to_string();
let tuple_accessor = Index::from(*index);
quote! {
#pattern => self.#tuple_accessor.serialize_path(suffix, serializer)
}
}
})
.collect()
}

fn generate_serde_serializations(fields: &[&Field]) -> Vec<TokenStream> {
fields.iter().map(|field| {
let identifier = &field.identifier;
let pattern = identifier.to_string();
quote! {
#pattern => serde::Serialize::serialize(&self.#identifier, serializer).map_err(serialize_hierarchy::Error::SerializationFailed)
}
fields.iter().map(|field|
match &field.identifier {
IdentOrTupleIndex::Ident(identifier) => {
let pattern = identifier.to_string();
quote! {
#pattern => serde::Serialize::serialize(&self.#identifier, serializer).map_err(serialize_hierarchy::Error::SerializationFailed)
}
},
IdentOrTupleIndex::TupleIndex(index) =>{
let pattern = index.to_string();
let tuple_accessor = Index::from(*index);
quote! {
#pattern => serde::Serialize::serialize(&self.#tuple_accessor, serializer).map_err(serialize_hierarchy::Error::SerializationFailed)
}
},
}).collect()
}

fn generate_path_deserializations(fields: &[&Field]) -> Vec<TokenStream> {
fields
.iter()
.filter(|field| !field.attributes.contains(&FieldAttribute::Leaf))
.map(|field| {
let identifier = &field.identifier;
let pattern = identifier.to_string();
quote! {
#pattern => self.#identifier.deserialize_path(suffix, deserializer)
.map(|field| match &field.identifier {
IdentOrTupleIndex::Ident(identifier) => {
let pattern = identifier.to_string();
quote! {
#pattern => self.#identifier.deserialize_path(suffix, deserializer)
}
}
IdentOrTupleIndex::TupleIndex(index) => {
let pattern = index.to_string();
let tuple_accessor = Index::from(*index);
quote! {
#pattern => self.#tuple_accessor.deserialize_path(suffix, deserializer)
}
}
})
.collect()
}

fn generate_serde_deserializations(fields: &[&Field]) -> Vec<TokenStream> {
fields.iter().map(|field| {
let identifier = &field.identifier;
let pattern = identifier.to_string();
let ty = &field.ty;
quote! {
#pattern => {
self.#identifier = <#ty as serde::Deserialize>::deserialize(deserializer).map_err(serialize_hierarchy::Error::DeserializationFailed)?;
Ok(())
}
fields.iter().map(|field|
match &field.identifier {
IdentOrTupleIndex::Ident(identifier) => {
let pattern = identifier.to_string();
let ty = &field.ty;
quote! {
#pattern => {
self.#identifier = <#ty as serde::Deserialize>::deserialize(deserializer).map_err(serialize_hierarchy::Error::DeserializationFailed)?;
Ok(())
}

}
}
},
IdentOrTupleIndex::TupleIndex(index) => {
let pattern = index.to_string();
let tuple_accessor = Index::from(*index);
let ty = &field.ty;
quote! {
#pattern => {
self.#tuple_accessor = <#ty as serde::Deserialize>::deserialize(deserializer).map_err(serialize_hierarchy::Error::DeserializationFailed)?;
Ok(())
}

}
}
}).collect()
}

Expand All @@ -219,7 +258,10 @@ fn generate_path_exists_getters(fields: &[&Field]) -> Vec<TokenStream> {
.iter()
.filter(|field| !field.attributes.contains(&FieldAttribute::Leaf))
.map(|field| {
let pattern = field.identifier.to_string();
let pattern = match &field.identifier {
IdentOrTupleIndex::Ident(identifier) => identifier.to_string(),
IdentOrTupleIndex::TupleIndex(index) => index.to_string(),
};
let ty = &field.ty;
quote! {
#pattern => <#ty as serialize_hierarchy::SerializeHierarchy>::exists(suffix)
Expand All @@ -232,7 +274,10 @@ fn generate_field_exists_getters(fields: &[&Field]) -> Vec<TokenStream> {
fields
.iter()
.map(|field| {
let pattern = field.identifier.to_string();
let pattern = match &field.identifier {
IdentOrTupleIndex::Ident(identifier) => identifier.to_string(),
IdentOrTupleIndex::TupleIndex(index) => index.to_string(),
};
quote! {
#pattern => true
}
Expand All @@ -244,7 +289,10 @@ fn generate_field_chains(fields: &[&Field]) -> Vec<TokenStream> {
fields
.iter()
.map(|field| {
let name_string = field.identifier.to_string();
let name_string = match &field.identifier {
IdentOrTupleIndex::Ident(identifier) => identifier.to_string(),
IdentOrTupleIndex::TupleIndex(index) => index.to_string(),
};
quote! {
fields.insert(format!("{prefix}{}", #name_string));
}
Expand All @@ -257,7 +305,10 @@ fn generate_path_field_chains(fields: &[&Field]) -> Vec<TokenStream> {
.iter()
.filter(|field| !field.attributes.contains(&FieldAttribute::Leaf))
.map(|field| {
let field_name = &field.identifier.to_string();
let field_name = match &field.identifier {
IdentOrTupleIndex::Ident(identifier) => identifier.to_string(),
IdentOrTupleIndex::TupleIndex(index)=>index.to_string(),
};
let ty = &field.ty;
quote! {
<#ty as serialize_hierarchy::SerializeHierarchy>::fill_fields(fields, &format!("{prefix}{}.", #field_name));
Expand Down Expand Up @@ -319,10 +370,16 @@ enum FieldAttribute {
Leaf,
}

#[derive(Debug)]
enum IdentOrTupleIndex {
Ident(Ident),
TupleIndex(usize),
}

#[derive(Debug)]
struct Field {
attributes: HashSet<FieldAttribute>,
identifier: Ident,
identifier: IdentOrTupleIndex,
ty: Type,
}

Expand All @@ -341,7 +398,8 @@ fn read_fields(input: &DataStruct) -> Vec<Field> {
input
.fields
.iter()
.map(|field| {
.enumerate()
.map(|(field_index, field)| {
let attributes = field
.attrs
.iter()
Expand All @@ -367,10 +425,10 @@ fn read_fields(input: &DataStruct) -> Vec<Field> {
}
})
.collect();
let identifier = field
.ident
.clone()
.unwrap_or_else(|| abort!(field, "field has to be named"));
let identifier = field.ident.clone().map_or_else(
|| IdentOrTupleIndex::TupleIndex(field_index),
IdentOrTupleIndex::Ident,
);
let ty = field.ty.clone();
Field {
attributes,
Expand Down
Loading