plum

#treesitter#compiler#wasm

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

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


c10b729 — Peter John 2026-11-10T10:35:49+05:30
wasm codegen: drop ref.casts the operand's static type already satisfies
compiler/wasm-codegen/Cargo.toml CHANGED
@@ -5,13 +5,13 @@ edition = "2021"
5
5
 
6
6
  [dependencies]
7
7
  wasm-encoder = "0.220"
8
+ wasmparser = "0.220"
8
9
  plum-core = { path = "../core" }
9
10
  plum-checker = { path = "../checker" }
10
11
  plum-driver = { path = "../driver" }
11
12
 
12
13
  [dev-dependencies]
13
14
  plum-test-support = { path = "../test-support" }
14
- wasmparser = "0.220"
15
15
  tree-sitter = "0.26"
16
16
  tree-sitter-plum = { path = "../tooling/tree-sitter-plum" }
17
17
  wasmtime = "47"
compiler/wasm-codegen/src/emit.rs CHANGED
@@ -269,6 +269,6 @@ impl<'a> Emit<'a> {
269
269
  .map(|u| u.name.clone()),
270
270
  );
271
271
  fn_keys.sort();
272
- Ok((module.finish(), fn_keys))
272
+ Ok((module.finishOptimized(), fn_keys))
273
273
  }
274
274
  }
compiler/wasm-codegen/src/lib.rs CHANGED
@@ -27,6 +27,7 @@ mod intrinsics;
27
27
  mod keys;
28
28
  mod matching;
29
29
  mod module;
30
+ mod optimize;
30
31
  mod stmts;
31
32
  mod traits;
32
33
  mod units;
compiler/wasm-codegen/src/module.rs CHANGED
@@ -163,7 +163,29 @@ impl WasmModule {
163
163
  table_idx
164
164
  }
165
165
 
