1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#[macro_export(local_inner_macros)]
macro_rules! untagged {
	(
		$(#[$attr:meta])*
		$vis:vis enum $name:ident {
			$(
				$(#[$variant_attr:meta])*
				$variant:ident($inner:ty)
			),+
		}
	) => {
		$(#[$attr])*
		#[derive(::serde::Serialize)]
		#[serde(untagged)]
		$vis enum $name {
			$(
				$(#[$variant_attr])*
				$variant($inner)
			),+
		}

		impl<'de> ::serde::Deserialize<'de> for $name
		where
			$($inner: ::serde::Deserialize<'de>),*
		{
			fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
			where
				D: ::serde::Deserializer<'de>
			{
				static VARIANTS: $crate::private::SyncLazy<
					::std::result::Result<
						[&'static str; count!($($variant)+)],
						::std::string::String
					>
				> = $crate::private::SyncLazy::new(|| ::std::result::Result::Ok([$({
					let extraction = <$inner as ::serde::Deserialize>::deserialize(
						$crate::private::NameExtractor
					);
					let extraction = match extraction {
						::std::result::Result::Ok(_) => ::std::unreachable!(),
						::std::result::Result::Err(e) => e
					};
					match extraction {
						$crate::private::Extraction::Ok(name) => name,
						$crate::private::Extraction::Err(err) => return Err(err)
					}
				}),+]));
				let variants: &'static [&'static str] = VARIANTS
					.as_ref()
					.map_err(|err| <D::Error as ::serde::de::Error>::custom(err))?;

				struct Visitor(&'static [&'static str]);

				impl<'de> ::serde::de::Visitor<'de> for Visitor {
					type Value = $name;

					fn expecting(
						&self, f: &mut ::std::fmt::Formatter<'_>
					) -> ::std::fmt::Result {
						::std::fmt::Display::fmt(&::std::format_args!(
							"any s-expr with a name in {:?}",
							self.0
						), f)
					}

					fn visit_enum<A>(self, data: A) -> ::std::result::Result<$name, A::Error>
					where
						A: ::serde::de::EnumAccess<'de>
					{
						let (variant_name, variant): (::std::borrow::Cow<'de, str>, _) =
							data.variant()?;

						let mut i = 0;
						$(
							if variant_name == self.0[i] {
								let inner: $inner =
									::serde::de::VariantAccess::newtype_variant(variant)?;
								return ::std::result::Result::Ok($name::$variant(inner));
							}
							i += 1;
						)+
						let _ = i;

						return ::std::result::Result::Err(
							<A::Error as ::serde::de::Error>::invalid_value(
								::serde::de::Unexpected::Other(&variant_name),
								&self
							)
						);
					}
				}

				deserializer.deserialize_enum(
					::std::stringify!($name),
					variants,
					Visitor(variants)
				)
			}
		}
	};
}

#[macro_export(local_inner_macros)]
#[doc(hidden)]
macro_rules! count {
	() => {
		0
	};

	($x:ident $($xs:ident)*) => {
		1 + count!($($xs)*)
	}
}

#[cfg(test)]
mod tests {
	mod foo_bar {
		use serde::{Deserialize, Serialize};

		#[derive(Debug, Deserialize, PartialEq, Serialize)]
		#[serde(deny_unknown_fields, rename = "foo")]
		pub(super) struct Foo;

		#[derive(Debug, Deserialize, PartialEq, Serialize)]
		#[serde(deny_unknown_fields, rename = "bar")]
		pub(super) struct Bar;
	}

	use foo_bar::{Bar, Foo};

	untagged! {
		#[derive(Debug, PartialEq)]
		enum FooOrBar {
			Foo(Foo),
			Bar(Bar)
		}
	}

	#[test]
	fn deserialize_foo() {
		let input = "(foo)";
		let expected = FooOrBar::Foo(Foo);

		let parsed: FooOrBar =
			crate::from_str(input).expect("Failed to parse input");
		assert_eq!(parsed, expected);
	}

	#[test]
	fn deserialize_bar() {
		let input = "(bar)";
		let expected = FooOrBar::Bar(Bar);

		let parsed: FooOrBar =
			crate::from_str(input).expect("Failed to parse input");
		assert_eq!(parsed, expected);
	}
}