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

Fields mandatory unless specified otherwise #145

Closed
wants to merge 5 commits into from
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
18 changes: 9 additions & 9 deletions examples/src/boscop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,24 +61,24 @@ pub struct Control {
pub h: u32,
#[yaserde(attribute)]
pub color: String,
#[yaserde(attribute)]
#[yaserde(attribute, default)]
pub scalef: f32,
#[yaserde(attribute)]
#[yaserde(attribute, default)]
pub scalet: f32,
#[yaserde(attribute)]
#[yaserde(attribute, default)]
pub local_off: bool,
#[yaserde(attribute)]
#[yaserde(attribute, default)]
pub sp: bool,
#[yaserde(attribute)]
#[yaserde(attribute, default)]
pub sr: bool,
pub midi: Vec<Midi>,
#[yaserde(attribute)]
#[yaserde(attribute, default)]
pub response: String,
#[yaserde(attribute)]
#[yaserde(attribute, default)]
pub inverted: String,
#[yaserde(attribute)]
#[yaserde(attribute, default)]
pub centered: String,
#[yaserde(attribute)]
#[yaserde(attribute, default)]
pub norollover: String,
}

Expand Down
1 change: 1 addition & 0 deletions yaserde/tests/flatten.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ fn flatten_name_in_unknown_child() {
}

#[derive(PartialEq, Debug, YaDeserialize, YaSerialize)]
#[yaserde(default)]
enum Value {
Foo(FooStruct),
}
Expand Down
9 changes: 6 additions & 3 deletions yaserde/tests/namespace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,8 @@ fn enum_namespace() {
#[yaserde(
rename = "root",
prefix = "ns",
namespace = "ns: http://www.sample.com/ns/domain"
namespace = "ns: http://www.sample.com/ns/domain",
default
)]
pub enum XmlStruct {
#[yaserde(prefix = "ns")]
Expand Down Expand Up @@ -362,7 +363,8 @@ fn enum_multi_namespaces() {
#[yaserde(
rename = "root",
namespace = "ns1: http://www.sample.com/ns/domain1",
namespace = "ns2: http://www.sample.com/ns/domain2"
namespace = "ns2: http://www.sample.com/ns/domain2",
default
)]
pub enum XmlStruct {
#[yaserde(prefix = "ns1")]
Expand Down Expand Up @@ -405,7 +407,8 @@ fn enum_attribute_namespace() {
#[yaserde(
rename = "rootA",
prefix = "ns",
namespace = "ns: http://www.sample.com/ns/domain"
namespace = "ns: http://www.sample.com/ns/domain",
default
)]
pub enum XmlStruct {
#[yaserde(prefix = "ns")]
Expand Down
14 changes: 13 additions & 1 deletion yaserde_derive/src/common/attribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,18 @@ fn get_value(iter: &mut IntoIter) -> Option<String> {
}
}

fn get_value_or_default(iter: &mut IntoIter) -> Option<String> {
match (iter.next(), iter.next()) {
(Some(TokenTree::Punct(operator)), Some(TokenTree::Literal(value))) => if operator.as_char() == '=' {
Some(value.to_string().replace('"', ""))
} else {
None
},
(None, None) => Some(String::new()),
_ => None
}
}

