Skip to main content

tagged_union/
tagged_union.rs

1//! Sum types: a packed tagged union built from a C11 anonymous union, with a
2//! pointer accessor that uses `->`, a ternary, and a cast.
3//!
4//! Run with: `cargo run --example tagged_union`
5
6use tamago::*;
7
8fn main() {
9    let v = || Expr::new_ident_with_str("v");
10
11    // struct __attribute__((packed)) Value {
12    //   int tag;
13    //   union { int i; double d; };   // anonymous: write v.i, not v.payload.i
14    // };
15    let value_struct = StructBuilder::new_with_str("Value")
16        .attr(Attribute::packed())
17        .field(FieldBuilder::new_with_str("tag", Type::base(BaseType::Int)).build())
18        .field(
19            Field::anonymous_union(vec![
20                FieldBuilder::new_with_str("i", Type::base(BaseType::Int)).build(),
21                FieldBuilder::new_with_str("d", Type::base(BaseType::Double)).build(),
22            ])
23            .build(),
24        )
25        .build();
26
27    // typedef struct Value Value;
28    let value_typedef =
29        TypeDefBuilder::new_with_str(Type::base(BaseType::Struct("Value".to_string())), "Value")
30            .build();
31
32    // double value_as_double(const Value *v) {
33    //     return v->tag ? v->d : (double)v->i;
34    // }
35    let as_double = FunctionBuilder::new_with_str("value_as_double", Type::base(BaseType::Double))
36        .param(
37            ParameterBuilder::new_with_str(
38                "v",
39                Type::new(BaseType::TypeDef("Value".to_string()))
40                    .make_const()
41                    .make_pointer()
42                    .build(),
43            )
44            .build(),
45        )
46        .body(
47            BlockBuilder::new()
48                .statement(Statement::Return(Some(Expr::new_ternary(
49                    Expr::new_ptr_mem_access_with_str(v(), "tag"),
50                    Expr::new_ptr_mem_access_with_str(v(), "d"),
51                    Expr::new_cast(
52                        Type::base(BaseType::Double),
53                        Expr::new_ptr_mem_access_with_str(v(), "i"),
54                    ),
55                ))))
56                .build(),
57        )
58        .build();
59
60    let m = Module::new("value")
61        .struct_(value_struct)
62        .typedef(value_typedef)
63        .header_newline()
64        .function(as_double)
65        .build();
66
67    println!("// ===== value.h =====");
68    print!("{}", m.header());
69    println!("\n// ===== value.c =====");
70    print!("{}", m.source());
71}