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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use darling::FromAttributes;
use proc_macro::TokenStream;
use quote::quote;
use std::error::Error;
use syn::{DataEnum, Fields, Ident, ext::IdentExt};
use crate::jsjson::attributes::{ContainerOpts, FieldOpts};
// {
// "Somestring": "foobar"
// }
//
// {
// "Point": { "x": 10, "y": "one" }
// }
//
// {
// "Tuple": ["two", 20]
// }
//
// "Nothing"
pub(super) fn impl_js_json_enum(
name: &Ident,
data: &DataEnum,
container_opts: ContainerOpts,
) -> Result<TokenStream, Box<dyn Error>> {
// Encoding code for every variant
let mut variant_encodes = vec![];
// Encoding code for every simple variant (data-less)
let mut variant_string_decodes = vec![];
// Envoding code for every compound variant (with data)
let mut variant_object_decodes = vec![];
for variant in &data.variants {
let field_opts = FieldOpts::from_attributes(&variant.attrs)?;
let variant_ident = &variant.ident;
let variant_name = variant.ident.unraw().to_string();
let json_key = match field_opts.rename {
Some(json_key) => json_key,
None => match container_opts.rename_all {
Some(rule) => rule.rename(&variant_name),
None => variant_name.clone(),
},
};
match &variant.fields {
// Simple variant
// Enum::Variant <-> "Variant"
Fields::Unit => {
variant_encodes.push(quote! { Self::#variant_ident => #json_key.to_json(), });
variant_string_decodes.push(quote! { #json_key => Ok(Self::#variant_ident), });
}
// Compound variant with unnamed field(s) (tuple)
// Enum::Variant(...) <-> "Variant": ...
Fields::Unnamed(fields) => {
// Enum::Variant(T) <-> "Variant": T
if fields.unnamed.len() == 1 {
// Encode
variant_encodes.push(quote! {
Self::#variant_ident(value) => {
vertigo::JsJson::Object(::std::collections::BTreeMap::from([
(
#json_key.to_string(),
value.to_json(),
),
]))
}
});
// Decode
variant_object_decodes.push(quote! {
if let Some(value) = compound_variant.get_mut(#json_key) {
return Ok(Self::#variant_ident(
vertigo::JsJsonDeserialize::from_json(ctx.clone(), value.to_owned())?
))
}
});
// Enum::Variant(T1, T2...) <-> "Variant": [T1, T2, ...]
} else {
// Encode
let (field_idents, field_encodes) =
super::tuple_fields::get_encodes(fields.unnamed.iter());
variant_encodes.push(quote! {
Self::#variant_ident(#(#field_idents,)*) => {
vertigo::JsJson::Object(::std::collections::BTreeMap::from([
(
#json_key.to_string(),
vertigo::JsJson::List(vec![
#(#field_encodes)*
])
),
]))
}
});
// Decode
let fields_number = field_idents.len();
let field_decodes = super::tuple_fields::get_decodes(field_idents);
variant_object_decodes.push(quote! {
if let Some(value) = compound_variant.get_mut(#json_key) {
match value.to_owned() {
vertigo::JsJson::List(fields) => {
if fields.len() != #fields_number {
return Err(ctx.add(
format!("Wrong unmber of fields in tuple for variant {}. Expected {}, got {}", #variant_name, #fields_number, fields.len())
));
}
let mut fields_rev = fields.into_iter().rev().collect::<Vec<_>>();
return Ok(Self::#variant_ident (
#(#field_decodes)*
))
},
x => return Err(ctx.add(
format!("Invalid type {} while decoding enum tuple, expected list", x.typename())
)),
}
}
});
}
}
// Compound variant with named field(s) (anonymous struct)
// Enum::Variant { x: X, y: Y, ...) <-> "Variant": { x: X, y: Y, ... }
Fields::Named(fields) => {
// Encode
let field_idents = fields
.named
.iter()
.filter_map(|field| field.ident.clone())
.collect::<Vec<_>>();
let field_encodes = field_idents
.iter()
.map(|field_ident| {
let field_name = field_ident.unraw().to_string();
quote! {
(#field_name.to_string(), #field_ident.to_json()),
}
})
.collect::<Vec<_>>();
variant_encodes.push(quote! {
Self::#variant_ident {#(#field_idents,)*} => {
vertigo::JsJson::Object(::std::collections::BTreeMap::from([
(
#json_key.to_string(),
vertigo::JsJson::Object(::std::collections::BTreeMap::from([
#(#field_encodes)*
]))
),
]))
}
});
// Decode
let field_decodes = field_idents
.iter()
.map(|field_ident| {
let field_name = field_ident.unraw().to_string();
quote! {
#field_ident: value.get_property(&ctx, #field_name)?,
}
})
.collect::<Vec<_>>();
variant_object_decodes.push(quote! {
if let Some(value) = compound_variant.get_mut(#json_key) {
return Ok(Self::#variant_ident {
#(#field_decodes)*
})
}
});
}
}
}
let result = quote! {
impl vertigo::JsJsonSerialize for #name {
fn to_json(self) -> vertigo::JsJson {
match self {
#(#variant_encodes)*
}
}
}
impl vertigo::JsJsonDeserialize for #name {
fn from_json(
ctx: vertigo::JsJsonContext,
json: vertigo::JsJson,
) -> Result<Self, vertigo::JsJsonContext> {
match json {
vertigo::JsJson::String(simple_variant) => {
match simple_variant.as_str() {
#(#variant_string_decodes)*
x => Err(ctx.add(format!("Invalid simple variant {x}"))),
}
}
vertigo::JsJson::Object(mut compound_variant) => {
#(#variant_object_decodes)*
Err(ctx.add("Value not matched with any variant".to_string()))
}
x => Err(ctx.add(
format!("Invalid type {} while decoding enum, expected string or object", x.typename())
)),
}
}
}
};
Ok(result.into())
}