plum

#treesitter#compiler#wasm

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

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


457345f — Peter John 2026-11-09T22:09:36+05:30
Trait dispatch: a br_table on a type tag instead of a ref.test chain
benchmarks/dispatch/run.py ADDED
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env python3
2
+ """Times a trait method call through trait objects of 2, 9 and 20 implementers.
3
+
4
+ usage: python3 benchmarks/dispatch/run.py [--plum target/release/plum] [--base PATH]
5
+ [--runs 5] [--out target/dispatch] [--sizes 2,9,20]
6
+
7
+ Run from the repository root. For each size N the script writes a program with N struct
8
+ types implementing `Act[Int]` and one generic implementer `G[M]`, a Slice of 64 trait
9
+ objects that cycles through them in a scrambled order, and a loop that calls `a.val(x)` on
10
+ them 20 million times. Each compiler (`--plum`, and `--base` when given)
11
+ builds the program once; then every executable runs once per round for `--runs` rounds.
12
+ The table gives the median in-program ms and the wasm size, and fails if two builds print
13
+ different checksums.
14
+ """
15
+ import argparse
16
+ import os
17
+ import re
18
+ import statistics
19
+ import subprocess
20
+ import sys
21
+
22
+ CALLS = 20_000_000
23
+
24
+
25
+ def program(n):
26
+ out = ["import std/Int", "import std/Float", "import std/Str", "import std/Io", "import std/Slice", "import std/Option", "",
27
+ "trait Act[M] =", " fun val(self, x: Int) -> Int", " fun kind(self) -> Int = 0", ""]
28
+ for i in range(n):
29
+ out.append(f"struct S{i}(k: Int) is Act[Int] =")
30
+ out.append(f" fun val(self, x: Int) -> Int = {{x * {i + 3} + self.k}} % 1000003")
31
+ out.append("")
32
+ out.append("struct G[M](k: Int, t: M) is Act[M] =")
33
+ out.append(" fun val(self, x: Int) -> Int = {x + self.k * 5} % 1000003")
34
+ out.append("")
35
+ out.append("fun objects() -> Slice[Act[Int]] =")
36
+ out.append(" xs := Slice[Act[Int]]()")
37
+ out.append(" for i := range 64")
38
+ out.append(f" j := {{i * 37 + 11}} % {n + 1}")
39
+ for i in range(n):
40
+ out.append(f" if j == {i}")
41
+ out.append(f" xs.push(S{i}(k: i))")
42
+ out.append(f" if j == {n}")
43
+ out.append(" xs.push(G[Int](k: i, t: 1))")
44
+ out.append(" xs")
45
+ out.append("")
46
+ out.append("fun go(xs: Slice[Act[Int]], i: Int, n: Int, acc: Int) -> Int =")
47
+ out.append(" if i >= n then acc else go(xs, i + 1, n, xs.at({i * 13} % 64).val(acc))")
48
+ out.append("")
49
+ out.append("fun main(io: Io) =")
50
+ out.append(" xs := objects()")
51
+ out.append(" t0 := io.nowMicros()")
52
+ out.append(f" r := go(xs, 0, {CALLS}, 1)")
53
+ out.append(" t1 := io.nowMicros()")
54
+ out.append(" el := {t1 - t0} / 1000.0")
55
+ out.append(' io.printLn("ms {el} checksum {r}")')
56
+ return "\n".join(out) + "\n"
57
+
58
+
59
+ def main():
60
+ ap = argparse.ArgumentParser()
61
+ ap.add_argument("--plum", default="target/release/plum")
62
+ ap.add_argument("--base")
63
+ ap.add_argument("--runs", type=int, default=5)
64
+ ap.add_argument("--out", default="target/dispatch")
65
+ ap.add_argument("--sizes", default="2,9,20")
66
+ a = ap.parse_args()
67
+ out = os.path.abspath(a.out)
68
+ os.makedirs(out, exist_ok=True)
69
+ vers = [("new", os.path.abspath(a.plum))] + ([("base", os.path.abspath(a.base))] if a.base else [])
70
+ sizes = [int(s) for s in a.sizes.split(",")]
71
+ res = {}
72
+ for n in sizes:
73
+ src = f"{out}/dispatch_{n}.plum"
74
+ open(src, "w").write(program(n))
75
+ for v, plum in vers:
76
+ exe = f"{out}/dispatch_{n}.{v}"
77
+ subprocess.run([plum, "build", src, "-o", exe], check=True, capture_output=True)
78
+ subprocess.run([plum, "compile", src, "-o", exe + ".wasm"], check=True, capture_output=True)
79
+ res[(n, v)] = {"exe": exe, "size": os.path.getsize(exe + ".wasm"), "ms": [], "line": set()}
80
+ for k in range(a.runs):
81
+ for n in sizes:
82
+ for v, _ in vers[k % len(vers):] + vers[:k % len(vers)]:
83
+ r = res[(n, v)]
84
+ p = subprocess.run([r["exe"]], capture_output=True, text=True)
85
+ m = re.search(r"ms (\S+) (checksum .*)", p.stdout)
86
+ if p.returncode != 0 or not m:
87
+ sys.exit(f"dispatch_{n} {v} failed: {p.stdout[-500:]} {p.stderr[-2000:]}")
88
+ r["ms"].append(float(m.group(1)))
89
+ r["line"].add(m.group(2).strip())
90
+ print("| implementers | " + " | ".join(f"{v} ms" for v, _ in vers) + " | " + " | ".join(f"{v} wasm bytes" for v, _ in vers) + " |")
91
+ print("|---|" + "---|" * (2 * len(vers)))
92
+ for n in sizes:
93
+ lines = {tuple(sorted(res[(n, v)]["line"])) for v, _ in vers}
94
+ if len(lines) != 1 or len(next(iter(lines))) != 1:
95
+ sys.exit(f"dispatch_{n}: the builds disagree: {lines}")
96
+ ms = [f"{statistics.median(res[(n, v)]['ms']):.1f} ({min(res[(n, v)]['ms']):.1f}-{max(res[(n, v)]['ms']):.1f})" for v, _ in vers]
97
+ sz = [str(res[(n, v)]["size"]) for v, _ in vers]
98
+ print(f"| {n} (+1 generic) | " + " | ".join(ms) + " | " + " | ".join(sz) + " |")
99
+
100
+
101
+ if __name__ == "__main__":
102
+ main()
compiler/wasm-codegen/src/calls.rs CHANGED
@@ -190,7 +190,7 @@ pub(crate) fn compileFieldRead(
190
190
  compileExpr(object, body, ctx, state)?;
191
191
  Instruction::StructGet {
192
192
  struct_type_index: super_type_idx,
193
- field_index: field_idx as u32,
193
+ field_index: field_idx as u32 + ctx.gc_types.fieldBase(super_type_idx),
194
194
  }
195
195
  .encode(body);
196
196
  unboxIfValue(want, body);
@@ -218,7 +218,7 @@ pub(crate) fn compileFieldRead(
218
218
  Instruction::RefCastNonNull(HeapType::Concrete(variant_type_idx)).encode(body);
219
219
  Instruction::StructGet {
220
220
  struct_type_index: variant_type_idx,
221
- field_index: field_idx as u32,
221
+ field_index: field_idx as u32 + ctx.gc_types.fieldBase(variant_type_idx),
222
222
  }
223
223
  .encode(body);
224
224
  unboxIfValue(want, body);
compiler/wasm-codegen/src/construct.rs CHANGED
@@ -137,6 +137,7 @@ pub(crate) fn compileVariantConstruction(
137
137
  // single construction instruction — positional args already match field
138
138
  // declaration order (unlike named class-field construction), so no reordering
139
139
  // is needed here.
140
+ ctx.gc_types.emitTag(variant_type_idx, body);
140
141
  for (i, arg) in call.args.iter().enumerate() {
141
142
  let arg_expr = match arg {
142
143
  ast::Arg::Positional(e) => e,
compiler/wasm-codegen/src/driver.rs CHANGED
@@ -626,6 +626,7 @@ impl<'a> Setup<'a> {
626
626
  Instruction::RefNull(HeapType::Concrete(variant_idx)).encode(&mut init);
627
627
  let global_idx = module.addGlobal(gcRef(variant_idx), true, &init);
628
628
  singleton_globals.insert((ty.clone(), name.clone()), global_idx);
629
+ gc_types.emitTag(variant_idx, start_body);
629
630
  Instruction::StructNew(variant_idx).encode(start_body);
630
631
  Instruction::GlobalSet(global_idx).encode(start_body);
631
632
  }
compiler/wasm-codegen/src/expr.rs CHANGED
@@ -562,7 +562,7 @@ pub(crate) fn compileExpr(
562
562
  if call.reboxed.contains(&fa.name) && isValueTy(fty) && inferLocalType(&fa.value, ctx) == *fty {
563
563
  Instruction::StructGet {
564
564
  struct_type_index: variant_idx,
565
- field_index: field_idx as u32,
565
+ field_index: field_idx as u32 + ctx.gc_types.fieldBase(variant_idx),
566
566
  }
567
567
  .encode(body);
568
568
  compileExprInto(&fa.value, fty, body, ctx, state)?;
@@ -572,7 +572,7 @@ pub(crate) fn compileExpr(
572
572
  compileExprIntoHeap(&fa.value, fty, body, ctx, state)?;
573
573
  Instruction::StructSet {
574
574
  struct_type_index: variant_idx,
575
- field_index: field_idx as u32,
575
+ field_index: field_idx as u32 + ctx.gc_types.fieldBase(variant_idx),
576
576
  }
577
577
  .encode(body);
578
578
  }
@@ -611,7 +611,7 @@ pub(crate) fn compileExpr(
611
611
  }
612
612
  Instruction::StructSet {
613
613
  struct_type_index: variant_idx,
614
- field_index: field_idx as u32,
614
+ field_index: field_idx as u32 + ctx.gc_types.fieldBase(variant_idx),
615
615
  }
616
616
  .encode(body);
617
617
  }
@@ -620,6 +620,7 @@ pub(crate) fn compileExpr(
620
620
  return Ok(());
621
621
  }
622
622
  }
623
+ ctx.gc_types.emitTag(variant_idx, body);
623
624
  for (field_idx, field_name) in field_names.iter().enumerate() {
624
625
  match call.fields.iter().position(|fa| &fa.name == field_name) {
625
626
  Some(i) if hoisted.contains(&i) => {
@@ -649,7 +650,7 @@ pub(crate) fn compileExpr(
649
650
  Instruction::RefCastNonNull(HeapType::Concrete(variant_idx)).encode(body);
650
651
  Instruction::StructGet {
651
652
  struct_type_index: variant_idx,
652
- field_index: field_idx as u32,
653
+ field_index: field_idx as u32 + ctx.gc_types.fieldBase(variant_idx),
653
654
  }
654
655
  .encode(body);
655
656
  }
compiler/wasm-codegen/src/gctypes.rs CHANGED
@@ -101,6 +101,18 @@ pub struct GcTypeRegistry {
101
101
  pub leaf_array_idx: HashMap<ValType, u32>,
102
102
  /// Helper `(arr: array<i8>) -> Str` building `Str{arr}`; `None` when the program has no `Str`.
103
103
  pub mk_str_fn: Option<u32>,
104
+ /// `$Obj`, `(sub (struct (field i32)))`: the type of every trait object, and the
105
+ /// supertype of every type that implements a trait. Its one field is the value's type
106
+ /// tag, which a trait method call branches on (`br_table`, see `traits.rs`). `None`
107
+ /// when the program declares no trait.
108
+ pub obj_idx: Option<u32>,
109
+ /// Names of every declared trait (their objects are `ref null $Obj`).
110
+ pub trait_names: HashSet<String>,
111
+ /// Each type that implements a trait (canonical `TNamed` / `TApp` instance) -> its tag.
112
+ pub tags: HashMap<PlumType, i32>,
113
+ /// Struct type index of a tagged type (its supertype and each variant) -> its tag: these
114
+ /// structs start with the tag field, so their own fields start at index 1.
115
+ pub tagged: HashMap<u32, i32>,
104
116
  }
105
117
 
106
118
  impl GcTypeRegistry {
@@ -124,6 +136,28 @@ impl GcTypeRegistry {
124
136
  _ => None,
125
137
  }
126
138
  }
139
+ /// Index of a struct type's first own field: 1 when it starts with the type tag.
140
+ pub fn fieldBase(&self, struct_idx: u32) -> u32 {
141
+ u32::from(self.tagged.contains_key(&struct_idx))
142
+ }
143
+ /// The type tag of `ty`, if it implements a trait.
144
+ pub fn tagOf(&self, ty: &PlumType) -> Option<i32> {
145
+ self.tags.get(&canonTy(ty)).copied()
146
+ }
147
+ /// Pushes the type tag a new struct of type `struct_idx` starts with, if it has one
148
+ /// (before its fields, for `struct.new`).
149
+ pub fn emitTag(&self, struct_idx: u32, body: &mut Vec<u8>) {
150
+ if let Some(t) = self.tagged.get(&struct_idx) {
151
+ Instruction::I32Const(*t).encode(body);
152
+ }
153
+ }
154
+ /// Whether `ty` is a trait object (`Shape`, `Actor[Msg]`).
155
+ pub fn isTraitObject(&self, ty: &PlumType) -> bool {
156
+ match ty {
157
+ PlumType::TNamed(n) | PlumType::TApp(n, _) => self.trait_names.contains(n),
158
+ _ => false,
159
+ }
160
+ }
127
161
  /// Struct index of variant `vname` of enum type `ty`.
128
162
  pub fn variantIdx(&self, ty: &PlumType, vname: &str) -> Option<u32> {
129
163
  match ty {
@@ -151,6 +185,9 @@ pub(crate) fn isArraySpecialization(name: &str) -> bool {
151
185
  /// other class's index to already be assigned (see `buildGcTypeRegistry`'s two-pass
152
186
  /// structure: this function is only ever called during its second pass).
153
187
  pub(crate) fn plumTypeToGcValtype(t: &PlumType, registry: &GcTypeRegistry) -> ValType {
188
+ if let Some(obj) = registry.obj_idx.filter(|_| registry.isTraitObject(t)) {
189
+ return gcRef(obj);
190
+ }
154
191
  match t {
155
192
  PlumType::TApp(n, _) => match registry.classIdx(t).or_else(|| registry.superIdx(t)) {
156
193
  Some(idx) => gcRef(idx),
@@ -217,6 +254,7 @@ pub(crate) fn buildGcTypeRegistry(
217
254
  ) -> GcTypeRegistry {
218
255
  enum Slot {
219
256
  Str,
257
+ Obj,
220
258
  EnumSuper(PlumType),
221
259
  Variant(PlumType, String),
222
260
  ArrayRef(ValType),
@@ -237,7 +275,20 @@ pub(crate) fn buildGcTypeRegistry(
237
275
  array_type_idx: 0,
238
276
  leaf_array_idx: HashMap::new(),
239
277
  mk_str_fn: None,
278
+ obj_idx: None,
279
+ trait_names: HashSet::new(),
280
+ tags: HashMap::new(),
281
+ tagged: HashMap::new(),
240
282
  };
283
+ for item in &source.items {
284
+ if let ast::Item::Trait(t) = item {
285
+ reg.trait_names.insert(t.name.clone());
286
+ }
287
+ }
288
+ if !reg.trait_names.is_empty() {
289
+ reg.obj_idx = Some(slots.len() as u32);
290
+ slots.push(Slot::Obj);
291
+ }
241
292
  let mut enum_decls: HashMap<String, &ast::Enum> = HashMap::new();
242
293
  let mut instances: Vec<PlumType> = Vec::new();
243
294
  for item in &source.items {
@@ -267,10 +318,33 @@ pub(crate) fn buildGcTypeRegistry(
267
318
  2
268
319
  }
269
320
  });
321
+ // Tags: the types that implement a trait, ordered by the sorted names of their traits
322
+ // (supertraits included), so that a trait's implementers get nearby tags (a small
323
+ // `br_table`): `Actor` < `Actor,Screen` < `Reducer`.
324
+ if reg.obj_idx.is_some() {
325
+ let mut impls: Vec<(String, &PlumType)> = instances
326
+ .iter()
327
+ .filter_map(|ty| {
328
+ let e = enum_decls[plum_checker::nominalName(ty).unwrap()];
329
+ let mut names: Vec<&str> = e.implements.iter().map(|t| t.name.as_str()).collect();
330
+ names.sort();
331
+ names.dedup();
332
+ (!names.is_empty()).then(|| (names.join(","), ty))
333
+ })
334
+ .collect();
335
+ impls.sort_by(|a, b| a.0.cmp(&b.0));
336
+ for (i, (_, ty)) in impls.into_iter().enumerate() {
337
+ reg.tags.insert(ty.clone(), i as i32);
338
+ }
339
+ }
270
340
  for ty in &instances {
271
341
  let n = plum_checker::nominalName(ty).unwrap().to_string();
272
342
  let e = enum_decls[&n];
273
343
  let super_idx = slots.len() as u32;
344
+ let tag = reg.tags.get(ty).copied();
345
+ if let Some(t) = tag {
346
+ reg.tagged.insert(super_idx, t);
347
+ }
274
348
  slots.push(Slot::EnumSuper(ty.clone()));
275
349
  match ty {
276
350
  PlumType::TNamed(_) => {
@@ -283,6 +357,9 @@ pub(crate) fn buildGcTypeRegistry(
283
357
  for v in &e.variants {
284
358
  let idx = slots.len() as u32;
285
359
  slots.push(Slot::Variant(ty.clone(), v.name.clone()));
360
+ if let Some(t) = tag {
361
+ reg.tagged.insert(idx, t);
362
+ }
286
363
  match ty {
287
364
  PlumType::TNamed(_) => {
288
365
  reg.variant_type_idx.insert(v.name.clone(), idx);
@@ -381,11 +458,23 @@ pub(crate) fn buildGcTypeRegistry(
381
458
  shared: false,
382
459
  },
383
460
  },
461
+ Slot::Obj => SubType {
462
+ is_final: false,
463
+ supertype_idx: None,
464
+ composite_type: CompositeType {
465
+ inner: CompositeInnerType::Struct(StructType { fields: vec![tagField()].into() }),
466
+ shared: false,
467
+ },
468
+ },
384
469
  Slot::EnumSuper(ty) => {
385
470
  let n = plum_checker::nominalName(ty).unwrap();
386
471
  let s = subst_for(ty);
387
472
  let params = enum_params.get(n).cloned().unwrap_or_default();
473
+ let tagged = reg.tags.contains_key(ty);
388
474
  let mut field_types: Vec<FieldType> = Vec::new();
475
+ if tagged {
476
+ field_types.push(tagField());
477
+ }
389
478
  field_types.extend(params.iter().map(|(_, fty)| FieldType {
390
479
  element_type: StorageType::Val(plumTypeToGcValtype(
391
480
  &plum_checker::types::substitute(fty, &s),
@@ -395,7 +484,7 @@ pub(crate) fn buildGcTypeRegistry(
395
484
  }));
396
485
  SubType {
397
486
  is_final: false,
398
- supertype_idx: None,
487
+ supertype_idx: if tagged { reg.obj_idx } else { None },
399
488
  composite_type: CompositeType {
400
489
  inner: CompositeInnerType::Struct(StructType {
401
490
  fields: field_types.into(),
@@ -413,6 +502,9 @@ pub(crate) fn buildGcTypeRegistry(
413
502
  });
414
503
  let super_idx = reg.superIdx(ty).expect("enum supertype slot");
415
504
  let mut field_types: Vec<FieldType> = Vec::new();
505
+ if reg.tags.contains_key(ty) {
506
+ field_types.push(tagField());
507
+ }
416
508
  if let Some(leaves) = valueFieldsOf(ty).map(|_| flatValtypes(ty, &reg)) {
417
509
  // A value enum's box holds its flattened leaves directly.
418
510
  field_types.extend(leaves.into_iter().map(|vt| FieldType {
@@ -472,6 +564,11 @@ pub(crate) fn buildGcTypeRegistry(
472
564
  reg
473
565
  }
474
566
 
567
+ /// The type tag field: an immutable `i32`, first in `$Obj` and every tagged struct.
568
+ fn tagField() -> FieldType {
569
+ FieldType { element_type: StorageType::Val(ValType::I32), mutable: false }
570
+ }
571
+
475
572
  pub(crate) fn blockTypeFor(result_vt: Option<ValType>) -> BlockType {
476
573
  // A value enum's block result is its flat leaves; its box reference type stands in
477
574
  // for it as the `result_vt` marker (see `GenState::value_block_types`).
compiler/wasm-codegen/src/matching.rs CHANGED
@@ -380,7 +380,7 @@ pub(crate) fn compileCasePositions(
380
380
  }
381
381
  AsTarget::Never => compileMatchArmsMulti(rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state),
382
382
  AsTarget::Test(tags, cast, t) => {
383
- AsTarget::emitTest(&tags, body, &mut |b| Instruction::LocalGet(scratch_local).encode(b));
383
+ AsTarget::emitTest(&tags, ctx.gc_types, body, &mut |b| Instruction::LocalGet(scratch_local).encode(b));
384
384
  Instruction::If(blockTypeFor(result_vt)).encode(body);
385
385
  let _tg = TailDepth::enter(&ctx.tail_depth);
386
386
  bind(cast, &t, body)?;
@@ -742,7 +742,7 @@ pub(crate) fn compileVariantConstructorArm(
742
742
  /// Pushes field `fpos` of the pattern container in `container_local`.
743
743
  pub(crate) fn emitContainerField(
744
744
  body: &mut Vec<u8>,
745
- _ctx: &LocalCtx,
745
+ ctx: &LocalCtx,
746
746
  container_local: u32,
747
747
  container_type_idx: u32,
748
748
  fpos: usize,
@@ -751,7 +751,7 @@ pub(crate) fn emitContainerField(
751
751
  Instruction::LocalGet(container_local).encode(body);
752
752
  Instruction::StructGet {
753
753
  struct_type_index: container_type_idx,
754
- field_index: leaf_map.map(|m| m[fpos]).unwrap_or(fpos as u32),
754
+ field_index: leaf_map.map(|m| m[fpos]).unwrap_or(fpos as u32 + ctx.gc_types.fieldBase(container_type_idx)),
755
755
  }
756
756
  .encode(body);
757
757
  }
@@ -817,7 +817,7 @@ pub(crate) fn compileFieldPatterns(
817
817
  }
818
818
  AsTarget::Never => compileMatchArmsMulti(rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state),
819
819
  AsTarget::Test(tags, cast, t) => {
820
- AsTarget::emitTest(&tags, body, &mut |b| emitContainerField(b, ctx, container_local, container_type_idx, fpos, leaf_map));
820
+ AsTarget::emitTest(&tags, ctx.gc_types, body, &mut |b| emitContainerField(b, ctx, container_local, container_type_idx, fpos, leaf_map));
821
821
  Instruction::If(blockTypeFor(result_vt)).encode(body);
822
822
  let _tg = TailDepth::enter(&ctx.tail_depth);
823
823
  load(cast, &t, body)?;
@@ -1320,9 +1320,10 @@ pub(crate) fn compileEnumUnwrap(
1320
1320
  .gc_types
1321
1321
  .variantIdx(rt, "Err")
1322
1322
  .ok_or_else(|| format!("codegen: `?` in a function returning {}", rt))?;
1323
+ ctx.gc_types.emitTag(out_idx, body);
1323
1324
  Instruction::LocalGet(scratch).encode(body);
1324
1325
  Instruction::RefCastNonNull(HeapType::Concrete(err_idx)).encode(body);
1325
- Instruction::StructGet { struct_type_index: err_idx, field_index: 0 }.encode(body);
1326
+ Instruction::StructGet { struct_type_index: err_idx, field_index: ctx.gc_types.fieldBase(err_idx) }.encode(body);
1326
1327
  Instruction::StructNew(out_idx).encode(body);
1327
1328
  }
1328
1329
  Instruction::Return.encode(body);
@@ -1357,7 +1358,7 @@ pub(crate) fn compileEnumUnwrap(
1357
1358
  for (v, vidx) in &err_variants {
1358
1359
  Instruction::LocalGet(scratch).encode(body);
1359
1360
  Instruction::RefCastNonNull(HeapType::Concrete(err_idx)).encode(body);
1360
- Instruction::StructGet { struct_type_index: err_idx, field_index: 0 }.encode(body);
1361
+ Instruction::StructGet { struct_type_index: err_idx, field_index: ctx.gc_types.fieldBase(err_idx) }.encode(body);
1361
1362
  Instruction::RefTestNonNull(HeapType::Concrete(*vidx)).encode(body);
1362
1363
  Instruction::If(BlockType::Empty).encode(body);
1363
1364
  compileStaticString(&format!("unwrap on Err({}){}", v, at), body, state);
@@ -1374,7 +1375,7 @@ pub(crate) fn compileEnumUnwrap(
1374
1375
  Instruction::End.encode(body);
1375
1376
  Instruction::LocalGet(scratch).encode(body);
1376
1377
  Instruction::RefCastNonNull(HeapType::Concrete(good_idx)).encode(body);
1377
- Instruction::StructGet { struct_type_index: good_idx, field_index: 0 }.encode(body);
1378
+ Instruction::StructGet { struct_type_index: good_idx, field_index: ctx.gc_types.fieldBase(good_idx) }.encode(body);
1378
1379
  let success = targs[0].clone();
1379
1380
  if matches!(success, PlumType::TUnit) {
1380
1381
  Instruction::Drop.encode(body);
compiler/wasm-codegen/src/stmts.rs CHANGED
@@ -295,7 +295,7 @@ pub(crate) fn compileFieldStore(
295
295
  boxIfValue(&src.ty, body);
296
296
  Instruction::StructSet {
297
297
  struct_type_index: super_type_idx,
298
- field_index: field_idx as u32,
298
+ field_index: field_idx as u32 + ctx.gc_types.fieldBase(super_type_idx),
299
299
  }
300
300
  .encode(body);
301
301
  }
@@ -333,7 +333,7 @@ pub(crate) fn compileFieldStore(
333
333
  boxIfValue(&src.ty, body);
334
334
  Instruction::StructSet {
335
335
  struct_type_index: variant_type_idx,
336
- field_index: field_idx as u32,
336
+ field_index: field_idx as u32 + ctx.gc_types.fieldBase(variant_type_idx),
337
337
  }
338
338
  .encode(body);
339
339
  }
compiler/wasm-codegen/src/traits.rs CHANGED
@@ -1,12 +1,15 @@
1
1
  //! Trait objects.
2
2
  //!
3
- //! A trait object (`Actor`, `Actor[Msg]`) is an `anyref` to the value itself: every type
3
+ //! A trait object (`Actor`, `Actor[Msg]`) is a `ref null $Obj` to the value itself: every
4
- //! that implements a trait is a heap struct (see `plum_core::layout`), so an implementer
4
+ //! type that implements a trait is a heap struct (see `plum_core::layout`) whose wasm-gc
5
+ //! type is a subtype of `$Obj`, so an implementer becomes a trait object with no
5
- //! becomes a trait object with no instruction, and the value's wasm-gc type is its tag.
6
+ //! instruction. `$Obj`'s one field, first in every implementer, is the type's tag (see
6
- //! A method call on a trait object calls the trait's dispatcher, one wasm function per
7
+ //! `buildGcTypeRegistry`). A method call on a trait object calls the trait's dispatcher, one
7
- //! (trait object type, method): a `ref.test` per type that implements the trait in the
8
+ //! wasm function per (trait object type, method): a `br_table` on the tag over the types
8
- //! program (whole-program, the same code a `match` makes), each arm a `return_call` of that
9
+ //! that implement the trait in the program (whole-program), each arm a `return_call` of that
9
- //! type's own method (or its copy of the default, see `plum_core::trait_defaults`).
10
+ //! type's own method (or its copy of the default, see `plum_core::trait_defaults`). The
11
+ //! call costs the same for 2 implementers or 20; a chain of `ref.test`s grew with each one.
12
+ //! A downcast compares tags too.
10
13
 
11
14
  use crate::*;
12
15
  use plum_checker::traits::Traits;
@@ -38,8 +41,8 @@ pub(crate) fn implementersOf(obj: &PlumType, reg: &GcTypeRegistry, traits: &Trai
38
41
  .collect()
39
42
  }
40
43
 
41
- /// The heap type a value of the implementer `c` has (its tag): a struct's one variant, or an
44
+ /// The heap type a value of the implementer `c` has: a struct's one variant, or an enum's
42
- /// enum's supertype.
45
+ /// supertype.
43
46
  pub(crate) fn tagIdx(c: &PlumType, reg: &GcTypeRegistry) -> Option<u32> {
44
47
  reg.classIdx(c).or_else(|| reg.superIdx(c))
45
48
  }
@@ -118,7 +121,52 @@ fn implementerMethod(
118
121
  }
119
122
  }
120
123
 
124
+ /// A trait object's wasm type, `ref null $Obj`.
125
+ fn objRef(reg: &GcTypeRegistry) -> ValType {
126
+ gcRef(reg.obj_idx.expect("a program with a trait object has $Obj"))
127
+ }
128
+
129
+ /// Pushes the type tag of the trait object in local `l`.
130
+ fn emitTagOf(l: u32, reg: &GcTypeRegistry, body: &mut Vec<u8>) {
131
+ Instruction::LocalGet(l).encode(body);
132
+ Instruction::StructGet { struct_type_index: reg.obj_idx.expect("$Obj"), field_index: 0 }.encode(body);
133
+ }
134
+
135
+ /// Branches on the type tag of the trait object in `local` to one of `arms` (its tags, its code): a
136
+ /// `br_table` over the tags' range. Each arm's code must leave the function
137
+ /// (`return_call`, `return`); any other tag traps.
138
+ fn emitTagSwitch(local: u32, reg: &GcTypeRegistry, arms: &[(Vec<i32>, Vec<u8>)], body: &mut Vec<u8>) {
139
+ let tags = || arms.iter().flat_map(|a| a.0.iter().copied());
140
+ if arms.is_empty() || tags().next().is_none() {
141
+ Instruction::Unreachable.encode(body);
142
+ return;
143
+ }
144
+ let lo = tags().min().unwrap();
145
+ let hi = tags().max().unwrap();
146
+ let n = arms.len() as u32;
147
+ // block $miss { block $arm[n-1] { .. block $arm[0] { br_table } arm[0] code } .. }
148
+ Instruction::Block(BlockType::Empty).encode(body);
149
+ for _ in 0..n {
150
+ Instruction::Block(BlockType::Empty).encode(body);
151
+ }
152
+ emitTagOf(local, reg, body);
153
+ if lo != 0 {
154
+ Instruction::I32Const(lo).encode(body);
155
+ Instruction::I32Sub.encode(body);
156
+ }
157
+ let table: Vec<u32> = (lo..=hi)
158
+ .map(|t| arms.iter().position(|a| a.0.contains(&t)).map(|i| i as u32).unwrap_or(n))
159
+ .collect();
160
+ Instruction::BrTable(table.into(), n).encode(body);
161
+ for (_, code) in arms {
162
+ Instruction::End.encode(body);
163
+ body.extend_from_slice(code);
164
+ }
165
+ Instruction::End.encode(body);
166
+ Instruction::Unreachable.encode(body);
167
+ }
168
+
121
- /// The signature of the dispatcher of `obj.method`: `self` as `anyref`, then the trait's
169
+ /// The signature of the dispatcher of `obj.method`: `self` as the trait object, then the trait's
122
170
  /// parameters with `Self` as the trait object.
123
171
  fn dispatcherSig(obj: &PlumType, method: &str, traits: &Traits, reg: &GcTypeRegistry) -> Result<FuncSig, String> {
124
172
  let sig = traits
@@ -127,7 +175,7 @@ fn dispatcherSig(obj: &PlumType, method: &str, traits: &Traits, reg: &GcTypeRegi
127
175
  let PlumType::TFun(params, ret) = sig else {
128
176
  return Err(format!("codegen: {obj}.{method} is not a method"));
129
177
  };
130
- let mut vts = vec![ValType::Ref(RefType::ANYREF)];
178
+ let mut vts = vec![objRef(reg)];
131
179
  for p in &params {
132
180
  leafTypes(p, reg, &mut vts);
133
181
  }
@@ -183,7 +231,7 @@ impl<'a> Setup<'a> {
183
231
  .and_then(|t| t.method(&method))
184
232
  .is_some_and(|m| m.dyn_copy);
185
233
  let target = if dyn_copy { plum_core::trait_defaults::dynName(&method) } else { method.clone() };
186
- let mut b: Vec<u8> = vec![0u8];
234
+ let mut arms: Vec<(Vec<i32>, Vec<u8>)> = Vec::new();
187
235
  for c in implementersOf(&obj, &reg, &traits) {
188
236
  let (Some(tag), Some((f, csig))) = (
189
237
  tagIdx(&c, &reg),
@@ -198,9 +246,11 @@ impl<'a> Setup<'a> {
198
246
  ));
199
247
  continue;
200
248
  }
201
- Instruction::LocalGet(0).encode(&mut b);
249
+ let Some(t) = reg.tagOf(&c) else {
202
- Instruction::RefTestNonNull(HeapType::Concrete(tag)).encode(&mut b);
250
+ self.dispatch_errors.push(format!("internal codegen error: {c} implements {obj} but has no type tag"));
251
+ continue;
252
+ };
203
- Instruction::If(BlockType::Empty).encode(&mut b);
253
+ let mut b: Vec<u8> = Vec::new();
204
254
  Instruction::LocalGet(0).encode(&mut b);
205
255
  Instruction::RefCastNonNull(HeapType::Concrete(tag)).encode(&mut b);
206
256
  let mut ok = true;
@@ -220,9 +270,10 @@ impl<'a> Setup<'a> {
220
270
  self.dispatch_errors.push(format!("codegen: {c}.{method}: its parameters don't fit {obj}'s"));
221
271
  }
222
272
  Instruction::ReturnCall(f).encode(&mut b);
223
- Instruction::End.encode(&mut b);
273
+ arms.push((vec![t], b));
224
274
  }
275
+ let mut b: Vec<u8> = vec![0u8];
225
- Instruction::Unreachable.encode(&mut b);
276
+ emitTagSwitch(0, &reg, &arms, &mut b);
226
277
  Instruction::End.encode(&mut b);
227
278
  let t = self.module.addType(&sig.params, &sig.ret);
228
279
  let idx = self.module.addFunction(t, &b);
@@ -230,40 +281,52 @@ impl<'a> Setup<'a> {
230
281
  withGen(|s| s.dispatchers.insert((obj.clone(), method.clone()), (idx, sig)));
231
282
  }
232
283
  for obj in eqs {
233
- let with_eq: Vec<(PlumType, u32, u32)> = implementersOf(&obj, &reg, &traits)
284
+ let with_eq: Vec<(i32, u32, u32)> = implementersOf(&obj, &reg, &traits)
234
285
  .into_iter()
235
286
  .filter_map(|c| {
236
287
  let (f, _) = implementerMethod(&c, "eq", &self.func_ids, &self.func_sigs, &self.inst_funcs, &self.inst_index)?;
237
- Some((c.clone(), tagIdx(&c, &reg)?, f))
288
+ Some((reg.tagOf(&c)?, tagIdx(&c, &reg)?, f))
238
289
  })
239
290
  .collect();
240
291
  if with_eq.is_empty() {
241
292
  continue;
242
293
  }
243
- // (a: anyref, b: anyref) -> i32: same type and that type's `eq`, else identity.
294
+ // (a: $Obj, b: $Obj) -> i32: same type and that type's `eq`, else identity.
244
295
  let mut b: Vec<u8> = vec![0u8];
245
- for (_, tag, f) in &with_eq {
296
+ // Different tags: different types, never equal.
246
- for l in 0..2 {
247
- Instruction::LocalGet(l).encode(&mut b);
297
+ emitTagOf(0, &reg, &mut b);
248
- Instruction::RefTestNonNull(HeapType::Concrete(*tag)).encode(&mut b);
298
+ emitTagOf(1, &reg, &mut b);
249
- }
250
- Instruction::I32And.encode(&mut b);
299
+ Instruction::I32Ne.encode(&mut b);
251
- Instruction::If(BlockType::Empty).encode(&mut b);
300
+ Instruction::If(BlockType::Empty).encode(&mut b);
301
+ Instruction::I32Const(0).encode(&mut b);
302
+ Instruction::Return.encode(&mut b);
303
+ Instruction::End.encode(&mut b);
304
+ let mut arms: Vec<(Vec<i32>, Vec<u8>)> = Vec::new();
305
+ for (t, idx, f) in &with_eq {
306
+ let mut a = Vec::new();
252
307
  for l in 0..2 {
253
- Instruction::LocalGet(l).encode(&mut b);
308
+ Instruction::LocalGet(l).encode(&mut a);
254
- Instruction::RefCastNonNull(HeapType::Concrete(*tag)).encode(&mut b);
309
+ Instruction::RefCastNonNull(HeapType::Concrete(*idx)).encode(&mut a);
255
310
  }
256
- Instruction::ReturnCall(*f).encode(&mut b);
311
+ Instruction::ReturnCall(*f).encode(&mut a);
257
- Instruction::End.encode(&mut b);
312
+ arms.push((vec![*t], a));
258
- }
259
- for l in 0..2 {
260
- Instruction::LocalGet(l).encode(&mut b);
261
- Instruction::RefCastNullable(RefType::EQREF.heap_type).encode(&mut b);
262
313
  }
314
+ // A type without an `eq`: identity.
315
+ let mut ident = Vec::new();
316
+ Instruction::LocalGet(0).encode(&mut ident);
317
+ Instruction::LocalGet(1).encode(&mut ident);
263
- Instruction::RefEq.encode(&mut b);
318
+ Instruction::RefEq.encode(&mut ident);
319
+ Instruction::Return.encode(&mut ident);
320
+ let rest: Vec<i32> = implementersOf(&obj, &reg, &traits)
321
+ .iter()
322
+ .filter_map(|c| reg.tagOf(c))
323
+ .filter(|t| !with_eq.iter().any(|w| w.0 == *t))
324
+ .collect();
325
+ arms.push((rest, ident));
326
+ emitTagSwitch(0, &reg, &arms, &mut b);
264
327
  Instruction::End.encode(&mut b);
265
- let any = ValType::Ref(RefType::ANYREF);
328
+ let o = objRef(&reg);
266
- let t = self.module.addType(&[any, any], &[ValType::I32]);
329
+ let t = self.module.addType(&[o, o], &[ValType::I32]);
267
330
  let idx = self.module.addFunction(t, &b);
268
331
  self.module.nameFunction(idx, &format!("eq.{obj}"));
269
332
  withGen(|s| s.trait_eq.insert(obj.clone(), idx));
@@ -271,9 +334,11 @@ impl<'a> Setup<'a> {
271
334
  }
272
335
  }
273
336
 
274
- /// `sub` is a concrete reference type and `sup` is `anyref`: a result that fits by subtyping.
337
+ /// `sub` is a concrete reference type and `sup` is `anyref` or a trait object (`$Obj`): a
338
+ /// result that fits by subtyping.
275
339
  fn isRefTo(sup: ValType, sub: ValType) -> bool {
340
+ let obj = withGen(|s| s.gc_types.as_ref().and_then(|r| r.obj_idx));
276
- sup == ValType::Ref(RefType::ANYREF) && matches!(sub, ValType::Ref(_))
341
+ (sup == ValType::Ref(RefType::ANYREF) || obj.is_some_and(|o| sup == gcRef(o))) && matches!(sub, ValType::Ref(_))
277
342
  }
278
343
 
279
344
  /// `left == right` (or `!=`) with a trait object on the left: the same type and equal values
@@ -312,17 +377,35 @@ pub(crate) enum AsTarget {
312
377
  Always(PlumType),
313
378
  /// No value of the subject's type is ever of this type.
314
379
  Never,
315
- /// A `ref.test` against each of the tags (any one matches), then the bound value cast
380
+ /// A compare of the subject's type tag with each of the tags (any one matches), then
316
- /// to the type (`Some`), or kept as an `anyref` (a trait object: `None`).
381
+ /// the bound value cast to the type (`Some`), or kept as a trait object (`None`).
317
- Test(Vec<u32>, Option<u32>, PlumType),
382
+ Test(Vec<i32>, Option<u32>, PlumType),
318
383
  }
319
384
 
320
385
  impl AsTarget {
321
- /// Leaves 1 on the stack if the value `load` pushes is one of `tags`, else 0.
386
+ /// Leaves 1 on the stack if the trait object `load` pushes has one of `tags`, else 0:
387
+ /// a compare per tag, or for more than two tags under 64, a bit of a mask.
322
- pub(crate) fn emitTest(tags: &[u32], body: &mut Vec<u8>, load: &mut dyn FnMut(&mut Vec<u8>)) {
388
+ pub(crate) fn emitTest(tags: &[i32], reg: &GcTypeRegistry, body: &mut Vec<u8>, load: &mut dyn FnMut(&mut Vec<u8>)) {
389
+ let obj = reg.obj_idx.expect("a downcast's subject is a trait object");
323
- for (i, tag) in tags.iter().enumerate() {
390
+ let tag = |body: &mut Vec<u8>, load: &mut dyn FnMut(&mut Vec<u8>)| {
324
391
  load(body);
392
+ Instruction::StructGet { struct_type_index: obj, field_index: 0 }.encode(body);
393
+ };
394
+ if tags.len() > 2 && tags.iter().all(|t| (0..64).contains(t)) {
395
+ let mask = tags.iter().fold(0u64, |m, t| m | (1u64 << t));
396
+ Instruction::I64Const(mask as i64).encode(body);
397
+ tag(body, load);
398
+ Instruction::I64ExtendI32U.encode(body);
399
+ Instruction::I64ShrU.encode(body);
400
+ Instruction::I32WrapI64.encode(body);
401
+ Instruction::I32Const(1).encode(body);
402
+ Instruction::I32And.encode(body);
403
+ return;
404
+ }
405
+ for (i, t) in tags.iter().enumerate() {
406
+ tag(body, load);
325
- Instruction::RefTestNonNull(HeapType::Concrete(*tag)).encode(body);
407
+ Instruction::I32Const(*t).encode(body);
408
+ Instruction::I32Eq.encode(body);
326
409
  if i > 0 {
327
410
  Instruction::I32Or.encode(body);
328
411
  }
@@ -371,15 +454,15 @@ pub(crate) fn asTarget(ty: &str, args: &[ast::Type], subject: &PlumType, subst:
371
454
  if traits.supertraitsOf(subject).iter().any(|s| canonTy(s) == canonTy(&target)) {
372
455
  return AsTarget::Always(target);
373
456
  }
374
- let tags: Vec<u32> = implementersOf(&target, reg, &traits)
457
+ let tags: Vec<i32> = implementersOf(&target, reg, &traits)
375
458
  .iter()
376
459
  .filter(|c| implementersOf(subject, reg, &traits).contains(c))
377
- .filter_map(|c| tagIdx(c, reg))
460
+ .filter_map(|c| reg.tagOf(c))
378
461
  .collect();
379
462
  return if tags.is_empty() { AsTarget::Never } else { AsTarget::Test(tags, None, target) };
380
463
  }
381
- match tagIdx(&target, reg) {
464
+ match (tagIdx(&target, reg), reg.tagOf(&target)) {
382
- Some(idx) => AsTarget::Test(vec![idx], Some(idx), target),
465
+ (Some(idx), Some(t)) => AsTarget::Test(vec![t], Some(idx), target),
383
- None => AsTarget::Never,
466
+ _ => AsTarget::Never,
384
467
  }
385
468
  }
compiler/wasm-codegen/tests/wasm_codegen/dispatch_test.rs ADDED
@@ -0,0 +1,253 @@
1
+ #![allow(non_snake_case)]
2
+ //! Trait dispatch on the type tag: every type that implements a trait is a subtype of
3
+ //! `$Obj` and starts with an `i32` tag, a trait method call is one `br_table` on it, and a
4
+ //! downcast compares tags. These check the code shape (no `ref.test` chain) and run it.
5
+ use std::collections::HashMap;
6
+
7
+ /// Per compiled function (by debug name): its operators' names.
8
+ fn operators(wasm: &[u8]) -> HashMap<String, Vec<String>> {
9
+ let mut names: HashMap<u32, String> = HashMap::new();
10
+ let mut imports = 0u32;
11
+ for p in wasmparser::Parser::new(0).parse_all(wasm) {
12
+ match p.unwrap() {
13
+ wasmparser::Payload::ImportSection(r) => {
14
+ imports = r.into_iter().filter(|i| matches!(i.as_ref().unwrap().ty, wasmparser::TypeRef::Func(_))).count() as u32
15
+ }
16
+ wasmparser::Payload::CustomSection(c) => {
17
+ if let wasmparser::KnownCustom::Name(r) = c.as_known() {
18
+ for n in r.flatten() {
19
+ if let wasmparser::Name::Function(m) = n {
20
+ for e in m.into_iter().flatten() {
21
+ names.insert(e.index, e.name.to_string());
22
+ }
23
+ }
24
+ }
25
+ }
26
+ }
27
+ _ => {}
28
+ }
29
+ }
30
+ let mut out = HashMap::new();
31
+ let mut idx = imports;
32
+ for p in wasmparser::Parser::new(0).parse_all(wasm) {
33
+ if let wasmparser::Payload::CodeSectionEntry(b) = p.unwrap() {
34
+ let mut ops = Vec::new();
35
+ let mut r = b.get_operators_reader().unwrap();
36
+ while !r.eof() {
37
+ let op = format!("{:?}", r.read().unwrap());
38
+ ops.push(op.split([' ', '{', '(']).next().unwrap_or_default().to_string());
39
+ }
40
+ out.insert(names.get(&idx).cloned().unwrap_or_else(|| format!("f{idx}")), ops);
41
+ idx += 1;
42
+ }
43
+ }
44
+ out
45
+ }
46
+
47
+ fn count(ops: &[String], name: &str) -> usize {
48
+ ops.iter().filter(|o| *o == name).count()
49
+ }
50
+
51
+ fn compile(name: &str, src: &str, fbip: bool) -> Vec<u8> {
52
+ let source = plum_test_support::load(name, src).unwrap_or_else(|e| panic!("load: {e}"));
53
+ let opts = plum_wasm_codegen::CompileOptions {
54
+ passes: plum_driver::PassOptions { fbip, explain: false, ..plum_driver::PassOptions::default() },
55
+ ..Default::default()
56
+ };
57
+ let bytes = plum_wasm_codegen::compile(&source, &opts)
58
+ .map(|o| o.wasm)
59
+ .unwrap_or_else(|e| panic!("compile failed: {}", e.iter().map(|d| d.to_string()).collect::<Vec<_>>().join("\n")));
60
+ wasmparser::validate(&bytes).expect("valid wasm");
61
+ bytes
62
+ }
63
+
64
+ fn runInt(wasm: &[u8]) -> i64 {
65
+ let engine = plum_test_support::engine();
66
+ let module = wasmtime::Module::new(&engine, wasm).unwrap();
67
+ let mut store = wasmtime::Store::new(&engine, ());
68
+ let mut linker = wasmtime::Linker::new(&engine);
69
+ linker.define_unknown_imports_as_default_values(&mut store, &module).unwrap();
70
+ let instance = linker.instantiate(&mut store, &module).unwrap();
71
+ let main = instance.get_typed_func::<(), i64>(&mut store, "main").unwrap();
72
+ main.call(&mut store, ()).unwrap()
73
+ }
74
+
75
+ const PRE: &str = "import std/Str\nimport std/Int\nimport std/List\nimport std/Slice\nimport std/Option\n\n";
76
+
77
+ /// A trait with `n` struct implementers `S0..`, each `val` adding `i + 1`, and a generic one.
78
+ fn many(n: usize) -> String {
79
+ let mut s = String::from("trait Act[M] =\n fun val(self, x: Int) -> Int\n fun twice(self, x: Int) -> Int = self.val(self.val(x))\n\n");
80
+ for i in 0..n {
81
+ s += &format!("struct S{i}(k: Int) is Act[Int] =\n fun val(self, x: Int) -> Int = x + {} + self.k\n\n", i + 1);
82
+ }
83
+ s += "struct G[M](k: Int, m: M) is Act[M] =\n fun val(self, x: Int) -> Int = x * 2 + self.k\n\n";
84
+ s += "fun objects() -> Slice[Act[Int]] =\n xs := Slice[Act[Int]]()\n";
85
+ for i in 0..n {
86
+ s += &format!(" xs.push(S{i}(k: 0))\n");
87
+ }
88
+ s += " xs.push(G[Int](k: 1, m: 5))\n xs\n\n";
89
+ s += "fun foldA(xs: Slice[Act[Int]], i: Int, acc: Int) -> Int = if i >= xs.length() then acc else foldA(xs, i + 1, acc * 3 % 1000003 + xs.at(i).val(acc))\n\n";
90
+ s += "fun foldB(xs: Slice[Act[Int]], i: Int, acc: Int) -> Int = if i >= xs.length() then acc else foldB(xs, i + 1, acc + xs.at(i).twice(1))\n\n";
91
+ s += "fun foldC(xs: Slice[Act[Int]], i: Int, acc: Int) -> Int = if i >= xs.length() then acc else foldC(xs, i + 1, acc + xs.at(i).val(10))\n\n";
92
+ s
93
+ }
94
+
95
+ /// The dispatcher of a trait with 20 implementers (one generic) is one `br_table`, no
96
+ /// `ref.test`; every implementer's method is reached, and a default too.
97
+ #[test]
98
+ fn dispatch_over_many_implementers_is_one_br_table() {
99
+ let body = "fun main() -> Int =
100
+ xs := objects()
101
+ foldA(xs, 0, 0) * 1000000 + foldB(xs, 0, 0)
102
+ ";
103
+ let wasm = compile("dispatch_many", &format!("{PRE}{}{body}", many(19)), true);
104
+ let ops = operators(&wasm);
105
+ let d = ops.iter().find(|(n, _)| n.starts_with("dispatch.") && n.ends_with(".val")).expect("a dispatcher of val");
106
+ assert_eq!(count(d.1, "BrTable"), 1, "{:?}", d.1);
107
+ assert_eq!(count(d.1, "RefTestNonNull"), 0, "{:?}", d.1);
108
+ assert_eq!(count(d.1, "ReturnCall"), 20);
109
+ // Fold by hand: S_i.val(x) = x + i + 1, G.val(x) = 2x + 1.
110
+ let mut a: i64 = 0;
111
+ let mut b: i64 = 0;
112
+ for i in 0..20i64 {
113
+ let val = |x: i64| if i < 19 { x + i + 1 } else { x * 2 + 1 };
114
+ a = a * 3 % 1000003 + val(a);
115
+ b += val(val(1));
116
+ }
117
+ assert_eq!(runInt(&wasm), a * 1000000 + b);
118
+ }
119
+
120
+ /// Two implementers (one generic).
121
+ #[test]
122
+ fn dispatch_with_two_implementers() {
123
+ let body = "fun main() -> Int =
124
+ xs := objects()
125
+ foldC(xs, 0, 0)
126
+ ";
127
+ let wasm = compile("dispatch_two", &format!("{PRE}{}{body}", many(1)), true);
128
+ assert_eq!(runInt(&wasm), 11 + 21);
129
+ }
130
+
131
+ const SCREENS: &str = "trait Actor[M] =
132
+ fun key(self) -> Int
133
+ fun react(self, m: M) -> Self = self
134
+
135
+ trait Screen[S, M] is Actor[M] =
136
+ fun title(self, s: S) -> Str
137
+
138
+ struct Ball(id: Int, n: Int) is Actor[Int] =
139
+ fun key(self) -> Int = self.id * 10 + self.n
140
+ fun react(self, m: Int) -> Ball = Ball(..self, n: self.n + m)
141
+
142
+ struct Menu(id: Int) is Screen[Str, Int] =
143
+ fun key(self) -> Int = self.id
144
+ fun title(self, s: Str) -> Str = \"menu \" + s
145
+
146
+ struct Play(id: Int, score: Int) is Screen[Str, Int] =
147
+ fun key(self) -> Int = self.id + self.score
148
+ fun title(self, s: Str) -> Str = \"play \" + s
149
+ fun react(self, m: Int) -> Play = Play(..self, score: self.score + m)
150
+
151
+ enum Dot is Actor[Int] =
152
+ | Big
153
+ | Small
154
+
155
+ fun key(self) -> Int = match self
156
+ Big => 100
157
+ Small => 1
158
+
159
+ fun screenKey(a: Actor[Int]) -> Int =
160
+ match a
161
+ Screen[Str, Int] as s => s.title(\"x\").length() * 1000 + s.key()
162
+ Ball as b => b.n
163
+ _ => -1
164
+
165
+ fun isBig(a: Actor[Int]) -> Bool =
166
+ match a
167
+ Dot as d => d == Big
168
+ _ => false
169
+
170
+ ";
171
+
172
+ /// Inherited traits dispatch on the same tag: a `Screen` is an `Actor` with no cast, a
173
+ /// downcast to a trait or a type compares tags, and an enum implementer works.
174
+ #[test]
175
+ fn inherited_traits_and_downcasts_use_tags() {
176
+ let body = "fun main() -> Int =
177
+ xs: List[Actor[Int]] := [Ball(id: 1, n: 2), Menu(id: 3), Play(id: 4, score: 5), Big, Small]
178
+ ys := xs.map(|a| a.react(7))
179
+ keys := ys.fold(0, |acc, a| acc * 7 + a.key())
180
+ downs := ys.fold(0, |acc, a| acc * 11 + screenKey(a))
181
+ bigs := ys.fold(0, |acc, a| if isBig(a) then acc + 1 else acc)
182
+ keys * 1000000 + downs % 1000000 + bigs * 7
183
+ ";
184
+ let wasm = compile("dispatch_screens", &format!("{PRE}{SCREENS}{body}"), true);
185
+ let ops = operators(&wasm);
186
+ for f in ["screenKey", "isBig"] {
187
+ let o = ops.get(f).unwrap_or_else(|| panic!("no fn {f}: {:?}", ops.keys().collect::<Vec<_>>()));
188
+ assert_eq!(count(o, "RefTestNonNull") + count(o, "RefTestNullable"), 0, "{f}: {o:?}");
189
+ }
190
+ // keys: Ball(1, 9) 19, Menu 3, Play(4, 12) 16, Big 100, Small 1.
191
+ let keys = [19i64, 3, 16, 100, 1].iter().fold(0, |acc, k| acc * 7 + k);
192
+ // downs: Ball 9, Menu len("menu x")=6 -> 6003, Play 6000 + 16, Big -1, Small -1.
193
+ let downs = [9i64, 6003, 6016, -1, -1].iter().fold(0, |acc, k| acc * 11 + k);
194
+ assert_eq!(runInt(&wasm), keys * 1000000 + downs % 1000000 + 7);
195
+ }
196
+
197
+ /// The tag is not a field to the language: `==` on implementers compares their fields,
198
+ /// and `==` on trait objects is the same type and equal fields.
199
+ #[test]
200
+ fn equality_ignores_the_tag() {
201
+ let src = "trait Named =
202
+ fun name(self) -> Str
203
+
204
+ struct P(x: Int, y: Int) is Named =
205
+ fun name(self) -> Str = \"p\"
206
+ fun eq(self, o: P) -> Bool = self.x == o.x && self.y == o.y
207
+
208
+ struct Q(x: Int, y: Int) is Named =
209
+ fun name(self) -> Str = \"q\"
210
+ fun eq(self, o: Q) -> Bool = self.x == o.x && self.y == o.y
211
+
212
+ struct R(x: Int) is Named =
213
+ fun name(self) -> Str = \"r\"
214
+
215
+ fun main() -> Int =
216
+ a: Named := P(x: 1, y: 2)
217
+ b: Named := P(x: 1, y: 2)
218
+ c: Named := Q(x: 1, y: 2)
219
+ r: Named := R(x: 1)
220
+ r2: Named := R(x: 1)
221
+ n := if a == b then 1 else 0
222
+ m := if a == c then 10 else 0
223
+ k := if P(x: 3, y: 4) == P(x: 3, y: 4) then 100 else 0
224
+ i := if r == r then 1000 else 0
225
+ j := if r == r2 then 10000 else 0
226
+ n + m + k + i + j
227
+ ";
228
+ let wasm = compile("dispatch_eq", &format!("{PRE}{src}"), true);
229
+ assert_eq!(runInt(&wasm), 1101);
230
+ }
231
+
232
+ /// An implementer updated through its trait (`Ball(..self, ..)` in `react`) is written in
233
+ /// place by default, the tag kept; with `--no-fbip` each update copies, tag and all.
234
+ #[test]
235
+ fn fbip_keeps_the_tag() {
236
+ let body = "fun spin(a: Actor[Int], n: Int) -> Actor[Int] = if n == 0 then a else spin(a.react(1), n - 1)
237
+
238
+ fun main() -> Int =
239
+ a := spin(Ball(id: 1, n: 0), 500)
240
+ p := spin(Play(id: 2, score: 0), 300)
241
+ screenKey(a) * 100000 + screenKey(p)
242
+ ";
243
+ let src = format!("{PRE}{SCREENS}{body}");
244
+ let news = |wasm: &[u8], f: &str| -> usize {
245
+ operators(wasm).iter().filter(|(n, _)| *n == f || n.starts_with(&format!("{f}$"))).map(|(_, o)| count(o, "StructNew")).sum()
246
+ };
247
+ let wasm = compile("dispatch_fbip", &src, true);
248
+ assert_eq!(news(&wasm, "Ball.react"), 0, "in place");
249
+ assert_eq!(runInt(&wasm), 500 * 100000 + 6000 + 302);
250
+ let copying = compile("dispatch_fbip_copy", &src, false);
251
+ assert_eq!(news(&copying, "Ball.react"), 1, "--no-fbip copies");
252
+ assert_eq!(runInt(&copying), 500 * 100000 + 6000 + 302);
253
+ }
compiler/wasm-codegen/tests/wasm_codegen/main.rs CHANGED
@@ -1,6 +1,7 @@
1
1
  #![allow(non_snake_case)]
2
2
  //! Single integration-test binary for plum-wasm-codegen (one link instead of one per file).
3
3
  mod codegen_tests;
4
+ mod dispatch_test;
4
5
  mod e2e_mem;
5
6
  mod e2e_records;
6
7
  mod e2e_tail;
tests/traits/tags.plum ADDED
@@ -0,0 +1,89 @@
1
+ # Trait dispatch on the type tag: many implementers, a generic one, an enum, inherited
2
+ # traits, downcasts to a type and to a trait, and `==` that never sees the tag.
3
+ import std/Int
4
+ import std/Str
5
+ import std/List
6
+
7
+ trait Part[M] =
8
+ fun weight(self) -> Int
9
+ fun heavier(self, by: Int) -> Self
10
+
11
+ trait Tool[M] is Part[M] =
12
+ fun use(self) -> Int
13
+
14
+ struct A(n: Int) is Part[Int] =
15
+ fun weight(self) -> Int = self.n
16
+ fun heavier(self, by: Int) -> A = A(..self, n: self.n + by)
17
+ fun eq(self, o: A) -> Bool = self.n == o.n
18
+
19
+ struct B(n: Int, m: Int) is Part[Int] =
20
+ fun weight(self) -> Int = self.n * self.m
21
+ fun heavier(self, by: Int) -> B = B(..self, m: self.m + by)
22
+
23
+ struct C(s: Str) is Part[Int] =
24
+ fun weight(self) -> Int = self.s.length()
25
+ fun heavier(self, by: Int) -> C = C(s: self.s + "x")
26
+
27
+ struct D(n: Int) is Part[Int] =
28
+ fun weight(self) -> Int = 4 * self.n
29
+ fun heavier(self, by: Int) -> D = D(n: self.n + by)
30
+
31
+ struct Hammer(n: Int) is Tool[Int] =
32
+ fun weight(self) -> Int = 50 + self.n
33
+ fun heavier(self, by: Int) -> Hammer = Hammer(n: self.n + by)
34
+ fun use(self) -> Int = 7
35
+
36
+ struct Saw(n: Int) is Tool[Int] =
37
+ fun weight(self) -> Int = 60 + self.n
38
+ fun heavier(self, by: Int) -> Saw = Saw(n: self.n + by)
39
+ fun use(self) -> Int = 9
40
+
41
+ struct Crate[M](n: Int, label: M) is Part[M] =
42
+ fun weight(self) -> Int = 1000 + self.n
43
+ fun heavier(self, by: Int) -> Crate[M] = Crate(..self, n: self.n + by)
44
+
45
+ enum Pebble is Part[Int] =
46
+ | Tiny
47
+ | Round
48
+
49
+ fun weight(self) -> Int = match self
50
+ Tiny => 1
51
+ Round => 2
52
+
53
+ fun heavier(self, by: Int) -> Pebble = Round
54
+
55
+ fun parts() -> List[Part[Int]] = [A(n: 1), B(n: 2, m: 3), C(s: "ab"), D(n: 1), Hammer(n: 0), Saw(n: 1), Crate[Int](n: 5, label: 3), Tiny]
56
+
57
+ fun total(xs: List[Part[Int]]) -> Int = xs.fold(0, |acc, p| acc + p.weight())
58
+
59
+ fun uses(xs: List[Part[Int]]) -> Int = xs.fold(0, |acc, p| match p
60
+ Tool[Int] as t => acc + t.use()
61
+ _ => acc)
62
+
63
+ fun bs(xs: List[Part[Int]]) -> Int = xs.fold(0, |acc, p| match p
64
+ B as b => acc + b.m
65
+ Crate[Int] as c => acc + c.label * 100
66
+ _ => acc)
67
+
68
+ test "every implementer's method through the trait object"
69
+ assert total(parts()) == 1 + 6 + 2 + 4 + 50 + 61 + 1005 + 1
70
+
71
+ test "Self methods return each implementer's own update"
72
+ assert total(parts().map(|p| p.heavier(1))) == 2 + 8 + 3 + 8 + 51 + 62 + 1006 + 2
73
+
74
+ test "a downcast to a trait matches its implementers only"
75
+ assert uses(parts()) == 16
76
+
77
+ test "a downcast to a type, generic or not"
78
+ assert bs(parts()) == 303
79
+
80
+ test "== goes to the type's eq, on the type and on trait objects"
81
+ assert A(n: 1) == A(n: 1)
82
+ assert A(n: 1) != A(n: 2)
83
+ x: Part[Int] := A(n: 1)
84
+ y: Part[Int] := A(n: 1)
85
+ z: Part[Int] := D(n: 1)
86
+ assert x == y
87
+ assert x != z
88
+ assert z == z
89
+ assert {z == D(n: 1)} == false