Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 83 additions & 1 deletion bend2/comp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -669,7 +669,7 @@ function ty_key(T: HTerm): string {
}

function tld_of(k: Name): Bend.TLD {
return FL.book.tlds[k];
return FL.book.tlds[k] ?? FL.made[k];
}

function ty_tag(t: HTerm | null, tags: string): boolean {
Expand Down Expand Up @@ -1095,6 +1095,86 @@ function loop_of(k: Name): Name[] {
return memo(FL.loops, k, () => (visit(k), FL.loops.get(k)!));
}

// A def that answers a Nat or a U32 and calls itself outside a tail goes on
// in d~acc, which takes the sum so far first, if every such call is an
// operand of a tail add: there, under successors, or bound by a let used
// once. The other operands join the sum, bound before the calls, each call
// takes it in turn (the last as a tail call), and any other answer is added
// to it: no part of a sum of Nats passes the whole, and U32 wraps. d calls
// d~acc with 0. A def in a tail cycle with another keeps its tail calls.
// loop_of opens d's body, so a let's probe is past every index term_lower
// gives.
function acc_def(d: Name): void {
const f = fun_of(d);
const { T } = tld_of(d) as Bend.Def;
const R = ty_adt(tele_fill(T, Array(f.n).fill(DUMMY)));
const op = R?.k + ".add";
const w = d + "~acc";
if (FL.js || !intr_of(op) || R!.k === "F32" || f.lays.length >= WIDE
|| !term_any(f.h!, (s, tail) => !tail && term_spine(s).k === d)
|| loop_of(d).length > 1) {
return;
}
const go = (t: HTerm, a: HTerm, env: Map<number, Spine>): any => {
const s = term_force(t);
const on = (x: HTerm) => go(x, a, env);
if (s.$ === "Lam") {
return { ...s, f: (x: HTerm) => on(s.f(x)) };
}
if (s.$ === "Let") {
const o = term_open(s);
const m = term_spine(s.v[0]);
const one = s.k.length === 1 && m.k === d && !m.b
&& rest_use([o.b], o.ps[0]) === 1;
return { ...s, f: (xs: Of<"Var">[]) => go(s.f(xs), a,
one ? new Map(env).set(xs[0].i, m) : env) };
}
if (s.$ === "Mat") {
return { ...s, h: on(s.h), m: on(s.m) };
}
if (s.$ === "Ann") {
return { ...s, x: on(s.x) };
}
if (s.$ === "Rwt") {
return { ...s, f: on(s.f) };
}
if (s.$ === "Efq") {
return s;
}
const cs: Spine[] = [];
const flat = (x: HTerm): void => {
const y = term_strip(x);
const m = term_spine(y);
const [b, n] = y.$ === "Ctr" && y.k === "Succ" ? nat_peel(y) : [null, 0];
const c = m.k === d && !m.b ? m : y.$ === "Var" && env.get(y.i);
if (b !== null) {
flat(b);
flat(Bend.Lit("Nat", n));
} else if (m.t.$ === "Ref" && m.t.k === op) {
m.args.forEach(flat);
} else if (c) {
cs.push(c);
} else if (!term_const(y)
|| (Bend.u32_from_term(y) ?? nat_peel(y)[1]) !== 0) {
// a literal 0 adds nothing: the sum goes on as it is, untested
a = Bend.Ann(Bend.App(Bend.App(Bend.Ref(op), a), Bend.Ann(x, R!)), R!);
}
};
flat(s);
return cs.length === 0 ? a : Bend.Let(["a"], [0], [Bend.Ann(a, R!)],
(xs: HTerm[]) => cs.reduce((a, m) => Bend.Ann(m.all.reduce((g, x) =>
Bend.App(g, x), Bend.App(Bend.Ref(w), a)), R!), xs[0]));
};
const e = Bend.term_lower(Bend.Lam("acc", 0, (a: HTerm) =>
go(f.h!, a, new Map())));
const v = Bend.term_higher(e);
if (!term_any(v, (s) => s.$ === "Ref" && s.k === d)) {
FL.made[w] = { $: "Def", n: f.n + 1, x: 0, v, e,
T: Bend.All(Bend.Many(), "acc", 0, R!, () => T) };
f.h = term_eta(Bend.App(Bend.Ref(w), Bend.Lit(R!.k as "Nat", 0)), T, f.n);
}
}

function flat_of(k: Name): boolean {
return memo(FL.flats, k, () => {
const deps = FL.srcs.get(k);
Expand Down Expand Up @@ -1148,6 +1228,7 @@ function file_new(book: Bend.Book, js: boolean) {
srcs: new Map<Name, Set<Name> | null>(),
loops: new Map<Name, Name[]>(),
flats: new Map<Name, boolean>(),
made: Object.create(null) as Record<Name, Bend.Def>,
funs: new Map<Name, Fun>(),
nodes: new Map<Name, Lay>(),
lays: new Map<string, Lay>(),
Expand Down Expand Up @@ -1227,6 +1308,7 @@ function file_book(roots: Name[]): void {
if (!done_live(tld)) {
continue;
}
acc_def(d);
const deps = new Set<Name>();
let flat = true;
term_any(fun_of(d).h!, (s, tail) => {
Expand Down
4 changes: 3 additions & 1 deletion tests/io/stack_fault_trap.bend
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
# Nat is a native immediate) matched ahead of the self-call, and
# 300M levels overrun the 2GB window into the guard page in under
# a second, on whichever lane owns the deep child.
# The result of the self-call is xored before the adds: a tail sum of one
# self-call would run as a loop on the C lane and push no frame.
# The JS walls join the numbered-error law at io_run: a cut there
# is a nested host call, so the host stack throws RangeError long
# before the machine's depth, and io_run's catch translates it into
Expand Down Expand Up @@ -41,7 +43,7 @@ def deep(n, a, b, c, d):
(a + b + c + d : U32)
case 1n+p:
x = deep(p, (a + 1 : U32), (b + 2 : U32), (c + 3 : U32), (d + 4 : U32))
(x + a + b + c + d : U32)
(U32.xor(x, a) + b + c + d : U32)

law run:
for n: U32
Expand Down
123 changes: 123 additions & 0 deletions tests/run/nat_sum_loop.bend
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# A def whose tail is Nat.add, or successors, of one call to itself runs as
# a loop on the C lane: the other operand joins a sum the loop carries, and
# whatever the def answers last is added to it, so the recursion holds no
# frame. Every count comes from the command line's length (1 in the
# harness), which no compiler sees. The shapes: the call on either side of
# Nat.add, under successors, beside a plain tail call and a tail call to
# another def, an operand that consumes a list while the call takes its
# tail, a sum that lands on 2^48-1, twenty thousand steps (the JS lanes
# hold about thirty thousand frames), and the same def under a fork. Two
# calls under one Nat.add (both) and a call bound by a let first (bound)
# loop too: sum_loop_calls and sum_loop_shapes hold the rest.
import Base

def digits(+k: Nat, +n: Nat) -> Nat:
match k:
case 0n:
n
case 1n+p:
Nat.add(Nat.mod(n, 10n), digits(p, Nat.div(n, 10n)))

def left(+n: Nat) -> Nat:
match n:
case 0n:
7n
case 1n+p:
Nat.add(left(p), n)

def succ(+n: Nat) -> Nat:
match n:
case 0n:
0n
case 1n+p:
3n+succ(p)

def other(+n: Nat) -> Nat:
Nat.mul(n, 1000n)

def mixed(+n: Nat, +m: Nat) -> Nat:
match n:
case 0n:
other(m)
case 1n+p:
match m:
case 0n:
mixed(p, 5n)
case 1n+q:
Nat.add(Nat.mul(n, m), mixed(p, q))

def lens(xss: List<&2, List<&2, Nat>>) -> Nat:
match xss:
case Nil{}:
0n
case Con{h, t}:
Nat.add(List.length(&2, Nat, h), lens(t))

def rows(+n: Nat, acc: List<&2, List<&2, Nat>>) -> List<&2, List<&2, Nat>>:
match n:
case 0n:
acc
case 1n+p:
rows(p, Con{List.range(n), acc})

def big() -> Nat:
Nat.add(Nat.mul(16777215n, 16777216n), 16777215n)

def edge(+n: Nat, +x: Nat) -> Nat:
match n:
case 0n:
x
case 1n+p:
Nat.add(x, edge(p, x))

def both(+n: Nat) -> Nat:
match n:
case 0n:
1n
case 1n+p:
Nat.add(both(p), both(p))

def bound(+n: Nat) -> Nat:
match n:
case 0n:
0n
case 1n+p:
r = bound(p)
Nat.add(n, r)

def fork(+d: Nat, +n: Nat) -> Nat:
match d:
case 0n:
left(n)
case 1n+p:
a b = fork(p, n) left(Nat.add(n, d))
Nat.add(a, b)

def show(+one: Nat) -> String:
String.join([
Nat.show(digits(Nat.mul(9n, one), Nat.mul(987654321n, one))),
Nat.show(left(Nat.mul(100n, one))),
Nat.show(succ(Nat.mul(100n, one))),
Nat.show(mixed(Nat.mul(40n, one), Nat.mul(9n, one))),
Nat.show(lens(rows(Nat.mul(50n, one), Nil{}))),
Nat.show(edge(Nat.mul(254n, one), Nat.div(big(), Nat.mul(255n, one)))),
Nat.show(left(Nat.mul(20000n, one))),
Nat.show(both(Nat.mul(12n, one))),
Nat.show(bound(Nat.mul(1000n, one))),
Nat.show(fork(Nat.mul(6n, one), Nat.mul(1000n, one)))], "\n")

def main() -> IO(Unit):
do IO<Unit>:
xs : List<String> <- IO.args()
IO.print(show(List.length(&1, String, xs)))

#|45
#|5057
#|300
#|7930
#|1275
#|281474976710655
#|200010007
#|4096
#|500500
#|3524605
23 changes: 23 additions & 0 deletions tests/run/nat_sum_overflow.bend
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# A sum carried by a loop (nat_sum_loop) stops at the same wall as the
# recursion it replaces: 255 steps of (2^48-1) / 255 land on 2^48-1, and
# the step count here is one more. The count is scaled by the command
# line's length (1 in the harness), which no compiler sees.
import Base

def big() -> Nat:
Nat.add(Nat.mul(16777215n, 16777216n), 16777215n)

def edge(+n: Nat, +x: Nat) -> Nat:
match n:
case 0n:
x
case 1n+p:
Nat.add(x, edge(p, x))

def main() -> IO(Unit):
do IO<Unit>:
xs : List<String> <- IO.args()
IO.print(Nat.show(edge(Nat.mul(255n, List.length(&1, String, xs)), Nat.div(big(), 255n))))

#|bend: a Nat past the largest immediate 2^48-1
#|exit 1
Loading
Loading