From 77376f39eaca96eb12a6fe2c5bae3403ff478478 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Sun, 1 Apr 2018 22:11:21 +0200 Subject: [PATCH] Produce error message for use of flatten in tuple structs --- serde_derive_internals/src/check.rs | 11 ++++++++++- .../conflict/flatten-newtype-struct.rs | 16 ++++++++++++++++ .../conflict/flatten-tuple-struct.rs | 16 ++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 test_suite/tests/compile-fail/conflict/flatten-newtype-struct.rs create mode 100644 test_suite/tests/compile-fail/conflict/flatten-tuple-struct.rs diff --git a/serde_derive_internals/src/check.rs b/serde_derive_internals/src/check.rs index 31980a398..6db99a173 100644 --- a/serde_derive_internals/src/check.rs +++ b/serde_derive_internals/src/check.rs @@ -47,11 +47,20 @@ fn check_flatten(cx: &Ctxt, cont: &Container) { Data::Enum(_) => { assert!(!cont.attrs.has_flatten()); } - Data::Struct(_, _) => { + Data::Struct(style, _) => { for field in cont.data.all_fields() { if !field.attrs.flatten() { continue; } + match style { + Style::Tuple => { + cx.error("#[serde(flatten)] cannot be used on tuple structs"); + } + Style::Newtype => { + cx.error("#[serde(flatten)] cannot be used on newtype structs"); + } + _ => {} + } if field.attrs.skip_serializing() { cx.error( "#[serde(flatten] can not be combined with \ diff --git a/test_suite/tests/compile-fail/conflict/flatten-newtype-struct.rs b/test_suite/tests/compile-fail/conflict/flatten-newtype-struct.rs new file mode 100644 index 000000000..07566f8c7 --- /dev/null +++ b/test_suite/tests/compile-fail/conflict/flatten-newtype-struct.rs @@ -0,0 +1,16 @@ +// Copyright 2018 Serde Developers +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[macro_use] +extern crate serde_derive; + +#[derive(Serialize)] //~ ERROR: proc-macro derive panicked +//~^ HELP: #[serde(flatten)] cannot be used on newtype structs +struct Foo(#[serde(flatten)] HashMap); + +fn main() {} diff --git a/test_suite/tests/compile-fail/conflict/flatten-tuple-struct.rs b/test_suite/tests/compile-fail/conflict/flatten-tuple-struct.rs new file mode 100644 index 000000000..167bdbdac --- /dev/null +++ b/test_suite/tests/compile-fail/conflict/flatten-tuple-struct.rs @@ -0,0 +1,16 @@ +// Copyright 2018 Serde Developers +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[macro_use] +extern crate serde_derive; + +#[derive(Serialize)] //~ ERROR: proc-macro derive panicked +//~^ HELP: #[serde(flatten)] cannot be used on tuple structs +struct Foo(u32, #[serde(flatten)] HashMap); + +fn main() {}