ModuleBuilder

Struct ModuleBuilder 

Source
pub struct ModuleBuilder<F = Identity> { /* private fields */ }
Expand description

Module builder

Implementations§

Source§

impl ModuleBuilder

Source

pub fn new() -> Self

New empty module builder

Source§

impl<F> ModuleBuilder<F>
where F: Invoke<Module>,

Source

pub fn with_callback(callback: F) -> Self

New module builder with bound callback

Source

pub fn with_module(self, module: Module) -> Self

Builder from raw module

Source

pub fn with_sections<I>(self, sections: I) -> Self
where I: IntoIterator<Item = Section>,

Fill module with sections from iterator

Source

pub fn with_section(self, section: Section) -> Self

Add additional section

Source

pub fn with_signatures(self, bindings: Vec<Signature>) -> Self

Binds to the type section, creates additional types when required

Source

pub fn push_function(&mut self, func: FunctionDefinition) -> CodeLocation

Push stand-alone function definition, creating sections, signature and code blocks in corresponding sections. FunctionDefinition can be build using builder::function builder

Source

pub fn push_memory(&mut self, memory: MemoryDefinition) -> u32

Push linear memory region

Source

pub fn push_table(&mut self, table: TableDefinition) -> u32

Push table

Source

pub fn push_signature(&mut self, signature: Signature) -> u32

Push one function signature, returning it’s calling index. Can create corresponding type in type section.

Examples found in repository?
examples/inject.rs (lines 49-55)
28fn main() {
29    let args = env::args().collect::<Vec<_>>();
30    if args.len() != 3 {
31        println!("Usage: {} input_file.wasm output_file.wasm", args[0]);
32        return;
33    }
34
35    let mut module = sophon_wasm::deserialize_file(&args[1]).unwrap();
36
37    for section in module.sections_mut() {
38        match section {
39            &mut elements::Section::Code(ref mut code_section) => {
40                for ref mut func_body in code_section.bodies_mut() {
41                    inject_nop(func_body.code_mut());
42                }
43            },
44            _ => { }
45        }
46    }
47
48    let mut build = builder::from_module(module);
49    let import_sig = build.push_signature(
50        builder::signature()
51            .param().i32()
52            .param().i32()
53            .return_type().i32()
54            .build_sig()
55    );
56    let build = build.import()
57        .module("env")
58        .field("log")
59        .external().func(import_sig)
60        .build();
61
62    sophon_wasm::serialize_to_file(&args[2], build.build()).unwrap();
63}
Source

pub fn push_signatures(&mut self, signatures: Vec<Signature>) -> Vec<u32>

Push signatures in the module, returning corresponding indices of pushed signatures

Source

pub fn push_import(&mut self, import: ImportEntry) -> u32

Push import entry to module. Not that it does not update calling indices in function bodies.

Source

pub fn push_export(&mut self, export: ExportEntry) -> u32

Push export entry to module.

Source

pub fn function(self) -> FunctionBuilder<Self>

Add new function using dedicated builder

Examples found in repository?
examples/build.rs (line 29)
12fn main() {
13
14    // Example binary accepts one parameter which is the output file
15    // where generated wasm module will be written at the end of execution
16    let args = env::args().collect::<Vec<_>>();
17    if args.len() != 2 {
18        println!("Usage: {} output_file.wasm", args[0]);
19        return;
20    }
21
22    // Main entry for the builder api is the module function
23    // It returns empty module builder structure which can be further
24    // appended with various wasm artefacts
25    let module = builder::module()
26        // Here we append function to the builder
27        // function() function returns a function builder attached
28        // to the module builder.
29        .function()
30            // We describe signature for the function via signature()
31            // function. In our simple example it's just one input
32            // argument of type 'i32' without return value
33            .signature().with_param(elements::ValueType::I32).build()
34            // body() without any further arguments means that the body
35            // of the function will be empty
36            .body().build()
37            // This is the end of the function builder. When `build()` is
38            // invoked, function builder returns original module builder
39            // from which it was invoked
40            .build()
41        // And finally we finish our module builder to produce actual
42        // wasm module.
43        .build();
44
45    // Module structure can be serialzed to produce a valid wasm file
46    sophon_wasm::serialize_to_file(&args[1], module).unwrap();
47}
Source

pub fn memory(self) -> MemoryBuilder<Self>

Add new linear memory using dedicated builder

Source

pub fn table(self) -> TableBuilder<Self>

Add new table using dedicated builder

Source

pub fn functions(self) -> SignaturesBuilder<Self>

Define functions section

Source

pub fn with_export(self, entry: ExportEntry) -> Self

With inserted export entry

Source

pub fn with_import(self, entry: ImportEntry) -> Self

With inserted import entry

Source

pub fn import(self) -> ImportBuilder<Self>

Import entry builder

§Examples
use sophon_wasm::builder::module;

let module = module()
   .import()
       .module("env")
       .field("memory")
       .external().memory(256, Some(256))
       .build()
   .build();

