Skip to main content

Module

Struct Module 

Source
pub struct Module { /* private fields */ }
Expand description

A C translation unit: a header (.h) and a source (.c) generated together.

Build one with Module::new and the ModuleBuilder routing helpers, then render each file with Module::header and Module::source.

Implementations§

Source§

impl Module

Source

pub fn new(name: &str) -> ModuleBuilder

Creates a ModuleBuilder for a module with the given base name (used for the header guard and the source’s self-include, e.g. "widget" for widget.h/widget.c).

Examples found in repository?
examples/tagged_union.rs (line 60)
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}
More examples
Hide additional examples
examples/module_header_source.rs (line 64)
17fn main() {
18    let float = Type::base(BaseType::Float);
19    let vec2 = Type::base(BaseType::TypeDef("Vec2".to_string()));
20
21    // struct Vec2 { float x; float y; };
22    let vec2_struct = StructBuilder::new_with_str("Vec2")
23        .field(FieldBuilder::new_with_str("x", float.clone()).build())
24        .field(FieldBuilder::new_with_str("y", float.clone()).build())
25        .build();
26
27    // typedef struct Vec2 Vec2;
28    let vec2_typedef =
29        TypeDefBuilder::new_with_str(Type::base(BaseType::Struct("Vec2".to_string())), "Vec2")
30            .build();
31
32    // Vec2 vec2_add(Vec2 a, Vec2 b) { return (Vec2){a.x + b.x, a.y + b.y}; }
33    let add = FunctionBuilder::new_with_str("vec2_add", vec2.clone())
34        .param(ParameterBuilder::new_with_str("a", vec2.clone()).build())
35        .param(ParameterBuilder::new_with_str("b", vec2.clone()).build())
36        .body(
37            BlockBuilder::new()
38                .statement(Statement::Return(Some(Expr::new_cast(
39                    vec2.clone(),
40                    Expr::new_init_struct_in_order(vec![
41                        Expr::new_binary(member("a", "x"), BinOp::Add, member("b", "x")),
42                        Expr::new_binary(member("a", "y"), BinOp::Add, member("b", "y")),
43                    ]),
44                ))))
45                .build(),
46        )
47        .build();
48
49    // float vec2_dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }
50    let dot = FunctionBuilder::new_with_str("vec2_dot", float.clone())
51        .param(ParameterBuilder::new_with_str("a", vec2.clone()).build())
52        .param(ParameterBuilder::new_with_str("b", vec2.clone()).build())
53        .body(
54            BlockBuilder::new()
55                .statement(Statement::Return(Some(Expr::new_binary(
56                    Expr::new_binary(member("a", "x"), BinOp::Mul, member("b", "x")),
57                    BinOp::Add,
58                    Expr::new_binary(member("a", "y"), BinOp::Mul, member("b", "y")),
59                ))))
60                .build(),
61        )
62        .build();
63
64    let m = Module::new("vec2")
65        .struct_(vec2_struct)
66        .typedef(vec2_typedef)
67        .header_newline()
68        .function(add)
69        .function(dot)
70        .build();
71
72    println!("// ===== vec2.h =====");
73    print!("{}", m.header());
74    println!("\n// ===== vec2.c =====");
75    print!("{}", m.source());
76}
Source

pub fn name(&self) -> &str

The module’s base name.

Source

pub fn header_stmts(&self) -> &[GlobalStatement]

The statements destined for the header.

Source

pub fn source_stmts(&self) -> &[GlobalStatement]

The statements destined for the source.

Source

pub fn header(&self) -> String

Renders the header file, wrapped in the configured include guard, using default RenderOptions.

