plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
f4569b2
— Peter John
2026-11-16T21:31:30+05:30
U4d part 2: literal strings in globals, interpolation in one exact-size buffer
- compiler/wasm-codegen/src/construct.rs +16 -18
- compiler/wasm-codegen/src/context.rs +4 -0
- compiler/wasm-codegen/src/driver.rs +64 -0
- compiler/wasm-codegen/src/emit.rs +34 -4
- compiler/wasm-codegen/src/gctypes.rs +4 -0
- compiler/wasm-codegen/tests/wasm_codegen/literals_test.rs +12 -4
- docs/language.md +1 -1
- std/Int.plum +41 -17
- tests/core/interpolation_join.plum +43 -3
compiler/wasm-codegen/src/construct.rs
CHANGED
|
@@ -152,10 +152,11 @@ pub(crate) fn compileVariantConstruction(
|
|
|
152
152
|
Ok(())
|
|
153
153
|
}
|
|
154
154
|
|
|
155
|
-
/// Emits a static (compile-time-known) string literal
|
|
155
|
+
/// Emits a static (compile-time-known) string literal: a read of the global that holds
|
|
156
|
-
///
|
|
156
|
+
/// its one `Str`. Each distinct text is a passive data segment, and its global is made
|
|
157
|
+
/// from it once, before the start function runs (`Emit::addPassiveSegments`), so a
|
|
157
|
-
///
|
|
158
|
+
/// literal costs nothing where it is evaluated. A `Str` is never written to, and a literal
|
|
158
|
-
///
|
|
159
|
+
/// is never taken as a fresh value (the in-place passes), so one object serves every use.
|
|
159
160
|
pub(crate) fn compileStaticString(text: &str, body: &mut Vec<u8>, state: &mut ModuleState) {
|
|
160
161
|
let bytes = text.as_bytes();
|
|
161
162
|
let next = state.passive_segments.len() as u32;
|
|
@@ -163,15 +164,7 @@ pub(crate) fn compileStaticString(text: &str, body: &mut Vec<u8>, state: &mut Mo
|
|
|
163
164
|
if data_index == next {
|
|
164
165
|
state.passive_segments.push(bytes.to_vec());
|
|
165
166
|
}
|
|
166
|
-
let byte_array_type_idx = { let r = gcTypes(); r.byte_array_type_idx };
|
|
167
|
-
Instruction::I32Const(0).encode(body);
|
|
168
|
-
Instruction::
|
|
167
|
+
Instruction::GlobalGet(state.str_global_base + data_index).encode(body);
|
|
169
|
-
Instruction::ArrayNewData {
|
|
170
|
-
array_type_index: byte_array_type_idx,
|
|
171
|
-
array_data_index: data_index,
|
|
172
|
-
}
|
|
173
|
-
.encode(body);
|
|
174
|
-
wrapBytesAsStr(body);
|
|
175
168
|
}
|
|
176
169
|
|
|
177
170
|
/// Whether the interpolated `e`, of type `ty`, has a `toStr` to call: its type's own method,
|
|
@@ -186,9 +179,10 @@ fn hasToStr(e: &ast::Expr, ty: &PlumType, ctx: &LocalCtx) -> bool {
|
|
|
186
179
|
/// Every part becomes a string-pointer-valued expression (static text via
|
|
187
180
|
/// `compileStaticString`; `Str`/`Int`/`Bool`/`Float` interpolated values
|
|
188
181
|
/// converted at runtime — `Float` via `Float.toStr`, see the `TFloat` arm
|
|
182
|
+
/// below). Up to `STR_JOIN_MAX_PARAMS` parts are passed to `strJoin<n>`, which copies every
|
|
189
|
-
///
|
|
183
|
+
/// part once into one buffer of the summed length (left-folding `Str.concat` would copy the
|
|
190
|
-
/// `array<Str>` for `strJoin`, which copies every part once into a buffer of the summed
|
|
191
|
-
///
|
|
184
|
+
/// growing prefix again at every part); more go into one `array<Str>` for `strJoin`, which
|
|
185
|
+
/// does the same.
|
|
192
186
|
pub(crate) fn compileInterpolatedString(
|
|
193
187
|
s: &ast::StringExpr,
|
|
194
188
|
body: &mut Vec<u8>,
|
|
@@ -214,7 +208,8 @@ pub(crate) fn compileInterpolatedString(
|
|
|
214
208
|
}
|
|
215
209
|
}
|
|
216
210
|
}
|
|
211
|
+
let joinN = gcTypes().str_join_n.get(parts.len().wrapping_sub(2)).copied();
|
|
217
|
-
let join = gcTypes().str_join.filter(|_| parts.len() >= 3);
|
|
212
|
+
let join = gcTypes().str_join.filter(|_| joinN.is_none() && parts.len() >= 3);
|
|
218
213
|
for part in parts {
|
|
219
214
|
match part {
|
|
220
215
|
ast::StringPart::Text(t) => {
|
|
@@ -276,7 +271,7 @@ pub(crate) fn compileInterpolatedString(
|
|
|
276
271
|
}
|
|
277
272
|
}
|
|
278
273
|
}
|
|
279
|
-
if !first && join.is_none() {
|
|
274
|
+
if !first && join.is_none() && joinN.is_none() {
|
|
280
275
|
let add = *ctx.func_ids.get("Str::concat").ok_or_else(|| {
|
|
281
276
|
"codegen: string interpolation requires `Str.concat` (import std/Str)".to_string()
|
|
282
277
|
})?;
|
|
@@ -284,6 +279,9 @@ pub(crate) fn compileInterpolatedString(
|
|
|
284
279
|
}
|
|
285
280
|
first = false;
|
|
286
281
|
}
|
|
282
|
+
if let Some(f) = joinN {
|
|
283
|
+
Instruction::Call(f).encode(body);
|
|
284
|
+
}
|
|
287
285
|
if let Some((join_fn, parts_idx)) = join {
|
|
288
286
|
Instruction::ArrayNewFixed { array_type_index: parts_idx, array_size: parts.len() as u32 }.encode(body);
|
|
289
287
|
Instruction::Call(join_fn).encode(body);
|
compiler/wasm-codegen/src/context.rs
CHANGED
|
@@ -125,6 +125,10 @@ pub(crate) struct ModuleState {
|
|
|
125
125
|
/// Index in `passive_segments` of each distinct text: a literal written many times
|
|
126
126
|
/// shares one segment.
|
|
127
127
|
pub(crate) segment_ids: HashMap<Vec<u8>, u32>,
|
|
128
|
+
/// The global holding the `Str` of `passive_segments[i]` is `str_global_base + i`: the
|
|
129
|
+
/// globals after every one `Setup` adds, made with the segments (`addPassiveSegments`)
|
|
130
|
+
/// and filled before the start function runs.
|
|
131
|
+
pub(crate) str_global_base: u32,
|
|
128
132
|
}
|
|
129
133
|
|
|
130
134
|
pub(crate) struct LocalCtx<'a> {
|
compiler/wasm-codegen/src/driver.rs
CHANGED
|
@@ -717,6 +717,7 @@ impl<'a> Setup<'a> {
|
|
|
717
717
|
}])[0];
|
|
718
718
|
let join = emitStrJoin(module, str_idx, gc_types.byte_array_type_idx, parts);
|
|
719
719
|
gc_types.str_join = Some((join, parts));
|
|
720
|
+
gc_types.str_join_n = (2..=STR_JOIN_MAX_PARAMS).map(|n| emitStrJoinN(module, str_idx, gc_types.byte_array_type_idx, n)).collect();
|
|
720
721
|
}
|
|
721
722
|
withGen(|s| s.gc_types = Some(std::rc::Rc::new(gc_types.clone())));
|
|
722
723
|
}
|
|
@@ -1016,6 +1017,7 @@ impl<'a> Setup<'a> {
|
|
|
1016
1017
|
let state = ModuleState {
|
|
1017
1018
|
passive_segments: Vec::new(),
|
|
1018
1019
|
segment_ids: HashMap::new(),
|
|
1020
|
+
str_global_base: module.global_count,
|
|
1019
1021
|
};
|
|
1020
1022
|
Emit {
|
|
1021
1023
|
source,
|
|
@@ -1128,6 +1130,68 @@ fn emitStrJoin(module: &mut WasmModule, str_idx: u32, bytes_idx: u32, parts_idx:
|
|
|
1128
1130
|
f
|
|
1129
1131
|
}
|
|
1130
1132
|
|
|
1133
|
+
/// The most parts an interpolation joins through a `strJoin<n>` of parameters; one of more
|
|
1134
|
+
/// parts goes through `strJoin`'s array.
|
|
1135
|
+
pub(crate) const STR_JOIN_MAX_PARAMS: u32 = 8;
|
|
1136
|
+
|
|
1137
|
+
/// `strJoin<n>(p0: Str, .., p<n-1>: Str) -> Str`: `strJoin` with its parts as parameters, so an
|
|
1138
|
+
/// interpolation of up to `STR_JOIN_MAX_PARAMS` parts allocates its bytes once, of the summed
|
|
1139
|
+
/// length, and its `Str`, and nothing else.
|
|
1140
|
+
fn emitStrJoinN(module: &mut WasmModule, str_idx: u32, bytes_idx: u32, n: u32) -> u32 {
|
|
1141
|
+
// Locals after the n parameters: total, offset (i32), out.
|
|
1142
|
+
let (total, off, out) = (n, n + 1, n + 2);
|
|
1143
|
+
let mut b = Vec::new();
|
|
1144
|
+
2u32.encode(&mut b);
|
|
1145
|
+
2u32.encode(&mut b);
|
|
1146
|
+
ValType::I32.encode(&mut b);
|
|
1147
|
+
1u32.encode(&mut b);
|
|
1148
|
+
gcRef(bytes_idx).encode(&mut b);
|
|
1149
|
+
let field = |b: &mut Vec<u8>, k: u32| Instruction::StructGet { struct_type_index: str_idx, field_index: k }.encode(b);
|
|
1150
|
+
let partLen = |b: &mut Vec<u8>, p: u32| {
|
|
1151
|
+
Instruction::LocalGet(p).encode(b);
|
|
1152
|
+
field(b, 2);
|
|
1153
|
+
Instruction::I32WrapI64.encode(b);
|
|
1154
|
+
};
|
|
1155
|
+
partLen(&mut b, 0);
|
|
1156
|
+
for p in 1..n {
|
|
1157
|
+
partLen(&mut b, p);
|
|
1158
|
+
Instruction::I32Add.encode(&mut b);
|
|
1159
|
+
}
|
|
1160
|
+
Instruction::LocalTee(total).encode(&mut b);
|
|
1161
|
+
Instruction::ArrayNewDefault(bytes_idx).encode(&mut b);
|
|
1162
|
+
Instruction::LocalSet(out).encode(&mut b);
|
|
1163
|
+
for p in 0..n {
|
|
1164
|
+
// array.copy out[off..] <- p.data[p.start .. p.start + p.len]
|
|
1165
|
+
Instruction::LocalGet(out).encode(&mut b);
|
|
1166
|
+
Instruction::LocalGet(off).encode(&mut b);
|
|
1167
|
+
Instruction::LocalGet(p).encode(&mut b);
|
|
1168
|
+
field(&mut b, 0);
|
|
1169
|
+
Instruction::LocalGet(p).encode(&mut b);
|
|
1170
|
+
field(&mut b, 1);
|
|
1171
|
+
Instruction::I32WrapI64.encode(&mut b);
|
|
1172
|
+
partLen(&mut b, p);
|
|
1173
|
+
Instruction::ArrayCopy { array_type_index_dst: bytes_idx, array_type_index_src: bytes_idx }.encode(&mut b);
|
|
1174
|
+
if p + 1 < n {
|
|
1175
|
+
Instruction::LocalGet(off).encode(&mut b);
|
|
1176
|
+
partLen(&mut b, p);
|
|
1177
|
+
Instruction::I32Add.encode(&mut b);
|
|
1178
|
+
Instruction::LocalSet(off).encode(&mut b);
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
Instruction::LocalGet(out).encode(&mut b);
|
|
1182
|
+
Instruction::RefAsNonNull.encode(&mut b);
|
|
1183
|
+
Instruction::I64Const(0).encode(&mut b);
|
|
1184
|
+
Instruction::LocalGet(total).encode(&mut b);
|
|
1185
|
+
Instruction::I64ExtendI32U.encode(&mut b);
|
|
1186
|
+
Instruction::StructNew(str_idx).encode(&mut b);
|
|
1187
|
+
Instruction::End.encode(&mut b);
|
|
1188
|
+
let params: Vec<ValType> = (0..n).map(|_| gcRef(str_idx)).collect();
|
|
1189
|
+
let t = module.addType(¶ms, &[gcRef(str_idx)]);
|
|
1190
|
+
let f = module.addFunction(t, &b);
|
|
1191
|
+
module.nameFunction(f, &format!("strJoin{n}"));
|
|
1192
|
+
f
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1131
1195
|
/// A static without generics of its own (`Recursion.dec`): one wasm function, so it can be
|
|
1132
1196
|
/// used as a value (`call(Recursion.dec, n)`) through a trampoline like a free fn.
|
|
1133
1197
|
pub(crate) fn isPlainStatic(f: &ast::Fn) -> bool {
|
compiler/wasm-codegen/src/emit.rs
CHANGED
|
@@ -124,12 +124,42 @@ impl<'a> Emit<'a> {
|
|
|
124
124
|
Ok(())
|
|
125
125
|
}
|
|
126
126
|
|
|
127
|
-
/// Add the passive data segments gathered while compiling
|
|
127
|
+
/// Add the passive data segments gathered while compiling, and the global of each
|
|
128
|
+
/// (`compileStaticString`): its `Str`, made from the segment by a function that runs
|
|
129
|
+
/// at instantiation and then calls the start function.
|
|
128
130
|
pub(crate) fn addPassiveSegments(&mut self) {
|
|
129
|
-
let Emit { module, state, .. } = self;
|
|
131
|
+
let Emit { module, state, ctx, .. } = self;
|
|
130
|
-
|
|
132
|
+
if state.passive_segments.is_empty() {
|
|
131
|
-
|
|
133
|
+
return;
|
|
132
134
|
}
|
|
135
|
+
let bytes_idx = ctx.gc_types.byte_array_type_idx;
|
|
136
|
+
let (str_ty, mk) = match (ctx.gc_types.class_type_idx.get(ast::STR_TYPE), ctx.gc_types.mk_str_fn) {
|
|
137
|
+
(Some(&s), Some(mk)) => (s, Some(mk)),
|
|
138
|
+
_ => (bytes_idx, None),
|
|
139
|
+
};
|
|
140
|
+
let mut init = vec![0u8];
|
|
141
|
+
for (i, bytes) in state.passive_segments.iter().enumerate() {
|
|
142
|
+
let segment = module.addPassiveDataSegment(bytes);
|
|
143
|
+
let mut null = Vec::new();
|
|
144
|
+
Instruction::RefNull(HeapType::Concrete(str_ty)).encode(&mut null);
|
|
145
|
+
let global = module.addGlobal(gcRef(str_ty), true, &null);
|
|
146
|
+
assert_eq!(global, state.str_global_base + i as u32, "a string literal's global comes after every other");
|
|
147
|
+
Instruction::I32Const(0).encode(&mut init);
|
|
148
|
+
Instruction::I32Const(bytes.len() as i32).encode(&mut init);
|
|
149
|
+
Instruction::ArrayNewData { array_type_index: bytes_idx, array_data_index: segment }.encode(&mut init);
|
|
150
|
+
if let Some(mk) = mk {
|
|
151
|
+
Instruction::Call(mk).encode(&mut init);
|
|
152
|
+
}
|
|
153
|
+
Instruction::GlobalSet(global).encode(&mut init);
|
|
154
|
+
}
|
|
155
|
+
if let Some(start) = module.start_function {
|
|
156
|
+
Instruction::Call(start).encode(&mut init);
|
|
157
|
+
}
|
|
158
|
+
Instruction::End.encode(&mut init);
|
|
159
|
+
let t = module.addType(&[], &[]);
|
|
160
|
+
let f = module.addFunction(t, &init);
|
|
161
|
+
module.nameFunction(f, "strings");
|
|
162
|
+
module.setStartFunction(f);
|
|
133
163
|
}
|
|
134
164
|
|
|
135
165
|
/// Entry points (`main`, `export fun`, `test`) and their `Io` wrappers.
|
compiler/wasm-codegen/src/gctypes.rs
CHANGED
|
@@ -109,6 +109,9 @@ pub struct GcTypeRegistry {
|
|
|
109
109
|
/// `Str` of all the parts, copying each once into one buffer of the summed length (an
|
|
110
110
|
/// interpolation of three or more parts); `None` when the program has no `Str`.
|
|
111
111
|
pub str_join: Option<(u32, u32)>,
|
|
112
|
+
/// `strJoin2` .. `strJoin8`: the same join for a fixed number of parts taken as
|
|
113
|
+
/// parameters (index 0 is 2 parts), with no parts array; empty when there is no `Str`.
|
|
114
|
+
pub str_join_n: Vec<u32>,
|
|
112
115
|
/// `$Obj`, `(sub (struct (field i32)))`: the type of every trait object, and the
|
|
113
116
|
/// supertype of every type that implements a trait. Its one field is the value's type
|
|
114
117
|
/// tag, which a trait method call branches on (`br_table`, see `traits.rs`). `None`
|
|
@@ -351,6 +354,7 @@ pub(crate) fn buildGcTypeRegistry(
|
|
|
351
354
|
leaf_array_idx: HashMap::new(),
|
|
352
355
|
mk_str_fn: None,
|
|
353
356
|
str_join: None,
|
|
357
|
+
str_join_n: Vec::new(),
|
|
354
358
|
obj_idx: None,
|
|
355
359
|
trait_names: HashSet::new(),
|
|
356
360
|
tags: HashMap::new(),
|
compiler/wasm-codegen/tests/wasm_codegen/literals_test.rs
CHANGED
|
@@ -49,13 +49,21 @@ fn names(bytes: &[u8]) -> Vec<String> {
|
|
|
49
49
|
out
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
+
/// An interpolation builds one buffer: up to eight parts through `strJoin<n>` (the parts as
|
|
52
|
-
///
|
|
53
|
+
/// parameters), more through `strJoin` (an array of them); none calls `Str.concat`. Its
|
|
54
|
+
/// literal pieces are globals made once by the `strings` start function.
|
|
53
55
|
#[test]
|
|
54
56
|
fn longInterpolationJoinsOnce() {
|
|
55
57
|
let long = "import std/Int\nimport std/Str\nimport std/App\nprimitive Main[App] =\n fun show(a: Str, n: Int) -> Str =\n \"<{a}:{n}>\"\n\n fun main() -> Str =\n Main.show(\"k\", 42)\n";
|
|
56
|
-
|
|
58
|
+
let ns = names(&compile("join5", long));
|
|
59
|
+
assert!(ns.iter().any(|n| n == "strJoin5"), "{ns:?}");
|
|
60
|
+
assert!(ns.iter().any(|n| n == "strings"), "{ns:?}");
|
|
61
|
+
assert!(!ns.iter().any(|n| n == "Str.concat"), "{ns:?}");
|
|
57
|
-
assert_eq!(runStr("
|
|
62
|
+
assert_eq!(runStr("join5", long), "<k:42>");
|
|
58
63
|
let short = "import std/Int\nimport std/Str\nimport std/App\nprimitive Main[App] =\n fun show(a: Str) -> Str =\n \"<{a}\"\n\n fun main() -> Str =\n Main.show(\"k\")\n";
|
|
59
|
-
assert!(
|
|
64
|
+
assert!(names(&compile("join2", short)).iter().any(|n| n == "strJoin2"));
|
|
60
65
|
assert_eq!(runStr("join2", short), "<k");
|
|
66
|
+
let nine = "import std/Int\nimport std/Str\nimport std/App\nprimitive Main[App] =\n fun show(a: Str) -> Str =\n \"{a}1{a}2{a}3{a}4{a}\"\n\n fun main() -> Str =\n Main.show(\"k\")\n";
|
|
67
|
+
assert!(names(&compile("join9", nine)).iter().any(|n| n == "strJoin"));
|
|
68
|
+
assert_eq!(runStr("join9", nine), "k1k2k3k4k");
|
|
61
69
|
}
|
docs/language.md
CHANGED
|
@@ -76,7 +76,7 @@ primitive Greeting =
|
|
|
76
76
|
"Hello, {name}! Your name has {name.length()} letters."
|
|
77
77
|
```
|
|
78
78
|
|
|
79
|
-
`Str` has no `+`: build strings with interpolation, `"{a}{b}"` rather than `a + b` (`a + b` on a `Str` is a type error that says so), or call `a.concat(b)`. `Int`, `Float`, `Bool` and any type with a `toStr` method interpolate directly. Write `{{` and `}}` for literal braces.
|
|
79
|
+
`Str` has no `+`: build strings with interpolation, `"{a}{b}"` rather than `a + b` (`a + b` on a `Str` is a type error that says so), or call `a.concat(b)`. `Int`, `Float`, `Bool` and any type with a `toStr` method interpolate directly. Write `{{` and `}}` for literal braces. An interpolation makes its text in one buffer of the exact length, copying each part once, and a literal's text is made once, when the program starts, so reading `"done"` in a loop costs nothing (one `Str` serves every read: `@sameRef` of two reads of it is true).
|
|
80
80
|
|
|
81
81
|
**Grouping** uses `{ }`, because `( )` is only for calls:
|
|
82
82
|
|
std/Int.plum
CHANGED
|
@@ -7,6 +7,7 @@ import std/Pair
|
|
|
7
7
|
import std/Option
|
|
8
8
|
import std/Result
|
|
9
9
|
import std/Array
|
|
10
|
+
import std/Byte
|
|
10
11
|
import std/collections/List
|
|
11
12
|
|
|
12
13
|
# Why `Int.parse` / `Float.parse` failed: not a number, or one past Int's range.
|
|
@@ -157,26 +158,35 @@ primitive Int =
|
|
|
157
158
|
|
|
158
159
|
# Plain decimal rendering of an `Int` — factored out of `Float.toStr` so the
|
|
159
160
|
# `Float` branch can reuse it (via `intToStr(whole_part)`) without
|
|
160
|
-
# re-dispatching back through `Float.toStr` itself.
|
|
161
|
+
# re-dispatching back through `Float.toStr` itself. The digits are written into one
|
|
161
|
-
#
|
|
162
|
+
# byte array of the exact length, from the last; a negative `n` is never negated, so
|
|
162
|
-
# overflows back to itself) prints as `-9223372036854775808`.
|
|
163
|
+
# `Int.Min` (whose negation overflows back to itself) prints as `-9223372036854775808`.
|
|
163
164
|
fun intToStr(n: Int) -> Str =
|
|
164
165
|
if n == 0
|
|
165
166
|
"0"
|
|
166
|
-
else if n < 0
|
|
167
|
-
"-{digitsToStr(-{n / 10})}{digitChar(-{n % 10})}"
|
|
168
167
|
else
|
|
168
|
+
len := if n < 0 then digitCount(n) + 1 else digitCount(n)
|
|
169
|
+
out := Array<Byte>().resize(len)
|
|
170
|
+
if n < 0
|
|
171
|
+
out.set(0, Byte(45))
|
|
169
|
-
|
|
172
|
+
writeDigits(out, len - 1, n)
|
|
170
|
-
|
|
173
|
+
Str(data: out, start: 0, len: len)
|
|
174
|
+
|
|
175
|
+
# How many decimal digits `n` has (1 for 0), its sign aside.
|
|
176
|
+
fun digitCount(n: Int) -> Int =
|
|
177
|
+
if n > -10 && n < 10 then 1 else 1 + digitCount(n / 10)
|
|
178
|
+
|
|
179
|
+
# Writes the digits of `n` (its sign aside) into `out`, the last at `i`, then each
|
|
180
|
+
# before it.
|
|
181
|
+
fun writeDigits(out: Array<Byte>, i: Int, n: Int) =
|
|
182
|
+
d := n % 10
|
|
183
|
+
out.set(i, Byte(48 + {if d < 0 then -d else d}))
|
|
184
|
+
if n / 10 != 0
|
|
185
|
+
writeDigits(out, i - 1, n / 10)
|
|
186
|
+
|
|
171
|
-
#
|
|
187
|
+
# The decimal digits of a positive Int, most significant first ("" for 0).
|
|
172
|
-
# peeling off one digit at a time from the least significant end (so the
|
|
173
|
-
# recursion emits digits in reverse call order — the leading, smallest-place
|
|
174
|
-
# digit is appended last).
|
|
175
188
|
fun digitsToStr(n: Int) -> Str =
|
|
176
|
-
if n == 0
|
|
177
|
-
""
|
|
178
|
-
else
|
|
179
|
-
|
|
189
|
+
if n == 0 then "" else intToStr(n)
|
|
180
190
|
|
|
181
191
|
fun digitChar(d: Int) -> Str =
|
|
182
192
|
match d
|
|
@@ -194,12 +204,26 @@ primitive Int =
|
|
|
194
204
|
|
|
195
205
|
# Renders `n`'s digits most-significant-first, always emitting exactly as many
|
|
196
206
|
# digits as `place_value` has powers of ten (leading zeros included) — used to
|
|
197
|
-
# render a fractional part at a fixed width regardless of its own leading zeros.
|
|
207
|
+
# render a fractional part at a fixed width regardless of its own leading zeros. One
|
|
208
|
+
# byte array of the exact length; a digit out of 0-9 (a negative `n`) is a "0".
|
|
198
209
|
fun fixedFracDigits(n: Int, place_value: Int) -> Str =
|
|
199
210
|
if place_value == 0
|
|
200
211
|
""
|
|
201
212
|
else
|
|
213
|
+
len := placeCount(place_value)
|
|
214
|
+
out := Array<Byte>().resize(len)
|
|
215
|
+
writeFixed(out, 0, n, place_value)
|
|
216
|
+
Str(data: out, start: 0, len: len)
|
|
217
|
+
|
|
218
|
+
# How many times `p` can be divided by 10 before it is 0.
|
|
219
|
+
fun placeCount(p: Int) -> Int =
|
|
202
|
-
|
|
220
|
+
if p == 0 then 0 else 1 + placeCount(p / 10)
|
|
221
|
+
|
|
222
|
+
fun writeFixed(out: Array<Byte>, i: Int, n: Int, p: Int) =
|
|
223
|
+
if p != 0
|
|
224
|
+
d := n / p % 10
|
|
225
|
+
out.set(i, Byte(48 + {if d >= 0 && d <= 9 then d else 0}))
|
|
226
|
+
writeFixed(out, i + 1, n, p / 10)
|
|
203
227
|
|
|
204
228
|
fun pow10(n: Int) -> Int =
|
|
205
229
|
if n <= 0
|
tests/core/interpolation_join.plum
CHANGED
|
@@ -7,9 +7,11 @@ import std/collections/Map
|
|
|
7
7
|
import std/collections/Set
|
|
8
8
|
import std/Test
|
|
9
9
|
|
|
10
|
-
# An interpolation
|
|
10
|
+
# An interpolation is built in one buffer of the summed length (`strJoin2`..`strJoin8` for up
|
|
11
|
-
#
|
|
11
|
+
# to eight parts, `strJoin` past that): every part lands in order, views into other strings
|
|
12
|
-
# start) copy only their own bytes, and empty parts add nothing.
|
|
12
|
+
# (a `sub` with a non-zero start) copy only their own bytes, and empty parts add nothing. Its
|
|
13
|
+
# literal pieces are each one `Str`, made once (a global), and an `Int` part is written into
|
|
14
|
+
# one array of its exact length.
|
|
13
15
|
|
|
14
16
|
primitive InterpolationJoinTest[UnitTest] =
|
|
15
17
|
fun severalPartsJoinInOrder() =
|
|
@@ -44,6 +46,44 @@ primitive InterpolationJoinTest[UnitTest] =
|
|
|
44
46
|
assert show([["x"]]) == "<[[x]]>"
|
|
45
47
|
assert show(7) == "<7>"
|
|
46
48
|
|
|
49
|
+
# each kind of part, at every count of parts from one to past eight
|
|
50
|
+
fun everyKindOfPart() =
|
|
51
|
+
s := "ab"
|
|
52
|
+
assert "{7}" == "7" && "{-7}" == "-7" && "{0}" == "0"
|
|
53
|
+
assert "{Int.Min}|{Int.Max}" == "-9223372036854775808|9223372036854775807"
|
|
54
|
+
assert "{-1234567}" == "-1234567" && "{1000000}" == "1000000" && "{-10}" == "-10"
|
|
55
|
+
assert "{0.5}{-2.25}" == "0.5-2.25" && "{3.0}" == "3.0"
|
|
56
|
+
assert "{s}{s}{s}" == "ababab"
|
|
57
|
+
assert "{s}{1}{s}{2}{s}{3}{s}" == "ab1ab2ab3ab"
|
|
58
|
+
assert "{s}{1}{s}{2}{s}{3}{s}{4}" == "ab1ab2ab3ab4"
|
|
59
|
+
assert "{s}{1}{s}{2}{s}{3}{s}{4}{s}" == "ab1ab2ab3ab4ab"
|
|
60
|
+
assert "a{1}b{2}c{3}d{4}e{5}f" == "a1b2c3d4e5f"
|
|
61
|
+
assert Range.until(0, 3).map(|i| "<{i}>").join(",") == "<0>,<1>,<2>"
|
|
62
|
+
|
|
63
|
+
# an interpolation inside another, and parts that are empty
|
|
64
|
+
fun nestedAndEmpty() =
|
|
65
|
+
e := ""
|
|
66
|
+
n := 4
|
|
67
|
+
assert "[{"<{n}>"}]" == "[<4>]"
|
|
68
|
+
assert "{"{"{n}"}"}" == "4"
|
|
69
|
+
assert "{e}" == "" && "{e}{n}" == "4" && "{n}{e}" == "4" && "x{e}" == "x"
|
|
70
|
+
assert "{e}{e}{e}{e}{e}{e}{e}{e}{e}{e}" == ""
|
|
71
|
+
|
|
72
|
+
# bytes that are not ASCII are copied as they are
|
|
73
|
+
fun nonAscii() =
|
|
74
|
+
w := "wörld"
|
|
75
|
+
assert "héllo {w} {1}€" == "héllo wörld 1€"
|
|
76
|
+
assert "héllo {w} {1}€".length() == 18
|
|
77
|
+
assert "{w}{w}" == "wörldwörld" && "→{w}←".length() == 12
|
|
78
|
+
|
|
79
|
+
# a literal is one value however often it is read, and equal to one built at run time
|
|
80
|
+
fun aLiteralIsOneValue() =
|
|
81
|
+
a := InterpolationJoinTest.lit()
|
|
82
|
+
b := InterpolationJoinTest.lit()
|
|
83
|
+
assert @sameRef(a, b) && a == "lit" && "l{"i"}t" == a && a.length() == 3
|
|
84
|
+
|
|
85
|
+
fun lit() -> Str = "lit"
|
|
86
|
+
|
|
47
87
|
fun describe(name: Str, n: Int, ok: Bool) -> Str =
|
|
48
88
|
"{name} has {n} items, ok={ok}!"
|
|
49
89
|
|