assert_eq!(module.import_section().expect("import section to exist").entries().len(), 1);
Examples found in repository?
examples/inject.rs (line 56)
28fn main() {
29    let args = env::args().collect::<Vec<_>>();
30    if args.len() != 3 {
31        println!("Usage: {} input_file.wasm output_file.wasm", args[0]);
32        return;
33    }
34
35    let mut module = sophon_wasm::deserialize_file(&args[1]).unwrap();
36
37    for section in module.sections_mut() {
38        match section {
39            &mut elements::Section::Code(ref mut code_section) => {
40                for ref mut func_body in code_section.bodies_mut() {
41                    inject_nop(func_body.code_mut());
42                }
43            },
44            _ => { }
45        }
46    }
47
48    let mut build = builder::from_module(module);
49    let import_sig = build.push_signature(
50        builder::signature()
51            .param().i32()
52            .param().i32()
53            .return_type().i32()
54            .build_sig()
55    );
56    let build = build.import()
57        .module("env")
58        .field("log")
59        .external().func(import_sig)
60        .build();
61
62    sophon_wasm::serialize_to_file(&args[2], build.build()).unwrap();
63}
Source

pub fn with_global(self, global: GlobalEntry) -> Self

With global variable

Source

pub fn with_table(self, table: TableType) -> Self

With table

Source

pub fn export(self) -> ExportBuilder<Self>

Export entry builder

§Examples
use sophon_wasm::builder::module;
use sophon_wasm::elements::Opcode::*;

let module = module()
   .global()
        .value_type().i32()
        .init_expr(I32Const(0))
        .build()
   .export()
       .field("_zero")
       .internal().global(0)
       .build()
   .build();

assert_eq!(module.export_section().expect("export section to exist").entries().len(), 1);
Source

pub fn global(self) -> GlobalBuilder<Self>

Glboal entry builder

§Examples
use sophon_wasm::builder::module;
use sophon_wasm::elements::Opcode::*;

let module = module()
   .global()
        .value_type().i32()
        .init_expr(I32Const(0))
        .build()
   .build();

assert_eq!(module.global_section().expect("global section to exist").entries().len(), 1);
Source

pub fn with_data_segment(self, segment: DataSegment) -> Self

Add data segment to the builder

Source

pub fn data(self) -> DataSegmentBuilder<Self>

Data entry builder

Source

pub fn build(self) -> F::Result

Build module (final step)

Examples found in repository?
examples/inject.rs (line 62)
28fn main() {
29    let args = env::args().collect::<Vec<_>>();
30    if args.len() != 3 {
31        println!("Usage: {} input_file.wasm output_file.wasm", args[0]);
32        return;
33    }
34
35    let mut module = sophon_wasm::deserialize_file(&args[1]).unwrap();
36
37    for section in module.sections_mut() {
38        match section {
39            &mut elements::Section::Code(ref mut code_section) => {
40                for ref mut func_body in code_section.bodies_mut() {
41                    inject_nop(func_body.code_mut());
42                }
43            },
44            _ => { }
45        }
46    }
47
48    let mut build = builder::from_module(module);
49    let import_sig = build.push_signature(
50        builder::signature()
51            .param().i32()
52            .param().i32()
53            .return_type().i32()
54            .build_sig()
55    );
56    let build = build.import()
57        .module("env")
58        .field("log")
59        .external().func(import_sig)
60        .build();
61
62    sophon_wasm::serialize_to_file(&args[2], build.build()).unwrap();
63}
More examples
Hide additional examples
examples/build.rs (line 43)
12fn main() {
13
14    // Example binary accepts one parameter which is the output file
15    // where generated wasm module will be written at the end of execution
16    let args = env::args().collect::<Vec<_>>();
17    if args.len() != 2 {
18        println!("Usage: {} output_file.wasm", args[0]);
19        return;
20    }
21
22    // Main entry for the builder api is the module function
23    // It returns empty module builder structure which can be further
24    // appended with various wasm artefacts
25    let module = builder::module()
26        // Here we append function to the builder
27        // function() function returns a function builder attached
28        // to the module builder.
29        .function()
30            // We describe signature for the function via signature()
31            // function. In our simple example it's just one input
32            // argument of type 'i32' without return value
33            .signature().with_param(elements::ValueType::I32).build()
34            // body() without any further arguments means that the body
35            // of the function will be empty
36            .body().build()
37            // This is the end of the function builder. When `build()` is
38            // invoked, function builder returns original module builder
39            // from which it was invoked
40            .build()
41        // And finally we finish our module builder to produce actual
42        // wasm module.
43        .build();
44
45    // Module structure can be serialzed to produce a valid wasm file
46    sophon_wasm::serialize_to_file(&args[1], module).unwrap();
47}

Auto Trait Implementations§

§

impl<F> Freeze for ModuleBuilder<F>
where F: Freeze,

§

impl<F> RefUnwindSafe for ModuleBuilder<F>
where F: RefUnwindSafe,

§

impl<F> Send for ModuleBuilder<F>
where F: Send,

§

impl<F> Sync for ModuleBuilder<F>
where F: Sync,

§

impl<F> Unpin for ModuleBuilder<F>
where F: Unpin,

§

impl<F> UnwindSafe for ModuleBuilder<F>
where F: UnwindSafe,

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> 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, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
Source§

impl<T> Erased for T