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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
use super::helpers::{
escape_c_keyword, format_expr_to_c, format_type_to_c, generate_nested_field_access,
primitive_to_c_type, sanitize_type_name,
};
use super::ir_footprint::{resolve_param_binding, sanitize_symbol};
use crate::abi::expr::ExprKind;
use crate::abi::resolved::{ConstantStatus, ResolvedType, ResolvedTypeKind, Size};
use crate::abi::types::PrimitiveType;
use crate::codegen::shared::ir::TypeIr;
use std::collections::{BTreeMap, HashSet};
use std::fmt::Write;
pub fn emit_validate_fn_struct(resolved_type: &ResolvedType, type_ir: Option<&TypeIr>) -> String {
let mut output = String::new();
let type_name = sanitize_type_name(&resolved_type.name);
let type_name_str = type_name.as_str();
let legacy_fn = format!("{}_validate_legacy", type_name);
write!(
output,
"static int {}( void const * buffer, uint64_t buf_sz, uint64_t * out_bytes_consumed ) {{\n",
legacy_fn
)
.unwrap();
if let Size::Const(_size) = resolved_type.size {
/* CASE 1: Constant size struct */
write!(output, " uint64_t offset = sizeof( {}_t );\n", type_name).unwrap();
/* Check buffer size */
write!(
output,
" if( offset > buf_sz ) return 1; /* Buffer too small */\n"
)
.unwrap();
/* Iterate through fields to validate enums and typerefs */
let mut init = false;
if let ResolvedTypeKind::Struct { fields, .. } = &resolved_type.kind {
for field in fields {
let escaped_name = escape_c_keyword(&field.name);
match &field.field_type.kind {
ResolvedTypeKind::Enum {
tag_expression,
tag_constant_status,
variants,
} => {
if !init {
write!(
output,
" {}_t const * self = ({}_t const *)buffer;\n",
type_name, type_name
)
.unwrap();
init = true;
}
write!(output, "/* Validate enum field '{}' */\n", field.name).unwrap();
/* Extract tag value */
if let ExprKind::FieldRef(field_ref) = tag_expression {
let tag_path = field_ref.path.join(".");
output
.push_str(&generate_nested_field_access(&tag_path, type_name_str));
} else if let ConstantStatus::NonConstant(field_refs) = tag_constant_status
{
for field_ref in field_refs.keys() {
output.push_str(&generate_nested_field_access(
field_ref,
type_name_str,
));
}
let non_constant_refs: Vec<String> =
field_refs.keys().cloned().collect();
let tag_expr_str =
format_expr_to_c(&tag_expression, &non_constant_refs);
write!(output, " int64_t computed_tag = {};\n", tag_expr_str).unwrap();
}
/* Check tag against valid variants */
let valid_tag_var = format!("valid_tag_{}", field.name);
write!(output, " int {} = 0;\n", valid_tag_var).unwrap();
for variant in variants {
if let ExprKind::FieldRef(field_ref) = tag_expression {
let tag_var_name = field_ref.path.join(".").replace(".", "_");
write!(
output,
" if( {} == {} ) {} = 1; /* {} */\n",
tag_var_name, variant.tag_value, valid_tag_var, variant.name
)
.unwrap();
} else if let ConstantStatus::NonConstant(_) = tag_constant_status {
write!(
output,
" if( computed_tag == {} ) {} = 1; /* {} */\n",
variant.tag_value, valid_tag_var, variant.name
)
.unwrap();
}
}
write!(
output,
" if( !{} ) return 2; /* Invalid tag value */\n\n",
valid_tag_var
)
.unwrap();
}
ResolvedTypeKind::TypeRef { target_name, .. } => {
if !init {
write!(
output,
" {}_t const * self = ({}_t const *)buffer;\n",
type_name, type_name
)
.unwrap();
init = true;
}
write!(
output,
"\n /* Validate typeref field '{}' */\n",
field.name
)
.unwrap();
write!(output, " {{\n").unwrap();
write!(output, " int err = {}_validate( (uint8_t const *)buffer + offsetof( {}_t, {} ), buf_sz - offsetof( {}_t, {} ), NULL );\n",
target_name, type_name, escaped_name, type_name, escaped_name).unwrap();
write!(output, " if( err ) return err;\n").unwrap();
write!(output, " }}\n").unwrap();
}
_ => {
/* Primitive, array, or inline struct/union - no validation needed for constant size */
}
}
}
}
write!(
output,
" if( out_bytes_consumed ) *out_bytes_consumed = offset;\n"
)
.unwrap();
write!(output, " return 0; /* Success */\n").unwrap();
} else {
/* CASE 2: Variable size struct */
write!(
output,
" {}_t const * self = ({}_t const *)buffer;\n",
type_name, type_name
)
.unwrap();
/* Gather all field references */
let mut all_field_refs: BTreeMap<String, PrimitiveType> = BTreeMap::new();
if let Size::Variable(variable_refs) = &resolved_type.size {
for refs in variable_refs.values() {
for (ref_path, prim_type) in refs {
all_field_refs
.entry(ref_path.clone())
.or_insert_with(|| prim_type.clone());
}
}
}
let mut fam_offset_code = String::new();
fam_offset_code.push_str(" /* Calculate offset past FAM fields */\n");
let mut declared_refs: HashSet<String> = HashSet::new();
if let ResolvedTypeKind::Struct { fields, .. } = &resolved_type.kind {
let mut after_variable_size_data = false;
for field in fields {
let escaped_name = escape_c_keyword(&field.name);
let is_fam = matches!(&field.field_type.size, Size::Variable(_));
if is_fam && !after_variable_size_data {
/* For enum fields, body is inline bytes, not an actual struct field */
if matches!(&field.field_type.kind, ResolvedTypeKind::Enum { .. }) {
write!(output, " uint64_t offset = sizeof( {}_t );\n", type_name).unwrap();
} else {
write!(
output,
" uint64_t offset = offsetof( {}_t, {} );\n",
type_name, field.name
)
.unwrap();
}
write!(output, " if( offset > buf_sz ) return 1;\n").unwrap();
after_variable_size_data = true;
}
if !after_variable_size_data {
/* Validate fields before FAM (similar to constant-size case) */
match &field.field_type.kind {
ResolvedTypeKind::Enum {
tag_expression,
tag_constant_status,
variants,
} => {
write!(
output,
" /* Validate enum field '{}' (before FAM) */\n",
field.name
)
.unwrap();
/* Extract and validate tag */
if let ExprKind::FieldRef(field_ref) = tag_expression {
let tag_path = field_ref.path.join(".");
output.push_str(&generate_nested_field_access(
&tag_path,
type_name_str,
));
} else if let ConstantStatus::NonConstant(field_refs) =
tag_constant_status
{
for field_ref in field_refs.keys() {
output.push_str(&generate_nested_field_access(
field_ref,
type_name_str,
));
}
let non_constant_refs: Vec<String> =
field_refs.keys().cloned().collect();
let tag_expr_str =
format_expr_to_c(&tag_expression, &non_constant_refs);
write!(output, " int64_t computed_tag = {};\n", tag_expr_str)
.unwrap();
}
let valid_tag_var = format!("valid_tag_{}", field.name);
write!(output, " int {} = 0;\n", valid_tag_var).unwrap();
for variant in variants {
if let ExprKind::FieldRef(field_ref) = tag_expression {
let tag_var_name = field_ref.path.join(".").replace(".", "_");
write!(
output,
" if( {} == {} ) {} = 1;\n",
tag_var_name, variant.tag_value, valid_tag_var
)
.unwrap();
} else if let ConstantStatus::NonConstant(_) = tag_constant_status {
write!(
output,
" if( computed_tag == {} ) {} = 1;\n",
variant.tag_value, valid_tag_var
)
.unwrap();
}
}
write!(
output,
" if( !{} ) return 2; /* Invalid tag */\n\n",
valid_tag_var
)
.unwrap();
}
ResolvedTypeKind::TypeRef { target_name, .. } => {
write!(
output,
" /* Validate typeref field '{}' (before FAM) */\n",
field.name
)
.unwrap();
write!(output, " {{\n").unwrap();
write!(output, " int err = {}_validate( (uint8_t const *)buffer + offsetof( {}_t, {} ), buf_sz - offsetof( {}_t, {} ), NULL );\n",
target_name, type_name, escaped_name, type_name, escaped_name).unwrap();
write!(output, " if( err ) return err;\n").unwrap();
write!(output, " }}\n\n").unwrap();
}
_ => {}
}
}
/* Track offset calculation for FAM fields */
if after_variable_size_data {
write!(fam_offset_code, " /* Process field '{}' */\n", field.name).unwrap();
match &field.field_type.kind {
ResolvedTypeKind::Array {
element_type,
size_expression,
..
} => {
if let Size::Variable(field_map) = &field.field_type.size {
if let Some(field_refs) = field_map.get(&field.name) {
/* Read field references */
for field_ref in field_refs.keys() {
if declared_refs.insert(field_ref.clone()) {
fam_offset_code.push_str(
&generate_nested_field_access(
field_ref,
type_name_str,
),
);
}
}
let non_constant_refs: Vec<String> =
field_refs.keys().cloned().collect();
let size_expr_str =
format_expr_to_c(&size_expression, &non_constant_refs);
/* Validate array size */
write!(
fam_offset_code,
" if( ({}) < 0 ) return 3; /* Invalid array size */\n",
size_expr_str
)
.unwrap();
/* Safe multiply and add */
match &element_type.kind {
ResolvedTypeKind::TypeRef { target_name, .. } => {
write!(fam_offset_code, " {{\n").unwrap();
write!(
fam_offset_code,
" uint64_t elem_size = {}_footprint();\n",
target_name
)
.unwrap();
write!(fam_offset_code, " uint64_t array_bytes;\n")
.unwrap();
write!(fam_offset_code, " if( safe_mul_u64( elem_size, (uint64_t)({}), &array_bytes ) ) return 3;\n", size_expr_str).unwrap();
write!(fam_offset_code, " if( safe_add_u64( offset, array_bytes, &offset ) ) return 3;\n").unwrap();
write!(fam_offset_code, " if( offset > buf_sz ) return 1; /* Buffer too small */\n").unwrap();
write!(fam_offset_code, " }}\n").unwrap();
}
_ => {
let elem_type_str = format_type_to_c(element_type);
write!(fam_offset_code, " {{\n").unwrap();
write!(fam_offset_code, " uint64_t array_bytes;\n")
.unwrap();
write!(fam_offset_code, " if( safe_mul_u64( sizeof( {} ), (uint64_t)({}), &array_bytes ) ) return 3;\n", elem_type_str, size_expr_str).unwrap();
write!(fam_offset_code, " if( safe_add_u64( offset, array_bytes, &offset ) ) return 3;\n").unwrap();
write!(fam_offset_code, " if( offset > buf_sz ) return 1; /* Buffer too small */\n").unwrap();
write!(fam_offset_code, " }}\n").unwrap();
}
}
}
}
}
ResolvedTypeKind::TypeRef { target_name, .. } => {
write!(
fam_offset_code,
" /* Validate typeref '{}' */\n",
field.name
)
.unwrap();
write!(fam_offset_code, " {{\n").unwrap();
write!(fam_offset_code, " uint64_t consumed = 0;\n").unwrap();
write!(fam_offset_code, " int err = {}_validate( (uint8_t const *)buffer + offset, buf_sz - offset, &consumed );\n", target_name).unwrap();
write!(fam_offset_code, " if( err ) return err;\n").unwrap();
write!(
fam_offset_code,
" if( safe_add_u64( offset, consumed, &offset ) ) return 3;\n"
)
.unwrap();
write!(
fam_offset_code,
" if( offset > buf_sz ) return 1; /* Buffer too small */\n"
)
.unwrap();
write!(fam_offset_code, " }}\n").unwrap();
}
ResolvedTypeKind::Primitive { prim_type } => {
let prim_type_str = primitive_to_c_type(prim_type);
write!(
fam_offset_code,
" if( safe_add_u64( offset, sizeof( {} ), &offset ) ) return 3;\n",
prim_type_str
)
.unwrap();
write!(
fam_offset_code,
" if( offset > buf_sz ) return 1; /* Buffer too small */\n"
)
.unwrap();
}
ResolvedTypeKind::Enum {
tag_expression,
tag_constant_status,
variants,
} => {
write!(
fam_offset_code,
" /* Validate enum field '{}' (after FAM) */\n",
field.name
)
.unwrap();
/* Extract and validate tag */
if let ExprKind::FieldRef(field_ref) = tag_expression {
let tag_path = field_ref.path.join(".");
if declared_refs.insert(tag_path.clone()) {
fam_offset_code.push_str(&generate_nested_field_access(
&tag_path,
type_name_str,
));
}
} else if let ConstantStatus::NonConstant(field_refs) =
tag_constant_status
{
for field_ref in field_refs.keys() {
if declared_refs.insert(field_ref.clone()) {
fam_offset_code.push_str(&generate_nested_field_access(
field_ref,
type_name_str,
));
}
}
let non_constant_refs: Vec<String> =
field_refs.keys().cloned().collect();
let tag_expr_str =
format_expr_to_c(&tag_expression, &non_constant_refs);
write!(
fam_offset_code,
" int64_t computed_tag = {};\n",
tag_expr_str
)
.unwrap();
}
/* Check tag against valid variants */
let valid_tag_var = format!("valid_tag_{}", field.name);
write!(fam_offset_code, " int {} = 0;\n", valid_tag_var).unwrap();
for variant in variants {
if let ExprKind::FieldRef(field_ref) = tag_expression {
let tag_var_name = field_ref.path.join(".").replace(".", "_");
write!(
fam_offset_code,
" if( {} == {} ) {} = 1; /* {} */\n",
tag_var_name,
variant.tag_value,
valid_tag_var,
variant.name
)
.unwrap();
} else if let ConstantStatus::NonConstant(_) = tag_constant_status {
write!(
fam_offset_code,
" if( computed_tag == {} ) {} = 1; /* {} */\n",
variant.tag_value, valid_tag_var, variant.name
)
.unwrap();
}
}
write!(
fam_offset_code,
" if( !{} ) return 2; /* Invalid tag value */\n\n",
valid_tag_var
)
.unwrap();
/* Calculate size based on whether enum is variable-sized */
if let Size::Variable(_variable_refs) = &resolved_type.size {
if let Some(_field_map) = _variable_refs.get(&field.name) {
/* Variable-sized enum - calculate size inline by switching on tag */
write!(fam_offset_code, " /* Variable-sized enum - calculate size based on tag */\n").unwrap();
/* Get tag variable name */
let tag_var_name =
if let ExprKind::FieldRef(tag_field_ref) = tag_expression {
tag_field_ref.path.join(".").replace(".", "_")
} else {
String::from("computed_tag")
};
/* Generate switch on tag to add variant size */
write!(fam_offset_code, " switch ( {} ) {{\n", tag_var_name)
.unwrap();
for variant in variants {
let variant_ident = escape_c_keyword(&variant.name);
write!(
fam_offset_code,
" case {}:\n",
variant.tag_value
)
.unwrap();
write!(fam_offset_code, " {{\n").unwrap();
match &variant.variant_type.size {
Size::Const(size) => {
write!(fam_offset_code, " if( safe_add_u64( offset, {}, &offset ) ) return 3;\n", size).unwrap();
}
Size::Variable(_) => {
/* For variable-size variants, call variant footprint function */
let variant_type_name = format!(
"{}_{}_inner",
type_name, variant_ident
);
write!(fam_offset_code, " if( safe_add_u64( offset, {}_footprint(), &offset ) ) return 3;\n",
variant_type_name).unwrap();
}
}
write!(fam_offset_code, " break;\n").unwrap();
write!(fam_offset_code, " }}\n").unwrap();
}
write!(fam_offset_code, " default:\n").unwrap();
write!(fam_offset_code, " break;\n").unwrap();
write!(fam_offset_code, " }}\n").unwrap();
write!(
fam_offset_code,
" if( offset > buf_sz ) return 1; /* Buffer too small */\n"
)
.unwrap();
} else {
/* Constant-sized enum - all variants have same size */
if let Size::Const(size) = &field.field_type.size {
write!(fam_offset_code, " if( safe_add_u64( offset, {}, &offset ) ) return 3;\n", size).unwrap();
write!(fam_offset_code, " if( offset > buf_sz ) return 1; /* Buffer too small */\n").unwrap();
}
}
} else {
/* Constant-sized enum - all variants have same size */
if let Size::Const(size) = &field.field_type.size {
write!(
fam_offset_code,
" if( safe_add_u64( offset, {}, &offset ) ) return 3;\n",
size
)
.unwrap();
write!(
fam_offset_code,
" if( offset > buf_sz ) return 1; /* Buffer too small */\n"
)
.unwrap();
}
}
}
_ => {
write!(
fam_offset_code,
" /* TODO: Handle other field types after FAM */\n"
)
.unwrap();
}
}
}
}
}
output.push_str(&fam_offset_code);
write!(
output,
"\n if( out_bytes_consumed ) *out_bytes_consumed = offset;\n"
)
.unwrap();
write!(output, " return 0; /* Success */\n").unwrap();
}
write!(output, "}}\n\n").unwrap();
emit_validator_entrypoint(&mut output, &type_name, &legacy_fn, resolved_type, type_ir);
output
}
pub fn emit_validate_fn_union(resolved_type: &ResolvedType, type_ir: Option<&TypeIr>) -> String {
let mut output = String::new();
let type_name = sanitize_type_name(&resolved_type.name);
let legacy_fn = format!("{}_validate_legacy", type_name);
write!(
output,
"static int {}( void const * buffer, uint64_t buf_sz, uint64_t * out_bytes_consumed ) {{\n",
legacy_fn
)
.unwrap();
if let Size::Const(_size) = resolved_type.size {
write!(output, " if( sizeof( {}_t ) > buf_sz ) {{\n", type_name).unwrap();
write!(output, " return 1; /* Buffer too small */\n").unwrap();
write!(output, " }}\n").unwrap();
/* Set bytes consumed */
write!(output, " if( out_bytes_consumed != NULL ) {{\n").unwrap();
write!(
output,
" *out_bytes_consumed = sizeof( {}_t );\n",
type_name
)
.unwrap();
write!(output, " }}\n").unwrap();
write!(output, " return 0; /* Success */\n").unwrap();
} else {
panic!("Unions should have constant size");
}
write!(output, "}}\n\n").unwrap();
emit_validator_entrypoint(&mut output, &type_name, &legacy_fn, resolved_type, type_ir);
output
}
/* ERROR CODES
1 = Buffer too small
2 = Invalid tag value
3 = Invalid array size
4 = other
*/
pub fn emit_validate_fn(resolved_type: &ResolvedType, type_ir: Option<&TypeIr>) -> String {
match &resolved_type.kind {
ResolvedTypeKind::Struct { .. } => emit_validate_fn_struct(&resolved_type, type_ir),
ResolvedTypeKind::Union { .. } => emit_validate_fn_union(&resolved_type, type_ir),
ResolvedTypeKind::SizeDiscriminatedUnion { .. } => {
format!("/* TODO: EMIT SET FN FOR SizeDiscriminatedUnion */\n\n")
}
_ => {
/* Unsupported type*/
String::new()
}
}
}
fn emit_validator_entrypoint(
output: &mut String,
type_name: &str,
legacy_fn: &str,
resolved_type: &ResolvedType,
type_ir: Option<&TypeIr>,
) {
writeln!(
output,
"int {}_validate( void const * buffer, uint64_t buf_sz, uint64_t * out_bytes_consumed ) {{",
type_name
)
.unwrap();
let mut ir_call_data = None;
let mut ir_missing_comment = None;
if let Some(ir) = type_ir {
match prepare_ir_validate_call(resolved_type, ir) {
Ok(data) => ir_call_data = Some(data),
Err(missing) => {
if !missing.is_empty() {
ir_missing_comment = Some(format!(
"IR validator check skipped (missing params: {})",
missing.join(", ")
));
}
}
}
}
if let (Some(ir), Some(ref data)) = (type_ir, ir_call_data.as_ref()) {
emit_payload_param_setup(output, type_name, &data.payloads);
emit_ir_validate_primary_path(output, type_name, ir, data);
writeln!(output, "}}\n").unwrap();
return;
}
emit_legacy_validate_body(
output,
type_name,
legacy_fn,
resolved_type,
ir_missing_comment.take(),
);
writeln!(output, "}}\n").unwrap();
}
fn emit_legacy_validate_body(
output: &mut String,
_type_name: &str,
legacy_fn: &str,
_resolved_type: &ResolvedType,
comment: Option<String>,
) {
if let Some(msg) = comment {
writeln!(output, " /* {} */", msg).unwrap();
}
writeln!(output, " uint64_t tn_bytes_sink = 0ULL;").unwrap();
writeln!(
output,
" uint64_t * tn_bytes_ptr = out_bytes_consumed ? out_bytes_consumed : &tn_bytes_sink;"
)
.unwrap();
writeln!(
output,
" int tn_legacy_err = {}( buffer, buf_sz, tn_bytes_ptr );",
legacy_fn
)
.unwrap();
writeln!(output, " uint64_t tn_legacy_bytes = 0ULL;").unwrap();
writeln!(
output,
" if( tn_legacy_err == 0 ) tn_legacy_bytes = *tn_bytes_ptr;\n"
)
.unwrap();
writeln!(output, " (void)tn_legacy_bytes;").unwrap();
writeln!(output, " return tn_legacy_err;").unwrap();
}
fn emit_ir_validate_primary_path(
output: &mut String,
type_name: &str,
type_ir: &TypeIr,
ir_data: &IrValidateCallData,
) {
emit_ir_param_decls(output, type_name, ir_data);
writeln!(output, " uint64_t tn_ir_bytes = 0ULL;").unwrap();
let call = format_ir_validate_call(type_ir, "tn_ir_bytes", &ir_data.args);
writeln!(output, " int tn_ir_err = {};", call).unwrap();
writeln!(
output,
" if( out_bytes_consumed ) *out_bytes_consumed = tn_ir_bytes;"
)
.unwrap();
writeln!(output, " return tn_ir_err;").unwrap();
}
fn emit_ir_param_decls(output: &mut String, type_name: &str, ir_data: &IrValidateCallData) {
let mut emitted_self = false;
for (var, source) in &ir_data.params {
match source {
IrParamSource::Getter { path } => {
if !emitted_self {
writeln!(
output,
" {}_t const * tn_ir_self = ({}_t const *)buffer;",
type_name, type_name
)
.unwrap();
emitted_self = true;
}
let getter = path.replace('.', "_");
writeln!(
output,
" int64_t {} = (int64_t)({}_get_{}( tn_ir_self ));",
var, type_name, getter
)
.unwrap();
}
IrParamSource::Payload => {}
}
}
}
fn emit_payload_param_setup(output: &mut String, type_name: &str, payloads: &[SduPayloadBinding]) {
if payloads.is_empty() {
return;
}
for payload in payloads {
writeln!(
output,
" size_t {}_offset = offsetof( {}_t, {} );",
payload.var, type_name, payload.field_name
)
.unwrap();
writeln!(output, " if( {}_offset > buf_sz ) return 1;", payload.var).unwrap();
writeln!(
output,
" uint64_t {} = buf_sz - {}_offset;",
payload.var, payload.var
)
.unwrap();
}
}
fn format_ir_validate_call(type_ir: &TypeIr, bytes_ident: &str, args: &[String]) -> String {
let fn_name = sanitize_symbol(&format!("{}_validate_ir", type_ir.type_name));
if args.is_empty() {
format!("{}( buf_sz, &{} )", fn_name, bytes_ident)
} else {
format!(
"{}( buf_sz, &{}, {} )",
fn_name,
bytes_ident,
args.join(", ")
)
}
}
struct IrValidateCallData {
params: Vec<(String, IrParamSource)>,
payloads: Vec<SduPayloadBinding>,
args: Vec<String>,
}
enum IrParamSource {
Getter { path: String },
Payload,
}
struct SduPayloadBinding {
var: String,
field_name: String,
}
fn prepare_ir_validate_call(
resolved_type: &ResolvedType,
type_ir: &TypeIr,
) -> Result<IrValidateCallData, Vec<String>> {
let bindings = collect_dynamic_param_bindings(resolved_type);
let available: Vec<String> = bindings.keys().cloned().collect();
let mut args = Vec::new();
let mut params: Vec<(String, IrParamSource)> = Vec::new();
let mut payloads: Vec<SduPayloadBinding> = Vec::new();
let mut missing = Vec::new();
for param in &type_ir.parameters {
let sanitized = sanitize_symbol(¶m.name.replace('.', "_"));
if let Some(binding) = resolve_param_binding(&sanitized, &available) {
if let Some(path) = bindings.get(binding.as_str()) {
if !params.iter().any(|(var, _)| var == binding) {
params.push((
binding.clone(),
IrParamSource::Getter { path: path.clone() },
));
}
args.push(format!("(uint64_t){}", binding));
} else {
missing.push(sanitized);
}
} else if let Some(field_name) = extract_payload_field_name(¶m.name) {
let escaped_field = escape_c_keyword(&field_name);
if !payloads.iter().any(|p| p.var == sanitized) {
payloads.push(SduPayloadBinding {
var: sanitized.clone(),
field_name: escaped_field,
});
params.push((sanitized.clone(), IrParamSource::Payload));
}
args.push(format!("(uint64_t){}", sanitized));
} else {
missing.push(sanitized);
}
}
if missing.is_empty() {
Ok(IrValidateCallData {
params,
payloads,
args,
})
} else {
Err(missing)
}
}
fn collect_dynamic_param_bindings(resolved_type: &ResolvedType) -> BTreeMap<String, String> {
let mut map = BTreeMap::new();
for refs in resolved_type.dynamic_params.values() {
for (path, _) in refs {
if path.starts_with("_typeref_") {
continue;
}
let sanitized = sanitize_symbol(&path.replace('.', "_"));
map.entry(sanitized).or_insert_with(|| path.clone());
}
}
map
}
fn extract_payload_field_name(param_name: &str) -> Option<String> {
let base = param_name.strip_suffix(".payload_size")?;
let normalized = base.replace("::", ".");
normalized.rsplit('.').next().map(|field| field.to_string())
}