Skip to content

Commit aa331df

Browse files
committed
Use native JS paths for Nat and map operations
1 parent 0b82c20 commit aa331df

6 files changed

Lines changed: 127 additions & 9 deletions

File tree

‎bend2/base.bend‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2598,9 +2598,11 @@ def Map.bit.at(key: String, co: Nat & Nat) -> String & Bool:
25982598
(ci, off) = co
25992599
Map.bit.go(key, ci, off)
26002600

2601+
# Each Char contributes a presence bit, then 32 code bits, most significant first.
26012602
def Map.bit(key: String, pos: Nat) -> String & Bool:
26022603
Map.bit.at(key, Nat.divmod(pos, 33n))
26032604

2605+
# Bit width of x, capped by the fuel n; zero has width zero.
26042606
law Map.msb.u:
26052607
for n: Nat
26062608
for +x: U32

‎bend2/comp.ts‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,22 +234,29 @@ const OPERATIONS: Record<string, Intr> = Object.setPrototypeOf({
234234
...tpl_ops("nat_", "add:$1 double:$0", "nat_chk(e, $0 + $o)",
235235
"nat_chk($0 + $o)"),
236236
nat_mul: { C: "nat_mul(e, $0, $1)", JS: "nat_chk($0 * $1)" },
237+
nat_pow: { JS: "nat_pow($0, $1)" },
237238
nat_cmp: { C: "(($0 > $1) + ($0 >= $1))", JS: "cmp_new($0, $1)" },
238239
...tpl_ops("nat_", "sub", "($0 < $1 ? 0 : $0 - $1)"),
239-
...tpl_ops("nat_", "is_lt:<", "($0 $o $1)"),
240+
...tpl_ops("nat_", CMPS, "($0 $o $1)"),
240241
...tpl_ops("nat_", "min:< max:>", "($0 $o $1 ? $0 : $1)"),
241242
nat_divmod: {
242243
C: ["($1 == 0 ? 0 : $0 / $1)", "($1 == 0 ? $0 : $0 % $1)"],
243244
JS: "nat_divmod($0, $1)",
244245
},
245246
...tpl_ops("bool_", "or:|:|| xor:^:!==", "(($0) $o ($1))", "($0 $o $1)"),
246247
u32_show: { JS: "String($0)" },
248+
map_bit: { JS: "map_bit($0, $1)" },
249+
map_msb_u: { JS: "Math.min($0, 32 - Math.clz32($1))" },
247250
nat_show: { JS: "nat_show($0)" },
248251
u32_read: { JS: "decimal_read($0, 4294967295)" },
249252
nat_read: { JS: "decimal_read($0, 281474976710655)" },
250253
string_append: { JS: "($0 + $1)" },
251254
string_contains: { JS: "string_contains($0, $1)" },
252255
string_order: { JS: "cmp_new(string_compare($0, $1), 0)" },
256+
string_cmp: {
257+
JS: "{$: \"Tuple\", fst: {$: \"Tuple\", fst: $0, snd: $1},"
258+
+ " snd: cmp_new(string_compare($0, $1), 0)}",
259+
},
253260
string_eq: { JS: "(string_compare($0, $1) === 0)" },
254261
string_get: { JS: "string_get($0, $1)" },
255262
string_length: { JS: "[...str_out($0)].length" },
@@ -508,6 +515,24 @@ function nat_chk(n) {
508515
return n;
509516
}
510517
518+
function nat_pow(a, n) {
519+
let r = 1;
520+
while (n > 0) {
521+
if (n % 2) r = nat_chk(r * a);
522+
n = Math.floor(n / 2);
523+
if (n > 0) a = nat_chk(a * a);
524+
}
525+
return r;
526+
}
527+
528+
function map_bit(s, n) {
529+
let i = 0, k = Math.floor(n / 33);
530+
const off = n % 33;
531+
while (i < s.length && k-- > 0) i += char_len(s, i);
532+
return {$: "Tuple", fst: s, snd: i < s.length
533+
&& (off === 0 || ((char_code(s, i) >>> (32 - off)) & 1) !== 0)};
534+
}
535+
511536
function nat_in(n) {
512537
return Number.isInteger(n) && n >= 0 && n <= 2 ** 53 ? n : nat_chk(1 / 0);
513538
}

‎guide/GUIDE.md‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ applications like `U32.add(2)` are closures too.
8686

8787
### Recursion and Termination
8888

89-
Bend uses recursion to repeat work. Tail calls compile to loops.
89+
Tail calls compile to loops. Compiled JS uses repeated squaring for `Nat.pow`.
9090

9191
```python
9292
import Base
@@ -102,13 +102,10 @@ def main() -> U32:
102102
sum([1, 2, 3, 4], 0)
103103
```
104104

105-
Here, `t` has one fewer element than `xs`, so `sum` eventually reaches the empty
106-
list. Bend verifies termination by requiring recursive calls to use smaller
107-
parts of their inputs, obtained through pattern matching. The check reads the
108-
arguments of a recursive call from left to right: each must be passed unchanged
109-
until one is a smaller part of its parameter, and the ones after it are free.
110-
So, put the parameter that shrinks first. Also, is no `if` syntax yet. Use
111-
`match` on `True{}` and `False{}` instead.
105+
`t` is a pattern-bound tail of `xs`, so `sum` terminates. Recursive arguments
106+
must be passed unchanged, left to right, until one is a structurally smaller
107+
part of its parameter; later arguments are unrestricted. Put the shrinking
108+
parameter first. There is no `if`: match `True{}` or `False{}` instead.
112109

113110
Termination is mandatory and mutual recursion is not allowed. Both restrictions
114111
keep Bend's proofs sound, as a function that never returns could otherwise prove

‎tests/base/native_sequence.bend‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,29 @@ def order(c: Cmp) -> String:
2626
case GT{}:
2727
"GT"
2828

29+
def bit(b: Bool) -> String:
30+
match b:
31+
case True{}:
32+
"1"
33+
case False{}:
34+
"0"
35+
36+
def predicates(+a: Nat, +b: Nat) -> String:
37+
bit(Nat.is_eq(a, b)) ++ bit(Nat.is_ne(a, b)) ++ bit(Nat.is_le(a, b)) ++
38+
bit(Nat.is_gt(a, b)) ++ bit(Nat.is_ge(a, b))
39+
40+
def compared_text(p: String & String, c: Cmp) -> String:
41+
(s, t) = p
42+
codes(s) ++ "|" ++ codes(t) ++ ":" ++ order(c)
43+
44+
def compared(p: (String & String) & Cmp) -> String:
45+
(s, c) = p
46+
compared_text(s, c)
47+
48+
def keyed(p: String & Bool) -> String:
49+
(s, b) = p
50+
codes(s) ++ "|" ++ bit(b)
51+
2952
def power(f: @+a: U32 -> Nat -> U32, a: U32, n: Nat) -> U32:
3053
f(a, n)
3154

@@ -43,6 +66,22 @@ def main() -> IO(Unit):
4366
IO.print(U32.show(power(U32.pow, 2, n)) ++ ":" ++ U32.show(U32.pow(3, 32n)))
4467
IO.print(Nat.show(U32.log2(0)) ++ ":" ++ Nat.show(U32.log2(1)) ++ ":" ++ Nat.show(U32.log2(2)))
4568
IO.print(Nat.show(U32.log2(2147483647)) ++ ":" ++ Nat.show(U32.log2(2147483648)) ++ ":" ++ Nat.show(U32.log2(4294967295)))
69+
IO.print(Nat.show(Nat.pow(0n, 0n)) ++ ":" ++ Nat.show(Nat.pow(Nat.add(Nat.mul(4294967295n, 65536n), 65535n), 1n)))
70+
IO.print(Nat.show(Nat.pow(3n, 17n)))
71+
IO.print(predicates(17n, 17n) ++ ":" ++ predicates(17n, 18n) ++ ":" ++ predicates(18n, 17n))
72+
IO.print(compared(String.cmp(s, s)))
73+
IO.print(compared(String.cmp(SCon{Chr{4294967295}, SNil{}}, SCon{Chr{0}, SNil{}})))
74+
IO.print(keyed(Map.bit(s, 100n)))
75+
IO.print(bit(Pair.snd(String, Bool, Map.bit(s, 0n))) ++ ":" ++
76+
bit(Pair.snd(String, Bool, Map.bit(s, 1n))) ++ ":" ++
77+
bit(Pair.snd(String, Bool, Map.bit(s, 50n))) ++ ":" ++
78+
bit(Pair.snd(String, Bool, Map.bit(s, 82n))) ++ ":" ++
79+
bit(Pair.snd(String, Bool, Map.bit(s, 165n))) ++ ":" ++
80+
bit(Pair.snd(String, Bool, Map.bit(s, n))))
81+
IO.print(Nat.show(Map.msb.u(0n, 4294967295)) ++ ":" ++
82+
Nat.show(Map.msb.u(1n, 4294967295)) ++ ":" ++
83+
Nat.show(Map.msb.u(32n, 0)) ++ ":" ++ Nat.show(Map.msb.u(32n, 1)) ++ ":" ++
84+
Nat.show(Map.msb.u(32n, 2147483648)) ++ ":" ++ Nat.show(Map.msb.u(n, 4294967295)))
4685

4786
#|0:55296:65536:4294967295:97:
4887
#|GT
@@ -54,3 +93,11 @@ def main() -> IO(Unit):
5493
#|0:3793632897
5594
#|0:0:1
5695
#|30:31:31
96+
#|1:281474976710655
97+
#|129140163
98+
#|10101:01100:01011
99+
#|0:55296:65536:4294967295:97:|0:55296:65536:4294967295:97::EQ
100+
#|4294967295:|0::GT
101+
#|0:55296:65536:4294967295:97:|1
102+
#|1:0:1:1:0:0
103+
#|0:1:0:1:32:32

‎tests/io/base_helpers_export.bend‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import Base
2+
3+
def Nat.base_helpers_export() -> IO(U32):
4+
import "./base_helpers_export.js"
5+
6+
def main() -> IO(Unit):
7+
do IO<Unit>:
8+
value : U32 <- Nat.base_helpers_export()
9+
IO.print(U32.show(value))
10+
11+
#|0

‎tests/io/base_helpers_export.js‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
function base_helpers_export() {
2+
const fs = require("node:fs");
3+
const path = require("node:path");
4+
const child = require("node:child_process");
5+
const dir = fs.mkdtempSync(path.join(process.cwd(), ".bend-base-export-"));
6+
try {
7+
const input = path.join(dir, "lib.bend");
8+
const output = path.join(dir, "lib.mjs");
9+
fs.writeFileSync(input, `import Base
10+
11+
def power(a: Nat, n: Nat) -> Nat:
12+
Nat.pow(a, n)
13+
14+
`);
15+
const built = child.spawnSync(process.execPath,
16+
[path.resolve("bend2/main.ts"), input, "-o", output], {
17+
encoding: "utf8",
18+
env: { ...process.env, HOME: dir, BEND_ORIGIN: "http://127.0.0.1:9" },
19+
});
20+
if (built.status !== 0) throw new Error(built.stderr || built.stdout);
21+
const lib = require(output).default;
22+
if (lib.power(0, 0) !== 1 || lib.power(0, 4294967296) !== 0
23+
|| lib.power(1, 281474976710655) !== 1
24+
|| lib.power(281474976710655, 1) !== 281474976710655) return 1;
25+
try {
26+
lib.power(2, 48);
27+
return 2;
28+
} catch {
29+
return 0;
30+
}
31+
} finally {
32+
fs.rmSync(dir, { recursive: true, force: true });
33+
}
34+
}
35+
36+
io_eff(CID(Nat.base_helpers_export), base_helpers_export);

0 commit comments

Comments
 (0)