Initial project import

This commit is contained in:
Agila Forge Importer committed 2026-07-13 15:20:32 +00:00
commit 23f2d29e32
11957 files changed
+1754577

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
## Description
The `wasm` module is a pure V implementation of the WebAssembly bytecode module format,
available in the form of a builder.
It allows users to generate WebAssembly modules in memory.
With the V wasm module, users can create functions, opcodes, and utilize the entire wasm
specification without the need for a large dependency like binaryen. All of this
functionality is available within V itself, making the module a valuable resource for
V developers seeking to build high-performance web applications.
The module is designed to generate a `[]u8`, which can be written to a `.wasm` file
or executed in memory.
Examples are present in `examples/wasm_codegen`.
```v
import wasm
import os
fn main() {
mut m := wasm.Module{}
mut func := m.new_function('add', [.i32_t, .i32_t], [.i32_t])
{
func.local_get(0) // | local.get 0
func.local_get(1) // | local.get 1
func.add(.i32_t) // | i32.add
}
m.commit(func, true) // `export: true`
mod := m.compile() // []u8
os.write_file_array('add.wasm', mod)!
}
```
This module does not perform verification of the WebAssembly output.
Use a tool like `wasm-validate` to validate, and `wasm-dis` to show a decompiled form.
+171
View File
@@ -0,0 +1,171 @@
// Copyright (c) 2023 l-m.dev. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module wasm
import encoding.leb128
// constexpr_value returns a constant expression that evaluates to a single value.
pub fn constexpr_value[T](v T) ConstExpression {
mut expr := ConstExpression{}
$if T is i64 {
expr.i64_const(v)
} $else $if T is $int {
expr.i32_const(i32(v))
} $else $if T is f32 {
expr.f32_const(v)
} $else $if T is f64 {
expr.f64_const(v)
} $else {
$compile_error('values can only be int, i32, i64, f32, f64')
}
return expr
}
// constexpr_value_zero returns a constant expression that evaluates to zero.
pub fn constexpr_value_zero(v ValType) ConstExpression {
mut expr := ConstExpression{}
match v {
.i32_t {
expr.i32_const(0)
}
.i64_t {
expr.i64_const(0)
}
.f32_t {
expr.f32_const(0.0)
}
.f64_t {
expr.f64_const(0.0)
}
.funcref_t, .externref_t {
expr.ref_null(RefType(v))
}
.v128_t {
panic('type `v128_t` not permitted in a constant expression')
}
}
return expr
}
// constexpr_ref_null returns a constant expression that evaluates to a null reference.
pub fn constexpr_ref_null(rt RefType) ConstExpression {
mut expr := ConstExpression{}
expr.ref_null(rt)
return expr
}
// WebAssembly constant expressions are permitted to use a subset of valid instructions.
pub struct ConstExpression {
mut:
call_patches []CallPatch
code []u8
}
// i32_const places a constant i32 value on the stack.
// WebAssembly instruction: `i32.const`.
pub fn (mut expr ConstExpression) i32_const(v i32) {
expr.code << 0x41 // i32.const
expr.code << leb128.encode_i32(v)
}
// i64_const places a constant i64 value on the stack.
// WebAssembly instruction: `i64.const`.
pub fn (mut expr ConstExpression) i64_const(v i64) {
expr.code << 0x42 // i64.const
expr.code << leb128.encode_i64(v)
}
// f32_const places a constant f32 value on the stack.
// WebAssembly instruction: `f32.const`.
pub fn (mut expr ConstExpression) f32_const(v f32) {
expr.code << 0x43 // f32.const
push_f32(mut expr.code, v)
}
// f64_const places a constant f64 value on the stack.
// WebAssembly instruction: `f64.const`.
pub fn (mut expr ConstExpression) f64_const(v f64) {
expr.code << 0x44 // f64.const
push_f64(mut expr.code, v)
}
// add adds two values on the stack with type `typ`.
// WebAssembly instructions: `i32|i64.add`.
pub fn (mut expr ConstExpression) add(typ NumType) {
assert typ in [.i32_t, .i64_t]
match typ {
.i32_t { expr.code << 0x6A } // i32.add
.i64_t { expr.code << 0x7C } // i64.add
else {}
}
}
// sub subtracts two values on the stack with type `typ`.
// WebAssembly instructions: `i32|i64.sub`.
pub fn (mut expr ConstExpression) sub(typ NumType) {
assert typ in [.i32_t, .i64_t]
match typ {
.i32_t { expr.code << 0x6B } // i32.sub
.i64_t { expr.code << 0x7D } // i64.sub
else {}
}
}
// mul multiplies two values on the stack with type `typ`.
// WebAssembly instructions: `i32|i64.mul`.
pub fn (mut expr ConstExpression) mul(typ NumType) {
assert typ in [.i32_t, .i64_t]
match typ {
.i32_t { expr.code << 0x6C } // i32.mul
.i64_t { expr.code << 0x7E } // i64.mul
else {}
}
}
// global_get places the value of the global at the index `global` on the stack.
// Constant expressions are only allowed to refer to imported globals.
// WebAssembly instruction: `global.get`.
pub fn (mut expr ConstExpression) global_get(global GlobalImportIndex) {
expr.code << 0x23 // global.get
expr.code << leb128.encode_u32(u32(global))
}
// ref_null places a null reference on the stack.
// WebAssembly instruction: `ref.null`.
pub fn (mut expr ConstExpression) ref_null(rt RefType) {
expr.code << 0xD0 // ref.null
expr.code << u8(rt)
}
// ref_func places a reference to a function with `name` on the stack.
// If this function does not exist when calling `compile` on the module, it will panic.
// WebAssembly instruction: `ref.func`.
pub fn (mut expr ConstExpression) ref_func(name string) {
expr.code << 0xD2 // ref.func
expr.call_patches << FunctionCallPatch{
name: name
pos: expr.code.len
}
}
// ref_func places a reference to an imported function with `name` on the stack.
// If the imported function does not exist when calling `compile` on the module, it will panic.
// WebAssembly instruction: `ref.func`.
pub fn (mut expr ConstExpression) ref_func_import(mod string, name string) {
expr.code << 0xD2 // ref.func
expr.call_patches << ImportCallPatch{
mod: mod
name: name
pos: expr.code.len
}
}
+453
View File
@@ -0,0 +1,453 @@
// Copyright (c) 2023 l-m.dev. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module wasm
import encoding.leb128
import math.bits
fn (mut mod Module) u32(v u32) {
mod.buf << leb128.encode_u32(v)
}
fn (mut mod Module) patch_start() int {
return mod.buf.len
}
fn (mut mod Module) patch_len(pos int) {
len := mod.buf.len - pos
data := leb128.encode_u32(u32(len))
mod.buf.insert(pos, data)
}
fn (mut mod Module) patch_u32(pos int, val u32) {
data := leb128.encode_u32(val)
mod.buf.insert(pos, data)
}
fn (mut mod Module) result_type(results []ValType) {
mod.u32(u32(results.len))
for r in results {
mod.buf << u8(r)
}
}
fn (mut mod Module) function_type(ft FuncType) {
mod.buf << 0x60 // function type indicator
mod.result_type(ft.parameters)
mod.result_type(ft.results)
}
fn (mut mod Module) global_type(vt ValType, is_mut bool) {
mod.buf << u8(vt)
mod.buf << u8(is_mut)
}
fn push_f32(mut buf []u8, v f32) {
rv := bits.f32_bits(v)
buf << u8(rv >> u32(0))
buf << u8(rv >> u32(8))
buf << u8(rv >> u32(16))
buf << u8(rv >> u32(24))
}
fn push_f64(mut buf []u8, v f64) {
rv := bits.f64_bits(v)
buf << u8(rv >> u32(0))
buf << u8(rv >> u32(8))
buf << u8(rv >> u32(16))
buf << u8(rv >> u32(24))
buf << u8(rv >> u32(32))
buf << u8(rv >> u32(40))
buf << u8(rv >> u32(48))
buf << u8(rv >> u32(56))
}
fn (mod &Module) get_function_idx(patch CallPatch) int {
mut idx := -1
match patch {
FunctionCallPatch {
ftt := mod.functions[patch.name] or {
panic('called function ${patch.name} does not exist')
}
idx = ftt.idx + mod.fn_imports.len
}
ImportCallPatch {
for fnidx, c in mod.fn_imports {
if c.mod == patch.mod && c.name == patch.name {
idx = fnidx
break
}
}
if idx == -1 {
panic('called imported function ${patch.mod}.${patch.name} does not exist')
}
}
}
return idx
}
fn (mut mod Module) patch(ft Function) {
mut ptr := 0
for patch in ft.patches {
mut idx := 0
match patch {
CallPatch {
idx = mod.get_function_idx(patch)
}
FunctionGlobalPatch {
idx = mod.global_imports.len + patch.idx
}
}
mod.buf << ft.code[ptr..patch.pos]
mod.u32(u32(idx))
ptr = patch.pos
}
mod.buf << ft.code[ptr..]
}
fn (mut mod Module) name(name string) {
mod.u32(u32(name.len))
mod.buf << name.bytes()
}
fn (mut mod Module) start_subsection(sec Subsection) int {
mod.buf << u8(sec)
return mod.patch_start()
}
fn (mut mod Module) start_section(sec Section) int {
mod.buf << u8(sec)
return mod.patch_start()
}
fn (mut mod Module) end_section(tpatch int) {
mod.patch_len(tpatch)
}
// compile serialises the WebAssembly module into a byte array.
// The returned byte array can be written out into a `.wasm`, or executed in memory.
pub fn (mut mod Module) compile() []u8 {
mod.buf = []u8{cap: 128}
// WASM_BINARY_MAGIC, WASM_BINARY_VERSION
mod.buf << [u8(0x00), 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]
// https://webassembly.github.io/spec/core/binary/modules.html#type-section
//
if mod.functypes.len > 0 {
tpatch := mod.start_section(.type_section)
{
mod.u32(u32(mod.functypes.len))
for ft in mod.functypes {
mod.function_type(ft)
}
}
mod.end_section(tpatch)
}
// https://webassembly.github.io/spec/core/binary/modules.html#import-section
//
if mod.fn_imports.len > 0 || mod.global_imports.len > 0 {
tpatch := mod.start_section(.import_section)
{
mod.u32(u32(mod.fn_imports.len + mod.global_imports.len))
for ft in mod.fn_imports {
mod.name(ft.mod)
mod.name(ft.name)
mod.buf << 0x00 // function
mod.u32(u32(ft.tidx))
}
for gt in mod.global_imports {
mod.name(gt.mod)
mod.name(gt.name)
mod.buf << 0x03 // global
mod.global_type(gt.typ, gt.is_mut)
}
}
mod.end_section(tpatch)
}
// https://webassembly.github.io/spec/core/binary/modules.html#binary-funcsec
//
if mod.functions.len > 0 {
tpatch := mod.start_section(.function_section)
{
mod.u32(u32(mod.functions.len))
for _, ft in mod.functions {
mod.u32(u32(ft.tidx))
}
}
mod.end_section(tpatch)
}
// https://webassembly.github.io/spec/core/binary/modules.html#binary-memsec
//
if memory := mod.memory {
tpatch := mod.start_section(.memory_section)
{
mod.u32(1)
if max := memory.max {
mod.buf << 0x01 // limit, max present
mod.u32(memory.min)
mod.u32(max)
} else {
mod.buf << 0x00 // limit, max not present
mod.u32(memory.min)
}
}
mod.end_section(tpatch)
}
// https://webassembly.github.io/spec/core/binary/modules.html#global-section
//
if mod.globals.len > 0 {
tpatch := mod.start_section(.global_section)
{
mod.u32(u32(mod.globals.len))
for gt in mod.globals {
mod.global_type(gt.typ, gt.is_mut)
{
mut ptr := 0
for patch in gt.init.call_patches {
idx := mod.get_function_idx(patch)
mod.buf << gt.init.code[ptr..patch.pos]
mod.u32(u32(idx))
ptr = patch.pos
}
mod.buf << gt.init.code[ptr..]
}
mod.buf << 0x0B // END expression opcode
}
}
mod.end_section(tpatch)
}
// https://webassembly.github.io/spec/core/binary/modules.html#export-section
//
{
tpatch := mod.start_section(.export_section)
{
lpatch := mod.patch_start()
mut lsz := 0
for _, ft in mod.functions {
if !ft.export {
continue
}
lsz++
mod.name(ft.export_name or { ft.name })
mod.buf << 0x00 // function
mod.u32(u32(ft.idx + mod.fn_imports.len))
}
if memory := mod.memory {
if memory.export {
lsz++
mod.name(memory.name)
mod.buf << 0x02 // function
mod.u32(0)
}
}
for idx, gbl in mod.globals {
if !gbl.export {
continue
}
lsz++
mod.name(gbl.name)
mod.buf << 0x03 // global
mod.u32(u32(idx + mod.global_imports.len))
}
mod.patch_u32(lpatch, u32(lsz))
}
mod.end_section(tpatch)
}
// https://webassembly.github.io/spec/core/binary/modules.html#binary-startsec
//
if start := mod.start {
ftt := mod.functions[start] or { panic('start function ${start} does not exist') }
tpatch := mod.start_section(.start_section)
{
mod.u32(u32(ftt.idx + mod.fn_imports.len))
}
mod.end_section(tpatch)
}
// https://webassembly.github.io/spec/core/binary/modules.html#data-count-section
//
if mod.segments.len > 0 {
tpatch := mod.start_section(.data_count_section)
{
mod.u32(u32(mod.segments.len))
}
mod.end_section(tpatch)
}
// https://webassembly.github.io/spec/core/binary/modules.html#binary-codesec
//
if mod.functions.len > 0 {
tpatch := mod.start_section(.code_section)
{
mod.u32(u32(mod.functions.len))
for _, ft in mod.functions {
fpatch := mod.patch_start()
rloc := ft.locals[mod.functypes[ft.tidx].parameters.len..]
{
mod.u32(u32(rloc.len))
for lt in rloc {
mod.u32(1)
mod.buf << u8(lt.typ)
}
mod.patch(ft)
mod.buf << 0x0B // END expression opcode
}
mod.patch_len(fpatch)
}
}
mod.end_section(tpatch)
}
// https://webassembly.github.io/spec/core/binary/modules.html#data-section
//
if mod.segments.len > 0 {
tpatch := mod.start_section(.data_section)
{
mod.u32(u32(mod.segments.len))
for _, seg in mod.segments {
if idx := seg.idx {
mod.buf << 0x00 // active
// constant expr
mod.buf << 0x41 // i32.const
mod.buf << leb128.encode_i32(i32(idx))
mod.buf << 0x0B // END expression opcode
} else {
mod.buf << 0x01 // passive
}
mod.u32(u32(seg.data.len))
mod.buf << seg.data
}
}
mod.end_section(tpatch)
}
// https://webassembly.github.io/spec/core/appendix/custom.html#name-section
//
if mod.debug {
tpatch := mod.start_section(.custom_section)
mod.name('name')
if mod_name := mod.mod_name {
mpatch := mod.start_subsection(.name_module)
{
mod.name(mod_name)
}
mod.end_section(mpatch)
}
{
mpatch := mod.start_subsection(.name_function)
{
mod.u32(u32(mod.functions.len + mod.fn_imports.len))
mut idx := 0
for f in mod.fn_imports {
mod.u32(u32(idx))
mod.name('${f.mod}.${f.name}')
idx++
}
for n, _ in mod.functions {
mod.u32(u32(idx))
mod.name(n)
idx++
}
}
mod.end_section(mpatch)
}
{
mpatch := mod.start_subsection(.name_local)
{
fpatch := mod.patch_start()
mut fcount := 0
mut idx := mod.fn_imports.len // after imports
for _, ft in mod.functions {
// only add entry if it contains a local with an assigned name
if ft.locals.any(it.name != none) {
mod.u32(u32(idx)) // function idx
mut lcount := 0
lcpatch := mod.patch_start()
for lidx, loc in ft.locals {
if name := loc.name {
mod.u32(u32(lidx))
mod.name(name)
lcount++
}
}
mod.patch_u32(lcpatch, u32(lcount))
fcount++
}
idx++
}
mod.patch_u32(fpatch, u32(fcount))
}
mod.end_section(mpatch)
}
{
mpatch := mod.start_subsection(.name_type)
{
fpatch := mod.patch_start()
mut fcount := 0
for idx, ft in mod.functypes {
if name := ft.name {
mod.u32(u32(idx))
mod.name(name)
fcount++
}
}
mod.patch_u32(fpatch, u32(fcount))
}
mod.end_section(mpatch)
}
if memory := mod.memory {
mpatch := mod.start_subsection(.name_memory)
{
mod.u32(u32(1)) // one memory in vec
mod.u32(u32(0)) // 0 idx
mod.name(memory.name) // memory name
}
mod.end_section(mpatch)
}
if mod.globals.len != 0 || mod.global_imports.len != 0 {
mpatch := mod.start_subsection(.name_global)
{
fpatch := mod.patch_start()
mut fcount := 0
for gbl in mod.global_imports {
mod.u32(u32(fcount))
mod.name('${gbl.mod}.${gbl.name}')
fcount++
}
for gbl in mod.globals {
mod.u32(u32(fcount))
mod.name(gbl.name)
fcount++
}
mod.patch_u32(fpatch, u32(fcount))
}
mod.end_section(mpatch)
}
if mod.segments.any(it.name != none) {
mpatch := mod.start_subsection(.name_data)
{
fpatch := mod.patch_start()
mut fcount := 0
for idx, ds in mod.segments {
if name := ds.name {
mod.u32(u32(idx))
mod.name(name)
fcount++
}
}
mod.patch_u32(fpatch, u32(fcount))
}
mod.end_section(mpatch)
}
mod.end_section(tpatch)
}
return mod.buf
}
+53
View File
@@ -0,0 +1,53 @@
// Copyright (c) 2023 l-m.dev. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module wasm
struct ImportCallPatch {
mod string
name string
mut:
pos int
}
struct FunctionCallPatch {
name string
mut:
pos int
}
type CallPatch = FunctionCallPatch | ImportCallPatch
struct FunctionGlobalPatch {
idx GlobalIndex
mut:
pos int
}
type FunctionPatch = CallPatch | FunctionGlobalPatch
struct FunctionLocal {
typ ValType
name ?string
}
pub struct Function {
tidx int
idx int
mut:
patches []FunctionPatch // sorted
label int
export bool
mod &Module = unsafe { nil }
code []u8
locals []FunctionLocal
pub:
name string
pub mut:
export_name ?string
}
// export_name sets the export name of the function to `name`
pub fn (mut func Function) export_name(name string) {
func.export_name = name
}
File diff suppressed because it is too large. Load diff
+280
View File
@@ -0,0 +1,280 @@
// Copyright (c) 2023 l-m.dev. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module wasm
enum Section as u8 {
custom_section
type_section
import_section
function_section
table_section
memory_section
global_section
export_section
start_section
element_section
code_section
data_section
data_count_section
}
enum Subsection as u8 {
name_module
name_function
name_local
// see: https://github.com/WebAssembly/extended-name-section
name_label
name_type
name_table
name_memory
name_global
name_elem
name_data
}
pub enum NumType as u8 {
i32_t = 0x7f
i64_t = 0x7e
f32_t = 0x7d
f64_t = 0x7c
}
pub enum ValType as u8 {
i32_t = 0x7f
i64_t = 0x7e
f32_t = 0x7d
f64_t = 0x7c
v128_t = 0x7b
funcref_t = 0x70
externref_t = 0x6f
}
pub enum RefType as u8 {
funcref_t = 0x70
externref_t = 0x6f
}
// Module contains the WebAssembly module.
// Use the `compile` method to compile the module into a pure byte array.
@[heap]
pub struct Module {
mut:
buf []u8
functypes []FuncType
functions map[string]Function
globals []Global
memory ?Memory
start ?string
fn_imports []FunctionImport
global_imports []GlobalImport
segments []DataSegment
debug bool
mod_name ?string
}
struct Global {
typ ValType
is_mut bool
name string
export bool
mut:
init ConstExpression
}
struct GlobalImport {
mod string
name string
typ ValType
is_mut bool
}
struct FunctionImport {
mod string
name string
tidx int
}
struct Memory {
name string
export bool
min u32
max ?u32
}
struct DataSegment {
idx ?int
data []u8
name ?string
}
pub type LocalIndex = int
pub type GlobalIndex = int
pub type GlobalImportIndex = int
pub type DataSegmentIndex = int
pub struct FuncType {
pub:
parameters []ValType
results []ValType
name ?string
}
fn (mut mod Module) new_functype(ft FuncType) int {
// interns existing types
mut idx := mod.functypes.index(ft)
if idx == -1 {
idx = mod.functypes.len
mod.functypes << ft
}
return idx
}
// new_function creates a function struct.
pub fn (mut mod Module) new_function(name string, parameters []ValType, results []ValType) Function {
assert name !in mod.functions.keys()
idx := mod.functions.len
tidx := mod.new_functype(FuncType{parameters, results, none})
return Function{
name: name
tidx: tidx
idx: idx
mod: mod
locals: parameters.map(FunctionLocal{}) // specifying it's ValType doesn't matter
}
}
// new_debug_function creates a function struct with extra debug information.
// `argument_names` must be the same length as the parameters in the function type `typ`.
pub fn (mut mod Module) new_debug_function(name string, typ FuncType, argument_names []?string) Function {
assert name !in mod.functions.keys()
assert typ.parameters.len == argument_names.len
idx := mod.functions.len
tidx := mod.new_functype(typ)
return Function{
name: name
tidx: tidx
idx: idx
mod: mod
locals: argument_names.map(FunctionLocal{ name: it }) // specifying it's ValType doesn't matter
}
}
// enable_debug sets whether to emit debug information for not.
pub fn (mut mod Module) enable_debug(mod_name ?string) {
mod.debug = true
mod.mod_name = mod_name
}
// assign_memory assigns memory to the current module.
pub fn (mut mod Module) assign_memory(name string, export bool, min u32, max ?u32) {
mod.memory = Memory{
name: name
export: export
min: min
max: max
}
}
// assign_start assigns the start function to the current module.
pub fn (mut mod Module) assign_start(name string) {
mod.start = name
}
// new_function_import imports a new function into the current module.
pub fn (mut mod Module) new_function_import(modn string, name string, parameters []ValType, results []ValType) {
assert !mod.fn_imports.any(it.mod == modn && it.name == name)
tidx := mod.new_functype(FuncType{parameters, results, none})
mod.fn_imports << FunctionImport{
mod: modn
name: name
tidx: tidx
}
}
// new_function_import_debug imports a new function into the current module with extra debug information.
pub fn (mut mod Module) new_function_import_debug(modn string, name string, typ FuncType) {
assert !mod.fn_imports.any(it.mod == modn && it.name == name)
tidx := mod.new_functype(typ)
mod.fn_imports << FunctionImport{
mod: modn
name: name
tidx: tidx
}
}
// commit commits a function to the module, use `export` to export the function.
pub fn (mut mod Module) commit(func Function, export bool) {
assert func.name !in mod.functions.keys()
mod.functions[func.name] = Function{
...func
export: export
}
}
// new_data_segment inserts a new data segment at the memory index `pos`.
// `name` is optional, it is used for debug info.
pub fn (mut mod Module) new_data_segment(name ?string, pos int, data []u8) DataSegmentIndex {
len := mod.segments.len
mod.segments << DataSegment{
idx: pos
data: data
name: name
}
return len
}
// new_passive_data_segment inserts a new passive data segment.
// `name` is optional, it is used for debug info.
pub fn (mut mod Module) new_passive_data_segment(name ?string, data []u8) {
mod.segments << DataSegment{
data: data
name: name
}
}
// new_global creates a global and returns it's index.
// See `global_get`, `global_set`.
pub fn (mut mod Module) new_global(name string, export bool, typ ValType, is_mut bool, init ConstExpression) GlobalIndex {
len := mod.globals.len
mod.globals << Global{
typ: typ
is_mut: is_mut
name: name
export: export
init: init
}
return len
}
// new_global_import imports a new global into the current module and returns it's index.
// See `global_get`, `global_set`.
pub fn (mut mod Module) new_global_import(modn string, name string, typ ValType, is_mut bool) GlobalImportIndex {
assert !mod.fn_imports.any(it.mod == modn && it.name == name)
len := mod.global_imports.len
mod.global_imports << GlobalImport{
mod: modn
name: name
typ: typ
is_mut: is_mut
}
return len
}
// assign_global_init assigns a global with the constant expression `init`.
// See `new_global`.
pub fn (mut mod Module) assign_global_init(global GlobalIndex, init ConstExpression) {
mod.globals[global].init = init
}
+36
View File
@@ -0,0 +1,36 @@
module main
import wasm
fn test_add() {
mut m := wasm.Module{}
mut a1 := m.new_function('add', [.i32_t, .i32_t], [.i32_t])
{
a1.local_get(0)
a1.local_get(1)
a1.add(.i32_t)
}
m.commit(a1, true)
mut a2 := m.new_function('sub', [.i32_t, .i32_t], [.i32_t])
{
a2.local_get(0)
a2.local_get(1)
a2.sub(.i32_t)
}
m.commit(a2, true)
mut a3 := m.new_function('mul', [.i32_t, .i32_t], [.i32_t])
{
a3.local_get(0)
a3.local_get(1)
a3.mul(.i32_t)
}
m.commit(a3, true)
mut a4 := m.new_function('div', [.i32_t, .i32_t], [.i32_t])
{
a4.local_get(0)
a4.local_get(1)
a4.div(.i32_t, true)
}
m.commit(a4, true)
validate(m.compile()) or { panic(err) }
}
+123
View File
@@ -0,0 +1,123 @@
module main
import wasm
fn test_block() {
mut m := wasm.Module{}
mut a1 := m.new_function('param', [], [.i32_t])
{
a1.i32_const(1)
blk := a1.c_block([.i32_t], [.i32_t])
{
a1.i32_const(2)
a1.add(.i32_t)
}
a1.c_end(blk)
}
m.commit(a1, true)
mut a2 := m.new_function('params', [], [.i32_t])
{
a2.i32_const(1)
a2.i32_const(2)
blk := a2.c_block([.i32_t, .i32_t], [.i32_t])
{
a2.add(.i32_t)
}
a2.c_end(blk)
}
m.commit(a2, true)
mut a3 := m.new_function('params-id', [], [.i32_t])
{
a3.i32_const(1)
a3.i32_const(2)
blk := a3.c_block([.i32_t, .i32_t], [.i32_t, .i32_t])
{
}
a3.c_end(blk)
a3.add(.i32_t)
}
m.commit(a3, true)
mut b1 := m.new_function('param-break', [], [.i32_t])
{
b1.i32_const(1)
blk := b1.c_block([.i32_t], [.i32_t])
{
b1.i32_const(2)
b1.add(.i32_t)
b1.c_br(blk)
}
b1.c_end(blk)
}
m.commit(b1, true)
mut b2 := m.new_function('params-break', [], [.i32_t])
{
b2.i32_const(1)
b2.i32_const(2)
blk := b2.c_block([.i32_t, .i32_t], [.i32_t])
{
b2.add(.i32_t)
b2.c_br(blk)
}
b2.c_end(blk)
}
m.commit(b2, true)
mut b3 := m.new_function('params-id-break', [], [.i32_t])
{
b3.i32_const(1)
b3.i32_const(2)
blk := b3.c_block([.i32_t, .i32_t], [.i32_t, .i32_t])
{
b3.c_br(blk)
}
b3.c_end(blk)
b3.add(.i32_t)
}
m.commit(b3, true)
mut dummy := m.new_function('dummy', [], [])
{
}
m.commit(dummy, false)
mut c1 := m.new_function('singular', [], [.i32_t])
{
blk1 := c1.c_block([], [])
{
c1.nop()
}
c1.c_end(blk1)
blk2 := c1.c_block([], [.i32_t])
{
c1.i32_const(7)
}
c1.c_end(blk2)
}
m.commit(c1, true)
mut c2 := m.new_function('nested', [], [.i32_t])
{
blk := c2.c_block([], [.i32_t])
{
blk1 := c2.c_block([], [])
{
c2.call('dummy')
blk2 := c2.c_block([], [])
{
}
c2.c_end(blk2)
c2.nop()
}
c2.c_end(blk1)
blk2 := c2.c_block([], [.i32_t])
{
c2.call('dummy')
c2.i32_const(9)
}
c2.c_end(blk2)
}
c2.c_end(blk)
}
m.commit(c2, true)
validate(m.compile()) or { panic(err) }
}
+86
View File
@@ -0,0 +1,86 @@
module main
import wasm
fn test_call() {
mut m := wasm.Module{}
mut a1 := m.new_function('const-i32', [], [.i32_t])
{
a1.i32_const(0x132)
}
m.commit(a1, false)
mut a2 := m.new_function('const-i64', [], [.i64_t])
{
a2.i64_const(0x164)
}
m.commit(a2, false)
mut a3 := m.new_function('const-f32', [], [.f32_t])
{
a3.f32_const(0.2)
}
m.commit(a3, false)
mut a4 := m.new_function('const-f64', [], [.f64_t])
{
a4.f64_const(0.4)
}
m.commit(a4, false)
mut a5 := m.new_function('const-i32-i64', [], [.i32_t, .i64_t])
{
a5.i32_const(0x132)
a5.i64_const(0x164)
}
m.commit(a5, false)
mut b1 := m.new_function('type-i32', [], [.i32_t])
{
b1.call('const-i32')
}
m.commit(b1, true)
mut b2 := m.new_function('type-i64', [], [.i64_t])
{
b2.call('const-i64')
}
m.commit(b2, true)
mut b3 := m.new_function('type-f32', [], [.f32_t])
{
b3.call('const-f32')
}
m.commit(b3, true)
mut b4 := m.new_function('type-f64', [], [.f64_t])
{
b4.call('const-f64')
}
m.commit(b4, true)
mut b5 := m.new_function('type-i32-i64', [], [.i32_t, .i64_t])
{
b5.call('const-i32-i64')
}
m.commit(b5, true)
mut fac := m.new_function('fac', [.i64_t], [.i64_t])
{
fac.local_get(0)
fac.eqz(.i64_t)
ifs := fac.c_if([], [.i64_t])
{
fac.i64_const(1)
}
fac.c_else(ifs)
{
{
fac.local_get(0)
}
{
fac.local_get(0)
fac.i64_const(1)
fac.sub(.i64_t)
fac.call('fac')
}
fac.mul(.i64_t)
}
fac.c_end(ifs)
}
m.commit(fac, true)
validate(m.compile()) or { panic(err) }
}
+40
View File
@@ -0,0 +1,40 @@
module main
import os
const pid = os.getpid()
const wasm_validate_exe = find_wasm_validate() or {
println('>>> Skipping test, since wasm-validate could not be found, error: ${err}')
exit(0)
}
fn find_wasm_validate() !string {
// Prefer to find our own version first, if it was installed already
// through install_wabt.vsh, since it is more likely to be known, recent, and stable:
thirdpart_wasm_validate_folder := os.join_path(@VEXEROOT, 'thirdparty', 'wabt', 'bin')
extension := $if windows { '.exe' } $else { '' }
wasm_validate_executable := os.join_path(thirdpart_wasm_validate_folder,
'wasm-validate${extension}')
if os.exists(wasm_validate_executable) {
return wasm_validate_executable
}
if path := os.find_abs_path_of_executable('wasm-validate') {
return path
}
return error('could not find wasm-validate executable in thirdparty/ as well, try first `v run cmd/tools/install_wabt.vsh`')
}
// validate validates the given wasm code using `wasm-validate` executable.
pub fn validate(code []u8) ! {
println('validating using: ${wasm_validate_exe}')
outfile := os.join_path(os.temp_dir(), 'code_${pid}.wasm')
os.write_file(outfile, code.bytestr())!
validation_cmd := '${os.quoted_path(wasm_validate_exe)} ${os.quoted_path(outfile)}'
res := os.execute(validation_cmd)
if res.exit_code != 0 {
eprintln('failed exit code: ${res.exit_code} | command:\n${validation_cmd}')
return error('wasm-validate exited with a non zero exit code: ${res.exit_code}')
}
os.rm(outfile)!
}
+60
View File
@@ -0,0 +1,60 @@
module main
import wasm
fn test_debug() {
mut m := wasm.Module{}
m.enable_debug('hello VLANG!')
// FuncType with debuginfo/name
func_type := wasm.FuncType{[.i32_t, .i32_t], [.i32_t], 'fn_<int_int>_int'}
// []?string, named function parameters
param_names := [?string('a'), 'b']
mut a1 := m.new_debug_function('add', func_type, param_names)
{
loc := a1.new_local_named(.i32_t, 'intermediary')
a1.local_get(0)
a1.local_get(1)
a1.add(.i32_t)
a1.local_set(loc)
a1.local_get(loc)
}
m.commit(a1, false)
validate(m.compile()) or { panic(err) }
}
fn test_wasi_debug() {
mut m := wasm.Module{}
m.enable_debug('hello!')
m.new_global('__vsp', true, .i32_t, true, wasm.constexpr_value(10))
m.new_global_import('env', 'glble', .i32_t, false)
m.new_function_import('wasi_unstable', 'proc_exit', [.i32_t], [])
m.new_function_import('wasi_unstable', 'fd_write', [.i32_t, .i32_t, .i32_t, .i32_t], [
.i32_t,
])
m.assign_memory('memory', true, 1, none)
m.new_data_segment('CIOVec.str', 0, [u8(8), 0, 0, 0]) // pointer to string
m.new_data_segment('CIOVec.len', 4, [u8(13), 0, 0, 0]) // length of string
m.new_data_segment(none, 8, 'Hello, WASI!\n'.bytes())
mut func := m.new_function('_start', [], [])
{
func.new_local_named(.i32_t, 'loc')
func.i32_const(1) // stdout
func.i32_const(0) // *iovs
func.i32_const(1) // 1 iov
func.i32_const(-1) // *retptrs
func.call_import('wasi_unstable', 'fd_write')
func.drop()
func.i32_const(0)
func.call_import('wasi_unstable', 'proc_exit')
}
m.commit(func, true)
print(m.compile().bytestr())
}
+30
View File
@@ -0,0 +1,30 @@
module main
import wasm
fn test_patch() {
mut m := wasm.Module{}
vsp := m.new_global('__vsp', false, .i32_t, true, wasm.constexpr_value(10))
mut at := m.new_function('add', [], [])
{
pp := at.patch_pos()
at.drop()
at.i32_const(10)
at.i32_const(10)
at.i32_const(10)
at.drop()
at.drop()
at.drop()
pps := at.patch_pos()
{
at.i32_const(10)
at.i32_const(10)
at.global_set(vsp)
at.i32_const(10)
at.global_set(vsp)
}
at.patch(pp, pps) // move to start
}
m.commit(at, true)
validate(m.compile()) or { panic(err) }
}
+36
View File
@@ -0,0 +1,36 @@
module main
import wasm
fn test_globals() {
mut m := wasm.Module{}
m.enable_debug('vlang')
vsp := m.new_global('__vsp', false, .i32_t, true, wasm.constexpr_value(10))
mut func := m.new_function('vsp', [], [.i32_t])
{
func.global_get(vsp)
func.i32_const(20)
func.add(.i32_t)
func.global_set(vsp)
func.global_get(vsp)
}
m.commit(func, true)
fref := m.new_global('__ref', true, .funcref_t, true, wasm.constexpr_ref_null(.funcref_t))
mut func1 := m.new_function('ref', [], [])
{
func1.ref_func('vsp')
func1.global_set(fref)
}
m.commit(func1, true)
gimport := m.new_global_import('env', '__import', .f64_t, false)
mut func2 := m.new_function('import', [], [.f64_t])
{
func2.global_get(gimport)
}
m.commit(func2, true)
validate(m.compile()) or { panic(err) }
}