plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
07463f2
— Peter John
2026-11-10T11:14:01+05:30
wasm codegen: one data segment per distinct literal; long interpolations join once
- compiler/wasm-codegen/src/construct.rs +14 -5
- compiler/wasm-codegen/src/context.rs +3 -0
- compiler/wasm-codegen/src/driver.rs +113 -0
- compiler/wasm-codegen/src/gctypes.rs +5 -0
- compiler/wasm-codegen/tests/wasm_codegen/literals_test.rs +67 -0
- compiler/wasm-codegen/tests/wasm_codegen/main.rs +1 -0
- tests/core/interpolation_join.plum +31 -0
compiler/wasm-codegen/src/construct.rs
CHANGED
|
@@ -158,8 +158,11 @@ pub(crate) fn compileVariantConstruction(
|
|
|
158
158
|
/// `Str` (`wrapBytesAsStr` — see `str.plum`'s header comment on `Str`'s shape).
|
|
159
159
|
pub(crate) fn compileStaticString(text: &str, body: &mut Vec<u8>, state: &mut ModuleState) {
|
|
160
160
|
let bytes = text.as_bytes();
|
|
161
|
-
let
|
|
161
|
+
let next = state.passive_segments.len() as u32;
|
|
162
|
+
let data_index = *state.segment_ids.entry(bytes.to_vec()).or_insert(next);
|
|
163
|
+
if data_index == next {
|
|
162
|
-
|
|
164
|
+
state.passive_segments.push(bytes.to_vec());
|
|
165
|
+
}
|
|
163
166
|
let byte_array_type_idx = { let r = gcTypes(); r.byte_array_type_idx };
|
|
164
167
|
Instruction::I32Const(0).encode(body);
|
|
165
168
|
Instruction::I32Const(bytes.len() as i32).encode(body);
|
|
@@ -175,8 +178,9 @@ pub(crate) fn compileStaticString(text: &str, body: &mut Vec<u8>, state: &mut Mo
|
|
|
175
178
|
/// Every part becomes a string-pointer-valued expression (static text via
|
|
176
179
|
/// `compileStaticString`; `Str`/`Int`/`Bool`/`Float` interpolated values
|
|
177
180
|
/// converted at runtime — `Float` via `Float.toStr`, see the `TFloat` arm
|
|
178
|
-
/// below)
|
|
181
|
+
/// below). Two parts are joined with the `Str.add` method; three or more go into one
|
|
182
|
+
/// `array<Str>` for `strJoin`, which copies every part once into a buffer of the summed
|
|
179
|
-
/// `Str.add`
|
|
183
|
+
/// length (left-folding `Str.add` would copy the growing prefix again at every part).
|
|
180
184
|
pub(crate) fn compileInterpolatedString(
|
|
181
185
|
s: &ast::StringExpr,
|
|
182
186
|
body: &mut Vec<u8>,
|
|
@@ -203,6 +207,7 @@ pub(crate) fn compileInterpolatedString(
|
|
|
203
207
|
}
|
|
204
208
|
}
|
|
205
209
|
}
|
|
210
|
+
let join = gcTypes().str_join.filter(|_| parts.len() >= 3);
|
|
206
211
|
for part in parts {
|
|
207
212
|
match part {
|
|
208
213
|
ast::StringPart::Text(t) => {
|
|
@@ -266,7 +271,7 @@ pub(crate) fn compileInterpolatedString(
|
|
|
266
271
|
}
|
|
267
272
|
}
|
|
268
273
|
}
|
|
269
|
-
if !first {
|
|
274
|
+
if !first && join.is_none() {
|
|
270
275
|
let add = *ctx.func_ids.get("Str::add").ok_or_else(|| {
|
|
271
276
|
"codegen: string interpolation requires `Str.add` (import std/Str)".to_string()
|
|
272
277
|
})?;
|
|
@@ -274,5 +279,9 @@ pub(crate) fn compileInterpolatedString(
|
|
|
274
279
|
}
|
|
275
280
|
first = false;
|
|
276
281
|
}
|
|
282
|
+
if let Some((join_fn, parts_idx)) = join {
|
|
283
|
+
Instruction::ArrayNewFixed { array_type_index: parts_idx, array_size: parts.len() as u32 }.encode(body);
|
|
284
|
+
Instruction::Call(join_fn).encode(body);
|
|
285
|
+
}
|
|
277
286
|
Ok(())
|
|
278
287
|
}
|
compiler/wasm-codegen/src/context.rs
CHANGED
|
@@ -115,6 +115,9 @@ pub struct CompileCtx<'a> {
|
|
|
115
115
|
/// assembled at the end of `compileSource`.
|
|
116
116
|
pub(crate) struct ModuleState {
|
|
117
117
|
pub(crate) passive_segments: Vec<Vec<u8>>,
|
|
118
|
+
/// Index in `passive_segments` of each distinct text: a literal written many times
|
|
119
|
+
/// shares one segment.
|
|
120
|
+
pub(crate) segment_ids: HashMap<Vec<u8>, u32>,
|
|
118
121
|
}
|
|
119
122
|
|
|
120
123
|
pub(crate) struct LocalCtx<'a> {
|
compiler/wasm-codegen/src/driver.rs
CHANGED
|
@@ -661,6 +661,19 @@ impl<'a> Setup<'a> {
|
|
|
661
661
|
Instruction::End.encode(&mut b);
|
|
662
662
|
let t = module.addType(&[gcRef(gc_types.byte_array_type_idx)], &[gcRef(str_idx)]);
|
|
663
663
|
gc_types.mk_str_fn = Some(module.addFunction(t, &b));
|
|
664
|
+
let parts = module.addGcTypes(vec![SubType {
|
|
665
|
+
is_final: true,
|
|
666
|
+
supertype_idx: None,
|
|
667
|
+
composite_type: CompositeType {
|
|
668
|
+
inner: CompositeInnerType::Array(ArrayType(FieldType {
|
|
669
|
+
element_type: StorageType::Val(gcRef(str_idx)),
|
|
670
|
+
mutable: false,
|
|
671
|
+
})),
|
|
672
|
+
shared: false,
|
|
673
|
+
},
|
|
674
|
+
}])[0];
|
|
675
|
+
let join = emitStrJoin(module, str_idx, gc_types.byte_array_type_idx, parts);
|
|
676
|
+
gc_types.str_join = Some((join, parts));
|
|
664
677
|
}
|
|
665
678
|
withGen(|s| s.gc_types = Some(std::rc::Rc::new(gc_types.clone())));
|
|
666
679
|
}
|
|
@@ -972,6 +985,7 @@ impl<'a> Setup<'a> {
|
|
|
972
985
|
|
|
973
986
|
let state = ModuleState {
|
|
974
987
|
passive_segments: Vec::new(),
|
|
988
|
+
segment_ids: HashMap::new(),
|
|
975
989
|
};
|
|
976
990
|
Emit {
|
|
977
991
|
source,
|
|
@@ -984,3 +998,102 @@ impl<'a> Setup<'a> {
|
|
|
984
998
|
}
|
|
985
999
|
}
|
|
986
1000
|
}
|
|
1001
|
+
|
|
1002
|
+
/// `strJoin(parts: array<Str>) -> Str`: sums the parts' lengths, allocates one byte array
|
|
1003
|
+
/// of that size, copies each part's bytes in, and wraps it as a `Str` (`Str(data, start,
|
|
1004
|
+
/// len)`, `start`/`len` as `i64`).
|
|
1005
|
+
fn emitStrJoin(module: &mut WasmModule, str_idx: u32, bytes_idx: u32, parts_idx: u32) -> u32 {
|
|
1006
|
+
// Locals: 0 parts, 1 i, 2 n, 3 total (then the write offset), 4 out, 5 part.
|
|
1007
|
+
let mut b = Vec::new();
|
|
1008
|
+
3u32.encode(&mut b);
|
|
1009
|
+
3u32.encode(&mut b);
|
|
1010
|
+
ValType::I32.encode(&mut b);
|
|
1011
|
+
1u32.encode(&mut b);
|
|
1012
|
+
gcRef(bytes_idx).encode(&mut b);
|
|
1013
|
+
1u32.encode(&mut b);
|
|
1014
|
+
gcRef(str_idx).encode(&mut b);
|
|
1015
|
+
let field = |n: u32| Instruction::StructGet { struct_type_index: str_idx, field_index: n };
|
|
1016
|
+
let partLen = |b: &mut Vec<u8>| {
|
|
1017
|
+
field(2).encode(b);
|
|
1018
|
+
Instruction::I32WrapI64.encode(b);
|
|
1019
|
+
};
|
|
1020
|
+
let i = |b: &mut Vec<u8>| Instruction::LocalGet(1).encode(b);
|
|
1021
|
+
let next = |b: &mut Vec<u8>| {
|
|
1022
|
+
Instruction::LocalGet(1).encode(b);
|
|
1023
|
+
Instruction::I32Const(1).encode(b);
|
|
1024
|
+
Instruction::I32Add.encode(b);
|
|
1025
|
+
Instruction::LocalSet(1).encode(b);
|
|
1026
|
+
};
|
|
1027
|
+
// n = parts.len
|
|
1028
|
+
Instruction::LocalGet(0).encode(&mut b);
|
|
1029
|
+
Instruction::ArrayLen.encode(&mut b);
|
|
1030
|
+
Instruction::LocalSet(2).encode(&mut b);
|
|
1031
|
+
// total = sum of the parts' lengths
|
|
1032
|
+
Instruction::Block(BlockType::Empty).encode(&mut b);
|
|
1033
|
+
Instruction::Loop(BlockType::Empty).encode(&mut b);
|
|
1034
|
+
i(&mut b);
|
|
1035
|
+
Instruction::LocalGet(2).encode(&mut b);
|
|
1036
|
+
Instruction::I32GeU.encode(&mut b);
|
|
1037
|
+
Instruction::BrIf(1).encode(&mut b);
|
|
1038
|
+
Instruction::LocalGet(3).encode(&mut b);
|
|
1039
|
+
Instruction::LocalGet(0).encode(&mut b);
|
|
1040
|
+
i(&mut b);
|
|
1041
|
+
Instruction::ArrayGet(parts_idx).encode(&mut b);
|
|
1042
|
+
partLen(&mut b);
|
|
1043
|
+
Instruction::I32Add.encode(&mut b);
|
|
1044
|
+
Instruction::LocalSet(3).encode(&mut b);
|
|
1045
|
+
next(&mut b);
|
|
1046
|
+
Instruction::Br(0).encode(&mut b);
|
|
1047
|
+
Instruction::End.encode(&mut b);
|
|
1048
|
+
Instruction::End.encode(&mut b);
|
|
1049
|
+
// out = a byte array of that size; i = 0, total becomes the write offset
|
|
1050
|
+
Instruction::LocalGet(3).encode(&mut b);
|
|
1051
|
+
Instruction::ArrayNewDefault(bytes_idx).encode(&mut b);
|
|
1052
|
+
Instruction::LocalSet(4).encode(&mut b);
|
|
1053
|
+
Instruction::I32Const(0).encode(&mut b);
|
|
1054
|
+
Instruction::LocalSet(1).encode(&mut b);
|
|
1055
|
+
Instruction::I32Const(0).encode(&mut b);
|
|
1056
|
+
Instruction::LocalSet(3).encode(&mut b);
|
|
1057
|
+
Instruction::Block(BlockType::Empty).encode(&mut b);
|
|
1058
|
+
Instruction::Loop(BlockType::Empty).encode(&mut b);
|
|
1059
|
+
i(&mut b);
|
|
1060
|
+
Instruction::LocalGet(2).encode(&mut b);
|
|
1061
|
+
Instruction::I32GeU.encode(&mut b);
|
|
1062
|
+
Instruction::BrIf(1).encode(&mut b);
|
|
1063
|
+
Instruction::LocalGet(0).encode(&mut b);
|
|
1064
|
+
i(&mut b);
|
|
1065
|
+
Instruction::ArrayGet(parts_idx).encode(&mut b);
|
|
1066
|
+
Instruction::LocalSet(5).encode(&mut b);
|
|
1067
|
+
// array.copy out[offset..] <- part.data[part.start .. part.start + part.len]
|
|
1068
|
+
Instruction::LocalGet(4).encode(&mut b);
|
|
1069
|
+
Instruction::LocalGet(3).encode(&mut b);
|
|
1070
|
+
Instruction::LocalGet(5).encode(&mut b);
|
|
1071
|
+
field(0).encode(&mut b);
|
|
1072
|
+
Instruction::LocalGet(5).encode(&mut b);
|
|
1073
|
+
field(1).encode(&mut b);
|
|
1074
|
+
Instruction::I32WrapI64.encode(&mut b);
|
|
1075
|
+
Instruction::LocalGet(5).encode(&mut b);
|
|
1076
|
+
partLen(&mut b);
|
|
1077
|
+
Instruction::ArrayCopy { array_type_index_dst: bytes_idx, array_type_index_src: bytes_idx }.encode(&mut b);
|
|
1078
|
+
Instruction::LocalGet(3).encode(&mut b);
|
|
1079
|
+
Instruction::LocalGet(5).encode(&mut b);
|
|
1080
|
+
partLen(&mut b);
|
|
1081
|
+
Instruction::I32Add.encode(&mut b);
|
|
1082
|
+
Instruction::LocalSet(3).encode(&mut b);
|
|
1083
|
+
next(&mut b);
|
|
1084
|
+
Instruction::Br(0).encode(&mut b);
|
|
1085
|
+
Instruction::End.encode(&mut b);
|
|
1086
|
+
Instruction::End.encode(&mut b);
|
|
1087
|
+
// Str(data: out, start: 0, len: offset)
|
|
1088
|
+
Instruction::LocalGet(4).encode(&mut b);
|
|
1089
|
+
Instruction::RefAsNonNull.encode(&mut b);
|
|
1090
|
+
Instruction::I64Const(0).encode(&mut b);
|
|
1091
|
+
Instruction::LocalGet(3).encode(&mut b);
|
|
1092
|
+
Instruction::I64ExtendI32U.encode(&mut b);
|
|
1093
|
+
Instruction::StructNew(str_idx).encode(&mut b);
|
|
1094
|
+
Instruction::End.encode(&mut b);
|
|
1095
|
+
let t = module.addType(&[gcRef(parts_idx)], &[gcRef(str_idx)]);
|
|
1096
|
+
let f = module.addFunction(t, &b);
|
|
1097
|
+
module.nameFunction(f, "strJoin");
|
|
1098
|
+
f
|
|
1099
|
+
}
|
compiler/wasm-codegen/src/gctypes.rs
CHANGED
|
@@ -101,6 +101,10 @@ 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
|
+
/// `(strJoin fn, its parts array type)`: `strJoin(parts: array<Str>) -> Str` builds one
|
|
105
|
+
/// `Str` of all the parts, copying each once into one buffer of the summed length (an
|
|
106
|
+
/// interpolation of three or more parts); `None` when the program has no `Str`.
|
|
107
|
+
pub str_join: Option<(u32, u32)>,
|
|
104
108
|
/// `$Obj`, `(sub (struct (field i32)))`: the type of every trait object, and the
|
|
105
109
|
/// supertype of every type that implements a trait. Its one field is the value's type
|
|
106
110
|
/// tag, which a trait method call branches on (`br_table`, see `traits.rs`). `None`
|
|
@@ -275,6 +279,7 @@ pub(crate) fn buildGcTypeRegistry(
|
|
|
275
279
|
array_type_idx: 0,
|
|
276
280
|
leaf_array_idx: HashMap::new(),
|
|
277
281
|
mk_str_fn: None,
|
|
282
|
+
str_join: None,
|
|
278
283
|
obj_idx: None,
|
|
279
284
|
trait_names: HashSet::new(),
|
|
280
285
|
tags: HashMap::new(),
|
compiler/wasm-codegen/tests/wasm_codegen/literals_test.rs
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
//! String literals in the module: one data segment per distinct text.
|
|
2
|
+
|
|
3
|
+
use plum_test_support::{compile, runStr};
|
|
4
|
+
|
|
5
|
+
/// The module's passive data segments, in order.
|
|
6
|
+
fn segments(bytes: &[u8]) -> Vec<Vec<u8>> {
|
|
7
|
+
let mut out = Vec::new();
|
|
8
|
+
for payload in wasmparser::Parser::new(0).parse_all(bytes) {
|
|
9
|
+
if let wasmparser::Payload::DataSection(r) = payload.unwrap() {
|
|
10
|
+
for d in r {
|
|
11
|
+
out.push(d.unwrap().data.to_vec());
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
out
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const REPEATED: &str = "\
|
|
19
|
+
import std/Int
|
|
20
|
+
import std/Str
|
|
21
|
+
|
|
22
|
+
fun tag(n: Int) -> Str =
|
|
23
|
+
if n == 0 then \"same text\" else if n == 1 then \"same text\" else \"other\"
|
|
24
|
+
|
|
25
|
+
fun main() -> Str =
|
|
26
|
+
tag(0) + tag(1) + \"same text\" + tag(2)
|
|
27
|
+
";
|
|
28
|
+
|
|
29
|
+
/// A literal written three times is one segment, and each use still reads it.
|
|
30
|
+
#[test]
|
|
31
|
+
fn repeatedLiteralSharesOneSegment() {
|
|
32
|
+
let segs = segments(&compile("dupseg", REPEATED));
|
|
33
|
+
assert_eq!(segs.iter().filter(|s| s.as_slice() == b"same text").count(), 1, "{segs:?}");
|
|
34
|
+
let mut uniq = segs.clone();
|
|
35
|
+
uniq.sort();
|
|
36
|
+
uniq.dedup();
|
|
37
|
+
assert_eq!(uniq.len(), segs.len(), "{segs:?}");
|
|
38
|
+
assert_eq!(runStr("dupseg", REPEATED), "same textsame textsame textother");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/// Every function name in the module.
|
|
42
|
+
fn names(bytes: &[u8]) -> Vec<String> {
|
|
43
|
+
let mut out = Vec::new();
|
|
44
|
+
for payload in wasmparser::Parser::new(0).parse_all(bytes) {
|
|
45
|
+
if let Ok(wasmparser::Payload::CustomSection(c)) = payload {
|
|
46
|
+
if let wasmparser::KnownCustom::Name(reader) = c.as_known() {
|
|
47
|
+
for sub in reader.flatten() {
|
|
48
|
+
if let wasmparser::Name::Function(map) = sub {
|
|
49
|
+
out.extend(map.into_iter().flatten().map(|n| n.name.to_string()));
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
out
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/// Three or more parts build one buffer with `strJoin`; two parts keep `Str.add`.
|
|
59
|
+
#[test]
|
|
60
|
+
fn longInterpolationJoinsOnce() {
|
|
61
|
+
let long = "import std/Int\nimport std/Str\n\nfun show(a: Str, n: Int) -> Str =\n \"<{a}:{n}>\"\n\nfun main() -> Str =\n show(\"k\", 42)\n";
|
|
62
|
+
assert!(names(&compile("join3", long)).iter().any(|n| n == "strJoin"));
|
|
63
|
+
assert_eq!(runStr("join3", long), "<k:42>");
|
|
64
|
+
let short = "import std/Int\nimport std/Str\n\nfun show(a: Str) -> Str =\n \"<{a}\"\n\nfun main() -> Str =\n show(\"k\")\n";
|
|
65
|
+
assert!(!names(&compile("join2", short)).iter().any(|n| n == "strJoin"));
|
|
66
|
+
assert_eq!(runStr("join2", short), "<k");
|
|
67
|
+
}
|
compiler/wasm-codegen/tests/wasm_codegen/main.rs
CHANGED
|
@@ -8,5 +8,6 @@ mod e2e_tail;
|
|
|
8
8
|
mod e2e_types;
|
|
9
9
|
mod examples_test;
|
|
10
10
|
mod fusion_alloc_test;
|
|
11
|
+
mod literals_test;
|
|
11
12
|
mod native_test;
|
|
12
13
|
mod optimize_test;
|
tests/core/interpolation_join.plum
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Str
|
|
3
|
+
import std/Float
|
|
4
|
+
|
|
5
|
+
# An interpolation of three or more parts is built in one buffer of the summed length
|
|
6
|
+
# (`strJoin`): every part lands in order, views into other strings (a `sub` with a non-zero
|
|
7
|
+
# start) copy only their own bytes, and empty parts add nothing.
|
|
8
|
+
|
|
9
|
+
fun describe(name: Str, n: Int, ok: Bool) -> Str =
|
|
10
|
+
"{name} has {n} items, ok={ok}!"
|
|
11
|
+
|
|
12
|
+
test "several parts join in order"
|
|
13
|
+
assert describe("box", 3, true) == "box has 3 items, ok=true!"
|
|
14
|
+
assert describe("", -12, false) == " has -12 items, ok=false!"
|
|
15
|
+
|
|
16
|
+
test "a view into another string copies only its own bytes"
|
|
17
|
+
word := "xxhelloyy".sub(2, 7)
|
|
18
|
+
assert "<{word}|{word}>" == "<hello|hello>"
|
|
19
|
+
assert "<{word}|{word}>".length() == 13
|
|
20
|
+
|
|
21
|
+
test "empty parts add nothing"
|
|
22
|
+
e := ""
|
|
23
|
+
assert "{e}{e}{e}" == ""
|
|
24
|
+
assert "{e}a{e}b{e}" == "ab"
|
|
25
|
+
|
|
26
|
+
test "two parts still join"
|
|
27
|
+
assert "n={1}" == "n=1"
|
|
28
|
+
assert "{2}{3}" == "23"
|
|
29
|
+
|
|
30
|
+
test "a float part"
|
|
31
|
+
assert "x={1.5}, y={2}" == "x=1.5, y=2"
|