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

Allow #[serde(crate = "...")] to override extern crate serde #1499

Merged
merged 5 commits into from
Apr 3, 2019
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion serde_derive/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ pub fn expand_derive_deserialize(input: &syn::DeriveInput) -> Result<TokenStream
}
};

Ok(dummy::wrap_in_const("DESERIALIZE", ident, impl_block))
Ok(dummy::wrap_in_const(cont.attrs.serde_path(), "DESERIALIZE", ident, impl_block))
}

fn precondition(cx: &Ctxt, cont: &Container) {
Expand Down
17 changes: 13 additions & 4 deletions serde_derive/src/dummy.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,31 @@
use proc_macro2::{Ident, Span, TokenStream};

use syn;
use try;

pub fn wrap_in_const(trait_: &str, ty: &Ident, code: TokenStream) -> TokenStream {
pub fn wrap_in_const(serde_path: Option<&syn::Path>, trait_: &str, ty: &Ident, code: TokenStream) -> TokenStream {
let try_replacement = try::replacement();

let dummy_const = Ident::new(
&format!("_IMPL_{}_FOR_{}", trait_, unraw(ty)),
Span::call_site(),
);

quote! {
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
const #dummy_const: () = {
let use_serde = serde_path.map(|path| {
quote!(use #path as _serde;)
}).unwrap_or_else(|| {
quote! {
#[allow(unknown_lints)]
#[cfg_attr(feature = "cargo-clippy", allow(useless_attribute))]
#[allow(rust_2018_idioms)]
extern crate serde as _serde;
}
});

quote! {
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
const #dummy_const: () = {
#use_serde
#try_replacement
#code
};
Expand Down
14 changes: 14 additions & 0 deletions serde_derive/src/internals/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ pub struct Container {
remote: Option<syn::Path>,
identifier: Identifier,
has_flatten: bool,
serde_path: Option<syn::Path>,
}

/// Styles of representing an enum.
Expand Down Expand Up @@ -298,6 +299,7 @@ impl Container {
let mut remote = Attr::none(cx, "remote");
let mut field_identifier = BoolAttr::none(cx, "field_identifier");
let mut variant_identifier = BoolAttr::none(cx, "variant_identifier");
let mut serde_path = Attr::none(cx, "serde_path");

for meta_items in item.attrs.iter().filter_map(get_serde_meta_items) {
for meta_item in meta_items {
Expand Down Expand Up @@ -582,6 +584,13 @@ impl Container {
variant_identifier.set_true(word);
}

// Parse `#[serde(serde_path = "foo")]`
Meta(NameValue(ref m)) if m.ident == "serde_path" => {
if let Ok(path) = parse_lit_into_path(cx, &m.ident, &m.lit) {
serde_path.set(&m.ident, path)
}
}

Meta(ref meta_item) => {
cx.error_spanned_by(
meta_item.name(),
Expand Down Expand Up @@ -613,6 +622,7 @@ impl Container {
remote: remote.get(),
identifier: decide_identifier(cx, item, field_identifier, variant_identifier),
has_flatten: false,
serde_path: serde_path.get(),
}
}

Expand Down Expand Up @@ -671,6 +681,10 @@ impl Container {
pub fn mark_has_flatten(&mut self) {
self.has_flatten = true;
}

pub fn serde_path(&self) -> Option<&syn::Path> {
self.serde_path.as_ref()
}
}

fn decide_tag(
Expand Down
2 changes: 1 addition & 1 deletion serde_derive/src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pub fn expand_derive_serialize(input: &syn::DeriveInput) -> Result<TokenStream,
}
};

Ok(dummy::wrap_in_const("SERIALIZE", ident, impl_block))
Ok(dummy::wrap_in_const(cont.attrs.serde_path(), "SERIALIZE", ident, impl_block))
}

fn precondition(cx: &Ctxt, cont: &Container) {
Expand Down
39 changes: 39 additions & 0 deletions test_suite/tests/test_serde_path.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#[test]
fn test_gen_custom_serde() {
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(serde_path = "fake_serde")]
struct Foo;

// Would be overlapping if serde::Serialize were implemented
impl AssertNotSerdeSerialize for Foo {}
// Would be overlapping if serde::Deserialize were implemented
impl<'a> AssertNotSerdeDeserialize<'a> for Foo {}

fake_serde::assert::<Foo>();
}

mod fake_serde {
pub use serde::*;

pub fn assert<T>()
where
T: Serialize,
T: for<'a> Deserialize<'a>,
{}

pub trait Serialize {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>;
}

pub trait Deserialize<'a>: Sized {
fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error>;
}
}

trait AssertNotSerdeSerialize {}

impl<T: serde::Serialize> AssertNotSerdeSerialize for T {}

trait AssertNotSerdeDeserialize<'a> {}

impl<'a, T: serde::Deserialize<'a>> AssertNotSerdeDeserialize<'a> for T {}