use crate::parser::ast::{TypeSpec, Spec};
use crate::parser::FuncTypeKey;
use crate::parser::Token;
use crate::parser::parse_str;
use std::collections::HashMap;
use wasm_encoder::{
CodeSection, ExportKind, ExportSection, Function, FunctionSection, Instruction,
Module as WasmModule, TypeSection, ValType, MemorySection, MemoryType,
};
use crate::parser::{
ast::{BasicLit, Decl, Expr, File, FuncDecl, Stmt, GenDecl},
objects::{AstObjects, IdentKey, SpecKey},
};
use std::rc::Rc;
fn extract_export_name(source: &str, func_name: &str) -> Option<String> {
let lines: Vec<&str> = source.lines().collect();
for (i, line) in lines.iter().enumerate() {
if line.contains(&format!("func {}", func_name)) {
for j in (0..i).rev() {
let check_line = lines[j].trim();
if check_line.starts_with("//export ") {
let export_name = check_line.strip_prefix("//export ").unwrap().trim();
if !export_name.is_empty() {
return Some(export_name.to_string());
}
}
if !check_line.is_empty() && !check_line.starts_with("//") {
break;
}
}
break;
}
}
None
}
#[derive(Debug, Clone)]
pub enum WasmExpr {
Integer(i32),
Variable(String),
Binary(WasmBinaryOp, Box<WasmExpr>, Box<WasmExpr>),
Unary(WasmUnaryOp, Box<WasmExpr>),
Call(String, Vec<WasmExpr>),
Assign(String, Box<WasmExpr>),
StructLiteral(String, Vec<(String, WasmExpr)>), FieldAccess(Box<WasmExpr>, String), FieldAssign(Box<WasmExpr>, String, Box<WasmExpr>), AddressOf(Box<WasmExpr>), Dereference(Box<WasmExpr>), }
#[derive(Debug, Clone)]
pub enum WasmUnaryOp {
Neg,
Not,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WasmBinaryOp {
Add,
Sub,
Mul,
Div,
Rem, Lt,
Gt,
LtEq,
GtEq,
Eq,
NotEq,
And, Or, Xor, Shl, Shr, LogicalOr, LogicalAnd, }
#[derive(Debug, Clone)]
pub enum WasmStatement {
ExprStmt(WasmExpr),
VarDecl(String, WasmExpr),
Return(Option<WasmExpr>),
Block(Vec<WasmStatement>),
If(WasmExpr, Vec<WasmStatement>, Option<Vec<WasmStatement>>),
Loop(Vec<WasmStatement>),
Break,
StructDecl(String, Vec<(String, WasmType)>), }
#[derive(Debug, Clone)]
pub struct WasmFunctionDef {
pub name: String,
pub export_name: Option<String>,
pub params: Vec<(String, WasmType)>,
pub return_type: Option<WasmType>,
pub body: Vec<WasmStatement>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum WasmType {
Int,
Float,
Void,
Struct(String), Pointer(Box<WasmType>), }
#[derive(Debug, Clone)]
pub struct WasmStructDef {
pub name: String,
pub fields: Vec<(String, WasmType)>,
pub field_offsets: HashMap<String, u32>, pub size: u32, }
#[derive(Debug)]
pub struct WasmProgram {
pub functions: Vec<WasmFunctionDef>,
pub structs: Vec<WasmStructDef>,
}
pub struct GoToWasmTranslator {
struct_defs: HashMap<String, WasmStructDef>,
}
impl GoToWasmTranslator {
pub fn new() -> Self {
Self {
struct_defs: HashMap::new(),
}
}
pub fn translate_program(go_program: &File, objs: &AstObjects, source: &str) -> WasmProgram {
let mut translator = Self::new();
let mut functions = Vec::new();
let mut structs = Vec::new();
for decl in &go_program.decls {
if let Decl::Gen(gen_decl) = decl {
for spec_key in &gen_decl.specs {
if let Spec::Type(type_spec) = &objs.specs[*spec_key] {
if let Some(struct_def) = translator.translate_struct_definition(type_spec, objs) {
translator.struct_defs.insert(struct_def.name.clone(), struct_def.clone());
structs.push(struct_def);
}
}
}
}
}
for decl in &go_program.decls {
if let Decl::Func(func_decl_key) = decl {
let func_decl = &objs.fdecls[*func_decl_key];
functions.push(translator.translate_function(func_decl, objs, source));
}
}
WasmProgram { functions, structs }
}
fn translate_struct_definition(&mut self, type_spec: &TypeSpec, objs: &AstObjects) -> Option<WasmStructDef> {
let struct_name = objs.idents[type_spec.name].name.clone();
if let Expr::Struct(struct_type) = &type_spec.typ {
let mut fields = Vec::new();
let mut field_offsets = HashMap::new();
let mut current_offset = 0u32;
for field_key in &struct_type.fields.list {
let field = &objs.fields[*field_key];
let field_type = Self::go_type_to_wasm_type(&field.typ, objs);
let field_size = Self::get_type_size(&field_type);
if !field.names.is_empty() {
for name_key in &field.names {
let field_name = objs.idents[*name_key].name.clone();
field_offsets.insert(field_name.clone(), current_offset);
fields.push((field_name, field_type.clone()));
current_offset += field_size;
}
} else {
let field_name = format!("field_{}", fields.len());
field_offsets.insert(field_name.clone(), current_offset);
fields.push((field_name, field_type.clone()));
current_offset += field_size;
}
}
return Some(WasmStructDef {
name: struct_name,
fields,
field_offsets,
size: current_offset,
});
}
None
}
fn get_type_size(wasm_type: &WasmType) -> u32 {
match wasm_type {
WasmType::Int => 4, WasmType::Float => 4, WasmType::Void => 0,
WasmType::Pointer(_) => 4, WasmType::Struct(_struct_name) => {
16 }
}
}
fn translate_function(&self, go_func: &FuncDecl, objs: &AstObjects, source: &str) -> WasmFunctionDef {
let func_name = objs.idents[go_func.name].name.clone();
let (params, return_type) = Self::extract_function_signature(&go_func.typ, objs);
let body = if let Some(ref body_block) = go_func.body {
self.translate_statements(&body_block.list, objs)
} else {
Vec::new()
};
let export_name = extract_export_name(source, &func_name);
WasmFunctionDef {
name: func_name,
export_name,
params,
return_type,
body,
}
}
fn extract_function_signature(
func_type_key: &FuncTypeKey,
objs: &AstObjects,
) -> (Vec<(String, WasmType)>, Option<WasmType>) {
let func_type = &objs.ftypes[*func_type_key];
let mut params = Vec::new();
for field_key in &func_type.params.list {
let field = &objs.fields[*field_key];
let param_type = Self::go_type_to_wasm_type(&field.typ, objs);
if !field.names.is_empty() {
for name_key in &field.names {
let param_name = objs.idents[*name_key].name.clone();
params.push((param_name, param_type.clone()));
}
} else {
params.push((format!("param_{}", params.len()), param_type));
}
}
let return_type = if let Some(ref results) = func_type.results {
if !results.list.is_empty() {
let return_field = &objs.fields[results.list[0]];
Some(Self::go_type_to_wasm_type(&return_field.typ, objs))
} else {
None
}
} else {
None
};
(params, return_type)
}
fn go_type_to_wasm_type(go_type: &Expr, objs: &AstObjects) -> WasmType {
match go_type {
Expr::Ident(ident_key) => {
let type_name = &objs.idents[*ident_key].name;
match type_name.as_str() {
"int" | "int32" | "int64" => WasmType::Int,
"float32" | "float64" => WasmType::Float,
_ => WasmType::Int, }
}
_ => WasmType::Int, }
}
fn translate_binary_op(go_op: &Token) -> WasmBinaryOp {
match go_op {
Token::ADD => WasmBinaryOp::Add,
Token::SUB => WasmBinaryOp::Sub,
Token::MUL => WasmBinaryOp::Mul,
Token::QUO => WasmBinaryOp::Div,
Token::REM => WasmBinaryOp::Rem, Token::LSS => WasmBinaryOp::Lt,
Token::GTR => WasmBinaryOp::Gt,
Token::LEQ => WasmBinaryOp::LtEq,
Token::GEQ => WasmBinaryOp::GtEq,
Token::EQL => WasmBinaryOp::Eq,
Token::NEQ => WasmBinaryOp::NotEq,
Token::AND => WasmBinaryOp::And, Token::OR => WasmBinaryOp::Or, Token::XOR => WasmBinaryOp::Xor, Token::SHL => WasmBinaryOp::Shl, Token::SHR => WasmBinaryOp::Shr, Token::LOR => WasmBinaryOp::LogicalOr, Token::LAND => WasmBinaryOp::LogicalAnd, _ => {
let op_str = format!("{:?}", go_op);
match op_str.as_str() {
"%" => WasmBinaryOp::Rem,
"&" => WasmBinaryOp::And,
"|" => WasmBinaryOp::Or,
"^" => WasmBinaryOp::Xor,
"<<" => WasmBinaryOp::Shl,
">>" => WasmBinaryOp::Shr,
"||" => WasmBinaryOp::LogicalOr,
"&&" => WasmBinaryOp::LogicalAnd,
_ => {
println!("Warning: Unknown binary operator: {:?}", go_op);
WasmBinaryOp::Add }
}
}
}
}
fn translate_unary_op(go_op: &Token) -> WasmUnaryOp {
match go_op {
Token::SUB => WasmUnaryOp::Neg,
Token::NOT => WasmUnaryOp::Not,
_ => {
println!("Warning: Unknown unary operator: {:?}", go_op);
WasmUnaryOp::Neg }
}
}
fn translate_statements(&self, go_stmts: &[Stmt], objs: &AstObjects) -> Vec<WasmStatement> {
go_stmts
.iter()
.filter_map(|stmt| self.translate_statement_optional(stmt, objs))
.collect()
}
fn translate_expression(&self, go_expr: &Expr, objs: &AstObjects) -> WasmExpr {
match go_expr {
Expr::BasicLit(lit) => {
match &lit.token {
Token::INT(lit_val) => {
let value_str: &String = lit_val.as_ref();
WasmExpr::Integer(value_str.parse::<i32>().unwrap_or(0))
}
Token::CHAR(lit_val) => {
let value_str: &String = lit_val.as_ref();
WasmExpr::Integer(value_str.chars().next().unwrap_or('0') as i32)
}
_ => WasmExpr::Integer(0)
}
}
Expr::Ident(ident_key) => {
let ident_name = objs.idents[*ident_key].name.clone();
WasmExpr::Variable(ident_name)
}
Expr::Paren(paren_expr) => {
self.translate_expression(&paren_expr.expr, objs)
}
Expr::Binary(binary_expr) => {
let left = self.translate_expression(&binary_expr.expr_a, objs);
let right = self.translate_expression(&binary_expr.expr_b, objs);
let op = Self::translate_binary_op(&binary_expr.op);
WasmExpr::Binary(op, Box::new(left), Box::new(right))
}
Expr::Call(call_expr) => {
let func_name = if let Expr::Ident(func_ident) = &call_expr.func {
objs.idents[*func_ident].name.clone()
} else {
"unknown".to_string()
};
let args = call_expr
.args
.iter()
.map(|arg| self.translate_expression(arg, objs))
.collect();
WasmExpr::Call(func_name, args)
}
Expr::Unary(unary_expr) => {
let operand = self.translate_expression(&unary_expr.expr, objs);
let op = Self::translate_unary_op(&unary_expr.op);
match unary_expr.op {
Token::AND => WasmExpr::AddressOf(Box::new(operand)),
Token::MUL => WasmExpr::Dereference(Box::new(operand)),
_ => WasmExpr::Unary(op, Box::new(operand)),
}
}
Expr::Selector(selector_expr) => {
let object = self.translate_expression(&selector_expr.expr, objs);
let field_name = objs.idents[selector_expr.sel].name.clone();
WasmExpr::FieldAccess(Box::new(object), field_name)
}
Expr::CompositeLit(composite_lit) => {
let struct_name = if let Some(Expr::Ident(type_ident)) = &composite_lit.typ {
objs.idents[*type_ident].name.clone()
} else {
"unknown".to_string()
};
let mut field_values = Vec::new();
for element in &composite_lit.elts {
match element {
Expr::KeyValue(kv_expr) => {
if let Expr::Ident(key_ident) = &kv_expr.key {
let field_name = objs.idents[*key_ident].name.clone();
let field_value = self.translate_expression(&kv_expr.val, objs);
field_values.push((field_name, field_value));
}
}
_ => {
let field_name = format!("field_{}", field_values.len());
let field_value = self.translate_expression(element, objs);
field_values.push((field_name, field_value));
}
}
}
WasmExpr::StructLiteral(struct_name, field_values)
}
_ => {
println!("Warning: Unsupported expression type for struct support: {:?}", go_expr);
WasmExpr::Integer(0)
}
}
}
fn translate_statement_optional(&self, go_stmt: &Stmt, objs: &AstObjects) -> Option<WasmStatement> {
match go_stmt {
Stmt::Empty(_) => None,
Stmt::Expr(expr) => Some(WasmStatement::ExprStmt(self.translate_expression(expr, objs))),
Stmt::Assign(assign_key) => {
let assign_stmt = &objs.a_stmts[*assign_key];
if !assign_stmt.lhs.is_empty() && !assign_stmt.rhs.is_empty() {
if let Expr::Selector(selector_expr) = &assign_stmt.lhs[0] {
let object = self.translate_expression(&selector_expr.expr, objs);
let field_name = objs.idents[selector_expr.sel].name.clone();
let value = self.translate_expression(&assign_stmt.rhs[0], objs);
return Some(WasmStatement::ExprStmt(
WasmExpr::FieldAssign(Box::new(object), field_name, Box::new(value))
));
}
if let Expr::Ident(var_key) = &assign_stmt.lhs[0] {
let var_name = objs.idents[*var_key].name.clone();
let value_expr = self.translate_expression(&assign_stmt.rhs[0], objs);
match assign_stmt.token {
Token::ASSIGN | Token::DEFINE => {
Some(WasmStatement::VarDecl(var_name, value_expr))
}
_ => {
println!("Warning: Unsupported assignment operator: {:?}", assign_stmt.token);
Some(WasmStatement::VarDecl(var_name, value_expr))
}
}
} else {
None
}
} else {
None
}
}
Stmt::Return(return_stmt) => {
let return_expr = if !return_stmt.results.is_empty() {
Some(self.translate_expression(&return_stmt.results[0], objs))
} else {
None
};
Some(WasmStatement::Return(return_expr))
}
Stmt::Block(block) => {
let statements = self.translate_statements(&block.list, objs);
Some(WasmStatement::Block(statements))
}
Stmt::If(if_stmt) => {
let condition = self.translate_expression(&if_stmt.cond, objs);
let if_statements = self.translate_statements(&if_stmt.body.list, objs);
let else_statements = if let Some(ref else_stmt) = if_stmt.els {
match else_stmt {
Stmt::Block(else_block) => {
Some(self.translate_statements(&else_block.list, objs))
}
_ => Some(vec![self.translate_statement_optional(else_stmt, objs)?]),
}
} else {
None
};
Some(WasmStatement::If(condition, if_statements, else_statements))
}
Stmt::IncDec(inc_dec) => {
if let Expr::Ident(var_key) = &inc_dec.expr {
let var_name = objs.idents[*var_key].name.clone();
let operation = match inc_dec.token {
Token::INC => WasmBinaryOp::Add,
Token::DEC => WasmBinaryOp::Sub,
_ => {
println!("Warning: Unknown increment/decrement operator: {:?}", inc_dec.token);
WasmBinaryOp::Add
}
};
let increment_expr = WasmExpr::Binary(
operation,
Box::new(WasmExpr::Variable(var_name.clone())),
Box::new(WasmExpr::Integer(1)),
);
Some(WasmStatement::VarDecl(var_name, increment_expr))
} else {
println!("Warning: Skipping complex increment/decrement");
None
}
}
Stmt::For(for_stmt) => {
let mut loop_body = Vec::new();
if let Some(ref condition) = for_stmt.cond {
let negated_condition = WasmExpr::Unary(
WasmUnaryOp::Not,
Box::new(self.translate_expression(condition, objs))
);
loop_body.push(WasmStatement::If(
negated_condition,
vec![WasmStatement::Break],
None
));
}
let body_statements = self.translate_statements(&for_stmt.body.list, objs);
loop_body.extend(body_statements);
if let Some(ref post_stmt) = for_stmt.post {
if let Some(post_wasm) = self.translate_statement_optional(post_stmt, objs) {
loop_body.push(post_wasm);
}
}
let mut statements = Vec::new();
if let Some(ref init_stmt) = for_stmt.init {
if let Some(init_wasm) = self.translate_statement_optional(init_stmt, objs) {
statements.push(init_wasm);
}
}
statements.push(WasmStatement::Loop(loop_body));
Some(WasmStatement::Block(statements))
}
_ => {
println!("Warning: Skipping unsupported statement type: {:?}", go_stmt);
None
}
}
}
}
pub struct WasmCompiler {
types: TypeSection,
functions: FunctionSection,
exports: ExportSection,
codes: CodeSection,
function_types: HashMap<String, u32>,
function_indices: HashMap<String, u32>,
variables: HashMap<String, u32>,
next_local_index: u32,
current_func_index: u32,
struct_definitions: HashMap<String, WasmStructDef>,
memory_offset: u32, heap_pointer: u32, }
impl WasmCompiler {
pub fn new() -> Self {
Self {
types: TypeSection::new(),
functions: FunctionSection::new(),
exports: ExportSection::new(),
codes: CodeSection::new(),
function_types: HashMap::new(),
function_indices: HashMap::new(),
variables: HashMap::new(),
next_local_index: 0,
current_func_index: 0,
struct_definitions: HashMap::new(),
memory_offset: 0,
heap_pointer: 1024, }
}
pub fn compile_program(&mut self, program: &WasmProgram) -> Vec<u8> {
for struct_def in &program.structs {
self.struct_definitions.insert(struct_def.name.clone(), struct_def.clone());
}
for func in &program.functions {
let param_types: Vec<ValType> = func
.params
.iter()
.map(|(_, ty)| match ty {
WasmType::Int => ValType::I32,
WasmType::Float => ValType::F32,
WasmType::Void => panic!("Void cannot be a parameter type"),
WasmType::Struct(_) => ValType::I32, WasmType::Pointer(_) => ValType::I32,
})
.collect();
let return_types: Vec<ValType> = match &func.return_type {
Some(WasmType::Int) => vec![ValType::I32],
Some(WasmType::Float) => vec![ValType::F32],
Some(WasmType::Struct(_)) => vec![ValType::I32], Some(WasmType::Pointer(_)) => vec![ValType::I32],
Some(WasmType::Void) | None => vec![],
};
let type_index = self.types.len();
self.types.ty().function(param_types, return_types);
self.function_types.insert(func.name.clone(), type_index);
self.function_indices
.insert(func.name.clone(), self.current_func_index);
self.current_func_index += 1;
}
self.current_func_index = 0;
for func in &program.functions {
self.compile_function(func);
}
let mut module = WasmModule::new();
module.section(&self.types);
module.section(&self.functions);
let mut memory_section = MemorySection::new();
memory_section.memory(MemoryType {
minimum: 1, maximum: None,
memory64: false,
shared: false,
page_size_log2: None,
});
module.section(&memory_section);
module.section(&self.exports);
module.section(&self.codes);
module.finish()
}
fn compile_function(&mut self, func: &WasmFunctionDef) {
self.variables.clear();
self.next_local_index = 0;
let mut locals = Vec::new();
for (i, (name, _)) in func.params.iter().enumerate() {
self.variables.insert(name.clone(), i as u32);
self.next_local_index += 1;
}
let type_index = *self.function_types.get(&func.name).unwrap();
self.functions.function(type_index);
if let Some(export_name) = &func.export_name {
self.exports
.export(export_name, ExportKind::Func, self.current_func_index);
}
self.collect_variable_declarations(&func.body, &mut locals);
let mut f = Function::new(locals);
self.next_local_index = func.params.len() as u32;
for stmt in &func.body {
self.compile_statement_with_indexing(stmt, &mut f);
}
f.instruction(&Instruction::End);
self.codes.function(&f);
self.current_func_index += 1;
}
fn collect_variable_declarations(
&mut self,
statements: &[WasmStatement],
locals: &mut Vec<(u32, ValType)>,
) {
for stmt in statements {
match stmt {
WasmStatement::VarDecl(_, _) => {
locals.push((1, ValType::I32));
}
WasmStatement::Block(block_stmts) => {
self.collect_variable_declarations(block_stmts, locals);
}
WasmStatement::If(_, if_stmts, else_stmts) => {
self.collect_variable_declarations(if_stmts, locals);
if let Some(else_statements) = else_stmts {
self.collect_variable_declarations(else_statements, locals);
}
}
WasmStatement::Loop(loop_stmts) => {
self.collect_variable_declarations(loop_stmts, locals);
}
WasmStatement::StructDecl(_, _) => {
}
_ => {}
}
}
}
fn compile_statement_with_indexing(&mut self, stmt: &WasmStatement, f: &mut Function) {
match stmt {
WasmStatement::ExprStmt(expr) => {
self.compile_expression(expr, f, &mut Vec::new());
f.instruction(&Instruction::Drop); }
WasmStatement::VarDecl(name, init_expr) => {
self.compile_expression(init_expr, f, &mut Vec::new());
let local_idx = if let Some(&existing_idx) = self.variables.get(name) {
existing_idx
} else {
let idx = self.next_local_index;
self.variables.insert(name.clone(), idx);
self.next_local_index += 1;
idx
};
f.instruction(&Instruction::LocalSet(local_idx));
}
WasmStatement::Return(expr_opt) => {
if let Some(expr) = expr_opt {
self.compile_expression(expr, f, &mut Vec::new());
}
f.instruction(&Instruction::Return);
}
WasmStatement::Block(stmts) => {
for s in stmts {
self.compile_statement_with_indexing(s, f);
}
}
WasmStatement::If(condition, if_stmts, else_stmts) => {
self.compile_expression(condition, f, &mut Vec::new());
f.instruction(&Instruction::If(wasm_encoder::BlockType::Empty));
for stmt in if_stmts {
self.compile_statement_with_indexing(stmt, f);
}
if let Some(else_statements) = else_stmts {
f.instruction(&Instruction::Else);
for stmt in else_statements {
self.compile_statement_with_indexing(stmt, f);
}
}
f.instruction(&Instruction::End);
}
WasmStatement::Loop(body_stmts) => {
f.instruction(&Instruction::Block(wasm_encoder::BlockType::Empty));
f.instruction(&Instruction::Loop(wasm_encoder::BlockType::Empty));
for stmt in body_stmts {
if let WasmStatement::If(condition, if_stmts, _) = stmt {
if if_stmts.iter().any(|s| matches!(s, WasmStatement::Break)) {
self.compile_expression(condition, f, &mut Vec::new());
f.instruction(&Instruction::BrIf(1)); continue;
}
}
self.compile_statement_with_indexing(stmt, f);
}
f.instruction(&Instruction::Br(0)); f.instruction(&Instruction::End); f.instruction(&Instruction::End); }
WasmStatement::Break => {
f.instruction(&Instruction::Br(1)); }
WasmStatement::StructDecl(_, _) => {
}
}
}
fn compile_expression(&mut self, expr: &WasmExpr, f: &mut Function, _locals: &mut Vec<(u32, ValType)>) {
match expr {
WasmExpr::Integer(value) => {
f.instruction(&Instruction::I32Const(*value));
}
WasmExpr::Variable(name) => {
if let Some(&idx) = self.variables.get(name) {
f.instruction(&Instruction::LocalGet(idx));
} else {
f.instruction(&Instruction::I32Const(0));
}
}
WasmExpr::Binary(op, left, right) => {
self.compile_expression(left, f, _locals);
self.compile_expression(right, f, _locals);
match op {
WasmBinaryOp::Add => { f.instruction(&Instruction::I32Add); },
WasmBinaryOp::Sub => { f.instruction(&Instruction::I32Sub); },
WasmBinaryOp::Mul => { f.instruction(&Instruction::I32Mul); },
WasmBinaryOp::Div => { f.instruction(&Instruction::I32DivS); },
WasmBinaryOp::Rem => { f.instruction(&Instruction::I32RemS); },
WasmBinaryOp::Lt => { f.instruction(&Instruction::I32LtS); },
WasmBinaryOp::Gt => { f.instruction(&Instruction::I32GtS); },
WasmBinaryOp::LtEq => { f.instruction(&Instruction::I32LeS); },
WasmBinaryOp::GtEq => { f.instruction(&Instruction::I32GeS); },
WasmBinaryOp::Eq => { f.instruction(&Instruction::I32Eq); },
WasmBinaryOp::NotEq => { f.instruction(&Instruction::I32Ne); },
WasmBinaryOp::And => { f.instruction(&Instruction::I32And); },
WasmBinaryOp::Or => { f.instruction(&Instruction::I32Or); },
WasmBinaryOp::Xor => { f.instruction(&Instruction::I32Xor); },
WasmBinaryOp::Shl => { f.instruction(&Instruction::I32Shl); },
WasmBinaryOp::Shr => { f.instruction(&Instruction::I32ShrS); },
WasmBinaryOp::LogicalOr => {
f.instruction(&Instruction::I32Or);
f.instruction(&Instruction::I32Const(0));
f.instruction(&Instruction::I32Ne);
}
WasmBinaryOp::LogicalAnd => {
f.instruction(&Instruction::I32And);
f.instruction(&Instruction::I32Const(0));
f.instruction(&Instruction::I32Ne);
}
}
}
WasmExpr::Call(func_name, args) => {
for arg in args {
self.compile_expression(arg, f, _locals);
}
if let Some(&func_idx) = self.function_indices.get(func_name) {
f.instruction(&Instruction::Call(func_idx));
} else {
for _ in 0..args.len() {
f.instruction(&Instruction::Drop);
}
f.instruction(&Instruction::I32Const(0));
}
}
WasmExpr::Assign(name, value) => {
self.compile_expression(value, f, _locals);
if let Some(&idx) = self.variables.get(name) {
f.instruction(&Instruction::LocalTee(idx)); } else {
let idx = self.next_local_index;
self.variables.insert(name.clone(), idx);
self.next_local_index += 1;
f.instruction(&Instruction::LocalTee(idx));
}
}
WasmExpr::Unary(op, operand) => {
match op {
WasmUnaryOp::Neg => {
f.instruction(&Instruction::I32Const(0));
self.compile_expression(operand, f, _locals);
f.instruction(&Instruction::I32Sub);
}
WasmUnaryOp::Not => {
self.compile_expression(operand, f, _locals);
f.instruction(&Instruction::I32Eqz);
}
}
}
WasmExpr::StructLiteral(struct_name, field_values) => {
if let Some(struct_def) = self.struct_definitions.get(struct_name).cloned() {
f.instruction(&Instruction::I32Const(self.heap_pointer as i32));
for (field_name, field_expr) in field_values {
if let Some(&offset) = struct_def.field_offsets.get(field_name) {
f.instruction(&Instruction::I32Const(self.heap_pointer as i32));
f.instruction(&Instruction::I32Const(offset as i32));
f.instruction(&Instruction::I32Add);
self.compile_expression(field_expr, f, _locals);
f.instruction(&Instruction::I32Store(wasm_encoder::MemArg {
offset: 0,
align: 2, memory_index: 0,
}));
}
}
f.instruction(&Instruction::I32Const(self.heap_pointer as i32));
self.heap_pointer += struct_def.size;
} else {
f.instruction(&Instruction::I32Const(0));
}
}
WasmExpr::FieldAccess(object_expr, _field_name) => {
self.compile_expression(object_expr, f, _locals);
let field_offset = 0;
f.instruction(&Instruction::I32Const(field_offset));
f.instruction(&Instruction::I32Add);
f.instruction(&Instruction::I32Load(wasm_encoder::MemArg {
offset: 0,
align: 2,
memory_index: 0,
}));
}
WasmExpr::FieldAssign(object_expr, _field_name, value_expr) => {
self.compile_expression(object_expr, f, _locals);
let field_offset = 0; f.instruction(&Instruction::I32Const(field_offset));
f.instruction(&Instruction::I32Add);
self.compile_expression(value_expr, f, _locals);
f.instruction(&Instruction::I32Store(wasm_encoder::MemArg {
offset: 0,
align: 2,
memory_index: 0,
}));
}
WasmExpr::AddressOf(expr) => {
match expr.as_ref() {
WasmExpr::Variable(_var_name) => {
f.instruction(&Instruction::I32Const(self.heap_pointer as i32));
self.heap_pointer += 4; }
_ => {
self.compile_expression(expr, f, _locals);
}
}
}
WasmExpr::Dereference(expr) => {
self.compile_expression(expr, f, _locals);
f.instruction(&Instruction::I32Load(wasm_encoder::MemArg {
offset: 0,
align: 2,
memory_index: 0,
}));
}
}
}
}
pub fn compile_str(go_source: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let (ast_objects, go_program) =
parse_str(go_source).map_err(|e| format!("Parse error: {}", e))?;
let wasm_program = GoToWasmTranslator::translate_program(&go_program, &ast_objects, go_source);
let mut compiler = WasmCompiler::new();
let wasm_bytes = compiler.compile_program(&wasm_program);
Ok(wasm_bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_simple_function_compilation() {
let go_source = r#"
package main
func add(x int, y int) int {
return x + y
}
"#;
let result = compile_str(go_source);
assert!(result.is_ok(), "Failed to compile: {:?}", result.err());
let wasm_bytes = result.unwrap();
assert!(!wasm_bytes.is_empty(), "Generated WASM should not be empty");
}
}