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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
extern crate proc_macro;
mod type_check;
use crate::type_check::{IsTypeCompatible, is_str_ref};
use proc_macro::TokenStream;
use proc_macro_crate::{FoundCrate, crate_name};
use proc_macro2::Span;
use quote::{format_ident, quote};
use syn::{
Attribute, Data, DeriveInput, Fields, GenericParam, Ident, Lifetime, Lit, Type, WherePredicate,
parse_macro_input, parse_quote,
};
fn fixlite_path() -> proc_macro2::TokenStream {
match crate_name("fixlite") {
Ok(FoundCrate::Itself) => quote!(::fixlite),
Ok(FoundCrate::Name(name)) => {
let ident = Ident::new(&name.replace('-', "_"), Span::call_site());
quote!(::#ident)
}
Err(_) => quote!(::fixlite),
}
}
#[proc_macro_derive(FixDeserialize, attributes(fix, fix_group, fix_registry))]
pub fn fix_deserialize_derive(input: TokenStream) -> TokenStream {
// Parse the input tokens into a syntax tree.
let input = parse_macro_input!(input as DeriveInput);
let fixlite_path = fixlite_path();
let registry_type = input
.attrs
.iter()
.find(|attr| attr.path().is_ident("fix_registry"))
.map(|attr| {
let ident = attr.parse_args::<Ident>().unwrap();
quote! {#ident}
})
.unwrap_or_else(|| {
quote! {#fixlite_path::tag::DefaultRegistry}
});
let mut assertions = Vec::new();
// Get the struct name.
let struct_name = input.ident;
let generics = input.generics.clone();
let (_, ty_generics, _) = generics.split_for_impl();
let mut impl_generics_new = generics.clone();
let fix_lifetime: Lifetime = parse_quote!('fixlite);
let fix_lifetime_def = GenericParam::Lifetime(parse_quote!(#fix_lifetime));
impl_generics_new.params.insert(0, fix_lifetime_def);
let mut where_clause_new = impl_generics_new.where_clause.clone();
if where_clause_new.is_none() {
where_clause_new = Some(parse_quote!(where));
}
if let Some(ref mut where_clause_new) = where_clause_new {
// For each struct lifetime 'a, add a where clause: 'fixlite: 'a
for lt in generics.lifetimes() {
let lt_ident = <.lifetime;
let predicate: WherePredicate = parse_quote!('fixlite: #lt_ident);
where_clause_new.predicates.push(predicate);
}
}
impl_generics_new.where_clause = where_clause_new;
let user_lifetime_defs: Vec<_> = impl_generics_new
.lifetimes()
.skip(1)
.map(|lt| lt.lifetime.clone())
.collect();
assert!(
!user_lifetime_defs.contains(&fix_lifetime),
"The lifetime `'fixlite` is reserved by fixlite. Please rename it in your struct."
);
let (impl_generics_new, _, where_clause_new) = impl_generics_new.split_for_impl();
let fix_lifetime: proc_macro2::TokenStream = quote!('fixlite);
let user_lifetime_tokens = if user_lifetime_defs.is_empty() {
quote!() // no lifetimes, omit <...>
} else {
quote! { <#(#user_lifetime_defs),*> }
};
// Generate code based on the struct's data.
let impl_block = match input.data {
Data::Struct(ref data_struct) => {
// Process the struct fields.
let mut field_parsers = Vec::new();
let mut field_initializers = Vec::new();
let mut field_names = Vec::new();
let mut field_checks = Vec::new();
let mut known_tags: Vec<u32> = Vec::new(); // Collect known tags
let mut component_handlers = Vec::new();
if let Fields::Named(ref fields_named) = data_struct.fields {
for field in &fields_named.named {
let field_name = field.ident.as_ref().unwrap();
field_names.push(field_name.clone());
let field_type = &field.ty;
let mut is_component = false;
let mut is_group = false;
let mut tag_value = None;
for attr in &field.attrs {
if attr.path().is_ident("fix") {
// #[fix(...)]
let (comp, tag_opt) = parse_fix_attribute(attr);
is_component = comp;
if let Some(tag) = tag_opt {
tag_value = Some(tag.clone());
// <-- put it into the constant list *unless* this field is a component
if !is_component {
known_tags.push(tag.parse().unwrap());
}
if let Ok(tag_u32) = tag.parse::<u32>() {
if let Some(inner_type) =
extract_inner_type(field_type, "Option")
{
assertions.push(quote! { assert_allowed::<Option<#inner_type>, #tag_u32>(); });
assertions.push(
quote! { assert_allowed::<#inner_type, #tag_u32>(); },
);
} else {
assertions.push(
quote! { assert_allowed::<#field_type, #tag_u32>(); },
);
}
}
}
} else if attr.path().is_ident("fix_group") {
// #[fix_group(tag = ...)]
is_group = true;
let (_, tag_opt) = parse_fix_attribute(attr);
let tag = tag_opt.expect("group tag must be specified");
tag_value = Some(tag.clone());
known_tags.push(tag.parse().unwrap()); // group-counter tags belong to the outer struct
}
}
// Generate code for field initialization.
let field_var = format_ident!("{}_tmp", field_name);
// Extract inner type from Option<T>
if let Some(inner_type) = extract_inner_type(field_type, "Option") {
// Field type is Option<T>, so use T
field_initializers.push(quote! {
let mut #field_var: Option<#inner_type> = None;
});
} else {
field_initializers.push(quote! {
let mut #field_var: Option<#field_type> = None;
});
}
/* ---------- decide what kind of parser to inject ---------- */
if is_component {
// component
let handler = generate_component_parser(
field_name,
field_type,
&fix_lifetime,
&fixlite_path,
);
component_handlers.push(handler);
// Components have no single FIX tag; emit MissingComponent on miss.
field_checks.push(generate_field_check(
field_name,
field_type,
None,
&fixlite_path,
));
} else if let Some(tag) = tag_value {
// regular field or repeating-group
let tag: u32 = tag.parse().unwrap();
if is_group {
field_parsers.push(generate_group_parser(
field_name,
field_type,
tag,
&fix_lifetime,
&fixlite_path,
));
} else {
// Generate code for regular field parsing.
let parser =
generate_field_parser(field_name, field_type, tag, &fixlite_path);
field_parsers.push(parser);
}
field_checks.push(generate_field_check(
field_name,
field_type,
Some(tag),
&fixlite_path,
));
}
}
}
// Sort the known tags for binary search.
known_tags.sort();
let known_tags_len = known_tags.len();
let known_tags_tokens = known_tags.iter().map(|tag| quote! { #tag });
let fix_module_path = fixlite_path.clone();
// Combine all parts into the final implementation.
quote! {
impl #impl_generics_new #fix_module_path::FixDeserialize<#fix_lifetime> for #struct_name #ty_generics #where_clause_new {
fn deserialize_fields<F>(
tags: &mut #fix_module_path::__private::TagCursor<#fix_lifetime>,
is_a_top_level_tag: F,
) -> Result<Self, #fix_module_path::FixError>
where
F: Fn(u32) -> bool,
{
use chrono::{NaiveDateTime, DateTime, Utc};
let mut first_tag = None;
#(#field_initializers)*
while let Some(tag) = tags.peek_tag_u32() {
// ---------- REPEATING GROUPS ----------
// The following checks heuristically detect the boundaries of elements
// within a repeating group and identify the end of the group.
//
// Check for the beginning of an element:
// This approach assumes that all elements in a repeating group start
// with the same tag. This assumption is generally reasonable.
if first_tag.is_none() {
first_tag = Some(tag);
} else if tag == first_tag.unwrap() {
// `first_tag` is expected to be the first tag in the repeating group.
// If encountered again, it marks the start of the next element of the group,
// so we stop processing the current element.
// If this is a top-level tag, i.e., it is not part of a repeating group,
// this logic does not matter as we do not expect any tag to appear
// more than once outside a repeating group.
break;
}
// Check for the end of the group:
// We assume that if while processing elements of a repeating group,
// we encounter a tag which does not belong to the element but is one
// of the top-level tags, this signals, that we are likely past the
// last element of the group, so we need to stop processing the current
// element.
if is_a_top_level_tag(tag) {
break;
}
// ---------- COMPONENTS ----------
#(#component_handlers)* // <-- executes all generated `if … continue;` blocks
match tag {
#(#field_parsers)*
_ => {
// Unrecognized tag, consume and ignore.
tags.skip();
}
}
}
#(#field_checks)*
Ok(Self {
#(
#field_names,
)*
})
}
fn is_known_tag(tag: u32) -> bool {
const KNOWN_TAGS: [u32; #known_tags_len] = [#(#known_tags_tokens),*];
KNOWN_TAGS.binary_search(&tag).is_ok()
}
}
}
}
_ => unimplemented!("FixDeserialize can only be derived for structs with named fields."),
};
let const_assert_fn_name = format_ident!(
"_ASSERT_ALLOWED_TAG_TYPES_{}",
struct_name.to_string().to_uppercase()
);
let const_block = quote! {
const #const_assert_fn_name: () = {
const fn assert_allowed<T, const TAG: u32>()
where
#registry_type: #fixlite_path::tag::AllowedType<TAG,T>,
{}
fn __assertions #user_lifetime_tokens () {
#(#assertions)*
}
let _ = __assertions;
};
};
// Convert the generated code into a TokenStream.
TokenStream::from(quote! {
#impl_block
#const_block
})
}
/// Returns (is_component, tag_value)
fn parse_fix_attribute(attr: &Attribute) -> (bool, Option<String>) {
let mut tag = None;
let mut is_component = false;
let _ = attr
.parse_nested_meta(|nested| {
if nested.path.is_ident("component") {
is_component = true;
} else if nested.path.is_ident("tag") {
nested.value()?.parse::<Lit>().map(|lit| match lit {
Lit::Str(s) => tag = Some(s.value()),
Lit::Int(i) => tag = Some(i.base10_digits().to_string()),
_ => {}
})?;
}
Ok(())
})
.is_ok();
(is_component, tag)
}
fn generate_field_parser(
field_name: &Ident,
field_type: &Type,
tag: u32,
fixlite_path: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
let field_var = format_ident!("{}_tmp", field_name);
// Determine the actual type to parse into
let parse_into_type = if let Some(inner_type) = extract_inner_type(field_type, "Option") {
inner_type
} else {
field_type
};
let parse_value = if is_str_ref(parse_into_type) {
quote! { value }
} else if "String".is_type_compatible(parse_into_type) {
quote! { value.to_string() }
} else if "DateTime<Utc>".is_type_compatible(parse_into_type) {
quote! {
{let dt = NaiveDateTime::parse_from_str(value, "%Y%m%d-%H:%M:%S%.f")?;
DateTime::<Utc>::from_naive_utc_and_offset(dt, Utc)}
}
} else {
quote! { value.parse::<#parse_into_type>().map_err(|_| #fixlite_path::FixError::invalid_value_ctx(#tag,value.as_bytes()))? }
};
quote! {
#tag => {
let value = tags.next_value().unwrap();
#field_var = Some(#parse_value);
},
}
}
fn generate_group_parser(
field_name: &Ident,
field_type: &Type,
tag: u32,
fix_lifetime: &proc_macro2::TokenStream,
fixlite_path: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
let field_var = format_ident!("{}_tmp", field_name);
// Extract inner type from Vec<T>
let inner_type =
extract_inner_type(field_type, "Vec").expect("Expected Vec<T> for repeating group");
quote! {
#tag => {
let value = tags.next_value().unwrap();
let group_count = value.parse::<usize>().map_err(|_| #fixlite_path::FixError::invalid_value_ctx(#tag,value.as_bytes()))?;
let mut entries = Vec::with_capacity(group_count);
for _ in 0..group_count {
let entry = <#inner_type as #fixlite_path::FixDeserialize<#fix_lifetime>>::deserialize_fields(tags, |tag| Self::is_known_tag(tag))?;
entries.push(entry);
}
#field_var = Some(entries);
},
}
}
fn generate_component_parser(
field_name: &Ident,
field_type: &Type,
fix_lifetime: &proc_macro2::TokenStream,
fixlite_path: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
let field_var = format_ident!("{}_tmp", field_name);
let inner_type = extract_inner_type(field_type, "Option").unwrap_or(field_type);
quote! {
if #field_var.is_none()
&& <#inner_type as #fixlite_path::FixDeserialize<#fix_lifetime>>::is_known_tag(tag)
{
let value =
<#inner_type as #fixlite_path::FixDeserialize<#fix_lifetime>>
::deserialize_fields(tags, |t| Self::is_known_tag(t))?;
#field_var = Some(value);
continue; // we already consumed the component’s fields
}
}
}
fn generate_field_check(
field_name: &Ident,
field_type: &Type,
tag: Option<u32>,
fixlite_path: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
let field_var = format_ident!("{}_tmp", field_name);
// Check if the field is optional (Option<T>)
let is_option = match field_type {
Type::Path(type_path) => {
if let Some(segment) = type_path.path.segments.first() {
segment.ident == "Option"
} else {
false
}
}
_ => false,
};
if is_option {
quote! {
let #field_name = #field_var;
}
} else if let Some(tag) = tag {
quote! {
let #field_name = #field_var.ok_or(
#fixlite_path::FixError::MissingField {
name: stringify!(#field_name),
tag: #tag,
}
)?;
}
} else {
// Component fields have no single FIX tag.
quote! {
let #field_name = #field_var.ok_or(
#fixlite_path::FixError::MissingComponent(stringify!(#field_name))
)?;
}
}
}
/// Used to extract inner type T from Option<T>, Vec<T>, etc.
fn extract_inner_type<'a>(field_type: &'a Type, expected_outer: &str) -> Option<&'a Type> {
if let Type::Path(type_path) = field_type
&& let Some(segment) = type_path.path.segments.first()
&& segment.ident == expected_outer
&& let syn::PathArguments::AngleBracketed(args) = &segment.arguments
&& let Some(syn::GenericArgument::Type(inner_type)) = args.args.first()
{
return Some(inner_type);
}
None
}