Examples found in repository?
examples/tagged_union.rs (line 68)
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}
More examples
Hide additional examples
examples/module_header_source.rs (line 73)
17fn main() {
18    let float = Type::base(BaseType::Float);
19    let vec2 = Type::base(BaseType::TypeDef("Vec2".to_string()));
20
21    // struct Vec2 { float x; float y; };
22    let vec2_struct = StructBuilder::new_with_str("Vec2")
23        .field(FieldBuilder::new_with_str("x", float.clone()).build())
24        .field(FieldBuilder::new_with_str("y", float.clone()).build())
25        .build();
26
27    // typedef struct Vec2 Vec2;
28    let vec2_typedef =
29        TypeDefBuilder::new_with_str(Type::base(BaseType::Struct("Vec2".to_string())), "Vec2")
30            .build();
31
32    // Vec2 vec2_add(Vec2 a, Vec2 b) { return (Vec2){a.x + b.x, a.y + b.y}; }
33    let add = FunctionBuilder::new_with_str("vec2_add", vec2.clone())
34        .param(ParameterBuilder::new_with_str("a", vec2.clone()).build())
35        .param(ParameterBuilder::new_with_str("b", vec2.clone()).build())
36        .body(
37            BlockBuilder::new()
38                .statement(Statement::Return(Some(Expr::new_cast(
39                    vec2.clone(),
40                    Expr::new_init_struct_in_order(vec![
41                        Expr::new_binary(member("a", "x"), BinOp::Add, member("b", "x")),
42                        Expr::new_binary(member("a", "y"), BinOp::Add, member("b", "y")),
43                    ]),
44                ))))
45                .build(),
46        )
47        .build();
48
49    // float vec2_dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }
50    let dot = FunctionBuilder::new_with_str("vec2_dot", float.clone())
51        .param(ParameterBuilder::new_with_str("a", vec2.clone()).build())
52        .param(ParameterBuilder::new_with_str("b", vec2.clone()).build())
53        .body(
54            BlockBuilder::new()
55                .statement(Statement::Return(Some(Expr::new_binary(
56                    Expr::new_binary(member("a", "x"), BinOp::Mul, member("b", "x")),
57                    BinOp::Add,
58                    Expr::new_binary(member("a", "y"), BinOp::Mul, member("b", "y")),
59                ))))
60                .build(),
61        )
62        .build();
63
64    let m = Module::new("vec2")
65        .struct_(vec2_struct)
66        .typedef(vec2_typedef)
67        .header_newline()
68        .function(add)
69        .function(dot)
70        .build();
71
72    println!("// ===== vec2.h =====");
73    print!("{}", m.header());
74    println!("\n// ===== vec2.c =====");
75    print!("{}", m.source());
76}
Source

pub fn header_with(&self, opts: RenderOptions) -> String

Renders the header file with explicit RenderOptions (so #line directives, tab indentation, C23 spellings, brace style, etc. all apply).

Source

pub fn source(&self) -> String

Renders the source file, prefixed (unless disabled) with an include of this module’s own header, using default RenderOptions.

Examples found in repository?
examples/tagged_union.rs (line 70)
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}
More examples
Hide additional examples
examples/module_header_source.rs (line 75)
17fn main() {
18    let float = Type::base(BaseType::Float);
19    let vec2 = Type::base(BaseType::TypeDef("Vec2".to_string()));
20
21    // struct Vec2 { float x; float y; };
22    let vec2_struct = StructBuilder::new_with_str("Vec2")
23        .field(FieldBuilder::new_with_str("x", float.clone()).build())
24        .field(FieldBuilder::new_with_str("y", float.clone()).build())
25        .build();
26
27    // typedef struct Vec2 Vec2;
28    let vec2_typedef =
29        TypeDefBuilder::new_with_str(Type::base(BaseType::Struct("Vec2".to_string())), "Vec2")
30            .build();
31
32    // Vec2 vec2_add(Vec2 a, Vec2 b) { return (Vec2){a.x + b.x, a.y + b.y}; }
33    let add = FunctionBuilder::new_with_str("vec2_add", vec2.clone())
34        .param(ParameterBuilder::new_with_str("a", vec2.clone()).build())
35        .param(ParameterBuilder::new_with_str("b", vec2.clone()).build())
36        .body(
37            BlockBuilder::new()
38                .statement(Statement::Return(Some(Expr::new_cast(
39                    vec2.clone(),
40                    Expr::new_init_struct_in_order(vec![
41                        Expr::new_binary(member("a", "x"), BinOp::Add, member("b", "x")),
42                        Expr::new_binary(member("a", "y"), BinOp::Add, member("b", "y")),
43                    ]),
44                ))))
45                .build(),
46        )
47        .build();
48
49    // float vec2_dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }
50    let dot = FunctionBuilder::new_with_str("vec2_dot", float.clone())
51        .param(ParameterBuilder::new_with_str("a", vec2.clone()).build())
52        .param(ParameterBuilder::new_with_str("b", vec2.clone()).build())
53        .body(
54            BlockBuilder::new()
55                .statement(Statement::Return(Some(Expr::new_binary(
56                    Expr::new_binary(member("a", "x"), BinOp::Mul, member("b", "x")),
57                    BinOp::Add,
58                    Expr::new_binary(member("a", "y"), BinOp::Mul, member("b", "y")),
59                ))))
60                .build(),
61        )
62        .build();
63
64    let m = Module::new("vec2")
65        .struct_(vec2_struct)
66        .typedef(vec2_typedef)
67        .header_newline()
68        .function(add)
69        .function(dot)
70        .build();
71
72    println!("// ===== vec2.h =====");
73    print!("{}", m.header());
74    println!("\n// ===== vec2.c =====");
75    print!("{}", m.source());
76}
Source

pub fn source_with(&self, opts: RenderOptions) -> String

Renders the source file with explicit RenderOptions.

Trait Implementations§

Source§

impl Clone for Module

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Module

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.