plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
d5ce22f
— Peter John
2026-11-16T22:05:02+05:30
U4f: Nil/None as ref.null, br_on_cast_fail for constructor arms
- compiler/wasm-codegen/src/construct.rs +1 -10
- compiler/wasm-codegen/src/driver.rs +14 -3
- compiler/wasm-codegen/src/expr.rs +4 -9
- compiler/wasm-codegen/src/fnbody.rs +17 -2
- compiler/wasm-codegen/src/gctypes.rs +97 -6
- compiler/wasm-codegen/src/matching.rs +130 -79
- compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs +23 -2
- docs/backlog.md +2 -2
- tests/core/null_variants.plum +142 -0
compiler/wasm-codegen/src/construct.rs
CHANGED
|
@@ -120,16 +120,7 @@ pub(crate) fn compileVariantConstruction(
|
|
|
120
120
|
if info.field_types.is_empty() {
|
|
121
121
|
// Pre-allocated singleton (this migration plan's Decision 2) — not a fresh
|
|
122
122
|
// struct.new per reference.
|
|
123
|
-
let global_idx = *ctx
|
|
124
|
-
.singleton_globals
|
|
125
|
-
|
|
123
|
+
emitSingleton(ctx.gc_types, ctx.singleton_globals, &ety, &call.name, body)?;
|
|
126
|
-
.ok_or_else(|| {
|
|
127
|
-
format!(
|
|
128
|
-
"codegen: payload-free variant '{}' has no singleton global",
|
|
129
|
-
call.name
|
|
130
|
-
)
|
|
131
|
-
})?;
|
|
132
|
-
Instruction::GlobalGet(global_idx).encode(body);
|
|
133
124
|
return Ok(());
|
|
134
125
|
}
|
|
135
126
|
|
compiler/wasm-codegen/src/driver.rs
CHANGED
|
@@ -654,7 +654,8 @@ impl<'a> Setup<'a> {
|
|
|
654
654
|
}
|
|
655
655
|
}
|
|
656
656
|
|
|
657
|
-
/// Pre-allocate one instance of every payload-free variant of every enum instance
|
|
657
|
+
/// Pre-allocate one instance of every payload-free variant of every enum instance, but
|
|
658
|
+
/// for the null variants (`GcTypeRegistry::null_variants`), which are `ref.null`.
|
|
658
659
|
pub(crate) fn registerSingletons(&mut self) {
|
|
659
660
|
let Setup { enum_variants, module, gc_types, singleton_globals, start_body, start_func_idx, .. } = self;
|
|
660
661
|
let gc_types = gc_types.as_mut().unwrap();
|
|
@@ -667,7 +668,7 @@ impl<'a> Setup<'a> {
|
|
|
667
668
|
.collect();
|
|
668
669
|
vnames.sort_by_key(|(_, i)| i.tag);
|
|
669
670
|
for (name, info) in vnames {
|
|
670
|
-
if !info.field_types.is_empty() {
|
|
671
|
+
if !info.field_types.is_empty() || gc_types.isNullVariant(name) {
|
|
671
672
|
continue;
|
|
672
673
|
}
|
|
673
674
|
let variant_idx = gc_types.variantIdx(&ty, name).unwrap_or_else(|| {
|
|
@@ -911,7 +912,8 @@ impl<'a> Setup<'a> {
|
|
|
911
912
|
|
|
912
913
|
/// Heap-valued consts: one cached global and one accessor function each.
|
|
913
914
|
pub(crate) fn registerConstInits(&mut self) {
|
|
914
|
-
let Setup { source, base_types, module, func_ids, const_inits, .. } = self;
|
|
915
|
+
let Setup { source, base_types, module, func_ids, const_inits, enum_variants, gc_types, .. } = self;
|
|
916
|
+
let gc_types = gc_types.as_ref().unwrap();
|
|
915
917
|
// Heap-valued consts (`TABLE = List(..)`): one lazily-initialised cached global and
|
|
916
918
|
// one accessor function each (`const#NAME`), compiled below.
|
|
917
919
|
for item in &source.items {
|
|
@@ -930,6 +932,14 @@ impl<'a> Setup<'a> {
|
|
|
930
932
|
let mut init = Vec::new();
|
|
931
933
|
Instruction::RefNull(rt.heap_type).encode(&mut init);
|
|
932
934
|
let global = module.addGlobal(vt, true, &init);
|
|
935
|
+
// A value that may be null (`Nil`, `None`) can't also mean "not built yet": a flag does.
|
|
936
|
+
let mayBeNull = plum_checker::nominalName(ty)
|
|
937
|
+
.is_some_and(|n| enum_variants.iter().any(|(v, i)| i.enum_name == n && gc_types.isNullVariant(v)));
|
|
938
|
+
let built = mayBeNull.then(|| {
|
|
939
|
+
let mut zero = Vec::new();
|
|
940
|
+
Instruction::I32Const(0).encode(&mut zero);
|
|
941
|
+
module.addGlobal(ValType::I32, true, &zero)
|
|
942
|
+
});
|
|
933
943
|
let t = module.addType(&[], &[vt]);
|
|
934
944
|
let func_idx = module.addFunction(t, &[]);
|
|
935
945
|
module.nameFunction(func_idx, &format!("const.{}", c.name));
|
|
@@ -940,6 +950,7 @@ impl<'a> Setup<'a> {
|
|
|
940
950
|
expr: &c.value,
|
|
941
951
|
ty: ty.clone(),
|
|
942
952
|
global,
|
|
953
|
+
built,
|
|
943
954
|
},
|
|
944
955
|
func_idx,
|
|
945
956
|
));
|
compiler/wasm-codegen/src/expr.rs
CHANGED
|
@@ -17,9 +17,8 @@ pub(crate) fn compileExprInto(
|
|
|
17
17
|
if let ast::ExprKind::TypeName(n) = &expr.kind {
|
|
18
18
|
if let (Some(info), PlumType::TApp(dn, _)) = (ctx.enum_variants.get(n), decl) {
|
|
19
19
|
if info.field_types.is_empty() && *dn == info.enum_name && !hasFreeTy(decl) {
|
|
20
|
-
if
|
|
20
|
+
if ctx.gc_types.isNullVariant(n) || ctx.singleton_globals.contains_key(&(canonTy(decl), n.clone())) {
|
|
21
|
-
|
|
21
|
+
return emitSingleton(ctx.gc_types, ctx.singleton_globals, decl, n, body);
|
|
22
|
-
return Ok(());
|
|
23
22
|
}
|
|
24
23
|
}
|
|
25
24
|
}
|
|
@@ -514,9 +513,7 @@ fn compileExprNode(
|
|
|
514
513
|
match ctx.enum_variants.get(n) {
|
|
515
514
|
Some(info) if info.field_types.is_empty() => {
|
|
516
515
|
let ety = enumTypeOfExpr(expr, info, ctx);
|
|
517
|
-
|
|
516
|
+
emitSingleton(ctx.gc_types, ctx.singleton_globals, &ety, n, body)?;
|
|
518
|
-
.ok_or_else(|| format!("internal codegen error: payload-free variant '{}' of {} has no singleton global", n, ety))?;
|
|
519
|
-
Instruction::GlobalGet(global_idx).encode(body);
|
|
520
517
|
}
|
|
521
518
|
Some(_) => {
|
|
522
519
|
return Err(format!(
|
|
@@ -620,9 +617,7 @@ fn compileExprNode(
|
|
|
620
617
|
// the checker's type of the call itself.
|
|
621
618
|
let info = &ctx.enum_variants[&call.type_name];
|
|
622
619
|
let ety = enumTypeOfExpr(expr, info, ctx);
|
|
623
|
-
|
|
620
|
+
emitSingleton(ctx.gc_types, ctx.singleton_globals, &ety, &call.type_name, body)?;
|
|
624
|
-
.ok_or_else(|| format!("internal codegen error: payload-free variant '{}' of {} has no singleton global", call.type_name, ety))?;
|
|
625
|
-
Instruction::GlobalGet(global_idx).encode(body);
|
|
626
621
|
}
|
|
627
622
|
// A NAMED-payload enum variant construction (`Circle(radius: 5)`, as
|
|
628
623
|
// opposed to the positional/generic-payload form `Next(T)` — constructed
|
compiler/wasm-codegen/src/fnbody.rs
CHANGED
|
@@ -304,6 +304,9 @@ pub(crate) struct ConstInit<'e> {
|
|
|
304
304
|
pub(crate) expr: &'e ast::Expr,
|
|
305
305
|
pub(crate) ty: PlumType,
|
|
306
306
|
pub(crate) global: u32,
|
|
307
|
+
/// The `i32` global set once the value is built, when the value may be null; else the
|
|
308
|
+
/// global's null says it is not built yet.
|
|
309
|
+
pub(crate) built: Option<u32>,
|
|
307
310
|
}
|
|
308
311
|
|
|
309
312
|
/// Whether a const initializer builds a fresh object — compiled once into a cached
|
|
@@ -491,11 +494,23 @@ pub(crate) fn compileFnBodyImpl(
|
|
|
491
494
|
};
|
|
492
495
|
|
|
493
496
|
if let Some(ci) = const_init {
|
|
497
|
+
match ci.built {
|
|
498
|
+
Some(b) => {
|
|
499
|
+
Instruction::GlobalGet(b).encode(&mut body);
|
|
500
|
+
Instruction::I32Eqz.encode(&mut body);
|
|
501
|
+
}
|
|
502
|
+
None => {
|
|
494
|
-
|
|
503
|
+
Instruction::GlobalGet(ci.global).encode(&mut body);
|
|
495
|
-
|
|
504
|
+
Instruction::RefIsNull.encode(&mut body);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
496
507
|
Instruction::If(BlockType::Empty).encode(&mut body);
|
|
497
508
|
compileExprInto(ci.expr, &ci.ty, &mut body, &local_ctx, state)?;
|
|
498
509
|
Instruction::GlobalSet(ci.global).encode(&mut body);
|
|
510
|
+
if let Some(b) = ci.built {
|
|
511
|
+
Instruction::I32Const(1).encode(&mut body);
|
|
512
|
+
Instruction::GlobalSet(b).encode(&mut body);
|
|
513
|
+
}
|
|
499
514
|
Instruction::End.encode(&mut body);
|
|
500
515
|
Instruction::GlobalGet(ci.global).encode(&mut body);
|
|
501
516
|
Instruction::End.encode(&mut body);
|
compiler/wasm-codegen/src/gctypes.rs
CHANGED
|
@@ -25,10 +25,9 @@ pub(crate) fn scratchTypeIdx(r: &GcTypeRegistry, ty: &PlumType, vname: &str) ->
|
|
|
25
25
|
})
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
-
/// A `ref null $Ty`
|
|
28
|
+
/// A `ref null $Ty`: every heap value (class instance, enum variant, Str array, closure
|
|
29
|
-
/// array, closure struct) is nullable-by-convention, matching how a bump-allocator
|
|
30
|
-
///
|
|
29
|
+
/// struct) is typed nullable. Null is a value only for an enum's null variant (`Nil`,
|
|
31
|
-
///
|
|
30
|
+
/// `None`, see `GcTypeRegistry::null_variants`).
|
|
32
31
|
pub(crate) fn gcRef(idx: u32) -> ValType {
|
|
33
32
|
ValType::Ref(RefType {
|
|
34
33
|
nullable: true,
|
|
@@ -51,6 +50,29 @@ pub(crate) fn pushSelfPlaceholder(vt: ValType, body: &mut Vec<u8>) {
|
|
|
51
50
|
}
|
|
52
51
|
}
|
|
53
52
|
|
|
53
|
+
/// Pushes payload-free variant `name` of enum type `ty`: `ref.null` of the enum's type for
|
|
54
|
+
/// its null variant (see `GcTypeRegistry::null_variants`), else its pre-allocated singleton.
|
|
55
|
+
pub(crate) fn emitSingleton(
|
|
56
|
+
reg: &GcTypeRegistry,
|
|
57
|
+
globals: &HashMap<(PlumType, String), u32>,
|
|
58
|
+
ty: &PlumType,
|
|
59
|
+
name: &str,
|
|
60
|
+
body: &mut Vec<u8>,
|
|
61
|
+
) -> Result<(), String> {
|
|
62
|
+
if reg.isNullVariant(name) {
|
|
63
|
+
let ValType::Ref(rt) = plumTypeToGcValtype(ty, reg) else {
|
|
64
|
+
return Err(format!("internal codegen error: '{}' of {} is not a reference", name, ty));
|
|
65
|
+
};
|
|
66
|
+
Instruction::RefNull(rt.heap_type).encode(body);
|
|
67
|
+
return Ok(());
|
|
68
|
+
}
|
|
69
|
+
let g = globals
|
|
70
|
+
.get(&(canonTy(ty), name.to_string()))
|
|
71
|
+
.ok_or_else(|| format!("internal codegen error: payload-free variant '{}' of {} has no singleton global", name, ty))?;
|
|
72
|
+
Instruction::GlobalGet(*g).encode(body);
|
|
73
|
+
Ok(())
|
|
74
|
+
}
|
|
75
|
+
|
|
54
76
|
pub(crate) fn strType() -> PlumType {
|
|
55
77
|
plum_checker::types::strType()
|
|
56
78
|
}
|
|
@@ -127,6 +149,15 @@ pub struct GcTypeRegistry {
|
|
|
127
149
|
/// Variant struct index -> where each of its fields is, when it holds a value struct
|
|
128
150
|
/// in line (see `inlinePlan`): `(first wasm field, the value type if in line)` per field.
|
|
129
151
|
pub inline_fields: HashMap<u32, InlineFields>,
|
|
152
|
+
/// The payload-free variant of each enum with exactly one of them and at least one
|
|
153
|
+
/// variant with fields (`Nil` of `List`, `None` of `Option`), when the enum has no
|
|
154
|
+
/// trait, no shared fields and is no value enum: its value is `ref.null` of the
|
|
155
|
+
/// enum's type, so making it reads no global and matching it is `ref.is_null`.
|
|
156
|
+
pub null_variants: HashSet<String>,
|
|
157
|
+
/// The other variant of such an enum when it has only two (`Cons`, `Some`): the
|
|
158
|
+
/// enum's type is this variant's struct, so a non-null value of the enum is one and
|
|
159
|
+
/// needs no cast.
|
|
160
|
+
pub sole_variants: HashSet<String>,
|
|
130
161
|
}
|
|
131
162
|
|
|
132
163
|
/// The fields of a variant struct that holds value structs in line: each field's first
|
|
@@ -230,6 +261,27 @@ impl GcTypeRegistry {
|
|
|
230
261
|
_ => false,
|
|
231
262
|
}
|
|
232
263
|
}
|
|
264
|
+
/// Whether variant `vname` is the `ref.null` of its enum (see `null_variants`).
|
|
265
|
+
pub fn isNullVariant(&self, vname: &str) -> bool {
|
|
266
|
+
self.null_variants.contains(vname)
|
|
267
|
+
}
|
|
268
|
+
/// Whether variant `vname` is every non-null value of its enum (see `sole_variants`).
|
|
269
|
+
pub fn isSoleVariant(&self, vname: &str) -> bool {
|
|
270
|
+
self.sole_variants.contains(vname)
|
|
271
|
+
}
|
|
272
|
+
/// With a value of the enum on the stack, leaves whether it is variant `vname` (struct
|
|
273
|
+
/// `idx`): `ref.is_null` for the null variant, not that for the sole other one, else a
|
|
274
|
+
/// `ref.test` of the variant's struct.
|
|
275
|
+
pub fn emitVariantTest(&self, vname: &str, idx: u32, body: &mut Vec<u8>) {
|
|
276
|
+
if self.isNullVariant(vname) {
|
|
277
|
+
Instruction::RefIsNull.encode(body);
|
|
278
|
+
} else if self.isSoleVariant(vname) {
|
|
279
|
+
Instruction::RefIsNull.encode(body);
|
|
280
|
+
Instruction::I32Eqz.encode(body);
|
|
281
|
+
} else {
|
|
282
|
+
Instruction::RefTestNonNull(HeapType::Concrete(idx)).encode(body);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
233
285
|
/// Struct index of variant `vname` of enum type `ty`.
|
|
234
286
|
pub fn variantIdx(&self, ty: &PlumType, vname: &str) -> Option<u32> {
|
|
235
287
|
match ty {
|
|
@@ -360,6 +412,8 @@ pub(crate) fn buildGcTypeRegistry(
|
|
|
360
412
|
tags: HashMap::new(),
|
|
361
413
|
tagged: HashMap::new(),
|
|
362
414
|
inline_fields: HashMap::new(),
|
|
415
|
+
null_variants: HashSet::new(),
|
|
416
|
+
sole_variants: HashSet::new(),
|
|
363
417
|
};
|
|
364
418
|
for item in &source.items {
|
|
365
419
|
if let ast::Item::Trait(t) = item {
|
|
@@ -380,6 +434,27 @@ pub(crate) fn buildGcTypeRegistry(
|
|
|
380
434
|
instances.push(PlumType::TNamed(e.name.clone()));
|
|
381
435
|
}
|
|
382
436
|
}
|
|
437
|
+
for e in enum_decls.values() {
|
|
438
|
+
let nullary: Vec<&str> = e
|
|
439
|
+
.variants
|
|
440
|
+
.iter()
|
|
441
|
+
.filter(|v| enum_variants.get(&v.name).is_some_and(|i| i.field_types.is_empty()))
|
|
442
|
+
.map(|v| v.name.as_str())
|
|
443
|
+
.collect();
|
|
444
|
+
let eligible = nullary.len() == 1
|
|
445
|
+
&& e.variants.len() >= 2
|
|
446
|
+
&& e.implements.is_empty()
|
|
447
|
+
&& !isArraySpecialization(&e.name)
|
|
448
|
+
&& enum_params.get(&e.name).is_none_or(|p| p.is_empty())
|
|
449
|
+
&& !withGen(|s| s.value_enums.contains_key(&e.name));
|
|
450
|
+
if eligible {
|
|
451
|
+
reg.null_variants.insert(nullary[0].to_string());
|
|
452
|
+
if e.variants.len() == 2 {
|
|
453
|
+
let other = e.variants.iter().find(|v| v.name != nullary[0]).unwrap();
|
|
454
|
+
reg.sole_variants.insert(other.name.clone());
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
383
458
|
let mut arrays: Vec<PlumType> = Vec::new();
|
|
384
459
|
for a in apps {
|
|
385
460
|
if let PlumType::TApp(n, _) = a {
|
|
@@ -449,6 +524,16 @@ pub(crate) fn buildGcTypeRegistry(
|
|
|
449
524
|
reg.app_variant.insert((ty.clone(), v.name.clone()), idx);
|
|
450
525
|
}
|
|
451
526
|
}
|
|
527
|
+
if reg.sole_variants.contains(&v.name) {
|
|
528
|
+
match ty {
|
|
529
|
+
PlumType::TNamed(_) => {
|
|
530
|
+
reg.enum_super_type_idx.insert(n.clone(), idx);
|
|
531
|
+
}
|
|
532
|
+
_ => {
|
|
533
|
+
reg.app_super.insert(ty.clone(), idx);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
452
537
|
if e.variants.len() == 1 && v.name == n {
|
|
453
538
|
match ty {
|
|
454
539
|
PlumType::TNamed(_) => {
|
|
@@ -603,7 +688,13 @@ pub(crate) fn buildGcTypeRegistry(
|
|
|
603
688
|
vname
|
|
604
689
|
)
|
|
605
690
|
});
|
|
691
|
+
// The null variant's struct is never made, and the sole variant's struct is
|
|
692
|
+
// the enum's type itself: neither has a supertype.
|
|
693
|
+
let super_idx = if reg.isNullVariant(vname) || reg.isSoleVariant(vname) {
|
|
694
|
+
None
|
|
695
|
+
} else {
|
|
606
|
-
|
|
696
|
+
Some(reg.superIdx(ty).expect("enum supertype slot"))
|
|
697
|
+
};
|
|
607
698
|
let mut field_types: Vec<FieldType> = Vec::new();
|
|
608
699
|
if reg.tags.contains_key(ty) {
|
|
609
700
|
field_types.push(tagField());
|
|
@@ -630,7 +721,7 @@ pub(crate) fn buildGcTypeRegistry(
|
|
|
630
721
|
}
|
|
631
722
|
SubType {
|
|
632
723
|
is_final: true,
|
|
633
|
-
supertype_idx:
|
|
724
|
+
supertype_idx: super_idx,
|
|
634
725
|
composite_type: CompositeType {
|
|
635
726
|
inner: CompositeInnerType::Struct(StructType {
|
|
636
727
|
fields: field_types.into(),
|
compiler/wasm-codegen/src/matching.rs
CHANGED
|
@@ -229,9 +229,9 @@ pub(crate) fn compileMatch(
|
|
|
229
229
|
&& m.subjects
|
|
230
230
|
.iter()
|
|
231
231
|
.all(|e| matches!(inferLocalType(e, ctx), PlumType::TBool));
|
|
232
|
-
|
|
232
|
+
// In statement position too: the last arm of a match proven exhaustive is not tested.
|
|
233
|
-
|
|
233
|
+
let exhaustive_fallback = (result_vt.is_some() && bool_match && matchCoversEveryBoolCombo(&m.cases, m.subjects.len()))
|
|
234
|
-
|
|
234
|
+
|| matchCoversEveryEnumVariant(&m.cases, &subject_vts, ctx);
|
|
235
235
|
|
|
236
236
|
compileMatchArmsMulti(
|
|
237
237
|
&m.cases,
|
|
@@ -560,11 +560,13 @@ pub(crate) fn compileVariantEqArm(
|
|
|
560
560
|
name, sty
|
|
561
561
|
)
|
|
562
562
|
})?;
|
|
563
|
+
// The last arm of a match proven exhaustive: nothing else can get here. Else one test
|
|
563
|
-
//
|
|
564
|
+
// (`GcTypeRegistry::emitVariantTest`): the variant's struct type is its discriminant.
|
|
564
|
-
|
|
565
|
+
if rest.is_empty() && exhaustive_fallback {
|
|
565
|
-
|
|
566
|
+
return compileCasePositions(case, pos + 1, all_subjects, rest, result_vt, exhaustive_fallback, body, ctx, state);
|
|
567
|
+
}
|
|
566
568
|
Instruction::LocalGet(scratch_local).encode(body);
|
|
567
|
-
|
|
569
|
+
ctx.gc_types.emitVariantTest(name, variant_idx, body);
|
|
568
570
|
Instruction::If(blockTypeFor(result_vt)).encode(body);
|
|
569
571
|
let _tg = TailDepth::enter(&ctx.tail_depth);
|
|
570
572
|
compileCasePositions(
|
|
@@ -614,6 +616,10 @@ pub(crate) fn compileVariantConstructorArm(
|
|
|
614
616
|
.enum_variants
|
|
615
617
|
.get(name)
|
|
616
618
|
.ok_or_else(|| format!("codegen: unknown enum variant '{}'", name))?;
|
|
619
|
+
// `Nil()`: the null variant has no struct to narrow to, only its test.
|
|
620
|
+
if ctx.gc_types.isNullVariant(name) && fields.is_empty() {
|
|
621
|
+
return compileVariantEqArm(name, subject_vt, scratch_local, case, pos, all_subjects, rest, result_vt, exhaustive_fallback, body, ctx, state);
|
|
622
|
+
}
|
|
617
623
|
if !matches!(subject_vt, ValType::Ref(_)) {
|
|
618
624
|
return Err(format!(
|
|
619
625
|
"codegen: constructor pattern '{}' against a non-enum subject",
|
|
@@ -666,25 +672,13 @@ pub(crate) fn compileVariantConstructorArm(
|
|
|
666
672
|
})?;
|
|
667
673
|
let narrow_local = ctx.nested_class_scratch_base + narrow_slot;
|
|
668
674
|
|
|
669
|
-
// A single ref.test against the variant's exact concrete type replaces the old
|
|
670
|
-
// "range-check against HEAP_BASE, then conditionally load+compare a tag" dance.
|
|
671
675
|
// When this is the last case of a match proven exhaustive, a failed test could only
|
|
672
|
-
// reach the `unreachable` of "no case left", so the test goes: the cast
|
|
676
|
+
// reach the `unreachable` of "no case left", so the test goes: the cast traps in its
|
|
673
|
-
//
|
|
677
|
+
// place.
|
|
674
678
|
let tested = !(rest.is_empty() && exhaustive_fallback);
|
|
675
|
-
let
|
|
679
|
+
let open = openVariantArm(name, variant_idx, subject_vt, tested, narrow_local, result_vt, body, ctx, &mut |b| {
|
|
676
|
-
Instruction::LocalGet(scratch_local).encode(
|
|
680
|
+
Instruction::LocalGet(scratch_local).encode(b)
|
|
677
|
-
Instruction::RefTestNonNull(HeapType::Concrete(variant_idx)).encode(body);
|
|
678
|
-
Instruction::If(blockTypeFor(result_vt)).encode(body);
|
|
679
|
-
Some(TailDepth::enter(&ctx.tail_depth))
|
|
680
|
-
} else {
|
|
681
|
-
None
|
|
682
|
-
};
|
|
681
|
+
})?;
|
|
683
|
-
// Narrow the subject down to this variant's concrete type before destructuring
|
|
684
|
-
// its fields — valid here specifically because the ref.test just above proved it.
|
|
685
|
-
Instruction::LocalGet(scratch_local).encode(body);
|
|
686
|
-
Instruction::RefCastNonNull(HeapType::Concrete(variant_idx)).encode(body);
|
|
687
|
-
Instruction::LocalSet(narrow_local).encode(body);
|
|
688
682
|
let mut onMatch = |body: &mut Vec<u8>, state: &mut ModuleState| {
|
|
689
683
|
compileCasePositions(
|
|
690
684
|
case,
|
|
@@ -715,20 +709,103 @@ pub(crate) fn compileVariantConstructorArm(
|
|
|
715
709
|
state,
|
|
716
710
|
&mut onMatch,
|
|
717
711
|
)?;
|
|
712
|
+
closeVariantArm(open, body, ctx, &mut |body| {
|
|
713
|
+
compileMatchArmsMulti(rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state)
|
|
714
|
+
})
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/// How a constructor arm tested its variant (see `openVariantArm`).
|
|
718
|
+
pub(crate) enum ArmOpen {
|
|
719
|
+
/// No test: the last arm of a match proven exhaustive.
|
|
720
|
+
Untested,
|
|
721
|
+
/// `if` (the value is not null, for the sole non-null variant), its `else` the rest.
|
|
722
|
+
If,
|
|
723
|
+
/// `block $out (block $fail (br_on_cast_fail $fail ..) <arm> br $out) drop <rest>`.
|
|
724
|
+
Cast,
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/// Opens a constructor arm for variant `name` (struct `idx`) of the value `load` pushes, of
|
|
728
|
+
/// wasm type `from`, and puts the value narrowed to the variant's struct in `narrow`: for
|
|
729
|
+
/// the sole non-null variant (`Cons`, `Some`) the enum's type is the variant's struct, so a
|
|
730
|
+
/// null test and no cast; for another variant one `br_on_cast_fail` both tests and narrows;
|
|
731
|
+
/// untested (`tested` false), the cast alone. `closeVariantArm` closes it once the arm is
|
|
732
|
+
/// compiled, with the rest of the match on the failing path.
|
|
733
|
+
#[allow(clippy::too_many_arguments)]
|
|
734
|
+
pub(crate) fn openVariantArm(
|
|
735
|
+
name: &str,
|
|
736
|
+
idx: u32,
|
|
737
|
+
from: ValType,
|
|
738
|
+
tested: bool,
|
|
739
|
+
narrow: u32,
|
|
740
|
+
result_vt: Option<ValType>,
|
|
741
|
+
body: &mut Vec<u8>,
|
|
742
|
+
ctx: &LocalCtx,
|
|
743
|
+
load: &mut dyn FnMut(&mut Vec<u8>),
|
|
744
|
+
) -> Result<ArmOpen, String> {
|
|
745
|
+
// The enum's own type is the sole variant's struct; a value of a type with free
|
|
746
|
+
// variables (`anyref`) is still cast.
|
|
747
|
+
let sole = ctx.gc_types.isSoleVariant(name) && from == gcRef(idx);
|
|
748
|
+
let to = RefType { nullable: false, heap_type: HeapType::Concrete(idx) };
|
|
718
|
-
if tested {
|
|
749
|
+
if !tested {
|
|
750
|
+
load(body);
|
|
751
|
+
if !sole {
|
|
752
|
+
Instruction::RefCastNonNull(HeapType::Concrete(idx)).encode(body);
|
|
753
|
+
}
|
|
754
|
+
Instruction::LocalSet(narrow).encode(body);
|
|
755
|
+
return Ok(ArmOpen::Untested);
|
|
756
|
+
}
|
|
757
|
+
match from {
|
|
758
|
+
ValType::Ref(from_rt) if !sole => {
|
|
759
|
+
Instruction::Block(blockTypeFor(result_vt)).encode(body);
|
|
760
|
+
Instruction::Block(BlockType::Result(from)).encode(body);
|
|
761
|
+
ctx.tail_depth.set(ctx.tail_depth.get() + 2);
|
|
762
|
+
load(body);
|
|
763
|
+
Instruction::BrOnCastFail { relative_depth: 0, from_ref_type: from_rt, to_ref_type: to }.encode(body);
|
|
764
|
+
Instruction::LocalSet(narrow).encode(body);
|
|
765
|
+
Ok(ArmOpen::Cast)
|
|
766
|
+
}
|
|
767
|
+
_ => {
|
|
768
|
+
load(body);
|
|
769
|
+
ctx.gc_types.emitVariantTest(name, idx, body);
|
|
770
|
+
Instruction::If(blockTypeFor(result_vt)).encode(body);
|
|
771
|
+
ctx.tail_depth.set(ctx.tail_depth.get() + 1);
|
|
772
|
+
load(body);
|
|
773
|
+
if !sole {
|
|
774
|
+
Instruction::RefCastNonNull(HeapType::Concrete(idx)).encode(body);
|
|
775
|
+
}
|
|
776
|
+
Instruction::LocalSet(narrow).encode(body);
|
|
777
|
+
Ok(ArmOpen::If)
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
/// Closes an arm `openVariantArm` opened: `rest` compiles the failing path.
|
|
783
|
+
pub(crate) fn closeVariantArm(
|
|
784
|
+
open: ArmOpen,
|
|
785
|
+
body: &mut Vec<u8>,
|
|
786
|
+
ctx: &LocalCtx,
|
|
787
|
+
rest: &mut dyn FnMut(&mut Vec<u8>) -> Result<(), String>,
|
|
788
|
+
) -> Result<(), String> {
|
|
789
|
+
match open {
|
|
790
|
+
ArmOpen::Untested => Ok(()),
|
|
791
|
+
ArmOpen::If => {
|
|
719
|
-
|
|
792
|
+
Instruction::Else.encode(body);
|
|
720
|
-
compileMatchArmsMulti(
|
|
721
|
-
rest,
|
|
722
|
-
all_subjects,
|
|
723
|
-
|
|
793
|
+
rest(body)?;
|
|
724
|
-
exhaustive_fallback,
|
|
725
|
-
body,
|
|
726
|
-
ctx,
|
|
727
|
-
state,
|
|
728
|
-
)?;
|
|
729
|
-
|
|
794
|
+
Instruction::End.encode(body);
|
|
795
|
+
ctx.tail_depth.set(ctx.tail_depth.get() - 1);
|
|
796
|
+
Ok(())
|
|
797
|
+
}
|
|
798
|
+
ArmOpen::Cast => {
|
|
799
|
+
Instruction::Br(1).encode(body);
|
|
800
|
+
Instruction::End.encode(body);
|
|
801
|
+
ctx.tail_depth.set(ctx.tail_depth.get() - 1);
|
|
802
|
+
Instruction::Drop.encode(body);
|
|
803
|
+
rest(body)?;
|
|
804
|
+
Instruction::End.encode(body);
|
|
805
|
+
ctx.tail_depth.set(ctx.tail_depth.get() - 1);
|
|
806
|
+
Ok(())
|
|
807
|
+
}
|
|
730
808
|
}
|
|
731
|
-
Ok(())
|
|
732
809
|
}
|
|
733
810
|
|
|
734
811
|
/// Pushes field `fpos` of the pattern container in `container_local`.
|
|
@@ -967,7 +1044,7 @@ pub(crate) fn compileFieldPatterns(
|
|
|
967
1044
|
fpos,
|
|
968
1045
|
leaf_map,
|
|
969
1046
|
);
|
|
970
|
-
|
|
1047
|
+
ctx.gc_types.emitVariantTest(n, variant_idx, body);
|
|
971
1048
|
Instruction::If(blockTypeFor(result_vt)).encode(body);
|
|
972
1049
|
let _tg = TailDepth::enter(&ctx.tail_depth);
|
|
973
1050
|
compileFieldPatterns(
|
|
@@ -1042,6 +1119,12 @@ pub(crate) fn compileFieldPatterns(
|
|
|
1042
1119
|
Instruction::End.encode(body);
|
|
1043
1120
|
Ok(())
|
|
1044
1121
|
}
|
|
1122
|
+
// A nested `Nil()`: the same test as a nested `Nil`.
|
|
1123
|
+
ast::CasePattern::Class { name, fields: inner_fields, .. } if inner_fields.is_empty() && ctx.gc_types.isNullVariant(name) => {
|
|
1124
|
+
let mut as_name = fields.to_vec();
|
|
1125
|
+
as_name[fpos] = ast::CasePattern::Name(name.clone());
|
|
1126
|
+
compileFieldPatterns(&as_name, field_types, inst_types, fpos, container_local, container_type_idx, leaf_map, rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state, on_match)
|
|
1127
|
+
}
|
|
1045
1128
|
ast::CasePattern::Class {
|
|
1046
1129
|
name,
|
|
1047
1130
|
fields: inner_fields,
|
|
@@ -1155,28 +1238,9 @@ pub(crate) fn compileFieldPatterns(
|
|
|
1155
1238
|
let inner_inst_types = instFields(info, field_ty);
|
|
1156
1239
|
let inner_field_types = inner_inst_types.clone();
|
|
1157
1240
|
|
|
1241
|
+
let open = openVariantArm(name, inner_variant_idx, decl_vt, true, nested_local, result_vt, body, ctx, &mut |b| {
|
|
1158
|
-
|
|
1242
|
+
emitContainerField(b, ctx, container_local, container_type_idx, fpos, leaf_map)
|
|
1159
|
-
body,
|
|
1160
|
-
ctx,
|
|
1161
|
-
container_local,
|
|
1162
|
-
container_type_idx,
|
|
1163
|
-
fpos,
|
|
1164
|
-
leaf_map,
|
|
1165
|
-
);
|
|
1243
|
+
})?;
|
|
1166
|
-
Instruction::RefTestNonNull(HeapType::Concrete(inner_variant_idx)).encode(body);
|
|
1167
|
-
Instruction::If(blockTypeFor(result_vt)).encode(body);
|
|
1168
|
-
let _tg = TailDepth::enter(&ctx.tail_depth);
|
|
1169
|
-
// Narrow into `nested_local` now that ref.test just above proved it's safe.
|
|
1170
|
-
emitContainerField(
|
|
1171
|
-
body,
|
|
1172
|
-
ctx,
|
|
1173
|
-
container_local,
|
|
1174
|
-
container_type_idx,
|
|
1175
|
-
fpos,
|
|
1176
|
-
leaf_map,
|
|
1177
|
-
);
|
|
1178
|
-
Instruction::RefCastNonNull(HeapType::Concrete(inner_variant_idx)).encode(body);
|
|
1179
|
-
Instruction::LocalSet(nested_local).encode(body);
|
|
1180
1244
|
let inner_leaf_map = ctx.gc_types.leafMap(inner_variant_idx);
|
|
1181
1245
|
let mut onNested = |body: &mut Vec<u8>, state: &mut ModuleState| {
|
|
1182
1246
|
compileFieldPatterns(
|
|
@@ -1214,18 +1278,9 @@ pub(crate) fn compileFieldPatterns(
|
|
|
1214
1278
|
state,
|
|
1215
1279
|
&mut onNested,
|
|
1216
1280
|
)?;
|
|
1217
|
-
Instruction::Else.encode(body);
|
|
1218
|
-
compileMatchArmsMulti(
|
|
1219
|
-
rest,
|
|
1220
|
-
all_subjects,
|
|
1221
|
-
result_vt,
|
|
1222
|
-
exhaustive_fallback,
|
|
1223
|
-
body,
|
|
1224
|
-
ctx,
|
|
1225
|
-
state,
|
|
1226
|
-
)?;
|
|
1227
|
-
|
|
1281
|
+
closeVariantArm(open, body, ctx, &mut |body| {
|
|
1282
|
+
compileMatchArmsMulti(rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state)
|
|
1228
|
-
|
|
1283
|
+
})
|
|
1229
1284
|
}
|
|
1230
1285
|
}
|
|
1231
1286
|
}
|
|
@@ -1283,7 +1338,7 @@ pub(crate) fn compileEnumUnwrap(
|
|
|
1283
1338
|
compileExpr(operand, body, ctx, state)?;
|
|
1284
1339
|
Instruction::LocalSet(scratch).encode(body);
|
|
1285
1340
|
Instruction::LocalGet(scratch).encode(body);
|
|
1286
|
-
|
|
1341
|
+
ctx.gc_types.emitVariantTest(good, good_idx, body);
|
|
1287
1342
|
Instruction::I32Eqz.encode(body);
|
|
1288
1343
|
Instruction::If(BlockType::Empty).encode(body);
|
|
1289
1344
|
if early_return {
|
|
@@ -1292,11 +1347,7 @@ pub(crate) fn compileEnumUnwrap(
|
|
|
1292
1347
|
.as_ref()
|
|
1293
1348
|
.ok_or_else(|| "codegen: `?` outside a function".to_string())?;
|
|
1294
1349
|
if kind == "Option" {
|
|
1295
|
-
let g = *ctx
|
|
1296
|
-
.singleton_globals
|
|
1297
|
-
.get(&(canonTy(rt), "None".to_string()))
|
|
1298
|
-
|
|
1350
|
+
emitSingleton(ctx.gc_types, ctx.singleton_globals, rt, "None", body)?;
|
|
1299
|
-
Instruction::GlobalGet(g).encode(body);
|
|
1300
1351
|
} else {
|
|
1301
1352
|
let err_idx = variant(bad)?;
|
|
1302
1353
|
let out_idx = ctx
|
|
@@ -1342,7 +1393,7 @@ pub(crate) fn compileEnumUnwrap(
|
|
|
1342
1393
|
Instruction::LocalGet(scratch).encode(body);
|
|
1343
1394
|
Instruction::RefCastNonNull(HeapType::Concrete(err_idx)).encode(body);
|
|
1344
1395
|
Instruction::StructGet { struct_type_index: err_idx, field_index: ctx.gc_types.fieldBase(err_idx) }.encode(body);
|
|
1345
|
-
|
|
1396
|
+
ctx.gc_types.emitVariantTest(v, *vidx, body);
|
|
1346
1397
|
Instruction::If(BlockType::Empty).encode(body);
|
|
1347
1398
|
compileStaticString(&format!("unwrap on Err({}){}", v, at), body, state);
|
|
1348
1399
|
Instruction::Call(crash_idx).encode(body);
|
compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs
CHANGED
|
@@ -242,7 +242,8 @@ fn stringInterpolationOfAFloatIsAClearError() {
|
|
|
242
242
|
assert!(err.contains("Float"), "got: {}", err);
|
|
243
243
|
}
|
|
244
244
|
|
|
245
|
-
/// The last case of a match proven exhaustive is not tested: two variants, one
|
|
245
|
+
/// The last case of a match proven exhaustive is not tested: two variants, one test, a
|
|
246
|
+
/// `br_on_cast_fail` that also narrows (no `ref.test` then `ref.cast`).
|
|
246
247
|
#[test]
|
|
247
248
|
fn lastCaseOfAnExhaustiveMatchIsNotTested() {
|
|
248
249
|
let src = "import std/Int\nimport std/App\nenum Shape =\n | Circle(r: Int)\n | Rect(w: Int, h: Int)\n\nprimitive Main[App] =\n fun areaOf(s: Shape) -> Int =\n match s\n Circle(r) => r * r * 3\n Rect(w, h) => w * h\n\n fun main() -> Int =\n Main.areaOf(Rect(w: 2, h: 5)) + Main.areaOf(Circle(r: 1))\n";
|
|
@@ -251,10 +252,30 @@ fn lastCaseOfAnExhaustiveMatchIsNotTested() {
|
|
|
251
252
|
let opts = CompileOptions { passes: plum_driver::PassOptions { fusion: false, ..Default::default() }, ..Default::default() };
|
|
252
253
|
let bytes = compile(&source, &opts).expect("compiles").wasm;
|
|
253
254
|
let ops = namedBodies(&bytes).into_iter().find(|(n, _)| n == "Main.areaOf").expect("areaOf").1;
|
|
254
|
-
assert_eq!(ops.iter().filter(|o| o.starts_with("RefTest")).count(),
|
|
255
|
+
assert_eq!(ops.iter().filter(|o| o.starts_with("RefTest")).count(), 0, "{ops:?}");
|
|
256
|
+
assert_eq!(ops.iter().filter(|o| o.starts_with("BrOnCastFail")).count(), 1, "{ops:?}");
|
|
255
257
|
assert_eq!(plum_test_support::runInt("lastcase", src), 13);
|
|
256
258
|
}
|
|
257
259
|
|
|
260
|
+
/// `Nil` is `ref.null` of `List`'s type, which is `Cons`'s struct: a match on a list is a
|
|
261
|
+
/// null test, with no `ref.test`, cast or `br_on_cast`, and making `Nil` reads no global.
|
|
262
|
+
/// A user enum of that shape (one payload-free variant) is the same.
|
|
263
|
+
#[test]
|
|
264
|
+
fn nullVariantIsRefNull() {
|
|
265
|
+
let src = "import std/Int\nimport std/collections/List\nimport std/App\nenum Chain =\n | End\n | Link(v: Int, next: Chain)\n\nprimitive Main[App] =\n fun sum(xs: List<Int>) -> Int =\n match xs\n Nil => 0\n Cons(h, t) => h + Main.sum(t)\n\n fun len(c: Chain) -> Int =\n match c\n End => 0\n Link(_, n) => 1 + Main.len(n)\n\n fun main() -> Int =\n Main.sum(Cons(head: 4, tail: Cons(head: 5, tail: Nil))) * 10 + Main.len(Link(v: 1, next: Link(v: 2, next: End)))\n";
|
|
266
|
+
let source = plum_test_support::load("nullvariant", src).expect("loads");
|
|
267
|
+
let opts = CompileOptions { passes: plum_driver::PassOptions { fusion: false, ..Default::default() }, ..Default::default() };
|
|
268
|
+
let bytes = compile(&source, &opts).expect("compiles").wasm;
|
|
269
|
+
let bodies: Vec<(String, Vec<String>)> = namedBodies(&bytes).into_iter().filter(|(n, _)| n.starts_with("Main.") || n == "main").collect();
|
|
270
|
+
assert!(bodies.len() >= 3, "{:?}", bodies.iter().map(|b| &b.0).collect::<Vec<_>>());
|
|
271
|
+
for (f, ops) in &bodies {
|
|
272
|
+
let casts = ops.iter().filter(|o| o.starts_with("RefTest") || o.starts_with("RefCast") || o.starts_with("BrOnCast")).count();
|
|
273
|
+
assert_eq!(casts, 0, "{f}: {ops:?}");
|
|
274
|
+
assert!(!ops.iter().any(|o| o.starts_with("GlobalGet")), "{f}: {ops:?}");
|
|
275
|
+
}
|
|
276
|
+
assert_eq!(plum_test_support::runInt("nullvariant", src), 92);
|
|
277
|
+
}
|
|
278
|
+
|
|
258
279
|
/// A codegen error points at the node it came out of: here the interpolation on line 3.
|
|
259
280
|
#[test]
|
|
260
281
|
fn codegenErrorCarriesThePosition() {
|
docs/backlog.md
CHANGED
|
@@ -16,7 +16,7 @@ The retained scene tree was replaced by master's screen view in functional form:
|
|
|
16
16
|
|
|
17
17
|
- **Modular checker and its cache** (user 2026-11-16: "Yes I want a modular checker", then "put it in the backlog"). Design and stages in `docs/plans/2026-11-16-modular-checker.md`: each module checked once into an artifact (a hashed interface plus body results), names fixed by the defining module, module-local node ids rebased at link, a per-program link step for trait implementers and generic instantiations, a memory and disk cache keyed by the imports' interface hashes. Stages 0-6, optional 7 (incremental re-checks in the passes). Expected: `plum check` 35-45% faster, `plum check std tests` 40-60%, the LSP most; `plum test` only 6-8% without stage 7. Today only the parse is cached (c086b705).
|
|
18
18
|
|
|
19
|
-
- **Compile-time layer** (`docs/plans/2026-11-09-comptime-generics.review.md`). The `<>` syntax, the trait list in `[]` and the trait jump table from that plan are done. Still to build: `@hasMethod`, `@hasField`, `@fields`, `@field`, `comptime if` and `comptime for`, `@compileError`, `@embedFile`, `@src`, constants computed while compiling, `comptime fun`, value generics and type aliases, default type parameters, `Option` of a reference as a nullable reference (no allocation for `Some`, allocation-free `for` loops), derives in std (`hash`, `eq`, `lerp`, JSON; `toStr` is `[Show]`, std/Str, since 2026-11-16), replay checksums with snapshot and rewind, easing and tweens in `Anim`.
|
|
19
|
+
- **Compile-time layer** (`docs/plans/2026-11-09-comptime-generics.review.md`). The `<>` syntax, the trait list in `[]` and the trait jump table from that plan are done. Still to build: `@hasMethod`, `@hasField`, `@fields`, `@field`, `comptime if` and `comptime for`, `@compileError`, `@embedFile`, `@src`, constants computed while compiling, `comptime fun`, value generics and type aliases, default type parameters, `Option` of a reference as a nullable reference (no allocation for `Some`, allocation-free `for` loops; since U4f `None`, `Nil` and the payload-free variant of any enum with only one are `ref.null` and `Some`/`Cons` need no cast, but `Some(x)` still allocates its box: making it `x` needs `Some` construction, patterns, `?`/`!`, cell reuse and spreads to treat a transparent variant, with `Option<Option<T>>` and `Option` of a nullable enum kept boxed; the fast paths since U4d make few `Some`s per tick), derives in std (`hash`, `eq`, `lerp`, JSON; `toStr` is `[Show]`, std/Str, since 2026-11-16), replay checksums with snapshot and rewind, easing and tweens in `Anim`.
|
|
20
20
|
- **Testing** (user: "All 3 please"): `group "name"` blocks with scoped helpers; compare-mode tests (one flag runs a test with and without fusion and in-place updates); property tests in std (`check(|a, b| a + b == b + a)` with generated inputs).
|
|
21
21
|
- **Constant map literals.** `[k => v]` lowers to `Map.empty().with(..)`, O(n log n). When every key is a compile-time constant, build the tree while compiling.
|
|
22
22
|
|
|
@@ -30,7 +30,7 @@ The retained scene tree was replaced by master's screen view in functional form:
|
|
|
30
30
|
- **In-place updates still miss** (recounted 2026-11-16 after U4c, `--explain-fusion`, each "not in place" line by its innermost reason): Orb Run 36 in place, 39 not (10 a value still used after the update, all the time travel's `rewindTo`/`undo`/`redo` from a fold; 8 bound to a shared value; 6 rebound by a pattern, `match self.history / Some(h)` and `Shift.after`; 5 a shared value; 3 taken out of `List.head`; 2 fields out of declaration order; 2 a receiver read again; 1 each other). Orbit Runner 31 in place of 96, Clockwork 26 of 88, Menu 20 of 86, Balloon Pop 23 of 86; the biggest reason in the four games is a receiver kept or read again after a method call (19-22, mostly the time travel and `Looping`). No closure reason is left (Balloon Pop's 5 "an argument is passed from inside a closure" went with U4c: its fold's closures are copies now), but the counts are the same as before U4c: each fix moved a spread's reason one step down. U4c added three proofs, each with a test in `uniqueness_fold_test.rs`: a field moved in one arm of a whole-body `match` (`moveRegions`: `Steer` in `PlayingScreen.update` is now a move of `self.ship`), a variable handed over through an inline `if` (`sized := if c then self.resized(p) else self`), and a field read into a local that is only read (`aliasReads`: `ship := self.ship` then `ship.body.pos`); and a pattern binder handed to a read-only parameter counts as a read. What blocks the hot ones now: `PlayingScreen.ship` is shared because the view holds the ship (`if !self.over then self.ship`), so `Ship.steer`/`step`/`hurtFor` copy; `List.head` is shared because `List.find` returns the head and `List.next` pairs it (a field's uniqueness is one fact for every element type), so the actors' steps copy; `Game.run`'s `sized` needs `Game.resized` to return its `self` in place, which `Game.remake` (shared) blocks. The Elm-style `update` regression (Orbit Runner's update 7-10% slower after the Elm screens) was not found in instructions retired here (`screen_views/orbit.plum update` 283M before U4c, 280M after).
|
|
31
31
|
- **Paint** (U4b, 2026-11-16, `sl/paint-direct`): each kind of view has its own copy of the draw's step (`View.paintAt`, `paintCulledAt`, `@final`), so an item costs one trait call in place of four; the walks recurse over the list with no closure (`List.each` with a capturing closure cost about 15% of a paint), skip the walk under an empty view, and an unturned `Place.under`, `Affine.scaleX`/`scaleY`/`rotation`, `Views.through` and a `Left` label skip the matrix product, `hypot`, `atan2` and the text width. `PLUM_NULL_GFX`'s stubs are raw host functions (a typed `Func::new` loaded every argument as a `Val`: a quarter of a timed paint). Instructions retired by the paint (paint run minus update run): Orbit Runner 2,659M to 1,087M, Clockwork (`benchmarks/screen_views/clockwork.plum`, new) 1,394M to 692M, `scale.plum` 7,750M to 2,740M; about a third of each drop is the null host. Open: wasmtime's `compiler_inlining` takes another 20% of instructions off paint and update both, but inlined frames drop out of a crash's `in f (called from g)` (`crash_in_a_loop_names_the_function_not_its_lifted_loop` fails), so it is off; still made each frame: the view's list (spreads upcast and copied) and each item's own list; `List.each`/`map` with a capturing closure is still slow everywhere else (`Views.stepIn`, `drawnIn`).
|
|
32
32
|
- **Closures inlined by size** (U4c, 2026-11-16): a callee of at most 64 expression nodes (`closure_spec::SMALL_CALLEE`; std's closure-taking fns are 3-59, `List.map` 3, `fold` 8, `Range.fold` 33, `Slice.mergeRun` 59, the biggest in the repository 68) gets a copy for every closure handed to it; a bigger one keeps a cap of 8 (`MAX_BIG_COPIES`) per callee, in the order its calls are met, so which of its calls are inlined still depends on the rest of the program. Copies made inside copies stop at 4 levels (`MAX_DEPTH`), and 256 copies of one small callee is a safety net. The escape analysis now resolves `x.m(..)` by the checker's receiver type (`FnCall.recv`, stamped before closure specialisation): `List.all` had never been specialised, as `t.all(keep)` resolved to every `all` and `Set.all` captures its closure. Cost: Orbit Runner compiles in 2.7% more instructions (8,722M to 8,957M), its .wasm is 352 bytes bigger (112,515 to 112,867). Run time within 1% in instructions retired on every benchmark (Orb Run 839M to 845M, Orbit Runner update 283M to 280M, Clockwork update 639M to 643M, `closures/calls` 3,084M to 3,083M; whole process, wasmtime's compile included).
|
|
33
|
-
- **Smaller codegen items**:
|
|
33
|
+
- **Smaller codegen items**: the inliner skips leaves that use their locals (`unbox.*`); purity treats every closure-taking function as impure, so pipelines fuse only after closure specialisation.
|
|
34
34
|
- No evidence either way, so not planned: unchecked reads in `for` over a `Slice` (checked `at` showed no cost).
|
|
35
35
|
|
|
36
36
|
## Bugs
|
tests/core/null_variants.plum
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# The payload-free variant of an enum with one such variant and others with fields (`Nil`,
|
|
2
|
+
# `None`, `Hole` below) is `ref.null` of the enum's type; with only one other variant
|
|
3
|
+
# (`Cons`, `Some`, `Leaf`) the enum's type is that variant's struct. Matching, nesting,
|
|
4
|
+
# generic code, `Option<Option<T>>`, `==`, `toStr`, `[Show]` and `@sameRef` all see the
|
|
5
|
+
# variants as before.
|
|
6
|
+
import std/Int
|
|
7
|
+
import std/Str
|
|
8
|
+
import std/Bool
|
|
9
|
+
import std/Option
|
|
10
|
+
import std/collections/List
|
|
11
|
+
import std/Test
|
|
12
|
+
|
|
13
|
+
# Two variants: the enum's type is `Leaf`'s struct.
|
|
14
|
+
enum Tree<T>[Show] =
|
|
15
|
+
| Hole
|
|
16
|
+
| Leaf(value: T, rest: Tree<T>)
|
|
17
|
+
|
|
18
|
+
# Three variants: `Gap` is null, the other two are subtypes of the enum's struct.
|
|
19
|
+
enum Shape[Show] =
|
|
20
|
+
| Gap
|
|
21
|
+
| Dot(x: Int)
|
|
22
|
+
| Bar(x: Int, len: Int)
|
|
23
|
+
|
|
24
|
+
struct Holder(t: Tree<Int>, o: Option<Shape>)
|
|
25
|
+
|
|
26
|
+
primitive NullVariants =
|
|
27
|
+
# A heap-valued const is built once; a null one too.
|
|
28
|
+
const NoShape = NullVariants.noShape()
|
|
29
|
+
const Empty = NullVariants.empty()
|
|
30
|
+
|
|
31
|
+
fun noShape() -> Option<Shape> = None
|
|
32
|
+
fun empty() -> List<Int> = Nil
|
|
33
|
+
|
|
34
|
+
fun size<T>(t: Tree<T>) -> Int = match t
|
|
35
|
+
Hole => 0
|
|
36
|
+
Leaf(_, rest) => 1 + size(rest)
|
|
37
|
+
|
|
38
|
+
fun width(s: Shape) -> Int = match s
|
|
39
|
+
Gap => 0
|
|
40
|
+
Dot(_) => 1
|
|
41
|
+
Bar(_, len) => len
|
|
42
|
+
|
|
43
|
+
# nested: a `Some` of each kind of shape, a `None`
|
|
44
|
+
fun nested(o: Option<Shape>) -> Int = match o
|
|
45
|
+
Some(Gap) => 10
|
|
46
|
+
Some(Dot(x)) => 20 + x
|
|
47
|
+
Some(Bar(x, _)) => 30 + x
|
|
48
|
+
None => 0
|
|
49
|
+
|
|
50
|
+
# `Nil()` and `Gap()` written as calls in patterns
|
|
51
|
+
fun calls(xs: List<Int>, s: Shape) -> Int = match xs, s
|
|
52
|
+
Nil(), Gap() => 1
|
|
53
|
+
Nil(), _ => 2
|
|
54
|
+
Cons(h, _), Gap() => h
|
|
55
|
+
_, _ => 4
|
|
56
|
+
|
|
57
|
+
fun depth<T>(o: Option<Option<T>>) -> Int = match o
|
|
58
|
+
None => 0
|
|
59
|
+
Some(None) => 1
|
|
60
|
+
Some(Some(_)) => 2
|
|
61
|
+
|
|
62
|
+
fun firstOr(xs: List<Option<Int>>, d: Int) -> Int = match xs
|
|
63
|
+
Cons(Some(n), _) => n
|
|
64
|
+
Cons(None, _) => -1
|
|
65
|
+
Nil => d
|
|
66
|
+
|
|
67
|
+
fun plusOne(o: Option<Int>) -> Option<Int> =
|
|
68
|
+
n := o?
|
|
69
|
+
Some(n + 1)
|
|
70
|
+
|
|
71
|
+
primitive NullVariantsTest[UnitTest] =
|
|
72
|
+
fun matchesSeeEveryVariant() =
|
|
73
|
+
assert NullVariants.size(Leaf(value: "a", rest: Leaf(value: "b", rest: Hole))) == 2
|
|
74
|
+
e: Tree<Int> := Hole
|
|
75
|
+
assert NullVariants.size(e) == 0
|
|
76
|
+
assert NullVariants.width(Gap) == 0
|
|
77
|
+
assert NullVariants.width(Dot(x: 3)) == 1
|
|
78
|
+
assert NullVariants.width(Bar(x: 1, len: 7)) == 7
|
|
79
|
+
|
|
80
|
+
fun nestedPatterns() =
|
|
81
|
+
assert NullVariants.nested(Some(Gap)) == 10
|
|
82
|
+
assert NullVariants.nested(Some(Dot(x: 2))) == 22
|
|
83
|
+
assert NullVariants.nested(Some(Bar(x: 3, len: 1))) == 33
|
|
84
|
+
assert NullVariants.nested(None) == 0
|
|
85
|
+
assert NullVariants.firstOr([Some(4)], 9) == 4
|
|
86
|
+
assert NullVariants.firstOr([None, Some(4)], 9) == -1
|
|
87
|
+
assert NullVariants.firstOr([], 9) == 9
|
|
88
|
+
|
|
89
|
+
fun constructorCallPatterns() =
|
|
90
|
+
assert NullVariants.calls([], Gap) == 1
|
|
91
|
+
assert NullVariants.calls([], Dot(x: 1)) == 2
|
|
92
|
+
assert NullVariants.calls([5], Gap) == 5
|
|
93
|
+
assert NullVariants.calls([5], Dot(x: 1)) == 4
|
|
94
|
+
|
|
95
|
+
fun optionsOfOptions() =
|
|
96
|
+
n: Option<Option<Int>> := None
|
|
97
|
+
assert NullVariants.depth(n) == 0
|
|
98
|
+
i: Option<Int> := None
|
|
99
|
+
assert NullVariants.depth(Some(i)) == 1
|
|
100
|
+
assert NullVariants.depth(Some(Some(3))) == 2
|
|
101
|
+
assert NullVariants.depth(Some(Some("s"))) == 2
|
|
102
|
+
assert Some(i) != n
|
|
103
|
+
assert Some(i) == Some(i)
|
|
104
|
+
|
|
105
|
+
fun questionMark() =
|
|
106
|
+
assert NullVariants.plusOne(Some(1)) == Some(2)
|
|
107
|
+
assert NullVariants.plusOne(None) == None
|
|
108
|
+
assert Some(5).unwrapOr(0) == 5
|
|
109
|
+
assert None.unwrapOr(7) == 7
|
|
110
|
+
|
|
111
|
+
fun equalityAndText() =
|
|
112
|
+
e: List<Int> := []
|
|
113
|
+
assert e == Nil
|
|
114
|
+
assert [1] != Nil
|
|
115
|
+
o: Option<Int> := None
|
|
116
|
+
assert o == None
|
|
117
|
+
assert o != Some(0)
|
|
118
|
+
assert Gap == Gap
|
|
119
|
+
assert Gap.toStr() == "Gap"
|
|
120
|
+
t: Tree<Int> := Hole
|
|
121
|
+
assert t.toStr() == "Hole"
|
|
122
|
+
assert Leaf(value: 1, rest: Hole).toStr() == "Leaf(1, Hole)"
|
|
123
|
+
assert "{e}" == "[]"
|
|
124
|
+
|
|
125
|
+
fun nullConsts() =
|
|
126
|
+
assert NullVariants.nested(NullVariants.NoShape) == 0
|
|
127
|
+
assert NullVariants.nested(NullVariants.NoShape) == 0
|
|
128
|
+
assert NullVariants.Empty.isEmpty()
|
|
129
|
+
assert NullVariants.Empty == []
|
|
130
|
+
|
|
131
|
+
fun inFieldsAndSameRef() =
|
|
132
|
+
h := Holder(t: Hole, o: None)
|
|
133
|
+
assert NullVariants.size(h.t) == 0
|
|
134
|
+
assert NullVariants.nested(h.o) == 0
|
|
135
|
+
h2 := Holder(..h, o: Some(Gap))
|
|
136
|
+
assert NullVariants.nested(h2.o) == 10
|
|
137
|
+
a: List<Int> := []
|
|
138
|
+
b: List<Int> := []
|
|
139
|
+
assert @sameRef(a, b)
|
|
140
|
+
c := [1]
|
|
141
|
+
assert !@sameRef(c, a)
|
|
142
|
+
assert @sameRef(c, c)
|