-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathdecode.rs
More file actions
332 lines (296 loc) · 12.5 KB
/
decode.rs
File metadata and controls
332 lines (296 loc) · 12.5 KB
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
use {
crate::utils::{canonical_ident, get_named_fields, NamedField},
proc_macro2::TokenStream,
quote::ToTokens,
syn::{Data, DataEnum, DataStruct, DeriveInput, Fields, FieldsUnnamed},
};
pub fn impl_decode_macro(ast: &DeriveInput) -> TokenStream {
match &ast.data {
Data::Struct(data_struct) => impl_struct_decode(ast, data_struct),
Data::Enum(data_enum) => impl_enum_decode(ast, data_enum),
Data::Union(_) => panic!("Unions are not supported by tree-buf"),
}
}
fn impl_struct_decode(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream {
let fields = get_named_fields(data_struct);
let name = &ast.ident;
let inits = fields
.iter()
.map(|NamedField { ident, canon_str, .. }| {
quote! {
let #ident = fields.remove(#canon_str).unwrap_or_default();
}
})
.collect::<Vec<_>>();
let unwraps = fields
.iter()
.map(|NamedField { ident, .. }| {
quote! {
#ident: #ident?,
}
})
.collect::<Vec<_>>();
let mut parallel_lhs = quote! {};
let mut decodes_parallel_rhs = quote! {};
let mut news_parallel_rhs = quote! {};
let mut is_first = true;
for NamedField { ident, ty, .. } in &fields {
if is_first {
is_first = false;
parallel_lhs = quote! { #ident };
decodes_parallel_rhs = quote! {
<#ty as ::tree_buf::internal::Decodable>::decode(
#ident,
options,
)
};
news_parallel_rhs = quote! {
::tree_buf::internal::DecoderArray::new(#ident, options)
};
} else {
parallel_lhs = quote! { (#ident, #parallel_lhs) };
decodes_parallel_rhs = quote! {
::tree_buf::internal::parallel(
|| <#ty as ::tree_buf::internal::Decodable>::decode(
#ident,
options,
),
|| #decodes_parallel_rhs,
options
)
};
news_parallel_rhs = quote! {
::tree_buf::internal::parallel(
|| ::tree_buf::internal::DecoderArray::new(#ident, options),
|| #news_parallel_rhs,
options
)
}
}
}
let array_fields = fields.iter().map(|NamedField { ident, ty, .. }| {
quote! {
#ident: <#ty as ::tree_buf::internal::Decodable>::DecoderArray
}
});
let decode_nexts = fields.iter().map(|NamedField { ident, .. }| {
quote! {
// Overly verbose because of `?` requiring `From` See also ec4fa3ba-def5-44eb-9065-e80b59530af6
#ident: match self.#ident.decode_next() { Ok(v) => v, Err(e) => { return Err(e.into()); } },
}
});
let decode = quote! {
let mut fields = match sticks {
::tree_buf::internal::DynRootBranch::Object { fields } => fields,
_ => return Err(::tree_buf::DecodeError::SchemaMismatch),
};
#(#inits)*
let #parallel_lhs = #decodes_parallel_rhs;
Ok(Self {
#(#unwraps)*
})
};
let new = quote! {
let mut fields = match sticks {
::tree_buf::internal::DynArrayBranch::Object { fields } => fields,
_ => return Err(::tree_buf::DecodeError::SchemaMismatch),
};
#(#inits)*
let #parallel_lhs = #news_parallel_rhs;
Ok(Self {
#(#unwraps)*
})
};
let decode_next = quote! {
Ok(#name {
#(#decode_nexts)*
})
};
fill_decode_skeleton(ast, decode, array_fields, new, decode_next)
}
fn fill_decode_skeleton<A: ToTokens>(
ast: &DeriveInput,
decode: impl ToTokens,
array_fields: impl Iterator<Item = A>,
new: impl ToTokens,
decode_next: impl ToTokens,
) -> TokenStream {
let name = &ast.ident;
let vis = &ast.vis;
let array_decoder_name = format_ident!("{}TreeBufDecoderArray", name);
quote! {
#[allow(non_snake_case)]
impl ::tree_buf::internal::Decodable for #name {
type DecoderArray = #array_decoder_name;
fn decode(sticks: ::tree_buf::internal::DynRootBranch<'_>, options: &impl ::tree_buf::experimental::options::DecodeOptions) -> Result<Self, ::tree_buf::DecodeError> {
// TODO: Re-enable profiling. See also a3b84cdc-be0f-4de2-8195-efb540004d2f
//let _profile_guard = ::tree_buf::internal::firestorm::start_guard(::tree_buf::internal::firestorm::FmtStr::Str3(::std::any::type_name::<Self>(), "::", "decode"));
#decode
}
}
#[allow(non_snake_case)]
#vis struct #array_decoder_name {
#(#array_fields,)*
}
#[allow(non_snake_case)]
impl ::tree_buf::internal::DecoderArray for #array_decoder_name {
type Decode=#name;
// TODO: See if sometimes we can use Infallible here.
type Error=::tree_buf::DecodeError;
fn new(sticks: ::tree_buf::internal::DynArrayBranch<'_>, options: &impl ::tree_buf::experimental::options::DecodeOptions) -> Result<Self, ::tree_buf::DecodeError> {
// TODO: Re-enable profiling. See also a3b84cdc-be0f-4de2-8195-efb540004d2f
//let _profile_guard = ::tree_buf::internal::firestorm::start_guard(::tree_buf::internal::firestorm::FmtStr::Str3(::std::any::type_name::<Self>(), "::", "decode"));
#new
}
fn decode_next(&mut self) -> ::std::result::Result<Self::Decode, Self::Error> {
#decode_next
}
}
}
}
fn impl_enum_decode(ast: &DeriveInput, data_enum: &DataEnum) -> TokenStream {
let ident = &ast.ident;
let mut array_fields = Vec::new();
array_fields.push(quote! {
tree_buf_discriminant: <u64 as ::tree_buf::Decodable>::DecoderArray
});
let mut new_matches = Vec::new();
let mut new_inits = Vec::new();
let mut decode_nexts = Vec::new();
let mut new_unpacks = Vec::new();
let mut new_parallel_lhs = quote! { tree_buf_discriminant };
let mut new_parallel_rhs = quote! { ::tree_buf::internal::DecoderArray::new(tree_buf_discriminant, options) };
let mut root_matches = Vec::new();
for variant in data_enum.variants.iter() {
let variant_ident = &variant.ident;
let discriminant = canonical_ident(variant_ident);
match &variant.fields {
Fields::Unit => {
root_matches.push(quote! {
// TODO: Verify that the branch is the void type?
#discriminant => Self::#variant_ident,
});
array_fields.push(quote! {
#variant_ident: Option<u64>
});
new_unpacks.push(quote! { #variant_ident: #variant_ident, });
new_matches.push(quote! {
#discriminant => {
if #variant_ident.is_some() {
return Err(::tree_buf::DecodeError::InvalidFormat);
}
#variant_ident = Some(index as u64);
}
});
new_inits.push(quote! {
let mut #variant_ident = None;
});
decode_nexts.push(quote! {
if let Some(d) = &mut self.#variant_ident {
if *d == discriminant {
return Ok(#ident::#variant_ident);
}
}
});
}
Fields::Named(_named_fields) => todo!("Enums with named fields not yet supported by tree-buf decode"),
Fields::Unnamed(FieldsUnnamed { unnamed, .. }) => {
match unnamed.len() {
// TODO: Check if this is really unreachable. It might be `Variant {}`
0 => unreachable!(),
1 => {
root_matches.push(quote! {
#discriminant => {
Self::#variant_ident(::tree_buf::internal::Decodable::decode(*value, options)?)
},
});
let ty = &unnamed[0].ty;
array_fields.push(quote! {
#variant_ident: Option<(u64, <#ty as ::tree_buf::internal::Decodable>::DecoderArray)>
});
new_unpacks.push(quote! { #variant_ident: #variant_ident.transpose()?, });
new_parallel_lhs = quote! { (#variant_ident, #new_parallel_lhs) };
new_parallel_rhs = quote! {
::tree_buf::internal::parallel(
|| #variant_ident.map(|(i, d)| { ::tree_buf::internal::DecoderArray::new(d, options).map(|v| (i, v)) }),
|| #new_parallel_rhs,
options
)
};
new_matches.push(quote! {
#discriminant => {
if #variant_ident.is_some() {
return Err(::tree_buf::DecodeError::InvalidFormat);
}
#variant_ident = Some(
(index as u64, data)
);
}
});
new_inits.push(quote! {
let mut #variant_ident = None;
});
decode_nexts.push(quote! {
if let Some((d, r)) = &mut self.#variant_ident {
if *d == discriminant {
// Overly verbose because of `?` requiring `From` See also ec4fa3ba-def5-44eb-9065-e80b59530af6
return Ok(#ident::#variant_ident(match r.decode_next() { Ok(v) => v, Err(e) => return Err(e.into()) }));
}
}
})
}
_ => todo!("Enums with multiple unnamed fields not yet supported by tree-buf Decode"),
}
}
}
}
let decode = quote! {
// If this is an enum,
if let ::tree_buf::internal::DynRootBranch::Enum { discriminant, value } = sticks {
Ok(
// See if it's a variant we are aware of, and that the value
// matches the expected data.
match discriminant {
#(#root_matches)*
_ => { return Err(::tree_buf::DecodeError::SchemaMismatch); },
}
)
} else {
Err(::tree_buf::DecodeError::SchemaMismatch)
}
};
let new = quote! {
match sticks {
::tree_buf::internal::DynArrayBranch::Enum {discriminants, variants} => {
let tree_buf_discriminant = *discriminants;
#(#new_inits)*;
for (index, variant) in variants.into_iter().enumerate() {
let ::tree_buf::internal::ArrayEnumVariant { ident, data } = variant;
match ident {
#(#new_matches),*
_ => { return Err(::tree_buf::DecodeError::SchemaMismatch); }
}
}
let #new_parallel_lhs = #new_parallel_rhs;
let result = Self {
tree_buf_discriminant: tree_buf_discriminant?,
#(#new_unpacks)*
};
// FIXME: Need to verify that the range of tree_buf_discriminant does
// not go beyond the number of variants listed (this would indicate a corrupt file)
// See also: fb0a3c86-23be-4d4a-9dbf-9c83ae6e2f0f
Ok(result)
}
_ => {
Err(::tree_buf::DecodeError::SchemaMismatch)
}
}
};
let decode_next = quote! {
let discriminant = ::tree_buf::internal::InfallibleDecoderArray::decode_next_infallible(&mut self.tree_buf_discriminant);
#(#decode_nexts)*
// See also: fb0a3c86-23be-4d4a-9dbf-9c83ae6e2f0f
todo!("Make this unreachable by verifying range");
};
fill_decode_skeleton(ast, decode, array_fields.iter(), new, decode_next)
}