thru-abi-gen 0.2.30

ABI code generation utilities for the Thru blockchain
Documentation
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
use super::helpers::{
    escape_c_keyword, format_expr_to_c, format_type_to_c, is_nested_complex_type,
    primitive_to_c_type, sanitize_type_name,
};
use crate::abi::resolved::{ResolvedType, ResolvedTypeKind, Size};
use std::fmt::Write;

fn emit_init_fn_struct(resolved_type: &ResolvedType) -> String {
    let mut output = String::new();
    let type_name = sanitize_type_name(&resolved_type.name);

    let fields = if let ResolvedTypeKind::Struct { fields, .. } = &resolved_type.kind {
        fields
    } else {
        return output;
    };

    #[derive(Clone)]
    enum FieldInitKind {
        Primitive {
            size_expr: String,
        },
        Array {
            len_name: String,
            elem_size_expr: String,
        },
        ConstPointer {
            size_expr: String,
        },
        VarPointer {
            size_param_name: String,
        },
    }

    struct FieldInitInfo {
        raw_name: String,
        param_name: String,
        init_kind: FieldInitKind,
        is_fam: bool,
    }

    let mut field_param_lines: Vec<String> = Vec::new();
    let mut field_infos: Vec<FieldInitInfo> = Vec::new();

    for (_idx, field) in fields.iter().enumerate() {
        let param_name = escape_c_keyword(&field.name);
        let is_fam = matches!(&field.field_type.size, Size::Variable(_));

        /* Skip enum fields in init - they don't have actual struct fields and are initialized separately */
        if matches!(&field.field_type.kind, ResolvedTypeKind::Enum { .. }) {
            continue;
        }

        match &field.field_type.kind {
            ResolvedTypeKind::Primitive { prim_type } => {
                let type_str = primitive_to_c_type(prim_type).to_string();
                field_param_lines.push(format!("{} {}", type_str, param_name.clone()));
                field_infos.push(FieldInitInfo {
                    raw_name: field.name.clone(),
                    param_name: param_name.clone(),
                    init_kind: FieldInitKind::Primitive {
                        size_expr: format!("sizeof( {} )", type_str),
                    },
                    is_fam,
                });
            }
            ResolvedTypeKind::Array { element_type, .. } => {
                let len_name = format!("{}_len", param_name);
                let mut element_param_type = format_type_to_c(element_type);
                if is_nested_complex_type(element_type) {
                    element_param_type = format!("{}_{}_inner_t", type_name, field.name);
                }

                field_param_lines.push(format!(
                    "{} const * {}, uint64_t {}",
                    element_param_type,
                    param_name.clone(),
                    len_name.clone()
                ));

                field_infos.push(FieldInitInfo {
                    raw_name: field.name.clone(),
                    param_name: param_name.clone(),
                    init_kind: FieldInitKind::Array {
                        len_name,
                        elem_size_expr: format!("sizeof( {} )", element_param_type),
                    },
                    is_fam,
                });
            }
            _ => {
                /* Handles TypeRef, inline structs, unions, enums, etc. */

                /* Special handling for enums: they're just raw variant bytes */
                if matches!(&field.field_type.kind, ResolvedTypeKind::Enum { .. }) {
                    /* Enum fields are always variable-sized (accept void const * + size) */
                    let size_param_name = format!("{}_sz", param_name);
                    field_param_lines.push(format!(
                        "void const * {}, uint64_t {}",
                        param_name.clone(),
                        size_param_name.clone()
                    ));
                    field_infos.push(FieldInitInfo {
                        raw_name: field.name.clone(),
                        param_name: param_name.clone(),
                        init_kind: FieldInitKind::VarPointer { size_param_name },
                        is_fam: true, /* Enums are treated like FAMs */
                    });
                } else {
                    /* Regular complex types (TypeRef, Union, etc.) */
                    let mut pointer_type = format_type_to_c(&field.field_type);
                    if is_nested_complex_type(&field.field_type) {
                        pointer_type = format!("{}_{}_inner_t", type_name, field.name);
                    }

                    /* Check if this field is variable-sized (FAM) */
                    if is_fam {
                        /* Variable-sized: need explicit size parameter */
                        let size_param_name = format!("{}_sz", param_name);
                        field_param_lines.push(format!(
                            "{} const * {}, uint64_t {}",
                            pointer_type,
                            param_name.clone(),
                            size_param_name.clone()
                        ));
                        field_infos.push(FieldInitInfo {
                            raw_name: field.name.clone(),
                            param_name: param_name.clone(),
                            init_kind: FieldInitKind::VarPointer { size_param_name },
                            is_fam,
                        });
                    } else {
                        /* Constant-sized: use sizeof */
                        field_param_lines.push(format!(
                            "{} const * {}",
                            pointer_type,
                            param_name.clone()
                        ));
                        field_infos.push(FieldInitInfo {
                            raw_name: field.name.clone(),
                            param_name: param_name.clone(),
                            init_kind: FieldInitKind::ConstPointer {
                                size_expr: format!("sizeof( {} )", pointer_type),
                            },
                            is_fam,
                        });
                    }
                }
            }
        }
    }

    if field_param_lines.is_empty() {
        write!(
            output,
            "int {}_init( void * buffer, uint64_t buf_sz ) {{\n",
            type_name
        )
        .unwrap();
    } else {
        write!(
            output,
            "int {}_init( void * buffer, uint64_t buf_sz,\n",
            type_name
        )
        .unwrap();
        for (idx, line) in field_param_lines.iter().enumerate() {
            let suffix = if idx + 1 == field_param_lines.len() {
                "\n"
            } else {
                ",\n"
            };
            write!(output, "  {}{}", line, suffix).unwrap();
        }
        write!(output, ") {{\n").unwrap();
    }

    write!(output, "  if( sizeof( {}_t ) > buf_sz ) {{\n", type_name).unwrap();
    write!(output, "    return -1; /* Buffer too small */\n").unwrap();
    write!(output, "  }}\n").unwrap();

    let mut after_variable_size_data = false;
    for info in &field_infos {
        if info.is_fam && !after_variable_size_data {
            after_variable_size_data = true;
            write!(output, "  /* VERIFYING SIZE */\n").unwrap();
            write!(
                output,
                "  uint64_t offset = offsetof( {}_t, {} );\n",
                type_name, info.raw_name
            )
            .unwrap();
        }
        if !after_variable_size_data {
            continue;
        }
        match &info.init_kind {
            FieldInitKind::Primitive { size_expr } => {
                let field_size = format!("(uint64_t)({})", size_expr);
                write!(output, "  {{  /* field: {} */\n", info.raw_name).unwrap();
                write!(output, "    uint64_t field_bytes = {};\n", field_size).unwrap();
                write!(
                    output,
                    "    if( safe_add_u64( offset, field_bytes, &offset ) ) return -1;\n"
                )
                .unwrap();
                write!(output, "  }}\n").unwrap();
            }
            FieldInitKind::Array {
                len_name,
                elem_size_expr,
            } => {
                let elem_size = format!("(uint64_t)({})", elem_size_expr);
                write!(output, "  {{  /* field: {} */\n", info.raw_name).unwrap();
                write!(output, "    uint64_t elem_size = {};\n", elem_size).unwrap();
                write!(output, "    uint64_t field_bytes = 0;\n").unwrap();
                write!(
                    output,
                    "    if( safe_mul_u64( elem_size, {}, &field_bytes ) ) return -1;\n",
                    len_name
                )
                .unwrap();
                write!(
                    output,
                    "    if( safe_add_u64( offset, field_bytes, &offset ) ) return -1;\n"
                )
                .unwrap();
                write!(output, "  }}\n").unwrap();
            }
            FieldInitKind::ConstPointer { size_expr } => {
                let field_size = format!("(uint64_t)({})", size_expr);
                write!(output, "  {{  /* field: {} */\n", info.raw_name).unwrap();
                write!(output, "    uint64_t field_bytes = {};\n", field_size).unwrap();
                write!(
                    output,
                    "    if( safe_add_u64( offset, field_bytes, &offset ) ) return -1;\n"
                )
                .unwrap();
                write!(output, "  }}\n").unwrap();
            }
            FieldInitKind::VarPointer { size_param_name } => {
                write!(
                    output,
                    "  {{  /* field: {} (variable-sized) */\n",
                    info.raw_name
                )
                .unwrap();
                write!(output, "    uint64_t field_bytes = {};\n", size_param_name).unwrap();
                write!(
                    output,
                    "    if( safe_add_u64( offset, field_bytes, &offset ) ) return -1;\n"
                )
                .unwrap();
                write!(output, "  }}\n").unwrap();
            }
        }
        write!(output, "  if( offset > buf_sz ) return -1;\n").unwrap();
    }

    /* Pre-compute which fields come after variable-size data by scanning original fields list */
    let mut has_variable_size_data = false;
    let mut first_variable_size_is_enum = false;
    for field in fields {
        if matches!(&field.field_type.size, Size::Variable(_)) {
            if !has_variable_size_data {
                has_variable_size_data = true;
                first_variable_size_is_enum =
                    matches!(&field.field_type.kind, ResolvedTypeKind::Enum { .. });
            }
            break;
        }
    }

    after_variable_size_data = false;
    write!(output, "  /* SETTING FIELD VALUES */\n").unwrap();
    write!(
        output,
        "  {}_t * self = ({}_t *)buffer;\n",
        type_name, type_name
    )
    .unwrap();

    for info in field_infos.iter() {
        if info.is_fam && !after_variable_size_data {
            after_variable_size_data = true;
            /* For enum fields, calculate offset as sizeof(struct) since enum body is not in the struct */
            if first_variable_size_is_enum {
                write!(output, "  uint64_t offset = sizeof( {}_t );\n", type_name).unwrap();
            } else {
                write!(
                    output,
                    "  uint64_t offset = offsetof( {}_t, {} );\n",
                    type_name, info.raw_name
                )
                .unwrap();
            }
        } else if has_variable_size_data && !after_variable_size_data {
            /* We haven't hit a FAM in field_infos yet, but we know there's variable-size data in the original fields (probably an enum) */
            after_variable_size_data = true;
            /* For enum fields, calculate offset as sizeof(struct) since enum body is not in the struct */
            if first_variable_size_is_enum {
                write!(output, "  uint64_t offset = sizeof( {}_t );\n", type_name).unwrap();
            }
        }
        match &info.init_kind {
            FieldInitKind::Primitive { size_expr } => {
                let field_size = format!("(uint64_t)({})", size_expr);
                if after_variable_size_data {
                    write!(output, "  {{  /* field: {} */\n", info.raw_name).unwrap();
                    write!(output, "    uint64_t field_bytes = {};\n", field_size).unwrap();
                    write!(
                        output,
                        "    memcpy( (unsigned char *)self + offset, &{}, field_bytes );\n",
                        info.param_name
                    )
                    .unwrap();
                    write!(output, "    offset += field_bytes;\n").unwrap();
                    write!(output, "  }}\n").unwrap();
                } else {
                    write!(
                        output,
                        "  memcpy( &self->{}, &{}, {} ); // field: {}\n",
                        info.raw_name, info.param_name, field_size, info.raw_name
                    )
                    .unwrap();
                }
            }
            FieldInitKind::Array {
                len_name,
                elem_size_expr,
            } => {
                let elem_size = format!("(uint64_t)({})", elem_size_expr);
                if after_variable_size_data {
                    write!(output, "  {{  /* field: {} */\n", info.raw_name).unwrap();
                    write!(output, "    uint64_t elem_size = {};\n", elem_size).unwrap();
                    write!(output, "    uint64_t field_bytes = 0;\n").unwrap();
                    write!(
                        output,
                        "    if( safe_mul_u64( elem_size, {}, &field_bytes ) ) return -1;\n",
                        len_name
                    )
                    .unwrap();
                    write!(
                        output,
                        "    memcpy( (unsigned char *)self + offset, {}, field_bytes );\n",
                        info.param_name
                    )
                    .unwrap();
                    write!(output, "    offset += field_bytes;\n").unwrap();
                    write!(output, "  }}\n").unwrap();
                } else {
                    write!(output, "  {{  /* field: {} */\n", info.raw_name).unwrap();
                    write!(output, "    uint64_t elem_size = {};\n", elem_size).unwrap();
                    write!(output, "    uint64_t field_bytes = 0;\n").unwrap();
                    write!(
                        output,
                        "    if( safe_mul_u64( elem_size, {}, &field_bytes ) ) return -1;\n",
                        len_name
                    )
                    .unwrap();
                    write!(
                        output,
                        "    memcpy( self->{}, {}, field_bytes );\n",
                        info.raw_name, info.param_name
                    )
                    .unwrap();
                    write!(output, "  }}\n").unwrap();
                }
            }
            FieldInitKind::ConstPointer { size_expr } => {
                let field_size = format!("(uint64_t)({})", size_expr);
                if after_variable_size_data {
                    write!(output, "  {{  /* field: {} */\n", info.raw_name).unwrap();
                    write!(output, "    uint64_t field_bytes = {};\n", field_size).unwrap();
                    write!(
                        output,
                        "    memcpy( (unsigned char *)self + offset, {}, field_bytes );\n",
                        info.param_name
                    )
                    .unwrap();
                    write!(output, "    offset += field_bytes;\n").unwrap();
                    write!(output, "  }}\n").unwrap();
                } else {
                    write!(
                        output,
                        "  memcpy( &self->{}, {}, {} ); // field: {}\n",
                        info.raw_name, info.param_name, field_size, info.raw_name
                    )
                    .unwrap();
                }
            }
            FieldInitKind::VarPointer { size_param_name } => {
                if after_variable_size_data {
                    write!(
                        output,
                        "  {{  /* field: {} (variable-sized) */\n",
                        info.raw_name
                    )
                    .unwrap();
                    write!(output, "    uint64_t field_bytes = {};\n", size_param_name).unwrap();
                    write!(
                        output,
                        "    memcpy( (unsigned char *)self + offset, {}, field_bytes );\n",
                        info.param_name
                    )
                    .unwrap();
                    write!(output, "    offset += field_bytes;\n").unwrap();
                    write!(output, "  }}\n").unwrap();
                } else {
                    write!(
                        output,
                        "  memcpy( &self->{}, {}, {} ); // field: {} (variable-sized)\n",
                        info.raw_name, info.param_name, size_param_name, info.raw_name
                    )
                    .unwrap();
                }
            }
        }
    }

    write!(
        output,
        "  int err = {}_validate( buffer, buf_sz, NULL );\n",
        type_name
    )
    .unwrap();
    write!(output, "  if( err ) return err;\n").unwrap();
    write!(output, "  return 0;\n").unwrap();
    write!(output, "}}\n\n").unwrap();

    output
}

