Format in rfc style

This commit is contained in:
David Tolnay 2017-04-18 14:23:21 -07:00
parent c567e749ef
commit 7a7d4c6364
No known key found for this signature in database
GPG Key ID: F9BA143B95FF6D82
12 changed files with 180 additions and 149 deletions

5
.gitignore vendored
View File

@ -1,3 +1,4 @@
Cargo.lock
target
target/
**/*.rs.bk
*.sw[po]
Cargo.lock

View File

@ -1039,7 +1039,8 @@ impl<'de> Visitor<'de> for OsStringVisitor {
match try!(data.variant()) {
(OsStringKind::Windows, v) => {
v.newtype_variant::<Vec<u16>>().map(|vec| OsString::from_wide(&vec))
v.newtype_variant::<Vec<u16>>()
.map(|vec| OsString::from_wide(&vec))
}
(OsStringKind::Unix, _) => Err(Error::custom("cannot deserialize Unix OS string on Windows",),),
}
@ -1151,7 +1152,7 @@ where
impl<'de, T> Deserialize<'de> for RefCell<T>
where
T: Deserialize<'de>
T: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<RefCell<T>, D::Error>
where

View File

@ -922,7 +922,8 @@ where
Second<I::Item>: Debug,
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.debug_struct("MapDeserializer")
formatter
.debug_struct("MapDeserializer")
.field("iter", &self.iter)
.field("value", &self.value)
.field("count", &self.count)

View File

@ -191,7 +191,8 @@ pub mod size_hint {
use lib::*;
pub fn from_bounds<I>(iter: &I) -> Option<usize>
where I: Iterator
where
I: Iterator,
{
helper(iter.size_hint())
}
@ -202,9 +203,7 @@ pub mod size_hint {
fn helper(bounds: (usize, Option<usize>)) -> Option<usize> {
match bounds {
(lower, Some(upper)) if lower == upper => {
Some(upper)
}
(lower, Some(upper)) if lower == upper => Some(upper),
_ => None,
}
}
@ -1026,10 +1025,7 @@ mod content {
type Error = E;
type Variant = VariantDeserializer<Self::Error>;
fn variant_seed<V>(
self,
seed: V,
) -> Result<(V::Value, VariantDeserializer<E>), Self::Error>
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), E>
where
V: de::DeserializeSeed<'de>,
{

View File

@ -169,7 +169,11 @@ where
generics
}
pub fn with_self_bound(cont: &Container, generics: &syn::Generics, bound: &syn::Path) -> syn::Generics {
pub fn with_self_bound(
cont: &Container,
generics: &syn::Generics,
bound: &syn::Path,
) -> syn::Generics {
let mut generics = generics.clone();
generics
.where_clause

View File

@ -288,7 +288,7 @@ fn deserialize_tuple(
None
};
let visit_seq = Stmts(deserialize_seq(&type_path, params, fields, false, cattrs),);
let visit_seq = Stmts(deserialize_seq(&type_path, params, fields, false, cattrs));
let visitor_expr = quote! {
__Visitor {
@ -488,7 +488,7 @@ fn deserialize_struct(
None => format!("struct {}", params.type_name()),
};
let visit_seq = Stmts(deserialize_seq(&type_path, params, fields, true, cattrs),);
let visit_seq = Stmts(deserialize_seq(&type_path, params, fields, true, cattrs));
let (field_visitor, fields_stmt, visit_map) =
deserialize_struct_visitor(type_path, params, fields, cattrs);
@ -618,8 +618,7 @@ fn deserialize_externally_tagged_enum(
let variant_visitor = Stmts(deserialize_generated_identifier(variant_names_idents, cattrs, true),);
// Match arms to extract a variant from a string
let variant_arms =
variants
let variant_arms = variants
.iter()
.enumerate()
.filter(|&(_, variant)| !variant.attrs.skip_deserializing())
@ -627,8 +626,7 @@ fn deserialize_externally_tagged_enum(
|(i, variant)| {
let variant_name = field_i(i);
let block =
Match(deserialize_externally_tagged_variant(params, variant, cattrs),);
let block = Match(deserialize_externally_tagged_variant(params, variant, cattrs),);
quote! {
(__Field::#variant_name, __variant) => #block
@ -1056,22 +1054,10 @@ fn deserialize_externally_tagged_variant(
deserialize_externally_tagged_newtype_variant(variant_ident, params, &variant.fields[0])
}
Style::Tuple => {
deserialize_tuple(
Some(variant_ident),
params,
&variant.fields,
cattrs,
None,
)
deserialize_tuple(Some(variant_ident), params, &variant.fields, cattrs, None)
}
Style::Struct => {
deserialize_struct(
Some(variant_ident),
params,
&variant.fields,
cattrs,
None,
)
deserialize_struct(Some(variant_ident), params, &variant.fields, cattrs, None)
}
}
}
@ -1223,7 +1209,7 @@ fn deserialize_generated_identifier(
(Some(ignore_variant), Some(fallthrough))
};
let visitor_impl = Stmts(deserialize_identifier(this, &fields, is_variant, fallthrough));
let visitor_impl = Stmts(deserialize_identifier(this, &fields, is_variant, fallthrough),);
quote_block! {
#[allow(non_camel_case_types)]
@ -1289,7 +1275,7 @@ fn deserialize_custom_identifier(
let names_idents: Vec<_> = ordinary
.iter()
.map(|variant| (variant.attrs.name().deserialize_name(), variant.ident.clone()))
.map(|variant| (variant.attrs.name().deserialize_name(), variant.ident.clone()),)
.collect();
let names = names_idents.iter().map(|&(ref name, _)| name);
@ -1308,8 +1294,9 @@ fn deserialize_custom_identifier(
Some(fields)
};
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params);
let visitor_impl = Stmts(deserialize_identifier(this.clone(), &names_idents, is_variant, fallthrough));
let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = split_with_de_lifetime(params,);
let visitor_impl =
Stmts(deserialize_identifier(this.clone(), &names_idents, is_variant, fallthrough),);
quote_block! {
#names_const

View File

@ -273,11 +273,7 @@ fn serialize_struct(params: &Parameters, fields: &[Field], cattrs: &attr::Contai
}
}
fn serialize_enum(
params: &Parameters,
variants: &[Variant],
cattrs: &attr::Container,
) -> Fragment {
fn serialize_enum(params: &Parameters, variants: &[Variant], cattrs: &attr::Container) -> Fragment {
assert!(variants.len() as u64 <= u32::MAX as u64);
let self_var = &params.self_var;

View File

@ -87,8 +87,7 @@ impl<'a> Body<'a> {
pub fn all_fields(&'a self) -> Box<Iterator<Item = &'a Field<'a>> + 'a> {
match *self {
Body::Enum(ref variants) => {
Box::new(variants.iter()
.flat_map(|variant| variant.fields.iter()))
Box::new(variants.iter().flat_map(|variant| variant.fields.iter()))
}
Body::Struct(_, ref fields) => Box::new(fields.iter()),
}
@ -100,8 +99,10 @@ impl<'a> Body<'a> {
}
fn enum_from_ast<'a>(cx: &Ctxt, variants: &'a [syn::Variant]) -> Vec<Variant<'a>> {
variants.iter()
.map(|variant| {
variants
.iter()
.map(
|variant| {
let (style, fields) = struct_from_ast(cx, &variant.data);
Variant {
ident: variant.ident.clone(),
@ -109,7 +110,8 @@ fn enum_from_ast<'a>(cx: &Ctxt, variants: &'a [syn::Variant]) -> Vec<Variant<'a>
style: style,
fields: fields,
}
})
},
)
.collect()
}
@ -125,14 +127,17 @@ fn struct_from_ast<'a>(cx: &Ctxt, data: &'a syn::VariantData) -> (Style, Vec<Fie
}
fn fields_from_ast<'a>(cx: &Ctxt, fields: &'a [syn::Field]) -> Vec<Field<'a>> {
fields.iter()
fields
.iter()
.enumerate()
.map(|(i, field)| {
.map(
|(i, field)| {
Field {
ident: field.ident.clone(),
attrs: attr::Field::from_ast(cx, i, field),
ty: &field.ty,
}
})
},
)
.collect()
}

View File

@ -41,7 +41,8 @@ impl<'c, T> Attr<'c, T> {
fn set(&mut self, value: T) {
if self.value.is_some() {
self.cx.error(format!("duplicate serde attribute `{}`", self.name));
self.cx
.error(format!("duplicate serde attribute `{}`", self.name));
} else {
self.value = Some(value);
}
@ -227,8 +228,10 @@ impl Container {
default.set(Default::Default);
}
_ => {
cx.error("#[serde(default)] can only be used on structs \
with named fields")
cx.error(
"#[serde(default)] can only be used on structs \
with named fields",
)
}
}
}
@ -241,8 +244,10 @@ impl Container {
default.set(Default::Path(path));
}
_ => {
cx.error("#[serde(default = \"...\")] can only be used \
on structs with named fields")
cx.error(
"#[serde(default = \"...\")] can only be used \
on structs with named fields",
)
}
}
}
@ -299,8 +304,10 @@ impl Container {
content.set(s);
}
syn::Body::Struct(_) => {
cx.error("#[serde(content = \"...\")] can only be used on \
enums")
cx.error(
"#[serde(content = \"...\")] can only be used on \
enums",
)
}
}
}
@ -431,8 +438,10 @@ fn decide_tag(
syn::VariantData::Unit => {}
syn::VariantData::Tuple(ref fields) => {
if fields.len() != 1 {
cx.error("#[serde(tag = \"...\")] cannot be used with tuple \
variants");
cx.error(
"#[serde(tag = \"...\")] cannot be used with tuple \
variants",
);
break;
}
}
@ -446,7 +455,7 @@ fn decide_tag(
EnumTag::External // doesn't matter, will error
}
(false, None, Some(_)) => {
cx.error("#[serde(tag = \"...\", content = \"...\")] must be used together");
cx.error("#[serde(tag = \"...\", content = \"...\")] must be used together",);
EnumTag::External
}
(true, None, Some(_)) => {
@ -460,7 +469,7 @@ fn decide_tag(
}
}
(true, Some(_), Some(_)) => {
cx.error("untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]");
cx.error("untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]",);
EnumTag::External
}
}
@ -475,7 +484,7 @@ fn decide_identifier(
match (&item.body, field_identifier.get(), variant_identifier.get()) {
(_, false, false) => Identifier::No,
(_, true, true) => {
cx.error("`field_identifier` and `variant_identifier` cannot both be set");
cx.error("`field_identifier` and `variant_identifier` cannot both be set",);
Identifier::No
}
(&syn::Body::Struct(_), true, false) => {
@ -773,7 +782,13 @@ impl Field {
if let Ok(borrowable) = borrowable_lifetimes(cx, &ident, &field.ty) {
for lifetime in &lifetimes {
if !borrowable.contains(lifetime) {
cx.error(format!("field `{}` does not have lifetime {}", ident, lifetime.ident));
cx.error(
format!(
"field `{}` does not have lifetime {}",
ident,
lifetime.ident
),
);
}
}
borrowed_lifetimes.set(lifetimes);
@ -789,7 +804,7 @@ impl Field {
}
MetaItem(ref meta_item) => {
cx.error(format!("unknown serde field attribute `{}`", meta_item.name()));
cx.error(format!("unknown serde field attribute `{}`", meta_item.name()),);
}
Literal(_) => {
@ -909,12 +924,14 @@ impl Field {
type SerAndDe<T> = (Option<T>, Option<T>);
fn get_ser_and_de<T, F>(cx: &Ctxt,
fn get_ser_and_de<T, F>(
cx: &Ctxt,
attr_name: &'static str,
items: &[syn::NestedMetaItem],
f: F)
-> Result<SerAndDe<T>, ()>
where F: Fn(&Ctxt, &str, &str, &syn::Lit) -> Result<T, ()>
f: F,
) -> Result<SerAndDe<T>, ()>
where
F: Fn(&Ctxt, &str, &str, &syn::Lit) -> Result<T, ()>,
{
let mut ser_item = Attr::none(cx, attr_name);
let mut de_item = Attr::none(cx, attr_name);
@ -934,9 +951,13 @@ fn get_ser_and_de<T, F>(cx: &Ctxt,
}
_ => {
cx.error(format!("malformed {0} attribute, expected `{0}(serialize = ..., \
cx.error(
format!(
"malformed {0} attribute, expected `{0}(serialize = ..., \
deserialize = ...)`",
attr_name));
attr_name
),
);
return Err(());
}
}
@ -949,9 +970,10 @@ fn get_renames(cx: &Ctxt, items: &[syn::NestedMetaItem]) -> Result<SerAndDe<Stri
get_ser_and_de(cx, "rename", items, get_string_from_lit)
}
fn get_where_predicates(cx: &Ctxt,
items: &[syn::NestedMetaItem])
-> Result<SerAndDe<Vec<syn::WherePredicate>>, ()> {
fn get_where_predicates(
cx: &Ctxt,
items: &[syn::NestedMetaItem],
) -> Result<SerAndDe<Vec<syn::WherePredicate>>, ()> {
get_ser_and_de(cx, "bound", items, parse_lit_into_where)
}
@ -962,17 +984,22 @@ pub fn get_serde_meta_items(attr: &syn::Attribute) -> Option<Vec<syn::NestedMeta
}
}
fn get_string_from_lit(cx: &Ctxt,
fn get_string_from_lit(
cx: &Ctxt,
attr_name: &str,
meta_item_name: &str,
lit: &syn::Lit)
-> Result<String, ()> {
lit: &syn::Lit,
) -> Result<String, ()> {
if let syn::Lit::Str(ref s, _) = *lit {
Ok(s.clone())
} else {
cx.error(format!("expected serde {} attribute to be a string: `{} = \"...\"`",
cx.error(
format!(
"expected serde {} attribute to be a string: `{} = \"...\"`",
attr_name,
meta_item_name));
meta_item_name
),
);
Err(())
}
}
@ -982,11 +1009,12 @@ fn parse_lit_into_path(cx: &Ctxt, attr_name: &str, lit: &syn::Lit) -> Result<syn
syn::parse_path(&string).map_err(|err| cx.error(err))
}
fn parse_lit_into_where(cx: &Ctxt,
fn parse_lit_into_where(
cx: &Ctxt,
attr_name: &str,
meta_item_name: &str,
lit: &syn::Lit)
-> Result<Vec<syn::WherePredicate>, ()> {
lit: &syn::Lit,
) -> Result<Vec<syn::WherePredicate>, ()> {
let string = try!(get_string_from_lit(cx, attr_name, meta_item_name, lit));
if string.is_empty() {
return Ok(Vec::new());
@ -994,26 +1022,28 @@ fn parse_lit_into_where(cx: &Ctxt,
let where_string = format!("where {}", string);
syn::parse_where_clause(&where_string).map(|wh| wh.predicates).map_err(|err| cx.error(err))
syn::parse_where_clause(&where_string)
.map(|wh| wh.predicates)
.map_err(|err| cx.error(err))
}
fn parse_lit_into_ty(cx: &Ctxt,
attr_name: &str,
lit: &syn::Lit)
-> Result<syn::Ty, ()> {
fn parse_lit_into_ty(cx: &Ctxt, attr_name: &str, lit: &syn::Lit) -> Result<syn::Ty, ()> {
let string = try!(get_string_from_lit(cx, attr_name, attr_name, lit));
syn::parse_type(&string).map_err(|_| {
cx.error(format!("failed to parse type: {} = {:?}", attr_name, string))
})
syn::parse_type(&string).map_err(
|_| {
cx.error(format!("failed to parse type: {} = {:?}", attr_name, string),)
},
)
}
// Parses a string literal like "'a + 'b + 'c" containing a nonempty list of
// lifetimes separated by `+`.
fn parse_lit_into_lifetimes(cx: &Ctxt,
fn parse_lit_into_lifetimes(
cx: &Ctxt,
attr_name: &str,
lit: &syn::Lit)
-> Result<BTreeSet<syn::Lifetime>, ()> {
lit: &syn::Lit,
) -> Result<BTreeSet<syn::Lifetime>, ()> {
let string = try!(get_string_from_lit(cx, attr_name, attr_name, lit));
if string.is_empty() {
cx.error("at least one lifetime must be borrowed");
@ -1035,7 +1065,7 @@ fn parse_lit_into_lifetimes(cx: &Ctxt,
return Ok(set);
}
}
Err(cx.error(format!("failed to parse borrowed lifetimes: {:?}", string)))
Err(cx.error(format!("failed to parse borrowed lifetimes: {:?}", string)),)
}
// Whether the type looks like it might be `std::borrow::Cow<T>` where elem="T".
@ -1079,10 +1109,8 @@ fn is_cow(ty: &syn::Ty, elem: &str) -> bool {
return false;
}
};
seg.ident == "Cow"
&& params.lifetimes.len() == 1
&& params.types == vec![syn::parse_type(elem).unwrap()]
&& params.bindings.is_empty()
seg.ident == "Cow" && params.lifetimes.len() == 1 &&
params.types == vec![syn::parse_type(elem).unwrap()] && params.bindings.is_empty()
}
// Whether the type looks like it might be `&T` where elem="T". This can have
@ -1108,8 +1136,8 @@ fn is_cow(ty: &syn::Ty, elem: &str) -> bool {
fn is_rptr(ty: &syn::Ty, elem: &str) -> bool {
match *ty {
syn::Ty::Rptr(Some(_), ref mut_ty) => {
mut_ty.mutability == syn::Mutability::Immutable
&& mut_ty.ty == syn::parse_type(elem).unwrap()
mut_ty.mutability == syn::Mutability::Immutable &&
mut_ty.ty == syn::parse_type(elem).unwrap()
}
_ => false,
}
@ -1122,14 +1150,15 @@ fn is_rptr(ty: &syn::Ty, elem: &str) -> bool {
//
// This is used when there is an explicit or implicit `#[serde(borrow)]`
// attribute on the field so there must be at least one borrowable lifetime.
fn borrowable_lifetimes(cx: &Ctxt,
fn borrowable_lifetimes(
cx: &Ctxt,
name: &str,
ty: &syn::Ty)
-> Result<BTreeSet<syn::Lifetime>, ()> {
ty: &syn::Ty,
) -> Result<BTreeSet<syn::Lifetime>, ()> {
let mut lifetimes = BTreeSet::new();
collect_lifetimes(ty, &mut lifetimes);
if lifetimes.is_empty() {
Err(cx.error(format!("field `{}` has no lifetimes to borrow", name)))
Err(cx.error(format!("field `{}` has no lifetimes to borrow", name)),)
} else {
Ok(lifetimes)
}

View File

@ -97,10 +97,12 @@ impl FromStr for RenameRule {
#[test]
fn rename_variants() {
for &(original, lower, camel, snake, screaming, kebab) in
&[("Outcome", "outcome", "outcome", "outcome", "OUTCOME", "outcome"),
&[
("Outcome", "outcome", "outcome", "outcome", "OUTCOME", "outcome"),
("VeryTasty", "verytasty", "veryTasty", "very_tasty", "VERY_TASTY", "very-tasty"),
("A", "a", "a", "a", "A", "a"),
("Z42", "z42", "z42", "z42", "Z42", "z42")] {
("Z42", "z42", "z42", "z42", "Z42", "z42"),
] {
assert_eq!(None.apply_to_variant(original), original);
assert_eq!(LowerCase.apply_to_variant(original), lower);
assert_eq!(PascalCase.apply_to_variant(original), original);
@ -114,10 +116,12 @@ fn rename_variants() {
#[test]
fn rename_fields() {
for &(original, pascal, camel, screaming, kebab) in
&[("outcome", "Outcome", "outcome", "OUTCOME", "outcome"),
&[
("outcome", "Outcome", "outcome", "OUTCOME", "outcome"),
("very_tasty", "VeryTasty", "veryTasty", "VERY_TASTY", "very-tasty"),
("a", "A", "a", "A", "a"),
("z42", "Z42", "z42", "Z42", "z42")] {
("z42", "Z42", "z42", "Z42", "z42"),
] {
assert_eq!(None.apply_to_field(original), original);
assert_eq!(PascalCase.apply_to_field(original), pascal);
assert_eq!(CamelCase.apply_to_field(original), camel);

View File

@ -28,8 +28,10 @@ fn check_getter(cx: &Ctxt, cont: &Container) {
}
Body::Struct(_, _) => {
if cont.body.has_getter() && cont.attrs.remote().is_none() {
cx.error("#[serde(getter = \"...\")] can only be used in structs \
that have #[serde(remote = \"...\")]");
cx.error(
"#[serde(getter = \"...\")] can only be used in structs \
that have #[serde(remote = \"...\")]",
);
}
}
}
@ -52,7 +54,8 @@ fn check_identifier(cx: &Ctxt, cont: &Container) {
for (i, variant) in variants.iter().enumerate() {
match (variant.style, cont.attrs.identifier(), variant.attrs.other()) {
// The `other` attribute may only be used in a field_identifier.
(_, Identifier::Variant, true) | (_, Identifier::No, true) => {
(_, Identifier::Variant, true) |
(_, Identifier::No, true) => {
cx.error("#[serde(other)] may only be used inside a field_identifier");
}

View File

@ -20,7 +20,11 @@ impl Ctxt {
}
pub fn error<T: Display>(&self, msg: T) {
self.errors.borrow_mut().as_mut().unwrap().push(msg.to_string());
self.errors
.borrow_mut()
.as_mut()
.unwrap()
.push(msg.to_string());
}
pub fn check(self) -> Result<(), String> {