Require getters to return the correct type

This commit is contained in:
David Tolnay 2017-04-09 10:59:54 -07:00
parent a6d172111b
commit 9d8987bde8
No known key found for this signature in database
GPG Key ID: F9BA143B95FF6D82
3 changed files with 33 additions and 1 deletions

View File

@ -8,6 +8,12 @@ use self::content::{SerializeTupleVariantAsMapValue, SerializeStructVariantAsMap
#[cfg(feature = "std")]
use std::error;
/// Used to check that serde(getter) attributes return the expected type.
/// Not public API.
pub fn constrain<T: ?Sized>(t: &T) -> &T {
t
}
/// Not public API.
pub fn serialize_tagged_newtype<S, T>(serializer: S,
type_ident: &'static str,

View File

@ -839,6 +839,9 @@ fn get_field<I>(params: &Parameters, field: &Field, ident: I) -> Tokens
let ident = ident.into();
quote!(&#self_var.#ident)
}
Some(getter) => quote!(&#getter(#self_var)),
Some(getter) => {
let ty = field.ty;
quote!(_serde::private::ser::constrain::<#ty>(&#getter(#self_var)))
}
}
}

View File

@ -0,0 +1,23 @@
#[macro_use]
extern crate serde_derive;
mod remote {
pub struct S {
a: u8,
}
impl S {
pub fn get(&self) -> u16 {
self.a as u16
}
}
}
#[derive(Serialize)] //~ ERROR: mismatched types
#[serde(remote = "remote::S")]
struct S {
#[serde(getter = "remote::S::get")]
a: u8, //~^^^^ expected u8, found u16
}
fn main() {}