From 4cef91c3b03581693ad342950d8f6399a892e178 Mon Sep 17 00:00:00 2001 From: Sam Zhou Date: Sun, 15 Dec 2024 17:38:53 -0800 Subject: [PATCH] [wasm][ast] Support struct type definitions --- crates/samlang-ast/src/wasm.rs | 20 ++++++++++++++++++++ crates/samlang-compiler/src/wasm_lowering.rs | 1 + 2 files changed, 21 insertions(+) diff --git a/crates/samlang-ast/src/wasm.rs b/crates/samlang-ast/src/wasm.rs index 7087b0b1..70e4e5bd 100644 --- a/crates/samlang-ast/src/wasm.rs +++ b/crates/samlang-ast/src/wasm.rs @@ -324,6 +324,7 @@ impl GlobalData { pub struct Module { pub function_type_parameter_counts: Vec, + pub type_definition: Vec, pub global_variables: Vec, pub exported_functions: Vec, pub functions: Vec, @@ -345,6 +346,17 @@ impl Module { collector.push_str(") (result i32)))\n"); } } + for type_def in &self.type_definition { + collector.push_str("(type $"); + type_def.name.write_encoded(&mut collector, heap, table); + collector.push_str(" (struct"); + for field in &type_def.mappings { + collector.push_str(" (field "); + field.pretty_print(&mut collector, heap, table); + collector.push(')'); + } + collector.push_str("))\n"); + } for d in &self.global_variables { d.pretty_print(&mut collector); } @@ -409,6 +421,13 @@ mod tests { let module = Module { function_type_parameter_counts: vec![0, 1, 2, 3], + type_definition: vec![lir::TypeDefinition { + name: table.create_type_name_for_test(PStr::UPPER_F), + mappings: vec![ + lir::Type::Int32, + lir::Type::Id(table.create_type_name_for_test(PStr::UPPER_F)), + ], + }], global_variables: vec![ GlobalData { constant_pointer: 1024, bytes: vec![0, 0] }, GlobalData { constant_pointer: 323, bytes: vec![3, 2] }, @@ -582,6 +601,7 @@ mod tests { (type $i32_=>_i32 (func (param i32) (result i32))) (type $i32_i32_=>_i32 (func (param i32 i32) (result i32))) (type $i32_i32_i32_=>_i32 (func (param i32 i32 i32) (result i32))) +(type $_F (struct (field number) (field _F))) (data (i32.const 1024) "\00\00") (data (i32.const 323) "\03\02") (table $0 1 funcref) diff --git a/crates/samlang-compiler/src/wasm_lowering.rs b/crates/samlang-compiler/src/wasm_lowering.rs index a8560768..58e385a9 100644 --- a/crates/samlang-compiler/src/wasm_lowering.rs +++ b/crates/samlang-compiler/src/wasm_lowering.rs @@ -304,6 +304,7 @@ pub(super) fn compile_lir_to_wasm(heap: &Heap, sources: &lir::Sources) -> wasm:: .collect::>() .into_iter() .collect_vec(), + type_definition: vec![], global_variables, exported_functions: sources.main_function_names.clone(), functions: sources