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
/* Footprint function generation for Rust ABI code */

use super::helpers::{
    format_expr_to_rust, format_type_to_rust, is_nested_complex_type, primitive_to_rust_type,
};
use crate::abi::resolved::{ResolvedType, ResolvedTypeKind, Size};
use crate::abi::types::PrimitiveType;
use std::collections::BTreeMap;
use std::fmt::Write;

/* Recursively collect nested type definitions and emit their footprint functions */
pub fn collect_and_emit_nested_footprints(
    type_def: &ResolvedType,
    type_path: Option<&str>,
    output: &mut String,
) {
    /* Phase 1: Recursively process all nested complex types first */
    match &type_def.kind {
        ResolvedTypeKind::Struct { fields, .. } => {
            let current_path = type_path.unwrap_or(&type_def.name);
            for field in fields {
                if is_nested_complex_type(&field.field_type) {
                    let nested_path = format!("{}_{}", current_path, field.name);
                    collect_and_emit_nested_footprints(
                        &field.field_type,
                        Some(&nested_path),
                        output,
                    );
                }
            }
        }
        ResolvedTypeKind::Union { variants } => {
            let current_path = type_path.unwrap_or(&type_def.name);
            for variant in variants {
                if is_nested_complex_type(&variant.field_type) {
                    let nested_path = format!("{}_{}", current_path, variant.name);
                    collect_and_emit_nested_footprints(
                        &variant.field_type,
                        Some(&nested_path),
                        output,
                    );
                }
            }
        }
        ResolvedTypeKind::Enum { variants, .. } => {
            let current_path = type_path.unwrap_or(&type_def.name);
            for variant in variants {
                if is_nested_complex_type(&variant.variant_type) {
                    let nested_path = format!("{}_{}", current_path, variant.name);
                    collect_and_emit_nested_footprints(
                        &variant.variant_type,
                        Some(&nested_path),
                        output,
                    );
                }
            }
        }
        ResolvedTypeKind::SizeDiscriminatedUnion { variants } => {
            let current_path = type_path.unwrap_or(&type_def.name);
            for variant in variants {
                if is_nested_complex_type(&variant.variant_type) {
                    let nested_path = format!("{}_{}", current_path, variant.name);
                    collect_and_emit_nested_footprints(
                        &variant.variant_type,
                        Some(&nested_path),
                        output,
                    );
                }
            }
        }
        _ => {}
    }

    /* Phase 2: Emit footprint for current nested type (only if it's a nested path) */
    if type_path.is_some() && is_nested_complex_type(type_def) {
        let mut nested_type = type_def.clone();
        nested_type.name = format!("{}_inner", type_path.unwrap());
        output.push_str(&emit_footprint_fn(&nested_type));
    }
}

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

    if let Size::Const(_size) = resolved_type.size {
        /* Case 1: Constant size - emit simple sizeof function with no parameters */
        write!(output, "pub fn {}_footprint() -> u64 {{\n", type_name).unwrap();
        write!(
            output,
            "    std::mem::size_of::<{}_t>() as u64\n",
            type_name
        )
        .unwrap();
        write!(output, "}}\n\n").unwrap();
        return output;
    }

    let mut all_field_refs: BTreeMap<String, PrimitiveType> = BTreeMap::new();
    if let Size::Variable(variable_refs) = &resolved_type.size {
        for inner_refs in variable_refs.values() {
            for (ref_path, prim_type) in inner_refs {
                all_field_refs
                    .entry(ref_path.clone())
                    .or_insert_with(|| prim_type.clone());
            }
        }
    }

    // Collect tag parameters for size-discriminated union fields
    let mut sdu_tag_params: Vec<String> = Vec::new();
    if let ResolvedTypeKind::Struct { fields, .. } = &resolved_type.kind {
        for field in fields {
            if matches!(
                &field.field_type.kind,
                ResolvedTypeKind::SizeDiscriminatedUnion { .. }
            ) {
                sdu_tag_params.push(format!("{}_tag: u8", field.name));
            }
        }
    }

    /* Generate function signature with field reference parameters */
    write!(output, "pub fn {}_footprint(", type_name).unwrap();
    if all_field_refs.is_empty() && sdu_tag_params.is_empty() {
        write!(output, ") -> u64 {{\n").unwrap();
    } else {
        let mut params: Vec<String> = all_field_refs
            .iter()
            .map(|(ref_path, prim_type)| {
                format!(
                    "{}: {}",
                    ref_path.replace('.', "_"),
                    primitive_to_rust_type(prim_type)
                )
            })
            .collect();
        params.extend(sdu_tag_params);
        write!(output, "{}) -> u64 {{\n", params.join(", ")).unwrap();
    }

    let mut after_fam = false;
    if let ResolvedTypeKind::Struct { fields, .. } = &resolved_type.kind {
        for field in fields {
            let is_fam = matches!(&field.field_type.size, Size::Variable(..));
            if is_fam && !after_fam {
                // For enum fields and size-discriminated unions, the body is inline bytes, not an actual struct field
                if matches!(
                    &field.field_type.kind,
                    ResolvedTypeKind::Enum { .. } | ResolvedTypeKind::SizeDiscriminatedUnion { .. }
                ) {
                    write!(
                        output,
                        "    let mut offset: u64 = std::mem::size_of::<{}_t>() as u64;\n",
                        type_name
                    )
                    .unwrap();
                } else {
                    write!(
                        output,
                        "    let mut offset: u64 = std::mem::offset_of!({}_t, {}) as u64;\n",
                        type_name, field.name
                    )
                    .unwrap();
                }
                after_fam = true;
            }

            if after_fam {
                match &field.field_type.kind {
                    ResolvedTypeKind::Primitive { prim_type } => {
                        write!(
                            output,
                            "    offset += std::mem::size_of::<{}>() as u64;\n",
                            primitive_to_rust_type(prim_type)
                        )
                        .unwrap();
                    }
                    ResolvedTypeKind::Array { element_type, .. } => {
                        if let Size::Variable(var_refs) = &field.field_type.size {
                            /* Get all field references for this FAM */
                            let field_refs: Vec<String> = var_refs
                                .values()
                                .flat_map(|refs| refs.keys().cloned())
                                .collect();

                            /* Build size expression */
                            let params: Vec<String> = all_field_refs.keys().cloned().collect();
                            let size_expr = if let Some(var_map) = var_refs.values().next() {
                                if let Some((first_ref, _)) = var_map.iter().next() {
                                    format_expr_to_rust(
                                        &crate::abi::expr::ExprKind::FieldRef(
                                            crate::abi::expr::FieldRefExpr {
                                                path: first_ref
                                                    .split('.')
                                                    .map(|s| s.to_string())
                                                    .collect(),
                                            },
                                        ),
                                        &params,
                                    )
                                } else {
                                    "0".to_string()
                                }
                            } else {
                                "0".to_string()
                            };

                            let elem_size = match &element_type.size {
                                Size::Const(s) => format!("{}", s),
                                Size::Variable(_) => {
                                    /* Nested FAM - recursive footprint call */
                                    let nested_params: Vec<String> =
                                        field_refs.iter().map(|r| r.replace('.', "_")).collect();
                                    if nested_params.is_empty() {
                                        format!("{}_footprint()", format_type_to_rust(element_type))
                                    } else {
                                        format!(
                                            "{}_footprint({})",
                                            format_type_to_rust(element_type),
                                            nested_params.join(", ")
                                        )
                                    }
                                }
                            };

                            write!(
                                output,
                                "    offset += ({} * {}) as u64;\n",
                                size_expr, elem_size
                            )
                            .unwrap();
                        }
                    }
                    ResolvedTypeKind::SizeDiscriminatedUnion { variants } => {
                        // Size-discriminated union: size determined from tag parameter
                        let tag_param = format!("{}_tag", field.name);
                        write!(output, "    offset += match {} {{\n", tag_param).unwrap();
                        for (idx, variant) in variants.iter().enumerate() {
                            write!(output, "        {} => {},\n", idx, variant.expected_size)
                                .unwrap();
                        }
                        write!(output, "        _ => 0, // Invalid tag\n").unwrap();
                        write!(output, "    }} as u64;\n").unwrap();
                    }
                    ResolvedTypeKind::TypeRef { .. }
                    | ResolvedTypeKind::Struct { .. }
                    | ResolvedTypeKind::Union { .. } => {
                        if let Size::Variable(var_refs) = &field.field_type.size {
                            /* Variable-sized nested type */
                            let field_refs: Vec<String> = var_refs
                                .values()
                                .flat_map(|refs| refs.keys().map(|r| r.replace('.', "_")))
                                .collect();

                            if field_refs.is_empty() {
                                write!(
                                    output,
                                    "    offset += {}_footprint() as u64;\n",
                                    format_type_to_rust(&field.field_type)
                                )
                                .unwrap();
                            } else {
                                write!(
                                    output,
                                    "    offset += {}_footprint({}) as u64;\n",
                                    format_type_to_rust(&field.field_type),
                                    field_refs.join(", ")
                                )
                                .unwrap();
                            }
                        } else {
                            /* Constant-sized nested type */
                            write!(
                                output,
                                "    offset += std::mem::size_of::<{}>() as u64;\n",
                                format_type_to_rust(&field.field_type)
                            )
                            .unwrap();
                        }
                    }
                    _ => {}
                }
            }
        }
    }

    if after_fam {
        write!(output, "    offset\n").unwrap();
    } else {
        write!(
            output,
            "    std::mem::size_of::<{}_t>() as u64\n",
            type_name
        )
        .unwrap();
    }

    write!(output, "}}\n\n").unwrap();
    output
}

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

    if let Size::Const(_size) = resolved_type.size {
        /* Constant size enum */
        write!(output, "pub fn {}_footprint() -> u64 {{\n", type_name).unwrap();
        write!(
            output,
            "    std::mem::size_of::<{}_t>() as u64\n",
            type_name
        )
        .unwrap();
        write!(output, "}}\n\n").unwrap();
        return output;
    }

    /* Variable size enum - needs variant parameter */
    if let ResolvedTypeKind::Enum { variants, .. } = &resolved_type.kind {
        /* Collect all field references from all variants */
        let mut all_field_refs: BTreeMap<String, PrimitiveType> = BTreeMap::new();
        for variant in variants {
            if let Size::Variable(var_refs) = &variant.variant_type.size {
                for inner_refs in var_refs.values() {
                    for (ref_path, prim_type) in inner_refs {
                        all_field_refs
                            .entry(ref_path.clone())
                            .or_insert_with(|| prim_type.clone());
                    }
                }
            }
        }

        write!(output, "pub fn {}_footprint(tag: u64", type_name).unwrap();
        for (ref_path, prim_type) in &all_field_refs {
            write!(
                output,
                ", {}: {}",
                ref_path.replace('.', "_"),
                primitive_to_rust_type(prim_type)
            )
            .unwrap();
        }
        write!(output, ") -> u64 {{\n").unwrap();

        write!(output, "    match tag {{\n").unwrap();
        for variant in variants {
            write!(output, "        {} => ", variant.tag_value).unwrap();
            if let Size::Const(s) = variant.variant_type.size {
                write!(output, "{},\n", s).unwrap();
            } else {
                /* Variable-sized variant */
                if let Size::Variable(var_refs) = &variant.variant_type.size {
                    let field_refs: Vec<String> = var_refs
                        .values()
                        .flat_map(|refs| refs.keys().map(|r| r.replace('.', "_")))
                        .collect();

                    if field_refs.is_empty() {
                        write!(
                            output,
                            "{}_footprint(),\n",
                            format_type_to_rust(&variant.variant_type)
                        )
                        .unwrap();
                    } else {
                        write!(
                            output,
                            "{}_footprint({}),\n",
                            format_type_to_rust(&variant.variant_type),
                            field_refs.join(", ")
                        )
                        .unwrap();
                    }
                } else {
                    write!(
                        output,
                        "std::mem::size_of::<{}>() as u64,\n",
                        format_type_to_rust(&variant.variant_type)
                    )
                    .unwrap();
                }
            }
        }
        write!(output, "        _ => 0,  /* Invalid tag */\n").unwrap();
        write!(output, "    }}\n").unwrap();
        write!(output, "}}\n\n").unwrap();
    }

    output
}

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

    /* Unions always have constant size (size of largest variant) */
    write!(output, "pub fn {}_footprint() -> u64 {{\n", type_name).unwrap();
    write!(
        output,
        "    std::mem::size_of::<{}_t>() as u64\n",
        type_name
    )
    .unwrap();
    write!(output, "}}\n\n").unwrap();

    output
}

pub fn emit_footprint_fn(resolved_type: &ResolvedType) -> String {
    match &resolved_type.kind {
        ResolvedTypeKind::Struct { .. } => emit_footprint_fn_struct(resolved_type),
        ResolvedTypeKind::Enum { .. } => emit_footprint_fn_enum(resolved_type),
        ResolvedTypeKind::Union { .. } => emit_footprint_fn_union(resolved_type),
        ResolvedTypeKind::SizeDiscriminatedUnion { .. } => emit_footprint_fn_union(resolved_type),
        _ => String::new(),
    }
}