fn emit_init_fn_union(resolved_type: &ResolvedType) -> String {
    let mut output = String::new();
    let type_name = sanitize_type_name(&resolved_type.name);

    let variants = match &resolved_type.kind {
        ResolvedTypeKind::Union { variants } => variants,
        _ => return output,
    };

    for variant in variants {
        let escaped_variant = escape_c_keyword(&variant.name);

        let mut array_size_expr: Option<String> = None;
        let param_decl = match &variant.field_type.kind {
            ResolvedTypeKind::Primitive { .. } => {
                let type_str = format_type_to_c(&variant.field_type);
                format!("{} value", type_str)
            }
            ResolvedTypeKind::Array {
                element_type,
                size_expression,
                ..
            } => {
                let mut element_c_type = format_type_to_c(element_type);
                if is_nested_complex_type(element_type) {
                    element_c_type = format!("{}_{}_inner_t", type_name, escaped_variant);
                }
                array_size_expr = Some(format_expr_to_c(&size_expression, &[]));
                format!("{} const * value, uint64_t len", element_c_type)
            }
            ResolvedTypeKind::TypeRef { target_name, .. } => {
                format!("{}_t const * value", target_name)
            }
            _ => {
                let target_name = if is_nested_complex_type(&variant.field_type) {
                    format!("{}_{}_inner_t", type_name, escaped_variant)
                } else {
                    format_type_to_c(&variant.field_type)
                };
                format!("{} const * value", target_name)
            }
        };

        write!(
            output,
            "int {}_init_{}( void * buffer, uint64_t buf_sz, {} ) {{\n",
            type_name, escaped_variant, param_decl
        )
        .unwrap();
        write!(output, "  if( sizeof( {}_t ) > buf_sz ) {{\n", type_name).unwrap();
        write!(output, "    return -1; /* Buffer too small */\n").unwrap();
        write!(output, "  }}\n").unwrap();
        write!(
            output,
            "  {}_t * self = ({}_t *)buffer;\n",
            type_name, type_name
        )
        .unwrap();
        match &variant.field_type.kind {
            ResolvedTypeKind::Primitive { .. } => {
                write!(
                    output,
                    "  memcpy( &self->{}, &value, sizeof( self->{} ) );\n",
                    escaped_variant, escaped_variant
                )
                .unwrap();
            }
            ResolvedTypeKind::Array { .. } => {
                if let Some(size_expr_str) = array_size_expr {
                    write!(output, "  assert( len == ({}) );\n", size_expr_str).unwrap();
                }
                write!(
                    output,
                    "  memcpy( self->{}, value, len * sizeof self->{}[0] );\n",
                    escaped_variant, escaped_variant
                )
                .unwrap();
            }
            _ => {
                write!(
                    output,
                    "  memcpy( &self->{}, value, sizeof( self->{} ) );\n",
                    escaped_variant, escaped_variant
                )
                .unwrap();
            }
        }
        write!(
            output,
            "  int err = {}_validate( buffer, buf_sz, NULL );\n",
            type_name
        )
        .unwrap();
        write!(output, "  if( err ) return err;\n").unwrap();
        write!(output, "  return 0;\n").unwrap();
        write!(output, "}}\n\n").unwrap();
    }

    output
}

pub fn emit_init_fn(resolved_type: &ResolvedType) -> String {
    match &resolved_type.kind {
        ResolvedTypeKind::Struct { .. } => emit_init_fn_struct(&resolved_type),
        ResolvedTypeKind::Union { .. } => emit_init_fn_union(&resolved_type),
        ResolvedTypeKind::SizeDiscriminatedUnion { .. } => {
            format!("/* TODO: EMIT SIZE FN FOR SizeDiscriminatedUnion */\n\n")
        }
        _ => {
            /* Unsupported type*/
            String::new()
        }
    }
}