166
+ /// The module's bytes as built, with no optimisation.
166
167
  pub fn finish(&mut self) -> Vec<u8> {
168
+ self.encode()
169
+ }
170
+
171
+ /// The module's bytes after the passes in `optimize`. When the module as built does not
172
+ /// validate, it is returned as it is, so the engine reports the error; a pass that
173
+ /// breaks a valid module is a compiler bug (a panic in debug builds, otherwise the
174
+ /// unoptimised module is used).
175
+ pub fn finishOptimized(&mut self) -> Vec<u8> {
176
+ if crate::optimize::validates(self).is_err() {
177
+ return self.encode();
178
+ }
179
+ let saved = self.functions.clone();
180
+ let r = crate::optimize::removeRedundantCasts(self).and_then(|_| crate::optimize::validates(self));
181
+ if let Err(e) = r {
182
+ debug_assert!(false, "wasm optimisation produced an invalid module: {e}");
183
+ self.functions = saved;
184
+ }
185
+ self.encode()
186
+ }
187
+
188
+ pub(crate) fn encode(&self) -> Vec<u8> {
167
189
  let mut module = wasm_encoder::Module::new();
168
190
 
169
191
  // Type section
compiler/wasm-codegen/src/optimize.rs ADDED
@@ -0,0 +1,123 @@
1
+ //! Passes over the finished module's bytes, run by `WasmModule::finishOptimized`.
2
+ //!
3
+ //! Codegen writes instructions straight into byte buffers without tracking the static
4
+ //! wasm type of what it pushed, so some of what it emits is only provably redundant once
5
+ //! the module is whole. Each pass walks the encoded module under wasmparser's validator
6
+ //! (which knows the exact operand-stack types at every instruction) and returns byte-range
7
+ //! edits to the function bodies; wasm control flow is structured, so cutting or replacing
8
+ //! whole instructions never needs any offset fixed up.
9
+
10
+ use crate::module::WasmModule;
11
+ use wasmparser::{FuncValidator, Operator, Parser, ValidPayload, Validator, ValidatorResources, WasmFeatures, WasmModuleResources};
12
+
13
+ /// Replace body bytes `start..end` (relative to the function's body bytes, as stored in
14
+ /// `WasmModule::functions`) by `with`.
15
+ pub(crate) struct Edit {
16
+ pub start: usize,
17
+ pub end: usize,
18
+ pub with: Vec<u8>,
19
+ }
20
+
21
+ /// Visits every instruction of every defined function, in order, before the validator
22
+ /// checks it: the validator's operand stack is then the instruction's input. `visit` gets
23
+ /// the defined-function position (0 = first non-import), the validator, the instruction
24
+ /// and its body-relative byte range.
25
+ fn walk(
26
+ bytes: &[u8],
27
+ mut visit: impl FnMut(usize, &FuncValidator<ValidatorResources>, &Operator, usize, usize),
28
+ ) -> Result<(), String> {
29
+ let mut validator = Validator::new_with_features(WasmFeatures::all());
30
+ let mut fn_i = 0;
31
+ for payload in Parser::new(0).parse_all(bytes) {
32
+ let payload = payload.map_err(|e| e.to_string())?;
33
+ if let ValidPayload::Func(f, body) = validator.payload(&payload).map_err(|e| e.to_string())? {
34
+ let mut v = f.into_validator(Default::default());
35
+ let base = body.range().start;
36
+ let mut r = body.get_binary_reader();
37
+ v.read_locals(&mut r).map_err(|e| e.to_string())?;
38
+ while !r.eof() {
39
+ let pos = r.original_position();
40
+ let op = r.read_operator().map_err(|e| e.to_string())?;
41
+ let end = r.original_position();
42
+ visit(fn_i, &v, &op, pos - base, end - base);
43
+ v.op(pos, &op).map_err(|e| e.to_string())?;
44
+ }
45
+ v.finish(r.original_position()).map_err(|e| e.to_string())?;
46
+ fn_i += 1;
47
+ }
48
+ }
49
+ Ok(())
50
+ }
51
+
52
+ /// Applies `edits` (sorted by `start`, not overlapping) to `body`.
53
+ fn applyEdits(body: &[u8], edits: &[Edit]) -> Vec<u8> {
54
+ let mut out = Vec::with_capacity(body.len());
55
+ let mut at = 0;
56
+ for e in edits {
57
+ out.extend_from_slice(&body[at..e.start]);
58
+ out.extend_from_slice(&e.with);
59
+ at = e.end;
60
+ }
61
+ out.extend_from_slice(&body[at..]);
62
+ out
63
+ }
64
+
65
+ /// Applies per-function edit lists, returning how many edits there were.
66
+ fn applyAll(module: &mut WasmModule, mut edits: Vec<Vec<Edit>>) -> usize {
67
+ let mut n = 0;
68
+ for (i, es) in edits.iter_mut().enumerate() {
69
+ if es.is_empty() {
70
+ continue;
71
+ }
72
+ es.sort_by_key(|e| e.start);
73
+ n += es.len();
74
+ let body = &mut module.functions[i].1;
75
+ *body = applyEdits(body, es);
76
+ }
77
+ n
78
+ }
79
+
80
+ /// Removes every `ref.cast` whose operand's static type already is the target type or a
81
+ /// subtype of it: the cast can never fail and changes nothing (codegen casts a field
82
+ /// access's object down to its struct type even when the object came from a local of
83
+ /// exactly that type). A non-null cast of a nullable value of such a type only checks for
84
+ /// null: it goes when the next instruction is a `struct.get` (which traps on null itself),
85
+ /// otherwise it becomes the one-byte `ref.as_non_null`. Returns the number of edits.
86
+ pub(crate) fn removeRedundantCasts(module: &mut WasmModule) -> Result<usize, String> {
87
+ let bytes = module.encode();
88
+ let mut edits: Vec<Vec<Edit>> = (0..module.functions.len()).map(|_| Vec::new()).collect();
89
+ // A null-check-only cast waiting to see the next instruction.
90
+ let mut pending: Option<(usize, usize, usize)> = None;
91
+ walk(&bytes, |fn_i, v, op, start, end| {
92
+ if let Some((f, s, e)) = pending.take() {
93
+ let traps_on_null = f == fn_i
94
+ && matches!(op, Operator::StructGet { .. } | Operator::StructGetS { .. } | Operator::StructGetU { .. } | Operator::ArrayLen);
95
+ edits[f].push(Edit { start: s, end: e, with: if traps_on_null { Vec::new() } else { vec![0xD4] } });
96
+ }
97
+ let (nullable, hty) = match op {
98
+ Operator::RefCastNonNull { hty } => (false, *hty),
99
+ Operator::RefCastNullable { hty } => (true, *hty),
100
+ _ => return,
101
+ };
102
+ let Some(Some(wasmparser::ValType::Ref(top))) = v.get_operand_type(0) else { return };
103
+ let Some(rt) = wasmparser::RefType::new(nullable, hty) else { return };
104
+ let mut target = wasmparser::ValType::Ref(rt);
105
+ if v.resources().check_value_type(&mut target, v.features(), start).is_err() {
106
+ return;
107
+ }
108
+ if v.resources().is_subtype(wasmparser::ValType::Ref(top), target) {
109
+ edits[fn_i].push(Edit { start, end, with: Vec::new() });
110
+ } else if top.is_nullable() && !nullable {
111
+ let Some(non_null) = wasmparser::RefType::new(false, top.heap_type()) else { return };
112
+ if v.resources().is_subtype(wasmparser::ValType::Ref(non_null), target) {
113
+ pending = Some((fn_i, start, end));
114
+ }
115
+ }
116
+ })?;
117
+ Ok(applyAll(module, edits))
118
+ }
119
+
120
+ /// Checks that `module` encodes to a valid module.
121
+ pub(crate) fn validates(module: &WasmModule) -> Result<(), String> {
122
+ walk(&module.encode(), |_, _, _, _, _| {})
123
+ }
compiler/wasm-codegen/tests/wasm_codegen/main.rs CHANGED
@@ -9,3 +9,4 @@ mod e2e_types;
9
9
  mod examples_test;
10
10
  mod fusion_alloc_test;
11
11
  mod native_test;
12
+ mod optimize_test;
compiler/wasm-codegen/tests/wasm_codegen/optimize_test.rs ADDED
@@ -0,0 +1,90 @@
1
+ //! The module-level passes in `src/optimize.rs`: what they take out, and that what is
2
+ //! left still runs.
3
+
4
+ use plum_test_support::{compile, runInt};
5
+
6
+ /// Every operator of every function body, as debug strings, with the function's name.
7
+ fn bodies(bytes: &[u8]) -> Vec<(String, Vec<String>)> {
8
+ let mut names: std::collections::HashMap<u32, String> = Default::default();
9
+ let mut out = Vec::new();
10
+ let mut imports = 0u32;
11
+ for payload in wasmparser::Parser::new(0).parse_all(bytes) {
12
+ match payload.unwrap() {
13
+ wasmparser::Payload::ImportSection(s) => imports = s.count(),
14
+ wasmparser::Payload::CustomSection(c) => {
15
+ if let wasmparser::KnownCustom::Name(r) = c.as_known() {
16
+ for n in r {
17
+ if let wasmparser::Name::Function(m) = n.unwrap() {
18
+ for e in m {
19
+ let e = e.unwrap();
20
+ names.insert(e.index, e.name.to_string());
21
+ }
22
+ }
23
+ }
24
+ }
25
+ }
26
+ wasmparser::Payload::CodeSectionEntry(b) => {
27
+ let mut ops = Vec::new();
28
+ let mut r = b.get_operators_reader().unwrap();
29
+ while !r.eof() {
30
+ ops.push(format!("{:?}", r.read().unwrap()));
31
+ }
32
+ out.push(ops);
33
+ }
34
+ _ => {}
35
+ }
36
+ }
37
+ out.into_iter().enumerate().map(|(i, ops)| (names.get(&(imports + i as u32)).cloned().unwrap_or_default(), ops)).collect()
38
+ }
39
+
40
+ fn body<'a>(all: &'a [(String, Vec<String>)], name: &str) -> &'a [String] {
41
+ &all.iter().find(|(n, _)| n == name).unwrap_or_else(|| panic!("no function {name}: {:?}", all.iter().map(|b| &b.0).collect::<Vec<_>>())).1
42
+ }
43
+
44
+ const POINT: &str = "\
45
+ import std/Int
46
+ import std/Str
47
+
48
+ struct Point(x: Int, y: Int, label: Str)
49
+
50
+ fun total(p: Point) -> Int =
51
+ p.x + p.y
52
+
53
+ fun main() -> Int =
54
+ total(Point(x: 3, y: 4, label: \"p\"))
55
+ ";
56
+
57
+ /// Reading a field of a struct-typed parameter needs no cast: the parameter already has
58
+ /// the struct's type.
59
+ #[test]
60
+ fn fieldOfAStructParameterIsNotCast() {
61
+ let all = bodies(&compile("nocast", POINT));
62
+ let ops = body(&all, "total");
63
+ assert!(!ops.iter().any(|o| o.starts_with("RefCast")), "{ops:?}");
64
+ assert!(ops.iter().any(|o| o.starts_with("StructGet")), "{ops:?}");
65
+ assert_eq!(runInt("nocast", POINT), 7);
66
+ }
67
+
68
+ /// A downcast to an enum variant is a real check and stays.
69
+ #[test]
70
+ fn variantDowncastStays() {
71
+ let src = "\
72
+ import std/Int
73
+
74
+ enum Shape =
75
+ | Circle(r: Int)
76
+ | Rect(w: Int, h: Int)
77
+
78
+ fun areaOf(s: Shape) -> Int =
79
+ match s
80
+ Circle(r) => r * r * 3
81
+ Rect(w, h) => w * h
82
+
83
+ fun main() -> Int =
84
+ areaOf(Rect(w: 2, h: 5)) + areaOf(Circle(r: 1))
85
+ ";
86
+ let all = bodies(&compile("variantcast", src));
87
+ let ops = body(&all, "areaOf");
88
+ assert!(ops.iter().any(|o| o.starts_with("RefCast") || o.starts_with("BrOnCast")), "{ops:?}");
89
+ assert_eq!(runInt("variantcast", src), 13);
90
+ }