impl YaSerdeAttribute {
pub fn parse(attrs: &[Attribute]) -> YaSerdeAttribute {
let mut attribute = false;
Expand All @@ -57,7 +69,7 @@ impl YaSerdeAttribute {
attribute = true;
}
"default" => {
default = get_value(&mut attr_iter);
default = get_value_or_default(&mut attr_iter);
}
"default_namespace" => {
default_namespace = get_value(&mut attr_iter);
Expand Down
16 changes: 10 additions & 6 deletions yaserde_derive/src/common/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,16 @@ impl YaSerdeField {
self.syn_field.span()
}

pub fn get_default_function(&self) -> Option<Ident> {
self
.attributes
.default
.as_ref()
.map(|default| Ident::new(default, self.get_span()))
pub fn get_default_function(&self) -> Option<TokenStream> {
self.attributes.default.as_ref().map(|default| {
if default != "" {
let f = Ident::new(default, self.get_span());
quote!( #f )
} else {
let field_type = &self.syn_field.ty;
quote!(<#field_type as std::default::Default>::default)
}
})
}

pub fn get_skip_serializing_if_function(&self) -> Option<Ident> {
Expand Down
20 changes: 19 additions & 1 deletion yaserde_derive/src/de/build_default_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,24 @@ use crate::common::YaSerdeField;
use proc_macro2::TokenStream;
use quote::quote;

pub fn build_value(field: &YaSerdeField, field_type: Option<TokenStream>) -> Option<TokenStream> {
let label = field.get_value_label();

let value = field
.get_default_function()
.map(|default_function| quote!(::std::option::Option::Some(#default_function())))
.unwrap_or_else(|| quote!(::std::option::Option::None));

let field_type = field_type
.map(|field_type| quote!(: std::option::Option<#field_type>))
.unwrap_or_default();

Some(quote! {
#[allow(unused_mut)]
let mut #label #field_type = #value;
})
}

pub fn build_default_value(
field: &YaSerdeField,
field_type: Option<TokenStream>,
Expand All @@ -12,7 +30,7 @@ pub fn build_default_value(
let default_value = field
.get_default_function()
.map(|default_function| quote!(#default_function()))
.unwrap_or_else(|| quote!(#value));
.unwrap_or_else(|| value);

let field_type = field_type
.map(|field_type| quote!(: #field_type))
Expand Down
16 changes: 13 additions & 3 deletions yaserde_derive/src/de/expand_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,18 @@ pub fn parse(

let flatten = root_attributes.flatten;

let variant_not_detected = if let Some(default_function) = &root_attributes.default {
if default_function == "" {
quote!(::std::result::Result::Ok(<#name as ::std::default::Default>::default()))
} else {
quote!(#default_function())
}
} else {
quote!(::std::result::Result::Err(
"Failed to match variant in '".to_string() + stringify!(#name) + "'"
))
};

quote! {
impl ::yaserde::YaDeserialize for #name {
#[allow(unused_variables)]
Expand Down Expand Up @@ -91,9 +103,7 @@ pub fn parse(
::yaserde::__derive_debug!("Enum {} @ {}: success", stringify!(#name), start_depth);
match enum_value {
::std::option::Option::Some(value) => ::std::result::Result::Ok(value),
::std::option::Option::None => {
::std::result::Result::Ok(<#name as ::std::default::Default>::default())
},
::std::option::Option::None => #variant_not_detected,
}
}
}
Expand Down
48 changes: 31 additions & 17 deletions yaserde_derive/src/de/expand_struct.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::common::{Field, YaSerdeAttribute, YaSerdeField};
use crate::de::build_default_value::build_default_value;
use crate::de::build_default_value::{build_default_value, build_value};
use heck::ToUpperCamelCase;
use proc_macro2::{Span, TokenStream};
use quote::quote;
Expand All @@ -23,11 +23,7 @@ pub fn parse(
.iter()
.map(|field| YaSerdeField::new(field.clone()))
.filter_map(|field| match field.get_type() {
Field::FieldStruct { struct_name } => build_default_value(
&field,
Some(quote!(#struct_name)),
quote!(<#struct_name as ::std::default::Default>::default()),
),
Field::FieldStruct { struct_name } => build_value(&field, Some(quote!(#struct_name))),
Field::FieldOption { .. } => {
build_default_value(&field, None, quote!(::std::option::Option::None))
}
Expand All @@ -50,11 +46,17 @@ pub fn parse(
)
}
},
string_type @ Field::FieldString if field.is_text_content() => {
let type_token: TokenStream = string_type.into();
build_default_value(
&field,
Some(type_token),
quote!(::std::string::String::new()),
)
}
simple_type => {
let type_token: TokenStream = simple_type.into();
let value_builder = quote!(<#type_token as ::std::default::Default>::default());

build_default_value(&field, Some(type_token), value_builder)
build_value(&field, Some(type_token))
}
})
.collect();
Expand Down Expand Up @@ -184,12 +186,17 @@ pub fn parse(
};

match field.get_type() {
Field::FieldStruct { struct_name } => visit_struct(struct_name, quote! { = value }),
Field::FieldStruct { struct_name } => {
visit_struct(struct_name, quote! { = ::std::option::Option::Some(value) })
}
Field::FieldOption { data_type } => {
visit_sub(data_type, quote! { = ::std::option::Option::Some(value) })
}
Field::FieldVec { data_type } => visit_sub(data_type, quote! { .push(value) }),
simple_type => visit_simple(simple_type, quote! { = value }),
string_type @ Field::FieldString if field.is_text_content() => {
visit_simple(string_type, quote! { = value })
}
simple_type => visit_simple(simple_type, quote! { = ::std::option::Option::Some(value) }),
}
})
.collect();
Expand All @@ -204,7 +211,7 @@ pub fn parse(

match field.get_type() {
Field::FieldStruct { .. } => Some(quote! {
#value_label = ::yaserde::de::from_str(&unused_xml_elements)?;
#value_label = Some(::yaserde::de::from_str(&unused_xml_elements)?);
}),
Field::FieldOption { data_type } => match *data_type {
Field::FieldStruct { .. } => Some(quote! {
Expand Down Expand Up @@ -243,7 +250,7 @@ pub fn parse(
Some(quote! {
for attr in attributes {
if attr.name.local_name == #label_name {
#label = attr.value.to_owned();
#label = Some(attr.value.to_owned());
}
}
})
Expand Down Expand Up @@ -277,8 +284,10 @@ pub fn parse(
visit_sub(data_type, quote! { = ::std::option::Option::Some(value) })
}
Field::FieldVec { .. } => unimplemented!(),
Field::FieldStruct { struct_name } => visit_struct(struct_name, quote! { = value }),
simple_type => visit_simple(simple_type, quote! { = value }),
Field::FieldStruct { struct_name } => {
visit_struct(struct_name, quote! { = ::std::option::Option::Some(value) })
}
simple_type => visit_simple(simple_type, quote! { = ::std::option::Option::Some(value) }),
}
})
.collect();
Expand Down Expand Up @@ -309,7 +318,7 @@ pub fn parse(
Field::FieldStruct { .. } | Field::FieldVec { .. } => None,
simple_type => {
let type_token = TokenStream::from(simple_type);
set_text(&quote! { #type_token::from_str(text_content).unwrap() })
set_text(&quote! { Some(#type_token::from_str(text_content).unwrap()) })
}
}
})
Expand All @@ -323,7 +332,12 @@ pub fn parse(
let label = &field.label();
let value_label = field.get_value_label();

quote! { #label: #value_label, }
match field.get_type() {
Field::FieldVec {..} => quote! { #label: #value_label, },
Field::FieldOption {..} => quote! { #label: #value_label, },
Field::FieldString if field.is_text_content() => quote! { #label: #value_label, },
_ => quote! { #label: #value_label.ok_or_else(|| "Missing field '".to_string() + stringify!(#label) + "'")?, }
}
})
.collect();

Expand Down
3 changes: 2 additions & 1 deletion yaserde_derive/src/ser/expand_struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,8 @@ pub fn serialize(
writer.write(data_event).map_err(|e| e.to_string())?;
)),
_ => Some(quote!(
let data_event = ::yaserde::__xml::writer::XmlEvent::characters(&self.#label);
let s = self.#label.to_string();
let data_event = ::yaserde::__xml::writer::XmlEvent::characters(&s);
writer.write(data_event).map_err(|e| e.to_string())?;
)),
};
Expand Down