plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


7ff787d — Peter John 2026-11-10T11:19:16+05:30
wasm codegen: declare each function type once
compiler/wasm-codegen/src/module.rs CHANGED
@@ -28,6 +28,10 @@ pub struct WasmModule {
28
28
  /// `types.len()`, since one `TypeEntry::Rec` occupies as many indices as it has
29
29
  /// members while still being a single `Vec` element.
30
30
  pub(crate) next_type_idx: u32,
31
+ /// Index of each distinct function type already declared: `addType` hands out the same
32
+ /// one again. A function type outside a rec group is its own one-member group, so two
33
+ /// structurally equal ones are the same type to the engine anyway.
34
+ pub(crate) func_type_ids: HashMap<(Vec<ValType>, Vec<ValType>), u32>,
31
35
  pub(crate) imports: Vec<(String, String, u32)>,
32
36
  pub(crate) functions: Vec<(u32, Vec<u8>)>,
33
37
  pub(crate) exports: Vec<(String, ExportKind, u32)>,
@@ -50,6 +54,7 @@ impl WasmModule {
50
54
  Self {
51
55
  types: Vec::new(),
52
56
  next_type_idx: 0,
57
+ func_type_ids: HashMap::new(),
53
58
  imports: Vec::new(),
54
59
  functions: Vec::new(),
55
60
  exports: Vec::new(),
@@ -72,7 +77,12 @@ impl WasmModule {
72
77
  }
73
78
 
74
79
  pub fn addType(&mut self, params: &[ValType], results: &[ValType]) -> u32 {
80
+ let key = (params.to_vec(), results.to_vec());
81
+ if let Some(&idx) = self.func_type_ids.get(&key) {
82
+ return idx;
83
+ }
75
84
  let idx = self.next_type_idx;
85
+ self.func_type_ids.insert(key, idx);
76
86
  self.types.push(TypeEntry::Func(FuncType::new(
77
87
  params.iter().copied(),
78
88
  results.iter().copied(),
compiler/wasm-codegen/tests/wasm_codegen/optimize_test.rs CHANGED
@@ -115,3 +115,24 @@ fun main() -> Int =
115
115
  assert!(names.iter().any(|n| n.starts_with("twice")), "{names:?}");
116
116
  assert_eq!(runInt("deadfns", src), 23);
117
117
  }
118
+
119
+ /// Each function signature is declared once in the type section, however many functions
120
+ /// share it.
121
+ #[test]
122
+ fn functionTypesAreDeclaredOnce() {
123
+ let bytes = compile("functypes", POINT);
124
+ let mut seen = std::collections::HashSet::new();
125
+ for payload in wasmparser::Parser::new(0).parse_all(&bytes) {
126
+ if let wasmparser::Payload::TypeSection(r) = payload.unwrap() {
127
+ for group in r {
128
+ for t in group.unwrap().into_types() {
129
+ if let wasmparser::CompositeInnerType::Func(f) = &t.composite_type.inner {
130
+ let key = format!("{:?} -> {:?}", f.params(), f.results());
131
+ assert!(seen.insert(key.clone()), "declared twice: {key}");
132
+ }
133
+ }
134
+ }
135
+ }
136
+ }
137
+ assert!(seen.len() > 3, "{seen:?}");
138
+ }