From ec03cbbf95392be930132d861bbafb87b92107f8 Mon Sep 17 00:00:00 2001 From: Victor Borja Date: Mon, 9 Nov 2026 04:03:40 -0600 Subject: [PATCH 1/2] tests: the gate and the speed oracle run s2 only (s2c seed -> s2c -> tests/s2; bench corpus refrozen to s2 sources and s2 tests, new baseline) --- bench/baseline.txt | 24 +- bench/corpus/lib/kanren.srs | 40 +- bench/corpus/s1/check.srs | 1091 --------------- bench/corpus/s1/emit.srs | 577 -------- bench/corpus/s1/facts.srs | 322 ----- bench/corpus/s1/given.srs | 305 ----- bench/corpus/s1/lean.srs | 604 --------- bench/corpus/s1/leanspec.srs | 703 ---------- bench/corpus/s1/lex.srs | 84 -- bench/corpus/s1/main.srs | 20 - bench/corpus/s1/mono.srs | 159 --- bench/corpus/s1/node.srs | 337 ----- bench/corpus/s1/parse.srs | 593 -------- bench/corpus/s1/purity.srs | 95 -- bench/corpus/s1/types.srs | 135 -- bench/corpus/s2/ast.srs | 819 +++++++++++ bench/corpus/s2/bmap.srs | 318 +++++ bench/corpus/s2/coll.srs | 196 +++ bench/corpus/s2/datalog.srs | 708 ++++++++++ bench/corpus/s2/elab.srs | 63 + bench/corpus/s2/emit.srs | 1118 +++++++++++++++ bench/corpus/s2/eval.srs | 356 +++++ bench/corpus/s2/facts.srs | 369 +++++ bench/corpus/s2/flow.srs | 1193 +++++++++++++++++ bench/corpus/s2/hash.srs | 508 +++++++ bench/corpus/s2/kanren.srs | 66 + bench/corpus/s2/kfd.srs | 332 +++++ bench/corpus/s2/ksearch.srs | 154 +++ bench/corpus/s2/lex.srs | 129 ++ bench/corpus/s2/mono.srs | 232 ++++ bench/corpus/s2/names.srs | 470 +++++++ bench/corpus/s2/parse.srs | 833 ++++++++++++ bench/corpus/s2/pure.srs | 197 +++ bench/corpus/s2/queue.srs | 28 + bench/corpus/s2/store.srs | 103 ++ bench/corpus/s2/sym.srs | 19 + bench/corpus/s2/tlevel.srs | 607 +++++++++ bench/corpus/s2/types.srs | 1086 +++++++++++++++ bench/corpus/s2c/main.srs | 376 ++++++ bench/corpus/tests/caps.out | 1 - bench/corpus/tests/contracts.out | 1 - bench/corpus/tests/datalog.out | 17 - bench/corpus/tests/facts.out | 1 - bench/corpus/tests/facts_vars.out | 1 - bench/corpus/tests/file_ok.out | 1 - bench/corpus/tests/generic.out | 4 - bench/corpus/tests/generic_enum.out | 4 - bench/corpus/tests/given_local.out | 1 - bench/corpus/tests/given_rank.out | 2 - bench/corpus/tests/givens.out | 5 - bench/corpus/tests/kanren.out | 8 - bench/corpus/tests/kanren_fd.out | 36 - bench/corpus/tests/kanren_neq.out | 16 - bench/corpus/tests/kanren_search.out | 18 - bench/corpus/tests/list.out | 1 - bench/corpus/tests/purity.out | 1 - bench/corpus/tests/region_ok.out | 1 - bench/corpus/tests/rules.out | 1 - bench/corpus/tests/s2/prog/body_want.srs | 23 + bench/corpus/tests/{ => s2/prog}/caps.srs | 0 bench/corpus/tests/s2/prog/check_mode.srs | 26 + .../corpus/tests/{ => s2/prog}/contracts.srs | 0 bench/corpus/tests/{ => s2/prog}/datalog.srs | 0 bench/corpus/tests/{ => s2/prog}/facts.srs | 0 .../corpus/tests/{ => s2/prog}/facts_vars.srs | 0 bench/corpus/tests/{ => s2/prog}/file.lib | 0 bench/corpus/tests/{ => s2/prog}/file_ok.srs | 0 bench/corpus/tests/s2/prog/fold.srs | 33 + bench/corpus/tests/{ => s2/prog}/generic.srs | 0 .../corpus/tests/s2/prog/generic_capture.srs | 25 + .../tests/{ => s2/prog}/generic_enum.srs | 0 .../tests/{ => s2/prog}/given_local.srs | 0 .../corpus/tests/{ => s2/prog}/given_rank.srs | 0 bench/corpus/tests/{ => s2/prog}/givens.srs | 0 bench/corpus/tests/{ => s2/prog}/kanren.srs | 0 .../corpus/tests/{ => s2/prog}/kanren_fd.srs | 10 +- .../corpus/tests/{ => s2/prog}/kanren_neq.srs | 0 .../tests/{ => s2/prog}/kanren_search.srs | 2 +- bench/corpus/tests/{ => s2/prog}/list.lib | 0 bench/corpus/tests/{ => s2/prog}/list.srs | 0 bench/corpus/tests/s2/prog/modules.srs | 37 + bench/corpus/tests/{ => s2/prog}/purity.srs | 0 .../corpus/tests/{ => s2/prog}/region_ok.srs | 0 bench/corpus/tests/{ => s2/prog}/rules.srs | 0 bench/corpus/tests/s2/prog/tailcall.srs | 57 + bench/corpus/tests/{ => s2/prog}/traits.srs | 0 .../corpus/tests/{ => s2/prog}/turnstile.srs | 4 +- .../tests/{ => s2/prog}/type_evidence.srs | 0 .../corpus/tests/{ => s2/prog}/type_facts.srs | 0 bench/corpus/tests/s2/prog/type_values.srs | 20 + .../corpus/tests/{ => s2/prog}/typelambda.srs | 0 bench/corpus/tests/s2/prog/val_pattern.srs | 34 + bench/corpus/tests/{ => s2/prog}/var_ok.srs | 0 bench/corpus/tests/traits.out | 1 - bench/corpus/tests/turnstile.out | 15 - bench/corpus/tests/type_evidence.out | 1 - bench/corpus/tests/type_facts.out | 1 - bench/corpus/tests/typelambda.out | 1 - bench/corpus/tests/var_ok.out | 1 - nix/commands.nix | 4 +- tests/bench.sh | 28 +- tests/run.sh | 86 +- 102 files changed, 10589 insertions(+), 5309 deletions(-) delete mode 100644 bench/corpus/s1/check.srs delete mode 100644 bench/corpus/s1/emit.srs delete mode 100644 bench/corpus/s1/facts.srs delete mode 100644 bench/corpus/s1/given.srs delete mode 100644 bench/corpus/s1/lean.srs delete mode 100644 bench/corpus/s1/leanspec.srs delete mode 100644 bench/corpus/s1/lex.srs delete mode 100644 bench/corpus/s1/main.srs delete mode 100644 bench/corpus/s1/mono.srs delete mode 100644 bench/corpus/s1/node.srs delete mode 100644 bench/corpus/s1/parse.srs delete mode 100644 bench/corpus/s1/purity.srs delete mode 100644 bench/corpus/s1/types.srs create mode 100644 bench/corpus/s2/ast.srs create mode 100644 bench/corpus/s2/bmap.srs create mode 100644 bench/corpus/s2/coll.srs create mode 100644 bench/corpus/s2/datalog.srs create mode 100644 bench/corpus/s2/elab.srs create mode 100644 bench/corpus/s2/emit.srs create mode 100644 bench/corpus/s2/eval.srs create mode 100644 bench/corpus/s2/facts.srs create mode 100644 bench/corpus/s2/flow.srs create mode 100644 bench/corpus/s2/hash.srs create mode 100644 bench/corpus/s2/kanren.srs create mode 100644 bench/corpus/s2/kfd.srs create mode 100644 bench/corpus/s2/ksearch.srs create mode 100644 bench/corpus/s2/lex.srs create mode 100644 bench/corpus/s2/mono.srs create mode 100644 bench/corpus/s2/names.srs create mode 100644 bench/corpus/s2/parse.srs create mode 100644 bench/corpus/s2/pure.srs create mode 100644 bench/corpus/s2/queue.srs create mode 100644 bench/corpus/s2/store.srs create mode 100644 bench/corpus/s2/sym.srs create mode 100644 bench/corpus/s2/tlevel.srs create mode 100644 bench/corpus/s2/types.srs create mode 100644 bench/corpus/s2c/main.srs delete mode 100644 bench/corpus/tests/caps.out delete mode 100644 bench/corpus/tests/contracts.out delete mode 100644 bench/corpus/tests/datalog.out delete mode 100644 bench/corpus/tests/facts.out delete mode 100644 bench/corpus/tests/facts_vars.out delete mode 100644 bench/corpus/tests/file_ok.out delete mode 100644 bench/corpus/tests/generic.out delete mode 100644 bench/corpus/tests/generic_enum.out delete mode 100644 bench/corpus/tests/given_local.out delete mode 100644 bench/corpus/tests/given_rank.out delete mode 100644 bench/corpus/tests/givens.out delete mode 100644 bench/corpus/tests/kanren.out delete mode 100644 bench/corpus/tests/kanren_fd.out delete mode 100644 bench/corpus/tests/kanren_neq.out delete mode 100644 bench/corpus/tests/kanren_search.out delete mode 100644 bench/corpus/tests/list.out delete mode 100644 bench/corpus/tests/purity.out delete mode 100644 bench/corpus/tests/region_ok.out delete mode 100644 bench/corpus/tests/rules.out create mode 100644 bench/corpus/tests/s2/prog/body_want.srs rename bench/corpus/tests/{ => s2/prog}/caps.srs (100%) create mode 100644 bench/corpus/tests/s2/prog/check_mode.srs rename bench/corpus/tests/{ => s2/prog}/contracts.srs (100%) rename bench/corpus/tests/{ => s2/prog}/datalog.srs (100%) rename bench/corpus/tests/{ => s2/prog}/facts.srs (100%) rename bench/corpus/tests/{ => s2/prog}/facts_vars.srs (100%) rename bench/corpus/tests/{ => s2/prog}/file.lib (100%) rename bench/corpus/tests/{ => s2/prog}/file_ok.srs (100%) create mode 100644 bench/corpus/tests/s2/prog/fold.srs rename bench/corpus/tests/{ => s2/prog}/generic.srs (100%) create mode 100644 bench/corpus/tests/s2/prog/generic_capture.srs rename bench/corpus/tests/{ => s2/prog}/generic_enum.srs (100%) rename bench/corpus/tests/{ => s2/prog}/given_local.srs (100%) rename bench/corpus/tests/{ => s2/prog}/given_rank.srs (100%) rename bench/corpus/tests/{ => s2/prog}/givens.srs (100%) rename bench/corpus/tests/{ => s2/prog}/kanren.srs (100%) rename bench/corpus/tests/{ => s2/prog}/kanren_fd.srs (90%) rename bench/corpus/tests/{ => s2/prog}/kanren_neq.srs (100%) rename bench/corpus/tests/{ => s2/prog}/kanren_search.srs (99%) rename bench/corpus/tests/{ => s2/prog}/list.lib (100%) rename bench/corpus/tests/{ => s2/prog}/list.srs (100%) create mode 100644 bench/corpus/tests/s2/prog/modules.srs rename bench/corpus/tests/{ => s2/prog}/purity.srs (100%) rename bench/corpus/tests/{ => s2/prog}/region_ok.srs (100%) rename bench/corpus/tests/{ => s2/prog}/rules.srs (100%) create mode 100644 bench/corpus/tests/s2/prog/tailcall.srs rename bench/corpus/tests/{ => s2/prog}/traits.srs (100%) rename bench/corpus/tests/{ => s2/prog}/turnstile.srs (99%) rename bench/corpus/tests/{ => s2/prog}/type_evidence.srs (100%) rename bench/corpus/tests/{ => s2/prog}/type_facts.srs (100%) create mode 100644 bench/corpus/tests/s2/prog/type_values.srs rename bench/corpus/tests/{ => s2/prog}/typelambda.srs (100%) create mode 100644 bench/corpus/tests/s2/prog/val_pattern.srs rename bench/corpus/tests/{ => s2/prog}/var_ok.srs (100%) delete mode 100644 bench/corpus/tests/traits.out delete mode 100644 bench/corpus/tests/turnstile.out delete mode 100644 bench/corpus/tests/type_evidence.out delete mode 100644 bench/corpus/tests/type_facts.out delete mode 100644 bench/corpus/tests/typelambda.out delete mode 100644 bench/corpus/tests/var_ok.out diff --git a/bench/baseline.txt b/bench/baseline.txt index 8534cd60..1b1a4b5f 100644 --- a/bench/baseline.txt +++ b/bench/baseline.txt @@ -1,15 +1,9 @@ -corpus-self wall 0.12775143381818183 0.011372803783640187 -corpus-self instr 274041244.1363636 33.912064793051734 -corpus-self mem 52900957.09090909 126570.67215362299 -corpus-lean wall 0.24611097923076924 0.015624251307958045 -corpus-lean instr 494192153.0 83.77549363228684 -corpus-lean mem 95700204.3076923 151121.35071269964 -corpus-tests wall 0.4935262161000001 0.002177963859206702 -corpus-tests instr 1112008029.7 15236.22809877096 -corpus-tests mem 10970726.4 70449.0831723325 -info-s1-self wall 0.14322669809523808 0.001320767815550332 -info-s1-self instr 334215777.8095238 16.101611868440525 -info-s1-self mem 62343460.571428575 108467.24186249574 -info-s1-lean wall 0.26766985463636367 0.0022573760950091648 -info-s1-lean instr 575020362.0909091 9.648363026488436 -info-s1-lean mem 111277149.0909091 67877.30514605681 +corpus-self wall 3.8078688442 1.1918706563666694 +corpus-self instr 3157647545.0 724.000345303785 +corpus-self mem 1259725619.2 205074.24837653313 +corpus-tests wall 6.646648772400001 1.5940560827021355 +corpus-tests instr 7408109693.6 5573.769891195725 +corpus-tests mem 143262515.2 77737.72059431637 +info-s2c-self wall 2.3844662332000004 0.09882857217685709 +info-s2c-self instr 3157645890.6 944.2217959780425 +info-s2c-self mem 1259707596.8 220736.02041171258 diff --git a/bench/corpus/lib/kanren.srs b/bench/corpus/lib/kanren.srs index 19af176a..9602ee13 100644 --- a/bench/corpus/lib/kanren.srs +++ b/bench/corpus/lib/kanren.srs @@ -4,7 +4,7 @@ enum Term: case TVar(n: I64) case TCon(f: Str, args: Terms) - case TInt(v: I64) + case KInt(v: I64) enum Terms: case TNil @@ -22,7 +22,7 @@ enum Unified: def walk(s: Subst, t: Term): Term = t match case TVar(n) => lookup(s, s, n, t) case TCon(_, _) => t - case TInt(_) => t + case KInt(_) => t def lookup(all: Subst, s: Subst, n: I64, t: Term): Term = s match case SNil => t @@ -32,7 +32,7 @@ def lookup(all: Subst, s: Subst, n: I64, t: Term): Term = s match def occurs(s: Subst, n: I64, t: Term): Bool = walk(s, t) match case TVar(m) => m == n case TCon(_, args) => occursIn(s, n, args) - case TInt(_) => false + case KInt(_) => false def occursIn(s: Subst, n: I64, ts: Terms): Bool = ts match case TNil => false @@ -47,16 +47,16 @@ def unify {r: Region} (s: Subst, a: Term, b: Term): Unified = case TCon(f, xs) => y match case TVar(m) => bind(s, m, x) case TCon(g, ys) => if rt_str_eq(f, g) then unifyAll(s, xs, ys) else Fail - case TInt(_) => Fail - case TInt(v) => y match + case KInt(_) => Fail + case KInt(v) => y match case TVar(m) => bind(s, m, x) - case TInt(w) => if v == w then Ok(s) else Fail + case KInt(w) => if v == w then Ok(s) else Fail case TCon(_, _) => Fail def bind {r: Region} (s: Subst, n: I64, t: Term): Unified = t match case TVar(m) => if m == n then Ok(s) else Ok(SBind(n, t, s)) case TCon(_, _) => if occurs(s, n, t) then Fail else Ok(SBind(n, t, s)) - case TInt(_) => Ok(SBind(n, t, s)) + case KInt(_) => Ok(SBind(n, t, s)) def unifyAll {r: Region} (s: Subst, xs: Terms, ys: Terms): Unified = xs match case TNil => ys match @@ -72,7 +72,7 @@ def unifyAll {r: Region} (s: Subst, xs: Terms, ys: Terms): Unified = xs match def walkAll {r: Region} (s: Subst, t: Term): Term = walk(s, t) match case TVar(n) => TVar(n) case TCon(f, args) => TCon(f, walkEach(s, args)) - case TInt(v) => TInt(v) + case KInt(v) => KInt(v) def walkEach {r: Region} (s: Subst, ts: Terms): Terms = ts match case TNil => TNil @@ -90,7 +90,7 @@ def showTerm(t: Term): Unit = t match rt_print("(") showTerms(args) rt_print(")") - case TInt(v) => rt_print_i64(v) + case KInt(v) => rt_print_i64(v) def showTerms(ts: Terms): Unit = ts match case TNil => () @@ -202,7 +202,7 @@ enum Run: def shift {r: Region} (t: Term, k: I64): Term = t match case TVar(n) => TVar(n + k) case TCon(f, args) => TCon(f, shiftAll(args, k)) - case TInt(v) => TInt(v) + case KInt(v) => KInt(v) def shiftAll {r: Region} (ts: Terms, k: I64): Terms = ts match case TNil => TNil @@ -309,9 +309,9 @@ def between {r: Region} (xs: Ints, a: I64, b: I64): Ints = xs match case INil => INil case ICons(h, t) => if h >= a && h <= b then ICons(h, between(t, a, b)) else between(t, a, b) -def without {r: Region} (xs: Ints, v: I64): Ints = xs match +def kwithout {r: Region} (xs: Ints, v: I64): Ints = xs match case INil => INil - case ICons(h, t) => if h == v then without(t, v) else ICons(h, without(t, v)) + case ICons(h, t) => if h == v then kwithout(t, v) else ICons(h, kwithout(t, v)) def meetInts {r: Region} (xs: Ints, d: Dom): Ints = xs match case INil => INil @@ -334,7 +334,7 @@ def dropDom {r: Region} (ds: Doms, n: I64): Doms = ds match def domOf {r: Region} (st: State, t: Term): DomOf = st match case State(s, _, ds, _, _) => walk(s, t) match case TVar(n) => lookupDom(ds, n) - case TInt(v) => Has(Dom(v, INil)) + case KInt(v) => Has(Dom(v, INil)) case TCon(_, _) => NotInt // t takes a value of xs (ascending): Bad when none is left, bound when one is left @@ -342,10 +342,10 @@ def setDom {r: Region} (st: State, t: Term, xs: Ints): Checked = st match case State(s, ns, ds, fs, nx) => xs match case INil => Bad case ICons(h, rest) => walk(s, t) match - case TInt(v) => if member(v, xs) then Good(st) else Bad + case KInt(v) => if member(v, xs) then Good(st) else Bad case TCon(_, _) => Bad case TVar(n) => rest match - case INil => unify(s, TVar(n), TInt(h)) match + case INil => unify(s, TVar(n), KInt(h)) match case Fail => Bad case Ok(s2) => Good(State(s2, ns, dropDom(ds, n), fs, nx)) case ICons(_, _) => Good(State(s, ns, DCons(n, Dom(h, rest), dropDom(ds, n)), fs, nx)) @@ -372,8 +372,8 @@ def leAt {r: Region} (st: State, x: Term, y: Term, dx: Dom, dy: Dom, k: I64): Ch def neqAt {r: Region} (st: State, x: Term, y: Term, dx: Dom, dy: Dom): Checked = if domSize(dx) == 1 && domSize(dy) == 1 then (if lo(dx) == lo(dy) then Bad else Good(st)) - else if domSize(dx) == 1 then setDom(st, y, without(ints(dy), lo(dx))) - else if domSize(dy) == 1 then setDom(st, x, without(ints(dx), lo(dy))) + else if domSize(dx) == 1 then setDom(st, y, kwithout(ints(dy), lo(dx))) + else if domSize(dy) == 1 then setDom(st, x, kwithout(ints(dx), lo(dy))) else Good(st) def binAt {r: Region} (st: State, op: Bin, x: Term, y: Term, dx: Dom, dy: Dom): Checked = op match @@ -455,7 +455,7 @@ def smaller(d: Dom, best: Pick): Bool = best match def labelBranches {r: Region} (st: State, t: Term, vs: Ints, after: Goals): Queue = vs match case INil => QNil - case ICons(v, more) => QCons(Branch(st, GCons(GEq(t, TInt(v)), after)), labelBranches(st, t, more, after)) + case ICons(v, more) => QCons(Branch(st, GCons(GEq(t, KInt(v)), after)), labelBranches(st, t, more, after)) // every two of xs differ def distinct {r: Region} (xs: Terms): Goal = xs match @@ -484,7 +484,7 @@ def picks {r: Region} (rules: Rules, rel: Str, args: Terms, st: State, nx: I64, Picked(QCons(b, bs), cost + 1) else Picked(bs, cost) -def step {r: Region} (rules: Rules, b: Branch): Step = b match +def kstep {r: Region} (rules: Rules, b: Branch): Step = b match case Branch(st, gs) => gs match case GNil => Done(st) case GCons(g, rest) => st match @@ -525,7 +525,7 @@ def solve {r: Region} (rules: Rules, g: Goal, nvars: I64, fuel: I64, limit: I64) case QNil => go = false case QCons(b, t) => q = t - step(rules, b) match + kstep(rules, b) match case Done(st) => found = ACons(st, found) n = n + 1 diff --git a/bench/corpus/s1/check.srs b/bench/corpus/s1/check.srs deleted file mode 100644 index e84327d9..00000000 --- a/bench/corpus/s1/check.srs +++ /dev/null @@ -1,1091 +0,0 @@ -// S1 checker: types + flow-typed effects (vic/c/effects.md, fx-rs#20). -// Judgment Γ1 ⊢ e : T ⊣ Γ2. Γ = GState(s = cap, t = state) + GVar(s = var, a = caps) list, innermost first. -// env = BVar(s = name, t = protocol or "", n = 0 val / 1 var / 2 cap, a = [Ty]); var Ty = bound, n 0 = none. -// Ty a = [TyTo, TyCap...]: value caps = regions the value lives in. -// "*" = the caller's capture variable ρ of a signature: never in Γ, always live. - -enum TG: - case TG(ty: Node, gam: Nodes, e2: Node) - -def tgTy(x: TG): Node = x match - case TG(t, _, _) => t -def tgGam(x: TG): Nodes = x match - case TG(_, g, _) => g -// the expansion: e as the emitter takes it (Turnstile e >> e2, vic/c/binders-design.md) -def tgE(x: TG): Node = x match - case TG(_, _, e) => e - -// e with new kids, every other field kept -def withKids {r: Region} (e: Node, ks: Nodes): Node = e match - case Node(k, s, t, n, l, _) => Node(k, s, t, n, l, ks) - case NoNode => NoNode - -def err(what: Str, name: Str, line: I64): Unit = - rt_eprint("srs:") - rt_eprint_i64(line) - rt_eprint(": error: ") - rt_eprint(what) - rt_eprint(" '") - rt_eprint(name) - rt_eprint("'\n") - rt_exit(1) - -def tyCaps(t: Node): Nodes - ensures result == tailS(kidsS(t)) -= tail(kids(t)) -def tyTo(t: Node): Str = text(head(kids(t))) -def mkTy {r: Region} (name: Str, caps: Nodes): Node = Node(Ty, name, "", 1, 0, NCons(leaf(TyTo, "", 0), caps)) -def prim {r: Region} (name: Str): Node = mkTy(name, NNil) -// the args of T[args] -def tyArgs(t: Node): Nodes = kids(head(kids(t))) -// t with new caps: name and type args kept -def recap {r: Region} (t: Node, caps: Nodes): Node = Node(Ty, text(t), "", 1, 0, NCons(Node(TyTo, "", "", 0, 0, tyArgs(t)), caps)) -// one type: same name, same type args (caps are checked apart) -def tyEq(a: Node, b: Node): Bool = eqs(text(a), text(b)) && tysEq(tyArgs(a), tyArgs(b)) -def tysEq(a: Nodes, b: Nodes): Bool = - if isNil(a) || isNil(b) then isNil(a) && isNil(b) else tyEq(head(a), head(b)) && tysEq(tail(a), tail(b)) -def eprintTy(t: Node): Unit = - rt_eprint(text(t)) - if !isNil(tyArgs(t)) then - rt_eprint("[") - var c = tyArgs(t) - while !isNil(c) do - eprintTy(head(c)) - if !isNil(tail(c)) then rt_eprint(", ") else () - c = tail(c) - rt_eprint("]") - else () - -// the binders of the [] groups of gs (type ascriptions, vic 2026-11-05) -def groupBinders {r: Region} (gs: Nodes): Nodes = - var out = NNil - var c = gs - while !isNil(c) do - if kind(head(c)) == Group && eqs(text(head(c)), "[") then out = append(out, kids(head(c))) else () - c = tail(c) - out -// [] binders of enum n: kept on each of its cases (kid 1) -def enumTParams {r: Region} (ds: Decls, n: Str): Nodes = groupBinders(kids(kid(head(kids(findDecl(ds, DEnum, n))), 1))) -def enumArity(ds: Decls, n: Str): I64 = - var k = 0 - var c = kids(kid(head(kids(findDecl(ds, DEnum, n))), 1)) - while !isNil(c) do - if kind(head(c)) == Group && eqs(text(head(c)), "[") then k = k + len(kids(head(c))) else () - c = tail(c) - k - -def isBuiltin(n: Str): Bool = eqs(n, "I64") || eqs(n, "Bool") || eqs(n, "Unit") || eqs(n, "Str") || eqs(n, "Ptr") -def isEnum(ds: Decls, n: Str): Bool = found(findDecl(ds, DEnum, n)) -def isProto(ds: Decls, n: Str): Bool = found(findDecl(ds, DProto, n)) -// a [] binder in scope: checkSig and checkFn put the fn's binders in front of ds -def isTParam(ds: Decls, n: Str): Bool = found(findDecl(ds, Binder, n)) - -// a, then each node of b whose text is not yet in, in b's order (onto the front) -spec def unionS(a: Nodes, b: Nodes): Nodes - ensures forall s: Str => memS(s, result) == (memS(s, a) || memS(s, b)) - proof by induction b -= b match - case NNil => a - case NCons(h, t) => unionS(if memS(textS(h), a) then a else NCons(h, a), t) -def union {r: Region} (a: Nodes, b: Nodes): Nodes - ensures result == unionS(a, b) -= - var out = a - var c = b - while !isNil(c) do - invariant unionS(out, c) == unionS(a, b) - decreases sizeS(c) - if !has(out, text(head(c))) then out = NCons(head(c), out) else () - c = tail(c) - out -// spec: every text of a is a text of b -spec def allIn(a: Nodes, b: Nodes): Bool = a match - case NNil => true - case NCons(h, t) => memS(textS(h), b) && allIn(t, b) - -def subset(a: Nodes, b: Nodes): Bool - ensures result == allIn(a, b) -= - var c = a - var ok = true - while ok && !isNil(c) do - invariant (ok && allIn(c, b)) == allIn(a, b) - decreases sizeS(c) - ok = has(b, text(head(c))) - c = tail(c) - ok - -def state(gam: Nodes, cap: Str): Str - ensures result == text2S(lookS(gam, GState, cap)) -= text2(find(gam, GState, cap)) -// replace the innermost Γ entry of x's kind and name by x -spec def replS(xs: Nodes, x: Node): Nodes = xs match - case NNil => NNil - case NCons(h, t) => if kindS(h) == kindS(x) && rt_str_eq(textS(h), textS(x)) then NCons(x, t) else NCons(h, replS(t, x)) -def setG {r: Region} (gam: Nodes, x: Node): Nodes - ensures result == replS(gam, x) -= - var out = NNil - var c = gam - var done = false - while !isNil(c) do - invariant revOnto(out, if done then c else replS(c, x)) == replS(gam, x) - decreases sizeS(c) - if !done && kind(head(c)) == kind(x) && eqs(text(head(c)), text(x)) then - out = NCons(x, out) - done = true - else out = NCons(head(c), out) - c = tail(c) - rev(out) -// spec: the cap states (text2) of a and b agree entry by entry -spec def agreeS(a: Nodes, b: Nodes): Bool = a match - case NNil => true - case NCons(h, t) => rt_str_eq(text2S(h), text2S(headS(b))) && agreeS(t, tailS(b)) -// spec: entry by entry, a's entry with the caps of both entries -spec def joinS(a: Nodes, b: Nodes): Nodes = a match - case NNil => NNil - case NCons(h, t) => NCons(Node(kindS(h), textS(h), text2S(h), 0, 0, unionS(kidsS(h), kidsS(headS(b)))), joinS(t, tailS(b))) -// Γ of two paths from one Γ (same entries, same order): var caps join by union (C8), cap states must agree -// accepts only when the states agree -def joinGam {r: Region} (a: Nodes, b: Nodes, what: Str, line: I64): Nodes - returns agreeS(a, b) && result == joinS(a, b) -= - var out = NNil - var x = a - var y = b - while !isNil(x) do - invariant agreeS(a, b) == agreeS(x, y) && joinS(a, b) == revOnto(out, joinS(x, y)) - decreases sizeS(x) - if !eqs(text2(head(x)), text2(head(y))) then err(what, text(head(x)), line) else () - out = NCons(Node(kind(head(x)), text(head(x)), text2(head(x)), 0, 0, union(kids(head(x)), kids(head(y)))), out) - x = tail(x) - y = tail(y) - rev(out) -// every var of a has caps within the same var of b -spec def withinS(a: Nodes, b: Nodes): Bool = a match - case NNil => true - case NCons(h, t) => allIn(kidsS(h), kidsS(headS(b))) && withinS(t, tailS(b)) -def within(a: Nodes, b: Nodes): Bool - ensures result == withinS(a, b) -= - var x = a - var y = b - var ok = true - while ok && !isNil(x) do - invariant (ok && withinS(x, y)) == withinS(a, b) - decreases sizeS(x) - ok = subset(kids(head(x)), kids(head(y))) - x = tail(x) - y = tail(y) - ok - -def protoEnds(ds: Nodes, p: Str): Nodes - ensures result == kidsS(nthS(kidsS(lookS(ds, DProto, p)), 1)) -= kids(kid(find(ds, DProto, p), 1)) -def protoStates(ds: Nodes, p: Str): Nodes = kids(kid(find(ds, DProto, p), 0)) - -// capture c is live: not a tracked cap (ρ), or its state is not an end state -spec def liveS(ds: Nodes, env: Nodes, gam: Nodes, c: Str): Bool = - if !foundS(lookS(env, BVar, c)) || numS(lookS(env, BVar, c)) != 2 then true - else !memS(text2S(lookS(gam, GState, c)), kidsS(nthS(kidsS(lookS(ds, DProto, text2S(lookS(env, BVar, c)))), 1))) -def live(ds: Nodes, env: Nodes, gam: Nodes, c: Str): Bool - ensures result == liveS(ds, env, gam, c) -= - val b = find(env, BVar, c) - if !found(b) || num(b) != 2 then true - else !has(protoEnds(ds, text2(b)), state(gam, c)) -spec def allLiveS(ds: Nodes, env: Nodes, gam: Nodes, xs: Nodes): Bool = xs match - case NNil => true - case NCons(h, t) => liveS(ds, env, gam, textS(h)) && allLiveS(ds, env, gam, t) -// accepts (returns) only when every capture of t is live, else the run stops -def needLive(ds: Nodes, env: Nodes, gam: Nodes, t: Node, line: I64): Unit - returns allLiveS(ds, env, gam, tailS(kidsS(t))) -= - var c = tyCaps(t) - while !isNil(c) do - invariant allLiveS(ds, env, gam, tailS(kidsS(t))) == allLiveS(ds, env, gam, c) - decreases sizeS(c) - if !live(ds, env, gam, text(head(c))) then err("use of value after its region ended:", text(head(c)), line) else () - c = tail(c) - -// annotation w/o caps = no cap bound: caps stay inferred from t (R2 Q2) -def bound {r: Region} (ann: Node, t: Node): Node = if num(ann) == 0 then recap(ann, tyCaps(t)) else ann -def uncapped {r: Region} (name: Str): Node = Node(Ty, name, "", 0, 0, one(leaf(TyTo, "", 0))) -// t with no caps and no annotation: a var's type, its caps are flow state -def uncap {r: Region} (t: Node): Node = Node(Ty, text(t), "", 0, 0, one(Node(TyTo, "", "", 0, 0, tyArgs(t)))) - -def assignable(a: Node, b: Node): Bool = tyEq(a, b) && subset(tyCaps(a), tyCaps(b)) -// facts on a type (vic-jxk): each cap of t that names a state (TyCap t) must be in that state in Γ now -def needStates(gam: Nodes, t: Node, line: I64): Unit = - var c = tyCaps(t) - while !isNil(c) do - val want = text2(head(c)) - if rt_str_len(want) > 0 && !eqs(state(gam, text(head(c))), want) then - rt_eprint("srs:") - rt_eprint_i64(line) - rt_eprint(": error: value needs '") - rt_eprint(text(head(c))) - rt_eprint("' in state ") - rt_eprint(want) - rt_eprint(", it is ") - rt_eprint(state(gam, text(head(c)))) - rt_eprint("\n") - rt_exit(1) - else () - c = tail(c) - -// a value of type a can stand where type b is expected only if it carries every fact of b (same cap, same state) -def needCarried(a: Node, b: Node, line: I64): Unit = - var c = tyCaps(b) - while !isNil(c) do - if rt_str_len(text2(head(c))) > 0 && !hasState(tyCaps(a), text(head(c)), text2(head(c))) then err("value does not carry the fact of its type: state of", text(head(c)), line) else () - c = tail(c) - -def hasState(cs: Nodes, cap: Str, s: Str): Bool = - var res = false - var c = cs - while !res && !isNil(c) do - res = eqs(text(head(c)), cap) && eqs(text2(head(c)), s) - c = tail(c) - res - -def needAssign(a: Node, b: Node, line: I64): Unit = - if !tyEq(a, b) then - rt_eprint("srs:") - rt_eprint_i64(line) - rt_eprint(": error: type mismatch: ") - eprintTy(a) - rt_eprint(" is not ") - eprintTy(b) - rt_eprint("\n") - rt_exit(1) - else if !subset(tyCaps(a), tyCaps(b)) then err("value escapes its region, expected type", text(b), line) - else needCarried(a, b, line) - -def needTy(ds: Decls, t: Node): Unit = - val n = text(t) - if !isBuiltin(n) && !isEnum(ds, n) && !isProto(ds, n) && !isTParam(ds, n) then err("unknown type", n, lineOf(t)) else () - // T[args]: as many args as T has [] binders (only an enum has any), each a type - val arity = if isEnum(ds, n) then enumArity(ds, n) else 0 - if len(tyArgs(t)) != arity then err("wrong number of type args for", n, lineOf(t)) else () - var c = tyArgs(t) - while !isNil(c) do - needTy(ds, head(c)) - c = tail(c) - if isProto(ds, n) then - val st = protoStates(declList(ds), n) - if rt_str_len(text2(t)) > 0 && (!has(st, text2(t)) || !has(st, tyTo(t))) then err("unknown protocol state in", n, lineOf(t)) else () - else () - -// region (cap) params of a signature -def regionParams {r: Region} (ps: Nodes): Nodes = - var out = NNil - var c = ps - while !isNil(c) do - if eqs(text(kid(head(c), 0)), "Region") then out = NCons(leaf(TyCap, text(head(c)), 0), out) else () - c = tail(c) - out - -// signature type as seen in the body: unannotated enum = region params + ρ -def sigTy {r: Region} (ds: Decls, ps: Nodes, t: Node): Node = - if isEnum(ds, text(t)) && num(t) == 0 then recap(t, NCons(leaf(TyCap, "*", 0), regionParams(ps))) - else t - -// one name, one meaning (vic-gkz): fns and enum cases share the call namespace, enums/protocols/traits/handlers the -// type namespace; a second decl of a name would silently lose to the first (find takes the first) -def uniqueNames {r: Region} (ds: Nodes): Unit = - var vals = NNil - var tys = NNil - var c = ds - while !isNil(c) do - val d = head(c) - val k = kind(d) - if k == DFn then - if has(vals, text(d)) then err("duplicate name:", text(d), lineOf(d)) else () - vals = NCons(d, vals) - else () - if k == DEnum || k == DProto || k == DTrait || k == DHandler || k == DType then - if has(tys, text(d)) then err("duplicate type name:", text(d), lineOf(d)) else () - tys = NCons(d, tys) - else () - if k == DEnum then - var cs = kids(d) - while !isNil(cs) do - if has(vals, text(head(cs))) then err("duplicate name:", text(head(cs)), lineOf(head(cs))) else () - vals = NCons(head(cs), vals) - cs = tail(cs) - else () - c = tail(c) - -// the program checked: decls with fn bodies expanded (e2), for the C emitter -def check {r: Region} (ds0: Nodes): Nodes = - // type lambdas applied, match types reduced (s1/types.srs) - val ds1 = expandTypes(mkDecls(ds0)) - uniqueNames(ds1) - // the decls passed down carry the fns with effects (s1/purity.srs), not the output - val dd = mkDecls(ds1) - val ds = declsCons(impureDecl(dd), dd) - var c = ds1 - var out = NNil - while !isNil(c) do - val d = head(c) - if kind(d) == DFn then checkSig(ds, d) else () - if kind(d) == DEnum then checkEnum(ds, d) else () - if kind(d) == DProto then checkProto(ds, d) else () - if kind(d) == DTrait then checkTrait(ds, d) else () - // spec defs: pure, no regions; Lean type-checks them - // defs and spec defs (pure mode, vic-u2d U1) are checked; their expansion e2 is kept - val d2 = if kind(d) == DFn && (num(d) == 0 || num(d) == 2) then checkFn(ds, d) else if kind(d) == DHandler then checkHandler(ds, d) else if kind(d) == DGiven then checkGiven(ds, d) else if kind(d) == DFn && num(d) == 1 then withKids(d, NCons(list(Params, lineOf(d), sigParams(ds, d, defSol(ds, d))), tail(kids(d)))) else d - out = NCons(d2, out) - c = tail(c) - rev(out) - -def checkEnum {r: Region} (ds0: Decls, d: Node): Unit = - // its [] binders are types in its field types; [] and <> on an enum: not yet - val gs = kids(kid(head(kids(d)), 1)) - var g = gs - while !isNil(g) do - if !eqs(text(head(g)), "[") then err("not yet: binder group on an enum", text(head(g)), lineOf(head(g))) else () - g = tail(g) - val ds = declsPrepend(groupBinders(gs), ds0) - var cs = kids(d) - while !isNil(cs) do - var fs = kids(kid(head(cs), 0)) - while !isNil(fs) do - val t = kid(head(fs), 0) - needTy(ds, t) - if isProto(ds, text(t)) then err("capability stored in data:", text(head(fs)), lineOf(t)) else () - fs = tail(fs) - cs = tail(cs) - -def checkProto {r: Region} (ds: Decls, d: Node): Unit = - val st = protoStates(declList(ds), text(d)) - if !has(st, text2(d)) then err("unknown start state in protocol", text(d), lineOf(d)) else () - checkRules(ds, d) - var ops = kids(kid(d, 3)) - while !isNil(ops) do - var tr = kids(kid(head(ops), 2)) - while !isNil(tr) do - if !has(st, text(head(tr))) || !has(st, text2(head(tr))) then err("unknown state in op", text(head(ops)), lineOf(head(ops))) else () - tr = tail(tr) - ops = tail(ops) - val dn = text(kid(d, 2)) - if rt_str_len(dn) > 0 && !found(find(kids(kid(d, 3)), DOp, dn)) then err("unknown drop op", dn, lineOf(d)) else () - -def checkHandler {r: Region} (ds: Decls, h: Node): Node = - val p = findDecl(ds, DProto, text2(h)) - if !found(p) then err("unknown protocol", text2(h), lineOf(h)) else () - if !found(find(kids(h), DFn, "init")) then err("handler needs init:", text(h), lineOf(h)) else () - var ops = kids(kid(p, 3)) - while !isNil(ops) do - val op = head(ops) - val f = find(kids(h), DFn, text(op)) - if !found(f) then err("handler misses op", text(op), lineOf(h)) else () - // impl = (self: Ptr, op params...): op ret - if len(kids(kid(f, 0))) != len(kids(kid(op, 0))) + 1 || !eqs(text(kid(f, 1)), text(kid(op, 1))) then err("handler op signature differs from protocol:", text(op), lineOf(f)) else () - ops = tail(ops) - var fs = kids(h) - var fs2 = NNil - while !isNil(fs) do - if !isNil(kids(kid(head(fs), 4))) then err("not yet: binder groups on a handler fn", text(head(fs)), lineOf(head(fs))) else () - checkSig(ds, head(fs)) - fs2 = NCons(checkFn(ds, head(fs)), fs2) - fs = tail(fs) - withKids(h, rev(fs2)) - -// [] binders of f: the binders of its [] groups, each of kind Type (vic-9l7.4 BD2) -def tparams {r: Region} (f: Node): Nodes = groupBinders(kids(kid(f, 4))) - -// decls as seen in f's signature and body: its [] binders are types there -def withTParams {r: Region} (ds: Decls, f: Node): Decls = declsPrepend(tparams(f), ds) - -def checkSig {r: Region} (ds0: Decls, f: Node): Unit = - // [] type ascriptions, {} evidence (a trait application); <> facts: BD5 - var gs = kids(kid(f, 4)) - while !isNil(gs) do - val g = head(gs) - if !eqs(text(g), "[") && !eqs(text(g), "{") && !eqs(text(g), "<") then err("not yet: binder group", text(g), lineOf(g)) else () - if eqs(text(g), "<") then needFacts(ds0, f, g) else () - var bs = kids(g) - while !isNil(bs) do - val k = kid(head(bs), 0) - if eqs(text(g), "[") then - if !eqs(text(k), "Type") || !isNil(kids(k)) then err("not yet: [] binder of kind", text(k), lineOf(head(bs))) else () - if isBuiltin(text(head(bs))) || isEnum(ds0, text(head(bs))) || isProto(ds0, text(head(bs))) then err("[] binder hides a type:", text(head(bs)), lineOf(head(bs))) else () - else if eqs(text(g), "{") && !isProto(ds0, text(k)) then needTrait(withTParams(ds0, f), termTy(k)) - else () - bs = tail(bs) - gs = tail(gs) - val ds = withTParams(ds0, f) - var ps = kids(kid(f, 0)) - while !isNil(ps) do - val pt = kid(head(ps), 0) - needTy(ds, pt) - // a capability is evidence: a {} binder, never a value param (vic 2026-11-05) - if isProto(ds, text(pt)) && num(f) != 1 then err("a capability is a {} binder, not a param:", text(head(ps)), lineOf(head(ps))) else () - ps = tail(ps) - needTy(ds, kid(f, 1)) - if isProto(ds, text(kid(f, 1))) then err("capability returned from", text(f), lineOf(f)) else () - -// the env and Γ a fn body starts in: params, caps in their `from` state (also used by the Lean backend) -// f's {} binders of a protocol type: its capabilities (vic 2026-11-05: capability = evidence of a handler), -// as params in written order; the elaborated fn has them first, so C and the body see ordinary cap params -def capParams {r: Region} (ds: Decls, f: Node, sol: Nodes): Nodes = - var out = NNil - var gs = kids(kid(f, 4)) - while !isNil(gs) do - if kind(head(gs)) == Group && eqs(text(head(gs)), "{") then - var bs = kids(head(gs)) - while !isNil(bs) do - val k = kid(head(bs), 0) - // its states: before the params = entry, after the result = exit (unchanged if absent) - val from = capState(f, text(head(bs)), "", sol) - val out2 = capState(f, text(head(bs)), "out", sol) - val to = if rt_str_len(out2) > 0 then out2 else from - if isProto(ds, text(k)) then out = NCons(Node(Param, text(head(bs)), "", 0, lineOf(head(bs)), one(Node(Ty, text(k), from, 0, lineOf(k), one(Node(TyTo, to, "", 0, 0, NNil))))), out) else () - bs = tail(bs) - else () - gs = tail(gs) - rev(out) - -// f's params as its body sees them: capabilities, then values -def sigParams {r: Region} (ds: Decls, f: Node, sol: Nodes): Nodes = append(capParams(ds, f, sol), kids(kid(f, 0))) - -def fnEnv {r: Region} (ds: Decls, ps: Nodes): Nodes = - var env = NNil - var c = ps - while !isNil(c) do - val p = head(c) - val t = kid(p, 0) - if isProto(ds, text(t)) then env = NCons(Node(BVar, text(p), text(t), 2, lineOf(p), one(t)), env) - else env = NCons(Node(BVar, text(p), "", 0, lineOf(p), one(sigTy(ds, ps, t))), env) - c = tail(c) - env -def fnGam {r: Region} (ds: Decls, ps: Nodes): Nodes = - var gam = NNil - var c = ps - while !isNil(c) do - val t = kid(head(c), 0) - if isProto(ds, text(t)) then - val from = if rt_str_len(text2(t)) > 0 then text2(t) else text2(findDecl(ds, DProto, text(t))) - gam = NCons(Node(GState, text(head(c)), from, 0, 0, NNil), gam) - else () - c = tail(c) - gam - -// f with its body expanded (e2). variables in its facts: the body is checked once per solution (vic (a′)), and -// must end in each solution's exit state; the expansion does not depend on states, so the first one is kept -def checkFn {r: Region} (ds0: Decls, f: Node): Node = - if hasVars(f) then - val ss = solutions(withTParams(ds0, f), f, NNil) - if isNil(ss) then err("entry facts have no solution:", text(f), lineOf(f)) else () - var c = tail(ss) - while !isNil(c) do - checkFnAt(ds0, f, kids(head(c))) - c = tail(c) - checkFnAt(ds0, f, kids(head(ss))) - else checkFnAt(ds0, f, NNil) - -def checkFnAt {r: Region} (ds0: Decls, f: Node, sol: Nodes): Node = - val ds = withTParams(ds0, f) - val ps = sigParams(ds, f, sol) - val env0 = append(evEnv(ds, f), fnEnv(ds, ps)) - // a spec def body: checked in pure mode (vic-u2d U1), the compile-time fragment - val env = if num(f) == 2 then NCons(leaf(BVar, "%pure", lineOf(f)), env0) else env0 - val res = chk(ds, env, fnGam(ds, ps), kid(f, 2), NoNode) - needAssign(tgTy(res), sigTy(ds, ps, kid(f, 1)), lineOf(f)) - var c = ps - while !isNil(c) do - val t = kid(head(c), 0) - if isProto(ds, text(t)) then - val want = if rt_str_len(text2(t)) > 0 then tyTo(t) else text2(findDecl(ds, DProto, text(t))) - if !eqs(state(tgGam(res), text(head(c))), want) then err("capability must end in its declared state:", text(head(c)), lineOf(f)) else () - else () - c = tail(c) - // elaborated: capabilities are leading params (the call e2 passes them first) - withKids(f, NCons(list(Params, lineOf(f), ps), NCons(kid(f, 1), NCons(tgE(res), tail(tail(tail(kids(f)))))))) - -// want: the type the context expects (an annotation, a param), or NoNode; it solves [] binders only the result names -def chk {r: Region} (ds: Decls, env: Nodes, gam: Nodes, e: Node, want: Node): TG = - val k = kind(e) - val line = lineOf(e) - if k == XInt then TG(prim("I64"), gam, e) - else if k == XBool then TG(prim("Bool"), gam, e) - else if k == XStr then TG(prim("Str"), gam, e) - else if k == XUnit then TG(prim("Unit"), gam, e) - else if k == XName then - val b = find(env, BVar, text(e)) - if found(b) then - if num(b) == 2 then err("capability is second-class, only a call argument:", text(e), line) else () - if num(b) == 3 then err("evidence is only a method receiver:", text(e), line) else () - // a var's caps are flow state: what it holds now (C8) - val t = if num(b) == 1 then recap(kid(b, 0), kids(find(gam, GVar, text(e)))) else kid(b, 0) - needLive(declList(ds), env, gam, t, line) - needStates(gam, t, line) - TG(t, gam, e) - else - val c = findDecl(ds, DCase, text(e)) - if !found(c) then err("unknown name", text(e), line) else () - if !isNil(kids(kid(c, 0))) then err("constructor needs arguments:", text(e), line) else () - chkNullary(ds, gam, c, e, want) - else if k == XCall then - val c = findDecl(ds, DCase, text(e)) - if found(c) then chkCtor(ds, env, gam, c, e, want) else chkCall(ds, env, gam, e, want, NNil) - else if k == XCallG then - if found(findDecl(ds, DCase, text(e))) then err("not yet: [] or {} on a constructor", text(e), line) else () - chkCall(ds, env, gam, Node(XCall, text(e), "", 0, line, tail(kids(e))), want, kids(head(kids(e)))) - else if k == XMethod then - val ev = find(env, BVar, text(e)) - if found(ev) && num(ev) == 3 then chkEv(ds, env, gam, e, ev) else chkMethod(ds, env, gam, e) - else if k == XBin then chkBin(ds, env, gam, e) - else if k == XUn then - val a = chk(ds, env, gam, kid(e, 0), NoNode) - val need = if eqs(text(e), "-") then "I64" else "Bool" - needAssign(tgTy(a), prim(need), line) - TG(tgTy(a), tgGam(a), withKids(e, one(tgE(a)))) - else if k == XIf then - val c = chk(ds, env, gam, kid(e, 0), NoNode) - needAssign(tgTy(c), prim("Bool"), line) - val t = chk(ds, env, tgGam(c), kid(e, 1), want) - val f = chk(ds, env, tgGam(c), kid(e, 2), want) - val e2 = withKids(e, NCons(tgE(c), NCons(tgE(t), one(tgE(f))))) - TG(join(tgTy(t), tgTy(f), line), joinGam(tgGam(t), tgGam(f), branchErr(), line), e2) - else if k == XMatch then chkMatch(ds, env, gam, e, want) - else if k == XBlock then chkBlock(ds, env, gam, e, want) - else if k == XWhile then chkWhile(ds, env, gam, e) - else if k == XAssign then - val b = find(env, BVar, text(e)) - if !found(b) || num(b) != 1 then err("assignment to non-var", text(e), line) else () - val a = chk(ds, env, gam, kid(e, 0), NoNode) - needAssign(tgTy(a), bound(kid(b, 0), tgTy(a)), line) - // strong update: the var now holds the caps of the new value (C8) - TG(prim("Unit"), setG(tgGam(a), Node(GVar, text(e), "", 0, 0, tyCaps(tgTy(a)))), withKids(e, one(tgE(a)))) - else - err("internal: expression", "?", line) - TG(prim("Unit"), gam, e) - -def branchErr(): Str = "branches leave capabilities in different states:" - -// Γ after a loop = fixpoint over any number of turns: var caps grow by union until stable, cap states fixed -def chkWhile {r: Region} (ds: Decls, env: Nodes, gam: Nodes, e: Node): TG = - val what = "loop changes capability state, protocol needs a fixed count:" - var g = gam - var done = false - var e2 = e - while !done do - val c = chk(ds, env, g, kid(e, 0), NoNode) - needAssign(tgTy(c), prim("Bool"), lineOf(e)) - val b = chk(ds, env, tgGam(c), kid(e, 1), NoNode) - val w = joinGam(g, joinGam(tgGam(c), tgGam(b), what, lineOf(e)), what, lineOf(e)) - done = within(w, g) - g = w - // the expansion of the last turn: types do not depend on Γ, so every turn expands the same - e2 = withKids(e, NCons(tgE(c), one(tgE(b)))) - TG(prim("Unit"), g, e2) - -def join {r: Region} (a: Node, b: Node, line: I64): Node = - if !tyEq(a, b) then needAssign(a, b, line) else () - recap(a, union(tyCaps(a), tyCaps(b))) - -def chkBin {r: Region} (ds: Decls, env: Nodes, gam: Nodes, e: Node): TG = - val op = text(e) - val line = lineOf(e) - val a = chk(ds, env, gam, kid(e, 0), NoNode) - val b = chk(ds, env, tgGam(a), kid(e, 1), NoNode) - val ta = tgTy(a) - val tb = tgTy(b) - val e2 = withKids(e, NCons(tgE(a), one(tgE(b)))) - if eqs(op, "&&") || eqs(op, "||") then - needAssign(ta, prim("Bool"), line) - needAssign(tb, prim("Bool"), line) - TG(prim("Bool"), tgGam(b), e2) - else if eqs(op, "==") || eqs(op, "!=") then - if !tyEq(ta, tb) then needAssign(tb, ta, line) else () - if eqs(text(ta), "Str") then err("Str has no ==, use", "rt_str_eq", line) else () - TG(prim("Bool"), tgGam(b), e2) - else - needAssign(ta, prim("I64"), line) - needAssign(tb, prim("I64"), line) - val cmp = eqs(op, "<") || eqs(op, "<=") || eqs(op, ">") || eqs(op, ">=") - TG(prim(if cmp then "Bool" else "I64"), tgGam(b), e2) - -// in a spec def body: the env holds the marker %pure (no srs name has a %) -def isPure(env: Nodes): Bool = found(find(env, BVar, "%pure")) - -// the externs without effects: pure, total, also in Lean (lean/Srs/Rt.lean namespace P) -def isPureExtern(n: Str): Bool = eqs(n, "rt_str_len") || eqs(n, "rt_str_at") || eqs(n, "rt_str_slice") || eqs(n, "rt_str_eq") - -// the one capability of protocol p in scope: what a {} binder of a callee takes (vic-9l7.7) -def theCap(env: Nodes, p: Str, line: I64): Str = - var c = env - var res = "" - var n = 0 - while !isNil(c) do - val b = head(c) - if num(b) == 2 && eqs(text2(b), p) && !eqs(text(b), res) then - if n == 0 then res = text(b) else () - n = n + 1 - else () - c = tail(c) - if n == 0 then err("no capability in scope for", p, line) else () - if n > 1 then err("ambiguous capability, more than one in scope for", p, line) else () - res - -// a chosen capability: a cap of protocol p in scope -def chosenCap(env: Nodes, n: Str, p: Str, line: I64): Str = - val b = find(env, BVar, n) - if !found(b) || num(b) != 2 || !eqs(text2(b), p) then err("chosen name is not a capability of", p, line) else () - n - -// unique Region capability in scope (effects.md) -def theRegion(env: Nodes, line: I64): Str = - var c = env - var res = "" - var n = 0 - while !isNil(c) do - val b = head(c) - if num(b) == 2 && eqs(text2(b), "Region") && !eqs(text(b), res) then - if n == 0 then res = text(b) else () - n = n + 1 - else () - c = tail(c) - if n == 0 then err("constructor needs a Region capability in scope", "", line) else () - if n > 1 then err("constructor region is ambiguous, more than one Region in scope", "", line) else () - res - -// op opName of protocol proto; its transition from the state of cap in gam -spec def opS(ds: Nodes, proto: Str, opName: Str): Node = lookS(kidsS(nthS(kidsS(lookS(ds, DProto, proto)), 3)), DOp, opName) -spec def trS(ds: Nodes, gam: Nodes, cap: Str, proto: Str, opName: Str): Node = - lookS(kidsS(nthS(kidsS(opS(ds, proto, opName)), 2)), DTrans, text2S(lookS(gam, GState, cap))) -// one protocol step on cap: Γ(cap) must have a transition in op -// accepts only when op and its transition exist; Γ after = cap moved to the transition target -def step {r: Region} (ds: Nodes, gam: Nodes, cap: Str, proto: Str, opName: Str, line: I64): Nodes - returns foundS(opS(ds, proto, opName)) && foundS(trS(ds, gam, cap, proto, opName)) && result == replS(gam, Node(GState, cap, text2S(trS(ds, gam, cap, proto, opName)), 0, 0, NNil)) -= - val op = find(kids(kid(find(ds, DProto, proto), 3)), DOp, opName) - if !found(op) then err("unknown op", opName, line) else () - val s = state(gam, cap) - val tr = find(kids(kid(op, 2)), DTrans, s) - if !found(tr) then - rt_eprint("srs:") - rt_eprint_i64(line) - rt_eprint(": error: protocol ") - rt_eprint(proto) - rt_eprint(": op '") - rt_eprint(opName) - rt_eprint("' not allowed in state ") - rt_eprint(s) - rt_eprint(" of '") - rt_eprint(cap) - rt_eprint("'\n") - rt_exit(1) - else () - setG(gam, Node(GState, cap, text2(tr), 0, 0, NNil)) - -def chkCtor {r: Region} (ds: Decls, env: Nodes, gam0: Nodes, c: Node, e: Node, want: Node): TG = - val line = lineOf(e) - var fs = kids(kid(c, 0)) - if len(fs) != len(kids(e)) then err("constructor arity", text(c), line) else () - if isNil(fs) then err("nullary constructor takes no ()", text(c), line) else () - // a spec def builds compile-time data: no Region (vic Q-U4); else the one Region in scope allocates it - val inSpec = isPure(env) - val reg = if inSpec then "" else theRegion(env, line) - var gam = if inSpec then gam0 else step(declList(ds), gam0, reg, "Region", "alloc", line) - var caps = if inSpec then NNil else one(leaf(TyCap, reg, line)) - // a generic enum: the field types match the args, binding its [] binders (as chkCall) - val tps = enumTParams(ds, text2(c)) - var sub = NNil - var a = kids(e) - var a2 = NNil - while !isNil(a) do - val ft = kid(head(fs), 0) - val w = applyTy(sub, ft) - val x = chk(ds, env, gam, head(a), if mentions(tps, w) then NoNode else w) - if mentions(tps, ft) then sub = matchTy(tps, ft, tgTy(x), sub, line) - else if !tyEq(tgTy(x), ft) then needAssign(tgTy(x), ft, line) - else () - caps = union(caps, tyCaps(tgTy(x))) - gam = tgGam(x) - a2 = NCons(tgE(x), a2) - a = tail(a) - fs = tail(fs) - if isNil(tps) then TG(mkTy(text2(c), caps), gam, withKids(e, rev(a2))) - else - val self = enumSelf(text2(c), tps) - if mentions(tps, applyTy(sub, self)) && found(want) then sub = matchTy(tps, self, want, sub, line) else () - val targs = instArgs(tps, sub, line) - TG(recap(applyTy(sub, self), caps), gam, Node(XNew, text(c), "", 0, line, NCons(list(Names, line, targs), rev(a2)))) - -// enum n applied to its own [] binders: the pattern its values match -def enumSelf {r: Region} (n: Str, tps: Nodes): Node = - var out = NNil - var c = tps - while !isNil(c) do - out = NCons(mkTy(text(head(c)), NNil), out) - c = tail(c) - Node(Ty, n, "", 1, 0, one(Node(TyTo, "", "", 0, 0, rev(out)))) - -// a nullary case of a generic enum: the expected type gives its type args -def chkNullary {r: Region} (ds: Decls, gam: Nodes, c: Node, e: Node, want: Node): TG = - val tps = enumTParams(ds, text2(c)) - if isNil(tps) then TG(prim(text2(c)), gam, e) - else - val sub = if found(want) then matchTy(tps, enumSelf(text2(c), tps), want, NNil, lineOf(e)) else NNil - val targs = instArgs(tps, sub, lineOf(e)) - TG(recap(applyTy(sub, enumSelf(text2(c), tps)), NNil), gam, Node(XNew, text(c), "", 0, lineOf(e), one(list(Names, lineOf(e), targs)))) - -spec def tgGamS(x: TG): Nodes = x match - case TG(_, g, _) => g -// accepts only when, in the Γ after the args, op and its transition exist; Γ after = cap e moved by op -def chkMethod {r: Region} (ds: Decls, env: Nodes, gam0: Nodes, e: Node): TG - returns exists gam: Nodes => foundS(opS(declsS(ds), text2S(lookS(env, BVar, textS(e))), text2S(e))) && foundS(trS(declsS(ds), gam, textS(e), text2S(lookS(env, BVar, textS(e))), text2S(e))) && tgGamS(result) == replS(gam, Node(GState, textS(e), text2S(trS(declsS(ds), gam, textS(e), text2S(lookS(env, BVar, textS(e))), text2S(e))), 0, 0, NNil)) -= - val line = lineOf(e) - val b = find(env, BVar, text(e)) - if !found(b) || num(b) != 2 then err("not a capability:", text(e), line) else () - val op = find(kids(kid(find(declList(ds), DProto, text2(b)), 3)), DOp, text2(e)) - if !found(op) then err("unknown op", text2(e), line) else () - var ps = kids(kid(op, 0)) - if len(ps) != len(kids(e)) then err("op arity", text2(e), line) else () - var gam = gam0 - var a = kids(e) - var a2 = NNil - while !isNil(a) do - val x = chk(ds, env, gam, head(a), NoNode) - needAssign(tgTy(x), kid(head(ps), 0), line) - gam = tgGam(x) - a2 = NCons(tgE(x), a2) - a = tail(a) - ps = tail(ps) - TG(kid(op, 1), step(declList(ds), gam, text(e), text2(b), text2(e), line), withKids(e, rev(a2))) - -// map callee cap-param name -> caller cap name -def mapCaps {r: Region} (caps: Nodes, m: Nodes): Nodes = - var out = NNil - var c = caps - while !isNil(c) do - val g = find(m, GState, text(head(c))) - // a fact on a type (vic-jxk): the cap keeps its required state (t) - out = NCons(Node(TyCap, if found(g) then text2(g) else text(head(c)), text2(head(c)), 0, 0, NNil), out) - c = tail(c) - out - -// gs: the call's groups (f[T]{a}(x), vic 2026-11-05): explicit type args, the {} binders chosen by name -def chkCall {r: Region} (ds: Decls, env: Nodes, gam0: Nodes, e: Node, want: Node, gs: Nodes): TG = - val line = lineOf(e) - val f = findDecl(ds, DFn, text(e)) - if !found(f) then err("unknown function", text(e), line) else () - // a spec def calls only fns without effects: pure defs and the pure externs (vic-u2d U1b, s1/purity.srs) - if isPure(env) && isImpure(ds, text(f)) then err("a spec def calls only pure defs and pure externs, not", text(e), line) else () - var ps = kids(kid(f, 0)) - if len(ps) != len(kids(e)) then err("arity of", text(e), line) else () - // pass 1: cap args, protocol state transitions S1 -> S2 - var m = NNil - var gam = gam0 - var a = kids(e) - var p = ps - while !isNil(a) do - val pt = kid(head(p), 0) - if isProto(ds, text(pt)) then - val x = head(a) - val b = find(env, BVar, text(x)) - if kind(x) != XName || !found(b) || num(b) != 2 || !eqs(text2(b), text(pt)) then err("expected capability argument of protocol", text(pt), line) else () - if found(find(m, GState, text(head(p)))) || has(mapVals(m), text(x)) then err("capability passed twice:", text(x), line) else () - m = NCons(Node(GState, text(head(p)), text(x), 0, 0, NNil), m) - else () - a = tail(a) - p = tail(p) - // {} capabilities: the one cap of that protocol in scope (as a constructor finds its region); 0 or 2+ = reject - val cps = capParams(ds, f, NNil) - // f{a, b}(x): one name per {} binder of f, in written order, else each found in scope - val ch = callGroup(gs, "{") - if !isNil(ch) && len(ch) != curlyCount(f) then err("wrong number of chosen evidence for", text(e), line) else () - var c = cps - var capArgs = NNil - while !isNil(c) do - val proto = text(kid(head(c), 0)) - val cap = if isNil(ch) then theCap(env, proto, line) else chosenCap(env, text(nth(ch, curlyIndex(f, text(head(c))))), proto, line) - if has(mapVals(m), cap) then err("capability passed twice:", cap, line) else () - m = NCons(Node(GState, text(head(c)), cap, 0, 0, NNil), m) - capArgs = NCons(leaf(XName, cap, line), capArgs) - c = tail(c) - var allPs = append(cps, ps) - // pass 2: value args, left to right - val tps = tparams(f) - // f[T1, T2](x): the [] binders given, else matched from the args - val ex = callGroup(gs, "[") - if !isNil(ex) && len(ex) != len(tps) then err("wrong number of type args for", text(e), line) else () - var tx = ex - while !isNil(tx) do - needTy(ds, head(tx)) - tx = tail(tx) - var sub = zipBind(tps, ex) - var rho = NNil - var a2 = NNil - a = kids(e) - p = ps - while !isNil(a) do - val pt = kid(head(p), 0) - // cap args stay as written - if isProto(ds, text(pt)) then a2 = NCons(head(a), a2) else () - if mentions(tps, pt) then - // the param type names [] binders: the arg type matches it, binding them; bound ones must agree - val w = applyTy(sub, pt) - val x = chk(ds, env, gam, head(a), if mentions(tps, w) then NoNode else w) - gam = tgGam(x) - a2 = NCons(tgE(x), a2) - sub = matchTy(tps, pt, tgTy(x), sub, line) - rho = union(rho, tyCaps(tgTy(x))) - else if !isProto(ds, text(pt)) then - val x = chk(ds, env, gam, head(a), pt) - gam = tgGam(x) - a2 = NCons(tgE(x), a2) - if isEnum(ds, text(pt)) && num(pt) == 0 then - if !tyEq(tgTy(x), pt) then needAssign(tgTy(x), pt, line) else () - rho = union(rho, tyCaps(tgTy(x))) - else needAssign(tgTy(x), recap(pt, mapCaps(tyCaps(pt), m)), line) - else () - a = tail(a) - p = tail(p) - // cap transitions happen during the call, after the args - // variables in its facts: Datalog binds them from the caps' states in Γ now (one solution), giving each cap its - // entry and exit state (vic (a′)) - if hasVars(f) then allPs = append(capParams(ds, f, callSol(ds, f, capEntry(m, gam), line)), ps) else () - p = allPs - while !isNil(p) do - val pt = kid(head(p), 0) - if isProto(ds, text(pt)) then - val cap = text2(find(m, GState, text(head(p)))) - val from = if rt_str_len(text2(pt)) > 0 then text2(pt) else text2(findDecl(ds, DProto, text(pt))) - val to = if rt_str_len(text2(pt)) > 0 then tyTo(pt) else from - if !eqs(state(gam, cap), from) then - rt_eprint("srs:") - rt_eprint_i64(line) - rt_eprint(": error: '") - rt_eprint(text(e)) - rt_eprint("' needs '") - rt_eprint(cap) - rt_eprint("' in state ") - rt_eprint(from) - rt_eprint(", it is ") - rt_eprint(state(gam, cap)) - rt_eprint("\n") - rt_exit(1) - else () - gam = setG(gam, Node(GState, cap, to, 0, 0, NNil)) - else () - p = tail(p) - val rt = kid(f, 1) - if isNil(tps) then - // the callee's {} evidence: each goal has one given (s1/given.srs) - goals(ds, env, kids(kid(f, 4)), NNil, ch, givenFuel(), line) - val caps = if isEnum(ds, text(rt)) && num(rt) == 0 then union(rho, mapCaps(regionParams(allPs), m)) else mapCaps(tyCaps(rt), m) - TG(recap(rt, caps), gam, withKids(e, append(rev(capArgs), rev(a2)))) - else - // a [] binder only the result names: the context's expected type solves it (check mode) - if mentions(tps, applyTy(sub, rt)) && found(want) then sub = matchTy(tps, rt, want, sub, line) else () - val targs = instArgs(tps, sub, line) - goals(ds, env, kids(kid(f, 4)), sub, ch, givenFuel(), line) - // a value of a [] binder lives in the regions of the args given for it - val rt2 = applyTy(sub, rt) - // only data (an enum, or a [] binder still open) lives in regions; I64, Bool, ... carry none - val res = if mentions(tps, rt) then recap(rt2, if isEnum(ds, text(rt2)) || isTParam(ds, text(rt2)) then rho else NNil) else recap(rt, mapCaps(tyCaps(rt), m)) - TG(res, gam, Node(XInst, text(e), "", 0, line, NCons(list(Names, line, targs), append(rev(capArgs), rev(a2))))) - -// t is one of the [] binders tps -def isTP(tps: Nodes, t: Node): Bool = found(find(tps, Binder, text(t))) - -// binder i of tps bound to type i of ts -def zipBind {r: Region} (tps: Nodes, ts: Nodes): Nodes = - if isNil(tps) || isNil(ts) then NNil - else NCons(Node(Binder, text(head(tps)), "", 0, 0, one(head(ts))), zipBind(tail(tps), tail(ts))) - -// t names a [] binder of tps, whole or inside T[args] -def mentions(tps: Nodes, t: Node): Bool = isTP(tps, t) || anyMentions(tps, tyArgs(t)) -def anyMentions(tps: Nodes, ts: Nodes): Bool = if isNil(ts) then false else mentions(tps, head(ts)) || anyMentions(tps, tail(ts)) - -// sub extended so the pattern p (it may name [] binders tps) is the type a: one-sided unify (a names none of tps) -def matchTy {r: Region} (tps: Nodes, p: Node, a: Node, sub: Nodes, line: I64): Nodes = - if isTP(tps, p) then - val b = find(sub, Binder, text(p)) - if found(b) then - needSame(a, kid(b, 0), line) - sub - else NCons(Node(Binder, text(p), "", 0, line, one(recap(a, NNil))), sub) - else - if !eqs(text(p), text(a)) || len(tyArgs(p)) != len(tyArgs(a)) then needAssign(a, p, line) else () - var s = sub - var ps = tyArgs(p) - var as = tyArgs(a) - while !isNil(ps) do - s = matchTy(tps, head(ps), head(as), s, line) - ps = tail(ps) - as = tail(as) - s - -// t with its bound [] binders replaced; caps and to-state kept -def applyTy {r: Region} (sub: Nodes, t: Node): Node = - val b = find(sub, Binder, text(t)) - if found(b) && isNil(tyArgs(t)) then kid(b, 0) - else - var out = NNil - var c = tyArgs(t) - while !isNil(c) do - out = NCons(applyTy(sub, head(c)), out) - c = tail(c) - Node(Ty, text(t), text2(t), num(t), lineOf(t), NCons(Node(TyTo, tyTo(t), "", 0, 0, rev(out)), tyCaps(t))) - -// a [] binder bound twice: the same type (unify on names, BD2; structure comes with type application, BD3) -def needSame(a: Node, b: Node, line: I64): Unit = if !tyEq(a, b) then needAssign(a, b, line) else () - -// the types of an instance, in [] binder order; every [] binder must be solved -def instArgs {r: Region} (tps: Nodes, sub: Nodes, line: I64): Nodes = - var out = NNil - var c = tps - while !isNil(c) do - val b = find(sub, Binder, text(head(c))) - if !found(b) then err("cannot infer", text(head(c)), line) else () - out = NCons(kid(b, 0), out) - c = tail(c) - rev(out) - -def mapVals {r: Region} (m: Nodes): Nodes = - var out = NNil - var c = m - while !isNil(c) do - out = NCons(leaf(Name, text2(head(c)), 0), out) - c = tail(c) - out - -def chkMatch {r: Region} (ds: Decls, env: Nodes, gam: Nodes, e: Node, want: Node): TG = - val line = lineOf(e) - val s = chk(ds, env, gam, kid(e, 0), NoNode) - val st = tgTy(s) - val en = findDecl(ds, DEnum, text(st)) - if !found(en) then err("match on non-enum type", text(st), line) else () - var arms = tail(kids(e)) - var seen = NNil - var wild = false - var res = NoNode - var out = NNil - var arms2 = NNil - while !isNil(arms) do - val arm = head(arms) - var env2 = env - if eqs(text(arm), "_") then wild = true - else - val c = find(kids(en), DCase, text(arm)) - if !found(c) then err("not a case of the scrutinee enum:", text(arm), lineOf(arm)) else () - seen = NCons(leaf(Name, text(arm), 0), seen) - var bs = tail(kids(arm)) - var fs = kids(kid(c, 0)) - if len(bs) != len(fs) then err("pattern arity", text(arm), lineOf(arm)) else () - while !isNil(bs) do - val ft = kid(head(fs), 0) - // fields share the capture of the scrutinee - // a generic enum: the scrutinee's type args fill the field types - val ft2 = applyTy(zipBind(enumTParams(ds, text(st)), tyArgs(st)), ft) - val bt = if isEnum(ds, text(ft2)) then recap(ft2, tyCaps(st)) else ft2 - env2 = NCons(Node(BVar, text(head(bs)), "", 0, lineOf(arm), one(bt)), env2) - bs = tail(bs) - fs = tail(fs) - val x = chk(ds, env2, tgGam(s), kid(arm, 0), want) - arms2 = NCons(withKids(arm, NCons(tgE(x), tail(kids(arm)))), arms2) - if found(res) then - res = join(res, tgTy(x), lineOf(arm)) - out = joinGam(out, tgGam(x), branchErr(), lineOf(arm)) - else - res = tgTy(x) - out = tgGam(x) - arms = tail(arms) - if !wild then - var cs = kids(en) - while !isNil(cs) do - if !has(seen, text(head(cs))) then err("match is not exhaustive, missing case", text(head(cs)), line) else () - cs = tail(cs) - else () - TG(res, out, withKids(e, NCons(tgE(s), rev(arms2)))) - -def chkBlock {r: Region} (ds: Decls, env0: Nodes, gam0: Nodes, blk: Node, want: Node): TG = - val line = lineOf(blk) - var env = env0 - var gam = gam0 - var caps = NNil - var res = prim("Unit") - var c = kids(blk) - var ss2 = NNil - while !isNil(c) do - val s = head(c) - val k = kind(s) - if k == SClause then ss2 = NCons(s, ss2) - else if k == SVal then - // the annotation is a type first: it is the expected type (want) of the value - if !isNil(tail(kids(s))) then needTy(ds, kid(s, 1)) else () - val x = chk(ds, env, gam, kid(s, 0), if isNil(tail(kids(s))) then NoNode else kid(s, 1)) - ss2 = NCons(withKids(s, NCons(tgE(x), tail(kids(s)))), ss2) - gam = tgGam(x) - var t = tgTy(x) - if !isNil(tail(kids(s))) then - val ann = kid(s, 1) - if isProto(ds, text(ann)) then err("capability bound to a val:", text(s), lineOf(s)) else () - needAssign(t, bound(ann, t), lineOf(s)) - t = if num(s) == 1 then ann else bound(ann, t) - else if num(s) == 1 then t = uncap(t) - else () - if num(s) == 1 then gam = NCons(Node(GVar, text(s), "", 0, 0, tyCaps(tgTy(x))), gam) else () - env = NCons(Node(BVar, text(s), "", num(s), lineOf(s), one(t)), env) - res = prim("Unit") - else if k == SHandle then - if isPure(env) then err("a spec def is pure: no handle of", text2(s), lineOf(s)) else () - val h = findDecl(ds, DHandler, text2(s)) - if !found(h) then err("unknown handler", text2(s), lineOf(s)) else () - val init = find(kids(h), DFn, "init") - var ps = kids(kid(init, 0)) - var a = kids(s) - var a2 = NNil - if len(ps) != len(a) then err("handler init arity", text2(s), lineOf(s)) else () - while !isNil(a) do - val x = chk(ds, env, gam, head(a), NoNode) - needAssign(tgTy(x), kid(head(ps), 0), lineOf(s)) - gam = tgGam(x) - a2 = NCons(tgE(x), a2) - a = tail(a) - ps = tail(ps) - ss2 = NCons(withKids(s, rev(a2)), ss2) - val p = findDecl(ds, DProto, text2(h)) - env = NCons(Node(BVar, text(s), text(p), 2, lineOf(s), one(mkTy(text(p), NNil))), env) - gam = NCons(Node(GState, text(s), text2(p), 0, 0, NNil), gam) - caps = NCons(Node(BVar, text(s), text(p), 2, lineOf(s), NNil), caps) - res = prim("Unit") - else - val x = chk(ds, env, gam, s, if isNil(tail(c)) then want else NoNode) - ss2 = NCons(tgE(x), ss2) - gam = tgGam(x) - res = tgTy(x) - c = tail(c) - // scope end: each handled cap reaches an end state, by itself or by its drop op - while !isNil(caps) do - val b = head(caps) - val p = findDecl(ds, DProto, text2(b)) - val s = state(gam, text(b)) - if !has(kids(kid(p, 1)), s) then - val dn = text(kid(p, 2)) - val op = find(kids(kid(p, 3)), DOp, dn) - val tr = find(kids(kid(op, 2)), DTrans, s) - if rt_str_len(dn) == 0 || !found(tr) || !has(kids(kid(p, 1)), text2(tr)) then - rt_eprint("srs:") - rt_eprint_i64(lineOf(b)) - rt_eprint(": error: protocol ") - rt_eprint(text(p)) - rt_eprint(": '") - rt_eprint(text(b)) - rt_eprint("' ends its scope in state ") - rt_eprint(s) - rt_eprint(", not an end state\n") - rt_exit(1) - else () - else () - if has(tyCaps(res), text(b)) then err("value escapes the scope of its region", text(b), lineOf(b)) else () - caps = tail(caps) - // block entries (caps, vars) were prepended to Γ: cut them - TG(res, drop(gam, len(gam) - len(gam0)), withKids(blk, rev(ss2))) diff --git a/bench/corpus/s1/emit.srs b/bench/corpus/s1/emit.srs deleted file mode 100644 index 07600934..00000000 --- a/bench/corpus/s1/emit.srs +++ /dev/null @@ -1,577 +0,0 @@ -// S1 emitter: decl nodes -> GNU C (statement expressions), same lowering as s0/emit.zig. -// cs = all DCase nodes (t = enum name). env = BVar nodes, innermost first. - -def allCases {r: Region} (ds: Decls): Nodes = - var out = NNil - var c = declList(ds) - while !isNil(c) do - if kind(head(c)) == DEnum then out = append(kids(head(c)), out) else () - c = tail(c) - out - -def ctype(ds: Decls, t: Node): Unit = - val n = text(t) - if eqs(n, "I64") || eqs(n, "Unit") then say("int64_t") - else if eqs(n, "Bool") then say("bool") - else if eqs(n, "Str") then say("srs_str") - else if eqs(n, "Ptr") then say("void*") - else if found(findDecl(ds, DEnum, n)) then - say("struct E_") - say(n) - // an enum instance (mono): its type args name it - if !isNil(tyArgs(t)) then typeSuffix(tyArgs(t)) else () - say("*") - else if found(findDecl(ds, DProto, n)) then say("srs_cap*") - else - rt_eprint(n) - fatal(": unknown type", lineOf(t)) - -// C name of a binding -def cname(b: Node): Unit = - if num(b) < 0 then - say("p_") - say(text(b)) - else - say("v_") - say(text(b)) - say("_") - sayn(num(b)) - -// fn naming: tag 0 = extern (C name), 1 = def (f_), 2 = handler fn (h__) -def fname(f: Node, tag: I64, h: Str): Unit = - // a given's method at a goal (mono): t = the trait, kid 4 = the goal's args - if rt_str_len(text2(f)) > 0 then givenName(text2(f), kids(kid(f, 4)), text(f)) - else fname2(f, tag, h) - -def givenName(trait: Str, args: Nodes, m: Str): Unit = - say("g_") - say(trait) - typeSuffix(args) - say("_") - say(m) - -def fname2(f: Node, tag: I64, h: Str): Unit = - if tag == 1 then say("f_") else () - if tag == 2 then - say("h_") - say(h) - say("_") - else () - say(text(f)) - // an instance (mono): kid 4 = its type args - if kind(kid(f, 4)) == Names then typeSuffix(kids(kid(f, 4))) else () - -// the C name part of an instance: _ then _ per type arg; T[args] as T__... (n = arg count, unambiguous) -def typeSuffix(ts: Nodes): Unit = - say("_") - var c = ts - while !isNil(c) do - say("_") - mangle(head(c)) - c = tail(c) - -def mangle(t: Node): Unit = - say(text(t)) - if !isNil(tyArgs(t)) then - say("_") - sayn(len(tyArgs(t))) - var c = tyArgs(t) - while !isNil(c) do - say("_") - mangle(head(c)) - c = tail(c) - else () - -// an enum instance (mono): kid 1 of its cases holds its type args (Names); a generic enum holds its groups -def enumArgs(d: Node): Nodes = if kind(kid(head(kids(d)), 1)) == Names then kids(kid(head(kids(d)), 1)) else NNil -def isGenericEnum(ds: Decls, d: Node): Bool = kind(kid(head(kids(d)), 1)) == Groups && enumArity(ds, text(d)) > 0 -def enumName(d: Node): Unit = - say(text(d)) - if !isNil(enumArgs(d)) then typeSuffix(enumArgs(d)) else () - -// a [] binder of a generic extern is a void* slot (vic B-Q6) -def slotType(ds: Decls, f: Node, t: Node): Unit = if isTParamOf(f, text(t)) then say("void*") else ctype(ds, t) - -// n names a [] binder of f ([] groups of kid 4; an instance's kid 4 is Names, no groups) -def isTParamOf(f: Node, n: Str): Bool = - var gs = kids(kid(f, 4)) - var res = false - while !res && !isNil(gs) do - res = kind(head(gs)) == Group && eqs(text(head(gs)), "[") && found(find(kids(head(gs)), Binder, n)) - gs = tail(gs) - res - -def sig(ds: Decls, f: Node, tag: I64, h: Str): Unit = - if tag != 0 then say("static ") else () - slotType(ds, f, kid(f, 1)) - say(" ") - fname(f, tag, h) - say("(") - var ps = kids(kid(f, 0)) - if isNil(ps) then say("void") else () - var first = true - while !isNil(ps) do - if !first then say(", ") else () - first = false - slotType(ds, f, kid(head(ps), 0)) - say(" p_") - say(text(head(ps))) - ps = tail(ps) - say(")") - -def unescLen(s: Str): I64 = - var n = 0 - var i = 0 - while i < rt_str_len(s) do - if rt_str_at(s, i) == '\\' then i = i + 2 else i = i + 1 - n = n + 1 - n - -def emitProgram {r: Region} (ds: Decls): Unit = - val cs = allCases(ds) - say("// DO-NOT-EDIT. Generated by srs (s1/emit.srs). bootstrap/seed.c: regenerate with seed-update.\n#include \n#include \n") - say("typedef struct { const uint8_t* p; int64_t n; } srs_str;\n") - say("typedef struct { void* self; void* const* vt; int64_t live; } srs_cap;\n") - say("void rt_init(int argc, char** argv);\n") - var c = declList(ds) - while !isNil(c) do - if kind(head(c)) == DEnum && !isGenericEnum(ds, head(c)) then - say("struct E_") - enumName(head(c)) - say(";\n") - else () - c = tail(c) - c = declList(ds) - while !isNil(c) do - if kind(head(c)) == DEnum && !isGenericEnum(ds, head(c)) then enumDef(ds, head(c)) else () - c = tail(c) - c = declList(ds) - while !isNil(c) do - val d = head(c) - if kind(d) == DFn && num(d) != 2 && !isGeneric(d) then - sig(ds, d, 1 - num(d), "") - say(";\n") - else if kind(d) == DHandler then - var fs = kids(d) - while !isNil(fs) do - sig(ds, head(fs), 2, text(d)) - say(";\n") - fs = tail(fs) - else () - c = tail(c) - c = declList(ds) - while !isNil(c) do - if kind(head(c)) == DHandler then vtable(ds, head(c)) else () - c = tail(c) - c = declList(ds) - while !isNil(c) do - val d = head(c) - if kind(d) == DFn && num(d) == 0 && !isGeneric(d) then body(ds, cs, d, 1, "") - else if kind(d) == DHandler then - var fs = kids(d) - while !isNil(fs) do - body(ds, cs, head(fs), 2, text(d)) - fs = tail(fs) - else () - c = tail(c) - if found(findDecl(ds, DFn, "main")) then say("int main(int argc, char** argv) { rt_init(argc, argv); return (int)f_main(); }\n") else () - -def protoOps(ds: Decls, p: Str): Nodes = kids(kid(findDecl(ds, DProto, p), 3)) - -def vtable(ds: Decls, h: Node): Unit = - say("static void* const vt_") - say(text(h)) - say("[] = {") - var ops = protoOps(ds, text2(h)) - while !isNil(ops) do - say(" (void*)h_") - say(text(h)) - say("_") - say(text(head(ops))) - say(",") - ops = tail(ops) - say(" 0 };\n") - -def enumDef(ds: Decls, d: Node): Unit = - say("struct E_") - enumName(d) - say(" { int64_t tag; union {") - var c = kids(d) - while !isNil(c) do - var fs = kids(kid(head(c), 0)) - if !isNil(fs) then - say(" struct {") - while !isNil(fs) do - say(" ") - ctype(ds, kid(head(fs), 0)) - say(" f_") - say(text(head(fs))) - say(";") - fs = tail(fs) - say(" } C_") - say(text(head(c))) - say(";") - else () - c = tail(c) - say(" int64_t none_; } u; };\n") - c = kids(d) - while !isNil(c) do - if isNil(kids(kid(head(c), 0))) then - say("static struct E_") - enumName(d) - say(" N_") - say(text(head(c))) - if !isNil(enumArgs(d)) then typeSuffix(enumArgs(d)) else () - say(" = { ") - sayn(num(head(c))) - say(", { 0 } };\n") - else () - c = tail(c) - -def paramEnv {r: Region} (ds: Decls, ps: Nodes): Nodes = - var env = NNil - var c = ps - while !isNil(c) do - val p = head(c) - val tn = text(kid(p, 0)) - env = NCons(Node(BVar, text(p), if found(findDecl(ds, DProto, tn)) then tn else "", -1, lineOf(p), kids(p)), env) - c = tail(c) - env - -def body {r: Region} (ds: Decls, cs: Nodes, f: Node, tag: I64, h: Str): Unit = - sig(ds, f, tag, h) - say(" { return ") - ex(ds, cs, paramEnv(ds, kids(kid(f, 0))), kid(f, 2)) - say("; }\n") - -def exArgs {r: Region} (ds: Decls, cs: Nodes, env: Nodes, xs: Nodes, lead: Bool): Unit = - var c = xs - var first = !lead - while !isNil(c) do - if !first then say(", ") else () - first = false - ex(ds, cs, env, head(c)) - c = tail(c) - -// innermost Region capability -def regionOf(env: Nodes): Node = - var c = env - var res = NoNode - while !found(res) && !isNil(c) do - if eqs(text2(head(c)), "Region") then res = head(c) else () - c = tail(c) - res - -def opIndex(ops: Nodes, name: Str): I64 = index(ops, name) - -// a call of a generic fn: a def calls its instance; an extern its one C symbol, a void* result cast to its type -def exInst {r: Region} (ds: Decls, cs: Nodes, env: Nodes, e: Node): Unit = - val f = findDecl(ds, DFn, text(e)) - val targs = kids(kid(e, 0)) - val ext = num(f) == 1 - val cast = ext && isTParamOf(f, text(kid(f, 1))) - if cast then - say("((") - ctype(ds, nth(targs, tparamIndex(f, text(kid(f, 1))))) - say(")") - else () - if !ext then say("f_") else () - say(text(e)) - if !ext then typeSuffix(targs) else () - say("(") - exArgs(ds, cs, env, tail(kids(e)), false) - say(")") - if cast then say(")") else () - -// a case of an enum instance: its struct and statics carry the instance's type args -def exNew {r: Region} (ds: Decls, cs: Nodes, env: Nodes, e: Node): Unit = - val c = find(cs, DCase, text(e)) - val targs = kids(kid(e, 0)) - if isNil(tail(kids(e))) then - say("(&N_") - say(text(e)) - typeSuffix(targs) - say(")") - else exCtor(ds, cs, env, c, tail(kids(e)), targs) - -def ctorStruct(c: Node, targs: Nodes): Unit = - say(text2(c)) - if !isNil(targs) then typeSuffix(targs) else () - -// position of [] binder n among f's [] binders, in written order -def tparamIndex(f: Node, n: Str): I64 = - var gs = kids(kid(f, 4)) - var i = 0 - var res = -1 - while res < 0 && !isNil(gs) do - if kind(head(gs)) == Group && eqs(text(head(gs)), "[") then - val j = index(kids(head(gs)), n) - if j >= 0 then res = i + j else i = i + len(kids(head(gs))) - else () - gs = tail(gs) - res - -def ex {r: Region} (ds: Decls, cs: Nodes, env: Nodes, e: Node): Unit = - val k = kind(e) - if k == XInt then - say("((int64_t)") - sayn(num(e)) - say(")") - else if k == XBool then say(if num(e) == 1 then "true" else "false") - else if k == XUnit then say("((int64_t)0)") - else if k == XStr then - say("((srs_str){(const uint8_t*)\"") - say(text(e)) - say("\", ") - sayn(unescLen(text(e))) - say("})") - else if k == XName then - val b = find(env, BVar, text(e)) - if found(b) then cname(b) - else - say("(&N_") - say(text(e)) - say(")") - else if k == XCall then - val c = find(cs, DCase, text(e)) - if found(c) then exCtor(ds, cs, env, c, kids(e), NNil) - else - val f = findDecl(ds, DFn, text(e)) - if num(f) == 0 then say("f_") else () - say(text(e)) - say("(") - exArgs(ds, cs, env, kids(e), false) - say(")") - else if k == XInst then exInst(ds, cs, env, e) - else if k == XNew then exNew(ds, cs, env, e) - else if k == XEv then - val et = head(kids(kid(e, 0))) - givenName(text(et), tyArgs(et), text(e)) - say("(") - exArgs(ds, cs, env, tail(kids(e)), false) - say(")") - else if k == XMethod then exMethod(ds, cs, env, e) - else if k == XBin then - say("(") - ex(ds, cs, env, kid(e, 0)) - say(" ") - say(text(e)) - say(" ") - ex(ds, cs, env, kid(e, 1)) - say(")") - else if k == XUn then - say("(") - say(text(e)) - ex(ds, cs, env, kid(e, 0)) - say(")") - else if k == XIf then - say("(") - ex(ds, cs, env, kid(e, 0)) - say(" ? ") - ex(ds, cs, env, kid(e, 1)) - say(" : ") - ex(ds, cs, env, kid(e, 2)) - say(")") - else if k == XMatch then exMatch(ds, cs, env, e) - else if k == XBlock then exBlock(ds, cs, env, kids(e)) - else if k == XWhile then - say("({ while (") - ex(ds, cs, env, kid(e, 0)) - say(") { (void)(") - ex(ds, cs, env, kid(e, 1)) - say("); } (int64_t)0; })") - else if k == XAssign then - say("(") - cname(find(env, BVar, text(e))) - say(" = (") - ex(ds, cs, env, kid(e, 0)) - say("), (int64_t)0)") - else fatal("internal: expression kind", lineOf(e)) - -def exMethod {r: Region} (ds: Decls, cs: Nodes, env: Nodes, e: Node): Unit = - val b = find(env, BVar, text(e)) - val p = findDecl(ds, DProto, text2(b)) - val ops = kids(kid(p, 3)) - val op = find(ops, DOp, text2(e)) - val ends = kids(kid(p, 1)) - var tr = kids(kid(op, 2)) - var kills = !isNil(tr) - while !isNil(tr) do - kills = kills && has(ends, text2(head(tr))) - tr = tail(tr) - say("({ __auto_type r_ = ((") - ctype(ds, kid(op, 1)) - say("(*)(void*") - var ps = kids(kid(op, 0)) - while !isNil(ps) do - say(", ") - ctype(ds, kid(head(ps), 0)) - ps = tail(ps) - say("))(") - cname(b) - say("->vt[") - sayn(opIndex(ops, text2(e))) - say("]))(") - cname(b) - say("->self") - exArgs(ds, cs, env, kids(e), true) - say("); ") - if kills then - cname(b) - say("->live = 0; ") - else () - say("r_; })") - -def exCtor {r: Region} (ds: Decls, cs: Nodes, env: Nodes, c: Node, xs: Nodes, targs: Nodes): Unit = - val reg = regionOf(env) - val u = len(env) - say("({ struct E_") - ctorStruct(c, targs) - say("* o") - sayn(u) - say(" = (struct E_") - ctorStruct(c, targs) - say("*)((void*(*)(void*, int64_t))(") - cname(reg) - say("->vt[") - sayn(opIndex(protoOps(ds, "Region"), "alloc")) - say("]))(") - cname(reg) - say("->self, (int64_t)sizeof(struct E_") - ctorStruct(c, targs) - say(")); o") - sayn(u) - say("->tag = ") - sayn(num(c)) - say(";") - var a = xs - var fs = kids(kid(c, 0)) - while !isNil(a) do - say(" o") - sayn(u) - say("->u.C_") - say(text(c)) - say(".f_") - say(text(head(fs))) - say(" = ") - ex(ds, cs, env, head(a)) - say(";") - a = tail(a) - fs = tail(fs) - say(" o") - sayn(u) - say("; })") - -def exMatch {r: Region} (ds: Decls, cs: Nodes, env: Nodes, e: Node): Unit = - val u = len(env) - say("({ __auto_type s") - sayn(u) - say(" = ") - ex(ds, cs, env, kid(e, 0)) - say("; ") - var arms = tail(kids(e)) - while !isNil(arms) do - val arm = head(arms) - val last = isNil(tail(arms)) - var env2 = env - if !eqs(text(arm), "_") then - val c = find(cs, DCase, text(arm)) - if !last then - say("s") - sayn(u) - say("->tag == ") - sayn(num(c)) - say(" ? ") - else () - say("({ ") - var bs = tail(kids(arm)) - var fs = kids(kid(c, 0)) - while !isNil(bs) do - val bn = text(head(bs)) - if !eqs(bn, "_") then - val b = Node(BVar, bn, "", len(env2), lineOf(arm), kids(head(fs))) - say("__auto_type ") - cname(b) - say(" = s") - sayn(u) - say("->u.C_") - say(text(c)) - say(".f_") - say(text(head(fs))) - say("; ") - env2 = NCons(b, env2) - else () - bs = tail(bs) - fs = tail(fs) - else say("({ ") - ex(ds, cs, env2, kid(arm, 0)) - say("; })") - if !last then say(" : ") else () - arms = tail(arms) - say("; })") - -def exBlock {r: Region} (ds: Decls, cs: Nodes, env0: Nodes, ss: Nodes): Unit = - var env = env0 - var caps = NNil - var c = ss - var hasLast = false - say("({ ") - while !isNil(c) do - val s = head(c) - val k = kind(s) - if k == SClause then () - else if k == SVal then - val b = Node(BVar, text(s), "", len(env), lineOf(s), NNil) - if isNil(tail(kids(s))) then say("__auto_type ") else ctype(ds, kid(s, 1)) - say(" ") - cname(b) - say(" = ") - ex(ds, cs, env, kid(s, 0)) - say("; ") - env = NCons(b, env) - else if k == SHandle then - val h = findDecl(ds, DHandler, text2(s)) - val b = Node(BVar, text(s), text2(h), len(env), lineOf(s), NNil) - say("srs_cap ") - cname(b) - say("_v = { h_") - say(text2(s)) - say("_init(") - exArgs(ds, cs, env, kids(s), false) - say("), vt_") - say(text2(s)) - say(", 1 }; srs_cap* ") - cname(b) - say(" = &") - cname(b) - say("_v; ") - env = NCons(b, env) - caps = NCons(b, caps) - else if isNil(tail(c)) then - say("__auto_type res_ = ") - ex(ds, cs, env, s) - say("; ") - hasLast = true - else - say("(void)(") - ex(ds, cs, env, s) - say("); ") - c = tail(c) - if !hasLast then say("__auto_type res_ = (int64_t)0; ") else () - while !isNil(caps) do - val b = head(caps) - val p = findDecl(ds, DProto, text2(b)) - val dn = text(kid(p, 2)) - if rt_str_len(dn) > 0 then - say("if (") - cname(b) - say("->live) ((int64_t(*)(void*))(") - cname(b) - say("->vt[") - sayn(opIndex(kids(kid(p, 3)), dn)) - say("]))(") - cname(b) - say("->self); ") - else () - caps = tail(caps) - say("res_; })") diff --git a/bench/corpus/s1/facts.srs b/bench/corpus/s1/facts.srs deleted file mode 100644 index e416df20..00000000 --- a/bench/corpus/s1/facts.srs +++ /dev/null @@ -1,322 +0,0 @@ -// <> Datalog facts of a signature (vic-9l7.8 BD5). before the params: what holds on entry; after the result: on exit -// (vic B-Q3: a call is a protocol step). atoms: at(cap, S) = the state of a {} capability, next(S1, op, S2) = a -// transition of its protocol. In a state position an Uppercase name is a state, a lowercase name a variable. -// A def with variables is checked once per solution of its entry facts (vic (a′)): its body must end in the exit -// state of that solution; a call binds the variables from Γ (one solution). Solutions: lib/datalog.srs. -// rules (`rule` decls, prelude): BD5b-2. - -// x in a state position is a variable (lowercase), else a state -def isVarName(x: Str): Bool = rt_str_at(x, 0) >= 'a' && rt_str_at(x, 0) <= 'z' - -// the value of variable x in the solution sol (Name s = var, t = state), or "" -def solValue(sol: Nodes, x: Str): Str = text2(find(sol, Name, x)) - -// the state of at(cap, S) in f's fact group out ("" entry, "out" exit) under sol, or "" (absent) -def capState(f: Node, cap: Str, out: Str, sol: Nodes): Str = - var res = "" - var gs = kids(kid(f, 4)) - while !isNil(gs) do - val g = head(gs) - if kind(g) == Group && eqs(text(g), "<") && eqs(text2(g), out) then - var c = kids(g) - while !isNil(c) do - if eqs(text(head(c)), "at") && eqs(text(kid(head(c), 0)), cap) then - val x = text(kid(head(c), 1)) - res = if isVarName(x) then solValue(sol, x) else x - else () - c = tail(c) - else () - gs = tail(gs) - res - -// the protocol of f's {} binder n, or "" -def binderProto(ds: Decls, f: Node, n: Str): Str = - var res = "" - var gs = kids(kid(f, 4)) - while !isNil(gs) do - if kind(head(gs)) == Group && eqs(text(head(gs)), "{") then - val b = find(kids(head(gs)), Binder, n) - if found(b) && isProto(ds, text(kid(b, 0))) then res = text(kid(b, 0)) else () - else () - gs = tail(gs) - res - -// the protocols of f's {} capabilities, one Name each -def capProtos {r: Region} (ds: Decls, f: Node): Nodes = - var out = NNil - var gs = kids(kid(f, 4)) - while !isNil(gs) do - if kind(head(gs)) == Group && eqs(text(head(gs)), "{") then - var bs = kids(head(gs)) - while !isNil(bs) do - val p = text(kid(head(bs), 0)) - if isProto(ds, p) && !has(out, p) then out = NCons(leaf(Name, p, 0), out) else () - bs = tail(bs) - else () - gs = tail(gs) - out - -// the protocol of f's caps that has op, or "" -def opProto {r: Region} (ds: Decls, f: Node, op: Str): Str = - var res = "" - var ps = capProtos(ds, f) - while !isNil(ps) do - if found(find(kids(kid(findDecl(ds, DProto, text(head(ps))), 3)), DOp, op)) then res = text(head(ps)) else () - ps = tail(ps) - res - -// a state position: a variable, or a state of protocol p -def needState(ds: Decls, p: Str, x: Node): Unit = - if !isVarName(text(x)) && !has(protoStates(declList(ds), p), text(x)) then err("unknown protocol state in", p, lineOf(x)) else () - -// the variables of the entry fact groups of f, each once, in written order -def entryVars {r: Region} (f: Node): Nodes = - var out = NNil - var gs = kids(kid(f, 4)) - while !isNil(gs) do - val g = head(gs) - if kind(g) == Group && eqs(text(g), "<") && rt_str_len(text2(g)) == 0 then - var c = kids(g) - while !isNil(c) do - var xs = statePos(head(c)) - while !isNil(xs) do - if isVarName(text(head(xs))) && !has(out, text(head(xs))) then out = NCons(leaf(Name, text(head(xs)), lineOf(head(xs))), out) else () - xs = tail(xs) - c = tail(c) - else () - gs = tail(gs) - rev(out) - -// the state positions of atom a: at(_, S) and next(S1, _, S2) -def statePos {r: Region} (a: Node): Nodes = - if eqs(text(a), "at") then tail(kids(a)) - else if eqs(text(a), "next") then NCons(kid(a, 0), one(kid(a, 2))) - else kids(a) - -def hasVars {r: Region} (f: Node): Bool = !isNil(entryVars(f)) - -// each atom of the fact group g: at(cap, S) or (entry only) next(S1, op, S2); exit variables are entry variables -def needFacts {r: Region} (ds: Decls, f: Node, g: Node): Unit = - var c = kids(g) - var seen = NNil - while !isNil(c) do - val a = head(c) - if eqs(text(a), "at") && len(kids(a)) == 2 then - val cap = text(kid(a, 0)) - val p = binderProto(ds, f, cap) - if rt_str_len(p) == 0 then err("at: not a {} capability of this def:", cap, lineOf(a)) else () - needState(ds, p, kid(a, 1)) - if has(seen, cap) then err("two states of one capability in a fact group:", cap, lineOf(a)) else () - seen = NCons(kid(a, 0), seen) - else if eqs(text(a), "next") && len(kids(a)) == 3 && rt_str_len(text2(g)) == 0 then - val p = opProto(ds, f, text(kid(a, 1))) - if rt_str_len(p) == 0 then err("next: not an op of a capability of this def:", text(kid(a, 1)), lineOf(a)) else () - needState(ds, p, kid(a, 0)) - needState(ds, p, kid(a, 2)) - else if rt_str_len(text2(g)) > 0 then err("not yet: fact after the result", text(a), lineOf(a)) - else if eqs(text(a), "at") || eqs(text(a), "next") then err("wrong number of args for relation", text(a), lineOf(a)) - // a rule def of the protocol of one of f's caps - else needAtomOf(ds, ruleProto(ds, f, text(a), lineOf(a)), a) - if rt_str_len(text2(g)) > 0 then needBound(f, a) else () - c = tail(c) - -// an exit atom names only entry variables -def needBound {r: Region} (f: Node, a: Node): Unit = - val vs = entryVars(f) - var xs = statePos(a) - while !isNil(xs) do - if isVarName(text(head(xs))) && !has(vs, text(head(xs))) then err("fact variable not bound by the entry facts:", text(head(xs)), lineOf(a)) else () - xs = tail(xs) - -// ── solutions (lib/datalog.srs) ── -def toArg {r: Region} (vars: Nodes, x: Str): Arg = if isVarName(x) && has(vars, x) then AVar(index(vars, x)) else AVal(VSym(x)) - -def toArgs {r: Region} (vars: Nodes, xs: Nodes): Args = - if isNil(xs) then ArgNil else ArgCons(toArg(vars, text(head(xs))), toArgs(vars, tail(xs))) - -// q(vars) :- the entry atoms of f -def query {r: Region} (f: Node, vars: Nodes): Clause = - var body = LitNil - var gs = kids(kid(f, 4)) - while !isNil(gs) do - val g = head(gs) - if kind(g) == Group && eqs(text(g), "<") && rt_str_len(text2(g)) == 0 then - var c = kids(g) - while !isNil(c) do - body = LitCons(Pos(Atom(text(head(c)), toArgs(vars, kids(head(c))))), body) - c = tail(c) - else () - gs = tail(gs) - Clause(Atom("q", varArgs(0, len(vars))), body) - -def varArgs {r: Region} (i: I64, n: I64): Args = if i >= n then ArgNil else ArgCons(AVar(i), varArgs(i + 1, n)) - -// the transitions of f's protocols as next(S1, op, S2), onto edb -def nextFacts {r: Region} (ds: Decls, f: Node, edb: Edb): Edb = - var out = edb - var ps = capProtos(ds, f) - while !isNil(ps) do - var ops = kids(kid(findDecl(ds, DProto, text(head(ps))), 3)) - while !isNil(ops) do - var ts = kids(kid(head(ops), 2)) - while !isNil(ts) do - out = EdbCons(Fact("next", ValCons(VSym(text(head(ts))), ValCons(VSym(text(head(ops))), ValCons(VSym(text2(head(ts))), ValNil)))), out) - ts = tail(ts) - ops = tail(ops) - ps = tail(ps) - out - -// at(cap, S) for each {} capability of f: its state in entry (a call), else every state of its protocol (a def) -def atFacts {r: Region} (ds: Decls, f: Node, entry: Nodes, edb: Edb): Edb = - var out = edb - var gs = kids(kid(f, 4)) - while !isNil(gs) do - if kind(head(gs)) == Group && eqs(text(head(gs)), "{") then - var bs = kids(head(gs)) - while !isNil(bs) do - val cap = text(head(bs)) - val p = text(kid(head(bs), 0)) - if isProto(ds, p) then - val e = find(entry, Name, cap) - var ss = if found(e) then one(leaf(Name, text2(e), 0)) else protoStates(declList(ds), p) - while !isNil(ss) do - out = EdbCons(Fact("at", ValCons(VSym(cap), ValCons(VSym(text(head(ss))), ValNil))), out) - ss = tail(ss) - else () - bs = tail(bs) - else () - gs = tail(gs) - out - -// the solutions of f's entry facts: each a list of Name(var, state); entry = Name(cap, state) of a call, or NNil -def solutions {r: Region} (ds: Decls, f: Node, entry: Nodes): Nodes = - val vars = entryVars(f) - evalDatalog(ClCons(query(f, vars), ruleClauses(ds, f, ClNil)), atFacts(ds, f, entry, nextFacts(ds, f, EdbNil))) match - case Unsafe(_) => - err("internal: unsafe facts of", text(f), lineOf(f)) - NNil - case NegCycle(_) => - err("internal: negation in facts of", text(f), lineOf(f)) - NNil - case Model(db) => qSols(vars, db, lineOf(f)) - -// the q facts of a model, each as a solution, in model order -def qSols {r: Region} (vars: Nodes, db: Facts, line: I64): Nodes = db match - case FactNil => NNil - case FactCons(h, _, t) => h match - case Fact(rel, vs) => if eqs(rel, "q") then NCons(list(Names, line, solOf(vars, vs)), qSols(vars, t, line)) else qSols(vars, t, line) - -// var i = state i -def solOf {r: Region} (vars: Nodes, vs: Vals): Nodes = - if isNil(vars) then NNil - else vs match - case ValNil => NNil - case ValCons(v, t) => NCons(Node(Name, text(head(vars)), symOf(v), 0, 0, NNil), solOf(tail(vars), t)) - -def symOf(v: Val): Str = v match - case VSym(s) => s - case VInt(_) => "" - -// the one solution of f's entry facts at a call: Γ gives each capability's state (entry) -def callSol {r: Region} (ds: Decls, f: Node, entry: Nodes, line: I64): Nodes = - val ss = solutions(ds, f, entry) - if isNil(ss) then err("entry facts do not hold at the call of", text(f), line) else () - if !isNil(tail(ss)) then err("entry facts have more than one solution at the call of", text(f), line) else () - kids(head(ss)) - -// the solution a def's body and its C/Lean output use: the first one (states are erased in C and Lean), or NNil -def defSol {r: Region} (ds: Decls, f: Node): Nodes = if hasVars(f) then kids(head(solutions(ds, f, NNil))) else NNil - -// the entry of a call: each callee capability (m: GState s = callee binder, t = caller cap) at its state in Γ -def capEntry {r: Region} (m: Nodes, gam: Nodes): Nodes = - if isNil(m) then NNil else NCons(Node(Name, text(head(m)), state(gam, text2(head(m))), 0, 0, NNil), capEntry(tail(m), gam)) - -// ── rule defs of protocols (vic 2026-11-05: a protocol is its own Datalog program) ── -def protoRules(ds: Decls, p: Str): Nodes = kids(kid(findDecl(ds, DProto, p), 4)) - -// the protocols of f's caps that define relation rel; err when none or two -def ruleProto {r: Region} (ds: Decls, f: Node, rel: Str, line: I64): Str = - var res = "" - var n = 0 - var ps = capProtos(ds, f) - while !isNil(ps) do - if found(find(protoRules(ds, text(head(ps))), DRule, rel)) then - res = text(head(ps)) - n = n + 1 - else () - ps = tail(ps) - if n == 0 then err("unknown relation in facts:", rel, line) else () - if n > 1 then err("relation defined in two protocols of this def:", rel, line) else () - res - -// atom a uses a relation of protocol p (next or a rule def of p) w/ its arity; states are p's or variables -def needAtomOf {r: Region} (ds: Decls, p: Str, a: Node): Unit = - if eqs(text(a), "next") then - if len(kids(a)) != 3 then err("next takes 3 args:", text(a), lineOf(a)) else () - if !found(find(kids(kid(findDecl(ds, DProto, p), 3)), DOp, text(kid(a, 1)))) then err("next: not an op of protocol", p, lineOf(a)) else () - else - val rl = find(protoRules(ds, p), DRule, text(a)) - if !found(rl) then err("unknown relation in rule:", text(a), lineOf(a)) else () - if len(kids(a)) != len(kids(kid(rl, 0))) then err("wrong number of args for relation", text(a), lineOf(a)) else () - var xs = statePos(a) - while !isNil(xs) do - needState(ds, p, head(xs)) - xs = tail(xs) - -// the rule defs of protocol d: names not at/next, unique; params variables, each in the body (Datalog safety) -def checkRules {r: Region} (ds: Decls, d: Node): Unit = - var seen = NNil - var rs = kids(kid(d, 4)) - while !isNil(rs) do - val rl = head(rs) - if eqs(text(rl), "at") || eqs(text(rl), "next") || eqs(text(rl), "q") then err("reserved relation name:", text(rl), lineOf(rl)) else () - // several rule defs of one name = its clauses (a disjunction, as Prolog); one arity - val prev = find(seen, DRule, text(rl)) - if found(prev) && len(kids(kid(prev, 0))) != len(kids(kid(rl, 0))) then err("rule defs of one relation differ in arity:", text(rl), lineOf(rl)) else () - seen = NCons(rl, seen) - var bvars = NNil - var as = tail(kids(rl)) - while !isNil(as) do - needAtomOf(ds, text(d), head(as)) - bvars = append(statePos(head(as)), bvars) - as = tail(as) - var ps = kids(kid(rl, 0)) - while !isNil(ps) do - if !isVarName(text(head(ps))) then err("rule def param must be a variable:", text(head(ps)), lineOf(rl)) else () - if !has(bvars, text(head(ps))) then err("rule def param not in its body:", text(head(ps)), lineOf(rl)) else () - ps = tail(ps) - rs = tail(rs) - -// rule def rl as a Datalog clause: params first, then the body's other variables -def ruleClause {r: Region} (rl: Node): Clause = - var vars = rev(kids(kid(rl, 0))) - var as = tail(kids(rl)) - while !isNil(as) do - var xs = statePos(head(as)) - while !isNil(xs) do - if isVarName(text(head(xs))) && !has(vars, text(head(xs))) then vars = NCons(head(xs), vars) else () - xs = tail(xs) - as = tail(as) - val vs = rev(vars) - var body = LitNil - as = tail(kids(rl)) - while !isNil(as) do - body = LitCons(Pos(Atom(text(head(as)), toArgs(vs, kids(head(as))))), body) - as = tail(as) - Clause(Atom(text(rl), toArgs(vs, kids(kid(rl, 0)))), body) - -// the rule clauses of f's cap protocols onto cs; a name in two of them = reject (their clauses would merge) -def ruleClauses {r: Region} (ds: Decls, f: Node, cs: Clauses): Clauses = - var out = cs - var other = NNil - var ps = capProtos(ds, f) - while !isNil(ps) do - val rs0 = protoRules(ds, text(head(ps))) - var rs = rs0 - while !isNil(rs) do - if has(other, text(head(rs))) then err("relation defined in two protocols of this def:", text(head(rs)), lineOf(f)) else () - out = ClCons(ruleClause(head(rs)), out) - rs = tail(rs) - other = append(rs0, other) - ps = tail(ps) - out diff --git a/bench/corpus/s1/given.srs b/bench/corpus/s1/given.srs deleted file mode 100644 index 870b57c0..00000000 --- a/bench/corpus/s1/given.srs +++ /dev/null @@ -1,305 +0,0 @@ -// Traits, givens and {} evidence (vic-9l7.6 BD4a). A given is a clause: its head holds when its {} evidence does. -// A call needs each {} goal of its callee: exactly one candidate (local evidence, or a given whose head matches), -// 1 fuel per pick (vic B1), 0 or 2+ candidates = reject (vic B2). Mono rebuilds the chosen method at the concrete goal. - -// t names trait T[args]: the trait exists, one arg per [] binder, each arg a type -def needTrait {r: Region} (ds: Decls, t: Node): Unit = - val tr = findDecl(ds, DTrait, text(t)) - if !found(tr) then err("unknown trait", text(t), lineOf(t)) else () - if len(tyArgs(t)) != len(groupBinders(kids(kid(tr, 0)))) then err("wrong number of type args for", text(t), lineOf(t)) else () - var c = tyArgs(t) - while !isNil(c) do - needTy(ds, head(c)) - c = tail(c) - -// trait Show [A: Type]: [] binders only; method signatures over them (vic-9l7.6 BD4a) -def checkTrait {r: Region} (ds0: Decls, d: Node): Unit = - val gs = kids(kid(d, 0)) - var g = gs - while !isNil(g) do - if !eqs(text(head(g)), "[") then err("not yet: binder group on a trait", text(head(g)), lineOf(head(g))) else () - g = tail(g) - val ds = declsPrepend(groupBinders(gs), ds0) - var ms = tail(kids(d)) - while !isNil(ms) do - if !isNil(kids(kid(head(ms), 4))) then err("not yet: binder groups on a trait method", text(head(ms)), lineOf(head(ms))) else () - checkSig(ds, head(ms)) - ms = tail(ms) - -// given ... T[args]: each trait method, with the trait's binders = the head's args, is a def of the given w/ that sig -def checkGiven {r: Region} (ds: Decls, d: Node): Node = - val tr = findDecl(ds, DTrait, text(d)) - if !found(tr) then err("unknown trait", text(d), lineOf(d)) else () - val hd = kid(d, 1) - needTrait(declsPrepend(groupBinders(kids(kid(d, 0))), ds), hd) - // every [] binder is fixed by the head, so a goal fixes all of them - var bs = groupBinders(kids(kid(d, 0))) - while !isNil(bs) do - if !mentions(one(head(bs)), hd) then err("given [] binder not in its head:", text(head(bs)), lineOf(d)) else () - bs = tail(bs) - val sub = zipBind(groupBinders(kids(kid(tr, 0))), tyArgs(hd)) - val fs = tail(tail(kids(d))) - var ms = tail(kids(tr)) - while !isNil(ms) do - val m = head(ms) - val f = find(fs, DFn, text(m)) - if !found(f) then err("given misses trait method", text(m), lineOf(d)) else () - if !sameSig(sub, m, f) then err("given method signature differs from its trait:", text(m), lineOf(f)) else () - ms = tail(ms) - var c = fs - var fs2 = NNil - while !isNil(c) do - if !found(find(tail(kids(tr)), DFn, text(head(c)))) then err("not a method of the trait:", text(head(c)), lineOf(head(c))) else () - checkSig(ds, head(c)) - fs2 = NCons(checkFn(ds, head(c)), fs2) - c = tail(c) - withKids(d, NCons(kid(d, 0), NCons(hd, rev(fs2)))) - -// f's params and result are m's with sub applied -def sameSig {r: Region} (sub: Nodes, m: Node, f: Node): Bool = - var a = kids(kid(m, 0)) - var b = kids(kid(f, 0)) - var ok = len(a) == len(b) && tyEq(applyTy(sub, kid(m, 1)), kid(f, 1)) - while ok && !isNil(a) do - ok = tyEq(applyTy(sub, kid(head(a), 0)), kid(head(b), 0)) - a = tail(a) - b = tail(b) - ok - - -// a group binder's type (TTerm, from the parser) as a Ty -def termTy {r: Region} (k: Node): Node = - var out = NNil - var c = kids(k) - while !isNil(c) do - out = NCons(termTy(head(c)), out) - c = tail(c) - Node(Ty, text(k), "", 0, lineOf(k), one(Node(TyTo, "", "", 0, 0, rev(out)))) - -// f's {} evidence binders as env entries (n 3): only a method-call receiver -def evEnv {r: Region} (ds: Decls, f: Node): Nodes = groupsEv(ds, kids(kid(f, 4))) - -// the {} evidence binders of groups gs as env entries -def groupsEv {r: Region} (ds: Decls, gs0: Nodes): Nodes = - var out = NNil - var gs = gs0 - while !isNil(gs) do - if kind(head(gs)) == Group && eqs(text(head(gs)), "{") then - var bs = kids(head(gs)) - while !isNil(bs) do - // a protocol binder is a capability (capParams), not trait evidence - if !isProto(ds, text(kid(head(bs), 0))) then out = NCons(Node(BVar, text(head(bs)), "", 3, lineOf(head(bs)), one(termTy(kid(head(bs), 0)))), out) else () - bs = tail(bs) - else () - gs = tail(gs) - out - -def errTy(what: Str, t: Node, line: I64): Unit = - rt_eprint("srs:") - rt_eprint_i64(line) - rt_eprint(": error: ") - rt_eprint(what) - rt_eprint(" ") - eprintTy(t) - rt_eprint("\n") - rt_exit(1) - -enum MatchR: - case NoMatch - case Matched(sub: Nodes) - -// sub extended so the pattern p (it names binders tps) is a, or NoMatch: matchTy without the error -def unifies {r: Region} (tps: Nodes, p: Node, a: Node, sub: Nodes): MatchR = - if isTP(tps, p) then - val b = find(sub, Binder, text(p)) - if !found(b) then Matched(NCons(Node(Binder, text(p), "", 0, 0, one(recap(a, NNil))), sub)) - else if tyEq(a, kid(b, 0)) then Matched(sub) - else NoMatch - else if !eqs(text(p), text(a)) || len(tyArgs(p)) != len(tyArgs(a)) then NoMatch - else unifiesAll(tps, tyArgs(p), tyArgs(a), sub) - -def unifiesAll {r: Region} (tps: Nodes, ps: Nodes, as: Nodes, sub: Nodes): MatchR = - if isNil(ps) then Matched(sub) - else unifies(tps, head(ps), head(as), sub) match - case NoMatch => NoMatch - case Matched(s2) => unifiesAll(tps, tail(ps), tail(as), s2) - -enum GivenAt: - case NoGiven - case Ambiguous - case GivenAt(g: Node, sub: Nodes) - -// the givens of ds whose head matches goal -def givenCands {r: Region} (ds: Decls, goal: Node): Nodes = - var c = declList(ds) - var out = NNil - while !isNil(c) do - val g = head(c) - if kind(g) == DGiven && eqs(text(g), text(goal)) then - unifies(gBinders(g), kid(g, 1), goal, NNil) match - case NoMatch => () - case Matched(_) => out = NCons(g, out) - else () - c = tail(c) - rev(out) - -def gBinders {r: Region} (g: Node): Nodes = groupBinders(kids(kid(g, 0))) - -// the one given for goal: the only candidate, or the one that beats every other (as Scala3 CompareScheme.New, -// vic-9l7.11); none = NoGiven, no such winner = Ambiguous -def pickGiven {r: Region} (ds: Decls, goal: Node): GivenAt = - val cs = givenCands(ds, goal) - var res = NoGiven - if !isNil(cs) then res = Ambiguous else () - var c = cs - var i = 0 - while !isNil(c) do - if beatsAll(i, cs) then - unifies(gBinders(head(c)), kid(head(c), 1), goal, NNil) match - case NoMatch => () - case Matched(s) => res = GivenAt(head(c), s) - else () - i = i + 1 - c = tail(c) - res - -// candidate i of cs beats every other candidate -def beatsAll {r: Region} (i: I64, cs: Nodes): Bool = - var ok = true - var j = 0 - var c = cs - while ok && !isNil(c) do - if j != i then ok = compareGivens(nth(cs, i), head(c)) > 0 else () - j = j + 1 - c = tail(c) - ok - -// Scala3 Applications.compare for two givens of one scope (same owner, no subtyping): 1 = g1 wins, -1 = g2, 0 = draw. -// a given is as good as another when the other's head instantiates to its own (its binders kept abstract): the -// more specific head wins (rules 2, 3b, :2296-2332); on a draw the one without {} evidence wins (:2497-2500) -def compareGivens {r: Region} (g1: Node, g2: Node): I64 = - val w1 = asGood(g1, g2) - val w2 = asGood(g2, g1) - if w1 && !w2 then 1 - else if w2 && !w1 then -1 - else if !hasEvidence(g1) && hasEvidence(g2) then 1 - else if hasEvidence(g1) && !hasEvidence(g2) then -1 - else 0 - -def asGood {r: Region} (g1: Node, g2: Node): Bool = unifies(gBinders(g2), kid(g2, 1), kid(g1, 1), NNil) match - case NoMatch => false - case Matched(_) => true - -def hasEvidence(g: Node): Bool = - var res = false - var c = kids(kid(g, 0)) - while !isNil(c) do - if kind(head(c)) == Group && eqs(text(head(c)), "{") && !isNil(kids(head(c))) then res = true else () - c = tail(c) - res - -// the local evidence of env for goal -def localCount(env: Nodes, goal: Node): I64 = - var c = env - var n = 0 - while !isNil(c) do - if kind(head(c)) == BVar && num(head(c)) == 3 && tyEq(kid(head(c), 0), goal) then n = n + 1 else () - c = tail(c) - n - -// the default fuel of a given search, as a default stack limit (vic Q-R4b); 1 per pick (vic B1) -def givenFuel(): I64 = 1000 - -// goal has exactly one candidate in the nearest scope that has one (as Scala3, vic-9l7.10): local {} evidence -// first, then the givens; so has each {} goal of the given picked; the fuel left -def resolve {r: Region} (ds: Decls, env: Nodes, goal: Node, fuel: I64, line: I64): I64 = - if fuel <= 0 then errTy("given search ran out of fuel at", goal, line) else () - val loc = localCount(env, goal) - if loc > 1 then errTy("ambiguous evidence for", goal, line) else () - if loc == 1 then fuel - 1 - else - pickGiven(ds, goal) match - case NoGiven => - errTy("no given for", goal, line) - fuel - case Ambiguous => - errTy("ambiguous givens for", goal, line) - fuel - case GivenAt(g, s) => goals(ds, env, kids(kid(g, 0)), s, NNil, fuel - 1, line) - -// each {} binder of the groups gs under sub, resolved in turn; ch = names chosen at the call (f{a}(x)), or NNil -def goals {r: Region} (ds: Decls, env: Nodes, gs: Nodes, sub: Nodes, ch: Nodes, fuel: I64, line: I64): I64 = - var f = fuel - var i = 0 - var c = gs - while !isNil(c) do - if kind(head(c)) == Group && eqs(text(head(c)), "{") then - var bs = kids(head(c)) - while !isNil(bs) do - val goal = applyTy(sub, termTy(kid(head(bs), 0))) - // a protocol binder is a capability: chkCall takes it (theCap or the chosen one) - if isProto(ds, text(goal)) then () - else if isNil(ch) then f = resolve(ds, env, goal, f, line) - else needChosenEv(env, text(nth(ch, i)), goal, line) - i = i + 1 - bs = tail(bs) - else () - c = tail(c) - f - -// a chosen evidence: local evidence of the goal's type -def needChosenEv(env: Nodes, n: Str, goal: Node, line: I64): Unit = - val b = find(env, BVar, n) - if !found(b) || num(b) != 3 || !tyEq(kid(b, 0), goal) then errTy("chosen evidence does not prove", goal, line) else () - -// the binders of f's {} groups in written order: what f{a, b}(x) chooses, one name each -def curlyCount(f: Node): I64 = - var n = 0 - var c = kids(kid(f, 4)) - while !isNil(c) do - if kind(head(c)) == Group && eqs(text(head(c)), "{") then n = n + len(kids(head(c))) else () - c = tail(c) - n - -// position of {} binder n of f among all its {} binders -def curlyIndex(f: Node, n: Str): I64 = - var i = 0 - var res = -1 - var c = kids(kid(f, 4)) - while res < 0 && !isNil(c) do - if kind(head(c)) == Group && eqs(text(head(c)), "{") then - val j = index(kids(head(c)), n) - if j >= 0 then res = i + j else i = i + len(kids(head(c))) - else () - c = tail(c) - res - -// the group g ("[" or "{") of call groups gs: its kids, or NNil -def callGroup(gs: Nodes, g: Str): Nodes = kids(find(gs, Group, g)) - -// s.m(args), s a {} binder: m of s's trait, its types with the trait's binders = s's type args. e2 = XEv -def chkEv {r: Region} (ds: Decls, env: Nodes, gam: Nodes, e: Node, b: Node): TG = - val line = lineOf(e) - val et = kid(b, 0) - val tr = findDecl(ds, DTrait, text(et)) - val m = find(tail(kids(tr)), DFn, text2(e)) - if !found(m) then err("not a method of the trait:", text2(e), line) else () - val sub = zipBind(groupBinders(kids(kid(tr, 0))), tyArgs(et)) - var ps = kids(kid(m, 0)) - if len(ps) != len(kids(e)) then err("arity of", text2(e), line) else () - var g = gam - var a = kids(e) - var a2 = NNil - var rho = NNil - while !isNil(a) do - val pt = applyTy(sub, kid(head(ps), 0)) - val x = chk(ds, env, g, head(a), pt) - if !tyEq(tgTy(x), pt) then needAssign(tgTy(x), pt, line) else () - g = tgGam(x) - rho = union(rho, tyCaps(tgTy(x))) - a2 = NCons(tgE(x), a2) - a = tail(a) - ps = tail(ps) - val rt = applyTy(sub, kid(m, 1)) - val caps = if isEnum(ds, text(rt)) || isTParam(ds, text(rt)) then rho else NNil - TG(recap(rt, caps), g, Node(XEv, text2(e), text(e), 0, line, NCons(list(Names, line, one(et)), rev(a2)))) diff --git a/bench/corpus/s1/lean.srs b/bench/corpus/s1/lean.srs deleted file mode 100644 index 6e18e322..00000000 --- a/bench/corpus/s1/lean.srs +++ /dev/null @@ -1,604 +0,0 @@ -// S1 Lean backend (C10 C11, vic/c/lean-backend.md): `s1 --lean files > X.lean`, so proofs target the srs impl. -// fn = Option-monad def + partial_fixpoint (none = exit). while = aux def `_w` over the scope vars, -// returning the vars it assigns. regions and caps erased: values are immutable data. bracketed do: no layout. - -def put(on: Bool, s: Str): Unit = if on then say(s) else () -def putn(on: Bool, n: I64): Unit = if on then sayn(n) else () -def lid(on: Bool, s: Str): Unit = - put(on, "«") - put(on, s) - put(on, "»") - -def lty(t: Node): Unit = - val n = text(t) - if eqs(n, "I64") then say("Int") - else if eqs(n, "Str") then say("ByteArray") - else if eqs(n, "Bool") || eqs(n, "Unit") then say(n) - else lid(true, n) - -def ctorName {r: Region} (on: Bool, ds: Decls, name: Str): Unit = - lid(on, text2(findDecl(ds, DCase, name))) - put(on, ".") - lid(on, name) - -def emitLean {r: Region} (ds0: Decls, ns: Str): Unit = - // the call graph and its SCCs, once (Tarjan); ds knows the recursive fns - val g = callGraph(ds0) - val gm = dmAddAll(DTip, g) - val sm = sccMap(gm, g) - val ds = withRec(ds0, recSet(gm, sm, g)) - say("-- DO-NOT-EDIT. Generated by s1 --lean (s1/lean.srs, s1/leanspec.srs).\nimport Srs.Rt\nimport Srs.Auto\nset_option autoImplicit false\nnamespace Srs.") - say(ns) - say("\nopen Srs.Rt\n\n") - // nullary enums alone, with decidable equality (`==` on them is lawful in proofs); data enums: one mutual block - var c = declList(ds) - while !isNil(c) do - if kind(head(c)) == DEnum && nullary(head(c)) then - leanEnum(head(c)) - say(" deriving DecidableEq\n") - else () - c = tail(c) - say("mutual\n") - c = declList(ds) - while !isNil(c) do - if kind(head(c)) == DEnum && !nullary(head(c)) then leanEnum(head(c)) else () - c = tail(c) - say("end\n\n") - // spec defs: pure, before the impl (contracts use them) - c = declList(ds) - while !isNil(c) do - if kind(head(c)) == DFn && num(head(c)) == 2 then specDef(ds, head(c)) else () - c = tail(c) - specTheorems(ds) - // each call-graph SCC after the SCCs it calls: a cycle = one mutual block, else a plain def (Lean needs - // partial_fixpoint exactly on recursive defs) - var done = DTip - var more = true - while more do - more = false - c = declList(ds) - while !isNil(c) do - val d = head(c) - if kind(d) == DFn && num(d) == 0 && !inSet(done, text(d)) then - val sc = sccOf(sm, text(d)) - if depsDone(gm, sc, done) then - val rec = recIn(gm, sm, text(d)) - if rec then say("mutual\n") else () - var m = declList(ds) - while !isNil(m) do - if kind(head(m)) == DFn && has(sc, text(head(m))) then leanFn(ds, head(m), rec) else () - m = tail(m) - if rec then say("end\n\n") else () - done = dmAddAll(done, sc) - more = true - else () - else () - c = tail(c) - verification(ds) - say("end Srs.") - say(ns) - say("\n") - -// call graph: Name(s = fn, a = the user fns its body calls) -def callGraph {r: Region} (ds: Decls): Nodes = - var out = NNil - var c = declList(ds) - while !isNil(c) do - val d = head(c) - if kind(d) == DFn && num(d) == 0 then out = NCons(Node(Name, text(d), "", 0, 0, callsOf(ds, kid(d, 2), NNil)), out) else () - c = tail(c) - out - -// the user fns e calls -def callsOf {r: Region} (ds: Decls, e: Node, acc: Nodes): Nodes = - var out = acc - if kind(e) == XCall then - val f = findDecl(ds, DFn, text(e)) - if found(f) && num(f) == 0 && !has(out, text(e)) then out = NCons(leaf(Name, text(e), 0), out) else () - else () - var c = kids(e) - while !isNil(c) do - out = callsOf(ds, head(c), out) - c = tail(c) - out - -def nullary(d: Node): Bool = - var cs = kids(d) - var ok = true - while ok && !isNil(cs) do - ok = isNil(kids(kid(head(cs), 0))) - cs = tail(cs) - ok - -def leanEnum(d: Node): Unit = - say("inductive ") - lid(true, text(d)) - say(" where\n") - var cs = kids(d) - while !isNil(cs) do - say(" | ") - lid(true, text(head(cs))) - var fs = kids(kid(head(cs), 0)) - while !isNil(fs) do - say(" (") - lid(true, text(head(fs))) - say(" : ") - lty(kid(head(fs), 0)) - say(")") - fs = tail(fs) - say("\n") - cs = tail(cs) - -def leanFn {r: Region} (ds: Decls, f: Node, fix: Bool): Unit = - val ps = kids(kid(f, 0)) - val env = fnEnv(ds, sigParams(ds, f, defSol(ds, f))) - val gam = fnGam(ds, sigParams(ds, f, defSol(ds, f))) - // pass 1: the aux defs of its loops - ls(ds, text(f), env, gam, kid(f, 2), false, 1) - say("def ") - lid(true, text(f)) - var c = ps - while !isNil(c) do - if !isProto(ds, text(kid(head(c), 0))) then - say(" (") - lid(true, text(head(c))) - say(" : ") - lty(kid(head(c), 0)) - say(")") - else () - c = tail(c) - say(" : Option ") - lty(kid(f, 1)) - say(" := do {\n") - ls(ds, text(f), env, gam, kid(f, 2), true, 1) - say(if fix then "}\npartial_fixpoint\n\n" else "}\n\n") - -// e as a do sequence. mode 1 = its value ends the sequence, 0 = discarded (Unit items) -def ls {r: Region} (ds: Decls, fn: Str, env: Nodes, gam: Nodes, e: Node, on: Bool, mode: I64): Unit = - val k = kind(e) - if k == XBlock then lsBlock(ds, fn, env, gam, kids(e), on, mode) - else if k == XIf then - put(on, "if ") - lx(ds, fn, env, gam, kid(e, 0), on) - put(on, " then {\n") - ls(ds, fn, env, gam, kid(e, 1), on, mode) - put(on, "} else {\n") - ls(ds, fn, env, gam, kid(e, 2), on, mode) - put(on, "};\n") - else if k == XMatch then lsMatch(ds, fn, env, gam, e, on, mode) - else if k == XWhile then - if on then lsLoop(ds, fn, env, e, mode) - else - // nested loops first: an aux def comes after the defs it calls - lx(ds, fn, env, gam, kid(e, 0), false) - ls(ds, fn, env, gam, kid(e, 1), false, 0) - leanAux(ds, fn, env, gam, e) - else if k == XAssign then - lid(on, text(e)) - put(on, " := ") - lx(ds, fn, env, gam, kid(e, 0), on) - put(on, ";\n") - if mode == 1 then put(on, "pure ()\n") else () - else - put(on, if mode == 1 then "pure " else "let _ := ") - lx(ds, fn, env, gam, e, on) - put(on, ";\n") - -def lsBlock {r: Region} (ds: Decls, fn: Str, env0: Nodes, gam0: Nodes, ss: Nodes, on: Bool, mode: I64): Unit = - var env = env0 - var gam = gam0 - var c = ss - if isNil(c) then put(on, "pure ();\n") else () - while !isNil(c) do - val s = head(c) - val last = isNil(tail(c)) - if kind(s) == SClause then - if last then put(on, if mode == 1 then "pure ()\n" else "") else () - else if kind(s) == SVal then - put(on, if num(s) == 1 then "let mut " else "let ") - lid(on, text(s)) - // val = bind (a lambda binder): partial_fixpoint cannot split a match on a let-variable - if num(s) == 1 then - put(on, " := ") - lx(ds, fn, env, gam, kid(s, 0), on) - else - put(on, " ← ") - lxAct(ds, fn, env, gam, kid(s, 0), on) - put(on, ";\n") - // the checker's own type of the bound value: the Lean types of the loop aux params - val x = chk(ds, env, gam, kid(s, 0), NoNode) - val t = if !isNil(tail(kids(s))) then kid(s, 1) else if num(s) == 1 then uncapped(text(tgTy(x))) else tgTy(x) - gam = tgGam(x) - env = NCons(Node(BVar, text(s), "", num(s), lineOf(s), one(t)), env) - if last then put(on, "pure ();\n") else () - else if kind(s) == SHandle then - // erased: values are immutable data in Lean; the cap is bound so the rest re-checks - val p = findDecl(ds, DProto, text2(findDecl(ds, DHandler, text2(s)))) - env = NCons(Node(BVar, text(s), text(p), 2, lineOf(s), one(mkTy(text(p), NNil))), env) - gam = NCons(Node(GState, text(s), text2(p), 0, 0, NNil), gam) - if last then put(on, "pure ();\n") else () - else - ls(ds, fn, env, gam, s, on, if last then mode else 0) - gam = tgGam(chk(ds, env, gam, s, NoNode)) - c = tail(c) - -def lsMatch {r: Region} (ds: Decls, fn: Str, env: Nodes, gam: Nodes, e: Node, on: Bool, mode: I64): Unit = - put(on, "match ") - lx(ds, fn, env, gam, kid(e, 0), on) - put(on, " with\n") - val sx = chk(ds, env, gam, kid(e, 0), NoNode) - val en = findDecl(ds, DEnum, text(tgTy(sx))) - var arms = tail(kids(e)) - while !isNil(arms) do - val arm = head(arms) - var env2 = env - put(on, "| ") - if eqs(text(arm), "_") then put(on, "_") - else - ctorName(on, ds, text(arm)) - var bs = tail(kids(arm)) - var fs = kids(kid(find(kids(en), DCase, text(arm)), 0)) - while !isNil(bs) do - put(on, " ") - if eqs(text(head(bs)), "_") then put(on, "_") else lid(on, text(head(bs))) - env2 = NCons(Node(BVar, text(head(bs)), "", 0, lineOf(arm), one(kid(head(fs), 0))), env2) - bs = tail(bs) - fs = tail(fs) - put(on, " => {\n") - ls(ds, fn, env2, tgGam(sx), kid(arm, 0), on, mode) - put(on, "}\n") - arms = tail(arms) - put(on, ";\n") - -// vars in scope, innermost binding of each name; caps erased -def scope {r: Region} (env: Nodes): Nodes = - var out = NNil - var c = env - while !isNil(c) do - if num(head(c)) != 2 && !found(find(out, BVar, text(head(c)))) then out = NCons(head(c), out) else () - c = tail(c) - rev(out) -def assigned {r: Region} (e: Node, acc: Nodes): Nodes = - var out = if kind(e) == XAssign && !has(acc, text(e)) then NCons(leaf(Name, text(e), 0), acc) else acc - var c = kids(e) - while !isNil(c) do - out = assigned(head(c), out) - c = tail(c) - out -// the scope vars a loop body assigns: the loop aux returns them -def mutated {r: Region} (sc: Nodes, body: Node): Nodes = - val names = assigned(body, NNil) - var out = NNil - var c = sc - while !isNil(c) do - if has(names, text(head(c))) then out = NCons(head(c), out) else () - c = tail(c) - rev(out) - -// loop aux name = _loop, k = loops of the fn on earlier lines: stable under edits outside the fn -def auxName(ds: Decls, on: Bool, fn: Str, e: Node): Unit = - put(on, "«") - put(on, fn) - put(on, "_loop") - putn(on, loopsBefore(kid(findDecl(ds, DFn, fn), 2), lineOf(e))) - put(on, "»") -def loopsBefore(e: Node, line: I64): I64 = - var n = if kind(e) == XWhile && lineOf(e) < line then 1 else 0 - var c = kids(e) - while !isNil(c) do - n = n + loopsBefore(head(c), line) - c = tail(c) - n -def auxArgs(on: Bool, sc: Nodes): Unit = - var c = sc - while !isNil(c) do - put(on, " ") - lid(on, text(head(c))) - c = tail(c) -def tuple(on: Bool, mu: Nodes): Unit = - if isNil(mu) then put(on, "()") - else if isNil(tail(mu)) then lid(on, text(head(mu))) - else - put(on, "(") - var c = mu - while !isNil(c) do - lid(on, text(head(c))) - if !isNil(tail(c)) then put(on, ", ") else () - c = tail(c) - put(on, ")") -def tupleTy(mu: Nodes): Unit = - if isNil(mu) then say("Unit") - else - say("(") - var c = mu - while !isNil(c) do - lty(kid(head(c), 0)) - if !isNil(tail(c)) then say(" × ") else () - c = tail(c) - say(")") -// component i of an n-tuple (a, (b, c)): .2 i times, then .1 unless last -def proj(i: I64, n: I64): Unit = - var k = 0 - while k < i do - say(".2") - k = k + 1 - if i < n - 1 then say(".1") else () - -def lsLoop {r: Region} (ds: Decls, fn: Str, env: Nodes, e: Node, mode: I64): Unit = - val sc = scope(env) - val mu = mutated(sc, kid(e, 1)) - say("let t_ ← ") - auxName(ds, true, fn, e) - auxArgs(true, captured(sc, mu)) - say(" ") - tuple(true, mu) - say(";\n") - var c = mu - var i = 0 - while !isNil(c) do - lid(true, text(head(c))) - say(" := t_") - if len(mu) > 1 then proj(i, len(mu)) else () - say(";\n") - i = i + 1 - c = tail(c) - if mode == 1 then say("pure ()\n") else () - -def leanAux {r: Region} (ds: Decls, fn: Str, env: Nodes, gam: Nodes, e: Node): Unit = - val sc = scope(env) - val mu = mutated(sc, kid(e, 1)) - // canonical shape, the one Srs.loop_inv covers: aux cap st = do if (← cond st) then aux cap (← body st) else pure st - say("def ") - auxName(ds, true, fn, e) - var c = captured(sc, mu) - while !isNil(c) do - say(" (") - lid(true, text(head(c))) - say(" : ") - lty(kid(head(c), 0)) - say(")") - c = tail(c) - say(" (st' : ") - tupleTy(mu) - say(") : Option ") - tupleTy(mu) - say(" := do {\nif (← (fun (") - tupleUsed(mu, kid(e, 0)) - say(" : ") - tupleTy(mu) - say(") => (do {\npure ") - lx(ds, fn, env, gam, kid(e, 0), true) - say("\n} : Option Bool)) st') then ") - auxName(ds, true, fn, e) - auxArgs(true, captured(sc, mu)) - say(" (← (fun (") - tuple(true, mu) - say(" : ") - tupleTy(mu) - say(") => (do {\n") - c = mu - while !isNil(c) do - say("let mut ") - lid(true, text(head(c))) - say(" := ") - lid(true, text(head(c))) - say(";\n") - c = tail(c) - ls(ds, fn, env, gam, kid(e, 1), true, 0) - say("pure ") - tuple(true, mu) - say("\n} : Option ") - tupleTy(mu) - say(")) st') else pure st'\n}\npartial_fixpoint\n\n") - -// the tuple pattern, `_` for vars e does not read -def tupleUsed(mu: Nodes, e: Node): Unit = - if isNil(mu) then say("()") - else if isNil(tail(mu)) then useOr(head(mu), e) - else - say("(") - var c = mu - while !isNil(c) do - useOr(head(c), e) - if !isNil(tail(c)) then say(", ") else () - c = tail(c) - say(")") -def useOr(v: Node, e: Node): Unit = if reads(e, text(v)) then lid(true, text(v)) else say("_") -def reads(e: Node, x: Str): Bool = - var hit = kind(e) == XName && eqs(text(e), x) - var c = kids(e) - while !hit && !isNil(c) do - hit = reads(head(c), x) - c = tail(c) - hit - -// the scope vars a loop reads but does not assign -def captured {r: Region} (sc: Nodes, mu: Nodes): Nodes = - var out = NNil - var c = sc - while !isNil(c) do - if !found(find(mu, BVar, text(head(c)))) then out = NCons(head(c), out) else () - c = tail(c) - rev(out) - -// e as a Lean term; effects lifted with (← ..) in srs order; control in value position = a nested do -def lx {r: Region} (ds: Decls, fn: Str, env: Nodes, gam: Nodes, e: Node, on: Bool): Unit = - val k = kind(e) - if k == XInt then - put(on, "(") - putn(on, num(e)) - put(on, " : Int)") - else if k == XBool then put(on, if num(e) == 1 then "true" else "false") - else if k == XStr then - put(on, "\"") - put(on, text(e)) - put(on, "\".toUTF8") - else if k == XUnit then put(on, "()") - else if k == XName then - if found(find(env, BVar, text(e))) then lid(on, text(e)) else ctorName(on, ds, text(e)) - else if k == XCall then - val c = findDecl(ds, DCase, text(e)) - if found(c) then - put(on, "(") - ctorName(on, ds, text(e)) - lxArgs(ds, fn, env, gam, kids(e), NNil, on) - put(on, ")") - else - put(on, "(← ") - lid(on, text(e)) - lxArgs(ds, fn, env, gam, kids(e), kids(kid(findDecl(ds, DFn, text(e)), 0)), on) - put(on, ")") - else if k == XBin then lxBin(ds, fn, env, gam, e, on) - else if k == XUn then - put(on, if eqs(text(e), "-") then "(0 - " else "(!") - lx(ds, fn, env, gam, kid(e, 0), on) - put(on, ")") - else if k == XMethod then put(on, "srs_unsupported_method") - else - put(on, "(← (do {\n") - ls(ds, fn, env, gam, e, on, 1) - put(on, "}))") - -// e as a monadic action: lx without the outer `(← )` lift -def lxAct {r: Region} (ds: Decls, fn: Str, env: Nodes, gam: Nodes, e: Node, on: Bool): Unit = - put(on, "(pure ") - lx(ds, fn, env, gam, e, on) - put(on, ")") - -// call args; an arg at a capability param is erased -def lxArgs {r: Region} (ds: Decls, fn: Str, env: Nodes, gam: Nodes, xs: Nodes, ps0: Nodes, on: Bool): Unit = - var a = xs - var ps = ps0 - while !isNil(a) do - val cap = !isNil(ps) && isProto(ds, text(kid(head(ps), 0))) - if !cap then - put(on, " ") - lx(ds, fn, env, gam, head(a), on) - else () - a = tail(a) - ps = if isNil(ps) then ps else tail(ps) - -def lxBin {r: Region} (ds: Decls, fn: Str, env: Nodes, gam: Nodes, e: Node, on: Bool): Unit = - val op = text(e) - if eqs(op, "&&") || eqs(op, "||") then - // short-circuit: b runs only when a does not decide - put(on, "(← (do {\nif ") - lx(ds, fn, env, gam, kid(e, 0), on) - if eqs(op, "&&") then - put(on, " then {\npure ") - lx(ds, fn, env, gam, kid(e, 1), on) - put(on, "\n} else {\npure false\n}\n}))") - else - put(on, " then {\npure true\n} else {\npure ") - lx(ds, fn, env, gam, kid(e, 1), on) - put(on, "\n}\n}))") - else - val cmp = eqs(op, "<") || eqs(op, "<=") || eqs(op, ">") || eqs(op, ">=") - put(on, if cmp then "(decide (" else if eqs(op, "/") then "(Int.tdiv " else if eqs(op, "%") then "(Int.tmod " else "(") - lx(ds, fn, env, gam, kid(e, 0), on) - put(on, " ") - if !eqs(op, "/") && !eqs(op, "%") then - put(on, op) - put(on, " ") - else () - lx(ds, fn, env, gam, kid(e, 1), on) - put(on, if cmp then "))" else ")") - -// ── call-graph SCCs in one pass (vic-qf6, speed): Tarjan 1972, "Depth-first search and linear graph algorithms" ── -// info of a visited fn: Node(Name, f, "1" while on the stack else "", index, lowlink); a newer entry shadows an older one -enum Tarjan: - case Tarjan(next: I64, info: DMap, stack: Nodes, comps: Nodes) - -// g's node of f: Name(f, its callees) -def gGet(gm: DMap, f: Str): Node = find(dmGet(gm, strHash(f)), Name, f) - -def inSet(m: DMap, x: Str): Bool = found(find(dmGet(m, strHash(x)), Name, x)) - -def tInfo(st: Tarjan, f: Str): Node = st match - case Tarjan(_, info, _, _) => find(dmGet(info, strHash(f)), Name, f) - -def tSet {r: Region} (st: Tarjan, x: Node): Tarjan = st match - case Tarjan(n, info, stack, comps) => Tarjan(n, dmAdd(info, strHash(text(x)), x), stack, comps) - -// lowlink(v) = min(lowlink(v), x) -def tLow {r: Region} (st: Tarjan, v: Str, x: I64): Tarjan = - val iv = tInfo(st, v) - if x < lineOf(iv) then tSet(st, Node(Name, v, text2(iv), num(iv), x, NNil)) else st - -def tVisit {r: Region} (gm: DMap, v: Str, st0: Tarjan): Tarjan = st0 match - case Tarjan(n, info, stack, comps) => - var st = Tarjan(n + 1, dmAdd(info, strHash(v), Node(Name, v, "1", n, n, NNil)), NCons(leaf(Name, v, 0), stack), comps) - var c = kids(gGet(gm, v)) - while !isNil(c) do - val w = text(head(c)) - val iw = tInfo(st, w) - if !found(iw) then - st = tVisit(gm, w, st) - st = tLow(st, v, lineOf(tInfo(st, w))) - else if eqs(text2(iw), "1") then st = tLow(st, v, num(iw)) - else () - c = tail(c) - val iv = tInfo(st, v) - if lineOf(iv) == num(iv) then tPop(st, v) else st - -// v roots a component: pop it off the stack -def tPop {r: Region} (st0: Tarjan, v: Str): Tarjan = st0 match - case Tarjan(n, info0, stack0, comps) => - var info = info0 - var stack = stack0 - var members = NNil - var go = true - while go && !isNil(stack) do - val w = text(head(stack)) - val iw = find(dmGet(info, strHash(w)), Name, w) - info = dmAdd(info, strHash(w), Node(Name, w, "", num(iw), lineOf(iw), NNil)) - members = NCons(leaf(Name, w, 0), members) - stack = tail(stack) - go = !eqs(w, v) - Tarjan(n, info, stack, NCons(Node(Names, "", "", 0, 0, members), comps)) - -// fn -> Name(fn, the members of its SCC) -def sccMap {r: Region} (gm: DMap, g: Nodes): DMap = - var st = Tarjan(0, DTip, NNil, NNil) - var c = g - while !isNil(c) do - if !found(tInfo(st, text(head(c)))) then st = tVisit(gm, text(head(c)), st) else () - c = tail(c) - var out = DTip - var cs = tComps(st) - while !isNil(cs) do - var m = kids(head(cs)) - while !isNil(m) do - out = dmAdd(out, strHash(text(head(m))), Node(Name, text(head(m)), "", 0, 0, kids(head(cs)))) - m = tail(m) - cs = tail(cs) - out - -def tComps(st: Tarjan): Nodes = st match - case Tarjan(_, _, _, comps) => comps - -def sccOf(sm: DMap, f: Str): Nodes = kids(find(dmGet(sm, strHash(f)), Name, f)) - -// f is recursive: its SCC has 2+ fns, or f calls itself -def recIn(gm: DMap, sm: DMap, f: Str): Bool = len(sccOf(sm, f)) > 1 || has(kids(gGet(gm, f)), f) - -// every callee of sc is in sc or done -def depsDone(gm: DMap, sc: Nodes, done: DMap): Bool = - var ok = true - var c = sc - while ok && !isNil(c) do - var w = kids(gGet(gm, text(head(c)))) - while ok && !isNil(w) do - ok = inSet(done, text(head(w))) || has(sc, text(head(w))) - w = tail(w) - c = tail(c) - ok - -// the fns in a cycle of the call graph -def recSet {r: Region} (gm: DMap, sm: DMap, g: Nodes): DMap = - var out = DTip - var c = g - while !isNil(c) do - if recIn(gm, sm, text(head(c))) then out = dmAdd(out, strHash(text(head(c))), leaf(Name, text(head(c)), 0)) else () - c = tail(c) - out diff --git a/bench/corpus/s1/leanspec.srs b/bench/corpus/s1/leanspec.srs deleted file mode 100644 index 0beeab6d..00000000 --- a/bench/corpus/s1/leanspec.srs +++ /dev/null @@ -1,703 +0,0 @@ -// S1 Lean backend, verification part (C13): spec defs, contracts and loop invariants as Lean defs and theorems. -// Specs are pure: no ← (they call spec defs, constructors and the pure externs Srs.Rt.P only). - -def clausesOf(f: Node): Nodes = if len(kids(f)) > 3 then kids(kid(f, 3)) else NNil -def clauseExprs {r: Region} (cs: Nodes, kw: Str): Nodes = - var out = NNil - var c = cs - while !isNil(c) do - if kind(head(c)) == SClause && eqs(text(head(c)), kw) then out = NCons(kid(head(c), 0), out) else () - c = tail(c) - rev(out) -def proofOf(cs: Nodes): Node = find(cs, SClause, "proof") - -// e as a pure Lean term -def lp {r: Region} (ds: Decls, e: Node): Unit = lpr(ds, NoNode, e) - -// res: the term `result` stands for (NoNode = the name «result») -def lpr {r: Region} (ds: Decls, res: Node, e: Node): Unit = - val k = kind(e) - if k == XInt then - say("(") - sayn(num(e)) - say(" : Int)") - else if k == XBool then say(if num(e) == 1 then "true" else "false") - else if k == XStr then - say("\"") - say(text(e)) - say("\".toUTF8") - else if k == XUnit then say("()") - else if k == XName then - if found(res) && eqs(text(e), "result") then lpr(ds, NoNode, res) - else if found(findDecl(ds, DCase, text(e))) then ctorName(true, ds, text(e)) else lid(true, text(e)) - else if k == XCall then - val f = findDecl(ds, DFn, text(e)) - say("(") - if found(findDecl(ds, DCase, text(e))) then ctorName(true, ds, text(e)) - else if found(f) && num(f) == 1 then - say("Srs.Rt.P.") - say(text(e)) - else if found(f) && num(f) == 2 then lid(true, text(e)) - else say("srs_spec_calls_only_spec_defs") - var a = kids(e) - while !isNil(a) do - say(" ") - lpr(ds, res, head(a)) - a = tail(a) - say(")") - else if k == XBin then - val op = text(e) - val cmp = eqs(op, "<") || eqs(op, "<=") || eqs(op, ">") || eqs(op, ">=") - say(if cmp then "(decide (" else if eqs(op, "/") then "(Int.tdiv " else if eqs(op, "%") then "(Int.tmod " else "(") - lpr(ds, res, kid(e, 0)) - if !eqs(op, "/") && !eqs(op, "%") then - say(" ") - say(op) - else () - say(" ") - lpr(ds, res, kid(e, 1)) - say(if cmp then "))" else ")") - else if k == XUn then - say(if eqs(text(e), "-") then "(0 - " else "(!") - lpr(ds, res, kid(e, 0)) - say(")") - else if k == XIf then - say("(if ") - lpr(ds, res, kid(e, 0)) - say(" then ") - lpr(ds, res, kid(e, 1)) - say(" else ") - lpr(ds, res, kid(e, 2)) - say(")") - else if k == XMatch then - say("(match ") - lpr(ds, res, kid(e, 0)) - say(" with") - var arms = tail(kids(e)) - while !isNil(arms) do - val arm = head(arms) - say(" | ") - if eqs(text(arm), "_") then say("_") - else - ctorName(true, ds, text(arm)) - var bs = tail(kids(arm)) - while !isNil(bs) do - say(" ") - if eqs(text(head(bs)), "_") then say("_") else lid(true, text(head(bs))) - bs = tail(bs) - say(" => ") - lpr(ds, res, kid(arm, 0)) - arms = tail(arms) - say(")") - else if k == XBlock then - var c = kids(e) - var opens = 0 - while !isNil(c) do - val s = head(c) - if kind(s) == SVal then - say("(let ") - lid(true, text(s)) - say(" := ") - lpr(ds, res, kid(s, 0)) - say("; ") - opens = opens + 1 - else if kind(s) == SClause then () - else lpr(ds, res, s) - c = tail(c) - while opens > 0 do - say(")") - opens = opens - 1 - else say("srs_unsupported_in_spec") - -// conjunction of clause exprs, as Bool -def lpAll {r: Region} (ds: Decls, es: Nodes): Unit = lpAllR(ds, NoNode, es) -def lpAllR {r: Region} (ds: Decls, res: Node, es: Nodes): Unit = - if isNil(es) then say("True") - else - say("(") - var c = es - while !isNil(c) do - lpp(ds, res, head(c)) - if !isNil(tail(c)) then say(" ∧ ") else () - c = tail(c) - say(")") - -// a contract as a Prop: logic and comparisons as Lean props (facts simp and omega use), other terms `= true` -def lpp {r: Region} (ds: Decls, res: Node, e: Node): Unit = - val op = text(e) - if kind(e) == XBin && (eqs(op, "&&") || eqs(op, "||")) then - say("(") - lpp(ds, res, kid(e, 0)) - say(if eqs(op, "&&") then " ∧ " else " ∨ ") - lpp(ds, res, kid(e, 1)) - say(")") - else if kind(e) == XBin && (eqs(op, "==") || eqs(op, "!=") || eqs(op, "<") || eqs(op, "<=") || eqs(op, ">") || eqs(op, ">=")) then - say("(") - lpr(ds, res, kid(e, 0)) - say(if eqs(op, "==") then " = " else if eqs(op, "!=") then " ≠ " else if eqs(op, "<=") then " ≤ " else if eqs(op, ">=") then " ≥ " else " ") - if eqs(op, "<") || eqs(op, ">") then - say(op) - say(" ") - else () - lpr(ds, res, kid(e, 1)) - say(")") - else if kind(e) == XForall || kind(e) == XExists then - say(if kind(e) == XForall then "(∀ (" else "(∃ (") - lid(true, text(e)) - say(" : ") - lty(kid(e, 0)) - say("), ") - lpp(ds, res, kid(e, 1)) - say(")") - else if kind(e) == XUn && eqs(op, "!") then - say("(¬ ") - lpp(ds, res, kid(e, 0)) - say(")") - else - say("(") - lpr(ds, res, e) - say(" = true)") - -def lparams(ds: Decls, ps: Nodes): Unit = - var c = ps - while !isNil(c) do - if !isProto(ds, text(kid(head(c), 0))) then - say(" (") - lid(true, text(head(c))) - say(" : ") - lty(kid(head(c), 0)) - say(")") - else () - c = tail(c) - -def specDef {r: Region} (ds: Decls, f: Node): Unit = - say("def ") - lid(true, text(f)) - lparams(ds, kids(kid(f, 0))) - say(" : ") - lty(kid(f, 1)) - say(" :=\n ") - lp(ds, kid(f, 2)) - val dec = clauseExprs(clausesOf(f), "decreases") - if !isNil(dec) then - say("\ntermination_by (") - lp(ds, head(dec)) - say(").toNat") - else () - say("\n\n") - -// the proof of a contract: srs_auto with the `using` facts, induction, or Lean tactics -def proofText {r: Region} (ds: Decls, f: Node, p: Node): Unit = - if found(p) && eqs(text2(p), "lean") then say(text(kid(p, 0))) - else - say("by\n ") - val lp0 = invLoop(kid(f, 2)) - if found(lp0) then loopSkeleton(ds, f, lp0, p, false) - else if found(p) && eqs(text2(p), "by") then - say("induction ") - lid(true, text(kid(p, 0))) - say(" <;> ") - autoCall(ds, p, selfFacts(ds, f)) - else autoCall(ds, p, selfFacts(ds, f)) - -// srs_auto with the `proof using` facts + `extra` (the fns a loop calls): each fn and its contract theorem -def autoCall {r: Region} (ds: Decls, p: Node, extra: Nodes): Unit = - say("srs_auto [") - factList(ds, p, extra, true) - say("]") - -// the facts of a proof, comma separated (first: no leading comma): fns, their _eq/_spec/_ret theorems -def factList {r: Region} (ds: Decls, p: Node, extra: Nodes, first0: Bool): Unit = - var c = eqSpecs(ds, if found(p) && eqs(text2(p), "using") then append(kids(p), extra) else extra) - var first = first0 - while !isNil(c) do - val f = findDecl(ds, DFn, text(head(c))) - // n 1 = the fn being proven: its own contract is not a fact yet - val spec = found(f) && num(head(c)) == 0 && num(f) != 1 && !isNil(clauseExprs(clausesOf(f), "ensures")) - val eqn = spec && isEqFn(ds, f) - val ret = found(f) && num(head(c)) == 0 && !isNil(clauseExprs(clausesOf(f), "returns")) - // a fn with an _eq or returns rule is used through it, not unfolded; a recursive fn never (unfolding never ends) - if !eqn && !ret && !(found(f) && num(f) == 0 && isRec(ds, text(head(c)))) then - if !first then say(", ") else () - factName(f, text(head(c))) - first = false - else () - if spec then - if !first then say(", ") else () - say("«") - say(text(head(c))) - say(if eqn then "_eq»" else "_spec»") - first = false - else () - if ret then - if !first then say(", ") else () - say("«") - say(text(head(c))) - say(if isNil(clauseExprs(clausesOf(f), "requires")) then "_ok»" else "_ret»") - first = false - else () - c = tail(c) - -// a fact: a non-recursive match-defined spec def gives its equation lemmas, they rewrite constructors only -// (simp unfolds the def itself on a var into a match: simp_all loops on `c = t[c]` from such matches) -def factName(f: Node, name: Str): Unit = - val b = if num(f) == 2 then kid(f, 2) else NoNode - if kind(b) == XMatch && !selfCalls(b, name) then - var i = 1 - var a = tail(kids(b)) - while !isNil(a) do - if i > 1 then say(", ") else () - lid(true, name) - say(".eq_") - sayn(i) - i = i + 1 - a = tail(a) - else lid(true, name) -// name is on a call-graph cycle (Lean partial_fixpoint) -// e calls name -def selfCalls(e: Node, name: Str): Bool = - var hit = kind(e) == XCall && eqs(text(e), name) - var c = kids(e) - while !hit && !isNil(c) do - hit = selfCalls(head(c), name) - c = tail(c) - hit -// f has an _eq rule: one `ensures result == E`, no requires -def isEqFn {r: Region} (ds: Decls, f: Node): Bool = - val ce = clausesOf(f) - num(f) == 0 && isNil(clauseExprs(ce, "requires")) && !isNil(clauseExprs(ce, "ensures")) && isNil(tail(clauseExprs(ce, "ensures"))) && resultEq(head(clauseExprs(ce, "ensures"))) -// facts xs + the match-defined spec defs in the E of each fn used through its _eq rule: they rewrite only -// constructors. other spec defs there (if bodies) stay opaque: the proof reasons about them as atoms -def eqSpecs {r: Region} (ds: Decls, xs: Nodes): Nodes = - var out = xs - var c = xs - while !isNil(c) do - val f = findDecl(ds, DFn, text(head(c))) - if found(f) && num(head(c)) == 0 && isEqFn(ds, f) then - var s = specCalls(ds, kid(head(clauseExprs(clausesOf(f), "ensures")), 1), NNil) - while !isNil(s) do - if kind(kid(findDecl(ds, DFn, text(head(s))), 2)) == XMatch && !has(out, text(head(s))) then out = NCons(head(s), out) else () - s = tail(s) - else () - c = tail(c) - out - -// theorem f_spec (params) (h : requires) : ∃ result, f params = some result ∧ ensures -def fnTheorem {r: Region} (ds: Decls, f: Node): Unit = - val cs = clausesOf(f) - val ens = clauseExprs(cs, "ensures") - val req = clauseExprs(cs, "requires") - if !isNil(ens) then - say("theorem «") - say(text(f)) - say("_spec»") - // proof by induction x (no requires): ∀ x, one arm per case (Lean `induction` rejects mutual enums) - // shortcut: x must be the last param (f_eq applies f_spec positionally), until args are named - val p = proofOf(cs) - val ind = if isNil(req) && found(p) && eqs(text2(p), "by") then text(kid(p, 0)) else "" - lparams(ds, without(kids(kid(f, 0)), ind)) - if !isNil(req) then - say(" (_h_req : ") - lpAll(ds, req) - say(")") - else () - say(" :\n ") - if rt_str_len(ind) > 0 then - say("∀ (") - lid(true, ind) - say(" : ") - lty(kid(find(kids(kid(f, 0)), Param, ind), 0)) - say("), ") - else () - say("∃ «result», ") - lid(true, text(f)) - var c = kids(kid(f, 0)) - while !isNil(c) do - if !isProto(ds, text(kid(head(c), 0))) then - say(" ") - lid(true, text(head(c))) - else () - c = tail(c) - say(" = some «result» ∧ ") - lpAll(ds, ens) - if rt_str_len(ind) > 0 then inductionArms(ds, f, p, ind, false) else - say(" := ") - proofText(ds, f, p) - say("\n\n") - if isNil(req) && isNil(tail(ens)) && resultEq(head(ens)) then eqTheorem(ds, f, kid(head(ens), 1)) else () - else () - val rets = clauseExprs(cs, "returns") - if !isNil(rets) then retTheorem(ds, f, rets) else () - -// returns (C15): theorem f_ret (params) (h : requires) : ∀ result, f params = some result → returns. exit = no claim -def retTheorem {r: Region} (ds: Decls, f: Node, rets: Nodes): Unit = - val cs = clausesOf(f) - val req = clauseExprs(cs, "requires") - val p = proofOf(cs) - say("theorem «") - say(text(f)) - say("_ret»") - lparams(ds, kids(kid(f, 0))) - if !isNil(req) then - say(" (_h_req : ") - lpAll(ds, req) - say(")") - else () - say(" :\n ∀ «result», ") - lid(true, text(f)) - largs(ds, kids(kid(f, 0))) - say(" = some «result» → ") - lpAll(ds, rets) - say(" := by\n refine Srs.ok_intro ?_\n ") - val lp0 = invLoop(kid(f, 2)) - if found(lp0) then loopSkeleton(ds, f, lp0, p, true) - else - // a recursive f unfolds once (a fact would unfold it forever); a loop w/o invariant stays opaque: the claim - // must hold for any loop result (Srs.ok_true) - if isRec(ds, text(f)) then - say("rw [«") - say(text(f)) - say("»]\n ") - else () - autoCall(ds, p, selfFacts(ds, f)) - say("\n\n") - // callers use f through f_ok: ok (f params) P = ∀ result, f params = some result → returns → P result - if isNil(req) then - say("theorem «") - say(text(f)) - say("_ok»") - lparams(ds, kids(kid(f, 0))) - say(" (P : ") - lty(kid(f, 1)) - say(" → Prop) :\n Srs.ok (") - lid(true, text(f)) - largs(ds, kids(kid(f, 0))) - say(") P = ∀ «result», ") - lid(true, text(f)) - largs(ds, kids(kid(f, 0))) - say(" = some «result» → ") - lpAll(ds, rets) - say(" → P «result» :=\n Srs.ok_ret («") - say(text(f)) - say("_ret»") - largs(ds, kids(kid(f, 0))) - say(") P\n\n") - else () - -def verification {r: Region} (ds: Decls): Unit = - var c = declList(ds) - while !isNil(c) do - if kind(head(c)) == DFn && num(head(c)) == 0 then fnTheorem(ds, head(c)) else () - c = tail(c) - -// spec def f with ensures: theorem f_spec (params) : ensures, `result` = the call f params -def specTheorems {r: Region} (ds: Decls): Unit = - var c = declList(ds) - while !isNil(c) do - val f = head(c) - val ens = if kind(f) == DFn && num(f) == 2 then clauseExprs(clausesOf(f), "ensures") else NNil - if !isNil(ens) then - val p = proofOf(clausesOf(f)) - val ind = if found(p) && eqs(text2(p), "by") then text(kid(p, 0)) else "" - say("theorem «") - say(text(f)) - say("_spec»") - lparams(ds, without(kids(kid(f, 0)), ind)) - say(" :\n ") - if rt_str_len(ind) > 0 then - say("∀ (") - lid(true, ind) - say(" : ") - lty(kid(find(kids(kid(f, 0)), Param, ind), 0)) - say("), ") - else () - // `result` = the call itself: a fact simp can use - var args = NNil - var a = kids(kid(f, 0)) - while !isNil(a) do - args = NCons(leaf(XName, text(head(a)), 0), args) - a = tail(a) - lpAllR(ds, Node(XCall, text(f), "", 0, 0, rev(args)), ens) - if rt_str_len(ind) > 0 then inductionArms(ds, f, p, ind, true) else - say(" := ") - proofText(ds, f, p) - say("\n\n") - else () - c = tail(c) - -// the first top-level loop of a fn body that has an invariant, else NoNode -def invLoop {r: Region} (body: Node): Node = - var res = NoNode - var c = if kind(body) == XBlock then kids(body) else one(body) - while !found(res) && !isNil(c) do - val s = head(c) - if kind(s) == XWhile && found(find(kids(kid(s, 1)), SClause, "invariant")) then res = s else () - c = tail(c) - res - -// env at loop w: params + the vals before it (types from the checker, as lsBlock does) -def loopEnv {r: Region} (ds: Decls, f: Node, w: Node): Nodes = - var env = fnEnv(ds, sigParams(ds, f, defSol(ds, f))) - var gam = fnGam(ds, sigParams(ds, f, defSol(ds, f))) - var c = if kind(kid(f, 2)) == XBlock then kids(kid(f, 2)) else NNil - while !isNil(c) && !(kind(head(c)) == XWhile && lineOf(head(c)) == lineOf(w)) do - val s = head(c) - if kind(s) == SVal then - val x = chk(ds, env, gam, kid(s, 0), NoNode) - val t = if !isNil(tail(kids(s))) then kid(s, 1) else if num(s) == 1 then uncapped(text(tgTy(x))) else tgTy(x) - gam = tgGam(x) - env = NCons(Node(BVar, text(s), "", num(s), lineOf(s), one(t)), env) - else if kind(s) == SClause || kind(s) == SHandle then () - else gam = tgGam(chk(ds, env, gam, s, NoNode)) - c = tail(c) - env - -def rpat(mu: Nodes): Unit = - if isNil(mu) then say("_") - else if isNil(tail(mu)) then lid(true, text(head(mu))) - else - say("⟨") - var c = mu - while !isNil(c) do - lid(true, text(head(c))) - if !isNil(tail(c)) then say(", ") else () - c = tail(c) - say("⟩") - -// the user fns a fn body calls: unfolded by srs_auto, or rewritten by their _eq rule -def bodyCalls {r: Region} (ds: Decls, body: Node): Nodes = - var out = NNil - var c = callsOf(ds, body, NNil) - while !isNil(c) do - out = NCons(leaf(Name, text(head(c)), 0), out) - c = tail(c) - out - -// the proof of a fn whose body loop has an invariant: Srs.loop_bind (ret: Srs.loop_ret_bind, partial) with the -// loop's invariant and measure; left: one turn keeps it (step), it holds on entry, the contract holds at exit -def loopSkeleton {r: Region} (ds: Decls, f: Node, w: Node, p: Node, ret: Bool): Unit = - val env = loopEnv(ds, f, w) - val sc = scope(env) - val mu = mutated(sc, kid(w, 1)) - val cap = captured(sc, mu) - val inv = clauseExprs(kids(kid(w, 1)), "invariant") - val dec = clauseExprs(kids(kid(w, 1)), "decreases") - val hints = append(bodyCalls(ds, kid(f, 2)), specClosure(ds, append(inv, append(dec, clauseExprs(clausesOf(f), if ret then "returns" else "ensures"))), NNil)) - say("rw [") - lid(true, text(f)) - say("]\n dsimp only\n (try simp only [Srs.some_bind, pure_bind") - factList(ds, p, hints, false) - say("])\n refine Srs.") - say(if ret then "loop_ret_bind (" else "loop_bind (") - auxName(ds, true, text(f), w) - var c = cap - while !isNil(c) do - say(" _") - c = tail(c) - say(") _ _ (fun _ => by rw [") - auxName(ds, true, text(f), w) - say("]) (fun (") - tuple(true, mu) - say(" : ") - tupleTy(mu) - say(") => ") - lpAll(ds, inv) - say(") (fun (") - tuple(true, mu) - say(" : ") - tupleTy(mu) - say(") => (") - if isNil(dec) then say("srs_loop_needs_decreases") else lp(ds, head(dec)) - say(").toNat) ?_ _ _ _ ?_ ?_\n · rintro ") - rpat(mu) - say(if ret then " hI b hc hb\n " else " hI\n ") - casesEnums(ds, condVars(ds, mu, kid(w, 0), kid(w, 1))) - autoCall(ds, p, hints) - say("\n · ") - autoCall(ds, p, hints) - say("\n · rintro ") - rpat(mu) - say(" hI hc\n ") - casesEnums(ds, condVars(ds, mu, kid(w, 0), kid(w, 1))) - autoCall(ds, p, hints) - -// case split on each enum- or Bool-typed loop var, and one level into its enum fields: conditions and bodies -// match on them -def casesEnums(ds: Decls, mu: Nodes): Unit = - var c = mu - while !isNil(c) do - val t = text(kid(head(c), 0)) - if isEnum(ds, t) then - say("rcases ") - lid(true, text(head(c))) - say(" with ") - enumPat(ds, t, 2) - say(" <;> ") - else if eqs(t, "Bool") then - say("cases ") - lid(true, text(head(c))) - say(" <;> ") - else () - c = tail(c) - -// rcases pattern of enum t, `depth` levels deep -def enumPat(ds: Decls, t: Str, depth: I64): Unit = - if depth == 0 || !isEnum(ds, t) then say("_") - else - say("(") - var cs = kids(findDecl(ds, DEnum, t)) - while !isNil(cs) do - var fs = kids(kid(head(cs), 0)) - if isNil(fs) then say("⟨⟩") - else - say("⟨") - while !isNil(fs) do - enumPat(ds, text(kid(head(fs), 0)), depth - 1) - if !isNil(tail(fs)) then say(", ") else () - fs = tail(fs) - say("⟩") - if !isNil(tail(cs)) then say(" | ") else () - cs = tail(cs) - say(")") - -def without {r: Region} (ps: Nodes, name: Str): Nodes = - var out = NNil - var c = ps - while !isNil(c) do - if !eqs(text(head(c)), name) then out = NCons(head(c), out) else () - c = tail(c) - rev(out) - -// proof by induction x: one arm per case of x's enum, an induction hypothesis per field of that enum -// (structural recursion: works for mutual enums too); gen: the hypothesis holds for all other params (accumulators) -def inductionArms {r: Region} (ds: Decls, f: Node, p: Node, x: Str, gen: Bool): Unit = - val ty = text(kid(find(kids(kid(f, 0)), Param, x), 0)) - var cs = kids(findDecl(ds, DEnum, ty)) - while !isNil(cs) do - say("\n | ") - ctorName(true, ds, text(head(cs))) - var fs = kids(kid(head(cs), 0)) - var i = 0 - while !isNil(fs) do - say(" a") - sayn(i) - i = i + 1 - fs = tail(fs) - say(" => by\n ") - fs = kids(kid(head(cs), 0)) - i = 0 - var ihs = NNil - while !isNil(fs) do - if eqs(text(kid(head(fs), 0)), ty) then - say("have ih") - sayn(i) - say(" := ") - var a = without(kids(kid(f, 0)), x) - if gen && !isNil(a) then - say("fun") - var g = a - while !isNil(g) do - say(" ") - lid(true, text(head(g))) - g = tail(g) - say(" => ") - else () - say("«") - say(text(f)) - say("_spec»") - while !isNil(a) do - say(" ") - lid(true, text(head(a))) - a = tail(a) - say(" a") - sayn(i) - say("\n ") - else () - i = i + 1 - fs = tail(fs) - autoCall(ds, p, selfFacts(ds, f)) - cs = tail(cs) - -// a proof without loop: f itself (n 1 = not yet a fact), the fns its body calls, the spec defs its contract calls -def selfFacts {r: Region} (ds: Decls, f: Node): Nodes = - val cs = clausesOf(f) - NCons(Node(Name, text(f), "", 1, 0, NNil), append(bodyCalls(ds, kid(f, 2)), specClosure(ds, append(clauseExprs(cs, "requires"), append(clauseExprs(cs, "ensures"), clauseExprs(cs, "returns"))), NNil))) -// the spec defs exprs es call (unfolded by srs_auto); not the ones those call: they stay opaque -def specClosure {r: Region} (ds: Decls, es: Nodes, acc: Nodes): Nodes = - var out = acc - var c = es - while !isNil(c) do - out = specCalls(ds, head(c), out) - c = tail(c) - out -def specCalls {r: Region} (ds: Decls, e: Node, acc: Nodes): Nodes = - var out = acc - if kind(e) == XCall then - val f = findDecl(ds, DFn, text(e)) - if found(f) && num(f) == 2 && !has(out, text(e)) then - out = NCons(leaf(Name, text(e), 0), out) - else () - else () - var c = kids(e) - while !isNil(c) do - out = specCalls(ds, head(c), out) - c = tail(c) - out - -// ensures `result == E` -def resultEq(e: Node): Bool = kind(e) == XBin && eqs(text(e), "==") && kind(kid(e, 0)) == XName && eqs(text(kid(e, 0)), "result") - -// theorem f_eq (params) : f params = some E: the contract as a rewrite rule for the proofs of callers -def eqTheorem {r: Region} (ds: Decls, f: Node, e: Node): Unit = - say("theorem «") - say(text(f)) - say("_eq»") - lparams(ds, kids(kid(f, 0))) - say(" :\n ") - lid(true, text(f)) - largs(ds, kids(kid(f, 0))) - say(" = some ") - lp(ds, e) - say(" := by\n obtain ⟨_, h1, h2⟩ := «") - say(text(f)) - say("_spec»") - largs(ds, kids(kid(f, 0))) - say("\n rw [h1, h2]\n\n") - -def largs(ds: Decls, ps: Nodes): Unit = - var c = ps - while !isNil(c) do - if !isProto(ds, text(kid(head(c), 0))) then - say(" ") - lid(true, text(head(c))) - else () - c = tail(c) - -// the loop vars the condition reads, or the body passes to a fn whose _eq rule is a non-recursive match: the -// case splits they need (that rule's equation lemmas rewrite constructors only) -def condVars {r: Region} (ds: Decls, mu: Nodes, cond: Node, body: Node): Nodes = - var out = NNil - var c = mu - while !isNil(c) do - if reads(cond, text(head(c))) || matchArg(ds, body, text(head(c))) then out = NCons(head(c), out) else () - c = tail(c) - rev(out) -// e has a call g(.., x, ..) with g's _eq rule a non-recursive match-defined spec def -def matchArg {r: Region} (ds: Decls, e: Node, x: Str): Bool = - var hit = kind(e) == XCall && nameArg(kids(e), x) && matchEq(ds, text(e)) - var c = kids(e) - while !hit && !isNil(c) do - hit = matchArg(ds, head(c), x) - c = tail(c) - hit -def nameArg(xs: Nodes, x: Str): Bool = - var hit = false - var c = xs - while !hit && !isNil(c) do - hit = kind(head(c)) == XName && eqs(text(head(c)), x) - c = tail(c) - hit -def matchEq {r: Region} (ds: Decls, g: Str): Bool = - val f = findDecl(ds, DFn, g) - val s = if found(f) && isEqFn(ds, f) then findDecl(ds, DFn, text(kid(head(clauseExprs(clausesOf(f), "ensures")), 1))) else NoNode - num(s) == 2 && kind(kid(s, 2)) == XMatch && !selfCalls(kid(s, 2), text(s)) diff --git a/bench/corpus/s1/lex.srs b/bench/corpus/s1/lex.srs deleted file mode 100644 index e80c5e1b..00000000 --- a/bench/corpus/s1/lex.srs +++ /dev/null @@ -1,84 +0,0 @@ -// S1 lexer: tokens + layout (TNl / TIndent / TDedent), same rules as s0/lex.zig. - -def isAlpha(c: I64): Bool = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' -def isDigit(c: I64): Bool = c >= '0' && c <= '9' -def isPunct(c: I64): Bool = - c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' || c == ':' || c == '=' || c == '+' || c == '-' || c == '*' || c == '/' || c == '%' || c == '<' || c == '>' || c == '!' || c == '.' || c == '^' || c == '@' -def isTwo(a: I64, b: I64): Bool = - (a == '=' && b == '>') || (a == '=' && b == '=') || (a == '!' && b == '=') || (a == '<' && b == '=') || (a == '>' && b == '=') || (a == '&' && b == '&') || (a == '|' && b == '|') || (a == '~' && b == '>') - -def tok {r: Region} (k: Kind, s: Str, line: I64): Node = Node(k, s, "", 0, line, NNil) - -// last token is a layout token (no TNl needed after it) -def layoutLast(out: Nodes): Bool = - if isNil(out) then true - else - val k = kind(head(out)) - k == TNl || k == TIndent || k == TDedent - -def lex {r: Region} (src: Str): Nodes = - var out = NNil - var ind = one(Node(TInt, "", "", 0, 0, NNil)) - var i = 0 - var line = 1 - var depth = 0 - var bol = true - val n = rt_str_len(src) - while i < n do - if bol && depth == 0 then - var col = 0 - while rt_str_at(src, i) == ' ' do - col = col + 1 - i = i + 1 - val c = rt_str_at(src, i) - if c == '\t' then fatal("tab in indentation", line) else () - val blank = c == -1 || c == '\n' || (c == '/' && rt_str_at(src, i + 1) == '/') - bol = false - if !blank then - if col > num(head(ind)) then - ind = NCons(Node(TInt, "", "", col, line, NNil), ind) - out = NCons(tok(TIndent, "", line), out) - else - while col < num(head(ind)) do - ind = tail(ind) - out = NCons(tok(TDedent, "", line), out) - if col != num(head(ind)) then fatal("bad dedent", line) else () - else () - else - val c = rt_str_at(src, i) - if c == '\n' then - if depth == 0 && !layoutLast(out) then out = NCons(tok(TNl, "", line), out) else () - line = line + 1 - i = i + 1 - bol = true - else if c == ' ' || c == '\r' then i = i + 1 - else if c == '/' && rt_str_at(src, i + 1) == '/' then - while i < n && rt_str_at(src, i) != '\n' do i = i + 1 - else if isAlpha(c) then - val b = i - while isAlpha(rt_str_at(src, i)) || isDigit(rt_str_at(src, i)) do i = i + 1 - out = NCons(tok(TIdent, rt_str_slice(src, b, i), line), out) - else if isDigit(c) then - val b = i - while isDigit(rt_str_at(src, i)) do i = i + 1 - out = NCons(tok(TInt, rt_str_slice(src, b, i), line), out) - else if c == '"' || c == '\'' then - i = i + 1 - val b = i - while i < n && rt_str_at(src, i) != c && rt_str_at(src, i) != '\n' do - if rt_str_at(src, i) == '\\' then i = i + 2 else i = i + 1 - if rt_str_at(src, i) != c then fatal("unterminated literal", line) else () - out = NCons(tok(if c == '"' then TStr else TChar, rt_str_slice(src, b, i), line), out) - i = i + 1 - else - val w = if isTwo(c, rt_str_at(src, i + 1)) then 2 else 1 - if w == 1 && !isPunct(c) then fatal("bad character", line) else () - if c == '(' || c == '[' then depth = depth + 1 else () - if (c == ')' || c == ']') && depth > 0 then depth = depth - 1 else () - out = NCons(tok(TOp, rt_str_slice(src, i, i + w), line), out) - i = i + w - if !isNil(out) && kind(head(out)) != TNl && kind(head(out)) != TDedent then out = NCons(tok(TNl, "", line), out) else () - while num(head(ind)) > 0 do - ind = tail(ind) - out = NCons(tok(TDedent, "", line), out) - rev(NCons(tok(TEof, "", line), out)) diff --git a/bench/corpus/s1/main.srs b/bench/corpus/s1/main.srs deleted file mode 100644 index 92b17b15..00000000 --- a/bench/corpus/s1/main.srs +++ /dev/null @@ -1,20 +0,0 @@ -// S1: `s1 a.srs b.srs ... > out.c`, or `s1 --lean NS a.srs ... > out.lean` (namespace Srs.NS) (s1/lean.srs). Decls of all files form one program. - -def main(): I64 = - handle r = Arena() - val lean = rt_argc() > 1 && rt_str_eq(rt_arg(1), "--lean") - var ds = NNil - var i = if lean then 3 else 1 - while i < rt_argc() do - val src = rt_read_file(rt_arg(i)) - if rt_str_len(src) < 0 then - rt_eprint("srs: cannot read ") - rt_eprint(rt_arg(i)) - rt_eprint("\n") - rt_exit(1) - else () - ds = append(ds, parseFile(lex(src))) - i = i + 1 - val ds2 = check(ds) - if lean then emitLean(mkDecls(expandTypes(mkDecls(ds))), rt_arg(2)) else emitProgram(mkDecls(mono(mkDecls(ds2)))) - 0 diff --git a/bench/corpus/s1/mono.srs b/bench/corpus/s1/mono.srs deleted file mode 100644 index 04245eab..00000000 --- a/bench/corpus/s1/mono.srs +++ /dev/null @@ -1,159 +0,0 @@ -// Mono (vic-9l7.4 BD2): the instances of generic defs. A generic def is copied once per distinct type args its calls -// reach (C name f____), [] binders replaced by the types; its kid 4 then holds the type args (Names). -// A generic extern keeps one C symbol: its [] binders are void* (vic B-Q6), so only pointer types fill them. -// BD2 type args are names the program declares, so the instances are finite and the loop ends. - -// a def with [] binders: only its instances are code -def isGeneric {r: Region} (d: Node): Bool = kind(d) == DFn && num(d) == 0 && !isNil(tparams(d)) - -// the checked program and the instances it reaches -def mono {r: Region} (ds: Decls): Nodes = - var todo = NNil - var c = declList(ds) - while !isNil(c) do - // a given's defs are reached by its evidence calls, not as roots - if !isGeneric(head(c)) && kind(head(c)) != DGiven && kind(head(c)) != DType then todo = insts(head(c), todo) else () - c = tail(c) - var made = NNil - while !isNil(todo) do - val x = head(todo) - todo = tail(todo) - val f = findDecl(ds, DFn, text(x)) - if kind(x) == XEv then - if !isMadeEv(made, x) then - val g = evInst(ds, x) - made = NCons(g, made) - todo = insts(kid(g, 2), todo) - else () - else if num(f) == 1 then needPointers(ds, x) - else if !isMade(made, x) then - val g = instantiate(f, kids(kid(x, 0))) - made = NCons(g, made) - todo = insts(kid(g, 2), todo) - else () - val prog = append(declList(ds), rev(made)) - append(prog, enumInsts(mkDecls(prog))) - -// the XInst nodes of e, onto acc -def insts {r: Region} (e: Node, acc: Nodes): Nodes = - var out = if kind(e) == XInst || kind(e) == XEv then NCons(e, acc) else acc - var c = kids(e) - while !isNil(c) do - out = insts(head(c), out) - c = tail(c) - out - -// an instance of x's callee at x's type args is made already -def isMade(made: Nodes, x: Node): Bool = - var c = made - var res = false - while !res && !isNil(c) do - res = eqs(text(head(c)), text(x)) && rt_str_len(text2(head(c))) == 0 && tysEq(kids(kid(head(c), 4)), kids(kid(x, 0))) - c = tail(c) - res - -// f with its [] binders replaced by targs; kid 4 = the type args -def instantiate {r: Region} (f: Node, targs: Nodes): Node = - val g = substTy(f, tparams(f), targs) - withKids(g, NCons(kid(g, 0), NCons(kid(g, 1), NCons(kid(g, 2), NCons(kid(g, 3), one(list(Names, lineOf(f), targs))))))) - -def substTy {r: Region} (e: Node, tps: Nodes, targs: Nodes): Node = - val i = if kind(e) == Ty then index(tps, text(e)) else -1 - if i >= 0 then nth(targs, i) - else - var out = NNil - var c = kids(e) - while !isNil(c) do - out = NCons(substTy(head(c), tps, targs), out) - c = tail(c) - withKids(e, rev(out)) - -// an extern's [] binder is a void* slot -def needPointers(ds: Decls, x: Node): Unit = - var c = kids(kid(x, 0)) - while !isNil(c) do - if !isEnum(ds, text(head(c))) && !eqs(text(head(c)), "Ptr") then err("extern [] binder needs a pointer type (void*), not", text(head(c)), lineOf(x)) else () - c = tail(c) - -// the instances of generic enums the program reaches: each enum T[args] its code names, closed over the fields -def enumInsts {r: Region} (ds: Decls): Nodes = - val cs = allCases(ds) - var todo = NNil - var c = declList(ds) - while !isNil(c) do - val d = head(c) - // not roots: generic defs and enums, givens (reached by evidence calls), traits (signatures only) - val generic = isGeneric(d) || (kind(d) == DEnum && isGenericEnum(ds, d)) || kind(d) == DGiven || kind(d) == DTrait || kind(d) == DType - if !generic then todo = applied(ds, cs, d, todo) else () - c = tail(c) - var made = NNil - while !isNil(todo) do - val t = head(todo) - todo = tail(todo) - if !isMadeEnum(made, t) then - val en = findDecl(ds, DEnum, text(t)) - val inst = enumInst(substTy(en, enumTParams(ds, text(t)), tyArgs(t)), tyArgs(t)) - made = NCons(inst, made) - todo = applied(ds, cs, inst, todo) - else () - rev(made) - -// the generic enum types e names, onto acc: T[args] types, and the type of each case it builds (XNew) -def applied {r: Region} (ds: Decls, cs: Nodes, e: Node, acc: Nodes): Nodes = - var out = acc - if kind(e) == Ty && !isNil(tyArgs(e)) && isEnum(ds, text(e)) then out = NCons(e, out) else () - if kind(e) == XNew then out = NCons(Node(Ty, text2(find(cs, DCase, text(e))), "", 0, lineOf(e), one(Node(TyTo, "", "", 0, 0, kids(kid(e, 0))))), out) else () - var c = kids(e) - while !isNil(c) do - out = applied(ds, cs, head(c), out) - c = tail(c) - out - -def isMadeEnum(made: Nodes, t: Node): Bool = - var c = made - var res = false - while !res && !isNil(c) do - res = eqs(text(head(c)), text(t)) && tysEq(enumArgs(head(c)), tyArgs(t)) - c = tail(c) - res - -// enum d at type args targs: every case keeps them as its kid 1 -def enumInst {r: Region} (d: Node, targs: Nodes): Node = - var out = NNil - var c = kids(d) - while !isNil(c) do - out = NCons(withKids(head(c), NCons(kid(head(c), 0), one(list(Names, lineOf(d), targs)))), out) - c = tail(c) - withKids(d, rev(out)) - -// the method of an evidence call at its concrete goal: the one given whose head matches (the checker proved one), -// instantiated at its [] binders; t = the trait and kid 4 = the goal's args name it in C (g_Show__I64_show) -def evInst {r: Region} (ds: Decls, x: Node): Node = - val et = head(kids(kid(x, 0))) - // the same pick as the checker's (s1/given.srs pickGiven) - pickGiven(ds, et) match - case NoGiven => - errTy("internal: no given at mono for", et, lineOf(x)) - x - case Ambiguous => - errTy("internal: ambiguous given at mono for", et, lineOf(x)) - x - case GivenAt(g, s) => - val f = find(tail(tail(kids(g))), DFn, text(x)) - val tps = groupBinders(kids(kid(g, 0))) - val h = substTy(f, tps, boundTypes(tps, s)) - Node(DFn, text(f), text(et), 0, lineOf(f), NCons(kid(h, 0), NCons(kid(h, 1), NCons(kid(h, 2), NCons(kid(h, 3), one(list(Names, lineOf(f), tyArgs(et)))))))) - -// the type each binder of tps is bound to in sub, in order -def boundTypes {r: Region} (tps: Nodes, sub: Nodes): Nodes = - if isNil(tps) then NNil else NCons(kid(find(sub, Binder, text(head(tps))), 0), boundTypes(tail(tps), sub)) - -// the method of x's goal is made already -def isMadeEv(made: Nodes, x: Node): Bool = - val et = head(kids(kid(x, 0))) - var c = made - var res = false - while !res && !isNil(c) do - res = eqs(text(head(c)), text(x)) && eqs(text2(head(c)), text(et)) && tysEq(kids(kid(head(c), 4)), tyArgs(et)) - c = tail(c) - res diff --git a/bench/corpus/s1/node.srs b/bench/corpus/s1/node.srs deleted file mode 100644 index 6ab9d833..00000000 --- a/bench/corpus/s1/node.srs +++ /dev/null @@ -1,337 +0,0 @@ -// S1 shared data: one node shape, closed Kind enum. - -enum Kind: - // tokens - case TIdent - case TInt - case TStr - case TChar - case TOp - case TNl - case TIndent - case TDedent - case TEof - // types: s = name, t = from state, a = [TyTo(s = to), TyCap(s)...], n = 1 if caps annotated - case Ty - case TyTo // s = to state, a = type args of T[args] - case TyCap - // decls - case DFn // s name, n 0 def / 1 extern / 2 spec def (Lean only), a = [Params, ret Ty, body?, Names clauses?, Groups?] - case DEnum // s name, a = cases - case DCase // s name, t enum name, n tag, a = [Params, Groups of the enum] - case DProto // s name, t start, a = [Names states, Names ends, Name drop, Ops, Names rules (DRule)] - case DRule // s name, a = [Names params, atoms (TTerm)...]: a rule def of a protocol - case DType // s name, n 1 = match type, a = [Groups, body Ty, DTCase...]: type F [A: Type] = T - case DTCase // a = [pattern Ty, result Ty]: a case of a match type - case DOp // s name, a = [Params, ret Ty, Names trans] - case DTrans // s from, t to - case DHandler // s name, t protocol, a = fns - case DTrait // s name, a = [Groups, DFn signatures...] - case DGiven // s trait name, a = [Groups, head Ty, DFn (kid 4 = the given's Groups)...] - case Params - case Param // s name, a = [Ty] - case Groups // a = Group in written order (vic/c/binders-design.md) - case Group // s "[" type ascriptions / "{" evidence / "<" facts, t "out" = facts after the return type, a = Binder or TTerm - case Binder // s name, a = [TTerm] - case TTerm // s name or digits, n 1 = int, a = args: a type (application) or a Datalog atom - case Names - case Name // s - // exprs - case XInt // n - case XBool // n - case XStr // s raw - case XUnit - case XName // s - case XCall // s callee, a = args - case XCallG // s callee, a = [Groups: "[" types / "{" Names chosen, args...]: f[T]{a}(x) (vic 2026-11-05) - case XInst // checker output (e2): call of a generic fn; s callee, a = [Names types in [] binder order, args...] - case XNew // checker output (e2): a case of a generic enum; s case, a = [Names type args, args...] - case XEv // checker output (e2): s.m(args) on {} evidence; s method, t binder, a = [Names [trait type], args...] - case XMethod // s receiver, t op, a = args - case XBin // s op, a = [l, r] - case XUn // s op, a = [e] - case XIf // a = [c, t, e] - case XMatch // a = [scrutinee, arms...] - case XForall // s var, a = [Ty, body]: `forall x: T => e`, spec exprs only (C14), Lean ∀ - case XExists // s var, a = [Ty, body]: `exists x: T => e`, spec exprs only (C15), Lean ∃ - case XArm // s ctor or "_", a = [body, binds...] - case XBlock // a = stmts; value = last when expression - case XWhile // a = [c, body] - case XAssign // s name, a = [e] - case SVal // s name, n 1 = var, a = [e, Ty?] - case SHandle // s name, t handler, a = args - case SClause // s requires/ensures/decreases/invariant/proof, t proof mode using/by/lean, a = [e] or names - // checker - case BVar // s name, t protocol or "", n local id (-1 = param), a = [Ty] (checker) - case BCap // s name, t C name, a = [Ty protocol] - case GState // s cap, t state - case GVar // s var, a = caps it holds now - -enum Node: - case NoNode - case Node(k: Kind, s: Str, t: Str, n: I64, line: I64, a: Nodes) - -enum Nodes: - case NNil - case NCons(h: Node, tl: Nodes) - -def kind(x: Node): Kind - ensures result == kindS(x) - proof by induction x -= x match - case Node(k, _, _, _, _, _) => k - case NoNode => TEof -def text(x: Node): Str - ensures result == textS(x) - proof by induction x -= x match - case Node(_, s, _, _, _, _) => s - case NoNode => "" -def text2(x: Node): Str - ensures result == text2S(x) - proof by induction x -= x match - case Node(_, _, t, _, _, _) => t - case NoNode => "" -def num(x: Node): I64 - ensures result == numS(x) - proof by induction x -= x match - case Node(_, _, _, n, _, _) => n - case NoNode => 0 -def lineOf(x: Node): I64 = x match - case Node(_, _, _, _, l, _) => l - case NoNode => 0 -def kids(x: Node): Nodes - ensures result == kidsS(x) - proof by induction x -= x match - case Node(_, _, _, _, _, a) => a - case NoNode => NNil - -def isNil(xs: Nodes): Bool = xs match - case NNil => true - case _ => false -def head(xs: Nodes): Node - ensures result == headS(xs) - proof by induction xs -= xs match - case NCons(h, _) => h - case NNil => NoNode -def tail(xs: Nodes): Nodes - ensures result == tailS(xs) - proof by induction xs -= xs match - case NCons(_, t) => t - case NNil => NNil -def len(xs: Nodes): I64 = - var n = 0 - var c = xs - while !isNil(c) do - n = n + 1 - c = tail(c) - n -def nth(xs: Nodes, i: I64): Node - ensures result == nthS(xs, i) -= - var c = xs - var k = i - while k > 0 do - invariant nthS(c, k) == nthS(xs, i) - decreases k - c = tail(c) - k = k - 1 - head(c) -def kid(x: Node, i: I64): Node - ensures result == nthS(kidsS(x), i) -= nth(kids(x), i) -def drop(xs: Nodes, i: I64): Nodes = - var c = xs - var k = i - while k > 0 do - c = tail(c) - k = k - 1 - c -spec def revOnto(xs: Nodes, acc: Nodes): Nodes = xs match - case NNil => acc - case NCons(h, t) => revOnto(t, NCons(h, acc)) -def rev {r: Region} (xs: Nodes): Nodes - ensures result == revOnto(xs, NNil) -= - var out = NNil - var c = xs - while !isNil(c) do - invariant revOnto(c, out) == revOnto(xs, NNil) - decreases sizeS(c) - out = NCons(head(c), out) - c = tail(c) - out -def one {r: Region} (x: Node): Nodes = NCons(x, NNil) -def append {r: Region} (xs: Nodes, ys: Nodes): Nodes = - var out = ys - var c = rev(xs) - while !isNil(c) do - out = NCons(head(c), out) - c = tail(c) - out -def leaf {r: Region} (k: Kind, s: Str, line: I64): Node = Node(k, s, "", 0, line, NNil) - -def eqs(a: Str, b: Str): Bool = rt_str_eq(a, b) -// specs (Lean only): the texts of a node list, its size -spec def textS(x: Node): Str = x match - case Node(_, s, _, _, _, _) => s - case NoNode => "" -spec def memS(s: Str, xs: Nodes): Bool = xs match - case NNil => false - case NCons(h, t) => rt_str_eq(textS(h), s) || memS(s, t) -spec def sizeS(xs: Nodes): I64 - ensures result >= 0 - proof by induction xs -= xs match - case NNil => 0 - case NCons(_, t) => 1 + sizeS(t) - -def has(xs: Nodes, s: Str): Bool - ensures result == memS(s, xs) -= - var c = xs - var found = false - while !found && !isNil(c) do - invariant (found || memS(s, c)) == memS(s, xs) - decreases sizeS(c) - found = eqs(text(head(c)), s) - c = tail(c) - found -spec def text2S(x: Node): Str = x match - case Node(_, _, t, _, _, _) => t - case NoNode => "" -spec def numS(x: Node): I64 = x match - case Node(_, _, _, n, _, _) => n - case NoNode => 0 -spec def foundS(x: Node): Bool = x match - case NoNode => false - case _ => true -spec def nthS(xs: Nodes, i: I64): Node = xs match - case NNil => NoNode - case NCons(h, t) => if i <= 0 then h else nthS(t, i - 1) -spec def kidsS(x: Node): Nodes = x match - case Node(_, _, _, _, _, a) => a - case NoNode => NNil -spec def headS(xs: Nodes): Node = xs match - case NCons(h, _) => h - case NNil => NoNode -spec def tailS(xs: Nodes): Nodes = xs match - case NCons(_, t) => t - case NNil => NNil -spec def kindS(x: Node): Kind = x match - case Node(k, _, _, _, _, _) => k - case NoNode => TEof -spec def lookS(xs: Nodes, k: Kind, s: Str): Node = xs match - case NNil => NoNode - case NCons(h, t) => if kindS(h) == k && rt_str_eq(textS(h), s) then h else lookS(t, k, s) - -// first node of kind k with text s, or NoNode if absent -def find(xs: Nodes, k: Kind, s: Str): Node - ensures result == lookS(xs, k, s) -= - var c = xs - var res = NoNode - var found = false - while !found && !isNil(c) do - invariant lookS(xs, k, s) == (if found then res else lookS(c, k, s)) && (found || res == NoNode) - decreases sizeS(c) - val x = head(c) - if kind(x) == k && eqs(text(x), s) then - res = x - found = true - else () - c = tail(c) - res -def found(x: Node): Bool - ensures result == foundS(x) - proof by induction x -= x match - case NoNode => false - case _ => true -def index(xs: Nodes, s: Str): I64 = - var c = xs - var i = 0 - var res = -1 - while res < 0 && !isNil(c) do - if eqs(text(head(c)), s) then res = i else () - i = i + 1 - c = tail(c) - res - -def say(s: Str): Unit = rt_print(s) -def sayn(n: I64): Unit = rt_print_i64(n) -def fatal(msg: Str, line: I64): Unit = - rt_eprint("srs:") - rt_eprint_i64(line) - rt_eprint(": error: ") - rt_eprint(msg) - rt_eprint("\n") - rt_exit(1) - -// ── decls, indexed (vic-qf6, speed): the list, and a binary search tree on the name hash ── -// a bucket holds the decls of one hash in list order, so findDecl = find on the whole list (first match) -enum DMap: - case DTip - case DBin(h: I64, bucket: Nodes, l: DMap, rt: DMap) - -enum Decls: - case Decls(all: Nodes, idx: DMap, rec: DMap) - - -def dmGet(m: DMap, h: I64): Nodes = m match - case DTip => NNil - case DBin(k, b, l, rt) => if h == k then b else if h < k then dmGet(l, h) else dmGet(rt, h) - -// x in front of its bucket: x is now first in the list -def dmAdd {r: Region} (m: DMap, h: I64, x: Node): DMap = m match - case DTip => DBin(h, NCons(x, NNil), DTip, DTip) - case DBin(k, b, l, rt) => - if h == k then DBin(k, NCons(x, b), l, rt) else if h < k then DBin(k, b, dmAdd(l, h, x), rt) else DBin(k, b, l, dmAdd(rt, h, x)) - -def declList(ds: Decls): Nodes - ensures result == declsS(ds) - proof by induction ds -= ds match - case Decls(all, _, _) => all - -def findDecl(ds: Decls, k: Kind, s: Str): Node = ds match - case Decls(_, m, _) => find(dmGet(m, strHash(s)), k, s) - -// an enum's cases are in the index too (not in the list): findDecl(ds, DCase, c) -def declsCons {r: Region} (x: Node, ds: Decls): Decls = ds match - case Decls(all, m, rs) => Decls(NCons(x, all), if kind(x) == DEnum then dmAddAll(dmAdd(m, strHash(text(x)), x), kids(x)) else dmAdd(m, strHash(text(x)), x), rs) - -def dmAddAll {r: Region} (m: DMap, xs: Nodes): DMap = - var out = m - var c = rev(xs) - while !isNil(c) do - out = dmAdd(out, strHash(text(head(c))), head(c)) - c = tail(c) - out - -// xs in front of ds, in order -def declsPrepend {r: Region} (xs: Nodes, ds: Decls): Decls = - var out = ds - var c = rev(xs) - while !isNil(c) do - out = declsCons(head(c), out) - c = tail(c) - out - -def mkDecls {r: Region} (xs: Nodes): Decls = declsPrepend(xs, Decls(NNil, DTip, DTip)) - -// the decls as a list (the model of Decls in contracts: an index finds what lookS(declsS(ds), ...) finds) -spec def declsS(ds: Decls): Nodes = ds match - case Decls(all, _, _) => all - -// ds with the set of recursive fns (s1/lean.srs computes it once: Tarjan SCCs) -def withRec {r: Region} (ds: Decls, rs: DMap): Decls = ds match - case Decls(all, m, _) => Decls(all, m, rs) - -def isRec(ds: Decls, name: Str): Bool = ds match - case Decls(_, _, rs) => found(find(dmGet(rs, strHash(name)), Name, name)) diff --git a/bench/corpus/s1/parse.srs b/bench/corpus/s1/parse.srs deleted file mode 100644 index 3b934fb0..00000000 --- a/bench/corpus/s1/parse.srs +++ /dev/null @@ -1,593 +0,0 @@ -// S1 parser: tokens -> decl nodes. Grammar = s0/parse.zig. - -enum PR: - case PR(n: Node, rest: Nodes) - -def pn(p: PR): Node = p match - case PR(n, _) => n -def pr(p: PR): Nodes = p match - case PR(_, rest) => rest - -def isK(ts: Nodes, k: Kind): Bool = kind(head(ts)) == k -def isT(ts: Nodes, s: Str): Bool = - val k = kind(head(ts)) - (k == TOp || k == TIdent) && eqs(text(head(ts)), s) -def at(ts: Nodes): I64 = lineOf(head(ts)) - -def perr(ts: Nodes, what: Str): Unit = - rt_eprint("srs:") - rt_eprint_i64(at(ts)) - rt_eprint(": parse error: expected ") - rt_eprint(what) - rt_eprint(", got '") - rt_eprint(text(head(ts))) - rt_eprint("'\n") - rt_exit(1) - -def expect(ts: Nodes, s: Str): Nodes = - if isT(ts, s) then tail(ts) - else - perr(ts, s) - ts -def expectK(ts: Nodes, k: Kind, what: Str): Nodes = - if isK(ts, k) then tail(ts) - else - perr(ts, what) - ts -def needIdent(ts: Nodes): Str = - if isK(ts, TIdent) then text(head(ts)) - else - perr(ts, "identifier") - "" -def layoutOpen(ts: Nodes): Nodes = expectK(expectK(expect(ts, ":"), TNl, "newline"), TIndent, "indent") -def endLine(ts: Nodes): Nodes = if isK(ts, TDedent) then ts else expectK(ts, TNl, "newline") -def list {r: Region} (k: Kind, line: I64, xs: Nodes): Node = Node(k, "", "", 0, line, xs) - -def parseFile {r: Region} (toks: Nodes): Nodes = - var ts = toks - var out = NNil - while !isK(ts, TEof) do - if isK(ts, TNl) then ts = tail(ts) - else - val p = decl(ts) - out = NCons(pn(p), out) - ts = pr(p) - rev(out) - -def decl {r: Region} (ts: Nodes): PR = - if isT(ts, "extern") then fn(tail(ts), 1) - else if isT(ts, "def") then fn(ts, 0) - else if isT(ts, "spec") then fn(tail(ts), 2) - else if isT(ts, "enum") then enumDecl(tail(ts)) - else if isT(ts, "protocol") then protoDecl(tail(ts)) - else if isT(ts, "handler") then handlerDecl(tail(ts)) - else if isT(ts, "trait") then traitDecl(tail(ts)) - else if isT(ts, "type") then typeDecl(tail(ts)) - else if isT(ts, "given") then givenDecl(tail(ts)) - else - perr(ts, "declaration") - PR(NoNode, ts) - -// signature = telescope: binder groups (vic/c/binders-design.md) around the one `()` group; facts after the return type -def fn {r: Region} (ts0: Nodes, ext: I64): PR = - var ts = expect(ts0, "def") - val line = at(ts) - val name = needIdent(ts) - val g1 = groups(tail(ts), NNil) - val ps = params(pr(g1)) - val g2 = groups(pr(ps), kids(pn(g1))) - val rt = ty(expect(pr(g2), ":")) - val g3 = if isT(pr(rt), "<") then outFacts(pr(rt), kids(pn(g2))) else g2 - val gs = list(Groups, line, rev(kids(pn(g3)))) - val after = if isT(pr(rt), "<") then pr(g3) else pr(rt) - // spec defs are Lean only (vic 2026-11-05); externs take groups: a trusted contract of the C body - if ext == 2 && !isNil(kids(gs)) then fatal("binder groups on def and extern def only, not spec def", line) else () - if ext == 1 then PR(Node(DFn, name, "", 1, line, NCons(pn(ps), NCons(pn(rt), NCons(NoNode, NCons(list(Names, line, NNil), one(gs)))))), after) - else - // contract clauses, indented between the signature and `=` - val cl = if isK(after, TNl) && isK(tail(after), TIndent) then clauses(tail(after)) else PR(list(Names, line, NNil), after) - val b = rhs(expect(pr(cl), "=")) - PR(Node(DFn, name, "", ext, line, NCons(pn(ps), NCons(pn(rt), NCons(pn(b), NCons(pn(cl), one(gs)))))), pr(b)) - -// groups in written order, reversed onto acc: `[A: Type]` type ascriptions, `{s: Show[A]}` evidence, `` facts -def groups {r: Region} (ts0: Nodes, acc: Nodes): PR = - var ts = ts0 - var gs = acc - while isT(ts, "{") || isT(ts, "[") || isT(ts, "<") do - val g = group(ts, "") - gs = NCons(pn(g), gs) - ts = pr(g) - PR(list(Groups, at(ts0), gs), ts) - -// facts after the return type: what holds when the call returns -def outFacts {r: Region} (ts: Nodes, acc: Nodes): PR = - val g = group(ts, "out") - PR(list(Groups, at(ts), NCons(pn(g), acc)), pr(g)) - -def group {r: Region} (ts0: Nodes, out: Str): PR = - val line = at(ts0) - val open = text(head(ts0)) - val close = if eqs(open, "{") then "}" else if eqs(open, "[") then "]" else ">" - var ts = tail(ts0) - var xs = NNil - while !isT(ts, close) do - if eqs(open, "<") then - val a = tterm(ts, "(") - xs = NCons(pn(a), xs) - ts = pr(a) - else - val n = needIdent(ts) - val bl = at(ts) - val t = tterm(expect(tail(ts), ":"), "[") - xs = NCons(Node(Binder, n, "", 0, bl, one(pn(t))), xs) - ts = pr(t) - if !isT(ts, close) then ts = expect(ts, ",") else () - PR(Node(Group, open, out, 0, line, rev(xs)), tail(ts)) - -// T | T[args] | 3: a type (open = "[") or a Datalog atom p(args) (open = "(") -def tterm {r: Region} (ts0: Nodes, open: Str): PR = - val line = at(ts0) - if isK(ts0, TInt) then PR(Node(TTerm, text(head(ts0)), "", 1, line, NNil), tail(ts0)) - else - val f = needIdent(ts0) - var ts = tail(ts0) - var xs = NNil - val close = if eqs(open, "[") then "]" else ")" - if isT(ts, open) then - ts = tail(ts) - while !isT(ts, close) do - val a = tterm(ts, open) - xs = NCons(pn(a), xs) - ts = pr(a) - if !isT(ts, close) then ts = expect(ts, ",") else () - ts = tail(ts) - else () - PR(Node(TTerm, f, "", 0, line, rev(xs)), ts) - -def clauses {r: Region} (ts0: Nodes): PR = - var ts = expectK(ts0, TIndent, "indent") - var cs = NNil - while !isK(ts, TDedent) do - val p = clause(ts) - cs = NCons(pn(p), cs) - ts = endLine(pr(p)) - PR(list(Names, at(ts0), rev(cs)), tail(ts)) - -def isClause(ts: Nodes): Bool = - isT(ts, "requires") || isT(ts, "ensures") || isT(ts, "returns") || isT(ts, "decreases") || isT(ts, "invariant") || isT(ts, "proof") - -// requires e | ensures e | returns e | decreases e | invariant e | proof using a, b | proof by induction x | proof lean "tactics" -def clause {r: Region} (ts0: Nodes): PR = - val line = at(ts0) - val kw = text(head(ts0)) - if !isClause(ts0) then perr(ts0, "requires, ensures, returns, decreases, invariant or proof") else () - if eqs(kw, "proof") then - val ts = tail(ts0) - if isT(ts, "using") then - var t = tail(ts) - var xs = NNil - xs = NCons(leaf(Name, needIdent(t), line), xs) - t = tail(t) - while isT(t, ",") do - xs = NCons(leaf(Name, needIdent(tail(t)), line), xs) - t = drop(t, 2) - PR(Node(SClause, kw, "using", 0, line, rev(xs)), t) - else if isT(ts, "by") then - val t = expect(tail(ts), "induction") - PR(Node(SClause, kw, "by", 0, line, one(leaf(Name, needIdent(t), line))), tail(t)) - else - val t = expect(ts, "lean") - if !isK(t, TStr) then perr(t, "a string of Lean tactics") else () - PR(Node(SClause, kw, "lean", 0, line, one(leaf(XStr, text(head(t)), line))), tail(t)) - else - val e = expr(tail(ts0)) - PR(Node(SClause, kw, "", 0, line, one(pn(e))), pr(e)) - -def enumDecl {r: Region} (ts0: Nodes): PR = - val line = at(ts0) - val name = needIdent(ts0) - // `enum List [A: Type]:` [] binders; every case keeps them as its kid 1, so the case list stays the enum's kids - val g = groups(tail(ts0), NNil) - val gs = list(Groups, line, rev(kids(pn(g)))) - var ts = layoutOpen(pr(g)) - var cs = NNil - var tag = 0 - while !isK(ts, TDedent) do - ts = expect(ts, "case") - val cl = at(ts) - val cn = needIdent(ts) - ts = tail(ts) - var fs = list(Params, cl, NNil) - if isT(ts, "(") then - val p = params(ts) - fs = pn(p) - ts = pr(p) - else () - cs = NCons(Node(DCase, cn, name, tag, cl, NCons(fs, one(gs))), cs) - tag = tag + 1 - ts = endLine(ts) - PR(Node(DEnum, name, "", 0, line, rev(cs)), tail(ts)) - -def protoDecl {r: Region} (ts0: Nodes): PR = - val line = at(ts0) - val name = needIdent(ts0) - var ts = layoutOpen(tail(ts0)) - var states = NNil - var start = "" - var ends = NNil - var dropOp = "" - var ops = NNil - var rules = NNil - while !isK(ts, TDedent) do - if isT(ts, "state") then - val p = names(tail(ts)) - states = kids(pn(p)) - ts = pr(p) - else if isT(ts, "start") then - start = needIdent(tail(ts)) - ts = drop(ts, 2) - else if isT(ts, "end") then - val p = names(tail(ts)) - ends = kids(pn(p)) - ts = pr(p) - else if isT(ts, "drop") then - dropOp = needIdent(tail(ts)) - ts = drop(ts, 2) - else if isT(ts, "rule") then - val p = ruleDecl(expect(tail(ts), "def")) - rules = NCons(pn(p), rules) - ts = pr(p) - else if isT(ts, "op") then - val p = opDecl(tail(ts)) - ops = NCons(pn(p), ops) - ts = pr(p) - else perr(ts, "protocol item") - ts = endLine(ts) - val parts = NCons(list(Names, line, states), NCons(list(Names, line, ends), NCons(leaf(Name, dropOp, line), NCons(list(Names, line, rev(ops)), one(list(Names, line, rev(rules))))))) - PR(Node(DProto, name, start, 0, line, parts), tail(ts)) - -// rule def name(v1, v2) = atom, atom (in a protocol, vic 2026-11-05): a Datalog rule; DRule s = name, a = [Names params, atoms...] -def ruleDecl {r: Region} (ts0: Nodes): PR = - val line = at(ts0) - val name = needIdent(ts0) - var ts = expect(tail(ts0), "(") - var ps = NNil - while !isT(ts, ")") do - ps = NCons(leaf(Name, needIdent(ts), at(ts)), ps) - ts = tail(ts) - if !isT(ts, ")") then ts = expect(ts, ",") else () - ts = expect(tail(ts), "=") - var body = NNil - var more = true - while more do - val a = tterm(ts, "(") - body = NCons(pn(a), body) - ts = pr(a) - more = isT(ts, ",") - if more then ts = tail(ts) else () - PR(Node(DRule, name, "", 0, line, NCons(list(Names, line, rev(ps)), rev(body))), ts) - -def opDecl {r: Region} (ts0: Nodes): PR = - val line = at(ts0) - val name = needIdent(ts0) - val ps = params(tail(ts0)) - val rt = ty(expect(pr(ps), ":")) - var ts = expect(pr(rt), ":") - var tr = NNil - var more = true - while more do - val f = needIdent(ts) - ts = expect(expect(tail(ts), "-"), ">") - tr = NCons(Node(DTrans, f, needIdent(ts), 0, line, NNil), tr) - ts = tail(ts) - if isT(ts, ",") then ts = tail(ts) else more = false - PR(Node(DOp, name, "", 0, line, NCons(pn(ps), NCons(pn(rt), one(list(Names, line, rev(tr)))))), ts) - -def names {r: Region} (ts0: Nodes): PR = - var ts = ts0 - var xs = one(leaf(Name, needIdent(ts), at(ts))) - ts = tail(ts) - while isT(ts, ",") do - xs = NCons(leaf(Name, needIdent(tail(ts)), at(ts)), xs) - ts = drop(ts, 2) - PR(list(Names, at(ts0), rev(xs)), ts) - -// type F [A: Type] = T, or a match type: type F [A: Type] = A match / case P => T ... (vic S18 + telescopes, vic-9l7.9 BD6) -// DType s = name, n 1 = match, a = [Groups, body Ty (the scrutinee of a match), DTCase(a = [pattern, result])...] -def typeDecl {r: Region} (ts0: Nodes): PR = - val line = at(ts0) - val name = needIdent(ts0) - val g = groups(tail(ts0), NNil) - val gs = list(Groups, line, rev(kids(pn(g)))) - var ts = expect(pr(g), "=") - val b = ty(ts) - ts = pr(b) - if isT(ts, "match") then - ts = expectK(expectK(tail(ts), TNl, "newline"), TIndent, "indent") - var cs = NNil - while !isK(ts, TDedent) do - val cl = at(ts) - val p = ty(expect(ts, "case")) - val t = ty(expect(pr(p), "=>")) - cs = NCons(Node(DTCase, "", "", 0, cl, NCons(pn(p), one(pn(t)))), cs) - ts = endLine(pr(t)) - PR(Node(DType, name, "", 1, line, NCons(gs, NCons(pn(b), rev(cs)))), tail(ts)) - else PR(Node(DType, name, "", 0, line, NCons(gs, one(pn(b)))), ts) - -// trait Show [A: Type]: indented `def` signatures (no bodies) (vic-9l7.6 BD4a) -def traitDecl {r: Region} (ts0: Nodes): PR = - val line = at(ts0) - val name = needIdent(ts0) - val g = groups(tail(ts0), NNil) - var ts = layoutOpen(pr(g)) - var fs = NNil - while !isK(ts, TDedent) do - val p = fn(ts, 1) - fs = NCons(pn(p), fs) - ts = endLine(pr(p)) - PR(Node(DTrait, name, "", 0, line, NCons(list(Groups, line, rev(kids(pn(g)))), rev(fs))), tail(ts)) - -// given [A: Type] {s: Show[A]} Show[List[A]]: indented defs. a clause: its head holds when its {} evidence does. -// each def keeps the given's groups as its kid 4, so it is checked and instantiated as a generic def -def givenDecl {r: Region} (ts0: Nodes): PR = - val line = at(ts0) - val g = groups(ts0, NNil) - val gs = list(Groups, line, rev(kids(pn(g)))) - val hd = ty(pr(g)) - var ts = layoutOpen(pr(hd)) - var fs = NNil - while !isK(ts, TDedent) do - val p = fn(ts, 0) - val f = pn(p) - fs = NCons(withKids(f, NCons(kid(f, 0), NCons(kid(f, 1), NCons(kid(f, 2), NCons(kid(f, 3), one(gs)))))), fs) - ts = pr(p) - if isK(ts, TNl) then ts = tail(ts) else () - PR(Node(DGiven, text(pn(hd)), "", 0, line, NCons(gs, NCons(pn(hd), rev(fs)))), tail(ts)) - -def handlerDecl {r: Region} (ts0: Nodes): PR = - val line = at(ts0) - val name = needIdent(ts0) - var ts = expect(tail(ts0), "for") - val proto = needIdent(ts) - ts = layoutOpen(tail(ts)) - var fs = NNil - while !isK(ts, TDedent) do - val p = fn(ts, 0) - fs = NCons(pn(p), fs) - ts = pr(p) - if isK(ts, TNl) then ts = tail(ts) else () - PR(Node(DHandler, name, proto, 0, line, rev(fs)), tail(ts)) - -def params {r: Region} (ts0: Nodes): PR = - var ts = expect(ts0, "(") - var ps = NNil - while !isT(ts, ")") do - val n = needIdent(ts) - val pl = at(ts) - val t = ty(expect(tail(ts), ":")) - ps = NCons(Node(Param, n, "", 0, pl, one(pn(t))), ps) - ts = pr(t) - if !isT(ts, ")") then ts = expect(ts, ",") else () - PR(list(Params, at(ts0), rev(ps)), tail(ts)) - -def ty {r: Region} (ts0: Nodes): PR = - val line = at(ts0) - val name = needIdent(ts0) - var ts = tail(ts0) - // type application T[args] (vic 2026-11-05: [] = types, the Scala3 surface): the args are the kids of TyTo, so tyCaps stays the tail - var args = NNil - if isT(ts, "[") then - ts = tail(ts) - while !isT(ts, "]") do - val a = ty(ts) - args = NCons(pn(a), args) - ts = pr(a) - if !isT(ts, "]") then ts = expect(ts, ",") else () - ts = tail(ts) - else () - var caps = NNil - var annotated = 0 - // caps T^: the regions a value lives in are facts (vic 2026-11-05) - if isT(ts, "^") then - annotated = 1 - ts = expect(tail(ts), "<") - while !isT(ts, ">") do - caps = NCons(leaf(TyCap, needIdent(ts), line), caps) - ts = tail(ts) - if !isT(ts, ">") then ts = expect(ts, ",") else () - ts = tail(ts) - else () - PR(Node(Ty, name, "", annotated, line, NCons(Node(TyTo, "", "", 0, line, rev(args)), rev(caps))), ts) - -def rhs {r: Region} (ts: Nodes): PR = - if isK(ts, TNl) && isK(tail(ts), TIndent) then block(tail(ts)) else expr(ts) - -def block {r: Region} (ts0: Nodes): PR = - var ts = expectK(ts0, TIndent, "indent") - var ss = NNil - while !isK(ts, TDedent) do - val p = stmt(ts) - ss = NCons(pn(p), ss) - ts = pr(p) - if isK(ts, TNl) then ts = tail(ts) else () - PR(list(XBlock, at(ts0), rev(ss)), tail(ts)) - -def stmt {r: Region} (ts0: Nodes): PR = - val line = at(ts0) - if isT(ts0, "val") || isT(ts0, "var") then - val mut = if isT(ts0, "var") then 1 else 0 - val name = needIdent(tail(ts0)) - var ts = drop(ts0, 2) - var tyk = NNil - if isT(ts, ":") then - val t = ty(tail(ts)) - tyk = one(pn(t)) - ts = pr(t) - else () - val e = rhs(expect(ts, "=")) - PR(Node(SVal, name, "", mut, line, NCons(pn(e), tyk)), pr(e)) - else if isT(ts0, "invariant") || isT(ts0, "decreases") then clause(ts0) - else if isT(ts0, "handle") then - val name = needIdent(tail(ts0)) - val ts = expect(drop(ts0, 2), "=") - val a = args(tail(ts)) - PR(Node(SHandle, name, needIdent(ts), 0, line, kids(pn(a))), pr(a)) - else expr(ts0) - -// f[T1, T2]{a, b}(args): explicit type args, chosen evidence or capabilities (vic 2026-11-05) -def callGroups {r: Region} (ts0: Nodes): PR = - var ts = ts0 - var gs = NNil - while isT(ts, "[") || isT(ts, "{") do - val open = text(head(ts)) - val close = if eqs(open, "[") then "]" else "}" - val line = at(ts) - ts = tail(ts) - var xs = NNil - while !isT(ts, close) do - if eqs(open, "[") then - val t = ty(ts) - xs = NCons(pn(t), xs) - ts = pr(t) - else - xs = NCons(leaf(Name, needIdent(ts), at(ts)), xs) - ts = tail(ts) - if !isT(ts, close) then ts = expect(ts, ",") else () - gs = NCons(Node(Group, open, "", 0, line, rev(xs)), gs) - ts = tail(ts) - PR(list(Groups, at(ts0), rev(gs)), ts) - -def args {r: Region} (ts0: Nodes): PR = - var ts = expect(ts0, "(") - var xs = NNil - while !isT(ts, ")") do - val e = expr(ts) - xs = NCons(pn(e), xs) - ts = pr(e) - if !isT(ts, ")") then ts = expect(ts, ",") else () - PR(list(Names, at(ts0), rev(xs)), tail(ts)) - -def expr {r: Region} (ts0: Nodes): PR = - val line = at(ts0) - if isT(ts0, "if") then - val c = expr(tail(ts0)) - val t = rhs(expect(pr(c), "then")) - var ts = pr(t) - if isK(ts, TNl) && isT(tail(ts), "else") then ts = tail(ts) else () - val e = rhs(expect(ts, "else")) - PR(Node(XIf, "", "", 0, line, NCons(pn(c), NCons(pn(t), one(pn(e))))), pr(e)) - else if isT(ts0, "forall") || isT(ts0, "exists") then - val x = needIdent(tail(ts0)) - val t = ty(expect(drop(ts0, 2), ":")) - val b = expr(expect(pr(t), "=>")) - PR(Node(if isT(ts0, "forall") then XForall else XExists, x, "", 0, line, NCons(pn(t), one(pn(b)))), pr(b)) - else if isT(ts0, "while") then - val c = expr(tail(ts0)) - val b = rhs(expect(pr(c), "do")) - PR(Node(XWhile, "", "", 0, line, NCons(pn(c), one(pn(b)))), pr(b)) - else if isK(ts0, TIdent) && isK(tail(ts0), TOp) && eqs(text(head(tail(ts0))), "=") then - val e = rhs(drop(ts0, 2)) - PR(Node(XAssign, text(head(ts0)), "", 0, line, one(pn(e))), pr(e)) - else - val b = binary(ts0, 0) - if isT(pr(b), "match") then arms(pn(b), tail(pr(b))) else b - -def arms {r: Region} (scrut: Node, ts0: Nodes): PR = - var ts = expectK(expectK(ts0, TNl, "newline"), TIndent, "indent") - var xs = NNil - while !isK(ts, TDedent) do - val al = at(ts) - ts = expect(ts, "case") - var ctor = "_" - var binds = NNil - if isT(ts, "_") then ts = tail(ts) - else - ctor = needIdent(ts) - ts = tail(ts) - if isT(ts, "(") then - ts = tail(ts) - while !isT(ts, ")") do - binds = NCons(leaf(XName, needIdent(ts), al), binds) - ts = tail(ts) - if !isT(ts, ")") then ts = expect(ts, ",") else () - ts = tail(ts) - else () - val b = rhs(expect(ts, "=>")) - xs = NCons(Node(XArm, ctor, "", 0, al, NCons(pn(b), rev(binds))), xs) - ts = pr(b) - if isK(ts, TNl) then ts = tail(ts) else () - PR(Node(XMatch, "", "", 0, lineOf(scrut), NCons(scrut, rev(xs))), tail(ts)) - -def opLevel(s: Str): I64 = - if eqs(s, "||") then 0 else if eqs(s, "&&") then 1 - else if eqs(s, "==") || eqs(s, "!=") then 2 - else if eqs(s, "<") || eqs(s, "<=") || eqs(s, ">") || eqs(s, ">=") then 3 - else if eqs(s, "+") || eqs(s, "-") then 4 - else if eqs(s, "*") || eqs(s, "/") || eqs(s, "%") then 5 - else -1 - -def binary {r: Region} (ts0: Nodes, lvl: I64): PR = - if lvl == 6 then unary(ts0) - else - var p = binary(ts0, lvl + 1) - while isK(pr(p), TOp) && opLevel(text(head(pr(p)))) == lvl do - val op = head(pr(p)) - val q = binary(tail(pr(p)), lvl + 1) - p = PR(Node(XBin, text(op), "", 0, lineOf(op), NCons(pn(p), one(pn(q)))), pr(q)) - p - -def unary {r: Region} (ts: Nodes): PR = - if isT(ts, "-") || isT(ts, "!") then - val e = unary(tail(ts)) - PR(Node(XUn, text(head(ts)), "", 0, at(ts), one(pn(e))), pr(e)) - else primary(ts) - -def parseInt(s: Str): I64 = - var v = 0 - var i = 0 - while i < rt_str_len(s) do - v = v * 10 + rt_str_at(s, i) - '0' - i = i + 1 - v - -def charValue(ts: Nodes): I64 = - val s = text(head(ts)) - if rt_str_len(s) == 1 then rt_str_at(s, 0) - else - val c = rt_str_at(s, 1) - if c == 'n' then '\n' else if c == 't' then '\t' else if c == 'r' then '\r' else if c == '0' then 0 - else if c == '\\' || c == '\'' || c == '"' then c - else - perr(ts, "char escape") - 0 - -def primary {r: Region} (ts: Nodes): PR = - val t = head(ts) - val line = lineOf(t) - val k = kind(t) - if k == TInt then PR(Node(XInt, "", "", parseInt(text(t)), line, NNil), tail(ts)) - else if k == TStr then PR(leaf(XStr, text(t), line), tail(ts)) - else if k == TChar then PR(Node(XInt, "", "", charValue(ts), line, NNil), tail(ts)) - else if k == TIdent then - val s = text(t) - if eqs(s, "true") then PR(Node(XBool, "", "", 1, line, NNil), tail(ts)) - else if eqs(s, "false") then PR(Node(XBool, "", "", 0, line, NNil), tail(ts)) - else if isT(tail(ts), "(") then - val a = args(tail(ts)) - PR(Node(XCall, s, "", 0, line, kids(pn(a))), pr(a)) - else if isT(tail(ts), "[") || isT(tail(ts), "{") then - val g = callGroups(tail(ts)) - val a = args(pr(g)) - PR(Node(XCallG, s, "", 0, line, NCons(pn(g), kids(pn(a)))), pr(a)) - else if isT(tail(ts), ".") then - val a = args(drop(ts, 3)) - PR(Node(XMethod, s, needIdent(drop(ts, 2)), 0, line, kids(pn(a))), pr(a)) - else PR(leaf(XName, s, line), tail(ts)) - else if isT(ts, "(") then - if isT(tail(ts), ")") then PR(leaf(XUnit, "", line), drop(ts, 2)) - else - val e = expr(tail(ts)) - PR(pn(e), expect(pr(e), ")")) - else - perr(ts, "expression") - PR(NoNode, ts) diff --git a/bench/corpus/s1/purity.srs b/bench/corpus/s1/purity.srs deleted file mode 100644 index 4cec1b93..00000000 --- a/bench/corpus/s1/purity.srs +++ /dev/null @@ -1,95 +0,0 @@ -// vic-u2d U1b: which fns have effects (vic 2026-11-05: pure = no effects), a Datalog program over the source bodies. -// a protocol is effect-free when every fn of each of its handlers is pure (vic Q-U5: "from handler bodies.") - -def purAtom1 {r: Region} (rel: Str, a: I64): Atom = Atom(rel, ArgCons(AVar(a), ArgNil)) -def purAtom2 {r: Region} (rel: Str, a: I64, b: I64): Atom = Atom(rel, ArgCons(AVar(a), ArgCons(AVar(b), ArgNil))) -def purRule1 {r: Region} (h: Atom, b: Atom): Clause = Clause(h, LitCons(Pos(b), LitNil)) -def purRule2 {r: Region} (h: Atom, b1: Atom, b2: Atom): Clause = Clause(h, LitCons(Pos(b1), LitCons(Pos(b2), LitNil))) - -// impure(F) :- direct(F) | calls(F, G), impure(G) | uses(F, P), effectful(P) -// effectful(P) :- handles(H, P), impureH(H) -// impureH(H) :- hdirect(H) | hcalls(H, G), impure(G) | huses(H, P), effectful(P) -def purityRules {r: Region} (): Clauses = - var cs = ClCons(purRule1(purAtom1("impure", 0), purAtom1("direct", 0)), ClNil) - cs = ClCons(purRule2(purAtom1("impure", 0), purAtom1("impure", 1), purAtom2("calls", 0, 1)), cs) - cs = ClCons(purRule2(purAtom1("impure", 0), purAtom1("effectful", 1), purAtom2("uses", 0, 1)), cs) - cs = ClCons(purRule2(purAtom1("effectful", 0), purAtom1("impureH", 1), purAtom2("handles", 1, 0)), cs) - cs = ClCons(purRule1(purAtom1("impureH", 0), purAtom1("hdirect", 0)), cs) - cs = ClCons(purRule2(purAtom1("impureH", 0), purAtom1("impure", 1), purAtom2("hcalls", 0, 1)), cs) - ClCons(purRule2(purAtom1("impureH", 0), purAtom1("effectful", 1), purAtom2("huses", 0, 1)), cs) - -def purFact1 {r: Region} (rel: Str, a: Str, edb: Edb): Edb = EdbCons(Fact(rel, ValCons(VSym(a), ValNil)), edb) -def purFact2 {r: Region} (rel: Str, a: Str, b: Str, edb: Edb): Edb = EdbCons(Fact(rel, ValCons(VSym(a), ValCons(VSym(b), ValNil))), edb) - -// the binders of f's {} groups (kid 4) -def curlyBinders {r: Region} (f: Node): Nodes = - var out = NNil - var gs = kids(kid(f, 4)) - while !isNil(gs) do - if kind(head(gs)) == Group && eqs(text(head(gs)), "{") then out = append(kids(head(gs)), out) else () - gs = tail(gs) - out - -// the facts of expr x in fn who (hd: who is a handler): calls, handles, method calls on trait evidence ev -def bodyFacts {r: Region} (ds: Decls, hd: Bool, who: Str, ev: Nodes, x: Node, edb0: Edb): Edb = - val k = kind(x) - var edb = edb0 - if k == XCall || k == XCallG then edb = purFact2(if hd then "hcalls" else "calls", who, text(x), edb) else () - if k == SHandle then edb = purFact2(if hd then "huses" else "uses", who, text2(findDecl(ds, DHandler, text2(x))), edb) else () - // the given that answers trait evidence is not known before mono: a direct effect - if k == XMethod && has(ev, text(x)) then edb = purFact1(if hd then "hdirect" else "direct", who, edb) else () - var c = kids(x) - while !isNil(c) do - edb = bodyFacts(ds, hd, who, ev, head(c), edb) - c = tail(c) - edb - -// the facts of fn f, named who: an extern not in the pure set is a direct effect; a {} cap binder uses its protocol -def fnFacts {r: Region} (ds: Decls, hd: Bool, who: Str, f: Node, edb0: Edb): Edb = - var edb = edb0 - if num(f) == 1 && !isPureExtern(text(f)) then edb = purFact1("direct", who, edb) else () - var ev = NNil - var c = curlyBinders(f) - while !isNil(c) do - val p = text(kid(head(c), 0)) - if isProto(ds, p) then edb = purFact2(if hd then "huses" else "uses", who, p, edb) else ev = NCons(head(c), ev) - c = tail(c) - if num(f) == 1 then edb else bodyFacts(ds, hd, who, ev, kid(f, 2), edb) - -def purityFacts {r: Region} (ds: Decls): Edb = - var edb = EdbNil - var c = declList(ds) - while !isNil(c) do - val d = head(c) - if kind(d) == DFn then edb = fnFacts(ds, false, text(d), d, edb) else () - if kind(d) == DHandler then - edb = purFact2("handles", text(d), text2(d), edb) - var fs = kids(d) - while !isNil(fs) do - edb = fnFacts(ds, true, text(d), head(fs), edb) - fs = tail(fs) - else () - c = tail(c) - edb - -def impureOf {r: Region} (db: Facts): Nodes = db match - case FactNil => NNil - case FactCons(h, _, t) => h match - case Fact(rel, vs) => vs match - case ValCons(v, _) => if eqs(rel, "impure") then NCons(Node(Name, symOf(v), "", 0, 0, NNil), impureOf(t)) else impureOf(t) - case ValNil => impureOf(t) - -// the marker decl %impure (no srs name has a %): the fns with effects; check() prepends it to the decls it passes down -def impureDecl {r: Region} (ds: Decls): Node = evalDatalog(purityRules(), purityFacts(ds)) match - case Model(db) => Node(Names, "%impure", "", 0, 0, impureOf(db)) - case Unsafe(p) => - err("internal: unsafe purity rule", p, 0) - NoNode - case NegCycle(p) => - err("internal: negation in purity rules", p, 0) - NoNode - -def isImpure(ds: Decls, n: Str): Bool = - val m = findDecl(ds, Names, "%impure") - if !found(m) then err("internal: no purity facts for", n, 0) else () - has(kids(m), n) diff --git a/bench/corpus/s1/types.srs b/bench/corpus/s1/types.srs deleted file mode 100644 index a1dc43ad..00000000 --- a/bench/corpus/s1/types.srs +++ /dev/null @@ -1,135 +0,0 @@ -// Type telescopes and match types (vic S18 + telescopes; vic-9l7.9 BD6). type F [A: Type] = T: F[X] is T with A := X. -// a match type reduces by its first case whose pattern is the scrutinee (concrete patterns). Expansion runs before -// checking, over every Ty of the program; each reduction step costs fuel (as givens, vic Q-R4b): a loop is a reject. - -def typeFuel(): I64 = 1000 - -// the program with every type lambda applied and every match type reduced -def expandTypes {r: Region} (ds: Decls): Nodes = - var out = NNil - var c = declList(ds) - while !isNil(c) do - val d = head(c) - if kind(d) == DType then checkTypeDecl(ds, d) else () - // the evidence in scope of its types: a def's (or a given's) {} binders; a type's {} goals resolve against it - out = NCons(if kind(d) == DType then d else expandIn(ds, declEv(ds, d), d), out) - c = tail(c) - rev(out) - -// e with each Ty normalized -def expandIn {r: Region} (ds: Decls, env: Nodes, e: Node): Node = - if kind(e) == Ty then normTy(ds, env, e, typeFuel()) - else - var out = NNil - var c = kids(e) - while !isNil(c) do - out = NCons(expandIn(ds, env, head(c)), out) - c = tail(c) - withKids(e, rev(out)) - -// t with its args normalized and, if it names a type decl, applied (and its match reduced); the use keeps its caps -def normTy {r: Region} (ds: Decls, env: Nodes, t: Node, fuel: I64): Node = - if fuel <= 0 then errTy("type reduction ran out of fuel at", t, lineOf(t)) else () - var args = NNil - var c = tyArgs(t) - while !isNil(c) do - args = NCons(normTy(ds, env, head(c), fuel - 1), args) - c = tail(c) - val t1 = Node(Ty, text(t), text2(t), num(t), lineOf(t), NCons(Node(TyTo, tyTo(t), "", 0, 0, rev(args)), tyCaps(t))) - val d = findDecl(ds, DType, text(t)) - if !found(d) then t1 - else - val tps = groupBinders(kids(kid(d, 0))) - if len(tyArgs(t1)) != len(tps) then err("wrong number of type args for", text(t), lineOf(t)) else () - val sub = zipBind(tps, tyArgs(t1)) - // its {} evidence: resolved at this use (as a call's, local evidence first, vic-jxk) - goals(ds, env, kids(kid(d, 0)), sub, NNil, givenFuel(), lineOf(t)) - val body = applyTy(sub, kid(d, 1)) - val res = if num(d) == 1 then reduceMatch(ds, d, normTy(ds, env, body, fuel - 1), sub, lineOf(t)) else body - // its facts : the caps of the use's scope, each with its required state (vic-jxk) - withCaps(normTy(ds, env, res, fuel - 1), t, typeFacts(ds, env, d, lineOf(t))) - -// res at the use t: t's caps, annotation flag and line -def withCaps {r: Region} (res: Node, t: Node, facts: Nodes): Node = Node(Ty, text(res), text2(res), num(t), lineOf(t), NCons(head(kids(res)), append(facts, tyCaps(t)))) - -// the result of the first case of match type d whose pattern is s; s must be a concrete type -def reduceMatch {r: Region} (ds: Decls, d: Node, s: Node, sub: Nodes, line: I64): Node = - if !isBuiltin(text(s)) && !isEnum(ds, text(s)) && !isProto(ds, text(s)) then errTy("match type needs a concrete type, not", s, line) else () - var res = NoNode - var c = tail(tail(kids(d))) - while !found(res) && !isNil(c) do - if tyEq(applyTy(sub, kid(head(c), 0)), s) then res = applyTy(sub, kid(head(c), 1)) else () - c = tail(c) - if !found(res) then errTy("no case of the match type matches", s, line) else () - res - -// [A: Type] binders, {} evidence (a trait) or capabilities (a protocol), facts (vic-jxk); () values: not yet -def checkTypeDecl {r: Region} (ds0: Decls, d: Node): Unit = - val ds = declsPrepend(groupBinders(kids(kid(d, 0))), ds0) - var gs = kids(kid(d, 0)) - while !isNil(gs) do - val g = head(gs) - if !eqs(text(g), "[") && !eqs(text(g), "{") && !eqs(text(g), "<") then err("not yet: binder group on a type", text(g), lineOf(g)) else () - if eqs(text(g), "<") then needTypeFacts(ds, d, g) else () - var bs = kids(g) - while !isNil(bs) do - val k = kid(head(bs), 0) - if eqs(text(g), "[") then - if !eqs(text(k), "Type") || !isNil(kids(k)) then err("not yet: [] binder of kind", text(k), lineOf(head(bs))) else () - else if eqs(text(g), "<") || isProto(ds, text(k)) then () - else needTrait(ds, termTy(k)) - bs = tail(bs) - gs = tail(gs) - -// the {} evidence in scope of a decl's types: a def's (a given's def: the given's) {} binders -def declEv {r: Region} (ds: Decls, d: Node): Nodes = - if kind(d) == DFn then append(capEnv(ds, d), evEnv(ds, d)) - else if kind(d) == DGiven then groupsEv(ds, kids(kid(d, 0))) - else NNil - -// a def's {} capabilities as env entries (BVar n 2, t = protocol): the caps a fact type at a use can name -def capEnv {r: Region} (ds: Decls, d: Node): Nodes = - var out = NNil - var c = capParams(ds, d, NNil) - while !isNil(c) do - out = NCons(Node(BVar, text(head(c)), text(kid(head(c), 0)), 2, lineOf(head(c)), NNil), out) - c = tail(c) - out - -// the protocol of type decl d's {} binder n, or "" -def typeBinderProto(ds: Decls, d: Node, n: Str): Str = - var res = "" - var gs = kids(kid(d, 0)) - while !isNil(gs) do - if kind(head(gs)) == Group && eqs(text(head(gs)), "{") then - val b = find(kids(head(gs)), Binder, n) - if found(b) && isProto(ds, text(kid(b, 0))) then res = text(kid(b, 0)) else () - else () - gs = tail(gs) - res - -// a type's facts: at(cap, State), cap a {} capability of the type, State a state of its protocol (no variables yet) -def needTypeFacts {r: Region} (ds: Decls, d: Node, g: Node): Unit = - var c = kids(g) - while !isNil(c) do - val a = head(c) - if !eqs(text(a), "at") || len(kids(a)) != 2 then err("not yet: fact on a type", text(a), lineOf(a)) else () - val p = typeBinderProto(ds, d, text(kid(a, 0))) - if rt_str_len(p) == 0 then err("at: not a {} capability of this type:", text(kid(a, 0)), lineOf(a)) else () - if !has(protoStates(declList(ds), p), text(kid(a, 1))) then err("unknown protocol state in", p, lineOf(a)) else () - c = tail(c) - -// the facts of type decl d at a use: each at(b, S) as the use scope's one cap of b's protocol, required in state S -def typeFacts {r: Region} (ds: Decls, env: Nodes, d: Node, line: I64): Nodes = - var out = NNil - var gs = kids(kid(d, 0)) - while !isNil(gs) do - if kind(head(gs)) == Group && eqs(text(head(gs)), "<") then - var c = kids(head(gs)) - while !isNil(c) do - val cap = theCap(env, typeBinderProto(ds, d, text(kid(head(c), 0))), line) - out = NCons(Node(TyCap, cap, text(kid(head(c), 1)), 0, line, NNil), out) - c = tail(c) - else () - gs = tail(gs) - out diff --git a/bench/corpus/s2/ast.srs b/bench/corpus/s2/ast.srs new file mode 100644 index 00000000..7abfd3a0 --- /dev/null +++ b/bench/corpus/s2/ast.srs @@ -0,0 +1,819 @@ +// s2 P1 (vic-m5r.23, vic/c/ast-design.md): the typed AST. one case per shape, named fields, so a wrong shape does not +// compile; an AST may still hold an invalid program (unknown name, bad state): the checker finds those as data. +// every node keeps its source line. Ast.print writes it back as srs source (the oracle of P1, and of the parser later). + +enum Ast.BinOp: + case Ast.Add + case Ast.Sub + case Ast.Mul + case Ast.Div + case Ast.Mod + case Ast.Lt + case Ast.Le + case Ast.Gt + case Ast.Ge + case Ast.Eq + case Ast.Ne + case Ast.And + case Ast.Or + +enum Ast.UnOp: + case Ast.Neg + case Ast.Not + +// T[args]^: no caps written = inferred; written = a bound +enum Ast.Caps: + case Ast.Inferred + case Ast.Stated(cs: Coll.List[Sym.Sym]) + +enum Ast.Ty: + case Ast.Ty(line: I64, name: Sym.Sym, args: Coll.List[Ast.Ty], caps: Ast.Caps, vals: Coll.List[Ast.Expr]) + +enum Ast.Q: + case Ast.Forall + case Ast.Exists + +enum Ast.LoopCond: + case Ast.LInvariant + case Ast.LDecreases + +enum Ast.Expr: + case Ast.Int(line: I64, v: I64) + case Ast.Bool(line: I64, v: Bool) + // s = the text between the quotes, escapes as written + case Ast.Str(line: I64, s: Str) + case Ast.Unit(line: I64) + case Ast.Name(line: I64, n: Sym.Sym) + // f[T]{a}(x): types and chosen evidence are empty lists when not written + case Ast.Call(line: I64, f: Sym.Sym, targs: Coll.List[Ast.Ty], chosen: Coll.List[Sym.Sym], args: Coll.List[Ast.Expr]) + // d.knock(): an op on a capability, or a method on {} evidence (the checker tells which) + case Ast.Method(line: I64, recv: Sym.Sym, op: Sym.Sym, args: Coll.List[Ast.Expr]) + case Ast.Bin(line: I64, op: Ast.BinOp, l: Ast.Expr, rhs: Ast.Expr) + case Ast.Un(line: I64, op: Ast.UnOp, e: Ast.Expr) + case Ast.If(line: I64, c: Ast.Expr, t: Ast.Expr, e: Ast.Expr) + case Ast.Match(line: I64, s: Ast.Expr, arms: Coll.List[Ast.Arm]) + // a block always has a value: after a last val or handle it is Ast.Unit + case Ast.Block(line: I64, stmts: Coll.List[Ast.Stmt], last: Ast.Expr) + case Ast.While(line: I64, c: Ast.Expr, body: Ast.Expr) + case Ast.Assign(line: I64, x: Sym.Sym, e: Ast.Expr) + // forall x: T => e, exists x: T => e (contracts only) + case Ast.Quant(line: I64, q: Ast.Q, x: Sym.Sym, t: Ast.Ty, e: Ast.Expr) + +enum Ast.Pat: + case Ast.PCase(c: Sym.Sym, binds: Coll.List[Sym.Sym]) + case Ast.PAny + +enum Ast.Arm: + case Ast.Arm(line: I64, p: Ast.Pat, body: Ast.Expr) + +enum Ast.Stmt: + case Ast.Val(line: I64, x: Sym.Sym, ann: Coll.Option[Ast.Ty], e: Ast.Expr) + case Ast.Var(line: I64, x: Sym.Sym, ann: Coll.Option[Ast.Ty], e: Ast.Expr) + case Ast.Handle(line: I64, x: Sym.Sym, h: Sym.Sym, args: Coll.List[Ast.Expr]) + case Ast.Do(e: Ast.Expr) + // a loop invariant or measure in a block (s1/parse.srs:494) + case Ast.Check(line: I64, k: Ast.LoopCond, e: Ast.Expr) + +// <> atoms. a name is a variable or a constant by its position (s1/facts.srs:1-3: lowercase in a state position is a +// variable, but `knock` in next(s, knock, s2) is an op): the checker decides, not the parser +enum Ast.Term: + case Ast.TName(n: Sym.Sym) + case Ast.TNum(v: I64) + +enum Ast.Atom: + case Ast.Atom(line: I64, rel: Sym.Sym, args: Coll.List[Ast.Term]) + +enum Ast.Binder: + case Ast.Binder(line: I64, x: Sym.Sym, ty: Ast.Ty) + +// binder groups in written order (vic/c/binders-design.md); the exit facts are a field of the fn +enum Ast.Group: + case Ast.Types(bs: Coll.List[Ast.Binder]) + case Ast.Evidence(bs: Coll.List[Ast.Binder]) + case Ast.Facts(atoms: Coll.List[Ast.Atom]) + +// a contract clause between a signature and its body (C13, s1/parse.srs:147-184), erased in C +enum Ast.Cond: + case Ast.Requires + case Ast.Ensures + case Ast.Returns + case Ast.Decreases + case Ast.Invariant + +enum Ast.Clause: + case Ast.CondC(line: I64, k: Ast.Cond, e: Ast.Expr) + case Ast.ProofUsing(line: I64, xs: Coll.List[Sym.Sym]) + case Ast.ProofInduction(line: I64, x: Sym.Sym) + case Ast.ProofLean(line: I64, s: Str) + +enum Ast.Body: + case Ast.Def(cs: Coll.List[Ast.Clause], e: Ast.Expr) + case Ast.Extern + // a spec def: a compile-time body, no binder groups (vic 2026-11-05), no Region + case Ast.Spec(cs: Coll.List[Ast.Clause], e: Ast.Expr) + +enum Ast.Fn: + case Ast.Fn(line: I64, name: Sym.Sym, groups: Coll.List[Ast.Group], params: Coll.List[Ast.Binder], ret: Ast.Ty, exit: Coll.List[Ast.Atom], body: Ast.Body) + +enum Ast.Trans: + case Ast.Trans(from: Sym.Sym, to: Sym.Sym) + +enum Ast.Op: + case Ast.Op(line: I64, name: Sym.Sym, params: Coll.List[Ast.Binder], ret: Ast.Ty, trans: Coll.List[Ast.Trans]) + +enum Ast.RuleDef: + case Ast.RuleDef(line: I64, name: Sym.Sym, params: Coll.List[Sym.Sym], body: Coll.List[Ast.Atom]) + +enum Ast.Proto: + case Ast.Proto(line: I64, name: Sym.Sym, states: Coll.List[Sym.Sym], start: Sym.Sym, ends: Coll.List[Sym.Sym], dropOp: Coll.Option[Sym.Sym], ops: Coll.List[Ast.Op], rules: Coll.List[Ast.RuleDef]) + +enum Ast.Handler: + case Ast.Handler(line: I64, name: Sym.Sym, proto: Sym.Sym, fns: Coll.List[Ast.Fn]) + +enum Ast.Case: + case Ast.Case(line: I64, name: Sym.Sym, fields: Coll.List[Ast.Binder]) + +enum Ast.Enum: + case Ast.Enum(line: I64, name: Sym.Sym, groups: Coll.List[Ast.Group], cases: Coll.List[Ast.Case]) + +// trait Name groups: its method signatures (no body) +enum Ast.Trait: + case Ast.Trait(line: I64, name: Sym.Sym, groups: Coll.List[Ast.Group], sigs: Coll.List[Ast.Fn]) + +// given groups Head[args]: the methods of the trait Head for those args +enum Ast.Given: + case Ast.Given(line: I64, groups: Coll.List[Ast.Group], head: Ast.Ty, fns: Coll.List[Ast.Fn]) + +// a value pattern of a type value match: an int, a string, true or false, or _ +enum Ast.VPat: + case Ast.VInt(v: I64) + case Ast.VStr(s: Str) + case Ast.VBool(v: Bool) + case Ast.VAny + +enum Ast.TyArm: + case Ast.TyArm(line: I64, pat: Ast.Ty, res: Ast.Ty) + +enum Ast.ValArm: + case Ast.ValArm(line: I64, pat: Ast.VPat, res: Ast.Ty) + +// the body of a type decl: a type, a match on a type, a match on a value binder +enum Ast.TBody: + case Ast.Alias(t: Ast.Ty) + case Ast.TyMatch(scrut: Ast.Ty, arms: Coll.List[Ast.TyArm]) + case Ast.ValMatch(x: Sym.Sym, arms: Coll.List[Ast.ValArm]) + +// type Name groups (value binders) = body +enum Ast.TypeDecl: + case Ast.TypeDecl(line: I64, name: Sym.Sym, groups: Coll.List[Ast.Group], vals: Coll.List[Ast.Binder], body: Ast.TBody) + +enum Ast.Decl: + case Ast.DFn(f: Ast.Fn) + case Ast.DEnum(e: Ast.Enum) + case Ast.DProto(p: Ast.Proto) + case Ast.DHandler(h: Ast.Handler) + case Ast.DTrait(t: Ast.Trait) + case Ast.DGiven(g: Ast.Given) + case Ast.DType(t: Ast.TypeDecl) + +// ── printer: srs source, Ast.step() spaces per level ── +def Ast.step(): I64 = 2 + +def Ast.sym(s: Sym.Sym): Unit = rt_print(Sym.str(s)) + +def Ast.indent(n: I64): Unit = + if n > 0 then + rt_print(" ") + Ast.indent(n - 1) + else () + +def Ast.line(ind: I64): Unit = + rt_print("\n") + Ast.indent(ind) + +// names separated by sep +def Ast.syms(xs: Coll.List[Sym.Sym], sep: Str): Unit = xs match + case Coll.Nil => () + case Coll.Cons(h, t) => + Ast.sym(h) + t match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print(sep) + Ast.syms(t, sep) + +def Ast.tys {r: Region} (xs: Coll.List[Ast.Ty]): Unit = xs match + case Coll.Nil => () + case Coll.Cons(h, t) => + Ast.ty(h) + t match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print(", ") + Ast.tys(t) + +def Ast.ty {r: Region} (t: Ast.Ty): Unit = + val Ast.Ty(_, n, args, caps, vals) = t + Ast.sym(n) + args match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print("[") + Ast.tys(args) + rt_print("]") + vals match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print("(") + Ast.args(vals, 0) + rt_print(")") + caps match + case Ast.Inferred => () + case Ast.Stated(cs) => + rt_print("^<") + Ast.syms(cs, ", ") + rt_print(">") + +def Ast.opText(op: Ast.BinOp): Str = op match + case Ast.Add => "+" + case Ast.Sub => "-" + case Ast.Mul => "*" + case Ast.Div => "/" + case Ast.Mod => "%" + case Ast.Lt => "<" + case Ast.Le => "<=" + case Ast.Gt => ">" + case Ast.Ge => ">=" + case Ast.Eq => "==" + case Ast.Ne => "!=" + case Ast.And => "&&" + case Ast.Or => "||" + +// how tightly an expression binds as an operand, loosest first: if, match, block, while and assign only in ( ); a +// binary operator by its level; a unary operator; an atom (literal, name, call, method) +enum Ast.Bind: + case Ast.Loose + case Ast.Infix(op: Ast.BinOp) + case Ast.Prefix + case Ast.Atomic + +// an operand position: it takes an expression that binds at least as tightly as b, or strictly more tightly +// (the right operand of a left associative operator) +enum Ast.Need: + case Ast.AtLeast(b: Ast.Bind) + case Ast.Above(b: Ast.Bind) + +// the order of Bind, loosest first; binary levels as the s1 parser (s1/parse.srs:593 opLevel). only compared +def Ast.rank(b: Ast.Bind): I64 = b match + case Ast.Loose => 0 + case Ast.Infix(op) => op match + case Ast.Or => 1 + case Ast.And => 2 + case Ast.Eq => 3 + case Ast.Ne => 3 + case Ast.Lt => 4 + case Ast.Le => 4 + case Ast.Gt => 4 + case Ast.Ge => 4 + case Ast.Add => 5 + case Ast.Sub => 5 + case Ast.Mul => 6 + case Ast.Div => 6 + case Ast.Mod => 6 + case Ast.Prefix => 7 + case Ast.Atomic => 8 + +def Ast.bindOf {r: Region} (e: Ast.Expr): Ast.Bind = e match + case Ast.Bin(_, op, _, _) => Ast.Infix(op) + case Ast.Un(_, _, _) => Ast.Prefix + case Ast.If(_, _, _, _) => Ast.Loose + case Ast.Match(_, _, _) => Ast.Loose + case Ast.Block(_, _, _) => Ast.Loose + case Ast.While(_, _, _) => Ast.Loose + case Ast.Assign(_, _, _) => Ast.Loose + case Ast.Quant(_, _, _, _, _) => Ast.Loose + case _ => Ast.Atomic + +def Ast.fits {r: Region} (e: Ast.Expr, n: Ast.Need): Bool = n match + case Ast.AtLeast(b) => Ast.rank(Ast.bindOf(e)) >= Ast.rank(b) + case Ast.Above(b) => Ast.rank(Ast.bindOf(e)) > Ast.rank(b) + +// e in an operand position: in ( ) when it does not fit +def Ast.operand {r: Region} (e: Ast.Expr, n: Ast.Need, ind: I64): Unit = + if Ast.fits(e, n) then Ast.expr(e, ind) + else + rt_print("(") + Ast.expr(e, ind) + rt_print(")") + +def Ast.args {r: Region} (xs: Coll.List[Ast.Expr], ind: I64): Unit = xs match + case Coll.Nil => () + case Coll.Cons(h, t) => + Ast.expr(h, ind) + t match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print(", ") + Ast.args(t, ind) + +// e after `=`, `then`, `else`, `do` or `=>`: a block on its own lines one level in, anything else on this line +def Ast.body {r: Region} (e: Ast.Expr, ind: I64): Unit = e match + case Ast.Block(_, ss, last) => + Ast.stmts(ss, ind + Ast.step()) + Ast.line(ind + Ast.step()) + Ast.expr(last, ind + Ast.step()) + case _ => + rt_print(" ") + Ast.expr(e, ind) + +def Ast.expr {r: Region} (e: Ast.Expr, ind: I64): Unit = e match + case Ast.Int(_, v) => rt_print_i64(v) + case Ast.Bool(_, v) => rt_print(if v then "true" else "false") + case Ast.Str(_, s) => + rt_print("\"") + rt_print(s) + rt_print("\"") + case Ast.Unit(_) => rt_print("()") + case Ast.Name(_, n) => Ast.sym(n) + case Ast.Call(_, f, targs, chosen, xs) => + Ast.sym(f) + targs match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print("[") + Ast.tys(targs) + rt_print("]") + chosen match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print("{") + Ast.syms(chosen, ", ") + rt_print("}") + rt_print("(") + Ast.args(xs, ind) + rt_print(")") + case Ast.Method(_, recv, op, xs) => + Ast.sym(recv) + rt_print(".") + Ast.sym(op) + rt_print("(") + Ast.args(xs, ind) + rt_print(")") + case Ast.Bin(_, op, l, rhs) => + Ast.operand(l, Ast.AtLeast(Ast.Infix(op)), ind) + rt_print(" ") + rt_print(Ast.opText(op)) + rt_print(" ") + Ast.operand(rhs, Ast.Above(Ast.Infix(op)), ind) + case Ast.Un(_, op, x) => + rt_print(Ast.unText(op)) + Ast.operand(x, Ast.AtLeast(Ast.Prefix), ind) + case Ast.If(_, c, t, x) => + rt_print("if ") + Ast.expr(c, ind) + rt_print(" then") + Ast.body(t, ind) + Ast.elseBody(t, x, ind) + case Ast.Match(_, s, arms) => + Ast.operand(s, Ast.AtLeast(Ast.Atomic), ind) + rt_print(" match") + Ast.arms(arms, ind + Ast.step()) + case Ast.Block(_, ss, last) => + Ast.stmts(ss, ind) + Ast.line(ind) + Ast.expr(last, ind) + case Ast.While(_, c, b) => + rt_print("while ") + Ast.expr(c, ind) + // a match condition ends with its arms: do starts the next line (as tests/s2/prog/contracts.srs) + c match + case Ast.Match(_, _, _) => + Ast.line(ind) + rt_print("do") + case _ => rt_print(" do") + Ast.body(b, ind) + case Ast.Quant(_, q, x, t, b) => + rt_print(Ast.qText(q)) + rt_print(" ") + Ast.sym(x) + rt_print(": ") + Ast.ty(t) + rt_print(" => ") + Ast.expr(b, ind) + case Ast.Assign(_, x, v) => + Ast.sym(x) + rt_print(" = ") + Ast.expr(v, ind) + +def Ast.unText(op: Ast.UnOp): Str = op match + case Ast.Neg => "-" + case Ast.Not => "!" + +// `else` on the line of a one-line then, on its own line after a block then +// else starts a new line when either branch takes more than one line (a block, a match, a multi-line if or while): +// after one, a same-line else would read as part of its last line +def Ast.elseBody {r: Region} (t: Ast.Expr, x: Ast.Expr, ind: I64): Unit = + if Ast.multiLine(t) || Ast.multiLine(x) then + Ast.line(ind) + rt_print("else") + Ast.body(x, ind) + else + rt_print(" else") + Ast.body(x, ind) + +def Ast.multiLine(e: Ast.Expr): Bool = e match + case Ast.Block(_, _, _) => true + case Ast.Match(_, _, _) => true + case Ast.While(_, _, _) => true + case Ast.If(_, _, t, x) => Ast.multiLine(t) || Ast.multiLine(x) + case _ => false + +def Ast.arms {r: Region} (xs: Coll.List[Ast.Arm], ind: I64): Unit = xs match + case Coll.Nil => () + case Coll.Cons(a, t) => + val Ast.Arm(_, p, b) = a + Ast.line(ind) + rt_print("case ") + Ast.pat(p) + rt_print(" =>") + Ast.body(b, ind) + Ast.arms(t, ind) + +def Ast.pat(p: Ast.Pat): Unit = p match + case Ast.PAny => rt_print("_") + case Ast.PCase(c, bs) => + Ast.sym(c) + bs match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print("(") + Ast.syms(bs, ", ") + rt_print(")") + +// each statement on its own line at ind +def Ast.stmts {r: Region} (xs: Coll.List[Ast.Stmt], ind: I64): Unit = xs match + case Coll.Nil => () + case Coll.Cons(s, t) => + Ast.line(ind) + Ast.stmt(s, ind) + Ast.stmts(t, ind) + +def Ast.stmt {r: Region} (s: Ast.Stmt, ind: I64): Unit = s match + case Ast.Val(_, x, ann, e) => + rt_print("val ") + Ast.binding(x, ann, e, ind) + case Ast.Var(_, x, ann, e) => + rt_print("var ") + Ast.binding(x, ann, e, ind) + case Ast.Handle(_, x, h, xs) => + rt_print("handle ") + Ast.sym(x) + rt_print(" = ") + Ast.sym(h) + rt_print("(") + Ast.args(xs, ind) + rt_print(")") + case Ast.Do(e) => Ast.expr(e, ind) + case Ast.Check(_, k, e) => + rt_print(Ast.loopText(k)) + rt_print(" ") + Ast.expr(e, ind) + +def Ast.qText(q: Ast.Q): Str = q match + case Ast.Forall => "forall" + case Ast.Exists => "exists" + +def Ast.loopText(k: Ast.LoopCond): Str = k match + case Ast.LInvariant => "invariant" + case Ast.LDecreases => "decreases" + +def Ast.binding {r: Region} (x: Sym.Sym, ann: Coll.Option[Ast.Ty], e: Ast.Expr, ind: I64): Unit = + Ast.sym(x) + ann match + case Coll.None => () + case Coll.Some(t) => + rt_print(": ") + Ast.ty(t) + rt_print(" =") + Ast.body(e, ind) + +def Ast.term(t: Ast.Term): Unit = t match + case Ast.TName(n) => Ast.sym(n) + case Ast.TNum(v) => rt_print_i64(v) + +def Ast.terms(xs: Coll.List[Ast.Term]): Unit = xs match + case Coll.Nil => () + case Coll.Cons(h, t) => + Ast.term(h) + t match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print(", ") + Ast.terms(t) + +def Ast.atoms(xs: Coll.List[Ast.Atom]): Unit = xs match + case Coll.Nil => () + case Coll.Cons(a, t) => + val Ast.Atom(_, rel, ts) = a + Ast.sym(rel) + rt_print("(") + Ast.terms(ts) + rt_print(")") + t match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print(", ") + Ast.atoms(t) + +def Ast.binders {r: Region} (xs: Coll.List[Ast.Binder]): Unit = xs match + case Coll.Nil => () + case Coll.Cons(b, t) => + val Ast.Binder(_, x, ty) = b + Ast.sym(x) + rt_print(": ") + Ast.ty(ty) + t match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print(", ") + Ast.binders(t) + +// each group followed by a space: ` [A: Type] {s: Show[A]} ` +def Ast.groups {r: Region} (xs: Coll.List[Ast.Group]): Unit = xs match + case Coll.Nil => () + case Coll.Cons(g, t) => + rt_print(" ") + g match + case Ast.Types(bs) => + rt_print("[") + Ast.binders(bs) + rt_print("]") + case Ast.Evidence(bs) => + rt_print("{") + Ast.binders(bs) + rt_print("}") + case Ast.Facts(ats) => + rt_print("<") + Ast.atoms(ats) + rt_print(">") + Ast.groups(t) + +def Ast.fn {r: Region} (f: Ast.Fn, ind: I64): Unit = + val Ast.Fn(_, _, _, _, _, _, body) = f + body match + case Ast.Extern => rt_print("extern ") + case Ast.Spec(_, _) => rt_print("spec ") + case Ast.Def(_, _) => () + Ast.fnSig(f, ind) + +// a trait method signature: a def without body and without extern +def Ast.sigs {r: Region} (xs: Coll.List[Ast.Fn], ind: I64): Unit = xs match + case Coll.Nil => () + case Coll.Cons(f, t) => + Ast.line(ind) + Ast.fnSig(f, ind) + Ast.sigs(t, ind) + +// def name groups (params): ty [= body] +def Ast.fnSig {r: Region} (f: Ast.Fn, ind: I64): Unit = + val Ast.Fn(_, name, gs, ps, ret, exit, body) = f + rt_print("def ") + Ast.sym(name) + Ast.groups(gs) + gs match + case Coll.Nil => () + case Coll.Cons(_, _) => rt_print(" ") + rt_print("(") + Ast.binders(ps) + rt_print("): ") + Ast.ty(ret) + exit match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print(" <") + Ast.atoms(exit) + rt_print(">") + body match + case Ast.Extern => () + case Ast.Def(cs, e) => Ast.withClauses(cs, e, ind) + case Ast.Spec(cs, e) => Ast.withClauses(cs, e, ind) + +// = body; with clauses: each on its own line one step in, then = at the start of a line (as tests/s2/prog/contracts.srs) +def Ast.withClauses {r: Region} (cs: Coll.List[Ast.Clause], e: Ast.Expr, ind: I64): Unit = cs match + case Coll.Nil => + rt_print(" =") + Ast.body(e, ind) + case Coll.Cons(_, _) => + Ast.clauses(cs, ind + Ast.step()) + Ast.line(ind) + rt_print("=") + Ast.body(e, ind) + +def Ast.condText(k: Ast.Cond): Str = k match + case Ast.Requires => "requires" + case Ast.Ensures => "ensures" + case Ast.Returns => "returns" + case Ast.Decreases => "decreases" + case Ast.Invariant => "invariant" + +def Ast.clauses {r: Region} (cs: Coll.List[Ast.Clause], ind: I64): Unit = cs match + case Coll.Nil => () + case Coll.Cons(c, rest) => + Ast.line(ind) + c match + case Ast.CondC(_, k, x) => + rt_print(Ast.condText(k)) + rt_print(" ") + Ast.expr(x, ind) + case Ast.ProofUsing(_, xs) => + rt_print("proof using ") + Ast.syms(xs, ", ") + case Ast.ProofInduction(_, x) => + rt_print("proof by induction ") + Ast.sym(x) + case Ast.ProofLean(_, s) => + rt_print("proof lean \"") + rt_print(s) + rt_print("\"") + Ast.clauses(rest, ind) + +def Ast.fns {r: Region} (xs: Coll.List[Ast.Fn], ind: I64): Unit = xs match + case Coll.Nil => () + case Coll.Cons(f, t) => + Ast.line(ind) + Ast.fn(f, ind) + Ast.fns(t, ind) + +def Ast.trans(xs: Coll.List[Ast.Trans]): Unit = xs match + case Coll.Nil => () + case Coll.Cons(tr, t) => + val Ast.Trans(a, b) = tr + Ast.sym(a) + rt_print(" -> ") + Ast.sym(b) + t match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print(", ") + Ast.trans(t) + +def Ast.ops {r: Region} (xs: Coll.List[Ast.Op]): Unit = xs match + case Coll.Nil => () + case Coll.Cons(o, t) => + val Ast.Op(_, name, ps, ret, trs) = o + Ast.line(Ast.step()) + rt_print("op ") + Ast.sym(name) + rt_print("(") + Ast.binders(ps) + rt_print("): ") + Ast.ty(ret) + rt_print(" : ") + Ast.trans(trs) + Ast.ops(t) + +def Ast.rules(xs: Coll.List[Ast.RuleDef]): Unit = xs match + case Coll.Nil => () + case Coll.Cons(rl, t) => + val Ast.RuleDef(_, name, ps, body) = rl + Ast.line(Ast.step()) + rt_print("rule def ") + Ast.sym(name) + rt_print("(") + Ast.syms(ps, ", ") + rt_print(") = ") + Ast.atoms(body) + Ast.rules(t) + +def Ast.cases {r: Region} (xs: Coll.List[Ast.Case]): Unit = xs match + case Coll.Nil => () + case Coll.Cons(c, t) => + val Ast.Case(_, name, fs) = c + Ast.line(Ast.step()) + rt_print("case ") + Ast.sym(name) + fs match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print("(") + Ast.binders(fs) + rt_print(")") + Ast.cases(t) + +def Ast.decl {r: Region} (d: Ast.Decl): Unit = d match + case Ast.DFn(f) => Ast.fn(f, 0) + case Ast.DEnum(en) => + val Ast.Enum(_, name, gs, cs) = en + rt_print("enum ") + Ast.sym(name) + Ast.groups(gs) + rt_print(":") + Ast.cases(cs) + case Ast.DProto(p) => + val Ast.Proto(_, name, sts, start, ends, dropOp, ops, rules) = p + rt_print("protocol ") + Ast.sym(name) + rt_print(":") + Ast.line(Ast.step()) + rt_print("state ") + Ast.syms(sts, ", ") + Ast.line(Ast.step()) + rt_print("start ") + Ast.sym(start) + Ast.line(Ast.step()) + rt_print("end ") + Ast.syms(ends, ", ") + Ast.ops(ops) + dropOp match + case Coll.None => () + case Coll.Some(o) => + Ast.line(Ast.step()) + rt_print("drop ") + Ast.sym(o) + Ast.rules(rules) + case Ast.DHandler(h) => + val Ast.Handler(_, name, proto, fs) = h + rt_print("handler ") + Ast.sym(name) + rt_print(" for ") + Ast.sym(proto) + rt_print(":") + Ast.fns(fs, Ast.step()) + case Ast.DTrait(tr) => + val Ast.Trait(_, name, gs, sigs) = tr + rt_print("trait ") + Ast.sym(name) + Ast.groups(gs) + rt_print(":") + Ast.sigs(sigs, Ast.step()) + case Ast.DGiven(g) => + val Ast.Given(_, gs, head, fs) = g + rt_print("given") + Ast.groups(gs) + rt_print(" ") + Ast.ty(head) + rt_print(":") + Ast.fns(fs, Ast.step()) + case Ast.DType(td) => + val Ast.TypeDecl(_, name, gs, vals, body) = td + rt_print("type ") + Ast.sym(name) + Ast.groups(gs) + vals match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print(" (") + Ast.binders(vals) + rt_print(")") + rt_print(" = ") + body match + case Ast.Alias(t) => Ast.ty(t) + case Ast.TyMatch(s, arms) => + Ast.ty(s) + rt_print(" match") + Ast.tyArms(arms) + case Ast.ValMatch(x, arms) => + Ast.sym(x) + rt_print(" match") + Ast.valArms(arms) + +def Ast.tyArms {r: Region} (xs: Coll.List[Ast.TyArm]): Unit = xs match + case Coll.Nil => () + case Coll.Cons(a, t) => + val Ast.TyArm(_, p, res) = a + Ast.line(Ast.step()) + rt_print("case ") + Ast.ty(p) + rt_print(" => ") + Ast.ty(res) + Ast.tyArms(t) + +def Ast.valArms {r: Region} (xs: Coll.List[Ast.ValArm]): Unit = xs match + case Coll.Nil => () + case Coll.Cons(a, t) => + val Ast.ValArm(_, p, res) = a + Ast.line(Ast.step()) + rt_print("case ") + p match + case Ast.VInt(v) => rt_print_i64(v) + case Ast.VStr(s) => + rt_print("\"") + rt_print(s) + rt_print("\"") + case Ast.VBool(b) => rt_print(if b then "true" else "false") + case Ast.VAny => rt_print("_") + rt_print(" => ") + Ast.ty(res) + Ast.valArms(t) + +// a program: its decls, one blank line between two, a newline after the last +def Ast.print {r: Region} (ds: Coll.List[Ast.Decl]): Unit = ds match + case Coll.Nil => () + case Coll.Cons(d, t) => + Ast.decl(d) + rt_print("\n") + t match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print("\n") + Ast.print(t) diff --git a/bench/corpus/s2/bmap.srs b/bench/corpus/s2/bmap.srs new file mode 100644 index 00000000..3037e89c --- /dev/null +++ b/bench/corpus/s2/bmap.srs @@ -0,0 +1,318 @@ +// s2 COL b1 (vic/c/col-design.md): Coll.BMap, a persistent 2-3-4 tree keyed by I64. The arity is the case, so a wrong key +// count cannot be built. Insert is top-down (Guibas-Sedgewick 1978): a full B4 is split before it is entered, so bIns +// never sees a B4 and no per-level result wrapper is allocated. Uniform leaf depth and key order are test invariants. +enum Coll.BTree [V: Type]: + case Coll.BTip + case Coll.B2(a: Coll.BTree[V], k1: I64, v1: V, b: Coll.BTree[V]) + case Coll.B3(a: Coll.BTree[V], k1: I64, v1: V, b: Coll.BTree[V], k2: I64, v2: V, c: Coll.BTree[V]) + case Coll.B4(a: Coll.BTree[V], k1: I64, v1: V, b: Coll.BTree[V], k2: I64, v2: V, c: Coll.BTree[V], k3: I64, v3: V, d: Coll.BTree[V]) + +enum Coll.BMap [V: Type]: + case Coll.BMap(n: I64, t: Coll.BTree[V]) + +def Coll.bEmpty [V: Type] {r: Region} (): Coll.BMap[V] = Coll.BMap(0, Coll.BTip) + +def Coll.bSize [V: Type] (m: Coll.BMap[V]): I64 = m match + case Coll.BMap(n, _) => n + +// the node holding k, BTip when absent (no allocation) +def Coll.bFind [V: Type] (t: Coll.BTree[V], k: I64): Coll.BTree[V] = t match + case Coll.BTip => t + case Coll.B2(a, k1, _, b) => if k < k1 then Coll.bFind(a, k) else if k > k1 then Coll.bFind(b, k) else t + case Coll.B3(a, k1, _, b, k2, _, c) => + if k < k1 then Coll.bFind(a, k) else if k == k1 then t else if k < k2 then Coll.bFind(b, k) else if k == k2 then t else Coll.bFind(c, k) + case Coll.B4(a, k1, _, b, k2, _, c, k3, _, d) => + if k < k1 then Coll.bFind(a, k) else if k == k1 then t else if k < k2 then Coll.bFind(b, k) else if k == k2 then t + else if k < k3 then Coll.bFind(c, k) else if k == k3 then t else Coll.bFind(d, k) + +// the value of k in node n (a bFind answer), d when n is BTip +def Coll.bValOr [V: Type] (n: Coll.BTree[V], k: I64, d: V): V = n match + case Coll.BTip => d + case Coll.B2(_, k1, v1, _) => if k == k1 then v1 else d + case Coll.B3(_, k1, v1, _, k2, v2, _) => if k == k1 then v1 else if k == k2 then v2 else d + case Coll.B4(_, k1, v1, _, k2, v2, _, k3, v3, _) => if k == k1 then v1 else if k == k2 then v2 else if k == k3 then v3 else d + +def Coll.bGetOr [V: Type] (m: Coll.BMap[V], k: I64, d: V): V = m match + case Coll.BMap(_, t) => Coll.bValOr(Coll.bFind(t, k), k, d) + +def Coll.bIsNode [V: Type] (n: Coll.BTree[V]): Bool = n match + case Coll.BTip => false + case Coll.B2(_, _, _, _) => true + case Coll.B3(_, _, _, _, _, _, _) => true + case Coll.B4(_, _, _, _, _, _, _, _, _, _) => true + +def Coll.bHas [V: Type] (m: Coll.BMap[V], k: I64): Bool = m match + case Coll.BMap(_, t) => Coll.bIsNode(Coll.bFind(t, k)) + +def Coll.bLookup [V: Type] {r: Region} (m: Coll.BMap[V], k: I64): Coll.Option[V] = m match + case Coll.BMap(_, t) => Coll.bGet(t, k) + +// the value of k in one descent +def Coll.bGet [V: Type] {r: Region} (t: Coll.BTree[V], k: I64): Coll.Option[V] = t match + case Coll.BTip => Coll.None + case Coll.B2(a, k1, v1, b) => if k < k1 then Coll.bGet(a, k) else if k > k1 then Coll.bGet(b, k) else Coll.Some(v1) + case Coll.B3(a, k1, v1, b, k2, v2, c) => + if k < k1 then Coll.bGet(a, k) else if k == k1 then Coll.Some(v1) else if k < k2 then Coll.bGet(b, k) else if k == k2 then Coll.Some(v2) else Coll.bGet(c, k) + case Coll.B4(a, k1, v1, b, k2, v2, c, k3, v3, d) => + if k < k1 then Coll.bGet(a, k) else if k == k1 then Coll.Some(v1) else if k < k2 then Coll.bGet(b, k) else if k == k2 then Coll.Some(v2) + else if k < k3 then Coll.bGet(c, k) else if k == k3 then Coll.Some(v3) else Coll.bGet(d, k) + +// t with the value of k replaced: the path is copied and the shape is kept (no split); t when k is absent +def Coll.bRep [V: Type] {r: Region} (t: Coll.BTree[V], k: I64, v: V): Coll.BTree[V] = t match + case Coll.BTip => t + case Coll.B2(a, k1, v1, b) => + if k < k1 then Coll.B2(Coll.bRep(a, k, v), k1, v1, b) else if k > k1 then Coll.B2(a, k1, v1, Coll.bRep(b, k, v)) else Coll.B2(a, k1, v, b) + case Coll.B3(a, k1, v1, b, k2, v2, c) => + if k < k1 then Coll.B3(Coll.bRep(a, k, v), k1, v1, b, k2, v2, c) else if k == k1 then Coll.B3(a, k1, v, b, k2, v2, c) + else if k < k2 then Coll.B3(a, k1, v1, Coll.bRep(b, k, v), k2, v2, c) else if k == k2 then Coll.B3(a, k1, v1, b, k2, v, c) + else Coll.B3(a, k1, v1, b, k2, v2, Coll.bRep(c, k, v)) + case Coll.B4(a, k1, v1, b, k2, v2, c, k3, v3, d) => + if k < k1 then Coll.B4(Coll.bRep(a, k, v), k1, v1, b, k2, v2, c, k3, v3, d) else if k == k1 then Coll.B4(a, k1, v, b, k2, v2, c, k3, v3, d) + else if k < k2 then Coll.B4(a, k1, v1, Coll.bRep(b, k, v), k2, v2, c, k3, v3, d) else if k == k2 then Coll.B4(a, k1, v1, b, k2, v, c, k3, v3, d) + else if k < k3 then Coll.B4(a, k1, v1, b, k2, v2, Coll.bRep(c, k, v), k3, v3, d) else if k == k3 then Coll.B4(a, k1, v1, b, k2, v2, c, k3, v, d) + else Coll.B4(a, k1, v1, b, k2, v2, c, k3, v3, Coll.bRep(d, k, v)) + +// a B4 split around its middle key: the two halves are B2 trees (left, middle key and value, right) +enum Coll.Split [V: Type]: + case Coll.Split(l: Coll.BTree[V], k: I64, v: V, r: Coll.BTree[V]) + +// the halves of a full node (its fields, so no other shape can be passed), k inserted into the half it belongs to. +// the halves are B2s, so bIns may enter them. +def Coll.bSplitIns [V: Type] {r: Region} (a: Coll.BTree[V], k1: I64, v1: V, b: Coll.BTree[V], k2: I64, v2: V, c: Coll.BTree[V], k3: I64, v3: V, d: Coll.BTree[V], k: I64, v: V): Coll.Split[V] = + if k == k2 then Coll.Split(Coll.B2(a, k1, v1, b), k2, v, Coll.B2(c, k3, v3, d)) + else if k < k2 then Coll.Split(Coll.bIns(Coll.B2(a, k1, v1, b), k, v), k2, v2, Coll.B2(c, k3, v3, d)) + else Coll.Split(Coll.B2(a, k1, v1, b), k2, v2, Coll.bIns(Coll.B2(c, k3, v3, d), k, v)) + +// a B4 root becomes a B2 over two B2s, then k enters it +def Coll.bRootIns [V: Type] {r: Region} (a: Coll.BTree[V], k1: I64, v1: V, b: Coll.BTree[V], k2: I64, v2: V, c: Coll.BTree[V], k3: I64, v3: V, d: Coll.BTree[V], k: I64, v: V): Coll.BTree[V] = + Coll.bIns(Coll.B2(Coll.B2(a, k1, v1, b), k2, v2, Coll.B2(c, k3, v3, d)), k, v) + +// a B4 is only met at the root (children are split before they are entered) +def Coll.bIns [V: Type] {r: Region} (t: Coll.BTree[V], k: I64, v: V): Coll.BTree[V] = t match + case Coll.BTip => Coll.B2(Coll.BTip, k, v, Coll.BTip) + case Coll.B2(a, k1, v1, b) => + if k == k1 then Coll.B2(a, k1, v, b) + else if k < k1 then Coll.bInto2L(a, k1, v1, b, k, v) + else Coll.bInto2R(a, k1, v1, b, k, v) + case Coll.B3(a, k1, v1, b, k2, v2, c) => + if k == k1 then Coll.B3(a, k1, v, b, k2, v2, c) + else if k == k2 then Coll.B3(a, k1, v1, b, k2, v, c) + else if k < k1 then Coll.bInto3A(a, k1, v1, b, k2, v2, c, k, v) + else if k < k2 then Coll.bInto3B(a, k1, v1, b, k2, v2, c, k, v) + else Coll.bInto3C(a, k1, v1, b, k2, v2, c, k, v) + case Coll.B4(a, k1, v1, b, k2, v2, c, k3, v3, d) => Coll.bRootIns(a, k1, v1, b, k2, v2, c, k3, v3, d, k, v) + +def Coll.bLift2L [V: Type] {r: Region} (s: Coll.Split[V], k1: I64, v1: V, b: Coll.BTree[V]): Coll.BTree[V] = s match + case Coll.Split(l, km, vm, rr) => Coll.B3(l, km, vm, rr, k1, v1, b) + +def Coll.bLift2R [V: Type] {r: Region} (a: Coll.BTree[V], k1: I64, v1: V, s: Coll.Split[V]): Coll.BTree[V] = s match + case Coll.Split(l, km, vm, rr) => Coll.B3(a, k1, v1, l, km, vm, rr) + +// descend into the left child a of B2(a, k1, v1, b) with k < k1 +def Coll.bInto2L [V: Type] {r: Region} (a: Coll.BTree[V], k1: I64, v1: V, b: Coll.BTree[V], k: I64, v: V): Coll.BTree[V] = a match + case Coll.BTip => Coll.B3(Coll.BTip, k, v, Coll.BTip, k1, v1, Coll.BTip) + case Coll.B4(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4) => Coll.bLift2L(Coll.bSplitIns(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, k, v), k1, v1, b) + case Coll.B2(_, _, _, _) => Coll.B2(Coll.bIns(a, k, v), k1, v1, b) + case Coll.B3(_, _, _, _, _, _, _) => Coll.B2(Coll.bIns(a, k, v), k1, v1, b) + +def Coll.bInto2R [V: Type] {r: Region} (a: Coll.BTree[V], k1: I64, v1: V, b: Coll.BTree[V], k: I64, v: V): Coll.BTree[V] = b match + case Coll.BTip => Coll.B3(Coll.BTip, k1, v1, Coll.BTip, k, v, Coll.BTip) + case Coll.B4(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4) => Coll.bLift2R(a, k1, v1, Coll.bSplitIns(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, k, v)) + case Coll.B2(_, _, _, _) => Coll.B2(a, k1, v1, Coll.bIns(b, k, v)) + case Coll.B3(_, _, _, _, _, _, _) => Coll.B2(a, k1, v1, Coll.bIns(b, k, v)) + +def Coll.bLift3A [V: Type] {r: Region} (s: Coll.Split[V], k1: I64, v1: V, b: Coll.BTree[V], k2: I64, v2: V, c: Coll.BTree[V]): Coll.BTree[V] = s match + case Coll.Split(l, km, vm, rr) => Coll.B4(l, km, vm, rr, k1, v1, b, k2, v2, c) + +def Coll.bLift3B [V: Type] {r: Region} (a: Coll.BTree[V], k1: I64, v1: V, s: Coll.Split[V], k2: I64, v2: V, c: Coll.BTree[V]): Coll.BTree[V] = s match + case Coll.Split(l, km, vm, rr) => Coll.B4(a, k1, v1, l, km, vm, rr, k2, v2, c) + +def Coll.bLift3C [V: Type] {r: Region} (a: Coll.BTree[V], k1: I64, v1: V, b: Coll.BTree[V], k2: I64, v2: V, s: Coll.Split[V]): Coll.BTree[V] = s match + case Coll.Split(l, km, vm, rr) => Coll.B4(a, k1, v1, b, k2, v2, l, km, vm, rr) + +def Coll.bInto3A [V: Type] {r: Region} (a: Coll.BTree[V], k1: I64, v1: V, b: Coll.BTree[V], k2: I64, v2: V, c: Coll.BTree[V], k: I64, v: V): Coll.BTree[V] = a match + case Coll.BTip => Coll.B4(Coll.BTip, k, v, Coll.BTip, k1, v1, Coll.BTip, k2, v2, Coll.BTip) + case Coll.B4(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4) => Coll.bLift3A(Coll.bSplitIns(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, k, v), k1, v1, b, k2, v2, c) + case Coll.B2(_, _, _, _) => Coll.B3(Coll.bIns(a, k, v), k1, v1, b, k2, v2, c) + case Coll.B3(_, _, _, _, _, _, _) => Coll.B3(Coll.bIns(a, k, v), k1, v1, b, k2, v2, c) + +def Coll.bInto3B [V: Type] {r: Region} (a: Coll.BTree[V], k1: I64, v1: V, b: Coll.BTree[V], k2: I64, v2: V, c: Coll.BTree[V], k: I64, v: V): Coll.BTree[V] = b match + case Coll.BTip => Coll.B4(Coll.BTip, k1, v1, Coll.BTip, k, v, Coll.BTip, k2, v2, Coll.BTip) + case Coll.B4(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4) => Coll.bLift3B(a, k1, v1, Coll.bSplitIns(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, k, v), k2, v2, c) + case Coll.B2(_, _, _, _) => Coll.B3(a, k1, v1, Coll.bIns(b, k, v), k2, v2, c) + case Coll.B3(_, _, _, _, _, _, _) => Coll.B3(a, k1, v1, Coll.bIns(b, k, v), k2, v2, c) + +def Coll.bInto3C [V: Type] {r: Region} (a: Coll.BTree[V], k1: I64, v1: V, b: Coll.BTree[V], k2: I64, v2: V, c: Coll.BTree[V], k: I64, v: V): Coll.BTree[V] = c match + case Coll.BTip => Coll.B4(Coll.BTip, k1, v1, Coll.BTip, k2, v2, Coll.BTip, k, v, Coll.BTip) + case Coll.B4(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4) => Coll.bLift3C(a, k1, v1, b, k2, v2, Coll.bSplitIns(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, k, v)) + case Coll.B2(_, _, _, _) => Coll.B3(a, k1, v1, b, k2, v2, Coll.bIns(c, k, v)) + case Coll.B3(_, _, _, _, _, _, _) => Coll.B3(a, k1, v1, b, k2, v2, Coll.bIns(c, k, v)) + +// the answer of bPut: the new map, Added when k was absent (the count grew), Replaced when k was bound (same shape) +enum Coll.Put [V: Type]: + case Coll.Added(m: Coll.BMap[V]) + case Coll.Replaced(m: Coll.BMap[V]) + +def Coll.bPut [V: Type] {r: Region} (m: Coll.BMap[V], k: I64, v: V): Coll.Put[V] = m match + case Coll.BMap(n, t) => if Coll.bIsNode(Coll.bFind(t, k)) then Coll.Replaced(Coll.BMap(n, Coll.bRep(t, k, v))) else Coll.Added(Coll.BMap(n + 1, Coll.bIns(t, k, v))) + +// b4: a BMap from a Sorted batch in O(n), built bottom-up one level at a time. A level of r entries becomes nodes of +// 2 to 4 children: r = 1, 2, 3 give one B2, B3, B4; r >= 4 gives a B3, promotes the next key and goes on with r - 3 >= 1 +// entries, so every leaf is at one depth. Each pass takes the first entry as its own argument (a group is never empty) +// and the passes alternate direction, so no level is reversed. The order of a level is in its type: +// BLvlA = the leftmost tree, then ascending BKT (a key and the tree right of it); +// BLvlD = descending BTK (a key and the tree left of it), then the rightmost tree. +enum Coll.BKT [V: Type]: + case Coll.BKT(k: I64, v: V, t: Coll.BTree[V]) + +enum Coll.BTK [V: Type]: + case Coll.BTK(t: Coll.BTree[V], k: I64, v: V) + +enum Coll.BLvlA [V: Type]: + case Coll.BLvlA(t: Coll.BTree[V], es: Coll.List[Coll.BKT[V]]) + +enum Coll.BLvlD [V: Type]: + case Coll.BLvlD(es: Coll.List[Coll.BTK[V]], t: Coll.BTree[V]) + +def Coll.blL2 [V: Type] {r: Region} (a: Coll.KV[V]): Coll.BTree[V] = a match + case Coll.KV(k1, v1) => Coll.B2(Coll.BTip, k1, v1, Coll.BTip) + +def Coll.blL3 [V: Type] {r: Region} (a: Coll.KV[V], b: Coll.KV[V]): Coll.BTree[V] = a match + case Coll.KV(k1, v1) => b match + case Coll.KV(k2, v2) => Coll.B3(Coll.BTip, k1, v1, Coll.BTip, k2, v2, Coll.BTip) + +def Coll.blL4 [V: Type] {r: Region} (a: Coll.KV[V], b: Coll.KV[V], c: Coll.KV[V]): Coll.BTree[V] = a match + case Coll.KV(k1, v1) => b match + case Coll.KV(k2, v2) => c match + case Coll.KV(k3, v3) => Coll.B4(Coll.BTip, k1, v1, Coll.BTip, k2, v2, Coll.BTip, k3, v3, Coll.BTip) + +// the leaf level: ascending pairs, a first; acc holds the promoted keys, descending +def Coll.blLeaf [V: Type] {r: Region} (a: Coll.KV[V], rest: Coll.List[Coll.KV[V]], acc: Coll.List[Coll.BTK[V]]): Coll.BLvlD[V] = rest match + case Coll.Nil => Coll.BLvlD(acc, Coll.blL2(a)) + case Coll.Cons(b, r2) => r2 match + case Coll.Nil => Coll.BLvlD(acc, Coll.blL3(a, b)) + case Coll.Cons(c, r3) => r3 match + case Coll.Nil => Coll.BLvlD(acc, Coll.blL4(a, b, c)) + case Coll.Cons(d, r4) => c match + case Coll.KV(kc, vc) => Coll.blLeaf(d, r4, Coll.Cons(Coll.BTK(Coll.blL3(a, b), kc, vc), acc)) + +def Coll.blA2 [V: Type] {r: Region} (t: Coll.BTree[V], a: Coll.BKT[V]): Coll.BTree[V] = a match + case Coll.BKT(k1, v1, t1) => Coll.B2(t, k1, v1, t1) + +def Coll.blA3 [V: Type] {r: Region} (t: Coll.BTree[V], a: Coll.BKT[V], b: Coll.BKT[V]): Coll.BTree[V] = a match + case Coll.BKT(k1, v1, t1) => b match + case Coll.BKT(k2, v2, t2) => Coll.B3(t, k1, v1, t1, k2, v2, t2) + +def Coll.blA4 [V: Type] {r: Region} (t: Coll.BTree[V], a: Coll.BKT[V], b: Coll.BKT[V], c: Coll.BKT[V]): Coll.BTree[V] = a match + case Coll.BKT(k1, v1, t1) => b match + case Coll.BKT(k2, v2, t2) => c match + case Coll.BKT(k3, v3, t3) => Coll.B4(t, k1, v1, t1, k2, v2, t2, k3, v3, t3) + +// an ascending level: t is the leftmost tree of the group, a its first entry +def Coll.blPassA [V: Type] {r: Region} (t: Coll.BTree[V], a: Coll.BKT[V], rest: Coll.List[Coll.BKT[V]], acc: Coll.List[Coll.BTK[V]]): Coll.BLvlD[V] = rest match + case Coll.Nil => Coll.BLvlD(acc, Coll.blA2(t, a)) + case Coll.Cons(b, r2) => r2 match + case Coll.Nil => Coll.BLvlD(acc, Coll.blA3(t, a, b)) + case Coll.Cons(c, r3) => r3 match + case Coll.Nil => Coll.BLvlD(acc, Coll.blA4(t, a, b, c)) + case Coll.Cons(d, r4) => c match + case Coll.BKT(kc, vc, tc) => Coll.blPassA(tc, d, r4, Coll.Cons(Coll.BTK(Coll.blA3(t, a, b), kc, vc), acc)) + +// the entries in ascending order (a left of b left of c), t is the rightmost tree +def Coll.blD2 [V: Type] {r: Region} (a: Coll.BTK[V], t: Coll.BTree[V]): Coll.BTree[V] = a match + case Coll.BTK(t1, k1, v1) => Coll.B2(t1, k1, v1, t) + +def Coll.blD3 [V: Type] {r: Region} (a: Coll.BTK[V], b: Coll.BTK[V], t: Coll.BTree[V]): Coll.BTree[V] = a match + case Coll.BTK(t1, k1, v1) => b match + case Coll.BTK(t2, k2, v2) => Coll.B3(t1, k1, v1, t2, k2, v2, t) + +def Coll.blD4 [V: Type] {r: Region} (a: Coll.BTK[V], b: Coll.BTK[V], c: Coll.BTK[V], t: Coll.BTree[V]): Coll.BTree[V] = a match + case Coll.BTK(t1, k1, v1) => b match + case Coll.BTK(t2, k2, v2) => c match + case Coll.BTK(t3, k3, v3) => Coll.B4(t1, k1, v1, t2, k2, v2, t3, k3, v3, t) + +// a descending level: t is the rightmost tree of the group, a its last entry; acc holds the promoted keys, ascending +def Coll.blPassD [V: Type] {r: Region} (t: Coll.BTree[V], a: Coll.BTK[V], rest: Coll.List[Coll.BTK[V]], acc: Coll.List[Coll.BKT[V]]): Coll.BLvlA[V] = rest match + case Coll.Nil => Coll.BLvlA(Coll.blD2(a, t), acc) + case Coll.Cons(b, r2) => r2 match + case Coll.Nil => Coll.BLvlA(Coll.blD3(b, a, t), acc) + case Coll.Cons(c, r3) => r3 match + case Coll.Nil => Coll.BLvlA(Coll.blD4(c, b, a, t), acc) + case Coll.Cons(d, r4) => c match + case Coll.BTK(tc, kc, vc) => Coll.blPassD(tc, d, r4, Coll.Cons(Coll.BKT(kc, vc, Coll.blD3(b, a, t)), acc)) + +def Coll.blFromA [V: Type] {r: Region} (l: Coll.BLvlA[V]): Coll.BTree[V] = l match + case Coll.BLvlA(t, es) => es match + case Coll.Nil => t + case Coll.Cons(a, rest) => Coll.blFromD(Coll.blPassA(t, a, rest, Coll.Nil)) + +def Coll.blFromD [V: Type] {r: Region} (l: Coll.BLvlD[V]): Coll.BTree[V] = l match + case Coll.BLvlD(es, t) => es match + case Coll.Nil => t + case Coll.Cons(a, rest) => Coll.blFromA(Coll.blPassD(t, a, rest, Coll.Nil)) + +def Coll.bFromSorted [V: Type] {r: Region} (s: Coll.Sorted[V]): Coll.BMap[V] = s match + case Coll.Sorted(xs) => xs match + case Coll.Nil => Coll.BMap(0, Coll.BTip) + case Coll.Cons(a, rest) => Coll.BMap(Coll.length(xs), Coll.blFromD(Coll.blLeaf(a, rest, Coll.Nil))) + +// the value bound to k in t, d when k is absent (no allocation) +def Coll.bTGetOr [V: Type] (t: Coll.BTree[V], k: I64, d: V): V = Coll.bValOr(Coll.bFind(t, k), k, d) + +// t with x consed onto the list bound to k (a one-element list when k is absent): one find, then one path copy +def Coll.bPushT [A: Type] {r: Region} (t: Coll.BTree[Coll.List[A]], k: I64, x: A): Coll.BTree[Coll.List[A]] = + val n = Coll.bFind(t, k) + if Coll.bIsNode(n) then Coll.bRep(t, k, Coll.Cons(x, Coll.bValOr(n, k, Coll.Nil))) else Coll.bIns(t, k, Coll.Cons(x, Coll.Nil)) + +// b3: a Sym map is a tree from the Sym hash to a bucket; a hash tie compares the strings (Sym.eq). The tree has no +// count: a bucket count is not a Sym count. +enum Coll.SEntry [V: Type]: + case Coll.SEntry(s: Sym.Sym, v: V) + +enum Coll.SMap [V: Type]: + case Coll.SMap(t: Coll.BTree[Coll.List[Coll.SEntry[V]]]) + +def Coll.sEmpty [V: Type] {r: Region} (): Coll.SMap[V] = Coll.SMap(Coll.BTip) + +// xs with the entry of s bound to v (added last when s is absent) +def Coll.sSet [V: Type] {r: Region} (xs: Coll.List[Coll.SEntry[V]], s: Sym.Sym, v: V): Coll.List[Coll.SEntry[V]] = xs match + case Coll.Nil => Coll.Cons(Coll.SEntry(s, v), Coll.Nil) + case Coll.Cons(e, t) => e match + case Coll.SEntry(s2, _) => if Sym.eq(s, s2) then Coll.Cons(Coll.SEntry(s, v), t) else Coll.Cons(e, Coll.sSet(t, s, v)) + +def Coll.sFind [V: Type] {r: Region} (xs: Coll.List[Coll.SEntry[V]], s: Sym.Sym): Coll.Option[V] = xs match + case Coll.Nil => Coll.None + case Coll.Cons(e, t) => e match + case Coll.SEntry(s2, v) => if Sym.eq(s, s2) then Coll.Some(v) else Coll.sFind(t, s) + +// m with s bound to v (a binding of s is replaced): one find, then one path copy +def Coll.sInsert [V: Type] {r: Region} (m: Coll.SMap[V], s: Sym.Sym, v: V): Coll.SMap[V] = m match + case Coll.SMap(t) => + val h = Sym.hash(s) + val n = Coll.bFind(t, h) + if Coll.bIsNode(n) then Coll.SMap(Coll.bRep(t, h, Coll.sSet(Coll.bValOr(n, h, Coll.Nil), s, v))) else Coll.SMap(Coll.bIns(t, h, Coll.Cons(Coll.SEntry(s, v), Coll.Nil))) + +def Coll.sLookup [V: Type] {r: Region} (m: Coll.SMap[V], s: Sym.Sym): Coll.Option[V] = m match + case Coll.SMap(t) => Coll.sFind(Coll.bTGetOr(t, Sym.hash(s), Coll.Nil), s) + +// an I64 set: a BMap to the one value U, so its count is the set size +enum Coll.Unit: + case Coll.U + +enum Coll.ISet: + case Coll.ISet(m: Coll.BMap[Coll.Unit]) + +def Coll.setEmpty {r: Region} (): Coll.ISet = Coll.ISet(Coll.bEmpty[Coll.Unit]()) + +def Coll.setAdd {r: Region} (s: Coll.ISet, k: I64): Coll.ISet = s match + case Coll.ISet(m) => Coll.ISet(Coll.bInsert(m, k, Coll.U)) + +def Coll.setHas (s: Coll.ISet, k: I64): Bool = s match + case Coll.ISet(m) => Coll.bHas(m, k) + +def Coll.setSize (s: Coll.ISet): I64 = s match + case Coll.ISet(m) => Coll.bSize(m) + +// bPut without the answer wrapper +def Coll.bInsert [V: Type] {r: Region} (m: Coll.BMap[V], k: I64, v: V): Coll.BMap[V] = m match + case Coll.BMap(n, t) => if Coll.bIsNode(Coll.bFind(t, k)) then Coll.BMap(n, Coll.bRep(t, k, v)) else Coll.BMap(n + 1, Coll.bIns(t, k, v)) diff --git a/bench/corpus/s2/coll.srs b/bench/corpus/s2/coll.srs new file mode 100644 index 00000000..7d1d97a4 --- /dev/null +++ b/bench/corpus/s2/coll.srs @@ -0,0 +1,196 @@ +// s2 collections (vic-m5r.13 C1): persistent and functional (val only); every loop is a self tail call, so it runs in +// constant C stack (vic-m5r.10). a function is a given of a trait, named by a marker type F (no closures). + +enum Coll.List [A: Type]: + case Coll.Nil + case Coll.Cons(h: A, t: Coll.List[A]) + +enum Coll.Option [A: Type]: + case Coll.None + case Coll.Some(v: A) + +// xs reversed onto acc +def Coll.revOnto [A: Type] {r: Region} (xs: Coll.List[A], acc: Coll.List[A]): Coll.List[A] = xs match + case Coll.Nil => acc + case Coll.Cons(h, t) => Coll.revOnto(t, Coll.Cons(h, acc)) + +def Coll.rev [A: Type] {r: Region} (xs: Coll.List[A]): Coll.List[A] = Coll.revOnto(xs, Coll.Nil) + +def Coll.lengthFrom [A: Type] (xs: Coll.List[A], n: I64): I64 = xs match + case Coll.Nil => n + case Coll.Cons(_, t) => Coll.lengthFrom(t, n + 1) + +def Coll.length [A: Type] (xs: Coll.List[A]): I64 = Coll.lengthFrom(xs, 0) + +def Coll.headOpt [A: Type] {r: Region} (xs: Coll.List[A]): Coll.Option[A] = xs match + case Coll.Nil => Coll.None + case Coll.Cons(h, _) => Coll.Some(h) + +// one step of a left fold: the given for marker F +trait Coll.Fold [F: Type] [A: Type] [B: Type]: + def step(acc: B, x: A): B + +def Coll.foldl [F: Type] [A: Type] [B: Type] {f: Coll.Fold[F, A, B]} (xs: Coll.List[A], acc: B): B = xs match + case Coll.Nil => acc + case Coll.Cons(h, t) => Coll.foldl[F, A, B](t, f.step(acc, h)) + +// a persistent map keyed by I64 (vic-m5r.13 C2): a weight-balanced tree, Adams' balance with delta 3, ratio 2 (the +// pair Haskell Data.Map uses; Hirai and Yamamoto 2011 prove it the only integer pair that keeps the balance). a key +// is an I64 (a name's strHash): one integer compare per level. an insert copies one path (O(log n) nodes). +enum Coll.IMap [V: Type]: + case Coll.Tip + case Coll.Bin(size: I64, k: I64, v: V, l: Coll.IMap[V], r: Coll.IMap[V]) + +// the two balance factors (Adams; delta 3, ratio 2, above): one side may hold at most delta times the other, and a +// rotation is single when the inner grandchild holds less than ratio times the outer one, else double +def Coll.delta(): I64 = 3 +def Coll.ratio(): I64 = 2 + +def Coll.size [V: Type] (m: Coll.IMap[V]): I64 = m match + case Coll.Tip => 0 + case Coll.Bin(s, _, _, _, _) => s + +def Coll.lookup [V: Type] {r: Region} (m: Coll.IMap[V], k: I64): Coll.Option[V] = m match + case Coll.Tip => Coll.None + case Coll.Bin(_, k2, v, l, r2) => if k < k2 then Coll.lookup(l, k) else if k > k2 then Coll.lookup(r2, k) else Coll.Some(v) + +// a node over l and r (their sizes known) +def Coll.bin [V: Type] {r: Region} (k: I64, v: V, l: Coll.IMap[V], r2: Coll.IMap[V]): Coll.IMap[V] = + Coll.Bin(Coll.size(l) + Coll.size(r2) + 1, k, v, l, r2) + +// k, v over l and r where one side grew or shrank by at most one element: rotate back into balance +def Coll.balance [V: Type] {r: Region} (k: I64, v: V, l: Coll.IMap[V], r2: Coll.IMap[V]): Coll.IMap[V] = + val sl = Coll.size(l) + val sr = Coll.size(r2) + if sl + sr <= 1 then Coll.bin(k, v, l, r2) + else if sr > Coll.delta() * sl then Coll.rotateL(k, v, l, r2) + else if sl > Coll.delta() * sr then Coll.rotateR(k, v, l, r2) + else Coll.bin(k, v, l, r2) + +def Coll.rotateL [V: Type] {r: Region} (k: I64, v: V, l: Coll.IMap[V], r2: Coll.IMap[V]): Coll.IMap[V] = r2 match + case Coll.Tip => Coll.bin(k, v, l, r2) + case Coll.Bin(_, k2, v2, rl, rr) => + if Coll.size(rl) < Coll.ratio() * Coll.size(rr) then Coll.bin(k2, v2, Coll.bin(k, v, l, rl), rr) + else rl match + case Coll.Tip => Coll.bin(k2, v2, Coll.bin(k, v, l, rl), rr) + case Coll.Bin(_, k3, v3, rll, rlr) => Coll.bin(k3, v3, Coll.bin(k, v, l, rll), Coll.bin(k2, v2, rlr, rr)) + +def Coll.rotateR [V: Type] {r: Region} (k: I64, v: V, l: Coll.IMap[V], r2: Coll.IMap[V]): Coll.IMap[V] = l match + case Coll.Tip => Coll.bin(k, v, l, r2) + case Coll.Bin(_, k2, v2, ll, lr) => + if Coll.size(lr) < Coll.ratio() * Coll.size(ll) then Coll.bin(k2, v2, ll, Coll.bin(k, v, lr, r2)) + else lr match + case Coll.Tip => Coll.bin(k2, v2, ll, Coll.bin(k, v, lr, r2)) + case Coll.Bin(_, k3, v3, lrl, lrr) => Coll.bin(k3, v3, Coll.bin(k2, v2, ll, lrl), Coll.bin(k, v, lrr, r2)) + +// m with k bound to v (a binding of k is replaced) +def Coll.insert [V: Type] {r: Region} (m: Coll.IMap[V], k: I64, v: V): Coll.IMap[V] = m match + case Coll.Tip => Coll.Bin(1, k, v, Coll.Tip, Coll.Tip) + case Coll.Bin(s, k2, v2, l, r2) => + if k < k2 then Coll.balance(k2, v2, Coll.insert(l, k, v), r2) + else if k > k2 then Coll.balance(k2, v2, l, Coll.insert(r2, k, v)) + else Coll.Bin(s, k, v, l, r2) + +// the node of k, Coll.Tip when absent: a lookup that allocates nothing (Coll.lookup allocates its Some) +def Coll.node [V: Type] (m: Coll.IMap[V], k: I64): Coll.IMap[V] = m match + case Coll.Tip => m + case Coll.Bin(_, k2, _, l, r2) => if k < k2 then Coll.node(l, k) else if k > k2 then Coll.node(r2, k) else m + +// b4 batch input: key/value pairs, strictly ascending by key. Only Coll.sortDedup builds a Sorted (no sealing in s1 yet: +// the order is a producer invariant, not a type one) +enum Coll.KV [V: Type]: + case Coll.KV(k: I64, v: V) + +enum Coll.Sorted [V: Type]: + case Coll.Sorted(xs: Coll.List[Coll.KV[V]]) + +def Coll.kvKey [V: Type] (e: Coll.KV[V]): I64 = e match + case Coll.KV(k, _) => k + +// the input order of a natural run: Up = non-decreasing (consed, the run is strictly descending), Down = strictly +// decreasing (consed, the run is ascending until it is closed) +enum Coll.Dir: + case Coll.Up + case Coll.Down + +// the run Cons(h, rt) as a strictly descending run +def Coll.closeRun [V: Type] {r: Region} (d: Coll.Dir, h: Coll.KV[V], rt: Coll.List[Coll.KV[V]]): Coll.List[Coll.KV[V]] = d match + case Coll.Up => Coll.Cons(h, rt) + case Coll.Down => Coll.revOnto(rt, Coll.Cons(h, Coll.Nil)) + +// the natural runs of xs, each strictly descending, the latest run first. In an Up run an equal key replaces the run +// head (the later binding wins); a one-element Up run turns Down when the next key is smaller. +def Coll.runs [V: Type] {r: Region} (xs: Coll.List[Coll.KV[V]]): Coll.List[Coll.List[Coll.KV[V]]] = xs match + case Coll.Nil => Coll.Nil + case Coll.Cons(x, t) => Coll.runStep(t, Coll.Up, x, Coll.Nil, Coll.Nil) + +// h is the last element taken into the current run Cons(h, rt) +def Coll.runStep [V: Type] {r: Region} (xs: Coll.List[Coll.KV[V]], d: Coll.Dir, h: Coll.KV[V], rt: Coll.List[Coll.KV[V]], acc: Coll.List[Coll.List[Coll.KV[V]]]): Coll.List[Coll.List[Coll.KV[V]]] = xs match + case Coll.Nil => Coll.Cons(Coll.closeRun(d, h, rt), acc) + case Coll.Cons(y, t) => + val ky = Coll.kvKey(y) + val kh = Coll.kvKey(h) + d match + case Coll.Up => + if ky > kh then Coll.runStep(t, d, y, Coll.Cons(h, rt), acc) + else if ky == kh then Coll.runStep(t, d, y, rt, acc) + else rt match + case Coll.Nil => Coll.runStep(t, Coll.Down, y, Coll.Cons(h, rt), acc) + case Coll.Cons(_, _) => Coll.runStep(t, Coll.Up, y, Coll.Nil, Coll.Cons(Coll.Cons(h, rt), acc)) + case Coll.Down => + if ky < kh then Coll.runStep(t, d, y, Coll.Cons(h, rt), acc) + else Coll.runStep(t, Coll.Up, y, Coll.Nil, Coll.Cons(Coll.closeRun(d, h, rt), acc)) + +// merge of two ascending runs onto acc, giving a descending run; equal keys: the element of b (the later run) wins +def Coll.mergeRev [V: Type] {r: Region} (a: Coll.List[Coll.KV[V]], b: Coll.List[Coll.KV[V]], acc: Coll.List[Coll.KV[V]]): Coll.List[Coll.KV[V]] = a match + case Coll.Nil => Coll.revOnto(b, acc) + case Coll.Cons(x, ta) => b match + case Coll.Nil => Coll.revOnto(a, acc) + case Coll.Cons(y, tb) => + val kx = Coll.kvKey(x) + val ky = Coll.kvKey(y) + if kx < ky then Coll.mergeRev(ta, b, Coll.Cons(x, acc)) + else if kx == ky then Coll.mergeRev(ta, tb, Coll.Cons(y, acc)) + else Coll.mergeRev(a, tb, Coll.Cons(y, acc)) + +// merge of two descending runs onto acc, giving an ascending run; equal keys: the element of a (the later run) wins +def Coll.mergeRevD [V: Type] {r: Region} (a: Coll.List[Coll.KV[V]], b: Coll.List[Coll.KV[V]], acc: Coll.List[Coll.KV[V]]): Coll.List[Coll.KV[V]] = a match + case Coll.Nil => Coll.revOnto(b, acc) + case Coll.Cons(x, ta) => b match + case Coll.Nil => Coll.revOnto(a, acc) + case Coll.Cons(y, tb) => + val kx = Coll.kvKey(x) + val ky = Coll.kvKey(y) + if kx > ky then Coll.mergeRevD(ta, b, Coll.Cons(x, acc)) + else if kx == ky then Coll.mergeRevD(ta, tb, Coll.Cons(x, acc)) + else Coll.mergeRevD(a, tb, Coll.Cons(y, acc)) + +// one pass over ascending runs, earliest first: descending runs, latest first (a last odd run is reversed) +def Coll.passA [V: Type] {r: Region} (runs: Coll.List[Coll.List[Coll.KV[V]]], acc: Coll.List[Coll.List[Coll.KV[V]]]): Coll.List[Coll.List[Coll.KV[V]]] = runs match + case Coll.Nil => acc + case Coll.Cons(a, t) => t match + case Coll.Nil => Coll.Cons(Coll.rev(a), acc) + case Coll.Cons(b, t2) => Coll.passA(t2, Coll.Cons(Coll.mergeRev(a, b, Coll.Nil), acc)) + +// one pass over descending runs, latest first: ascending runs, earliest first (a last odd run is reversed) +def Coll.passD [V: Type] {r: Region} (runs: Coll.List[Coll.List[Coll.KV[V]]], acc: Coll.List[Coll.List[Coll.KV[V]]]): Coll.List[Coll.List[Coll.KV[V]]] = runs match + case Coll.Nil => acc + case Coll.Cons(a, t) => t match + case Coll.Nil => Coll.Cons(Coll.rev(a), acc) + case Coll.Cons(b, t2) => Coll.passD(t2, Coll.Cons(Coll.mergeRevD(a, b, Coll.Nil), acc)) + +// the run order is in the function: mergeAllA gets ascending runs earliest first, mergeAllD descending runs latest first +def Coll.mergeAllA [V: Type] {r: Region} (runs: Coll.List[Coll.List[Coll.KV[V]]]): Coll.List[Coll.KV[V]] = runs match + case Coll.Nil => Coll.Nil + case Coll.Cons(a, t) => t match + case Coll.Nil => a + case Coll.Cons(_, _) => Coll.mergeAllD(Coll.passA(runs, Coll.Nil)) + +def Coll.mergeAllD [V: Type] {r: Region} (runs: Coll.List[Coll.List[Coll.KV[V]]]): Coll.List[Coll.KV[V]] = runs match + case Coll.Nil => Coll.Nil + case Coll.Cons(a, t) => t match + case Coll.Nil => Coll.rev(a) + case Coll.Cons(_, _) => Coll.mergeAllA(Coll.passD(runs, Coll.Nil)) + +// natural bottom-up merge sort, O(n log r) for r runs; a duplicate key keeps the last binding of the input +def Coll.sortDedup [V: Type] {r: Region} (xs: Coll.List[Coll.KV[V]]): Coll.Sorted[V] = Coll.Sorted(Coll.mergeAllD(Coll.runs(xs))) diff --git a/bench/corpus/s2/datalog.srs b/bench/corpus/s2/datalog.srs new file mode 100644 index 00000000..2bc9d8f7 --- /dev/null +++ b/bench/corpus/s2/datalog.srs @@ -0,0 +1,708 @@ +// s2 component 6: Datalog core: positive rules, semi-naive evaluation by round stamps (egglog): a relation keeps one +// set (dedup) and one index per probed column for all rounds; each row carries the round that derived it, and every +// bucket lists rows newest first, so in round r a body atom reads rows of round r-1 (recent: a bucket prefix), older +// rows (stable) or both, and each derivation is found once (atoms before the recent one read stable rows, after it +// both). each tuple is inserted once; a round ends by moving two counters. relations are compiled to integer ids; +// an atom reads the bucket of its first bound column; rounds are tail calls. +enum D.Val: + case D.VSym(s: Sym.Sym) + case D.VInt(v: I64) + +enum D.Arg: + case D.AVar(n: I64) + case D.AVal(v: D.Val) + +enum D.Atom: + case D.Atom(rel: Sym.Sym, args: Coll.List[D.Arg]) + +// a body literal: an atom that must hold, or one that must not (stratified negation) +enum D.Lit: + case D.Pos(a: D.Atom) + case D.Neg(a: D.Atom) + +// head :- body +enum D.Rule: + case D.Rule(head: D.Atom, body: Coll.List[D.Lit]) + +enum D.Fact: + case D.Fact(rel: Sym.Sym, vals: Coll.List[D.Val]) + +// hashing (no xor or shift on I64): h * D.mult() + x modulo the prime D.modulus(); every product stays below 2^63 +// (h < 1e9+7, 31 * h < 2^35). a tuple's hash starts at D.seed() +def D.modulus(): I64 = 1000000007 +def D.mult(): I64 = 31 +def D.seed(): I64 = 7 + +def D.vhash(v: D.Val): I64 = v match + case D.VSym(s) => Sym.hash(s) + case D.VInt(n) => ((n % D.modulus()) + D.modulus()) % D.modulus() + +def D.veq(a: D.Val, b: D.Val): Bool = a match + case D.VSym(x) => b match + case D.VSym(y) => Sym.eq(x, y) + case D.VInt(_) => false + case D.VInt(m) => b match + case D.VInt(n) => m == n + case D.VSym(_) => false + +def D.tupleEq(a: Coll.List[D.Val], b: Coll.List[D.Val]): Bool = a match + case Coll.Nil => b match + case Coll.Nil => true + case Coll.Cons(_, _) => false + case Coll.Cons(x, xt) => b match + case Coll.Nil => false + case Coll.Cons(y, yt) => if D.veq(x, y) then D.tupleEq(xt, yt) else false + +def D.thash(t: Coll.List[D.Val], h: I64): I64 = t match + case Coll.Nil => h + case Coll.Cons(v, rest) => D.thash(rest, (h * D.mult() + D.vhash(v)) % D.modulus()) + +def D.tupleHash(t: Coll.List[D.Val]): I64 = D.thash(t, D.seed()) + +// ── a relation: rows by tuple hash (dedup), by value hash for each probed column (ic), and all rows (scans); each list +// newest first. recent = rows of the last round, fresh = rows of this round ── +// a row and how it came to be (provenance, zhao-2020): an input fact (no round: it is older than every round), or a +// row made in round at by a compiled rule, which every row it makes shares. with the round stamp (a valid proof +// height: round r reads only older rows) D.why rebuilds a proof +enum D.Row: + case D.Input(t: Coll.List[D.Val]) + case D.Made(at: I64, rule: D.CRule, t: Coll.List[D.Val]) + +def D.tupleOf(row: D.Row): Coll.List[D.Val] = row match + case D.Input(t) => t + case D.Made(_, _, t) => t + +def D.stampOf(row: D.Row): I64 = row match + case D.Input(_) => D.inputRound() + case D.Made(at, _, _) => at + +enum D.Rel: + case D.Rel(ic: Coll.List[I64], set: Coll.BTree[Coll.List[D.Row]], cols: Coll.BTree[Coll.BTree[Coll.List[D.Row]]], all: Coll.List[D.Row], recent: I64, fresh: I64) + +def D.newRel {r: Region} (ic: Coll.List[I64]): D.Rel = D.Rel(ic, Coll.BTip, Coll.BTip, Coll.Nil, 0, 0) + +def D.bucket {r: Region} (m: Coll.BTree[Coll.List[D.Row]], h: I64): Coll.List[D.Row] = Coll.bTGetOr(m, h, Coll.Nil) + +def D.inRows(rows: Coll.List[D.Row], t: Coll.List[D.Val]): Bool = rows match + case Coll.Nil => false + case Coll.Cons(row, rest) => + val u = D.tupleOf(row) + if D.tupleEq(u, t) then true else D.inRows(rest, t) + +def D.has {r: Region} (rl: D.Rel, t: Coll.List[D.Val]): Bool = + val D.Rel(_, set, _, _, _, _) = rl + D.inRows(D.bucket(set, D.tupleHash(t)), t) + +// the values of t from column c on (no allocation): Nil when t has no column c +def D.from(t: Coll.List[D.Val], c: I64): Coll.List[D.Val] = + if c == 0 then t + else t match + case Coll.Nil => Coll.Nil + case Coll.Cons(_, rest) => D.from(rest, c - 1) + +// row added under each column of ic; a tuple without column c is not under c (no atom that probes c matches it) +def D.indexCols {r: Region} (cols: Coll.BTree[Coll.BTree[Coll.List[D.Row]]], row: D.Row, t: Coll.List[D.Val], ic: Coll.List[I64]): Coll.BTree[Coll.BTree[Coll.List[D.Row]]] = ic match + case Coll.Nil => cols + case Coll.Cons(c, rest) => D.from(t, c) match + case Coll.Nil => D.indexCols(cols, row, t, rest) + case Coll.Cons(v, _) => + val n = Coll.bFind(cols, c) + val col = Coll.bPushT(Coll.bValOr(n, c, Coll.BTip), D.vhash(v), row) + D.indexCols(if Coll.bIsNode(n) then Coll.bRep(cols, c, col) else Coll.bIns(cols, c, col), row, t, rest) + +// row added (the caller checked its tuple is new) +def D.add {r: Region} (rl: D.Rel, row: D.Row): D.Rel = + val D.Rel(ic, set, cols, all, rc, fr) = rl + val t = D.tupleOf(row) + val h = D.tupleHash(t) + D.Rel(ic, Coll.bPushT(set, h, row), D.indexCols(cols, row, t, ic), Coll.Cons(row, all), rc, fr + 1) + +// the rows an atom may match under a probe (a superset: the match checks values) +def D.cands {r: Region} (rl: D.Rel, p: D.Probe): Coll.List[D.Row] = + val D.Rel(_, _, cols, all, _, _) = rl + p match + case D.Scan => all + // no index on c: every row (in D.solve this means no rows yet; D.why binds the head first, so it can probe a + // column that the solve never probes) + case D.Col(c, h) => + val n = Coll.bFind(cols, c) + if Coll.bIsNode(n) then D.bucket(Coll.bValOr(n, c, Coll.BTip), h) else all + +// which rows an atom reads in round r: recent (round r-1), stable (older) or both; never rows of round r +enum D.Use: + case D.Stable + case D.Recent + case D.Full + +// ── rules compiled: relation names to ids (a program's relations, found once) ── +// a relation: its id and its name, made once when the name is first seen (D.internId) and shared by every atom of it, +// so an atom's id and name can not disagree, and a result that names a relation needs no lookup +enum D.RelRef: + case D.RelRef(id: I64, name: Sym.Sym) + +enum D.CAtom: + case D.CAtom(rel: D.RelRef, args: Coll.List[D.Arg]) + +// a compiled rule: the positive atoms in order, the negated ones (filters once the positives bound every variable); +// id = its position in the list given to D.solve, the name a proof shows; its join plans (below) +enum D.CRule: + case D.CRule(head: D.CAtom, body: Coll.List[D.CAtom], neg: Coll.List[D.CAtom], id: I64, plans: Coll.List[D.Plan]) + +// a join plan (semi-naive, as Souffle): for a body atom whose relation a rule derives, that atom first reading only +// the recent rows, so its few new rows bind the variables the others probe; then the other atoms in written order, +// those before it reading stable rows, those after it all older rows. each atom reads the same rows as in written +// order, so the derivations are the same; only the work changes. made once per rule: no position index exists +enum D.Plan: + case D.Plan(first: D.CAtom, rest: Coll.List[D.Step]) + +enum D.Step: + case D.ReadOld(a: D.CAtom) + case D.ReadAll(a: D.CAtom) + +// a rule with its atoms compiled, before its plans (they need every head of the program) +enum D.Draft: + case D.Draft(head: D.CAtom, body: Coll.List[D.CAtom], neg: Coll.List[D.CAtom], id: I64) + +// a value made while the name table grows +enum D.With [A: Type]: + case D.With(tab: Coll.List[D.RelRef], v: A) + +def D.refOf {r: Region} (tab: Coll.List[D.RelRef], s: Sym.Sym): Coll.Option[D.RelRef] = tab match + case Coll.Nil => Coll.None + case Coll.Cons(h, t) => + val D.RelRef(_, name) = h + if Sym.eq(name, s) then Coll.Some(h) else D.refOf(t, s) + +// the relation named s; a new name gets the next id and goes at the end of tab +def D.internId {r: Region} (tab: Coll.List[D.RelRef], s: Sym.Sym): D.With[D.RelRef] = D.refOf(tab, s) match + case Coll.Some(ref) => D.With(tab, ref) + case Coll.None => + val ref = D.RelRef(Coll.length(tab), s) + D.With(Coll.rev(Coll.Cons(ref, Coll.rev(tab))), ref) + +def D.idOfRef(ref: D.RelRef): I64 = + val D.RelRef(id, _) = ref + id + +def D.nameOfRef(ref: D.RelRef): Sym.Sym = + val D.RelRef(_, name) = ref + name + +def D.catom {r: Region} (tab: Coll.List[D.RelRef], a: D.Atom): D.With[D.CAtom] = + val D.Atom(rel, args) = a + val D.With(tab2, ref) = D.internId(tab, rel) + D.With(tab2, D.CAtom(ref, args)) + +enum D.Body: + case D.Body(pos: Coll.List[D.CAtom], neg: Coll.List[D.CAtom]) + +// the literals compiled in written order (so names get their ids in that order): the positive atoms, the negated ones +def D.cbody {r: Region} (tab: Coll.List[D.RelRef], ls: Coll.List[D.Lit], pos: Coll.List[D.CAtom], neg: Coll.List[D.CAtom]): D.With[D.Body] = ls match + case Coll.Nil => D.With(tab, D.Body(Coll.rev(pos), Coll.rev(neg))) + case Coll.Cons(l, rest) => l match + case D.Pos(a) => + val D.With(tab2, ca) = D.catom(tab, a) + D.cbody(tab2, rest, Coll.Cons(ca, pos), neg) + case D.Neg(a) => + val D.With(tab2, ca) = D.catom(tab, a) + D.cbody(tab2, rest, pos, Coll.Cons(ca, neg)) + +// rule i of rs has id i: its position in the list given to D.solve; the head's name gets its id first +def D.drafts {r: Region} (tab: Coll.List[D.RelRef], rs: Coll.List[D.Rule], i: I64, acc: Coll.List[D.Draft]): D.With[Coll.List[D.Draft]] = rs match + case Coll.Nil => D.With(tab, Coll.rev(acc)) + case Coll.Cons(rl, rest) => + val D.Rule(h, b) = rl + val D.With(tab2, ch) = D.catom(tab, h) + val D.With(tab3, bd) = D.cbody(tab2, b, Coll.Nil, Coll.Nil) + val D.Body(pos, neg) = bd + D.drafts(tab3, rest, i + 1, Coll.Cons(D.Draft(ch, pos, neg, i), acc)) + +def D.headIds {r: Region} (ds: Coll.List[D.Draft], acc: Coll.List[I64]): Coll.List[I64] = ds match + case Coll.Nil => acc + case Coll.Cons(d, rest) => + val D.Draft(h, _, _, _) = d + val D.CAtom(ref, _) = h + D.headIds(rest, Coll.Cons(D.idOfRef(ref), acc)) + +// each draft with its plans: one per body atom whose relation is a head (an input relation has recent rows only +// before the first pass, which reads in written order, so a plan for it would never run) +def D.crules {r: Region} (ds: Coll.List[D.Draft], heads: Coll.List[I64], acc: Coll.List[D.CRule]): Coll.List[D.CRule] = ds match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(d, rest) => + val D.Draft(h, body, neg, i) = d + D.crules(rest, heads, Coll.Cons(D.CRule(h, body, neg, i, D.plans(body, body, heads, 0, Coll.Nil)), acc)) + +// the plans for the atoms of xs (xs = the suffix of body from position j) +def D.plans {r: Region} (body: Coll.List[D.CAtom], xs: Coll.List[D.CAtom], heads: Coll.List[I64], j: I64, acc: Coll.List[D.Plan]): Coll.List[D.Plan] = xs match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(a, rest) => + val D.CAtom(ref, _) = a + if D.memberI(D.idOfRef(ref), heads) then D.plans(body, rest, heads, j + 1, Coll.Cons(D.Plan(a, D.steps(body, j, 0, Coll.Nil)), acc)) + else D.plans(body, rest, heads, j + 1, acc) + +// the other atoms of body around position j, in written order +def D.steps {r: Region} (body: Coll.List[D.CAtom], j: I64, i: I64, acc: Coll.List[D.Step]): Coll.List[D.Step] = body match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(a, rest) => + if i < j then D.steps(rest, j, i + 1, Coll.Cons(D.ReadOld(a), acc)) + else if i == j then D.steps(rest, j, i + 1, acc) + else D.steps(rest, j, i + 1, Coll.Cons(D.ReadAll(a), acc)) + +// ── joins ── +enum D.Bound: + case D.Unbound + case D.Is(v: D.Val) + +def D.argVal {r: Region} (env: Coll.IMap[D.Val], a: D.Arg): D.Bound = a match + case D.AVal(v) => D.Is(v) + case D.AVar(n) => Coll.node(env, n) match + case Coll.Tip => D.Unbound + case Coll.Bin(_, _, v, _, _) => D.Is(v) + +// how an atom finds its candidates under env: the bucket of its first bound column, else a scan +enum D.Probe: + case D.Scan + case D.Col(c: I64, h: I64) + +def D.probe {r: Region} (env: Coll.IMap[D.Val], args: Coll.List[D.Arg], c: I64): D.Probe = args match + case Coll.Nil => D.Scan + case Coll.Cons(a, rest) => D.argVal(env, a) match + case D.Is(v) => D.Col(c, D.vhash(v)) + case D.Unbound => D.probe(env, rest, c + 1) + +// env extended so args match t, or None +def D.matchT {r: Region} (env: Coll.IMap[D.Val], args: Coll.List[D.Arg], t: Coll.List[D.Val]): Coll.Option[Coll.IMap[D.Val]] = args match + case Coll.Nil => Coll.Some(env) + case Coll.Cons(a, rest) => t match + case Coll.Nil => Coll.None + case Coll.Cons(v, tr) => a match + case D.AVal(w) => if D.veq(v, w) then D.matchT(env, rest, tr) else Coll.None + case D.AVar(n) => Coll.node(env, n) match + case Coll.Tip => D.matchT(Coll.insert(env, n, v), rest, tr) + case Coll.Bin(_, _, w, _, _) => if D.veq(v, w) then D.matchT(env, rest, tr) else Coll.None + +// the extensions of e by the rows (newest first) that u reads in round r: rows of round r are skipped; recent ends at +// the first older row +def D.matchRows {r: Region} (e: Coll.IMap[D.Val], args: Coll.List[D.Arg], rows: Coll.List[D.Row], u: D.Use, rd: I64, out: Coll.List[Coll.IMap[D.Val]]): Coll.List[Coll.IMap[D.Val]] = rows match + case Coll.Nil => out + case Coll.Cons(row, rest) => + val at = D.stampOf(row) + val t = D.tupleOf(row) + if at >= rd then D.matchRows(e, args, rest, u, rd, out) + else + val take = u match + case D.Recent => at == rd - 1 + case D.Stable => at < rd - 1 + case D.Full => true + val stop = u match + case D.Recent => at < rd - 1 + case _ => false + if stop then out + else if !take then D.matchRows(e, args, rest, u, rd, out) + else D.matchT(e, args, t) match + case Coll.None => D.matchRows(e, args, rest, u, rd, out) + case Coll.Some(e2) => D.matchRows(e, args, rest, u, rd, Coll.Cons(e2, out)) + +def D.relOf {r: Region} (rels: Coll.IMap[D.Rel], id: I64): D.Rel = Coll.node(rels, id) match + case Coll.Tip => D.newRel(Coll.Nil) + case Coll.Bin(_, _, rl, _, _) => rl + +// every extension of each env by a row of the atom's relation that u reads +def D.joinAtom {r: Region} (rels: Coll.IMap[D.Rel], a: D.CAtom, u: D.Use, rd: I64, envs: Coll.List[Coll.IMap[D.Val]], out: Coll.List[Coll.IMap[D.Val]]): Coll.List[Coll.IMap[D.Val]] = envs match + case Coll.Nil => out + case Coll.Cons(e, rest) => + val D.CAtom(relRef, args) = a + val rel = D.idOfRef(relRef) + D.joinAtom(rels, a, u, rd, rest, D.matchRows(e, args, D.cands(D.relOf(rels, rel), D.probe(e, args, 0)), u, rd, out)) + +// a body evaluated in written order, every atom reading all older rows: the first round of a stratum, and D.why +def D.evalAll {r: Region} (rels: Coll.IMap[D.Rel], body: Coll.List[D.CAtom], rd: I64, envs: Coll.List[Coll.IMap[D.Val]]): Coll.List[Coll.IMap[D.Val]] = body match + case Coll.Nil => envs + case Coll.Cons(a, rest) => envs match + case Coll.Nil => Coll.Nil + case Coll.Cons(_, _) => D.evalAll(rels, rest, rd, D.joinAtom(rels, a, D.Full, rd, envs, Coll.Nil)) + +// a plan: its recent atom first, then its steps +def D.evalPlan {r: Region} (rels: Coll.IMap[D.Rel], p: D.Plan, rd: I64, envs: Coll.List[Coll.IMap[D.Val]]): Coll.List[Coll.IMap[D.Val]] = + val D.Plan(first, steps) = p + D.joinSteps(rels, steps, rd, D.joinAtom(rels, first, D.Recent, rd, envs, Coll.Nil)) + +def D.joinSteps {r: Region} (rels: Coll.IMap[D.Rel], steps: Coll.List[D.Step], rd: I64, envs: Coll.List[Coll.IMap[D.Val]]): Coll.List[Coll.IMap[D.Val]] = steps match + case Coll.Nil => envs + case Coll.Cons(s, rest) => envs match + case Coll.Nil => Coll.Nil + case Coll.Cons(_, _) => s match + case D.ReadOld(a) => D.joinSteps(rels, rest, rd, D.joinAtom(rels, a, D.Stable, rd, envs, Coll.Nil)) + case D.ReadAll(a) => D.joinSteps(rels, rest, rd, D.joinAtom(rels, a, D.Full, rd, envs, Coll.Nil)) + +def D.recentOf {r: Region} (rels: Coll.IMap[D.Rel], a: D.CAtom): I64 = + val D.CAtom(relRef, _) = a + val rel = D.idOfRef(relRef) + val D.Rel(_, _, _, _, rc, _) = D.relOf(rels, rel) + rc + +// ── heads ── +def D.inst {r: Region} (env: Coll.IMap[D.Val], args: Coll.List[D.Arg], acc: Coll.List[D.Val]): Coll.Option[Coll.List[D.Val]] = args match + case Coll.Nil => Coll.Some(Coll.rev(acc)) + case Coll.Cons(a, rest) => D.argVal(env, a) match + case D.Unbound => Coll.None + case D.Is(v) => D.inst(env, rest, Coll.Cons(v, acc)) + +// each env's head tuple added as a row of round rd, unless its relation has it (from any round) +def D.heads {r: Region} (rels: Coll.IMap[D.Rel], h: D.CAtom, rule: D.CRule, rd: I64, envs: Coll.List[Coll.IMap[D.Val]]): Coll.IMap[D.Rel] = envs match + case Coll.Nil => rels + case Coll.Cons(e, rest) => + val D.CAtom(relRef, args) = h + val rel = D.idOfRef(relRef) + D.inst(e, args, Coll.Nil) match + case Coll.None => D.heads(rels, h, rule, rd, rest) + case Coll.Some(t) => + val rl = D.relOf(rels, rel) + if D.has(rl, t) then D.heads(rels, h, rule, rd, rest) else D.heads(Coll.insert(rels, rel, D.add(rl, D.Made(rd, rule, t))), h, rule, rd, rest) + +// the envs whose negated atoms all fail: each tuple is in no round of its relation (a lower stratum, complete) +def D.negOk {r: Region} (rels: Coll.IMap[D.Rel], negs: Coll.List[D.CAtom], e: Coll.IMap[D.Val]): Bool = negs match + case Coll.Nil => true + case Coll.Cons(a, rest) => + val D.CAtom(relRef, args) = a + val rel = D.idOfRef(relRef) + D.inst(e, args, Coll.Nil) match + case Coll.None => false + case Coll.Some(t) => if D.has(D.relOf(rels, rel), t) then false else D.negOk(rels, rest, e) + +def D.filterNeg {r: Region} (rels: Coll.IMap[D.Rel], negs: Coll.List[D.CAtom], envs: Coll.List[Coll.IMap[D.Val]], out: Coll.List[Coll.IMap[D.Val]]): Coll.List[Coll.IMap[D.Val]] = envs match + case Coll.Nil => out + case Coll.Cons(e, rest) => D.filterNeg(rels, negs, rest, if D.negOk(rels, negs, e) then Coll.Cons(e, out) else out) + +// one rule in round rd, once per plan whose recent atom's relation has recent rows. the joins read the relations as +// the round began (rels0) +def D.fireAt {r: Region} (rels0: Coll.IMap[D.Rel], rl: D.CRule, ps: Coll.List[D.Plan], rd: I64, rels: Coll.IMap[D.Rel]): Coll.IMap[D.Rel] = ps match + case Coll.Nil => rels + case Coll.Cons(p, rest) => + val D.Plan(first, _) = p + val e0: Coll.IMap[D.Val] = Coll.Tip + if D.recentOf(rels0, first) == 0 then D.fireAt(rels0, rl, rest, rd, rels) + else D.fireAt(rels0, rl, rest, rd, D.fireWith(rels0, rl, D.evalPlan(rels0, p, rd, Coll.Cons(e0, Coll.Nil)), rd, rels)) + +// the body matches envs of rule rl, filtered by its negated atoms, as head rows of round rd +def D.fireWith {r: Region} (rels0: Coll.IMap[D.Rel], rl: D.CRule, envs: Coll.List[Coll.IMap[D.Val]], rd: I64, rels: Coll.IMap[D.Rel]): Coll.IMap[D.Rel] = + val D.CRule(h, _, neg, _, _) = rl + D.heads(rels, h, rl, rd, D.filterNeg(rels0, neg, envs, Coll.Nil)) + +// the first round of a stratum reads every row once; the next rounds run each rule's plans +enum D.Pass: + case D.FirstPass + case D.NextPass + +def D.fireAll {r: Region} (rels0: Coll.IMap[D.Rel], rs: Coll.List[D.CRule], rd: I64, pass: D.Pass, rels: Coll.IMap[D.Rel]): Coll.IMap[D.Rel] = rs match + case Coll.Nil => rels + case Coll.Cons(rl, rest) => + val D.CRule(_, body, _, _, plans) = rl + val e0: Coll.IMap[D.Val] = Coll.Tip + val rels2 = pass match + case D.FirstPass => D.fireWith(rels0, rl, D.evalAll(rels0, body, rd, Coll.Cons(e0, Coll.Nil)), rd, rels) + case D.NextPass => D.fireAt(rels0, rl, plans, rd, rels) + D.fireAll(rels0, rest, rd, pass, rels2) + +// a round ends: this round's rows become the recent ones; the number of new rows in all relations. a relation with no +// recent and no fresh rows is the same record after the round: it stays as it is in acc (which starts as rels) +def D.advance {r: Region} (rels: Coll.IMap[D.Rel], id: I64, k: I64, acc: Coll.IMap[D.Rel], news: I64): D.Next = + if id == k then D.Next(acc, news) + else + val D.Rel(ic, set, cols, all, rc, fr) = D.relOf(rels, id) + if rc == 0 && fr == 0 then D.advance(rels, id + 1, k, acc, news) + else D.advance(rels, id + 1, k, Coll.insert(acc, id, D.Rel(ic, set, cols, all, fr, 0)), news + fr) + +enum D.Next: + case D.Next(rels: Coll.IMap[D.Rel], news: I64) + +// the relations after a stratum, and the next round number (stamps keep growing across strata) +enum D.Stage: + case D.Stage(rels: Coll.IMap[D.Rel], rd: I64) + +// the input facts are rows of round D.inputRound(); the rounds that derive rows come after it +def D.inputRound(): I64 = 0 +def D.firstRound(): I64 = D.inputRound() + 1 + +// round rd reads rows of rounds < rd +def D.rounds {r: Region} (rs: Coll.List[D.CRule], rels: Coll.IMap[D.Rel], rd: I64, k: I64, pass: D.Pass): D.Stage = + val fired = D.fireAll(rels, rs, rd, pass, rels) + val D.Next(rels2, news) = D.advance(fired, 0, k, fired, 0) + if news == 0 then D.Stage(rels2, rd + 1) else D.rounds(rs, rels2, rd + 1, k, D.NextPass) + +// ── strata: a head's stratum is at least each positive body relation's, above each negated one's ── +def D.stOf(st: Coll.IMap[I64], id: I64): I64 = Coll.node(st, id) match + case Coll.Tip => 0 + case Coll.Bin(_, _, s, _, _) => s + +def D.maxSt(st: Coll.IMap[I64], as: Coll.List[D.CAtom], plus: I64, m: I64): I64 = as match + case Coll.Nil => m + case Coll.Cons(a, rest) => + val D.CAtom(relRef, _) = a + val rel = D.idOfRef(relRef) + val s = D.stOf(st, rel) + plus + D.maxSt(st, rest, plus, if s > m then s else m) + +enum D.Raised: + case D.Raised(st: Coll.IMap[I64], changed: Bool) + +def D.raiseAll {r: Region} (rs: Coll.List[D.CRule], st: Coll.IMap[I64], changed: Bool): D.Raised = rs match + case Coll.Nil => D.Raised(st, changed) + case Coll.Cons(rl, rest) => + val D.CRule(h, body, neg, _, _) = rl + val D.CAtom(hrRef, _) = h + val hr = D.idOfRef(hrRef) + val m = D.maxSt(st, neg, 1, D.maxSt(st, body, 0, 0)) + if m > D.stOf(st, hr) then D.raiseAll(rest, Coll.insert(st, hr, m), true) else D.raiseAll(rest, st, changed) + +def D.topOf(st: Coll.IMap[I64], id: I64, k: I64, m: I64): I64 = if id == k then m else D.topOf(st, id + 1, k, if D.stOf(st, id) > m then D.stOf(st, id) else m) + +// raise until no stratum changes, or one passes k (a cycle through negation: a stratification has at most k strata) +def D.strata {r: Region} (rs: Coll.List[D.CRule], st: Coll.IMap[I64], k: I64): Coll.IMap[I64] = + val D.Raised(st2, changed) = D.raiseAll(rs, st, false) + if !changed || D.topOf(st2, 0, k, 0) > k then st2 else D.strata(rs, st2, k) + +// the head with the smallest id whose stratum passed k (only heads are ever raised), or None: no cycle through negation +def D.overHead {r: Region} (rs: Coll.List[D.CRule], st: Coll.IMap[I64], k: I64, best: Coll.Option[D.CAtom]): Coll.Option[Sym.Sym] = rs match + case Coll.Nil => best match + case Coll.None => Coll.None + case Coll.Some(a) => + val D.CAtom(nameRef, _) = a + val name = D.nameOfRef(nameRef) + Coll.Some(name) + case Coll.Cons(rl, rest) => + val D.CRule(h, _, _, _, _) = rl + val D.CAtom(hrRef, _) = h + val hr = D.idOfRef(hrRef) + if D.stOf(st, hr) <= k then D.overHead(rest, st, k, best) else D.overHead(rest, st, k, D.smaller(h, best)) + +def D.smaller {r: Region} (h: D.CAtom, best: Coll.Option[D.CAtom]): Coll.Option[D.CAtom] = best match + case Coll.None => Coll.Some(h) + case Coll.Some(b) => + val D.CAtom(hrRef, _) = h + val hr = D.idOfRef(hrRef) + val D.CAtom(brRef, _) = b + val br = D.idOfRef(brRef) + if hr < br then Coll.Some(h) else best + +def D.rulesAt {r: Region} (rs: Coll.List[D.CRule], st: Coll.IMap[I64], s: I64, acc: Coll.List[D.CRule]): Coll.List[D.CRule] = rs match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(rl, rest) => + val D.CRule(h, _, _, _, _) = rl + val D.CAtom(hrRef, _) = h + val hr = D.idOfRef(hrRef) + D.rulesAt(rest, st, s, if D.stOf(st, hr) == s then Coll.Cons(rl, acc) else acc) + +def D.runStrata {r: Region} (rs: Coll.List[D.CRule], st: Coll.IMap[I64], s: I64, top: I64, rels: Coll.IMap[D.Rel], rd: I64, k: I64): Coll.IMap[D.Rel] = + if s > top then rels + else + val D.Stage(rels2, rd2) = D.rounds(D.rulesAt(rs, st, s, Coll.Nil), rels, rd, k, D.FirstPass) + D.runStrata(rs, st, s + 1, top, rels2, rd2, k) + +// ── safety: every head variable and every variable of a negated atom occurs in a positive atom ── +def D.allIn(vs: Coll.List[I64], bound: Coll.List[I64]): Bool = vs match + case Coll.Nil => true + case Coll.Cons(v, rest) => if D.memberI(v, bound) then D.allIn(rest, bound) else false + +def D.atomsVars {r: Region} (as: Coll.List[D.CAtom], acc: Coll.List[I64]): Coll.List[I64] = as match + case Coll.Nil => acc + case Coll.Cons(a, rest) => + val D.CAtom(_, args) = a + D.atomsVars(rest, D.argVars(args, acc)) + +// the head relation of the first unsafe rule, or None: every rule is safe +def D.firstUnsafe {r: Region} (rs: Coll.List[D.CRule]): Coll.Option[Sym.Sym] = rs match + case Coll.Nil => Coll.None + case Coll.Cons(rl, rest) => + val D.CRule(h, body, neg, _, _) = rl + val D.CAtom(nameRef, hargs) = h + val name = D.nameOfRef(nameRef) + val bound = D.atomsVars(body, Coll.Nil) + if D.allIn(D.argVars(hargs, Coll.Nil), bound) && D.allIn(D.atomsVars(neg, Coll.Nil), bound) then D.firstUnsafe(rest) else Coll.Some(name) + + +// ── which columns need an index: per body atom (variables bound left to right, constants bound) its first bound +// column, the one D.probe reads; no other column is ever indexed ── +def D.memberI(v: I64, xs: Coll.List[I64]): Bool = xs match + case Coll.Nil => false + case Coll.Cons(h, t) => if h == v then true else D.memberI(v, t) + +// the first column bound under bound (a constant, or a bound variable), or None: the atom is scanned +def D.firstBound {r: Region} (args: Coll.List[D.Arg], bound: Coll.List[I64], c: I64): Coll.Option[I64] = args match + case Coll.Nil => Coll.None + case Coll.Cons(a, rest) => a match + case D.AVal(_) => Coll.Some(c) + case D.AVar(n) => if D.memberI(n, bound) then Coll.Some(c) else D.firstBound(rest, bound, c + 1) + +def D.argVars {r: Region} (args: Coll.List[D.Arg], acc: Coll.List[I64]): Coll.List[I64] = args match + case Coll.Nil => acc + case Coll.Cons(a, rest) => a match + case D.AVal(_) => D.argVars(rest, acc) + case D.AVar(n) => D.argVars(rest, Coll.Cons(n, acc)) + +def D.colsOf {r: Region} (ics: Coll.IMap[Coll.List[I64]], rel: I64): Coll.List[I64] = Coll.node(ics, rel) match + case Coll.Tip => Coll.Nil + case Coll.Bin(_, _, cs, _, _) => cs + +def D.probesOf {r: Region} (body: Coll.List[D.CAtom], bound: Coll.List[I64], ics: Coll.IMap[Coll.List[I64]]): Coll.IMap[Coll.List[I64]] = body match + case Coll.Nil => ics + case Coll.Cons(a, rest) => + val D.CAtom(_, args) = a + D.probesOf(rest, D.argVars(args, bound), D.probeAtom(a, bound, ics)) + +// the column atom a probes under bound, recorded for its relation +def D.probeAtom {r: Region} (a: D.CAtom, bound: Coll.List[I64], ics: Coll.IMap[Coll.List[I64]]): Coll.IMap[Coll.List[I64]] = + val D.CAtom(relRef, args) = a + val rel = D.idOfRef(relRef) + val old = D.colsOf(ics, rel) + D.firstBound(args, bound, 0) match + case Coll.None => ics + case Coll.Some(c) => if D.memberI(c, old) then ics else Coll.insert(ics, rel, Coll.Cons(c, old)) + +// the probes of a plan: its recent atom with nothing bound, then its steps in order +def D.probesPlan {r: Region} (p: D.Plan, ics: Coll.IMap[Coll.List[I64]]): Coll.IMap[Coll.List[I64]] = + val D.Plan(first, steps) = p + val D.CAtom(_, args) = first + D.probesSteps(steps, D.argVars(args, Coll.Nil), D.probeAtom(first, Coll.Nil, ics)) + +def D.probesSteps {r: Region} (steps: Coll.List[D.Step], bound: Coll.List[I64], ics: Coll.IMap[Coll.List[I64]]): Coll.IMap[Coll.List[I64]] = steps match + case Coll.Nil => ics + case Coll.Cons(s, rest) => + val a: D.CAtom = s match + case D.ReadOld(x) => x + case D.ReadAll(x) => x + val D.CAtom(_, args) = a + D.probesSteps(rest, D.argVars(args, bound), D.probeAtom(a, bound, ics)) + +def D.probesPlans {r: Region} (ps: Coll.List[D.Plan], ics: Coll.IMap[Coll.List[I64]]): Coll.IMap[Coll.List[I64]] = ps match + case Coll.Nil => ics + case Coll.Cons(p, rest) => D.probesPlans(rest, D.probesPlan(p, ics)) + +// the probes of every rule: written order (the first pass, D.why) and each plan +def D.probesAll {r: Region} (rs: Coll.List[D.CRule], ics: Coll.IMap[Coll.List[I64]]): Coll.IMap[Coll.List[I64]] = rs match + case Coll.Nil => ics + case Coll.Cons(rl, rest) => + val D.CRule(_, body, _, _, plans) = rl + D.probesAll(rest, D.probesPlans(plans, D.probesOf(body, Coll.Nil, ics))) + +def D.initRels {r: Region} (ics: Coll.IMap[Coll.List[I64]], id: I64, k: I64, acc: Coll.IMap[D.Rel]): Coll.IMap[D.Rel] = + if id == k then acc + else D.initRels(ics, id + 1, k, Coll.insert(acc, id, D.newRel(D.colsOf(ics, id)))) + +// ── the model ── +enum D.Model: + case D.Model(tab: Coll.List[D.RelRef], rels: Coll.IMap[D.Rel]) + +// the input facts as rows of the input round; a relation that only facts name gets its id here +def D.load {r: Region} (tab: Coll.List[D.RelRef], fs: Coll.List[D.Fact], rels: Coll.IMap[D.Rel]): D.With[Coll.IMap[D.Rel]] = fs match + case Coll.Nil => D.With(tab, rels) + case Coll.Cons(f, rest) => + val D.Fact(rel, vals) = f + val D.With(tab2, ref) = D.internId(tab, rel) + val id = D.idOfRef(ref) + val rl = D.relOf(rels, id) + D.load(tab2, rest, if D.has(rl, vals) then rels else Coll.insert(rels, id, D.add(rl, D.Input(vals)))) + +// a program's result: its model, or why it is not a program (an unsafe rule, a cycle through negation) +enum D.Result: + case D.Solved(m: D.Model) + case D.Unsafe(rel: Sym.Sym) + case D.NegCycle(rel: Sym.Sym) + +// the model of rules over facts: strata in order, each to its fixpoint. ids: the rules' names in written order, then +// the names only facts use +def D.solve {r: Region} (rules: Coll.List[D.Rule], facts: Coll.List[D.Fact]): D.Result = + val D.With(tab1, ds) = D.drafts(Coll.Nil, rules, 0, Coll.Nil) + val crs = D.crules(ds, D.headIds(ds, Coll.Nil), Coll.Nil) + D.firstUnsafe(crs) match + case Coll.Some(bad) => D.Unsafe(bad) + case Coll.None => + val D.With(tab, rels0) = D.load(tab1, facts, D.initRels(D.probesAll(crs, Coll.Tip), 0, Coll.length(tab1), Coll.Tip)) + val k = Coll.length(tab) + val st = D.strata(crs, Coll.Tip, k) + D.overHead(crs, st, k, Coll.None) match + case Coll.Some(cyc) => D.NegCycle(cyc) + case Coll.None => + val D.Next(rels, _) = D.advance(rels0, 0, k, rels0, 0) + D.Solved(D.Model(tab, D.runStrata(crs, st, 0, D.topOf(st, 0, k, 0), rels, D.firstRound(), k))) + +def D.rowsOf {r: Region} (rows: Coll.List[D.Row], acc: Coll.List[Coll.List[D.Val]]): Coll.List[Coll.List[D.Val]] = rows match + case Coll.Nil => acc + case Coll.Cons(row, rest) => + val t = D.tupleOf(row) + D.rowsOf(rest, Coll.Cons(t, acc)) + +// the facts of rel in a model, oldest first (none when the model has no relation rel) +def D.tuples {r: Region} (m: D.Model, rel: Sym.Sym): Coll.List[Coll.List[D.Val]] = + val D.Model(tab, rels) = m + D.refOf(tab, rel) match + case Coll.None => Coll.Nil + case Coll.Some(ref) => + val D.Rel(_, _, _, all, _, _) = D.relOf(rels, D.idOfRef(ref)) + D.rowsOf(all, Coll.Nil) + +// ── provenance (vic-m5r.33, vic/c/dprov-design.md): the proof of a fact ── +enum D.Proof: + case D.Given(rel: Sym.Sym, t: Coll.List[D.Val]) + case D.ByRule(rule: I64, rel: Sym.Sym, t: Coll.List[D.Val], premises: Coll.List[D.Proof]) + // a negated premise: the atom is not in its relation, a complete lower stratum + case D.Absent(rel: Sym.Sym, t: Coll.List[D.Val]) + +def D.rowIn {r: Region} (rows: Coll.List[D.Row], t: Coll.List[D.Val]): Coll.Option[D.Row] = rows match + case Coll.Nil => Coll.None + case Coll.Cons(row, rest) => if D.tupleEq(D.tupleOf(row), t) then Coll.Some(row) else D.rowIn(rest, t) + +// the row of t in rl, found through the dedup set +def D.findRow {r: Region} (rl: D.Rel, t: Coll.List[D.Val]): Coll.Option[D.Row] = + val D.Rel(_, set, _, _, _, _) = rl + D.rowIn(D.bucket(set, D.tupleHash(t)), t) + +// the proof of t in relation ref: an input is given; a made row is proved by the rule it points to, with the first +// body match among rows of smaller stamps, so the recursion ends. in a stratum that reads only inputs a row's stamp +// is its minimal proof height, and so is the height of this proof (zhao-2020 txt:575-576); across strata it can be +// taller (bead vic-m5r.35) +def D.proofOf {r: Region} (rels: Coll.IMap[D.Rel], ref: D.RelRef, t: Coll.List[D.Val]): Coll.Option[D.Proof] = + val D.RelRef(id, rel) = ref + D.findRow(D.relOf(rels, id), t) match + case Coll.None => Coll.None + case Coll.Some(row) => row match + case D.Input(_) => Coll.Some(D.Given(rel, t)) + case D.Made(at, rl, _) => D.byRule(rels, rl, rel, at, t) + +def D.byRule {r: Region} (rels: Coll.IMap[D.Rel], rl: D.CRule, rel: Sym.Sym, at: I64, t: Coll.List[D.Val]): Coll.Option[D.Proof] = + val D.CRule(h, body, neg, i, _) = rl + val D.CAtom(_, hargs) = h + val e0: Coll.IMap[D.Val] = Coll.Tip + D.matchT(e0, hargs, t) match + case Coll.None => Coll.None + case Coll.Some(e) => D.evalAll(rels, body, at, Coll.Cons(e, Coll.Nil)) match + case Coll.Nil => Coll.None + case Coll.Cons(e2, _) => D.premises(rels, body, neg, e2, Coll.Nil) match + case Coll.None => Coll.None + case Coll.Some(ps) => Coll.Some(D.ByRule(i, rel, t, ps)) + +// the proofs of the positive atoms xs under e, in body order, then the negated atoms negs as absent +def D.premises {r: Region} (rels: Coll.IMap[D.Rel], xs: Coll.List[D.CAtom], negs: Coll.List[D.CAtom], e: Coll.IMap[D.Val], acc: Coll.List[D.Proof]): Coll.Option[Coll.List[D.Proof]] = xs match + case Coll.Nil => D.absents(negs, e, acc) + case Coll.Cons(a, rest) => + val D.CAtom(ref, args) = a + D.inst(e, args, Coll.Nil) match + case Coll.None => Coll.None + case Coll.Some(t) => D.proofOf(rels, ref, t) match + case Coll.None => Coll.None + case Coll.Some(p) => D.premises(rels, rest, negs, e, Coll.Cons(p, acc)) + +def D.absents {r: Region} (negs: Coll.List[D.CAtom], e: Coll.IMap[D.Val], acc: Coll.List[D.Proof]): Coll.Option[Coll.List[D.Proof]] = negs match + case Coll.Nil => Coll.Some(Coll.rev(acc)) + case Coll.Cons(a, rest) => + val D.CAtom(ref, args) = a + D.inst(e, args, Coll.Nil) match + case Coll.None => Coll.None + case Coll.Some(t) => D.absents(rest, e, Coll.Cons(D.Absent(D.nameOfRef(ref), t), acc)) + +// why tuple t of rel holds in m: its proof tree down to input facts, or None when t is not in m +def D.why {r: Region} (m: D.Model, rel: Sym.Sym, t: Coll.List[D.Val]): Coll.Option[D.Proof] = + val D.Model(tab, rels) = m + D.refOf(tab, rel) match + case Coll.None => Coll.None + case Coll.Some(ref) => D.proofOf(rels, ref, t) diff --git a/bench/corpus/s2/elab.srs b/bench/corpus/s2/elab.srs new file mode 100644 index 00000000..05cc450c --- /dev/null +++ b/bench/corpus/s2/elab.srs @@ -0,0 +1,63 @@ +// s2 self-host rung T3 (vic/c/s2-selfhost.md "T3 design"): the elaborated program, what mono and emit read. Ty.expr +// builds it while it infers, so the two cannot disagree. a term keeps its vars until mono reifies it with the final +// substitution. +enum El.Expr: + case El.Int(line: I64, v: I64) + case El.Bool(line: I64, v: Bool) + case El.Str(line: I64, s: Str) + case El.Unit(line: I64) + // a name bound in the fn: a param, a {} binder, a val, var, handle or pattern binder + case El.Local(line: I64, x: Sym.Sym) + // f[targs]{caps}(args): the instance and the caller's capability for each protocol {} binder ({r: Region}, ...), in written order + case El.CallFn(line: I64, f: Sym.Sym, targs: Coll.List[K.Term], caps: Coll.List[Sym.Sym], args: Coll.List[El.Expr]) + // a constructor: its enum at targs, allocated where at says + case El.New(line: I64, en: Sym.Sym, targs: Coll.List[K.Term], c: Sym.Sym, at: El.Alloc, args: Coll.List[El.Expr]) + case El.Nullary(line: I64, en: Sym.Sym, targs: Coll.List[K.Term], c: Sym.Sym) + // recv.op(args): an op of the capability recv's protocol, or a trait method of {} evidence recv + case El.Op(line: I64, recv: Sym.Sym, ty: K.Term, op: Sym.Sym, args: Coll.List[El.Expr]) + case El.Bin(line: I64, op: Ast.BinOp, l: El.Expr, rhs: El.Expr) + case El.Un(line: I64, op: Ast.UnOp, e: El.Expr) + case El.If(line: I64, c: El.Expr, t: El.Expr, e: El.Expr) + // scrut is an enum at targs + case El.Match(line: I64, s: El.Expr, en: K.Term, arms: Coll.List[El.Arm]) + case El.Block(line: I64, stmts: Coll.List[El.Stmt], last: El.Expr) + case El.While(line: I64, c: El.Expr, body: El.Expr) + case El.Assign(line: I64, x: Sym.Sym, e: El.Expr) + // an expression that did not type (its clash is in the result): emit never runs on a program with clashes + case El.Bad(line: I64) + +enum El.Arm: + case El.Arm(line: I64, p: Ast.Pat, body: El.Expr) + +enum El.Stmt: + // a val or var with its type (emit declares the C local with it) + case El.Val(line: I64, x: Sym.Sym, ty: K.Term, mut: Bool, e: El.Expr) + case El.Handle(line: I64, x: Sym.Sym, h: Sym.Sym, args: Coll.List[El.Expr]) + case El.Do(e: El.Expr) + +// a def: its [] binders (instantiated by mono), its protocol {} binders (leading C params), params with types +enum El.Param: + case El.Param(x: Sym.Sym, ty: K.Term) + +enum El.Fn: + case El.Fn(line: I64, name: Sym.Sym, tparams: Coll.List[Sym.Sym], caps: Coll.List[Sym.Sym], params: Coll.List[El.Param], ret: K.Term, body: El.Body) + +// a def has C, an extern is a C symbol of the runtime, a spec body is compile time only (no C) +enum El.Body: + case El.Def(e: El.Expr) + case El.Extern + case El.Spec(e: El.Expr) + +// handler name for protocol proto: its fns (init, then the ops) +enum El.Handler: + case El.Handler(name: Sym.Sym, proto: Sym.Sym, fns: Coll.List[El.Fn]) + +// given [tparams] {ev} head: the trait methods for the head's args (a call through {} evidence of a ground goal type is +// a static call to the instance of the given picked for it) +enum El.Given: + case El.Given(tparams: Coll.List[Sym.Sym], ev: Coll.List[Sym.Sym], head: K.Term, fns: Coll.List[El.Fn]) + +// where a constructor allocates: in the Region capability region, or nowhere at run time (a spec body: compile time only) +enum El.Alloc: + case El.In(region: Sym.Sym) + case El.Comptime diff --git a/bench/corpus/s2/emit.srs b/bench/corpus/s2/emit.srs new file mode 100644 index 00000000..ab997cf9 --- /dev/null +++ b/bench/corpus/s2/emit.srs @@ -0,0 +1,1118 @@ +// s2 self-host rung B2 (vic/c/s2-emit-spec.md): the C of an elaborated program at its mono instances, as s1/emit.srs +// prints it. the input typed with no clash, so every name the lookups read is declared. one C file to stdout. + +// a case: its tag (declaration index), its enum and its fields +enum Emit.CaseAt: + case Emit.CaseAt(tag: I64, en: Ast.Enum, c: Ast.Case) + +// how a constructor allocates: an inline bump when the program has the Arena handler (rt/srs_rt.c:24-25), else the vtable +enum Emit.Alloc: + case Emit.Inline + case Emit.VTable + +// the declarations emit reads, by name +enum Emit.Cx: + case Emit.Cx(s: Coll.IMap[K.Term], fns: Coll.SMap[El.Fn], cases: Coll.SMap[Emit.CaseAt], enums: Coll.SMap[Ast.Enum], protos: Coll.SMap[Ast.Proto], hprotos: Coll.SMap[Sym.Sym], alloc: Emit.Alloc, nominal: Coll.SMap[K.Term]) + +// a C local: a param p_x, or a binding v_x_n (n = the number of locals bound before it) +enum Emit.Name: + case Emit.P(x: Sym.Sym) + case Emit.L(x: Sym.Sym, n: I64) + +enum Emit.Env: + case Emit.Env(vs: Coll.List[Emit.Name], n: I64) + +// a capability opened by a handle: its protocol's drop op runs at the end of the block if it is still live +enum Emit.Drop: + case Emit.Drop(c: Emit.Name, proto: Sym.Sym) + +// a C param: a capability (srs_cap*) or a value of a ground type +enum Emit.Slot: + case Emit.SCap(x: Sym.Sym) + case Emit.SVal(x: Sym.Sym, t: K.Term) + +// the fn being printed: name and ground type args (a self call with them in tail position is a jump), the binder +// substitution, the C params, the ground result +enum Emit.Fi: + case Emit.Fi(self: Sym.Sym, targs: Coll.List[K.Term], sub: Coll.List[Ty.Bind], slots: Coll.List[Emit.Slot], ret: K.Term) + +// tail position: a self call there is a jump +enum Emit.Pos: + case Emit.Tail + case Emit.Inner + +// what a signature names: a def instance f_, a runtime symbol, a handler fn h__, a given fn g__ +enum Emit.Kind: + case Emit.KDef + case Emit.KExtern + case Emit.KHandler(h: Sym.Sym) + case Emit.KGiven(head: K.Term) + +// args after the first print a comma before them +enum Emit.Sep: + case Emit.First + case Emit.Comma + +// the test of a match arm: a `_` arm always holds, a case arm tests the tag +enum Emit.Guard: + case Emit.Always + case Emit.Tag(tag: I64) + +// a declaration's layout (enum struct, fn prototype) or its code (nullary statics, fn body) +enum Emit.Part: + case Emit.Layout + case Emit.Code + +// ── the declarations by name ── +def Emit.cxOf {r: Region} (ds: Coll.List[Ast.Decl], s: Coll.IMap[K.Term], fs: Coll.List[El.Fn]): Emit.Cx = + Emit.cxDecls(ds, Emit.Cx(s, Emit.fnMap(fs, Coll.sEmpty()), Coll.sEmpty(), Coll.sEmpty(), Coll.sEmpty(), Coll.sEmpty(), Emit.VTable, Coll.sEmpty())) + +def Emit.fnMap {r: Region} (fs: Coll.List[El.Fn], m: Coll.SMap[El.Fn]): Coll.SMap[El.Fn] = fs match + case Coll.Nil => m + case Coll.Cons(f, rest) => + val El.Fn(_, n, _, _, _, _, _) = f + Emit.fnMap(rest, Coll.sInsert(m, n, f)) + +def Emit.cxDecls {r: Region} (ds: Coll.List[Ast.Decl], cx: Emit.Cx): Emit.Cx = ds match + case Coll.Nil => cx + case Coll.Cons(d, rest) => + val Emit.Cx(s, fns, cs, es, ps, hp, al, nm) = cx + d match + case Ast.DEnum(e) => + val Ast.Enum(_, n, _, cases) = e + Emit.cxDecls(rest, Emit.Cx(s, fns, Emit.caseMap(cases, e, 0, cs), Coll.sInsert(es, n, e), ps, hp, al, nm)) + case Ast.DProto(p) => + val Ast.Proto(_, n, _, _, _, _, _, _) = p + Emit.cxDecls(rest, Emit.Cx(s, fns, cs, es, Coll.sInsert(ps, n, p), hp, al, nm)) + case Ast.DHandler(h) => + val Ast.Handler(_, n, p, _) = h + Emit.cxDecls(rest, Emit.Cx(s, fns, cs, es, ps, Coll.sInsert(hp, n, p), if rt_str_eq(Sym.str(n), "Arena") then Emit.Inline else al, nm)) + // a type with <> facts stays nominal through typing (s2/tlevel.srs Tl.nominal): in C it is its body's type + case Ast.DType(td) => + val Ast.TypeDecl(_, n, _, _, body) = td + body match + case Ast.Alias(t) => Emit.cxDecls(rest, Emit.Cx(s, fns, cs, es, ps, hp, al, Coll.sInsert(nm, n, Ty.term(t, Coll.Nil)))) + case _ => Emit.cxDecls(rest, cx) + case _ => Emit.cxDecls(rest, cx) + +def Emit.caseMap {r: Region} (cs: Coll.List[Ast.Case], e: Ast.Enum, i: I64, m: Coll.SMap[Emit.CaseAt]): Coll.SMap[Emit.CaseAt] = cs match + case Coll.Nil => m + case Coll.Cons(c, rest) => + val Ast.Case(_, n, _) = c + Emit.caseMap(rest, e, i + 1, Coll.sInsert(m, n, Emit.CaseAt(i, e, c))) + +def Emit.isProto {r: Region} (cx: Emit.Cx, n: Sym.Sym): Bool = + val Emit.Cx(_, _, _, _, ps, _, _, _) = cx + Coll.sLookup(ps, n) match + case Coll.Some(_) => true + case Coll.None => false + +def Emit.caseAt {r: Region} (cx: Emit.Cx, c: Sym.Sym): Coll.Option[Emit.CaseAt] = + val Emit.Cx(_, _, cs, _, _, _, _, _) = cx + Coll.sLookup(cs, c) + +def Emit.subst(cx: Emit.Cx): Coll.IMap[K.Term] = + val Emit.Cx(s, _, _, _, _, _, _, _) = cx + s + +def Emit.grAll {r: Region} (cx: Emit.Cx, fi: Emit.Fi, ts: Coll.List[K.Term]): Coll.List[K.Term] = + val Emit.Fi(_, _, sub, _, _) = fi + Mono.groundAll(Emit.subst(cx), sub, ts, Coll.Nil) + +def Emit.gr {r: Region} (cx: Emit.Cx, fi: Emit.Fi, t: K.Term): K.Term = + val Emit.Fi(_, _, sub, _, _) = fi + Mono.ground(Emit.subst(cx), sub, t) + +// ── names (spec sec 2) ── +// x with each `.` as `__` +def Emit.id(x: Sym.Sym): Unit = Emit.idFrom(Sym.str(x), 0, 0, rt_str_len(Sym.str(x))) + +def Emit.idFrom(s: Str, b: I64, i: I64, n: I64): Unit = + if i == n then rt_print(rt_str_slice(s, b, i)) + else if rt_str_at(s, i) == 46 then + rt_print(rt_str_slice(s, b, i)) + rt_print("__") + Emit.idFrom(s, i + 1, i + 1, n) + else Emit.idFrom(s, b, i + 1, n) + +def Emit.mangle(t: K.Term): Unit = t match + case K.Con(n, args) => + Emit.id(n) + args match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print("_") + rt_print_i64(Coll.length(args)) + Emit.mangleArgs(args) + case K.Int(v) => rt_print_i64(v) + case K.Var(v) => + rt_print("V") + rt_print_i64(v) + +def Emit.mangleArgs(ts: Coll.List[K.Term]): Unit = ts match + case Coll.Nil => () + case Coll.Cons(t, rest) => + rt_print("_") + Emit.mangle(t) + Emit.mangleArgs(rest) + +// an instance suffix: nothing for no type args +def Emit.suffix(ts: Coll.List[K.Term]): Unit = ts match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print("_") + Emit.mangleArgs(ts) + +def Emit.enumName(n: Sym.Sym, args: Coll.List[K.Term]): Unit = + Emit.id(n) + Emit.suffix(args) + +def Emit.cname(v: Emit.Name): Unit = v match + case Emit.P(x) => + rt_print("p_") + Emit.id(x) + case Emit.L(x, n) => + rt_print("v_") + Emit.id(x) + rt_print("_") + rt_print_i64(n) + +// the innermost local named x +def Emit.local(vs: Coll.List[Emit.Name], x: Sym.Sym): Unit = vs match + case Coll.Nil => Emit.id(x) + case Coll.Cons(v, rest) => if Sym.eq(Emit.nameOf(v), x) then Emit.cname(v) else Emit.local(rest, x) + +def Emit.nameOf(v: Emit.Name): Sym.Sym = v match + case Emit.P(x) => x + case Emit.L(x, _) => x + +def Emit.vs(env: Emit.Env): Coll.List[Emit.Name] = + val Emit.Env(vs, _) = env + vs + +def Emit.envN(env: Emit.Env): I64 = + val Emit.Env(_, n) = env + n + +def Emit.bind {r: Region} (env: Emit.Env, x: Sym.Sym): Emit.Env = + val Emit.Env(vs, n) = env + Emit.Env(Coll.Cons(Emit.L(x, n), vs), n + 1) + +// ── types (spec sec 3): a ground term ── +def Emit.ctype {r: Region} (cx: Emit.Cx, t: K.Term): Unit = t match + case K.Con(n, args) => + val x = Sym.str(n) + if rt_str_eq(x, "I64") || rt_str_eq(x, "Unit") then rt_print("int64_t") + else if rt_str_eq(x, "Bool") then rt_print("bool") + else if rt_str_eq(x, "Str") then rt_print("srs_str") + else if rt_str_eq(x, "Ptr") then rt_print("void*") + else if Emit.isProto(cx, n) then rt_print("srs_cap*") + else Emit.nominalOf(cx, n) match + case Coll.Some(b) => Emit.ctype(cx, b) + case Coll.None => + rt_print("struct E_") + Emit.enumName(n, args) + rt_print("*") + case _ => rt_print("int64_t") + +def Emit.nominalOf {r: Region} (cx: Emit.Cx, n: Sym.Sym): Coll.Option[K.Term] = + val Emit.Cx(_, _, _, _, _, _, _, nm) = cx + Coll.sLookup(nm, n) + +// ── expressions (spec sec 4) ── +def Emit.ex {r: Region} (cx: Emit.Cx, fi: Emit.Fi, env: Emit.Env, pos: Emit.Pos, e: El.Expr): Unit = e match + case El.Int(_, v) => + rt_print("((int64_t)") + rt_print_i64(v) + rt_print(")") + case El.Bool(_, v) => rt_print(if v then "true" else "false") + case El.Str(_, s) => + rt_print("((srs_str){(const uint8_t*)\"") + rt_print(s) + rt_print("\", ") + rt_print_i64(Emit.unescLen(s, 0, 0)) + rt_print("})") + case El.Unit(_) => rt_print("((int64_t)0)") + case El.Local(_, x) => Emit.local(Emit.vs(env), x) + case El.CallFn(_, f, ts, caps, args) => + val gts = Emit.grAll(cx, fi, ts) + if Emit.isTail(pos) && Emit.isSelf(fi, f, gts) then Emit.jump(cx, fi, env, caps, args) + else + val cast = Emit.externCast(cx, f, gts) + cast match + case Coll.Some(t) => + rt_print("((") + Emit.ctype(cx, t) + rt_print(")") + case Coll.None => () + Emit.fnName(cx, f, gts) + rt_print("(") + Emit.capArgs(env, caps, Emit.First) + Emit.args(cx, fi, env, args, if Coll.length(caps) == 0 then Emit.First else Emit.Comma) + rt_print(")") + cast match + case Coll.Some(_) => rt_print(")") + case Coll.None => () + case El.New(_, en, ts, c, at, args) => at match + case El.In(reg) => Emit.ctor(cx, fi, env, en, Emit.grAll(cx, fi, ts), c, reg, args) + case El.Comptime => rt_print("0") + case El.Nullary(_, _, ts, c) => + rt_print("(&N_") + Emit.id(c) + Emit.suffix(Emit.grAll(cx, fi, ts)) + rt_print(")") + case El.Op(_, recv, ty, op, args) => Emit.op(cx, fi, env, recv, Emit.gr(cx, fi, ty), op, args) + case El.Bin(_, op, l, x) => + rt_print("(") + Emit.ex(cx, fi, env, Emit.Inner, l) + rt_print(Emit.binOp(op)) + Emit.ex(cx, fi, env, Emit.Inner, x) + rt_print(")") + case El.Un(_, op, x) => + rt_print(Emit.unOp(op)) + Emit.ex(cx, fi, env, Emit.Inner, x) + rt_print(")") + case El.If(_, c, t, x) => + rt_print("(") + Emit.ex(cx, fi, env, Emit.Inner, c) + rt_print(" ? ") + Emit.ex(cx, fi, env, pos, t) + rt_print(" : ") + Emit.ex(cx, fi, env, pos, x) + rt_print(")") + case El.Match(_, x, _, arms) => + rt_print("({ __auto_type s") + rt_print_i64(Emit.envN(env)) + rt_print(" = ") + Emit.ex(cx, fi, env, Emit.Inner, x) + rt_print("; ") + Emit.arms(cx, fi, env, pos, arms) + rt_print("; })") + case El.Block(_, ss, last) => + rt_print("({ ") + Emit.block(cx, fi, env, pos, ss, last, Coll.Nil) + case El.While(_, c, b) => + rt_print("({ while (") + Emit.ex(cx, fi, env, Emit.Inner, c) + rt_print(") { (void)(") + Emit.ex(cx, fi, env, Emit.Inner, b) + rt_print("); } (int64_t)0; })") + case El.Assign(_, x, v) => + rt_print("(") + Emit.local(Emit.vs(env), x) + rt_print(" = (") + Emit.ex(cx, fi, env, Emit.Inner, v) + rt_print("), (int64_t)0)") + case El.Bad(_) => rt_print("0") + +def Emit.binOp(op: Ast.BinOp): Str = op match + case Ast.Add => " + " + case Ast.Sub => " - " + case Ast.Mul => " * " + case Ast.Div => " / " + case Ast.Mod => " % " + case Ast.Lt => " < " + case Ast.Le => " <= " + case Ast.Gt => " > " + case Ast.Ge => " >= " + case Ast.Eq => " == " + case Ast.Ne => " != " + case Ast.And => " && " + case Ast.Or => " || " + +def Emit.unOp(op: Ast.UnOp): Str = op match + case Ast.Neg => "(-" + case Ast.Not => "(!" + +// the length of a literal: an escape counts as one char +def Emit.unescLen(s: Str, i: I64, n: I64): I64 = + if i >= rt_str_len(s) then n + else if rt_str_at(s, i) == 92 then Emit.unescLen(s, i + 2, n + 1) + else Emit.unescLen(s, i + 1, n + 1) + +def Emit.isTail(pos: Emit.Pos): Bool = pos match + case Emit.Tail => true + case Emit.Inner => false + +def Emit.isSelf(fi: Emit.Fi, f: Sym.Sym, ts: Coll.List[K.Term]): Bool = + val Emit.Fi(self, sts, _, _, _) = fi + Sym.eq(f, self) && Mono.termsEq(ts, sts) + +def Emit.fnName {r: Region} (cx: Emit.Cx, f: Sym.Sym, ts: Coll.List[K.Term]): Unit = + val Emit.Cx(_, fns, _, _, _, _, _, _) = cx + Coll.sLookup(fns, f) match + case Coll.Some(g) => + val El.Fn(_, _, _, _, _, _, body) = g + body match + case El.Extern => Emit.id(f) + case _ => Emit.defName(f, ts) + case Coll.None => Emit.defName(f, ts) + +def Emit.defName(f: Sym.Sym, ts: Coll.List[K.Term]): Unit = + rt_print("f_") + Emit.id(f) + Emit.suffix(ts) + +def Emit.sep(s: Emit.Sep): Unit = s match + case Emit.First => () + case Emit.Comma => rt_print(", ") + +def Emit.capArgs(env: Emit.Env, caps: Coll.List[Sym.Sym], s: Emit.Sep): Unit = caps match + case Coll.Nil => () + case Coll.Cons(c, rest) => + Emit.sep(s) + Emit.local(Emit.vs(env), c) + Emit.capArgs(env, rest, Emit.Comma) + +def Emit.args {r: Region} (cx: Emit.Cx, fi: Emit.Fi, env: Emit.Env, xs: Coll.List[El.Expr], s: Emit.Sep): Unit = xs match + case Coll.Nil => () + case Coll.Cons(x, rest) => + Emit.sep(s) + Emit.ex(cx, fi, env, Emit.Inner, x) + Emit.args(cx, fi, env, rest, Emit.Comma) + +// a self tail call (spec sec 4.4): every arg to a temp, then to its param, then back to the top of the body +def Emit.jump {r: Region} (cx: Emit.Cx, fi: Emit.Fi, env: Emit.Env, caps: Coll.List[Sym.Sym], args: Coll.List[El.Expr]): Unit = + val Emit.Fi(_, _, _, slots, ret) = fi + rt_print("({ ") + Emit.temps(cx, fi, env, slots, caps, args, 0) + Emit.sets(slots, 0) + rt_print("goto srs_tail; (") + Emit.ctype(cx, ret) + rt_print("){0}; })") + +def Emit.temps {r: Region} (cx: Emit.Cx, fi: Emit.Fi, env: Emit.Env, slots: Coll.List[Emit.Slot], caps: Coll.List[Sym.Sym], args: Coll.List[El.Expr], i: I64): Unit = slots match + case Coll.Nil => () + case Coll.Cons(sl, rest) => sl match + case Emit.SCap(_) => caps match + case Coll.Nil => () + case Coll.Cons(c, crest) => + rt_print("srs_cap* t") + rt_print_i64(i) + rt_print(" = ") + Emit.local(Emit.vs(env), c) + rt_print("; ") + Emit.temps(cx, fi, env, rest, crest, args, i + 1) + case Emit.SVal(_, t) => args match + case Coll.Nil => () + case Coll.Cons(a, arest) => + Emit.ctype(cx, t) + rt_print(" t") + rt_print_i64(i) + rt_print(" = ") + Emit.ex(cx, fi, env, Emit.Inner, a) + rt_print("; ") + Emit.temps(cx, fi, env, rest, caps, arest, i + 1) + +def Emit.sets(slots: Coll.List[Emit.Slot], i: I64): Unit = slots match + case Coll.Nil => () + case Coll.Cons(sl, rest) => + rt_print("p_") + Emit.id(Emit.slotName(sl)) + rt_print(" = t") + rt_print_i64(i) + rt_print("; ") + Emit.sets(rest, i + 1) + +def Emit.slotName(sl: Emit.Slot): Sym.Sym = sl match + case Emit.SCap(x) => x + case Emit.SVal(x, _) => x + +// a constructor (spec sec 4.3): its own case's size in the region reg, then the fields in order +def Emit.ctor {r: Region} (cx: Emit.Cx, fi: Emit.Fi, env: Emit.Env, en: Sym.Sym, ts: Coll.List[K.Term], c: Sym.Sym, reg: Sym.Sym, args: Coll.List[El.Expr]): Unit = Emit.caseAt(cx, c) match + case Coll.None => rt_print("0") + case Coll.Some(ca) => + val Emit.CaseAt(tag, _, cs) = ca + val Ast.Case(_, _, fields) = cs + val Emit.Cx(_, _, _, _, _, _, al, _) = cx + val n = Emit.envN(env) + rt_print("({ struct E_") + Emit.enumName(en, ts) + rt_print("* o") + rt_print_i64(n) + rt_print(" = (struct E_") + Emit.enumName(en, ts) + rt_print("*)") + al match + case Emit.Inline => + rt_print("srs_alloc(") + Emit.local(Emit.vs(env), reg) + rt_print(", ") + case Emit.VTable => + rt_print("((void*(*)(void*, int64_t))(") + Emit.local(Emit.vs(env), reg) + rt_print("->vt[") + rt_print_i64(Emit.opIndex(cx, Sym.of("Region"), Sym.of("alloc"))) + rt_print("]))(") + Emit.local(Emit.vs(env), reg) + rt_print("->self, ") + rt_print("(int64_t)(offsetof(struct E_") + Emit.enumName(en, ts) + rt_print(", u) + sizeof(((struct E_") + Emit.enumName(en, ts) + rt_print("*)0)->u.C_") + Emit.id(c) + rt_print("))); o") + rt_print_i64(n) + rt_print("->tag = ") + rt_print_i64(tag) + rt_print(";") + Emit.fieldSets(cx, fi, env, n, c, fields, args) + rt_print(" o") + rt_print_i64(n) + rt_print("; })") + +def Emit.fieldSets {r: Region} (cx: Emit.Cx, fi: Emit.Fi, env: Emit.Env, n: I64, c: Sym.Sym, fs: Coll.List[Ast.Binder], xs: Coll.List[El.Expr]): Unit = fs match + case Coll.Nil => () + case Coll.Cons(f, frest) => xs match + case Coll.Nil => () + case Coll.Cons(x, xrest) => + val Ast.Binder(_, fx, _) = f + rt_print(" o") + rt_print_i64(n) + rt_print("->u.C_") + Emit.id(c) + rt_print(".f_") + Emit.id(fx) + rt_print(" = ") + Emit.ex(cx, fi, env, Emit.Inner, x) + rt_print(";") + Emit.fieldSets(cx, fi, env, n, c, frest, xrest) + +// the index of op in protocol p's op list +def Emit.opIndex {r: Region} (cx: Emit.Cx, p: Sym.Sym, op: Sym.Sym): I64 = + val Emit.Cx(_, _, _, _, ps, _, _, _) = cx + Coll.sLookup(ps, p) match + case Coll.None => 0 + case Coll.Some(pr) => + val Ast.Proto(_, _, _, _, _, _, ops, _) = pr + Emit.opIn(ops, op, 0) + +def Emit.opIn(os: Coll.List[Ast.Op], op: Sym.Sym, i: I64): I64 = os match + case Coll.Nil => i + case Coll.Cons(o, rest) => + val Ast.Op(_, n, _, _, _) = o + if Sym.eq(n, op) then i else Emit.opIn(rest, op, i + 1) + +// recv.op(args): through the capability's vtable (an op whose every transition ends the protocol clears live), or a +// trait method of {} evidence: the given's static fn (rung T2) +def Emit.op {r: Region} (cx: Emit.Cx, fi: Emit.Fi, env: Emit.Env, recv: Sym.Sym, ty: K.Term, op: Sym.Sym, args: Coll.List[El.Expr]): Unit = ty match + case K.Con(pn, targs) => + val Emit.Cx(_, _, _, _, ps, _, _, _) = cx + Coll.sLookup(ps, pn) match + case Coll.Some(p) => + val Ast.Proto(_, _, _, _, ends, _, ops, _) = p + Ty.opIn(ops, op) match + case Coll.Some(o) => + val Ast.Op(_, _, ops2, oret, trans) = o + rt_print("({ __auto_type r_ = ((") + Emit.ctype(cx, Ty.term(oret, Coll.Nil)) + rt_print("(*)(void*") + Emit.opTys(cx, ops2) + rt_print("))(") + Emit.local(Emit.vs(env), recv) + rt_print("->vt[") + rt_print_i64(Emit.opIn(ops, op, 0)) + rt_print("]))(") + Emit.local(Emit.vs(env), recv) + rt_print("->self") + Emit.args(cx, fi, env, args, Emit.Comma) + rt_print("); ") + if Emit.kills(trans, ends) then + Emit.local(Emit.vs(env), recv) + rt_print("->live = 0; ") + else () + rt_print("r_; })") + case Coll.None => rt_print("0") + case Coll.None => + rt_print("g_") + Emit.id(pn) + Emit.suffix(targs) + rt_print("_") + Emit.id(op) + rt_print("(") + Emit.args(cx, fi, env, args, Emit.First) + rt_print(")") + case _ => rt_print("0") + +def Emit.opTys {r: Region} (cx: Emit.Cx, ps: Coll.List[Ast.Binder]): Unit = ps match + case Coll.Nil => () + case Coll.Cons(p, rest) => + val Ast.Binder(_, _, t) = p + rt_print(", ") + Emit.ctype(cx, Ty.term(t, Coll.Nil)) + Emit.opTys(cx, rest) + +// every transition of the op ends the protocol (and it has one) +def Emit.kills(ts: Coll.List[Ast.Trans], ends: Coll.List[Sym.Sym]): Bool = ts match + case Coll.Nil => false + case Coll.Cons(_, _) => Emit.allEnd(ts, ends) + +def Emit.allEnd(ts: Coll.List[Ast.Trans], ends: Coll.List[Sym.Sym]): Bool = ts match + case Coll.Nil => true + case Coll.Cons(t, rest) => + val Ast.Trans(_, to) = t + if Ty.memberSym(to, ends) then Emit.allEnd(rest, ends) else false + +// match (spec sec 4.1): the scrutinee once in s; the last arm has no tag test +def Emit.arms {r: Region} (cx: Emit.Cx, fi: Emit.Fi, env: Emit.Env, pos: Emit.Pos, as: Coll.List[El.Arm]): Unit = as match + case Coll.Nil => () + case Coll.Cons(a, rest) => + val El.Arm(_, p, b) = a + val n = Emit.envN(env) + p match + case Ast.PAny => + Emit.test(rest, n, Emit.Always) + rt_print("({ ") + Emit.ex(cx, fi, env, pos, b) + rt_print("; })") + case Ast.PCase(c, binds) => Emit.caseAt(cx, c) match + case Coll.None => rt_print("0") + case Coll.Some(ca) => + val Emit.CaseAt(tag, _, cs) = ca + val Ast.Case(_, _, fields) = cs + Emit.test(rest, n, Emit.Tag(tag)) + rt_print("({ ") + Emit.ex(cx, fi, Emit.binds(env, n, c, binds, fields), pos, b) + rt_print("; })") + rest match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print(" : ") + Emit.arms(cx, fi, env, pos, rest) + +// the test of an arm that is not the last +def Emit.test(rest: Coll.List[El.Arm], n: I64, g: Emit.Guard): Unit = rest match + case Coll.Nil => () + case Coll.Cons(_, _) => g match + case Emit.Always => rt_print("1 ? ") + case Emit.Tag(tag) => + rt_print("s") + rt_print_i64(n) + rt_print("->tag == ") + rt_print_i64(tag) + rt_print(" ? ") + +// each binder of an arm (not `_`) to its case field of s +def Emit.binds {r: Region} (env: Emit.Env, n: I64, c: Sym.Sym, xs: Coll.List[Sym.Sym], fs: Coll.List[Ast.Binder]): Emit.Env = xs match + case Coll.Nil => env + case Coll.Cons(x, rest) => fs match + case Coll.Nil => env + case Coll.Cons(f, frest) => + if rt_str_eq(Sym.str(x), "_") then Emit.binds(env, n, c, rest, frest) + else + val Ast.Binder(_, fx, _) = f + val env2 = Emit.bind(env, x) + rt_print("__auto_type ") + Emit.cname(Emit.L(x, Emit.envN(env))) + rt_print(" = s") + rt_print_i64(n) + rt_print("->u.C_") + Emit.id(c) + rt_print(".f_") + Emit.id(fx) + rt_print("; ") + Emit.binds(env2, n, c, rest, frest) + +// a block (spec sec 4.2): statements in order, the last expression in res_, then the drops of its handles (latest first) +def Emit.block {r: Region} (cx: Emit.Cx, fi: Emit.Fi, env: Emit.Env, pos: Emit.Pos, ss: Coll.List[El.Stmt], last: El.Expr, drops: Coll.List[Emit.Drop]): Unit = ss match + case Coll.Nil => + rt_print("__auto_type res_ = ") + Emit.ex(cx, fi, env, Emit.lastPos(drops, pos), last) + rt_print("; ") + Emit.drops(cx, drops) + rt_print("res_; })") + case Coll.Cons(s, rest) => s match + case El.Val(_, x, ty, _, e) => + Emit.ctype(cx, Emit.gr(cx, fi, ty)) + rt_print(" ") + Emit.cname(Emit.L(x, Emit.envN(env))) + rt_print(" = ") + Emit.ex(cx, fi, env, Emit.Inner, e) + rt_print("; ") + Emit.block(cx, fi, Emit.bind(env, x), pos, rest, last, drops) + case El.Handle(_, x, h, args) => + val v = Emit.L(x, Emit.envN(env)) + rt_print("srs_cap ") + Emit.cname(v) + rt_print("_v = { h_") + Emit.id(h) + rt_print("_init(") + Emit.args(cx, fi, env, args, Emit.First) + rt_print("), vt_") + Emit.id(h) + rt_print(", 1 }; srs_cap* ") + Emit.cname(v) + rt_print(" = &") + Emit.cname(v) + rt_print("_v; ") + Emit.block(cx, fi, Emit.bind(env, x), pos, rest, last, Coll.Cons(Emit.Drop(v, Emit.protoOfH(cx, h)), drops)) + case El.Do(e) => + rt_print("(void)(") + Emit.ex(cx, fi, env, Emit.Inner, e) + rt_print("); ") + Emit.block(cx, fi, env, pos, rest, last, drops) + +// a block with a handle is not a tail position: its drops run after the last expression +def Emit.lastPos(drops: Coll.List[Emit.Drop], pos: Emit.Pos): Emit.Pos = drops match + case Coll.Nil => pos + case Coll.Cons(_, _) => Emit.Inner + +def Emit.drops {r: Region} (cx: Emit.Cx, ds: Coll.List[Emit.Drop]): Unit = ds match + case Coll.Nil => () + case Coll.Cons(d, rest) => + val Emit.Drop(v, p) = d + val Emit.Cx(_, _, _, _, ps, _, _, _) = cx + Coll.sLookup(ps, p) match + case Coll.None => () + case Coll.Some(pr) => + val Ast.Proto(_, _, _, _, _, dop, ops, _) = pr + dop match + case Coll.None => () + case Coll.Some(o) => + rt_print("if (") + Emit.cname(v) + rt_print("->live) ((int64_t(*)(void*))(") + Emit.cname(v) + rt_print("->vt[") + rt_print_i64(Emit.opIn(ops, o, 0)) + rt_print("]))(") + Emit.cname(v) + rt_print("->self); ") + Emit.drops(cx, rest) + +// the protocol of handler h +def Emit.protoOfH {r: Region} (cx: Emit.Cx, h: Sym.Sym): Sym.Sym = + val Emit.Cx(_, _, _, _, _, hp, _, _) = cx + Coll.sLookup(hp, h) match + case Coll.Some(p) => p + case Coll.None => h + +// ── a self call in tail position (spec sec 4.4): the body then gets the srs_tail label ── +def Emit.hasTail {r: Region} (cx: Emit.Cx, fi: Emit.Fi, e: El.Expr): Bool = e match + case El.CallFn(_, f, ts, _, _) => Emit.isSelf(fi, f, Emit.grAll(cx, fi, ts)) + case El.If(_, _, t, x) => Emit.hasTail(cx, fi, t) || Emit.hasTail(cx, fi, x) + case El.Match(_, _, _, arms) => Emit.armsTail(cx, fi, arms) + case El.Block(_, ss, last) => if Emit.hasHandle(ss) then false else Emit.hasTail(cx, fi, last) + case _ => false + +def Emit.armsTail {r: Region} (cx: Emit.Cx, fi: Emit.Fi, as: Coll.List[El.Arm]): Bool = as match + case Coll.Nil => false + case Coll.Cons(a, rest) => + val El.Arm(_, _, b) = a + if Emit.hasTail(cx, fi, b) then true else Emit.armsTail(cx, fi, rest) + +def Emit.hasHandle(ss: Coll.List[El.Stmt]): Bool = ss match + case Coll.Nil => false + case Coll.Cons(s, rest) => s match + case El.Handle(_, _, _, _) => true + case _ => Emit.hasHandle(rest) + +// ── an instance as the fn emit prints ── +def Emit.fiOf {r: Region} (cx: Emit.Cx, i: Mono.Inst): Emit.Fi = + val Mono.Inst(f, sub, _) = i + val El.Fn(_, name, tps, caps, ps, ret, _) = f + Emit.Fi(name, Emit.targsOf(sub, tps, Coll.Nil), sub, Emit.slots(cx, sub, caps, ps), Mono.ground(Emit.subst(cx), sub, ret)) + +def Emit.targsOf {r: Region} (sub: Coll.List[Ty.Bind], tps: Coll.List[Sym.Sym], acc: Coll.List[K.Term]): Coll.List[K.Term] = tps match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(x, rest) => Ty.lookup(sub, x) match + case Coll.Some(t) => Emit.targsOf(sub, rest, Coll.Cons(t, acc)) + case Coll.None => Emit.targsOf(sub, rest, Coll.Cons(K.Con(x, Coll.Nil), acc)) + +// the capabilities first, then the params +def Emit.slots {r: Region} (cx: Emit.Cx, sub: Coll.List[Ty.Bind], caps: Coll.List[Sym.Sym], ps: Coll.List[El.Param]): Coll.List[Emit.Slot] = caps match + case Coll.Cons(c, rest) => Coll.Cons(Emit.SCap(c), Emit.slots(cx, sub, rest, ps)) + case Coll.Nil => Emit.valSlots(cx, sub, ps, Coll.Nil) + +def Emit.valSlots {r: Region} (cx: Emit.Cx, sub: Coll.List[Ty.Bind], ps: Coll.List[El.Param], acc: Coll.List[Emit.Slot]): Coll.List[Emit.Slot] = ps match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(p, rest) => + val El.Param(x, t) = p + Emit.valSlots(cx, sub, rest, Coll.Cons(Emit.SVal(x, Mono.ground(Emit.subst(cx), sub, t)), acc)) + +def Emit.isDef(i: Mono.Inst): Bool = + val Mono.Inst(f, _, _) = i + val El.Fn(_, _, _, _, _, _, body) = f + body match + case El.Def(_) => true + case _ => false + +// ── signatures (spec sec 3) and bodies (sec 4.4) ── +def Emit.sig {r: Region} (cx: Emit.Cx, fi: Emit.Fi, k: Emit.Kind): Unit = + val Emit.Fi(self, targs, _, slots, ret) = fi + k match + case Emit.KExtern => () + case _ => rt_print("static ") + Emit.ctype(cx, ret) + rt_print(" ") + k match + case Emit.KDef => Emit.defName(self, targs) + case Emit.KExtern => Emit.id(self) + case Emit.KHandler(h) => + rt_print("h_") + Emit.id(h) + rt_print("_") + Emit.id(self) + case Emit.KGiven(head) => + rt_print("g_") + Emit.termName(head) + rt_print("_") + Emit.id(self) + rt_print("(") + slots match + case Coll.Nil => rt_print("void") + case Coll.Cons(_, _) => Emit.params(cx, slots, Emit.First) + rt_print(")") + +def Emit.params {r: Region} (cx: Emit.Cx, slots: Coll.List[Emit.Slot], s: Emit.Sep): Unit = slots match + case Coll.Nil => () + case Coll.Cons(sl, rest) => + Emit.sep(s) + sl match + case Emit.SCap(_) => rt_print("srs_cap*") + case Emit.SVal(_, t) => Emit.ctype(cx, t) + rt_print(" p_") + Emit.id(Emit.slotName(sl)) + Emit.params(cx, rest, Emit.Comma) + +def Emit.paramEnv {r: Region} (slots: Coll.List[Emit.Slot], acc: Coll.List[Emit.Name]): Emit.Env = slots match + case Coll.Nil => Emit.Env(acc, 0) + case Coll.Cons(sl, rest) => Emit.paramEnv(rest, Coll.Cons(Emit.P(Emit.slotName(sl)), acc)) + +// a def loops on its self tail calls; a handler fn does not (s1 emit.srs:270-275) +def Emit.body {r: Region} (cx: Emit.Cx, fi: Emit.Fi, k: Emit.Kind, e: El.Expr): Unit = + val Emit.Fi(_, _, _, slots, _) = fi + Emit.sig(cx, fi, k) + val pos = k match + case Emit.KDef => if Emit.hasTail(cx, fi, e) then Emit.Tail else Emit.Inner + case _ => Emit.Inner + pos match + case Emit.Tail => rt_print(" { srs_tail: return ") + case Emit.Inner => rt_print(" { return ") + Emit.ex(cx, fi, Emit.paramEnv(slots, Coll.Nil), pos, e) + rt_print("; }\n") + +// ── the enum instances the C names: of every signature and expression, closed over their fields (spec sec 1 B, C) ── +def Emit.instTys {r: Region} (cx: Emit.Cx, is: Coll.List[Mono.Inst], acc: Coll.List[K.Term]): Coll.List[K.Term] = is match + case Coll.Nil => acc + case Coll.Cons(i, rest) => + val Mono.Inst(f, _, _) = i + val El.Fn(_, _, _, _, _, _, body) = f + body match + case El.Def(e) => + val fi = Emit.fiOf(cx, i) + val Emit.Fi(_, _, _, slots, ret) = fi + Emit.instTys(cx, rest, Emit.exTys(cx, fi, e, Emit.slotTys(slots, Coll.Cons(ret, acc)))) + case _ => Emit.instTys(cx, rest, acc) + +def Emit.slotTys {r: Region} (slots: Coll.List[Emit.Slot], acc: Coll.List[K.Term]): Coll.List[K.Term] = slots match + case Coll.Nil => acc + case Coll.Cons(sl, rest) => sl match + case Emit.SCap(_) => Emit.slotTys(rest, acc) + case Emit.SVal(_, t) => Emit.slotTys(rest, Coll.Cons(t, acc)) + +def Emit.exTys {r: Region} (cx: Emit.Cx, fi: Emit.Fi, e: El.Expr, acc: Coll.List[K.Term]): Coll.List[K.Term] = e match + case El.CallFn(_, _, _, _, args) => Emit.exsTys(cx, fi, args, acc) + case El.New(_, en, ts, _, _, args) => Emit.exsTys(cx, fi, args, Coll.Cons(K.Con(en, Emit.grAll(cx, fi, ts)), acc)) + case El.Nullary(_, en, ts, _) => Coll.Cons(K.Con(en, Emit.grAll(cx, fi, ts)), acc) + case El.Op(_, _, _, _, args) => Emit.exsTys(cx, fi, args, acc) + case El.Bin(_, _, l, x) => Emit.exTys(cx, fi, x, Emit.exTys(cx, fi, l, acc)) + case El.Un(_, _, x) => Emit.exTys(cx, fi, x, acc) + case El.If(_, c, t, x) => Emit.exTys(cx, fi, x, Emit.exTys(cx, fi, t, Emit.exTys(cx, fi, c, acc))) + case El.Match(_, x, en, arms) => Emit.armsTys(cx, fi, arms, Emit.exTys(cx, fi, x, Coll.Cons(Emit.gr(cx, fi, en), acc))) + case El.Block(_, ss, last) => Emit.exTys(cx, fi, last, Emit.stmtsTys(cx, fi, ss, acc)) + case El.While(_, c, b) => Emit.exTys(cx, fi, b, Emit.exTys(cx, fi, c, acc)) + case El.Assign(_, _, x) => Emit.exTys(cx, fi, x, acc) + case _ => acc + +def Emit.exsTys {r: Region} (cx: Emit.Cx, fi: Emit.Fi, xs: Coll.List[El.Expr], acc: Coll.List[K.Term]): Coll.List[K.Term] = xs match + case Coll.Nil => acc + case Coll.Cons(x, rest) => Emit.exsTys(cx, fi, rest, Emit.exTys(cx, fi, x, acc)) + +def Emit.armsTys {r: Region} (cx: Emit.Cx, fi: Emit.Fi, as: Coll.List[El.Arm], acc: Coll.List[K.Term]): Coll.List[K.Term] = as match + case Coll.Nil => acc + case Coll.Cons(a, rest) => + val El.Arm(_, _, b) = a + Emit.armsTys(cx, fi, rest, Emit.exTys(cx, fi, b, acc)) + +def Emit.stmtsTys {r: Region} (cx: Emit.Cx, fi: Emit.Fi, ss: Coll.List[El.Stmt], acc: Coll.List[K.Term]): Coll.List[K.Term] = ss match + case Coll.Nil => acc + case Coll.Cons(s, rest) => s match + case El.Val(_, _, ty, _, e) => Emit.stmtsTys(cx, fi, rest, Emit.exTys(cx, fi, e, Coll.Cons(Emit.gr(cx, fi, ty), acc))) + case El.Handle(_, _, _, args) => Emit.stmtsTys(cx, fi, rest, Emit.exsTys(cx, fi, args, acc)) + case El.Do(e) => Emit.stmtsTys(cx, fi, rest, Emit.exTys(cx, fi, e, acc)) + +// the distinct enum terms of todo and of their fields, in the order found (seen: by hash bucket) +def Emit.closeEnums {r: Region} (cx: Emit.Cx, todo: Coll.List[K.Term], seen: Coll.BTree[Coll.List[K.Term]], out: Coll.List[K.Term]): Coll.List[K.Term] = todo match + case Coll.Nil => Coll.rev(out) + case Coll.Cons(t, rest) => t match + case K.Con(n, args) => + val Emit.Cx(_, _, _, es, _, _, _, _) = cx + val h = Mono.thash(t, 0) + Coll.sLookup(es, n) match + case Coll.None => Emit.closeEnums(cx, rest, seen, out) + case Coll.Some(e) => + if Emit.inTerms(Coll.bTGetOr(seen, h, Coll.Nil), t) then Emit.closeEnums(cx, rest, seen, out) + else Emit.closeEnums(cx, Emit.fieldTys(e, args, rest), Coll.bPushT(seen, h, t), Coll.Cons(t, out)) + case _ => Emit.closeEnums(cx, rest, seen, out) + +def Emit.inTerms(ts: Coll.List[K.Term], t: K.Term): Bool = ts match + case Coll.Nil => false + case Coll.Cons(x, rest) => if Mono.termEq(x, t) then true else Emit.inTerms(rest, t) + +// the field types of enum e at args +def Emit.fieldTys {r: Region} (e: Ast.Enum, args: Coll.List[K.Term], acc: Coll.List[K.Term]): Coll.List[K.Term] = + val Ast.Enum(_, _, gs, cases) = e + Emit.casesTys(cases, Ty.zipBind(Ty.tparams(gs, Coll.Nil), args, Coll.Nil), acc) + +def Emit.casesTys {r: Region} (cs: Coll.List[Ast.Case], tv: Coll.List[Ty.Bind], acc: Coll.List[K.Term]): Coll.List[K.Term] = cs match + case Coll.Nil => acc + case Coll.Cons(c, rest) => + val Ast.Case(_, _, fs) = c + Emit.casesTys(rest, tv, Emit.bindersTys(fs, tv, acc)) + +def Emit.bindersTys {r: Region} (fs: Coll.List[Ast.Binder], tv: Coll.List[Ty.Bind], acc: Coll.List[K.Term]): Coll.List[K.Term] = fs match + case Coll.Nil => acc + case Coll.Cons(f, rest) => + val Ast.Binder(_, _, t) = f + Emit.bindersTys(rest, tv, Coll.Cons(Ty.term(t, tv), acc)) + +// ── enum structs and nullary statics (spec sec 1.1) ── +def Emit.fwds(ts: Coll.List[K.Term]): Unit = ts match + case Coll.Nil => () + case Coll.Cons(t, rest) => + rt_print("struct E_") + Emit.termName(t) + rt_print(";\n") + Emit.fwds(rest) + +def Emit.termName(t: K.Term): Unit = t match + case K.Con(n, args) => Emit.enumName(n, args) + case _ => Emit.mangle(t) + +def Emit.structs {r: Region} (cx: Emit.Cx, ts: Coll.List[K.Term]): Unit = ts match + case Coll.Nil => () + case Coll.Cons(t, rest) => + Emit.withEnum(cx, t, Emit.Layout) + Emit.structs(cx, rest) + +def Emit.statics {r: Region} (cx: Emit.Cx, ts: Coll.List[K.Term]): Unit = ts match + case Coll.Nil => () + case Coll.Cons(t, rest) => + Emit.withEnum(cx, t, Emit.Code) + Emit.statics(cx, rest) + +// the struct (Layout) or the nullary statics (Code) of enum term t +def Emit.withEnum {r: Region} (cx: Emit.Cx, t: K.Term, what: Emit.Part): Unit = t match + case K.Con(n, args) => + val Emit.Cx(_, _, _, es, _, _, _, _) = cx + Coll.sLookup(es, n) match + case Coll.None => () + case Coll.Some(e) => + val Ast.Enum(_, _, gs, cases) = e + val tv = Ty.zipBind(Ty.tparams(gs, Coll.Nil), args, Coll.Nil) + what match + case Emit.Layout => + rt_print("struct E_") + Emit.enumName(n, args) + rt_print(" { int64_t tag; union {") + Emit.caseStructs(cx, cases, tv) + rt_print(" int64_t none_; } u; };\n") + case Emit.Code => Emit.nullaries(n, args, cases, 0) + case _ => () + +def Emit.caseStructs {r: Region} (cx: Emit.Cx, cs: Coll.List[Ast.Case], tv: Coll.List[Ty.Bind]): Unit = cs match + case Coll.Nil => () + case Coll.Cons(c, rest) => + val Ast.Case(_, cn, fs) = c + fs match + case Coll.Nil => () + case Coll.Cons(_, _) => + rt_print(" struct {") + Emit.fieldDecls(cx, fs, tv) + rt_print(" } C_") + Emit.id(cn) + rt_print(";") + Emit.caseStructs(cx, rest, tv) + +def Emit.fieldDecls {r: Region} (cx: Emit.Cx, fs: Coll.List[Ast.Binder], tv: Coll.List[Ty.Bind]): Unit = fs match + case Coll.Nil => () + case Coll.Cons(f, rest) => + val Ast.Binder(_, x, t) = f + rt_print(" ") + Emit.ctype(cx, Ty.term(t, tv)) + rt_print(" f_") + Emit.id(x) + rt_print(";") + Emit.fieldDecls(cx, rest, tv) + +def Emit.nullaries(n: Sym.Sym, args: Coll.List[K.Term], cs: Coll.List[Ast.Case], i: I64): Unit = cs match + case Coll.Nil => () + case Coll.Cons(c, rest) => + val Ast.Case(_, cn, fs) = c + fs match + case Coll.Nil => + rt_print("static struct E_") + Emit.enumName(n, args) + rt_print(" N_") + Emit.id(cn) + Emit.suffix(args) + rt_print(" = { ") + rt_print_i64(i) + rt_print(", { 0 } };\n") + case Coll.Cons(_, _) => () + Emit.nullaries(n, args, rest, i + 1) + +// ── prototypes (spec sec 1 D), vtables (E), bodies (G) ── +def Emit.externs {r: Region} (cx: Emit.Cx, fs: Coll.List[El.Fn]): Unit = fs match + case Coll.Nil => () + case Coll.Cons(f, rest) => + val El.Fn(_, _, tps, _, _, _, body) = f + body match + case El.Extern => + // one C symbol for every instance: a [] binder slot is void* (spec sec 3 slotType) + Emit.sig(cx, Emit.fiOf(cx, Mono.Inst(f, Emit.ptrs(tps, Coll.Nil), Mono.Top)), Emit.KExtern) + rt_print(";\n") + case _ => () + Emit.externs(cx, rest) + +def Emit.ptrs {r: Region} (tps: Coll.List[Sym.Sym], acc: Coll.List[Ty.Bind]): Coll.List[Ty.Bind] = tps match + case Coll.Nil => acc + case Coll.Cons(x, rest) => Emit.ptrs(rest, Coll.Cons(Ty.Bind(x, Ty.con("Ptr")), acc)) + +// a generic extern whose result is a [] binder returns void*: the call casts it to the instance's type (spec sec 4 XInst) +def Emit.externCast {r: Region} (cx: Emit.Cx, f: Sym.Sym, gts: Coll.List[K.Term]): Coll.Option[K.Term] = + val Emit.Cx(_, fns, _, _, _, _, _, _) = cx + Coll.sLookup(fns, f) match + case Coll.Some(g) => + val El.Fn(_, _, tps, _, _, ret, body) = g + body match + case El.Extern => ret match + case K.Con(n, xs) => if Coll.length(xs) == 0 then Ty.lookup(Ty.zipBind(tps, gts, Coll.Nil), n) else Coll.None + case _ => Coll.None + case _ => Coll.None + case Coll.None => Coll.None + +def Emit.protos {r: Region} (cx: Emit.Cx, is: Coll.List[Mono.Inst]): Unit = is match + case Coll.Nil => () + case Coll.Cons(i, rest) => + if Emit.isDef(i) then + Emit.sig(cx, Emit.fiOf(cx, i), Emit.kindOf(i)) + rt_print(";\n") + else () + Emit.protos(cx, rest) + +def Emit.bodies {r: Region} (cx: Emit.Cx, is: Coll.List[Mono.Inst]): Unit = is match + case Coll.Nil => () + case Coll.Cons(i, rest) => + val Mono.Inst(f, _, _) = i + val El.Fn(_, _, _, _, _, _, body) = f + body match + case El.Def(e) => Emit.body(cx, Emit.fiOf(cx, i), Emit.kindOf(i), e) + case _ => () + Emit.bodies(cx, rest) + +// the fns of every handler: prototypes (Layout) or bodies (Code) +def Emit.handlers {r: Region} (cx: Emit.Cx, hs: Coll.List[El.Handler], what: Emit.Part): Unit = hs match + case Coll.Nil => () + case Coll.Cons(h, rest) => + val El.Handler(hn, _, fs) = h + Emit.implFns(cx, Emit.KHandler(hn), fs, what) + Emit.handlers(cx, rest, what) + +def Emit.implFns {r: Region} (cx: Emit.Cx, k: Emit.Kind, fs: Coll.List[El.Fn], what: Emit.Part): Unit = fs match + case Coll.Nil => () + case Coll.Cons(f, rest) => + val El.Fn(_, _, _, _, _, _, body) = f + val fi = Emit.fiOf(cx, Mono.Inst(f, Coll.Nil, Mono.Top)) + what match + case Emit.Layout => + Emit.sig(cx, fi, k) + rt_print(";\n") + case Emit.Code => body match + case El.Def(e) => Emit.body(cx, fi, k, e) + case _ => () + Emit.implFns(cx, k, rest, what) + +// the vtable of a handler: its fn per op of its protocol, in the protocol's op order (spec sec 5.1) +def Emit.vtables {r: Region} (cx: Emit.Cx, hs: Coll.List[El.Handler]): Unit = hs match + case Coll.Nil => () + case Coll.Cons(h, rest) => + val El.Handler(hn, p, _) = h + val Emit.Cx(_, _, _, _, ps, _, _, _) = cx + rt_print("static void* const vt_") + Emit.id(hn) + rt_print("[] = {") + Coll.sLookup(ps, p) match + case Coll.Some(pr) => + val Ast.Proto(_, _, _, _, _, _, ops, _) = pr + Emit.vtOps(hn, ops) + case Coll.None => () + rt_print(" 0 };\n") + Emit.vtables(cx, rest) + +def Emit.vtOps(hn: Sym.Sym, ops: Coll.List[Ast.Op]): Unit = ops match + case Coll.Nil => () + case Coll.Cons(o, rest) => + val Ast.Op(_, n, _, _, _) = o + rt_print(" (void*)h_") + Emit.id(hn) + rt_print("_") + Emit.id(n) + rt_print(",") + Emit.vtOps(hn, rest) + +// the inline Arena bump (spec sec 5.2): the chunk layout of rt/srs_rt.c:24-25 +def Emit.allocFast {r: Region} (cx: Emit.Cx): Unit = + rt_print("typedef struct srs_chunk { struct srs_chunk* next; size_t used, cap; } srs_chunk;\n") + rt_print("static inline void* srs_alloc(srs_cap* c, int64_t size) {\n") + rt_print(" if (c->vt == vt_Arena) {\n") + rt_print(" srs_chunk* h = *(srs_chunk**)c->self;\n") + rt_print(" size_t n = ((size_t)size + 15) & ~(size_t)15;\n") + rt_print(" if (h && h->used + n <= h->cap) { void* p = (char*)(h + 1) + h->used; h->used += n; return p; }\n") + rt_print(" return rt_arena_alloc(c->self, size);\n") + rt_print(" }\n") + rt_print(" return ((void*(*)(void*, int64_t))c->vt[") + rt_print_i64(Emit.opIndex(cx, Sym.of("Region"), Sym.of("alloc"))) + rt_print("])(c->self, size);\n") + rt_print("}\n") + +def Emit.hasMain {r: Region} (cx: Emit.Cx): Bool = + val Emit.Cx(_, fns, _, _, _, _, _, _) = cx + Coll.sLookup(fns, Sym.of("main")) match + case Coll.Some(_) => true + case Coll.None => false + +// ── the program (spec sec 1): one C file to stdout ── +def Emit.program {r: Region} (ds: Coll.List[Ast.Decl], res: Ty.Result): Unit = + val Ty.Result(_, _, s, fs, hs, _) = res + val cx = Emit.cxOf(ds, s, fs) + val is = Mono.run(res) + val ens = Emit.closeEnums(cx, Emit.instTys(cx, is, Coll.Nil), Coll.BTip, Coll.Nil) + rt_print("// DO-NOT-EDIT. Generated by srs (s2/emit.srs).\n") + rt_print("#include \n#include \n#include \n") + rt_print("typedef struct { const uint8_t* p; int64_t n; } srs_str;\n") + rt_print("typedef struct { void* self; void* const* vt; int64_t live; } srs_cap;\n") + rt_print("void rt_init(int argc, char** argv);\n") + Emit.fwds(ens) + Emit.structs(cx, ens) + Emit.statics(cx, ens) + Emit.externs(cx, fs) + Emit.protos(cx, is) + Emit.handlers(cx, hs, Emit.Layout) + Emit.vtables(cx, hs) + val Emit.Cx(_, _, _, _, _, _, al, _) = cx + al match + case Emit.Inline => Emit.allocFast(cx) + case Emit.VTable => () + Emit.bodies(cx, is) + Emit.handlers(cx, hs, Emit.Code) + if Emit.hasMain(cx) then rt_print("int main(int argc, char** argv) { rt_init(argc, argv); return (int)f_main(); }\n") else () + +// a def instance is f_; a given method instance is named by its goal +def Emit.kindOf {r: Region} (i: Mono.Inst): Emit.Kind = + val Mono.Inst(_, _, site) = i + site match + case Mono.Top => Emit.KDef + case Mono.Impl(goal) => Emit.KGiven(goal) diff --git a/bench/corpus/s2/eval.srs b/bench/corpus/s2/eval.srs new file mode 100644 index 00000000..5b70cb24 --- /dev/null +++ b/bench/corpus/s2/eval.srs @@ -0,0 +1,356 @@ +// s2 comptime evaluator (s1/eval.srs, vic-u2d.2 U2, vic/c/comptime-eval.md E3 E4): runs the Ast of pure defs. fuel (vic +// Q-U2): 1 per call and 1 per loop turn; out of fuel and division by zero are rejects, as data. data at compile time has +// no Region (vic Q-U4): the compiler owns it. + +enum Ev.V: + case Ev.VUnit + case Ev.VInt(v: I64) + case Ev.VBool(b: Bool) + case Ev.VStr(s: Str) + case Ev.VData(c: Sym.Sym, fs: Coll.List[Ev.V]) + +enum Ev.Bind: + case Ev.Bind(x: Sym.Sym, v: Ev.V) + +// why a run stops: fuel out or a division by zero at fn f; an expression with no compile-time value (a call of an +// impure fn, an op on a capability) +enum Ev.Fail: + case Ev.Fuel(line: I64, f: Sym.Sym) + case Ev.DivZero(line: I64, f: Sym.Sym) + case Ev.NoValue(line: I64, f: Sym.Sym) + +// a value with the locals after it and the fuel left +enum Ev.R: + case Ev.Ok(v: Ev.V, env: Coll.List[Ev.Bind], fuel: I64) + case Ev.Err(e: Ev.Fail) + +// the defs by name, the cases by name (with their field count), the fns with effects +enum Ev.Cx: + case Ev.Cx(fns: Coll.SMap[Ast.Fn], cases: Coll.SMap[I64], impure: Coll.SMap[Bool]) + +def Ev.fuel(): I64 = 1000000 + +def Ev.cxOf {r: Region} (ds: Coll.List[Ast.Decl], imp: Coll.SMap[Bool]): Ev.Cx = Ev.cxDecls(ds, Ev.Cx(Coll.sEmpty(), Coll.sEmpty(), imp)) + +def Ev.cxDecls {r: Region} (ds: Coll.List[Ast.Decl], cx: Ev.Cx): Ev.Cx = ds match + case Coll.Nil => cx + case Coll.Cons(d, rest) => + val Ev.Cx(fs, cs, imp) = cx + d match + case Ast.DFn(f) => + val Ast.Fn(_, n, _, _, _, _, _) = f + Ev.cxDecls(rest, Ev.Cx(Coll.sInsert(fs, n, f), cs, imp)) + case Ast.DEnum(e) => + val Ast.Enum(_, _, _, cases) = e + Ev.cxDecls(rest, Ev.Cx(fs, Ev.caseMap(cases, cs), imp)) + case _ => Ev.cxDecls(rest, cx) + +def Ev.caseMap {r: Region} (cs: Coll.List[Ast.Case], m: Coll.SMap[I64]): Coll.SMap[I64] = cs match + case Coll.Nil => m + case Coll.Cons(c, rest) => + val Ast.Case(_, n, fs) = c + Ev.caseMap(rest, Coll.sInsert(m, n, Coll.length(fs))) + +def Ev.get {r: Region} (env: Coll.List[Ev.Bind], x: Sym.Sym): Coll.Option[Ev.V] = env match + case Coll.Nil => Coll.None + case Coll.Cons(b, rest) => + val Ev.Bind(y, v) = b + if Sym.eq(x, y) then Coll.Some(v) else Ev.get(rest, x) + +// an assignment replaces the innermost binding of x in place +def Ev.set {r: Region} (env: Coll.List[Ev.Bind], x: Sym.Sym, v: Ev.V): Coll.List[Ev.Bind] = env match + case Coll.Nil => Coll.Nil + case Coll.Cons(b, rest) => + val Ev.Bind(y, w) = b + if Sym.eq(x, y) then Coll.Cons(Ev.Bind(y, v), rest) else Coll.Cons(b, Ev.set(rest, x, v)) + +// the last k bindings dropped (a block ends: what it bound goes) +def Ev.drop {r: Region} (env: Coll.List[Ev.Bind], k: I64): Coll.List[Ev.Bind] = if k <= 0 then env else env match + case Coll.Nil => Coll.Nil + case Coll.Cons(_, rest) => Ev.drop(rest, k - 1) + +// ── e in env, inside fn f (for messages) ── +def Ev.expr {r: Region} (cx: Ev.Cx, f: Sym.Sym, env: Coll.List[Ev.Bind], fuel: I64, e: Ast.Expr): Ev.R = e match + case Ast.Int(_, v) => Ev.Ok(Ev.VInt(v), env, fuel) + case Ast.Bool(_, v) => Ev.Ok(Ev.VBool(v), env, fuel) + case Ast.Str(_, s) => Ev.Ok(Ev.VStr(s), env, fuel) + case Ast.Unit(_) => Ev.Ok(Ev.VUnit, env, fuel) + case Ast.Name(line, x) => Ev.get(env, x) match + case Coll.Some(v) => Ev.Ok(v, env, fuel) + case Coll.None => Ev.call(cx, f, env, fuel, line, x, Coll.Nil) + case Ast.Call(line, g, _, _, xs) => Ev.call(cx, f, env, fuel, line, g, xs) + case Ast.Bin(line, op, l, x) => Ev.bin(cx, f, env, fuel, line, op, l, x) + case Ast.Un(line, op, x) => Ev.expr(cx, f, env, fuel, x) match + case Ev.Ok(v, env2, fuel2) => Ev.un(f, line, op, v, env2, fuel2) + case Ev.Err(x) => Ev.Err(x) + case Ast.If(line, c, t, x) => Ev.expr(cx, f, env, fuel, c) match + case Ev.Ok(v, env2, fuel2) => v match + case Ev.VBool(b) => if b then Ev.expr(cx, f, env2, fuel2, t) else Ev.expr(cx, f, env2, fuel2, x) + case _ => Ev.Err(Ev.NoValue(line, f)) + case Ev.Err(x) => Ev.Err(x) + case Ast.Match(line, s, arms) => Ev.expr(cx, f, env, fuel, s) match + case Ev.Ok(v, env2, fuel2) => Ev.arms(cx, f, env2, fuel2, line, v, arms) + case Ev.Err(x) => Ev.Err(x) + case Ast.Block(_, ss, last) => Ev.block(cx, f, env, fuel, ss, last, 0) + case Ast.While(line, c, b) => Ev.loop(cx, f, env, fuel, line, c, b) + case Ast.Assign(_, x, v) => Ev.expr(cx, f, env, fuel, v) match + case Ev.Ok(w, env2, fuel2) => Ev.Ok(Ev.VUnit, Ev.set(env2, x, w), fuel2) + case Ev.Err(x) => Ev.Err(x) + case Ast.Method(line, _, _, _) => Ev.Err(Ev.NoValue(line, f)) + case Ast.Quant(line, _, _, _, _) => Ev.Err(Ev.NoValue(line, f)) + +// args left to right, values in order +enum Ev.Rs: + case Ev.Vals(vs: Coll.List[Ev.V], env: Coll.List[Ev.Bind], fuel: I64) + case Ev.Errs(e: Ev.Fail) + +def Ev.args {r: Region} (cx: Ev.Cx, f: Sym.Sym, env: Coll.List[Ev.Bind], fuel: I64, xs: Coll.List[Ast.Expr], acc: Coll.List[Ev.V]): Ev.Rs = xs match + case Coll.Nil => Ev.Vals(Coll.rev(acc), env, fuel) + case Coll.Cons(x, rest) => Ev.expr(cx, f, env, fuel, x) match + case Ev.Ok(v, env2, fuel2) => Ev.args(cx, f, env2, fuel2, rest, Coll.Cons(v, acc)) + case Ev.Err(e) => Ev.Errs(e) + +// a constructor, a pure extern, or a def (its params bound, its body run with 1 fuel less) +def Ev.call {r: Region} (cx: Ev.Cx, f: Sym.Sym, env: Coll.List[Ev.Bind], fuel: I64, line: I64, g: Sym.Sym, xs: Coll.List[Ast.Expr]): Ev.R = + val Ev.Cx(fns, cases, imp) = cx + Ev.args(cx, f, env, fuel, xs, Coll.Nil) match + case Ev.Errs(e) => Ev.Err(e) + case Ev.Vals(vs, env2, fuel2) => Coll.sLookup(cases, g) match + case Coll.Some(_) => Ev.Ok(Ev.VData(g, vs), env2, fuel2) + case Coll.None => + if fuel2 <= 0 then Ev.Err(Ev.Fuel(line, f)) + else if Pure.has(imp, g) then Ev.Err(Ev.NoValue(line, g)) + else Coll.sLookup(fns, g) match + case Coll.None => Ev.Err(Ev.NoValue(line, g)) + case Coll.Some(fd) => + val Ast.Fn(_, _, _, ps, _, _, body) = fd + val env3 = Ev.bindAll(ps, vs, Coll.Nil) + body match + case Ast.Def(_, b) => Ev.result(Ev.expr(cx, g, env3, fuel2 - 1, b), env2) + case Ast.Spec(_, b) => Ev.result(Ev.expr(cx, g, env3, fuel2 - 1, b), env2) + case Ast.Extern => Ev.extern(line, g, vs, env2, fuel2) + +// the callee's value with the caller's locals +def Ev.result {r: Region} (res: Ev.R, env: Coll.List[Ev.Bind]): Ev.R = res match + case Ev.Ok(v, _, fuel) => Ev.Ok(v, env, fuel) + case Ev.Err(x) => Ev.Err(x) + +def Ev.bindAll {r: Region} (ps: Coll.List[Ast.Binder], vs: Coll.List[Ev.V], acc: Coll.List[Ev.Bind]): Coll.List[Ev.Bind] = ps match + case Coll.Nil => acc + case Coll.Cons(p, rest) => vs match + case Coll.Nil => acc + case Coll.Cons(v, vrest) => + val Ast.Binder(_, x, _) = p + Ev.bindAll(rest, vrest, Coll.Cons(Ev.Bind(x, v), acc)) + +// the pure externs (s2/pure.srs Pure.pureExtern) at compile time +def Ev.extern {r: Region} (line: I64, g: Sym.Sym, vs: Coll.List[Ev.V], env: Coll.List[Ev.Bind], fuel: I64): Ev.R = + val n = Sym.str(g) + if rt_str_eq(n, "rt_str_len") then Ev.str1(line, g, vs, env, fuel) + else Ev.str2(line, g, n, vs, env, fuel) + +def Ev.str1 {r: Region} (line: I64, g: Sym.Sym, vs: Coll.List[Ev.V], env: Coll.List[Ev.Bind], fuel: I64): Ev.R = vs match + case Coll.Cons(a, _) => a match + case Ev.VStr(s) => Ev.Ok(Ev.VInt(rt_str_len(s)), env, fuel) + case _ => Ev.Err(Ev.NoValue(line, g)) + case Coll.Nil => Ev.Err(Ev.NoValue(line, g)) + +def Ev.str2 {r: Region} (line: I64, g: Sym.Sym, n: Str, vs: Coll.List[Ev.V], env: Coll.List[Ev.Bind], fuel: I64): Ev.R = vs match + case Coll.Cons(a, rest) => rest match + case Coll.Cons(b, more) => a match + case Ev.VStr(s) => + if rt_str_eq(n, "rt_str_eq") then Ev.strEq(line, g, s, b, env, fuel) + else if rt_str_eq(n, "rt_str_at") then Ev.strAt(line, g, s, b, env, fuel) + else if rt_str_eq(n, "rt_str_slice") then Ev.strSlice(line, g, s, b, more, env, fuel) + else Ev.Err(Ev.NoValue(line, g)) + case _ => Ev.Err(Ev.NoValue(line, g)) + case Coll.Nil => Ev.Err(Ev.NoValue(line, g)) + case Coll.Nil => Ev.Err(Ev.NoValue(line, g)) + +def Ev.strEq {r: Region} (line: I64, g: Sym.Sym, s: Str, b: Ev.V, env: Coll.List[Ev.Bind], fuel: I64): Ev.R = b match + case Ev.VStr(t) => Ev.Ok(Ev.VBool(rt_str_eq(s, t)), env, fuel) + case _ => Ev.Err(Ev.NoValue(line, g)) + +def Ev.strAt {r: Region} (line: I64, g: Sym.Sym, s: Str, b: Ev.V, env: Coll.List[Ev.Bind], fuel: I64): Ev.R = b match + case Ev.VInt(i) => Ev.Ok(Ev.VInt(rt_str_at(s, i)), env, fuel) + case _ => Ev.Err(Ev.NoValue(line, g)) + +def Ev.strSlice {r: Region} (line: I64, g: Sym.Sym, s: Str, b: Ev.V, more: Coll.List[Ev.V], env: Coll.List[Ev.Bind], fuel: I64): Ev.R = b match + case Ev.VInt(i) => more match + case Coll.Cons(c, _) => c match + case Ev.VInt(j) => Ev.Ok(Ev.VStr(rt_str_slice(s, i, j)), env, fuel) + case _ => Ev.Err(Ev.NoValue(line, g)) + case Coll.Nil => Ev.Err(Ev.NoValue(line, g)) + case _ => Ev.Err(Ev.NoValue(line, g)) + +// && and || do not run their right side when the left decides +def Ev.bin {r: Region} (cx: Ev.Cx, f: Sym.Sym, env: Coll.List[Ev.Bind], fuel: I64, line: I64, op: Ast.BinOp, l: Ast.Expr, x: Ast.Expr): Ev.R = Ev.expr(cx, f, env, fuel, l) match + case Ev.Ok(a, env2, fuel2) => op match + case Ast.And => a match + case Ev.VBool(b) => if b then Ev.expr(cx, f, env2, fuel2, x) else Ev.Ok(a, env2, fuel2) + case _ => Ev.Err(Ev.NoValue(line, f)) + case Ast.Or => a match + case Ev.VBool(b) => if b then Ev.Ok(a, env2, fuel2) else Ev.expr(cx, f, env2, fuel2, x) + case _ => Ev.Err(Ev.NoValue(line, f)) + case _ => Ev.expr(cx, f, env2, fuel2, x) match + case Ev.Ok(b, env3, fuel3) => Ev.binV(f, line, op, a, b, env3, fuel3) + case Ev.Err(x) => Ev.Err(x) + case Ev.Err(x) => Ev.Err(x) + +def Ev.binV {r: Region} (f: Sym.Sym, line: I64, op: Ast.BinOp, a: Ev.V, b: Ev.V, env: Coll.List[Ev.Bind], fuel: I64): Ev.R = op match + case Ast.Eq => Ev.Ok(Ev.VBool(Ev.eq(a, b)), env, fuel) + case Ast.Ne => Ev.Ok(Ev.VBool(!Ev.eq(a, b)), env, fuel) + case _ => a match + case Ev.VInt(x) => b match + case Ev.VInt(y) => Ev.binI(f, line, op, x, y, env, fuel) + case _ => Ev.Err(Ev.NoValue(line, f)) + case _ => Ev.Err(Ev.NoValue(line, f)) + +def Ev.binI {r: Region} (f: Sym.Sym, line: I64, op: Ast.BinOp, x: I64, y: I64, env: Coll.List[Ev.Bind], fuel: I64): Ev.R = op match + case Ast.Add => Ev.Ok(Ev.VInt(x + y), env, fuel) + case Ast.Sub => Ev.Ok(Ev.VInt(x - y), env, fuel) + case Ast.Mul => Ev.Ok(Ev.VInt(x * y), env, fuel) + case Ast.Div => if y == 0 then Ev.Err(Ev.DivZero(line, f)) else Ev.Ok(Ev.VInt(x / y), env, fuel) + case Ast.Mod => if y == 0 then Ev.Err(Ev.DivZero(line, f)) else Ev.Ok(Ev.VInt(x % y), env, fuel) + case Ast.Lt => Ev.Ok(Ev.VBool(x < y), env, fuel) + case Ast.Le => Ev.Ok(Ev.VBool(x <= y), env, fuel) + case Ast.Gt => Ev.Ok(Ev.VBool(x > y), env, fuel) + case Ast.Ge => Ev.Ok(Ev.VBool(x >= y), env, fuel) + case _ => Ev.Err(Ev.NoValue(line, f)) + +def Ev.un {r: Region} (f: Sym.Sym, line: I64, op: Ast.UnOp, v: Ev.V, env: Coll.List[Ev.Bind], fuel: I64): Ev.R = op match + case Ast.Neg => v match + case Ev.VInt(x) => Ev.Ok(Ev.VInt(0 - x), env, fuel) + case _ => Ev.Err(Ev.NoValue(line, f)) + case Ast.Not => v match + case Ev.VBool(b) => Ev.Ok(Ev.VBool(!b), env, fuel) + case _ => Ev.Err(Ev.NoValue(line, f)) + +def Ev.eq(a: Ev.V, b: Ev.V): Bool = a match + case Ev.VUnit => b match + case Ev.VUnit => true + case _ => false + case Ev.VInt(x) => b match + case Ev.VInt(y) => x == y + case _ => false + case Ev.VBool(x) => b match + case Ev.VBool(y) => x == y + case _ => false + case Ev.VStr(x) => b match + case Ev.VStr(y) => rt_str_eq(x, y) + case _ => false + case Ev.VData(c, fs) => b match + case Ev.VData(d, gs) => Sym.eq(c, d) && Ev.eqAll(fs, gs) + case _ => false + +def Ev.eqAll(xs: Coll.List[Ev.V], ys: Coll.List[Ev.V]): Bool = xs match + case Coll.Nil => ys match + case Coll.Nil => true + case Coll.Cons(_, _) => false + case Coll.Cons(x, xt) => ys match + case Coll.Nil => false + case Coll.Cons(y, yt) => if Ev.eq(x, y) then Ev.eqAll(xt, yt) else false + +// the first arm whose case is the value's (or `_`), its binders bound to the fields +def Ev.arms {r: Region} (cx: Ev.Cx, f: Sym.Sym, env: Coll.List[Ev.Bind], fuel: I64, line: I64, v: Ev.V, as: Coll.List[Ast.Arm]): Ev.R = as match + case Coll.Nil => Ev.Err(Ev.NoValue(line, f)) + case Coll.Cons(a, rest) => + val Ast.Arm(_, p, b) = a + p match + case Ast.PAny => Ev.expr(cx, f, env, fuel, b) + case Ast.PCase(c, binds) => v match + case Ev.VData(d, fs) => + if Sym.eq(c, d) then + val env2 = Ev.bindPat(binds, fs, env) + Ev.result(Ev.expr(cx, f, env2, fuel, b), env) + else Ev.arms(cx, f, env, fuel, line, v, rest) + case _ => Ev.Err(Ev.NoValue(line, f)) + +def Ev.bindPat {r: Region} (xs: Coll.List[Sym.Sym], vs: Coll.List[Ev.V], env: Coll.List[Ev.Bind]): Coll.List[Ev.Bind] = xs match + case Coll.Nil => env + case Coll.Cons(x, rest) => vs match + case Coll.Nil => env + case Coll.Cons(v, vrest) => Ev.bindPat(rest, vrest, if rt_str_eq(Sym.str(x), "_") then env else Coll.Cons(Ev.Bind(x, v), env)) + +// a block: each statement in turn, k = the bindings it made; they go when it ends +def Ev.block {r: Region} (cx: Ev.Cx, f: Sym.Sym, env: Coll.List[Ev.Bind], fuel: I64, ss: Coll.List[Ast.Stmt], last: Ast.Expr, k: I64): Ev.R = ss match + case Coll.Nil => Ev.expr(cx, f, env, fuel, last) match + case Ev.Ok(v, env2, fuel2) => Ev.Ok(v, Ev.drop(env2, k), fuel2) + case Ev.Err(x) => Ev.Err(x) + case Coll.Cons(s, rest) => s match + case Ast.Val(_, x, _, e) => Ev.bindStmt(cx, f, env, fuel, x, e, rest, last, k) + case Ast.Var(_, x, _, e) => Ev.bindStmt(cx, f, env, fuel, x, e, rest, last, k) + case Ast.Do(e) => Ev.expr(cx, f, env, fuel, e) match + case Ev.Ok(_, env2, fuel2) => Ev.block(cx, f, env2, fuel2, rest, last, k) + case Ev.Err(x) => Ev.Err(x) + case Ast.Check(_, _, _) => Ev.block(cx, f, env, fuel, rest, last, k) + case Ast.Handle(line, _, _, _) => Ev.Err(Ev.NoValue(line, f)) + +def Ev.bindStmt {r: Region} (cx: Ev.Cx, f: Sym.Sym, env: Coll.List[Ev.Bind], fuel: I64, x: Sym.Sym, e: Ast.Expr, rest: Coll.List[Ast.Stmt], last: Ast.Expr, k: I64): Ev.R = Ev.expr(cx, f, env, fuel, e) match + case Ev.Ok(v, env2, fuel2) => Ev.block(cx, f, Coll.Cons(Ev.Bind(x, v), env2), fuel2, rest, last, k + 1) + case Ev.Err(x) => Ev.Err(x) + +// a loop: 1 fuel per turn +def Ev.loop {r: Region} (cx: Ev.Cx, f: Sym.Sym, env: Coll.List[Ev.Bind], fuel: I64, line: I64, c: Ast.Expr, b: Ast.Expr): Ev.R = + if fuel <= 0 then Ev.Err(Ev.Fuel(line, f)) + else Ev.expr(cx, f, env, fuel, c) match + case Ev.Ok(v, env2, fuel2) => v match + case Ev.VBool(go) => + if go then Ev.expr(cx, f, env2, fuel2, b) match + case Ev.Ok(_, env3, fuel3) => Ev.loop(cx, f, env3, fuel3 - 1, line, c, b) + case Ev.Err(x) => Ev.Err(x) + else Ev.Ok(Ev.VUnit, env2, fuel2) + case _ => Ev.Err(Ev.NoValue(line, f)) + case Ev.Err(x) => Ev.Err(x) + +// ── `s2c --eval`: "name value" for each nullary pure def but main; a fail is a reject ── +enum Ev.Line: + case Ev.Shown(name: Sym.Sym, v: Ev.V) + +enum Ev.Out: + case Ev.Lines(ls: Coll.List[Ev.Line]) + case Ev.Failed(e: Ev.Fail) + +def Ev.all {r: Region} (ds: Coll.List[Ast.Decl], imp: Coll.SMap[Bool]): Ev.Out = Ev.run(Ev.cxOf(ds, imp), ds, Coll.Nil) + +def Ev.run {r: Region} (cx: Ev.Cx, ds: Coll.List[Ast.Decl], acc: Coll.List[Ev.Line]): Ev.Out = ds match + case Coll.Nil => Ev.Lines(Coll.rev(acc)) + case Coll.Cons(d, rest) => d match + case Ast.DFn(f) => + val Ast.Fn(_, n, gs, ps, _, _, body) = f + val Ev.Cx(_, _, imp) = cx + val nullary = Coll.length(ps) == 0 && Coll.length(gs) == 0 && !rt_str_eq(Sym.str(n), "main") && !Pure.has(imp, n) + val be: Coll.Option[Ast.Expr] = body match + case Ast.Def(_, e) => Coll.Some(e) + case Ast.Spec(_, e) => Coll.Some(e) + case Ast.Extern => Coll.None + be match + case Coll.Some(e) => + if nullary then Ev.expr(cx, n, Coll.Nil, Ev.fuel(), e) match + case Ev.Ok(v, _, _) => Ev.run(cx, rest, Coll.Cons(Ev.Shown(n, v), acc)) + case Ev.Err(err) => Ev.Failed(err) + else Ev.run(cx, rest, acc) + case Coll.None => Ev.run(cx, rest, acc) + case _ => Ev.run(cx, rest, acc) + +def Ev.show(v: Ev.V): Unit = v match + case Ev.VUnit => rt_print("()") + case Ev.VInt(n) => rt_print_i64(n) + case Ev.VBool(b) => rt_print(if b then "true" else "false") + case Ev.VStr(s) => rt_print(s) + case Ev.VData(c, fs) => + rt_print(Sym.str(c)) + fs match + case Coll.Nil => () + case Coll.Cons(h, t) => + rt_print("(") + Ev.show(h) + Ev.showRest(t) + rt_print(")") + +def Ev.showRest(fs: Coll.List[Ev.V]): Unit = fs match + case Coll.Nil => () + case Coll.Cons(h, t) => + rt_print(", ") + Ev.show(h) + Ev.showRest(t) diff --git a/bench/corpus/s2/facts.srs b/bench/corpus/s2/facts.srs new file mode 100644 index 00000000..58848de5 --- /dev/null +++ b/bench/corpus/s2/facts.srs @@ -0,0 +1,369 @@ +// s2 fact groups and rule defs well-formed (s1/facts.srs checks), as a Datalog rule library: the source gives facts, a +// clash is a derived (line, name) row. a def's <> groups: entry (g 0, before the params) and exit (g 1, after the result). +// in at(x, S) x is a {} capability of the def and S a state of its protocol (an upper-case S) or a variable; in +// next(s, op, t) op is an op of a protocol of the def's capabilities; any other relation is a rule def of one of them, +// with its arity. an exit variable is bound by the entry facts; an exit fact is an at. a protocol's rule defs: not named +// at or next, one arity per name, each param in the body, each body relation a rule def of the protocol, each next op +// an op of the protocol. + +enum Fx.Clash: + case Fx.NotCap(line: I64, x: Sym.Sym) + case Fx.BadState(line: I64, s: Sym.Sym) + case Fx.Twice(line: I64, x: Sym.Sym) + case Fx.NotOp(line: I64, op: Sym.Sym) + case Fx.UnknownRel(line: I64, rel: Sym.Sym) + case Fx.RelArity(line: I64, rel: Sym.Sym) + case Fx.Unbound(line: I64, v: Sym.Sym) + case Fx.ExitOther(line: I64, rel: Sym.Sym) + case Fx.Reserved(line: I64, rel: Sym.Sym) + case Fx.ClauseArity(line: I64, rel: Sym.Sym) + case Fx.Unsafe(line: I64, x: Sym.Sym) + case Fx.RuleUnknown(line: I64, rel: Sym.Sym) + case Fx.RuleOp(line: I64, op: Sym.Sym) + +enum Fx.Verdict: + case Fx.Ok + case Fx.Bad(cs: Coll.List[Fx.Clash]) + // the rule library is not Datalog, or a clash row of another shape: a bug in Fx.rules, as data + case Fx.RulesBad(rel: Sym.Sym) + +enum Fx.Rel: + case Fx.RCap + case Fx.RState + case Fx.ROpOf + case Fx.RRuleRel + case Fx.RSameN + case Fx.RUseAt + case Fx.RAtState + case Fx.RAtId + case Fx.RAtLine + case Fx.RSameId + case Fx.RUseNext + case Fx.RUseRel + case Fx.RExitOther + case Fx.RVarIn + case Fx.RParam + case Fx.RBodyVar + case Fx.RRUse + case Fx.RRNext + case Fx.RReserved + case Fx.RIsCap + case Fx.RDefOp + case Fx.RDefRel + case Fx.RDefRelN + case Fx.RVar0 + case Fx.RRRel + case Fx.RNotCapAt + case Fx.RBadStateAt + case Fx.RTwiceAt + case Fx.RNotOpAt + case Fx.RUnknownRelAt + case Fx.RRelArityAt + case Fx.RUnboundAt + case Fx.RExitOtherAt + case Fx.RReservedAt + case Fx.RClauseArityAt + case Fx.RUnsafeAt + case Fx.RRuleUnknownAt + case Fx.RRuleOpAt + +def Fx.relSym {r: Region} (rel: Fx.Rel): Sym.Sym = rel match + case Fx.RCap => Sym.of("fxCap") + case Fx.RState => Sym.of("fxState") + case Fx.ROpOf => Sym.of("fxOpOf") + case Fx.RRuleRel => Sym.of("fxRuleRel") + case Fx.RSameN => Sym.of("fxSameN") + case Fx.RUseAt => Sym.of("fxUseAt") + case Fx.RAtState => Sym.of("fxAtState") + case Fx.RAtId => Sym.of("fxAtId") + case Fx.RAtLine => Sym.of("fxAtLine") + case Fx.RSameId => Sym.of("fxSameId") + case Fx.RUseNext => Sym.of("fxUseNext") + case Fx.RUseRel => Sym.of("fxUseRel") + case Fx.RExitOther => Sym.of("fxExitOther") + case Fx.RVarIn => Sym.of("fxVarIn") + case Fx.RParam => Sym.of("fxParam") + case Fx.RBodyVar => Sym.of("fxBodyVar") + case Fx.RRUse => Sym.of("fxRUse") + case Fx.RRNext => Sym.of("fxRNext") + case Fx.RReserved => Sym.of("fxReserved") + case Fx.RIsCap => Sym.of("fxIsCap") + case Fx.RDefOp => Sym.of("fxDefOp") + case Fx.RDefRel => Sym.of("fxDefRel") + case Fx.RDefRelN => Sym.of("fxDefRelN") + case Fx.RVar0 => Sym.of("fxVar0") + case Fx.RRRel => Sym.of("fxRRel") + case Fx.RNotCapAt => Sym.of("fxNotCapAt") + case Fx.RBadStateAt => Sym.of("fxBadStateAt") + case Fx.RTwiceAt => Sym.of("fxTwiceAt") + case Fx.RNotOpAt => Sym.of("fxNotOpAt") + case Fx.RUnknownRelAt => Sym.of("fxUnknownRelAt") + case Fx.RRelArityAt => Sym.of("fxRelArityAt") + case Fx.RUnboundAt => Sym.of("fxUnboundAt") + case Fx.RExitOtherAt => Sym.of("fxExitOtherAt") + case Fx.RReservedAt => Sym.of("fxReservedAt") + case Fx.RClauseArityAt => Sym.of("fxClauseArityAt") + case Fx.RUnsafeAt => Sym.of("fxUnsafeAt") + case Fx.RRuleUnknownAt => Sym.of("fxRuleUnknownAt") + case Fx.RRuleOpAt => Sym.of("fxRuleOpAt") + +// ── rule builders: a var by number, a constant, an atom ── +def Fx.v {r: Region} (n: I64): D.Arg = D.AVar(n) +def Fx.c {r: Region} (n: I64): D.Arg = D.AVal(D.VInt(n)) +def Fx.at {r: Region} (rel: Fx.Rel, xs: Coll.List[D.Arg]): D.Atom = D.Atom(Fx.relSym(rel), xs) +def Fx.p {r: Region} (rel: Fx.Rel, xs: Coll.List[D.Arg]): D.Lit = D.Pos(Fx.at(rel, xs)) +def Fx.n {r: Region} (rel: Fx.Rel, xs: Coll.List[D.Arg]): D.Lit = D.Neg(Fx.at(rel, xs)) +def Fx.vs {r: Region} (xs: Coll.List[I64]): Coll.List[D.Arg] = xs match + case Coll.Nil => Coll.Nil + case Coll.Cons(x, rest) => Coll.Cons(Fx.v(x), Fx.vs(rest)) +def Fx.l1 [A: Type] {r: Region} (a: A): Coll.List[A] = Coll.Cons(a, Coll.Nil) +def Fx.l2 [A: Type] {r: Region} (a: A, b: A): Coll.List[A] = Coll.Cons(a, Fx.l1(b)) +def Fx.l3 [A: Type] {r: Region} (a: A, b: A, c: A): Coll.List[A] = Coll.Cons(a, Fx.l2(b, c)) +def Fx.l4 [A: Type] {r: Region} (a: A, b: A, c: A, d: A): Coll.List[A] = Coll.Cons(a, Fx.l3(b, c, d)) +def Fx.l5 [A: Type] {r: Region} (a: A, b: A, c: A, d: A, e: A): Coll.List[A] = Coll.Cons(a, Fx.l4(b, c, d, e)) +def Fx.rule {r: Region} (rel: Fx.Rel, hs: Coll.List[I64], body: Coll.List[D.Lit]): D.Rule = D.Rule(Fx.at(rel, Fx.vs(hs)), body) + +def Fx.rules {r: Region} (): Coll.List[D.Rule] = + val isCap = Fx.rule(Fx.RIsCap, Fx.l2(0, 1), Fx.l1(Fx.p(Fx.RCap, Fx.vs(Fx.l3(0, 1, 2))))) + val defOp = Fx.rule(Fx.RDefOp, Fx.l2(0, 3), Fx.l2(Fx.p(Fx.RCap, Fx.vs(Fx.l3(0, 1, 2))), Fx.p(Fx.ROpOf, Fx.vs(Fx.l2(2, 3))))) + val defRel = Fx.rule(Fx.RDefRel, Fx.l2(0, 3), Fx.l2(Fx.p(Fx.RCap, Fx.vs(Fx.l3(0, 1, 2))), Fx.p(Fx.RRuleRel, Fx.vs(Fx.l4(2, 3, 4, 5))))) + val defRelN = Fx.rule(Fx.RDefRelN, Fx.l3(0, 3, 4), Fx.l2(Fx.p(Fx.RCap, Fx.vs(Fx.l3(0, 1, 2))), Fx.p(Fx.RRuleRel, Fx.vs(Fx.l4(2, 3, 4, 5))))) + val var0 = Fx.rule(Fx.RVar0, Fx.l2(0, 2), Fx.l1(Fx.p(Fx.RVarIn, Fx.l4(Fx.v(0), Fx.c(0), Fx.v(2), Fx.v(3))))) + val rrel = Fx.rule(Fx.RRRel, Fx.l2(0, 1), Fx.l1(Fx.p(Fx.RRuleRel, Fx.vs(Fx.l4(0, 1, 2, 3))))) + val notCap = Fx.rule(Fx.RNotCapAt, Fx.l2(3, 2), Fx.l2(Fx.p(Fx.RUseAt, Fx.vs(Fx.l4(0, 1, 2, 3))), Fx.n(Fx.RIsCap, Fx.vs(Fx.l2(0, 2))))) + val badState = Fx.rule(Fx.RBadStateAt, Fx.l2(4, 3), Fx.l3(Fx.p(Fx.RAtState, Fx.vs(Fx.l5(0, 1, 2, 3, 4))), Fx.p(Fx.RCap, Fx.vs(Fx.l3(0, 2, 5))), Fx.n(Fx.RState, Fx.vs(Fx.l2(5, 3))))) + val twice = Fx.rule(Fx.RTwiceAt, Fx.l2(5, 2), Fx.l4(Fx.p(Fx.RAtId, Fx.vs(Fx.l4(0, 1, 2, 3))), Fx.p(Fx.RAtId, Fx.vs(Fx.l4(0, 1, 2, 4))), Fx.n(Fx.RSameId, Fx.vs(Fx.l2(3, 4))), Fx.p(Fx.RAtLine, Fx.vs(Fx.l2(3, 5))))) + val notOp = Fx.rule(Fx.RNotOpAt, Fx.l2(2, 1), Fx.l2(Fx.p(Fx.RUseNext, Fx.vs(Fx.l3(0, 1, 2))), Fx.n(Fx.RDefOp, Fx.vs(Fx.l2(0, 1))))) + val unknownRel = Fx.rule(Fx.RUnknownRelAt, Fx.l2(3, 1), Fx.l2(Fx.p(Fx.RUseRel, Fx.vs(Fx.l4(0, 1, 2, 3))), Fx.n(Fx.RDefRel, Fx.vs(Fx.l2(0, 1))))) + val relArity = Fx.rule(Fx.RRelArityAt, Fx.l2(3, 1), Fx.l3(Fx.p(Fx.RUseRel, Fx.vs(Fx.l4(0, 1, 2, 3))), Fx.p(Fx.RDefRel, Fx.vs(Fx.l2(0, 1))), Fx.n(Fx.RDefRelN, Fx.vs(Fx.l3(0, 1, 2))))) + val unbound = Fx.rule(Fx.RUnboundAt, Fx.l2(3, 2), Fx.l2(Fx.p(Fx.RVarIn, Fx.l4(Fx.v(0), Fx.c(1), Fx.v(2), Fx.v(3))), Fx.n(Fx.RVar0, Fx.vs(Fx.l2(0, 2))))) + val exitOther = Fx.rule(Fx.RExitOtherAt, Fx.l2(1, 0), Fx.l1(Fx.p(Fx.RExitOther, Fx.vs(Fx.l2(0, 1))))) + val reserved = Fx.rule(Fx.RReservedAt, Fx.l2(1, 0), Fx.l1(Fx.p(Fx.RReserved, Fx.vs(Fx.l2(0, 1))))) + val clauseArity = Fx.rule(Fx.RClauseArityAt, Fx.l2(3, 1), Fx.l3(Fx.p(Fx.RRuleRel, Fx.vs(Fx.l4(0, 1, 2, 3))), Fx.p(Fx.RRuleRel, Fx.vs(Fx.l4(0, 1, 4, 5))), Fx.n(Fx.RSameN, Fx.vs(Fx.l2(2, 4))))) + val unsafe = Fx.rule(Fx.RUnsafeAt, Fx.l2(2, 1), Fx.l2(Fx.p(Fx.RParam, Fx.vs(Fx.l3(0, 1, 2))), Fx.n(Fx.RBodyVar, Fx.vs(Fx.l2(0, 1))))) + val ruleUnknown = Fx.rule(Fx.RRuleUnknownAt, Fx.l2(2, 1), Fx.l2(Fx.p(Fx.RRUse, Fx.vs(Fx.l3(0, 1, 2))), Fx.n(Fx.RRRel, Fx.vs(Fx.l2(0, 1))))) + val ruleOp = Fx.rule(Fx.RRuleOpAt, Fx.l2(2, 1), Fx.l2(Fx.p(Fx.RRNext, Fx.vs(Fx.l3(0, 1, 2))), Fx.n(Fx.ROpOf, Fx.vs(Fx.l2(0, 1))))) + val a = Fx.l5(isCap, defOp, defRel, defRelN, var0) + val b = Fx.l5(rrel, notCap, badState, twice, notOp) + val c = Fx.l5(unknownRel, relArity, unbound, exitOther, reserved) + val d = Fx.l4(clauseArity, unsafe, ruleUnknown, ruleOp) + Coll.revOnto(Coll.rev(a), Coll.revOnto(Coll.rev(b), Coll.revOnto(Coll.rev(c), d))) + +// ── facts ── +def Fx.s {r: Region} (x: Sym.Sym): D.Val = D.VSym(x) +def Fx.i {r: Region} (n: I64): D.Val = D.VInt(n) +def Fx.fact {r: Region} (rel: Fx.Rel, vs: Coll.List[D.Val]): D.Fact = D.Fact(Fx.relSym(rel), vs) + +// the walk: the next id (atoms, rule defs) and the facts +enum Fx.St: + case Fx.St(next: I64, facts: Coll.List[D.Fact]) + +def Fx.add {r: Region} (st: Fx.St, f: D.Fact): Fx.St = + val Fx.St(n, fs) = st + Fx.St(n, Coll.Cons(f, fs)) + +def Fx.fresh(st: Fx.St): I64 = + val Fx.St(n, _) = st + n + +def Fx.bump {r: Region} (st: Fx.St): Fx.St = + val Fx.St(n, fs) = st + Fx.St(n + 1, fs) + +// a state or a variable: a name that starts with an upper-case letter is a state +def Fx.isConst(x: Sym.Sym): Bool = + val c = rt_str_at(Sym.str(x), 0) + c >= 65 && c <= 90 + +def Fx.sameNs {r: Region} (n: I64, st: Fx.St): Fx.St = if n < 0 then st else Fx.sameNs(n - 1, Fx.add(st, Fx.fact(Fx.RSameN, Fx.l2(Fx.i(n), Fx.i(n))))) + +def Fx.facts {r: Region} (ds: Coll.List[Ast.Decl]): Coll.List[D.Fact] = + val ps = Pure.protos(ds, Coll.Nil) + val Fx.St(_, fs) = Fx.decls(ps, ds, Fx.sameNs(16, Fx.St(0, Coll.Nil))) + fs + +def Fx.decls {r: Region} (ps: Coll.List[Sym.Sym], ds: Coll.List[Ast.Decl], st: Fx.St): Fx.St = ds match + case Coll.Nil => st + case Coll.Cons(d, rest) => d match + case Ast.DProto(p) => Fx.decls(ps, rest, Fx.proto(p, st)) + case Ast.DFn(f) => Fx.decls(ps, rest, Fx.fn(ps, f, st)) + case Ast.DType(td) => + val Ast.TypeDecl(_, n, gs, _, _) = td + Fx.decls(ps, rest, Fx.groups(n, gs, Fx.caps(ps, n, Ty.evidence(gs, Coll.Nil), st))) + case _ => Fx.decls(ps, rest, st) + +def Fx.proto {r: Region} (p: Ast.Proto, st: Fx.St): Fx.St = + val Ast.Proto(_, n, states, _, _, _, ops, rules) = p + Fx.ruleDefs(n, rules, Fx.opsF(n, ops, Fx.statesF(n, states, st))) + +def Fx.statesF {r: Region} (p: Sym.Sym, ss: Coll.List[Sym.Sym], st: Fx.St): Fx.St = ss match + case Coll.Nil => st + case Coll.Cons(s, rest) => Fx.statesF(p, rest, Fx.add(st, Fx.fact(Fx.RState, Fx.l2(Fx.s(p), Fx.s(s))))) + +def Fx.opsF {r: Region} (p: Sym.Sym, os: Coll.List[Ast.Op], st: Fx.St): Fx.St = os match + case Coll.Nil => st + case Coll.Cons(o, rest) => + val Ast.Op(_, n, _, _, _) = o + Fx.opsF(p, rest, Fx.add(st, Fx.fact(Fx.ROpOf, Fx.l2(Fx.s(p), Fx.s(n))))) + +// a rule def: its relation and arity; reserved names; its params; its body's names and relations +def Fx.ruleDefs {r: Region} (p: Sym.Sym, rs: Coll.List[Ast.RuleDef], st: Fx.St): Fx.St = rs match + case Coll.Nil => st + case Coll.Cons(rd, rest) => + val Ast.RuleDef(line, n, params, body) = rd + val rid = Fx.fresh(st) + val st1 = Fx.add(Fx.bump(st), Fx.fact(Fx.RRuleRel, Fx.l4(Fx.s(p), Fx.s(n), Fx.i(Coll.length(params)), Fx.i(line)))) + val st2 = if Fx.builtinRel(n) then Fx.add(st1, Fx.fact(Fx.RReserved, Fx.l2(Fx.s(n), Fx.i(line)))) else st1 + Fx.ruleDefs(p, rest, Fx.bodyAtoms(p, rid, body, Fx.params(rid, line, params, st2))) + +def Fx.builtinRel(n: Sym.Sym): Bool = rt_str_eq(Sym.str(n), "at") || rt_str_eq(Sym.str(n), "next") + +def Fx.params {r: Region} (rid: I64, line: I64, xs: Coll.List[Sym.Sym], st: Fx.St): Fx.St = xs match + case Coll.Nil => st + case Coll.Cons(x, rest) => Fx.params(rid, line, rest, Fx.add(st, Fx.fact(Fx.RParam, Fx.l3(Fx.i(rid), Fx.s(x), Fx.i(line))))) + +def Fx.bodyAtoms {r: Region} (p: Sym.Sym, rid: I64, as: Coll.List[Ast.Atom], st: Fx.St): Fx.St = as match + case Coll.Nil => st + case Coll.Cons(a, rest) => + val Ast.Atom(line, rel, args) = a + val st1 = Fx.bodyNames(rid, args, st) + Fx.bodyAtoms(p, rid, rest, Fx.bodyRel(p, line, rel, args, st1)) + +// next names an op; at is the protocol's own; any other relation is a use of a rule def +def Fx.bodyRel {r: Region} (p: Sym.Sym, line: I64, rel: Sym.Sym, args: Coll.List[Ast.Term], st: Fx.St): Fx.St = + if rt_str_eq(Sym.str(rel), "next") then Fx.ruleNext(p, line, args, st) + else if rt_str_eq(Sym.str(rel), "at") then st + else Fx.add(st, Fx.fact(Fx.RRUse, Fx.l3(Fx.s(p), Fx.s(rel), Fx.i(line)))) + +def Fx.bodyNames {r: Region} (rid: I64, ts: Coll.List[Ast.Term], st: Fx.St): Fx.St = ts match + case Coll.Nil => st + case Coll.Cons(t, rest) => t match + case Ast.TName(x) => Fx.bodyNames(rid, rest, Fx.add(st, Fx.fact(Fx.RBodyVar, Fx.l2(Fx.i(rid), Fx.s(x))))) + case Ast.TNum(_) => Fx.bodyNames(rid, rest, st) + +// the op of next(s, op, t): its second arg +def Fx.ruleNext {r: Region} (p: Sym.Sym, line: I64, ts: Coll.List[Ast.Term], st: Fx.St): Fx.St = Fx.nth(ts, 1) match + case Coll.Some(op) => Fx.add(st, Fx.fact(Fx.RRNext, Fx.l3(Fx.s(p), Fx.s(op), Fx.i(line)))) + case Coll.None => st + +def Fx.nth {r: Region} (ts: Coll.List[Ast.Term], i: I64): Coll.Option[Sym.Sym] = ts match + case Coll.Nil => Coll.None + case Coll.Cons(t, rest) => + if i == 0 then t match + case Ast.TName(x) => Coll.Some(x) + case Ast.TNum(_) => Coll.None + else Fx.nth(rest, i - 1) + +// a def: its {} capabilities, its entry groups (g 0) and its exit facts (g 1) +def Fx.fn {r: Region} (ps: Coll.List[Sym.Sym], f: Ast.Fn, st: Fx.St): Fx.St = + val Ast.Fn(_, d, gs, _, _, exit, _) = f + val st1 = Fx.caps(ps, d, Ty.evidence(gs, Coll.Nil), st) + Fx.atoms(d, 1, exit, Fx.groups(d, gs, st1)) + +def Fx.caps {r: Region} (ps: Coll.List[Sym.Sym], d: Sym.Sym, bs: Coll.List[Ast.Binder], st: Fx.St): Fx.St = bs match + case Coll.Nil => st + case Coll.Cons(b, rest) => + val Ast.Binder(_, x, t) = b + val Ast.Ty(_, n, _, _, _) = t + Fx.caps(ps, d, rest, if Ty.memberSym(n, ps) then Fx.add(st, Fx.fact(Fx.RCap, Fx.l3(Fx.s(d), Fx.s(x), Fx.s(n)))) else st) + +def Fx.groups {r: Region} (d: Sym.Sym, gs: Coll.List[Ast.Group], st: Fx.St): Fx.St = gs match + case Coll.Nil => st + case Coll.Cons(g, rest) => g match + case Ast.Facts(as) => Fx.groups(d, rest, Fx.atoms(d, 0, as, st)) + case _ => Fx.groups(d, rest, st) + +def Fx.atoms {r: Region} (d: Sym.Sym, g: I64, as: Coll.List[Ast.Atom], st: Fx.St): Fx.St = as match + case Coll.Nil => st + case Coll.Cons(a, rest) => Fx.atoms(d, g, rest, Fx.atom(d, g, a, st)) + +def Fx.atom {r: Region} (d: Sym.Sym, g: I64, a: Ast.Atom, st: Fx.St): Fx.St = + val Ast.Atom(line, rel, args) = a + val rn = Sym.str(rel) + if rt_str_eq(rn, "at") then Fx.atAtom(d, g, line, args, st) + else + val st1 = Fx.varsFrom(d, g, line, args, 0, Fx.opPos(rel), st) + if rt_str_eq(rn, "next") then Fx.nth(args, 1) match + case Coll.Some(op) => Fx.add(st1, Fx.fact(Fx.RUseNext, Fx.l3(Fx.s(d), Fx.s(op), Fx.i(line)))) + case Coll.None => st1 + else + val st2 = Fx.add(st1, Fx.fact(Fx.RUseRel, Fx.l4(Fx.s(d), Fx.s(rel), Fx.i(Coll.length(args)), Fx.i(line)))) + if g == 1 then Fx.add(st2, Fx.fact(Fx.RExitOther, Fx.l2(Fx.s(rel), Fx.i(line)))) else st2 + +// at(x, S): x a capability; S a state (constant) or a variable; one id per at atom (two of one x in a group clash) +def Fx.atAtom {r: Region} (d: Sym.Sym, g: I64, line: I64, args: Coll.List[Ast.Term], st: Fx.St): Fx.St = Fx.nth(args, 0) match + case Coll.None => st + case Coll.Some(x) => + val id = Fx.fresh(st) + val st1 = Fx.add(Fx.add(Fx.add(Fx.add(Fx.bump(st), Fx.fact(Fx.RUseAt, Fx.l4(Fx.s(d), Fx.i(g), Fx.s(x), Fx.i(line)))), Fx.fact(Fx.RAtId, Fx.l4(Fx.s(d), Fx.i(g), Fx.s(x), Fx.i(id)))), Fx.fact(Fx.RAtLine, Fx.l2(Fx.i(id), Fx.i(line)))), Fx.fact(Fx.RSameId, Fx.l2(Fx.i(id), Fx.i(id)))) + Fx.nth(args, 1) match + case Coll.None => st1 + case Coll.Some(s) => + if Fx.isConst(s) then Fx.add(st1, Fx.fact(Fx.RAtState, Fx.l5(Fx.s(d), Fx.i(g), Fx.s(x), Fx.s(s), Fx.i(line)))) + else Fx.add(st1, Fx.fact(Fx.RVarIn, Fx.l4(Fx.s(d), Fx.i(g), Fx.s(s), Fx.i(line)))) + +// the variables of an atom: its lower-case names, except the op of next(s, op, t) (Fx.opPos) +def Fx.varsFrom {r: Region} (d: Sym.Sym, g: I64, line: I64, ts: Coll.List[Ast.Term], i: I64, op: Coll.Option[I64], st: Fx.St): Fx.St = ts match + case Coll.Nil => st + case Coll.Cons(t, rest) => t match + case Ast.TNum(_) => Fx.varsFrom(d, g, line, rest, i + 1, op, st) + case Ast.TName(x) => + if Fx.isConst(x) || Fx.isPos(op, i) then Fx.varsFrom(d, g, line, rest, i + 1, op, st) + else Fx.varsFrom(d, g, line, rest, i + 1, op, Fx.add(st, Fx.fact(Fx.RVarIn, Fx.l4(Fx.s(d), Fx.i(g), Fx.s(x), Fx.i(line))))) + +// ── the verdict: each clash relation read as (line, name) ── +def Fx.check {r: Region} (ds: Coll.List[Ast.Decl]): Fx.Verdict = D.solve(Fx.rules(), Fx.facts(ds)) match + case D.Solved(m) => Fx.readAll(m, Fx.kinds(), Coll.Nil) + case D.Unsafe(rel) => Fx.RulesBad(rel) + case D.NegCycle(rel) => Fx.RulesBad(rel) + +def Fx.kinds {r: Region} (): Coll.List[Fx.Rel] = + val a = Fx.l5(Fx.RNotCapAt, Fx.RBadStateAt, Fx.RTwiceAt, Fx.RNotOpAt, Fx.RUnknownRelAt) + val b = Fx.l4(Fx.RRelArityAt, Fx.RUnboundAt, Fx.RExitOtherAt, Fx.RReservedAt) + val c = Fx.l4(Fx.RClauseArityAt, Fx.RUnsafeAt, Fx.RRuleUnknownAt, Fx.RRuleOpAt) + Coll.revOnto(Coll.rev(a), Coll.revOnto(Coll.rev(b), c)) + +def Fx.readAll {r: Region} (m: D.Model, ks: Coll.List[Fx.Rel], acc: Coll.List[Fx.Clash]): Fx.Verdict = ks match + case Coll.Nil => acc match + case Coll.Nil => Fx.Ok + case Coll.Cons(_, _) => Fx.Bad(Coll.rev(acc)) + case Coll.Cons(k, rest) => Fx.rows(k, D.tuples(m, Fx.relSym(k)), acc) match + case Coll.Some(acc2) => Fx.readAll(m, rest, acc2) + case Coll.None => Fx.RulesBad(Fx.relSym(k)) + +def Fx.rows {r: Region} (k: Fx.Rel, ts: Coll.List[Coll.List[D.Val]], acc: Coll.List[Fx.Clash]): Coll.Option[Coll.List[Fx.Clash]] = ts match + case Coll.Nil => Coll.Some(acc) + case Coll.Cons(t, rest) => t match + case Coll.Cons(a, more) => more match + case Coll.Cons(b, _) => a match + case D.VInt(line) => b match + case D.VSym(n) => Fx.make(k, line, n) match + case Coll.Some(c) => Fx.rows(k, rest, Coll.Cons(c, acc)) + case Coll.None => Coll.None + case D.VInt(_) => Coll.None + case D.VSym(_) => Coll.None + case Coll.Nil => Coll.None + case Coll.Nil => Coll.None + +def Fx.make {r: Region} (k: Fx.Rel, line: I64, n: Sym.Sym): Coll.Option[Fx.Clash] = k match + case Fx.RNotCapAt => Coll.Some(Fx.NotCap(line, n)) + case Fx.RBadStateAt => Coll.Some(Fx.BadState(line, n)) + case Fx.RTwiceAt => Coll.Some(Fx.Twice(line, n)) + case Fx.RNotOpAt => Coll.Some(Fx.NotOp(line, n)) + case Fx.RUnknownRelAt => Coll.Some(Fx.UnknownRel(line, n)) + case Fx.RRelArityAt => Coll.Some(Fx.RelArity(line, n)) + case Fx.RUnboundAt => Coll.Some(Fx.Unbound(line, n)) + case Fx.RExitOtherAt => Coll.Some(Fx.ExitOther(line, n)) + case Fx.RReservedAt => Coll.Some(Fx.Reserved(line, n)) + case Fx.RClauseArityAt => Coll.Some(Fx.ClauseArity(line, n)) + case Fx.RUnsafeAt => Coll.Some(Fx.Unsafe(line, n)) + case Fx.RRuleUnknownAt => Coll.Some(Fx.RuleUnknown(line, n)) + case Fx.RRuleOpAt => Coll.Some(Fx.RuleOp(line, n)) + case _ => Coll.None + +// the position of an op name in an atom: next(s, op, t) has one at 1, other relations none +def Fx.opPos {r: Region} (rel: Sym.Sym): Coll.Option[I64] = if rt_str_eq(Sym.str(rel), "next") then Coll.Some(1) else Coll.None + +def Fx.isPos(op: Coll.Option[I64], i: I64): Bool = op match + case Coll.Some(j) => i == j + case Coll.None => false diff --git a/bench/corpus/s2/flow.srs b/bench/corpus/s2/flow.srs new file mode 100644 index 00000000..9ca40095 --- /dev/null +++ b/bench/corpus/s2/flow.srs @@ -0,0 +1,1193 @@ +// s2 P2 FLOW, rung F1a (vic-m5r.3, vic/c/flow-design.md): protocol states as Datalog. Flow.facts walks one Ast.Fn and +// emits facts over its control-flow points; Flow.rules is a fixed rule library; D.solve gives what holds at each +// point, and a clash is a derived fact, returned as data. no join or loop code here: branches meet at a merge point +// and loops reach their fixpoint inside Datalog. F1a: handle, ops on a capability, if, while, blocks. +// +// a point exists only where something happens: a handle, an op step, the start of a branch, a merge, a loop head, a +// block end. a step's source point has no other out edge (branches start at fresh points), so a step moves only its +// capability and every other one keeps its state (frame). + +// a capability in scope: its name, its id (unique in the fn), its protocol, the line of its handle +enum Flow.Cap: + case Flow.Cap(name: Sym.Sym, id: I64, proto: Sym.Sym, line: I64) + +// the walk so far: the next free id, the facts, the capabilities in scope (innermost first) +enum Flow.St: + case Flow.St(next: I64, facts: Coll.List[D.Fact], caps: Coll.List[Flow.Cap]) + +// what the walk reads: the protocols, the handlers, the defs (a call reads its callee's signature), the enums (a +// constructor call allocates in the Region in scope) +enum Flow.Cx: + case Flow.Cx(ps: Coll.List[Ast.Proto], hs: Coll.List[Ast.Handler], fns: Coll.List[Ast.Fn], es: Coll.List[Ast.Enum], ts: Coll.List[Ast.TypeDecl]) + +def Flow.cxHs(cx: Flow.Cx): Coll.List[Ast.Handler] = + val Flow.Cx(_, hs, _, _, _) = cx + hs + +// the walk after an expression: its state and the point where control is now +enum Flow.At: + case Flow.At(st: Flow.St, p: I64) + +enum Flow.Clash: + case Flow.Stuck(line: I64, cap: Sym.Sym) + case Flow.Split(line: I64, cap: Sym.Sym) + case Flow.Unended(line: I64, cap: Sym.Sym) + // a call whose entry facts have more than one solution (s1/facts.srs:224); cap = the callee + case Flow.Ambig(line: I64, cap: Sym.Sym) + // a def whose body leaves a capability binder in another state than its exit fact says (s1/check.srs:525) + case Flow.ExitBad(line: I64, cap: Sym.Sym) + // a def whose entry facts have no solution (s1/check.srs:502); cap = the def + case Flow.NoSol(line: I64, cap: Sym.Sym) + // a value used after its region ended (s1 "use of value after its region ended"); cap = the region + case Flow.Dead(line: I64, cap: Sym.Sym) + // a block value that lives in a capability the block closes (s1 "value escapes the scope of its region") + case Flow.Escape(line: I64, cap: Sym.Sym) + // a value of a type with read where its capability is not in S (s1 "value needs c in state S"); name = the value + case Flow.Stale(line: I64, x: Sym.Sym) + +// every relation of Flow.rules and Flow.facts; Flow.relSym is the only place a relation name is a string +enum Flow.Rel: + case Flow.RFlow + case Flow.RStep + case Flow.RAt + case Flow.RCapOf + case Flow.RCapName + case Flow.RCapLine + case Flow.RHandle + case Flow.RClose + case Flow.RMerge + case Flow.RLine + case Flow.RTr + case Flow.RStart + case Flow.REndOk + case Flow.RSame + case Flow.RWorld + case Flow.RTouch + case Flow.RMoved + case Flow.RSeen + case Flow.RStuck + case Flow.RSplit + case Flow.RSplitAt + case Flow.RUnended + case Flow.RUnendedAt + case Flow.RCStep + case Flow.RBind + case Flow.RPre + case Flow.RPost + case Flow.RFirst + case Flow.RNext + case Flow.RLast + case Flow.ROk + case Flow.RFits + case Flow.RCallee + case Flow.RCSeen + case Flow.RAmbig + case Flow.RAmbigAt + case Flow.REnter + case Flow.RWant + case Flow.RExitBad + case Flow.RNoSol + case Flow.RNoSolAt + case Flow.RReadAt + case Flow.RAssign + case Flow.RAssignFrom + case Flow.RAssigns + case Flow.RHolds + case Flow.REdge + case Flow.RFin + case Flow.RDead + case Flow.REscCap + case Flow.REscVar + case Flow.REscape + case Flow.RNeed + case Flow.RSameS + case Flow.RStale + +def Flow.relSym {r: Region} (x: Flow.Rel): Sym.Sym = x match + case Flow.RFlow => Sym.of("flow") + case Flow.RStep => Sym.of("step") + case Flow.RAt => Sym.of("at") + case Flow.RCapOf => Sym.of("capOf") + case Flow.RCapName => Sym.of("capName") + case Flow.RCapLine => Sym.of("capLine") + case Flow.RHandle => Sym.of("handle") + case Flow.RClose => Sym.of("close") + case Flow.RMerge => Sym.of("merge") + case Flow.RLine => Sym.of("line") + case Flow.RTr => Sym.of("tr") + case Flow.RStart => Sym.of("start") + case Flow.REndOk => Sym.of("endOk") + case Flow.RSame => Sym.of("same") + case Flow.RWorld => Sym.of("world") + case Flow.RTouch => Sym.of("touch") + case Flow.RMoved => Sym.of("moved") + case Flow.RSeen => Sym.of("seen") + case Flow.RStuck => Sym.of("stuck") + case Flow.RSplit => Sym.of("split") + case Flow.RSplitAt => Sym.of("splitAt") + case Flow.RUnended => Sym.of("unended") + case Flow.RUnendedAt => Sym.of("unendedAt") + case Flow.RCStep => Sym.of("cstep") + case Flow.RBind => Sym.of("bind") + case Flow.RPre => Sym.of("pre") + case Flow.RPost => Sym.of("post") + case Flow.RFirst => Sym.of("firstParam") + case Flow.RNext => Sym.of("nextParam") + case Flow.RLast => Sym.of("lastParam") + case Flow.ROk => Sym.of("ok") + case Flow.RFits => Sym.of("fits") + case Flow.RCallee => Sym.of("callee") + case Flow.RCSeen => Sym.of("cseen") + case Flow.RAmbig => Sym.of("ambig") + case Flow.RAmbigAt => Sym.of("ambigAt") + case Flow.REnter => Sym.of("enter") + case Flow.RWant => Sym.of("want") + case Flow.RExitBad => Sym.of("exitBad") + case Flow.RNoSol => Sym.of("nosol") + case Flow.RNoSolAt => Sym.of("noSolAt") + case Flow.RReadAt => Sym.of("readAt") + case Flow.RAssign => Sym.of("assign") + case Flow.RAssignFrom => Sym.of("assignFrom") + case Flow.RAssigns => Sym.of("assigns") + case Flow.RHolds => Sym.of("holds") + case Flow.REdge => Sym.of("edge") + case Flow.RFin => Sym.of("fin") + case Flow.RDead => Sym.of("dead") + case Flow.REscCap => Sym.of("escCap") + case Flow.REscVar => Sym.of("escVar") + case Flow.REscape => Sym.of("escape") + case Flow.RNeed => Sym.of("need") + case Flow.RSameS => Sym.of("sameS") + case Flow.RStale => Sym.of("stale") + +// the clash relations of Flow.rules +enum Flow.Kind: + case Flow.KStuck + case Flow.KSplit + case Flow.KUnended + case Flow.KAmbig + case Flow.KExitBad + case Flow.KNoSol + case Flow.KDead + case Flow.KEscape + case Flow.KStale + +def Flow.relOf(k: Flow.Kind): Flow.Rel = k match + case Flow.KStuck => Flow.RStuck + case Flow.KSplit => Flow.RSplitAt + case Flow.KUnended => Flow.RUnendedAt + case Flow.KAmbig => Flow.RAmbigAt + case Flow.KExitBad => Flow.RExitBad + case Flow.KNoSol => Flow.RNoSolAt + case Flow.KDead => Flow.RDead + case Flow.KEscape => Flow.REscape + case Flow.KStale => Flow.RStale + +enum Flow.Verdict: + case Flow.Ok + case Flow.Bad(clashes: Coll.List[Flow.Clash]) + // the rule library is not a Datalog program (a bug in Flow.rules), as D.solve reports it + case Flow.RulesUnsafe(rel: Sym.Sym) + case Flow.RulesNegCycle(rel: Sym.Sym) + // a clash relation holds a tuple that is not (line, name): a bug in Flow.rules, reported, never dropped + case Flow.RulesIllTyped(rel: Sym.Sym) + +// ── facts: one constructor per relation, with its arity and column types ── +def Flow.i {r: Region} (n: I64): D.Val = D.VInt(n) +def Flow.s {r: Region} (x: Sym.Sym): D.Val = D.VSym(x) +def Flow.fact1 {r: Region} (rel: Flow.Rel, a: D.Val): D.Fact = D.Fact(Flow.relSym(rel), Coll.Cons(a, Coll.Nil)) +def Flow.fact2 {r: Region} (rel: Flow.Rel, a: D.Val, b: D.Val): D.Fact = D.Fact(Flow.relSym(rel), Coll.Cons(a, Coll.Cons(b, Coll.Nil))) +def Flow.fact4 {r: Region} (rel: Flow.Rel, a: D.Val, b: D.Val, c: D.Val, d: D.Val): D.Fact = D.Fact(Flow.relSym(rel), Coll.Cons(a, Coll.Cons(b, Coll.Cons(c, Coll.Cons(d, Coll.Nil))))) +def Flow.fFlow {r: Region} (p: I64, q: I64): D.Fact = Flow.fact2(Flow.RFlow, Flow.i(p), Flow.i(q)) +def Flow.fStep {r: Region} (p: I64, q: I64, cap: I64, op: Sym.Sym): D.Fact = Flow.fact4(Flow.RStep, Flow.i(p), Flow.i(q), Flow.i(cap), Flow.s(op)) +def Flow.fLine {r: Region} (p: I64, line: I64): D.Fact = Flow.fact2(Flow.RLine, Flow.i(p), Flow.i(line)) +def Flow.fMerge {r: Region} (m: I64): D.Fact = Flow.fact1(Flow.RMerge, Flow.i(m)) +def Flow.fClose {r: Region} (e: I64, cap: I64): D.Fact = Flow.fact2(Flow.RClose, Flow.i(e), Flow.i(cap)) +def Flow.fCapOf {r: Region} (cap: I64, proto: Sym.Sym): D.Fact = Flow.fact2(Flow.RCapOf, Flow.i(cap), Flow.s(proto)) +def Flow.fCapName {r: Region} (cap: I64, name: Sym.Sym): D.Fact = Flow.fact2(Flow.RCapName, Flow.i(cap), Flow.s(name)) +def Flow.fCapLine {r: Region} (cap: I64, line: I64): D.Fact = Flow.fact2(Flow.RCapLine, Flow.i(cap), Flow.i(line)) +def Flow.fHandle {r: Region} (p: I64, cap: I64): D.Fact = Flow.fact2(Flow.RHandle, Flow.i(p), Flow.i(cap)) +def Flow.fTr {r: Region} (proto: Sym.Sym, op: Sym.Sym, a: Sym.Sym, b: Sym.Sym): D.Fact = Flow.fact4(Flow.RTr, Flow.s(proto), Flow.s(op), Flow.s(a), Flow.s(b)) +def Flow.fStart {r: Region} (proto: Sym.Sym, s: Sym.Sym): D.Fact = Flow.fact2(Flow.RStart, Flow.s(proto), Flow.s(s)) +def Flow.fSame {r: Region} (a: Sym.Sym, b: Sym.Sym): D.Fact = Flow.fact2(Flow.RSame, Flow.s(a), Flow.s(b)) +def Flow.fEndOk {r: Region} (proto: Sym.Sym, s: Sym.Sym): D.Fact = Flow.fact2(Flow.REndOk, Flow.s(proto), Flow.s(s)) +def Flow.fWorld {r: Region} (w: I64): D.Fact = Flow.fact1(Flow.RWorld, Flow.i(w)) +def Flow.fact3 {r: Region} (rel: Flow.Rel, a: D.Val, b: D.Val, c: D.Val): D.Fact = D.Fact(Flow.relSym(rel), Coll.Cons(a, Coll.Cons(b, Coll.Cons(c, Coll.Nil)))) +def Flow.fCStep {r: Region} (p: I64, q: I64): D.Fact = Flow.fact2(Flow.RCStep, Flow.i(p), Flow.i(q)) +def Flow.fCallee {r: Region} (p: I64, f: Sym.Sym): D.Fact = Flow.fact2(Flow.RCallee, Flow.i(p), Flow.s(f)) +def Flow.fBind {r: Region} (p: I64, m: I64, cap: I64): D.Fact = Flow.fact3(Flow.RBind, Flow.i(p), Flow.i(m), Flow.i(cap)) +def Flow.fFirst {r: Region} (p: I64, m: I64): D.Fact = Flow.fact2(Flow.RFirst, Flow.i(p), Flow.i(m)) +def Flow.fNext {r: Region} (p: I64, m: I64, n: I64): D.Fact = Flow.fact3(Flow.RNext, Flow.i(p), Flow.i(m), Flow.i(n)) +def Flow.fLast {r: Region} (p: I64, m: I64): D.Fact = Flow.fact2(Flow.RLast, Flow.i(p), Flow.i(m)) +def Flow.fPre {r: Region} (p: I64, j: I64, m: I64, s: Sym.Sym): D.Fact = Flow.fact4(Flow.RPre, Flow.i(p), Flow.i(j), Flow.i(m), Flow.s(s)) +def Flow.fPost {r: Region} (p: I64, j: I64, m: I64, s: Sym.Sym): D.Fact = Flow.fact4(Flow.RPost, Flow.i(p), Flow.i(j), Flow.i(m), Flow.s(s)) +// a solution id is equal to itself (ambig compares solution ids with !same, as split compares states) +def Flow.fSameI {r: Region} (j: I64): D.Fact = Flow.fact2(Flow.RSame, Flow.i(j), Flow.i(j)) +def Flow.fEnter {r: Region} (p: I64, w: I64, cap: I64, s: Sym.Sym): D.Fact = Flow.fact4(Flow.REnter, Flow.i(p), Flow.i(w), Flow.i(cap), Flow.s(s)) +def Flow.fWant {r: Region} (p: I64, w: I64, cap: I64, s: Sym.Sym): D.Fact = Flow.fact4(Flow.RWant, Flow.i(p), Flow.i(w), Flow.i(cap), Flow.s(s)) +def Flow.fNoSol {r: Region} (line: I64, f: Sym.Sym): D.Fact = Flow.fact2(Flow.RNoSol, Flow.i(line), Flow.s(f)) +def Flow.fReadAt {r: Region} (p: I64, x: Sym.Sym, line: I64): D.Fact = Flow.fact3(Flow.RReadAt, Flow.i(p), Flow.s(x), Flow.i(line)) +def Flow.fAssign {r: Region} (p: I64, x: Sym.Sym, cap: I64): D.Fact = Flow.fact3(Flow.RAssign, Flow.i(p), Flow.s(x), Flow.i(cap)) +def Flow.fAssignFrom {r: Region} (p: I64, x: Sym.Sym, y: Sym.Sym): D.Fact = Flow.fact3(Flow.RAssignFrom, Flow.i(p), Flow.s(x), Flow.s(y)) +def Flow.fAssigns {r: Region} (p: I64, x: Sym.Sym): D.Fact = Flow.fact2(Flow.RAssigns, Flow.i(p), Flow.s(x)) +def Flow.fEscCap {r: Region} (e: I64, cap: I64, line: I64): D.Fact = Flow.fact3(Flow.REscCap, Flow.i(e), Flow.i(cap), Flow.i(line)) +def Flow.fEscVar {r: Region} (e: I64, y: Sym.Sym, line: I64): D.Fact = Flow.fact3(Flow.REscVar, Flow.i(e), Flow.s(y), Flow.i(line)) +def Flow.fFin {r: Region} (proto: Sym.Sym, s: Sym.Sym): D.Fact = Flow.fact2(Flow.RFin, Flow.s(proto), Flow.s(s)) + +def Flow.add {r: Region} (st: Flow.St, f: D.Fact): Flow.St = + val Flow.St(n, fs, cs) = st + Flow.St(n, Coll.Cons(f, fs), cs) + +// a fresh id +def Flow.fresh {r: Region} (st: Flow.St): Flow.At = + val Flow.St(n, fs, cs) = st + Flow.At(Flow.St(n + 1, fs, cs), n) + +def Flow.edge {r: Region} (st: Flow.St, p: I64, q: I64): Flow.St = Flow.add(st, Flow.fFlow(p, q)) + +// a fresh point that control reaches from p +def Flow.next {r: Region} (st: Flow.St, p: I64): Flow.At = + val Flow.At(st2, q) = Flow.fresh(st) + Flow.At(Flow.edge(st2, p, q), q) + +// the capability named x in scope, innermost first +def Flow.capNamed {r: Region} (cs: Coll.List[Flow.Cap], x: Sym.Sym): Coll.Option[Flow.Cap] = cs match + case Coll.Nil => Coll.None + case Coll.Cons(c, rest) => + val Flow.Cap(n, _, _, _) = c + if Sym.eq(n, x) then Coll.Some(c) else Flow.capNamed(rest, x) + +// the protocol a handler implements +def Flow.protoOf {r: Region} (hs: Coll.List[Ast.Handler], h: Sym.Sym): Coll.Option[Sym.Sym] = hs match + case Coll.Nil => Coll.None + case Coll.Cons(x, rest) => + val Ast.Handler(_, n, p, _) = x + if Sym.eq(n, h) then Coll.Some(p) else Flow.protoOf(rest, h) + +// ── the walk: e from point p ── +def Flow.expr {r: Region} (cx: Flow.Cx, st: Flow.St, p: I64, e: Ast.Expr): Flow.At = e match + case Ast.Call(line, f, _, chosen, xs) => + val Flow.At(st2, pa) = Flow.exprs(cx, st, p, xs) + val Flow.Cx(ps, _, fns, es, _) = cx + Flow.fnNamed(fns, f) match + case Coll.Some(g) => Flow.call(ps, st2, pa, g, chosen, line) + case Coll.None => if Flow.isCtor(es, f) then Flow.alloc(st2, pa, line) else Flow.At(st2, pa) + case Ast.Method(line, recv, op, xs) => + val Flow.At(st2, pa) = Flow.exprs(cx, st, p, xs) + val Flow.St(_, _, cs) = st2 + Flow.capNamed(cs, recv) match + case Coll.None => Flow.At(st2, pa) + case Coll.Some(c) => Flow.step(st2, pa, c, op, line) + case Ast.Bin(_, _, l, rhs) => + val Flow.At(st2, p2) = Flow.expr(cx, st, p, l) + Flow.expr(cx, st2, p2, rhs) + case Ast.Un(_, _, x) => Flow.expr(cx, st, p, x) + case Ast.If(line, c, t, x) => + val Flow.At(st1, pc) = Flow.expr(cx, st, p, c) + val Flow.At(st2, t0) = Flow.next(st1, pc) + val Flow.At(st3, pt) = Flow.expr(cx, st2, t0, t) + val Flow.At(st4, e0) = Flow.next(st3, pc) + val Flow.At(st5, pe) = Flow.expr(cx, st4, e0, x) + val Flow.At(st6, m) = Flow.next(st5, pt) + Flow.At(Flow.merge(Flow.edge(st6, pe, m), m, line), m) + case Ast.While(line, c, b) => + val Flow.At(st1, h) = Flow.next(st, p) + val Flow.At(st2, pc) = Flow.expr(cx, st1, h, c) + val Flow.At(st3, b0) = Flow.next(st2, pc) + val Flow.At(st4, pb) = Flow.expr(cx, st3, b0, b) + val Flow.At(st5, x) = Flow.next(Flow.merge(Flow.edge(st4, pb, h), h, line), pc) + Flow.At(st5, x) + case Ast.Block(line, ss, last) => Flow.block(cx, st, p, ss, last, line) + case Ast.Assign(_, x, v) => Flow.bindVal(cx, st, p, x, v) + case Ast.Match(line, s, arms) => + val Flow.At(st1, ps) = Flow.expr(cx, st, p, s) + val Flow.At(st2, m) = Flow.fresh(st1) + val Flow.St(_, _, cs) = st2 + Flow.At(Flow.merge(Flow.arms(cx, st2, ps, m, Flow.srcs(cx, cs, s, Coll.Nil), arms), m, line), m) + case Ast.Name(line, x) => Flow.At(Flow.add(st, Flow.fReadAt(p, x, line)), p) + case _ => Flow.At(st, p) + +// each arm a branch from ps (the point after the scrutinee) to the merge point m; its pattern binders hold what the +// scrutinee holds (sv) +def Flow.arms {r: Region} (cx: Flow.Cx, st: Flow.St, ps: I64, m: I64, sv: Coll.List[Flow.Src], arms: Coll.List[Ast.Arm]): Flow.St = arms match + case Coll.Nil => st + case Coll.Cons(a, rest) => + val Ast.Arm(_, pat, b) = a + val binds = Flow.patBinds(pat) + val Flow.At(st1, a0) = Flow.next(st, ps) + val Flow.At(st2, a1) = Flow.assignAll(st1, a0, binds, sv) + val Flow.At(st3, pa) = Flow.expr(cx, st2, a1, b) + Flow.arms(cx, Flow.edge(st3, pa, m), ps, m, sv, rest) + +// the names a pattern binds (a wildcard binds none) +def Flow.patBinds {r: Region} (p: Ast.Pat): Coll.List[Sym.Sym] = p match + case Ast.PCase(_, binds) => binds + case Ast.PAny => Coll.Nil + +// ── CAPS (R3, flow-design.md; parity C1-C4): the regions a value lives in. a source is a capability (a constructor's +// Region, a callee's region binder) or a name (what that name holds at the read point) ── +enum Flow.Src: + case Flow.SCap(c: I64) + case Flow.SVar(x: Sym.Sym) + +// the sources of e: a constructor lives in the Region in scope and in its args' sources; a call whose result is data (an +// enum) lives in the capabilities its region binders take and in its args' sources (s1 rho); if, match and block +// take the union of their values +def Flow.srcs {r: Region} (cx: Flow.Cx, cs: Coll.List[Flow.Cap], e: Ast.Expr, acc: Coll.List[Flow.Src]): Coll.List[Flow.Src] = e match + case Ast.Name(_, x) => Coll.Cons(Flow.SVar(x), acc) + case Ast.Call(_, f, _, chosen, xs) => + val Flow.Cx(ps, _, fns, es, _) = cx + Flow.fnNamed(fns, f) match + case Coll.Some(g) => + val Ast.Fn(_, _, gs, _, ret, _, _) = g + val Ast.Ty(_, rn, _, _, _) = ret + // a [] binder result may be any arg (pick) or made from one (a given's method): it lives in every arg's region + // too (vic-m5r.15) + val data = Flow.isEnumName(es, rn) || Ty.memberSym(rn, Ty.tparams(gs, Coll.Nil)) + if data then Flow.srcsAll(cx, cs, xs, Flow.regionSrcs(cs, chosen, Flow.regionBs(Flow.capBs(ps, gs, 0, Coll.Nil), Coll.Nil), acc)) else acc + case Coll.None => + if Flow.isCtor(es, f) then + Flow.onlyCap(cs, Sym.of("Region"), Coll.None) match + case Coll.None => Flow.srcsAll(cx, cs, xs, acc) + case Coll.Some(c) => + val Flow.Cap(_, id, _, _) = c + Flow.srcsAll(cx, cs, xs, Coll.Cons(Flow.SCap(id), acc)) + else acc + case Ast.If(_, _, t, x) => Flow.srcs(cx, cs, x, Flow.srcs(cx, cs, t, acc)) + case Ast.Block(_, _, last) => Flow.srcs(cx, cs, last, acc) + case Ast.Match(_, _, arms) => Flow.srcsArms(cx, cs, arms, acc) + // a method of {} evidence (a given turns an A into a B): its result keeps its args' regions + case Ast.Method(_, _, _, xs) => Flow.srcsAll(cx, cs, xs, acc) + case _ => acc + +def Flow.srcsAll {r: Region} (cx: Flow.Cx, cs: Coll.List[Flow.Cap], xs: Coll.List[Ast.Expr], acc: Coll.List[Flow.Src]): Coll.List[Flow.Src] = xs match + case Coll.Nil => acc + case Coll.Cons(x, rest) => Flow.srcsAll(cx, cs, rest, Flow.srcs(cx, cs, x, acc)) + +def Flow.srcsArms {r: Region} (cx: Flow.Cx, cs: Coll.List[Flow.Cap], arms: Coll.List[Ast.Arm], acc: Coll.List[Flow.Src]): Coll.List[Flow.Src] = arms match + case Coll.Nil => acc + case Coll.Cons(a, rest) => + val Ast.Arm(_, _, b) = a + Flow.srcsArms(cx, cs, rest, Flow.srcs(cx, cs, b, acc)) + +def Flow.isEnumName(es: Coll.List[Ast.Enum], n: Sym.Sym): Bool = es match + case Coll.Nil => false + case Coll.Cons(e, rest) => + val Ast.Enum(_, name, _, _) = e + if Sym.eq(name, n) then true else Flow.isEnumName(rest, n) + +// the binders of protocol Region +def Flow.regionBs {r: Region} (bs: Coll.List[Flow.CapB], acc: Coll.List[Flow.CapB]): Coll.List[Flow.CapB] = bs match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(b, rest) => + val Flow.CapB(_, _, proto) = b + if Sym.eq(proto, Sym.of("Region")) then Flow.regionBs(rest, Coll.Cons(b, acc)) else Flow.regionBs(rest, acc) + +// the caller capability each region binder takes (as at the call: the chosen name or the one in scope) +def Flow.regionSrcs {r: Region} (cs: Coll.List[Flow.Cap], chosen: Coll.List[Sym.Sym], bs: Coll.List[Flow.CapB], acc: Coll.List[Flow.Src]): Coll.List[Flow.Src] = bs match + case Coll.Nil => acc + case Coll.Cons(b, rest) => Flow.capFor(cs, chosen, b) match + case Coll.None => Flow.regionSrcs(cs, chosen, rest, acc) + case Coll.Some(c) => + val Flow.Cap(_, id, _, _) = c + Flow.regionSrcs(cs, chosen, rest, Coll.Cons(Flow.SCap(id), acc)) + +// x = v (val, var, assign): v is walked; when v has sources, a fresh point assigns them to x (strong update) +def Flow.bindVal {r: Region} (cx: Flow.Cx, st: Flow.St, p: I64, x: Sym.Sym, v: Ast.Expr): Flow.At = + val Flow.At(st1, pv) = Flow.expr(cx, st, p, v) + val Flow.St(_, _, cs) = st1 + Flow.assignAll(st1, pv, Coll.Cons(x, Coll.Nil), Flow.srcs(cx, cs, v, Coll.Nil)) + +// each x of xs gets the sources sv at a fresh point after p (no sources: nothing to assign, no point) +def Flow.assignAll {r: Region} (st: Flow.St, p: I64, xs: Coll.List[Sym.Sym], sv: Coll.List[Flow.Src]): Flow.At = sv match + case Coll.Nil => Flow.At(st, p) + case Coll.Cons(_, _) => xs match + case Coll.Nil => Flow.At(st, p) + case Coll.Cons(_, _) => + val Flow.At(st1, a) = Flow.next(st, p) + val st2 = Flow.assignFacts(st1, a, xs, sv) + Flow.next(st2, a) + +def Flow.assignFacts {r: Region} (st: Flow.St, a: I64, xs: Coll.List[Sym.Sym], sv: Coll.List[Flow.Src]): Flow.St = xs match + case Coll.Nil => st + case Coll.Cons(x, rest) => Flow.assignFacts(Flow.srcFacts(Flow.add(st, Flow.fAssigns(a, x)), a, x, sv), a, rest, sv) + +def Flow.srcFacts {r: Region} (st: Flow.St, a: I64, x: Sym.Sym, sv: Coll.List[Flow.Src]): Flow.St = sv match + case Coll.Nil => st + case Coll.Cons(s, rest) => s match + case Flow.SCap(c) => Flow.srcFacts(Flow.add(st, Flow.fAssign(a, x, c)), a, x, rest) + case Flow.SVar(y) => Flow.srcFacts(Flow.add(st, Flow.fAssignFrom(a, x, y)), a, x, rest) + +def Flow.exprs {r: Region} (cx: Flow.Cx, st: Flow.St, p: I64, xs: Coll.List[Ast.Expr]): Flow.At = xs match + case Coll.Nil => Flow.At(st, p) + case Coll.Cons(x, rest) => + val Flow.At(st2, p2) = Flow.expr(cx, st, p, x) + Flow.exprs(cx, st2, p2, rest) + +// m is a merge point (branches or a loop meet) at line +def Flow.merge {r: Region} (st: Flow.St, m: I64, line: I64): Flow.St = + Flow.add(Flow.add(st, Flow.fMerge(m)), Flow.fLine(m, line)) + +// op on capability c after point p: a step from a fresh point of its own (its only out edge, its only line) to a +// fresh point +def Flow.step {r: Region} (st: Flow.St, p: I64, c: Flow.Cap, op: Sym.Sym, line: I64): Flow.At = + val Flow.Cap(_, id, _, _) = c + val Flow.At(st1, s) = Flow.next(st, p) + val Flow.At(st2, q) = Flow.fresh(st1) + val st3 = Flow.add(st2, Flow.fStep(s, q, id, op)) + Flow.At(Flow.add(st3, Flow.fLine(s, line)), q) + +// a constructor call (written with args: a nullary case takes no ()) allocates: an alloc step on the one Region in +// scope (s1/check.srs:708-716). no Region, or two: the names check reports it. not yet: a spec def allocates nothing +// (the s2 Ast has no spec marker) +def Flow.alloc {r: Region} (st: Flow.St, p: I64, line: I64): Flow.At = + val Flow.St(_, _, cs) = st + Flow.onlyCap(cs, Sym.of("Region"), Coll.None) match + case Coll.None => Flow.At(st, p) + case Coll.Some(c) => Flow.step(st, p, c, Sym.of("alloc"), line) + +def Flow.isCtor {r: Region} (es: Coll.List[Ast.Enum], f: Sym.Sym): Bool = es match + case Coll.Nil => false + case Coll.Cons(e, rest) => + val Ast.Enum(_, _, _, cases) = e + if Flow.caseIn(cases, f) then true else Flow.isCtor(rest, f) + +def Flow.caseIn(cases: Coll.List[Ast.Case], f: Sym.Sym): Bool = cases match + case Coll.Nil => false + case Coll.Cons(c, rest) => + val Ast.Case(_, n, _) = c + if Sym.eq(n, f) then true else Flow.caseIn(rest, f) + +// ── calls (R2, flow-design.md): the step point is the kind, so pre/post/param facts are per call site ── +// a capability binder of a callee: its {} binder name, its index among the {} binders (f{a, b}(x) picks by it), its +// protocol +enum Flow.CapB: + case Flow.CapB(x: Sym.Sym, curly: I64, proto: Sym.Sym) + +// a fact variable bound to a state +enum Flow.VS: + case Flow.VS(x: Sym.Sym, s: Sym.Sym) + +def Flow.fnNamed {r: Region} (fns: Coll.List[Ast.Fn], f: Sym.Sym): Coll.Option[Ast.Fn] = fns match + case Coll.Nil => Coll.None + case Coll.Cons(g, rest) => + val Ast.Fn(_, n, _, _, _, _, _) = g + if Sym.eq(n, f) then Coll.Some(g) else Flow.fnNamed(rest, f) + +def Flow.protoNamed {r: Region} (ps: Coll.List[Ast.Proto], n: Sym.Sym): Coll.Option[Ast.Proto] = ps match + case Coll.Nil => Coll.None + case Coll.Cons(p, rest) => + val Ast.Proto(_, name, _, _, _, _, _, _) = p + if Sym.eq(name, n) then Coll.Some(p) else Flow.protoNamed(rest, n) + +// the {} binders of the groups gs whose type is a protocol, in written order; i = the {} index of the next binder +def Flow.capBs {r: Region} (ps: Coll.List[Ast.Proto], gs: Coll.List[Ast.Group], i: I64, acc: Coll.List[Flow.CapB]): Coll.List[Flow.CapB] = gs match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(g, rest) => g match + case Ast.Evidence(bs) => Flow.capBsOf(ps, rest, bs, i, acc) + case Ast.Types(_) => Flow.capBs(ps, rest, i, acc) + case Ast.Facts(_) => Flow.capBs(ps, rest, i, acc) + +def Flow.capBsOf {r: Region} (ps: Coll.List[Ast.Proto], gs: Coll.List[Ast.Group], bs: Coll.List[Ast.Binder], i: I64, acc: Coll.List[Flow.CapB]): Coll.List[Flow.CapB] = bs match + case Coll.Nil => Flow.capBs(ps, gs, i, acc) + case Coll.Cons(b, rest) => + val Ast.Binder(_, x, ty) = b + val Ast.Ty(_, tn, _, _, _) = ty + Flow.protoNamed(ps, tn) match + case Coll.None => Flow.capBsOf(ps, gs, rest, i + 1, acc) + case Coll.Some(_) => Flow.capBsOf(ps, gs, rest, i + 1, Coll.Cons(Flow.CapB(x, i, tn), acc)) + +// the entry atoms of f (its <> groups before the params) +def Flow.entryAtoms {r: Region} (gs: Coll.List[Ast.Group], acc: Coll.List[Ast.Atom]): Coll.List[Ast.Atom] = gs match + case Coll.Nil => acc + case Coll.Cons(g, rest) => g match + case Ast.Facts(atoms) => Flow.entryAtoms(rest, Coll.revOnto(Coll.rev(atoms), acc)) + case Ast.Types(_) => Flow.entryAtoms(rest, acc) + case Ast.Evidence(_) => Flow.entryAtoms(rest, acc) + +// the caller capability a binder takes: the chosen name (f{a}(x)), else the one capability of its protocol in scope; +// None when there is none or more than one (the names check reports it, s1/check.srs:643-660) +def Flow.capFor {r: Region} (cs: Coll.List[Flow.Cap], chosen: Coll.List[Sym.Sym], b: Flow.CapB): Coll.Option[Flow.Cap] = + val Flow.CapB(_, i, proto) = b + chosen match + case Coll.Nil => Flow.onlyCap(cs, proto, Coll.None) + case Coll.Cons(_, _) => Flow.nthSym(chosen, i) match + case Coll.None => Coll.None + case Coll.Some(n) => Flow.capOfProto(Flow.capNamed(cs, n), proto) + +def Flow.capOfProto {r: Region} (c: Coll.Option[Flow.Cap], proto: Sym.Sym): Coll.Option[Flow.Cap] = c match + case Coll.None => c + case Coll.Some(x) => + val Flow.Cap(_, _, p, _) = x + if Sym.eq(p, proto) then c else Coll.None + +def Flow.nthSym {r: Region} (xs: Coll.List[Sym.Sym], i: I64): Coll.Option[Sym.Sym] = xs match + case Coll.Nil => Coll.None + case Coll.Cons(x, rest) => if i == 0 then Coll.Some(x) else Flow.nthSym(rest, i - 1) + +// the one capability of protocol proto in cs (a name shadowed by an inner one counts once) +def Flow.onlyCap {r: Region} (cs: Coll.List[Flow.Cap], proto: Sym.Sym, found: Coll.Option[Flow.Cap]): Coll.Option[Flow.Cap] = cs match + case Coll.Nil => found + case Coll.Cons(c, rest) => + val Flow.Cap(n, _, p, _) = c + if !Sym.eq(p, proto) then Flow.onlyCap(rest, proto, found) + else found match + case Coll.None => Flow.onlyCap(rest, proto, Coll.Some(c)) + case Coll.Some(f) => + val Flow.Cap(fn, _, _, _) = f + if Sym.eq(fn, n) then Flow.onlyCap(rest, proto, found) else Coll.None + +// the caller capability of every binder, in order; None when one is missing +def Flow.capsFor {r: Region} (cs: Coll.List[Flow.Cap], chosen: Coll.List[Sym.Sym], bs: Coll.List[Flow.CapB], acc: Coll.List[Flow.Cap]): Coll.Option[Coll.List[Flow.Cap]] = bs match + case Coll.Nil => Coll.Some(Coll.rev(acc)) + case Coll.Cons(b, rest) => Flow.capFor(cs, chosen, b) match + case Coll.None => Coll.None + case Coll.Some(c) => Flow.capsFor(cs, chosen, rest, Coll.Cons(c, acc)) + +// a call of g after point p: a step from a fresh point to a fresh point, each capability binder bound to its caller +// capability, and the solutions of g's entry facts as pre/post states per binder +def Flow.call {r: Region} (ps: Coll.List[Ast.Proto], st: Flow.St, p: I64, g: Ast.Fn, chosen: Coll.List[Sym.Sym], line: I64): Flow.At = + val Ast.Fn(_, name, gs, _, _, exit, _) = g + val bs = Flow.capBs(ps, gs, 0, Coll.Nil) + val Flow.St(_, _, cs) = st + bs match + case Coll.Nil => Flow.At(st, p) + case Coll.Cons(_, _) => Flow.capsFor(cs, chosen, bs, Coll.Nil) match + case Coll.None => Flow.At(st, p) + case Coll.Some(caps) => + val Flow.At(st1, s) = Flow.next(st, p) + val Flow.At(st2, q) = Flow.fresh(st1) + val st3 = Flow.add(Flow.add(Flow.add(st2, Flow.fCStep(s, q)), Flow.fLine(s, line)), Flow.fCallee(s, name)) + val st4 = Flow.binds(st3, s, caps, 0) + val atoms = Flow.entryAtoms(gs, Coll.Nil) + val vars = Flow.varsOf(atoms, Coll.Nil) + Flow.At(Flow.sols(ps, st4, s, bs, atoms, exit, Flow.assigns(ps, Flow.ruleModels(ps, bs, Coll.Nil), bs, atoms, vars, Coll.Nil, Coll.Nil), 0), q) + +// bind(s, i, c), and the param chain firstParam / nextParam / lastParam +def Flow.binds {r: Region} (st: Flow.St, s: I64, caps: Coll.List[Flow.Cap], i: I64): Flow.St = caps match + case Coll.Nil => st + case Coll.Cons(c, rest) => + val Flow.Cap(_, id, _, _) = c + val st1 = Flow.add(st, Flow.fBind(s, i, id)) + val st2 = if i == 0 then Flow.add(st1, Flow.fFirst(s, i)) else Flow.add(st1, Flow.fNext(s, i - 1, i)) + val st3 = rest match + case Coll.Nil => Flow.add(st2, Flow.fLast(s, i)) + case Coll.Cons(_, _) => st2 + Flow.binds(st3, s, rest, i + 1) + +def Flow.isVar(x: Sym.Sym): Bool = + val c = rt_str_at(Sym.str(x), 0) + c >= 'a' && c <= 'z' + +// the state positions of an atom: at(_, S), next(S1, _, S2), every arg of a rule atom (s1/facts.srs statePos) +def Flow.statePos {r: Region} (a: Ast.Atom): Coll.List[Ast.Term] = + val Ast.Atom(_, rel, args) = a + if Sym.eq(rel, Sym.of("at")) then Flow.dropOne(args) + else if Sym.eq(rel, Sym.of("next")) then Flow.firstLast(args) + else args + +def Flow.dropOne {r: Region} (xs: Coll.List[Ast.Term]): Coll.List[Ast.Term] = xs match + case Coll.Nil => xs + case Coll.Cons(_, rest) => rest + +def Flow.firstLast {r: Region} (xs: Coll.List[Ast.Term]): Coll.List[Ast.Term] = xs match + case Coll.Cons(a, r1) => r1 match + case Coll.Cons(_, r2) => r2 match + case Coll.Cons(b, _) => Coll.Cons(a, Coll.Cons(b, Coll.Nil)) + case Coll.Nil => Coll.Nil + case Coll.Nil => Coll.Nil + case Coll.Nil => Coll.Nil + +def Flow.termSym {r: Region} (t: Ast.Term): Coll.Option[Sym.Sym] = t match + case Ast.TName(n) => Coll.Some(n) + case Ast.TNum(_) => Coll.None + +// the fact variables of the atoms, each once, in written order +def Flow.varsOf {r: Region} (atoms: Coll.List[Ast.Atom], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = atoms match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(a, rest) => Flow.varsOf(rest, Flow.varsIn(Flow.statePos(a), acc)) + +def Flow.varsIn {r: Region} (ts: Coll.List[Ast.Term], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = ts match + case Coll.Nil => acc + case Coll.Cons(t, rest) => Flow.termSym(t) match + case Coll.None => Flow.varsIn(rest, acc) + case Coll.Some(x) => if Flow.isVar(x) && !Flow.memberSym(x, acc) then Flow.varsIn(rest, Coll.Cons(x, acc)) else Flow.varsIn(rest, acc) + +// every assignment of vars to states (each over the states of all binder protocols) whose next and rule atoms hold +def Flow.assigns {r: Region} (ps: Coll.List[Ast.Proto], ms: Coll.List[Flow.PM], bs: Coll.List[Flow.CapB], atoms: Coll.List[Ast.Atom], vars: Coll.List[Sym.Sym], a: Coll.List[Flow.VS], acc: Coll.List[Coll.List[Flow.VS]]): Coll.List[Coll.List[Flow.VS]] = vars match + case Coll.Nil => if Flow.atomsHold(ps, ms, bs, atoms, a) then Coll.Cons(a, acc) else acc + case Coll.Cons(x, rest) => Flow.assignEach(ps, ms, bs, atoms, x, rest, a, Flow.statesOf(ps, bs, Coll.Nil), acc) + +def Flow.assignEach {r: Region} (ps: Coll.List[Ast.Proto], ms: Coll.List[Flow.PM], bs: Coll.List[Flow.CapB], atoms: Coll.List[Ast.Atom], x: Sym.Sym, rest: Coll.List[Sym.Sym], a: Coll.List[Flow.VS], ss: Coll.List[Sym.Sym], acc: Coll.List[Coll.List[Flow.VS]]): Coll.List[Coll.List[Flow.VS]] = ss match + case Coll.Nil => acc + case Coll.Cons(s, more) => Flow.assignEach(ps, ms, bs, atoms, x, rest, a, more, Flow.assigns(ps, ms, bs, atoms, rest, Coll.Cons(Flow.VS(x, s), a), acc)) + +// the states of the binder protocols, each once +def Flow.statesOf {r: Region} (ps: Coll.List[Ast.Proto], bs: Coll.List[Flow.CapB], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = bs match + case Coll.Nil => acc + case Coll.Cons(b, rest) => + val Flow.CapB(_, _, proto) = b + Flow.protoNamed(ps, proto) match + case Coll.None => Flow.statesOf(ps, rest, acc) + case Coll.Some(pr) => + val Ast.Proto(_, _, states, _, _, _, _, _) = pr + Flow.statesOf(ps, rest, Flow.addNew(states, acc)) + +def Flow.addNew {r: Region} (xs: Coll.List[Sym.Sym], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = xs match + case Coll.Nil => acc + case Coll.Cons(x, rest) => if Flow.memberSym(x, acc) then Flow.addNew(rest, acc) else Flow.addNew(rest, Coll.Cons(x, acc)) + +// a name under an assignment: a variable's state, else the name itself +def Flow.resolve(a: Coll.List[Flow.VS], x: Sym.Sym): Sym.Sym = a match + case Coll.Nil => x + case Coll.Cons(v, rest) => + val Flow.VS(y, s) = v + if Sym.eq(x, y) then s else Flow.resolve(rest, x) + +// every next(S1, op, S2) atom is a transition of op in a binder protocol, and every rule atom holds in the rule model of +// a binder protocol (at atoms are pre/post states, not filters) +def Flow.atomsHold {r: Region} (ps: Coll.List[Ast.Proto], ms: Coll.List[Flow.PM], bs: Coll.List[Flow.CapB], atoms: Coll.List[Ast.Atom], a: Coll.List[Flow.VS]): Bool = atoms match + case Coll.Nil => true + case Coll.Cons(at, rest) => + val Ast.Atom(_, rel, args) = at + if Sym.eq(rel, Sym.of("at")) then Flow.atomsHold(ps, ms, bs, rest, a) + else if Sym.eq(rel, Sym.of("next")) then + Flow.nextHolds(ps, bs, args, a) match + case Coll.Nil => false + case Coll.Cons(_, _) => Flow.atomsHold(ps, ms, bs, rest, a) + else if Flow.ruleHolds(ms, rel, Flow.tupleOf(args, a, Coll.Nil)) then Flow.atomsHold(ps, ms, bs, rest, a) + else false + +// ── protocol rule defs (s1/facts.srs, vic 2026-11-05: a protocol is its own Datalog program): each binder protocol with +// rule defs is solved once over its next facts; a rule atom of a def holds when its tuple is in that model ── +enum Flow.PM: + case Flow.PM(proto: Sym.Sym, m: D.Model) + +// the args of an atom under an assignment, as values +def Flow.tupleOf {r: Region} (ts: Coll.List[Ast.Term], a: Coll.List[Flow.VS], acc: Coll.List[D.Val]): Coll.List[D.Val] = ts match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(t, rest) => t match + case Ast.TName(n) => Flow.tupleOf(rest, a, Coll.Cons(D.VSym(Flow.resolve(a, n)), acc)) + case Ast.TNum(v) => Flow.tupleOf(rest, a, Coll.Cons(D.VInt(v), acc)) + +def Flow.ruleHolds {r: Region} (ms: Coll.List[Flow.PM], rel: Sym.Sym, t: Coll.List[D.Val]): Bool = ms match + case Coll.Nil => false + case Coll.Cons(pm, rest) => + val Flow.PM(_, m) = pm + if Flow.inTuples(D.tuples(m, rel), t) then true else Flow.ruleHolds(rest, rel, t) + +def Flow.inTuples(ts: Coll.List[Coll.List[D.Val]], t: Coll.List[D.Val]): Bool = ts match + case Coll.Nil => false + case Coll.Cons(u, rest) => if D.tupleEq(u, t) then true else Flow.inTuples(rest, t) + +// the rule model of every binder protocol that has rule defs (a protocol whose rules D rejects has none: the decl check +// reports it) +def Flow.ruleModels {r: Region} (ps: Coll.List[Ast.Proto], bs: Coll.List[Flow.CapB], acc: Coll.List[Flow.PM]): Coll.List[Flow.PM] = bs match + case Coll.Nil => acc + case Coll.Cons(b, rest) => + val Flow.CapB(_, _, proto) = b + Flow.protoNamed(ps, proto) match + case Coll.None => Flow.ruleModels(ps, rest, acc) + case Coll.Some(pr) => + val Ast.Proto(_, _, _, _, _, _, ops, rules) = pr + rules match + case Coll.Nil => Flow.ruleModels(ps, rest, acc) + case Coll.Cons(_, _) => D.solve(Flow.ruleDefs(rules, Coll.Nil), Flow.nextFacts(ops, Coll.Nil)) match + case D.Solved(m) => Flow.ruleModels(ps, rest, Coll.Cons(Flow.PM(proto, m), acc)) + case D.Unsafe(_) => Flow.ruleModels(ps, rest, acc) + case D.NegCycle(_) => Flow.ruleModels(ps, rest, acc) + +// next(S1, op, S2) for every transition of every op +def Flow.nextFacts {r: Region} (ops: Coll.List[Ast.Op], acc: Coll.List[D.Fact]): Coll.List[D.Fact] = ops match + case Coll.Nil => acc + case Coll.Cons(o, rest) => + val Ast.Op(_, name, _, _, trs) = o + Flow.nextFacts(rest, Flow.nextOf(name, trs, acc)) + +def Flow.nextOf {r: Region} (op: Sym.Sym, trs: Coll.List[Ast.Trans], acc: Coll.List[D.Fact]): Coll.List[D.Fact] = trs match + case Coll.Nil => acc + case Coll.Cons(t, rest) => + val Ast.Trans(a, b) = t + Flow.nextOf(op, rest, Coll.Cons(D.Fact(Sym.of("next"), Coll.Cons(D.VSym(a), Coll.Cons(D.VSym(op), Coll.Cons(D.VSym(b), Coll.Nil)))), acc)) + +// rule def name(params) = body as a D.Rule: variables are the lowercase names in state positions (the op of next is a +// constant), numbered in first-seen order from the params +def Flow.ruleDefs {r: Region} (rs: Coll.List[Ast.RuleDef], acc: Coll.List[D.Rule]): Coll.List[D.Rule] = rs match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(rd, rest) => + val Ast.RuleDef(_, name, params, body) = rd + val vs = Flow.varsOf(body, Coll.rev(params)) + Flow.ruleDefs(rest, Coll.Cons(D.Rule(D.Atom(name, Flow.argsOfNames(params, vs, Coll.Nil)), Flow.bodyLits(body, vs, Coll.Nil)), acc)) + +def Flow.argOf {r: Region} (x: Sym.Sym, vs: Coll.List[Sym.Sym]): D.Arg = Flow.indexSym(vs, x, 0) match + case Coll.Some(i) => D.AVar(i) + case Coll.None => D.AVal(D.VSym(x)) + +def Flow.indexSym {r: Region} (xs: Coll.List[Sym.Sym], x: Sym.Sym, i: I64): Coll.Option[I64] = xs match + case Coll.Nil => Coll.None + case Coll.Cons(y, rest) => if Sym.eq(x, y) then Coll.Some(i) else Flow.indexSym(rest, x, i + 1) + +def Flow.argsOfNames {r: Region} (xs: Coll.List[Sym.Sym], vs: Coll.List[Sym.Sym], acc: Coll.List[D.Arg]): Coll.List[D.Arg] = xs match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(x, rest) => Flow.argsOfNames(rest, vs, Coll.Cons(Flow.argOf(x, vs), acc)) + +// a body atom: next keeps its op as a constant, any other relation maps each name (variable or constant) +def Flow.bodyLits {r: Region} (atoms: Coll.List[Ast.Atom], vs: Coll.List[Sym.Sym], acc: Coll.List[D.Lit]): Coll.List[D.Lit] = atoms match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(at, rest) => + val Ast.Atom(_, rel, args) = at + Flow.bodyLits(rest, vs, Coll.Cons(D.Pos(D.Atom(rel, Flow.termArgs(args, vs, Coll.Nil))), acc)) + +// the args of an atom: a name in vs is a variable, any other a constant (the op of next is never in vs: statePos skips it) +def Flow.termArgs {r: Region} (ts: Coll.List[Ast.Term], vs: Coll.List[Sym.Sym], acc: Coll.List[D.Arg]): Coll.List[D.Arg] = ts match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(t, rest) => t match + case Ast.TNum(v) => Flow.termArgs(rest, vs, Coll.Cons(D.AVal(D.VInt(v)), acc)) + case Ast.TName(n) => Flow.termArgs(rest, vs, Coll.Cons(Flow.argOf(n, vs), acc)) + +// the binder protocols with a transition op: S1 -> S2 for the args of a next atom (empty = it does not hold) +def Flow.nextHolds {r: Region} (ps: Coll.List[Ast.Proto], bs: Coll.List[Flow.CapB], args: Coll.List[Ast.Term], a: Coll.List[Flow.VS]): Coll.List[Flow.CapB] = args match + case Coll.Cons(t1, r1) => r1 match + case Coll.Cons(t2, r2) => r2 match + case Coll.Cons(t3, _) => Flow.nextIn(ps, bs, Flow.termSym(t1), Flow.termSym(t2), Flow.termSym(t3), a, Coll.Nil) + case Coll.Nil => Coll.Nil + case Coll.Nil => Coll.Nil + case Coll.Nil => Coll.Nil + +def Flow.nextIn {r: Region} (ps: Coll.List[Ast.Proto], bs: Coll.List[Flow.CapB], s1: Coll.Option[Sym.Sym], op: Coll.Option[Sym.Sym], s2: Coll.Option[Sym.Sym], a: Coll.List[Flow.VS], acc: Coll.List[Flow.CapB]): Coll.List[Flow.CapB] = s1 match + case Coll.None => acc + case Coll.Some(x1) => op match + case Coll.None => acc + case Coll.Some(o) => s2 match + case Coll.None => acc + case Coll.Some(x2) => Flow.withTrans(ps, bs, Flow.resolve(a, x1), o, Flow.resolve(a, x2), acc) + +def Flow.withTrans {r: Region} (ps: Coll.List[Ast.Proto], bs: Coll.List[Flow.CapB], a: Sym.Sym, op: Sym.Sym, b: Sym.Sym, acc: Coll.List[Flow.CapB]): Coll.List[Flow.CapB] = bs match + case Coll.Nil => acc + case Coll.Cons(x, rest) => + val Flow.CapB(_, _, proto) = x + val ok: Bool = Flow.protoNamed(ps, proto) match + case Coll.None => false + case Coll.Some(pr) => + val Ast.Proto(_, _, _, _, _, _, ops, _) = pr + Flow.opHas(ops, op, a, b) + if ok then Flow.withTrans(ps, rest, a, op, b, Coll.Cons(x, acc)) else Flow.withTrans(ps, rest, a, op, b, acc) + +def Flow.opHas(ops: Coll.List[Ast.Op], op: Sym.Sym, a: Sym.Sym, b: Sym.Sym): Bool = ops match + case Coll.Nil => false + case Coll.Cons(o, rest) => + val Ast.Op(_, name, _, _, trs) = o + if Sym.eq(name, op) && Flow.transHas(trs, a, b) then true else Flow.opHas(rest, op, a, b) + +def Flow.transHas(trs: Coll.List[Ast.Trans], a: Sym.Sym, b: Sym.Sym): Bool = trs match + case Coll.Nil => false + case Coll.Cons(t, rest) => + val Ast.Trans(x, y) = t + if Sym.eq(x, a) && Sym.eq(y, b) then true else Flow.transHas(rest, a, b) + +// the state an at(binder, S) atom gives under a, or None when the binder has no such atom +def Flow.atState {r: Region} (atoms: Coll.List[Ast.Atom], x: Sym.Sym, a: Coll.List[Flow.VS]): Coll.Option[Sym.Sym] = atoms match + case Coll.Nil => Coll.None + case Coll.Cons(at, rest) => + val Ast.Atom(_, rel, args) = at + if Sym.eq(rel, Sym.of("at")) then Flow.atArgs(args, x, a, rest) else Flow.atState(rest, x, a) + +def Flow.atArgs {r: Region} (args: Coll.List[Ast.Term], x: Sym.Sym, a: Coll.List[Flow.VS], rest: Coll.List[Ast.Atom]): Coll.Option[Sym.Sym] = args match + case Coll.Cons(t1, r1) => r1 match + case Coll.Cons(t2, _) => Flow.termSym(t1) match + case Coll.Some(c) => if Sym.eq(c, x) then Flow.resolved(Flow.termSym(t2), a) else Flow.atState(rest, x, a) + case Coll.None => Flow.atState(rest, x, a) + case Coll.Nil => Flow.atState(rest, x, a) + case Coll.Nil => Flow.atState(rest, x, a) + +def Flow.resolved {r: Region} (t: Coll.Option[Sym.Sym], a: Coll.List[Flow.VS]): Coll.Option[Sym.Sym] = t match + case Coll.None => t + case Coll.Some(s) => Coll.Some(Flow.resolve(a, s)) + +// solution j per assignment: pre = the entry at() state, else the protocol start (s1/check.srs:899); post = the exit +// at() state, else pre +def Flow.sols {r: Region} (ps: Coll.List[Ast.Proto], st: Flow.St, s: I64, bs: Coll.List[Flow.CapB], atoms: Coll.List[Ast.Atom], exit: Coll.List[Ast.Atom], as: Coll.List[Coll.List[Flow.VS]], j: I64): Flow.St = as match + case Coll.Nil => st + case Coll.Cons(a, rest) => Flow.sols(ps, Flow.prePost(ps, Flow.add(st, Flow.fSameI(j)), s, j, bs, atoms, exit, a, 0), s, bs, atoms, exit, rest, j + 1) + +def Flow.prePost {r: Region} (ps: Coll.List[Ast.Proto], st: Flow.St, s: I64, j: I64, bs: Coll.List[Flow.CapB], atoms: Coll.List[Ast.Atom], exit: Coll.List[Ast.Atom], a: Coll.List[Flow.VS], m: I64): Flow.St = bs match + case Coll.Nil => st + case Coll.Cons(b, rest) => + val Flow.CapB(x, _, proto) = b + val pre: Coll.Option[Sym.Sym] = Flow.atState(atoms, x, a) match + case Coll.Some(e) => Coll.Some(e) + case Coll.None => Flow.startOf(ps, proto) + pre match + case Coll.None => Flow.prePost(ps, st, s, j, rest, atoms, exit, a, m + 1) + case Coll.Some(e) => + val post: Sym.Sym = Flow.atState(exit, x, a) match + case Coll.Some(o) => o + case Coll.None => e + Flow.prePost(ps, Flow.add(Flow.add(st, Flow.fPre(s, j, m, e)), Flow.fPost(s, j, m, post)), s, j, rest, atoms, exit, a, m + 1) + +def Flow.startOf {r: Region} (ps: Coll.List[Ast.Proto], proto: Sym.Sym): Coll.Option[Sym.Sym] = Flow.protoNamed(ps, proto) match + case Coll.None => Coll.None + case Coll.Some(pr) => + val Ast.Proto(_, _, _, start, _, _, _, _) = pr + Coll.Some(start) + +// a block: its statements, its value, then a block end point where its own capabilities end their scope +def Flow.block {r: Region} (cx: Flow.Cx, st: Flow.St, p: I64, ss: Coll.List[Ast.Stmt], last: Ast.Expr, line: I64): Flow.At = + val Flow.St(_, _, outer) = st + val Flow.At(st1, p1) = Flow.stmts(cx, st, p, ss) + val Flow.At(st2, p2) = Flow.expr(cx, st1, p1, last) + val Flow.At(st3, e) = Flow.next(st2, p2) + val Flow.St(n, fs, inner) = st3 + // a block that closes capabilities: its value must not live in one of them (escape) + val fs2 = if Coll.length(inner) <= Coll.length(outer) then fs else Flow.escFacts(Flow.srcs(cx, inner, last, Coll.Nil), e, line, fs) + Flow.At(Flow.St(n, Flow.closes(inner, outer, e, fs2), outer), e) + +def Flow.escFacts {r: Region} (sv: Coll.List[Flow.Src], e: I64, line: I64, fs: Coll.List[D.Fact]): Coll.List[D.Fact] = sv match + case Coll.Nil => fs + case Coll.Cons(s, rest) => s match + case Flow.SCap(c) => Flow.escFacts(rest, e, line, Coll.Cons(Flow.fEscCap(e, c, line), fs)) + case Flow.SVar(y) => Flow.escFacts(rest, e, line, Coll.Cons(Flow.fEscVar(e, y, line), fs)) + +// close(e, c) for every capability of inner that is not in outer (the block's own, innermost first) +def Flow.closes {r: Region} (inner: Coll.List[Flow.Cap], outer: Coll.List[Flow.Cap], e: I64, fs: Coll.List[D.Fact]): Coll.List[D.Fact] = + if Coll.length(inner) <= Coll.length(outer) then fs + else inner match + case Coll.Nil => fs + case Coll.Cons(c, rest) => + val Flow.Cap(_, id, _, _) = c + Flow.closes(rest, outer, e, Coll.Cons(Flow.fClose(e, id), fs)) + +def Flow.stmts {r: Region} (cx: Flow.Cx, st: Flow.St, p: I64, ss: Coll.List[Ast.Stmt]): Flow.At = ss match + case Coll.Nil => Flow.At(st, p) + case Coll.Cons(s, rest) => + val Flow.At(st2, p2) = Flow.stmt(cx, st, p, s) + Flow.stmts(cx, st2, p2, rest) + +def Flow.stmt {r: Region} (cx: Flow.Cx, st: Flow.St, p: I64, s: Ast.Stmt): Flow.At = s match + case Ast.Val(_, x, ann, e) => Flow.bindVal(cx, Flow.needs(cx, st, x, ann), p, x, e) + case Ast.Var(_, x, _, e) => Flow.bindVal(cx, st, p, x, e) + case Ast.Do(e) => Flow.expr(cx, st, p, e) + case Ast.Check(_, _, e) => Flow.expr(cx, st, p, e) + case Ast.Handle(line, x, h, xs) => + val Flow.At(st1, pa) = Flow.exprs(cx, st, p, xs) + Flow.protoOf(Flow.cxHs(cx), h) match + case Coll.None => Flow.At(st1, pa) + case Coll.Some(proto) => + val Flow.At(st2, id) = Flow.fresh(st1) + val Flow.St(n, fs, cs) = st2 + val st3 = Flow.St(n, fs, Coll.Cons(Flow.Cap(x, id, proto, line), cs)) + val st4 = Flow.add(Flow.add(st3, Flow.fCapOf(id, proto)), Flow.fCapName(id, x)) + Flow.At(Flow.add(Flow.add(st4, Flow.fCapLine(id, line)), Flow.fHandle(pa, id)), pa) + +// ── the protocols as facts: transitions, end states (an end state, or a state whose drop op reaches one), states ── +def Flow.protoFacts {r: Region} (ps: Coll.List[Ast.Proto], fs: Coll.List[D.Fact]): Coll.List[D.Fact] = ps match + case Coll.Nil => fs + case Coll.Cons(p, rest) => + val Ast.Proto(_, name, states, start, ends, dropOp, ops, _) = p + val fs1 = Flow.opFacts(name, ops, fs) + val fs2 = Flow.stateFacts(name, start, states, ends, dropOp, ops, fs1) + Flow.protoFacts(rest, fs2) + +def Flow.opFacts {r: Region} (proto: Sym.Sym, ops: Coll.List[Ast.Op], fs: Coll.List[D.Fact]): Coll.List[D.Fact] = ops match + case Coll.Nil => fs + case Coll.Cons(o, rest) => + val Ast.Op(_, name, _, _, trs) = o + Flow.opFacts(proto, rest, Flow.transFacts(proto, name, trs, fs)) + +def Flow.transFacts {r: Region} (proto: Sym.Sym, op: Sym.Sym, trs: Coll.List[Ast.Trans], fs: Coll.List[D.Fact]): Coll.List[D.Fact] = trs match + case Coll.Nil => fs + case Coll.Cons(t, rest) => + val Ast.Trans(a, b) = t + Flow.transFacts(proto, op, rest, Coll.Cons(Flow.fTr(proto, op, a, b), fs)) + +def Flow.stateFacts {r: Region} (proto: Sym.Sym, start: Sym.Sym, states: Coll.List[Sym.Sym], ends: Coll.List[Sym.Sym], dropOp: Coll.Option[Sym.Sym], ops: Coll.List[Ast.Op], fs: Coll.List[D.Fact]): Coll.List[D.Fact] = states match + case Coll.Nil => Coll.Cons(Flow.fStart(proto, start), fs) + case Coll.Cons(s, rest) => + val fs1 = Coll.Cons(Flow.fSame(s, s), fs) + val fs2 = if Flow.endsAfterDrop(s, ends, dropOp, ops) then Coll.Cons(Flow.fEndOk(proto, s), fs1) else fs1 + val fs3 = if Flow.memberSym(s, ends) then Coll.Cons(Flow.fFin(proto, s), fs2) else fs2 + Flow.stateFacts(proto, start, rest, ends, dropOp, ops, fs3) + +def Flow.memberSym(x: Sym.Sym, xs: Coll.List[Sym.Sym]): Bool = xs match + case Coll.Nil => false + case Coll.Cons(h, t) => if Sym.eq(h, x) then true else Flow.memberSym(x, t) + +// s is an end state, or the drop op takes s to an end state +def Flow.endsAfterDrop(s: Sym.Sym, ends: Coll.List[Sym.Sym], dropOp: Coll.Option[Sym.Sym], ops: Coll.List[Ast.Op]): Bool = + if Flow.memberSym(s, ends) then true + else dropOp match + case Coll.None => false + case Coll.Some(d) => Flow.dropReaches(s, d, ends, ops) + +def Flow.dropReaches(s: Sym.Sym, d: Sym.Sym, ends: Coll.List[Sym.Sym], ops: Coll.List[Ast.Op]): Bool = ops match + case Coll.Nil => false + case Coll.Cons(o, rest) => + val Ast.Op(_, name, _, _, trs) = o + if Sym.eq(name, d) then Flow.transReaches(s, trs, ends) else Flow.dropReaches(s, d, ends, rest) + +def Flow.transReaches(s: Sym.Sym, trs: Coll.List[Ast.Trans], ends: Coll.List[Sym.Sym]): Bool = trs match + case Coll.Nil => false + case Coll.Cons(t, rest) => + val Ast.Trans(a, b) = t + if Sym.eq(a, s) && Flow.memberSym(b, ends) then true else Flow.transReaches(s, rest, ends) + +// ── the rule library (variables are numbered per rule) ── +def Flow.v {r: Region} (n: I64): D.Arg = D.AVar(n) +def Flow.atom {r: Region} (rel: Flow.Rel, xs: Coll.List[I64]): D.Atom = D.Atom(Flow.relSym(rel), Flow.vars(xs)) +def Flow.vars {r: Region} (xs: Coll.List[I64]): Coll.List[D.Arg] = xs match + case Coll.Nil => Coll.Nil + case Coll.Cons(x, rest) => Coll.Cons(Flow.v(x), Flow.vars(rest)) +def Flow.l1 [A: Type] {r: Region} (a: A): Coll.List[A] = Coll.Cons(a, Coll.Nil) +def Flow.l2 [A: Type] {r: Region} (a: A, b: A): Coll.List[A] = Coll.Cons(a, Flow.l1(b)) +def Flow.l3 [A: Type] {r: Region} (a: A, b: A, c: A): Coll.List[A] = Coll.Cons(a, Flow.l2(b, c)) +def Flow.l4 [A: Type] {r: Region} (a: A, b: A, c: A, d: A): Coll.List[A] = Coll.Cons(a, Flow.l3(b, c, d)) +def Flow.l5 [A: Type] {r: Region} (a: A, b: A, c: A, d: A, e: A): Coll.List[A] = Coll.Cons(a, Flow.l4(b, c, d, e)) +def Flow.pos {r: Region} (rel: Flow.Rel, xs: Coll.List[I64]): D.Lit = D.Pos(Flow.atom(rel, xs)) +def Flow.neg {r: Region} (rel: Flow.Rel, xs: Coll.List[I64]): D.Lit = D.Neg(Flow.atom(rel, xs)) +def Flow.rule {r: Region} (rel: Flow.Rel, xs: Coll.List[I64], body: Coll.List[D.Lit]): D.Rule = D.Rule(Flow.atom(rel, xs), body) + +// variables: p 0, q 1, w 2, c 3, s 4, t 5, op 6, proto 7, line 8, name 9 +def Flow.rules {r: Region} (): Coll.List[D.Rule] = + // a handle puts its capability in the start state of its protocol (world 0: one world until facts with variables) + val enter = Flow.rule(Flow.RAt, Flow.l4(0, 2, 3, 4), Flow.l4(Flow.pos(Flow.RHandle, Flow.l2(0, 3)), Flow.pos(Flow.RCapOf, Flow.l2(3, 7)), Flow.pos(Flow.RStart, Flow.l2(7, 4)), Flow.pos(Flow.RWorld, Flow.l1(2)))) + // frame along control edges; a capability ends at the block end that closes it + val frame = Flow.rule(Flow.RAt, Flow.l4(1, 2, 3, 4), Flow.l3(Flow.pos(Flow.RFlow, Flow.l2(0, 1)), Flow.pos(Flow.RAt, Flow.l4(0, 2, 3, 4)), Flow.neg(Flow.RClose, Flow.l2(0, 3)))) + // a step moves its capability only + val touch = Flow.rule(Flow.RTouch, Flow.l2(0, 3), Flow.l1(Flow.pos(Flow.RStep, Flow.l4(0, 1, 3, 6)))) + val keep = Flow.rule(Flow.RAt, Flow.l4(1, 2, 3, 4), Flow.l3(Flow.pos(Flow.RStep, Flow.l4(0, 1, 5, 6)), Flow.pos(Flow.RAt, Flow.l4(0, 2, 3, 4)), Flow.neg(Flow.RTouch, Flow.l2(0, 3)))) + val move = Flow.rule(Flow.RAt, Flow.l4(1, 2, 3, 5), Flow.l4(Flow.pos(Flow.RStep, Flow.l4(0, 1, 3, 6)), Flow.pos(Flow.RCapOf, Flow.l2(3, 7)), Flow.pos(Flow.RTr, Flow.l4(7, 6, 4, 5)), Flow.pos(Flow.RAt, Flow.l4(0, 2, 3, 4)))) + val moved = Flow.rule(Flow.RMoved, Flow.l2(0, 2), Flow.l4(Flow.pos(Flow.RStep, Flow.l4(0, 1, 3, 6)), Flow.pos(Flow.RCapOf, Flow.l2(3, 7)), Flow.pos(Flow.RTr, Flow.l4(7, 6, 4, 5)), Flow.pos(Flow.RAt, Flow.l4(0, 2, 3, 4)))) + val seen = Flow.rule(Flow.RSeen, Flow.l3(0, 2, 3), Flow.l2(Flow.pos(Flow.RStep, Flow.l4(0, 1, 3, 6)), Flow.pos(Flow.RAt, Flow.l4(0, 2, 3, 4)))) + // clashes: the line and the capability's name + val stuck = Flow.rule(Flow.RStuck, Flow.l2(8, 9), Flow.l4(Flow.pos(Flow.RSeen, Flow.l3(0, 2, 3)), Flow.neg(Flow.RMoved, Flow.l2(0, 2)), Flow.pos(Flow.RLine, Flow.l2(0, 8)), Flow.pos(Flow.RCapName, Flow.l2(3, 9)))) + val split = Flow.rule(Flow.RSplit, Flow.l2(8, 3), Flow.l5(Flow.pos(Flow.RMerge, Flow.l1(0)), Flow.pos(Flow.RAt, Flow.l4(0, 2, 3, 4)), Flow.pos(Flow.RAt, Flow.l4(0, 2, 3, 5)), Flow.neg(Flow.RSame, Flow.l2(4, 5)), Flow.pos(Flow.RLine, Flow.l2(0, 8)))) + val splitN = Flow.rule(Flow.RSplitAt, Flow.l2(8, 9), Flow.l2(Flow.pos(Flow.RSplit, Flow.l2(8, 3)), Flow.pos(Flow.RCapName, Flow.l2(3, 9)))) + val unended = Flow.rule(Flow.RUnended, Flow.l2(8, 3), Flow.l5(Flow.pos(Flow.RClose, Flow.l2(0, 3)), Flow.pos(Flow.RAt, Flow.l4(0, 2, 3, 4)), Flow.pos(Flow.RCapOf, Flow.l2(3, 7)), Flow.neg(Flow.REndOk, Flow.l2(7, 4)), Flow.pos(Flow.RCapLine, Flow.l2(3, 8)))) + val unendedN = Flow.rule(Flow.RUnendedAt, Flow.l2(8, 9), Flow.l2(Flow.pos(Flow.RUnended, Flow.l2(8, 3)), Flow.pos(Flow.RCapName, Flow.l2(3, 9)))) + val f1 = Coll.Cons(enter, Coll.Cons(frame, Coll.Cons(touch, Coll.Cons(keep, Coll.Cons(move, Coll.Cons(moved, Coll.Cons(seen, Coll.Cons(stuck, Coll.Cons(split, Coll.Cons(splitN, Coll.Cons(unended, Coll.Cons(unendedN, Coll.Nil)))))))))))) + Coll.revOnto(Coll.rev(f1), Coll.revOnto(Coll.rev(Flow.callRules()), Flow.capsRules())) + +// R2 for calls (flow-design.md): the call point p is its own kind; j 10, m 11, n 12, i 13 +def Flow.callRules {r: Region} (): Coll.List[D.Rule] = + // a bound capability is touched: no frame across the call, its state comes from the solution that fits + val touchB = Flow.rule(Flow.RTouch, Flow.l2(0, 3), Flow.l1(Flow.pos(Flow.RBind, Flow.l3(0, 11, 3)))) + val cframe = Flow.rule(Flow.RAt, Flow.l4(1, 2, 3, 4), Flow.l3(Flow.pos(Flow.RCStep, Flow.l2(0, 1)), Flow.pos(Flow.RAt, Flow.l4(0, 2, 3, 4)), Flow.neg(Flow.RTouch, Flow.l2(0, 3)))) + // solution j fits when every param is in its pre state: a positive chain over the params + val ok1 = Flow.rule(Flow.ROk, Flow.l4(0, 2, 10, 11), Flow.l4(Flow.pos(Flow.RFirst, Flow.l2(0, 11)), Flow.pos(Flow.RPre, Flow.l4(0, 10, 11, 4)), Flow.pos(Flow.RBind, Flow.l3(0, 11, 3)), Flow.pos(Flow.RAt, Flow.l4(0, 2, 3, 4)))) + val ok2 = Flow.rule(Flow.ROk, Flow.l4(0, 2, 10, 12), Flow.l5(Flow.pos(Flow.ROk, Flow.l4(0, 2, 10, 11)), Flow.pos(Flow.RNext, Flow.l3(0, 11, 12)), Flow.pos(Flow.RPre, Flow.l4(0, 10, 12, 4)), Flow.pos(Flow.RBind, Flow.l3(0, 12, 3)), Flow.pos(Flow.RAt, Flow.l4(0, 2, 3, 4)))) + val fits = Flow.rule(Flow.RFits, Flow.l3(0, 2, 10), Flow.l2(Flow.pos(Flow.ROk, Flow.l4(0, 2, 10, 11)), Flow.pos(Flow.RLast, Flow.l2(0, 11)))) + val cmove = Flow.rule(Flow.RAt, Flow.l4(1, 2, 3, 4), Flow.l4(Flow.pos(Flow.RFits, Flow.l3(0, 2, 10)), Flow.pos(Flow.RCStep, Flow.l2(0, 1)), Flow.pos(Flow.RPost, Flow.l4(0, 10, 11, 4)), Flow.pos(Flow.RBind, Flow.l3(0, 11, 3)))) + val cmoved = Flow.rule(Flow.RMoved, Flow.l2(0, 2), Flow.l1(Flow.pos(Flow.RFits, Flow.l3(0, 2, 10)))) + val cseen = Flow.rule(Flow.RCSeen, Flow.l2(0, 2), Flow.l2(Flow.pos(Flow.RBind, Flow.l3(0, 11, 3)), Flow.pos(Flow.RAt, Flow.l4(0, 2, 3, 4)))) + // clashes: no solution fits (stuck, as an op), more than one fits (ambig); the name is the callee + val cstuck = Flow.rule(Flow.RStuck, Flow.l2(8, 9), Flow.l4(Flow.pos(Flow.RCSeen, Flow.l2(0, 2)), Flow.neg(Flow.RMoved, Flow.l2(0, 2)), Flow.pos(Flow.RLine, Flow.l2(0, 8)), Flow.pos(Flow.RCallee, Flow.l2(0, 9)))) + val ambig = Flow.rule(Flow.RAmbig, Flow.l2(0, 2), Flow.l3(Flow.pos(Flow.RFits, Flow.l3(0, 2, 10)), Flow.pos(Flow.RFits, Flow.l3(0, 2, 13)), Flow.neg(Flow.RSame, Flow.l2(10, 13)))) + val ambigN = Flow.rule(Flow.RAmbigAt, Flow.l2(8, 9), Flow.l3(Flow.pos(Flow.RAmbig, Flow.l2(0, 2)), Flow.pos(Flow.RLine, Flow.l2(0, 8)), Flow.pos(Flow.RCallee, Flow.l2(0, 9)))) + // the def side: a binder enters in its world's pre state; it must leave in the world's post state (exitBad) + val enterB = Flow.rule(Flow.RAt, Flow.l4(0, 2, 3, 4), Flow.l1(Flow.pos(Flow.REnter, Flow.l4(0, 2, 3, 4)))) + val exitBad = Flow.rule(Flow.RExitBad, Flow.l2(8, 9), Flow.l5(Flow.pos(Flow.RWant, Flow.l4(0, 2, 3, 4)), Flow.pos(Flow.RAt, Flow.l4(0, 2, 3, 5)), Flow.neg(Flow.RSame, Flow.l2(4, 5)), Flow.pos(Flow.RCapLine, Flow.l2(3, 8)), Flow.pos(Flow.RCapName, Flow.l2(3, 9)))) + val noSol = Flow.rule(Flow.RNoSolAt, Flow.l2(8, 9), Flow.l1(Flow.pos(Flow.RNoSol, Flow.l2(8, 9)))) + Coll.Cons(touchB, Coll.Cons(cframe, Coll.Cons(ok1, Coll.Cons(ok2, Coll.Cons(fits, Coll.Cons(cmove, Coll.Cons(cmoved, Coll.Cons(cseen, Coll.Cons(cstuck, Coll.Cons(ambig, Coll.Cons(ambigN, Coll.Cons(enterB, Coll.Cons(exitBad, Coll.Cons(noSol, Coll.Nil)))))))))))))) + +// the facts of fn f: its walk from a first point, the protocols. each solution j of f's entry facts is world j: the +// capability binders enter point 0 in their pre states and must leave the body in their post states (s1/check.srs:498); +// no binders: one world. no solution: the def has none (NoSol) +def Flow.facts {r: Region} (cx: Flow.Cx, f: Ast.Fn): Coll.List[D.Fact] = + val Ast.Fn(line, name, gs, _, _, exit, body) = f + val Flow.Cx(ps, _, _, _, _) = cx + val bs = Flow.capBs(ps, gs, 0, Coll.Nil) + val atoms = Flow.entryAtoms(gs, Coll.Nil) + val as: Coll.List[Coll.List[Flow.VS]] = bs match + case Coll.Nil => Coll.Cons(Coll.Nil, Coll.Nil) + case Coll.Cons(_, _) => Flow.assigns(ps, Flow.ruleModels(ps, bs, Coll.Nil), bs, atoms, Flow.varsOf(atoms, Coll.Nil), Coll.Nil, Coll.Nil) + val st0 = Flow.binderCaps(Flow.St(1, Coll.Nil, Coll.Nil), bs, line) + val Flow.St(_, _, caps) = st0 + val st1 = Flow.worlds(ps, st0, Coll.rev(caps), bs, atoms, exit, as, 0, Flow.Entry) + val walked: Flow.At = body match + case Ast.Extern => Flow.At(st1, 0) + case Ast.Def(_, e) => Flow.expr(cx, st1, 0, e) + case Ast.Spec(_, e) => Flow.expr(cx, st1, 0, e) + val Flow.At(st2, e) = walked + val st3 = Flow.worlds(ps, st2, Coll.rev(caps), bs, atoms, exit, as, 0, Flow.Exit(e)) + val st4 = as match + case Coll.Nil => Flow.add(st3, Flow.fNoSol(line, name)) + case Coll.Cons(_, _) => st3 + val Flow.St(_, fs, _) = st4 + Flow.protoFacts(ps, fs) + +// which end of the body world facts are for: the entry (world, enter) or the exit at point e (want) +enum Flow.End: + case Flow.Entry + case Flow.Exit(e: I64) + +// each capability binder is a capability in scope from point 0, named and lined by the def +def Flow.binderCaps {r: Region} (st: Flow.St, bs: Coll.List[Flow.CapB], line: I64): Flow.St = bs match + case Coll.Nil => st + case Coll.Cons(b, rest) => + val Flow.CapB(x, _, proto) = b + val Flow.At(st1, id) = Flow.fresh(st) + val Flow.St(n, fs, cs) = st1 + val st2 = Flow.St(n, fs, Coll.Cons(Flow.Cap(x, id, proto, line), cs)) + Flow.binderCaps(Flow.add(Flow.add(Flow.add(st2, Flow.fCapOf(id, proto)), Flow.fCapName(id, x)), Flow.fCapLine(id, line)), rest, line) + +// per solution j: world(j) and enter(0, j, c, pre) at the entry, want(e, j, c, post) at the exit +def Flow.worlds {r: Region} (ps: Coll.List[Ast.Proto], st: Flow.St, caps: Coll.List[Flow.Cap], bs: Coll.List[Flow.CapB], atoms: Coll.List[Ast.Atom], exit: Coll.List[Ast.Atom], as: Coll.List[Coll.List[Flow.VS]], j: I64, end: Flow.End): Flow.St = as match + case Coll.Nil => st + case Coll.Cons(a, rest) => + val st1 = end match + case Flow.Entry => Flow.add(st, Flow.fWorld(j)) + case Flow.Exit(_) => st + Flow.worlds(ps, Flow.worldCaps(ps, st1, caps, bs, atoms, exit, a, j, end), caps, bs, atoms, exit, rest, j + 1, end) + +def Flow.worldCaps {r: Region} (ps: Coll.List[Ast.Proto], st: Flow.St, caps: Coll.List[Flow.Cap], bs: Coll.List[Flow.CapB], atoms: Coll.List[Ast.Atom], exit: Coll.List[Ast.Atom], a: Coll.List[Flow.VS], j: I64, end: Flow.End): Flow.St = caps match + case Coll.Nil => st + case Coll.Cons(c, crest) => bs match + case Coll.Nil => st + case Coll.Cons(b, brest) => + val Flow.Cap(_, id, _, _) = c + val Flow.CapB(x, _, proto) = b + val pre: Coll.Option[Sym.Sym] = Flow.atState(atoms, x, a) match + case Coll.Some(s) => Coll.Some(s) + case Coll.None => Flow.startOf(ps, proto) + val st1: Flow.St = pre match + case Coll.None => st + case Coll.Some(s) => end match + case Flow.Entry => Flow.add(st, Flow.fEnter(0, j, id, s)) + case Flow.Exit(e) => Flow.atState(exit, x, a) match + case Coll.Some(o) => Flow.add(st, Flow.fWant(e, j, id, o)) + case Coll.None => Flow.add(st, Flow.fWant(e, j, id, s)) + Flow.worldCaps(ps, st1, crest, brest, atoms, exit, a, j, end) + +// ── the verdict: the clash relations read back. a tuple of another shape than (line, name) means Flow.rules is wrong: +// the whole reading is IllTyped (a verdict), so no clash value holds a bad tuple ── +enum Flow.Read: + case Flow.Got(cs: Coll.List[Flow.Clash]) + case Flow.IllTyped(rel: Sym.Sym) + +def Flow.clashes {r: Region} (m: D.Model, k: Flow.Kind, prev: Flow.Read): Flow.Read = prev match + case Flow.IllTyped(_) => prev + case Flow.Got(acc) => Flow.clashList(k, D.tuples(m, Flow.relSym(Flow.relOf(k))), acc) + +def Flow.clashList {r: Region} (k: Flow.Kind, ts: Coll.List[Coll.List[D.Val]], acc: Coll.List[Flow.Clash]): Flow.Read = ts match + case Coll.Nil => Flow.Got(acc) + case Coll.Cons(t, rest) => Flow.clashOf(k, t) match + case Coll.None => Flow.IllTyped(Flow.relSym(Flow.relOf(k))) + case Coll.Some(c) => Flow.clashList(k, rest, Coll.Cons(c, acc)) + +// a clash tuple is (line, capability name), exactly two values +def Flow.clashOf {r: Region} (k: Flow.Kind, t: Coll.List[D.Val]): Coll.Option[Flow.Clash] = t match + case Coll.Cons(a, rest) => rest match + case Coll.Cons(b, more) => more match + case Coll.Nil => Flow.clashLN(k, a, b) + case Coll.Cons(_, _) => Coll.None + case Coll.Nil => Coll.None + case Coll.Nil => Coll.None + +def Flow.clashLN {r: Region} (k: Flow.Kind, a: D.Val, b: D.Val): Coll.Option[Flow.Clash] = a match + case D.VInt(line) => b match + case D.VSym(name) => Coll.Some(Flow.make(k, line, name)) + case D.VInt(_) => Coll.None + case D.VSym(_) => Coll.None + +// every clash relation of a solved model, read +def Flow.readAll {r: Region} (m: D.Model): Flow.Read = + Flow.clashes(m, Flow.KStale, Flow.clashes(m, Flow.KStuck, Flow.clashes(m, Flow.KSplit, Flow.clashes(m, Flow.KUnended, Flow.clashes(m, Flow.KAmbig, Flow.clashes(m, Flow.KExitBad, Flow.clashes(m, Flow.KNoSol, Flow.clashes(m, Flow.KDead, Flow.clashes(m, Flow.KEscape, Flow.Got(Coll.Nil)))))))))) + +def Flow.make {r: Region} (k: Flow.Kind, line: I64, name: Sym.Sym): Flow.Clash = k match + case Flow.KStuck => Flow.Stuck(line, name) + case Flow.KSplit => Flow.Split(line, name) + case Flow.KUnended => Flow.Unended(line, name) + case Flow.KAmbig => Flow.Ambig(line, name) + case Flow.KExitBad => Flow.ExitBad(line, name) + case Flow.KNoSol => Flow.NoSol(line, name) + case Flow.KDead => Flow.Dead(line, name) + case Flow.KEscape => Flow.Escape(line, name) + case Flow.KStale => Flow.Stale(line, name) + +def Flow.verdictOf {r: Region} (rd: Flow.Read): Flow.Verdict = rd match + case Flow.IllTyped(rel) => Flow.RulesIllTyped(rel) + case Flow.Got(cs) => cs match + case Coll.Nil => Flow.Ok + case Coll.Cons(_, _) => Flow.Bad(cs) + +def Flow.check {r: Region} (cx: Flow.Cx, f: Ast.Fn): Flow.Verdict = + D.solve(Flow.rules(), Flow.facts(cx, f)) match + case D.Solved(m) => Flow.verdictOf(Flow.readAll(m)) + case D.Unsafe(rel) => Flow.RulesUnsafe(rel) + case D.NegCycle(rel) => Flow.RulesNegCycle(rel) + +// CAPS (R3): what each name holds flows along every edge; an assignment replaces it (strong update), a join is the union, +// a loop reaches its fixpoint. x 14, y 15 +def Flow.capsRules {r: Region} (): Coll.List[D.Rule] = + val e1 = Flow.rule(Flow.REdge, Flow.l2(0, 1), Flow.l1(Flow.pos(Flow.RFlow, Flow.l2(0, 1)))) + val e2 = Flow.rule(Flow.REdge, Flow.l2(0, 1), Flow.l1(Flow.pos(Flow.RStep, Flow.l4(0, 1, 3, 6)))) + val e3 = Flow.rule(Flow.REdge, Flow.l2(0, 1), Flow.l1(Flow.pos(Flow.RCStep, Flow.l2(0, 1)))) + val h1 = Flow.rule(Flow.RHolds, Flow.l3(1, 14, 3), Flow.l2(Flow.pos(Flow.RAssign, Flow.l3(0, 14, 3)), Flow.pos(Flow.REdge, Flow.l2(0, 1)))) + val h2 = Flow.rule(Flow.RHolds, Flow.l3(1, 14, 3), Flow.l3(Flow.pos(Flow.RAssignFrom, Flow.l3(0, 14, 15)), Flow.pos(Flow.RHolds, Flow.l3(0, 15, 3)), Flow.pos(Flow.REdge, Flow.l2(0, 1)))) + val h3 = Flow.rule(Flow.RHolds, Flow.l3(1, 14, 3), Flow.l3(Flow.pos(Flow.REdge, Flow.l2(0, 1)), Flow.pos(Flow.RHolds, Flow.l3(0, 14, 3)), Flow.neg(Flow.RAssigns, Flow.l2(0, 14)))) + // a read of x at p uses every region x holds there; a region in an end state is dead + val dead = Flow.rule(Flow.RDead, Flow.l2(8, 9), Coll.Cons(Flow.pos(Flow.RReadAt, Flow.l3(0, 14, 8)), Coll.Cons(Flow.pos(Flow.RHolds, Flow.l3(0, 14, 3)), Flow.l4(Flow.pos(Flow.RAt, Flow.l4(0, 2, 3, 4)), Flow.pos(Flow.RCapOf, Flow.l2(3, 7)), Flow.pos(Flow.RFin, Flow.l2(7, 4)), Flow.pos(Flow.RCapName, Flow.l2(3, 9)))))) + // a block value in a capability the block closes escapes + val esc1 = Flow.rule(Flow.REscape, Flow.l2(8, 9), Flow.l3(Flow.pos(Flow.REscCap, Flow.l3(0, 3, 8)), Flow.pos(Flow.RClose, Flow.l2(0, 3)), Flow.pos(Flow.RCapName, Flow.l2(3, 9)))) + val esc2 = Flow.rule(Flow.REscape, Flow.l2(8, 9), Flow.l4(Flow.pos(Flow.REscVar, Flow.l3(0, 15, 8)), Flow.pos(Flow.RHolds, Flow.l3(0, 15, 3)), Flow.pos(Flow.RClose, Flow.l2(0, 3)), Flow.pos(Flow.RCapName, Flow.l2(3, 9)))) + // a value whose type needs its capability in state S is read where the capability is in another state (vars: P 0, + // X 1, L 2, C 3, S 4, W 5, S2 6) + val stale = Flow.rule(Flow.RStale, Flow.l2(2, 1), Flow.l4(Flow.pos(Flow.RReadAt, Flow.l3(0, 1, 2)), Flow.pos(Flow.RNeed, Flow.l3(1, 3, 4)), Flow.pos(Flow.RAt, Flow.l4(0, 5, 3, 6)), Flow.neg(Flow.RSameS, Flow.l2(6, 4)))) + Coll.Cons(e1, Coll.Cons(e2, Coll.Cons(e3, Coll.Cons(h1, Coll.Cons(h2, Coll.Cons(h3, Coll.Cons(dead, Coll.Cons(esc1, Coll.Cons(esc2, Flow.l1(stale)))))))))) + +// x: T where T's decl has with b a {} capability of protocol P: x needs the one P in scope in state S at +// every read (vic-jxk type facts); sameS gives the states of P to compare +def Flow.needs {r: Region} (cx: Flow.Cx, st: Flow.St, x: Sym.Sym, ann: Coll.Option[Ast.Ty]): Flow.St = ann match + case Coll.None => st + case Coll.Some(t) => + val Ast.Ty(_, tn, _, _, _) = t + val Flow.Cx(ps, _, _, _, ts) = cx + Flow.typeDecl(ts, tn) match + case Coll.None => st + case Coll.Some(td) => + val Ast.TypeDecl(_, _, gs, _, _) = td + Flow.needAtoms(ps, Ty.evidence(gs, Coll.Nil), x, Flow.entryAtoms(gs, Coll.Nil), st) + +def Flow.typeDecl {r: Region} (ts: Coll.List[Ast.TypeDecl], n: Sym.Sym): Coll.Option[Ast.TypeDecl] = ts match + case Coll.Nil => Coll.None + case Coll.Cons(td, rest) => + val Ast.TypeDecl(_, m, _, _, _) = td + if Sym.eq(m, n) then Coll.Some(td) else Flow.typeDecl(rest, n) + +def Flow.needAtoms {r: Region} (ps: Coll.List[Ast.Proto], ev: Coll.List[Ast.Binder], x: Sym.Sym, as: Coll.List[Ast.Atom], st: Flow.St): Flow.St = as match + case Coll.Nil => st + case Coll.Cons(a, rest) => + val Ast.Atom(_, rel, args) = a + val st2 = if rt_str_eq(Sym.str(rel), "at") then Flow.needAt(ps, ev, x, args, st) else st + Flow.needAtoms(ps, ev, x, rest, st2) + +def Flow.needAt {r: Region} (ps: Coll.List[Ast.Proto], ev: Coll.List[Ast.Binder], x: Sym.Sym, args: Coll.List[Ast.Term], st: Flow.St): Flow.St = Fx.nth(args, 0) match + case Coll.None => st + case Coll.Some(b) => Fx.nth(args, 1) match + case Coll.None => st + case Coll.Some(s) => Flow.binderProto(ev, b) match + case Coll.None => st + case Coll.Some(p) => + val Flow.St(_, _, caps) = st + Flow.onlyCap(caps, p, Coll.None) match + case Coll.None => st + case Coll.Some(c) => + val Flow.Cap(_, id, _, _) = c + Flow.sameStates(ps, p, Flow.add(st, Flow.fact3(Flow.RNeed, Flow.s(x), Flow.i(id), Flow.s(s)))) + +def Flow.binderProto {r: Region} (bs: Coll.List[Ast.Binder], b: Sym.Sym): Coll.Option[Sym.Sym] = bs match + case Coll.Nil => Coll.None + case Coll.Cons(x, rest) => + val Ast.Binder(_, n, t) = x + val Ast.Ty(_, tn, _, _, _) = t + if Sym.eq(n, b) then Coll.Some(tn) else Flow.binderProto(rest, b) + +def Flow.sameStates {r: Region} (ps: Coll.List[Ast.Proto], p: Sym.Sym, st: Flow.St): Flow.St = ps match + case Coll.Nil => st + case Coll.Cons(pr, rest) => + val Ast.Proto(_, n, states, _, _, _, _, _) = pr + if Sym.eq(n, p) then Flow.sameAll(states, st) else Flow.sameStates(rest, p, st) + +def Flow.sameAll {r: Region} (ss: Coll.List[Sym.Sym], st: Flow.St): Flow.St = ss match + case Coll.Nil => st + case Coll.Cons(s, rest) => Flow.sameAll(rest, Flow.add(st, Flow.fact2(Flow.RSameS, Flow.s(s), Flow.s(s)))) diff --git a/bench/corpus/s2/hash.srs b/bench/corpus/s2/hash.srs new file mode 100644 index 00000000..024375a3 --- /dev/null +++ b/bench/corpus/s2/hash.srs @@ -0,0 +1,508 @@ +// s2 content hashes (s1/hash.srs, vic-uw3 H1; vic 2026-11-06: Unison hashing, names are metadata, digest (a)). the hash +// of a decl = the digest of its Ast: a local as its binding position (innermost first), a ref to another decl as that +// decl's hash, a ref inside its own SCC as the member's position (members ordered by their first-pass hash). + +// ── digest (a): 4 lanes, each h = (h * p + x) % m, m a prime below 2^32, p < 2^30: every step stays below 2^63 ── +enum Hs.Dg: + case Hs.Dg(a: I64, b: I64, c: I64, d: I64) + +def Hs.lane(h: I64, x: I64, p: I64, m: I64): I64 = if x >= 0 && x < 2147483648 then (h * p + x) % m else (h * p + ((x % m) + m) % m) % m + +def Hs.add {r: Region} (g: Hs.Dg, x: I64): Hs.Dg = + val Hs.Dg(a, b, c, d) = g + Hs.Dg(Hs.lane(a, x, 1000000007, 4294967291), Hs.lane(b, x, 998244353, 4294967279), Hs.lane(c, x, 754974721, 4294967231), Hs.lane(d, x, 167772161, 4294967197)) + +// a string: its length, then its bytes, 3 per step (the length keeps it prefix-free) +def Hs.str {r: Region} (g: Hs.Dg, s: Str): Hs.Dg = Hs.bytes(Hs.add(g, rt_str_len(s)), s, 0, rt_str_len(s)) + +def Hs.bytes {r: Region} (g: Hs.Dg, s: Str, i: I64, n: I64): Hs.Dg = + if i + 2 < n then Hs.bytes(Hs.add(g, rt_str_at(s, i) + 256 * rt_str_at(s, i + 1) + 65536 * rt_str_at(s, i + 2)), s, i + 3, n) + else if i < n then Hs.bytes(Hs.add(g, rt_str_at(s, i)), s, i + 1, n) + else g + +def Hs.dg {r: Region} (g: Hs.Dg, h: Hs.Dg): Hs.Dg = + val Hs.Dg(a, b, c, d) = h + Hs.add(Hs.add(Hs.add(Hs.add(g, a), b), c), d) + +def Hs.less(x: Hs.Dg, y: Hs.Dg): Bool = + val Hs.Dg(a, b, c, d) = x + val Hs.Dg(a2, b2, c2, d2) = y + a < a2 || (a == a2 && (b < b2 || (b == b2 && (c < c2 || (c == c2 && d < d2))))) + +// ── the walk: pass 1 hashes a ref to an SCC member as one token, pass 2 as the member's position ── +enum Hs.Pass: + case Hs.First + case Hs.Second + +enum Hs.Cx: + case Hs.Cx(hm: Coll.SMap[Hs.Dg], mem: Coll.List[Sym.Sym], pass: Hs.Pass) + +// a name: a local (its position, only where a local can stand), a member of this SCC, or a ref (a hash, else its text) +enum Hs.Where: + case Hs.Local + case Hs.Global + +def Hs.name {r: Region} (cx: Hs.Cx, env: Coll.List[Sym.Sym], g: Hs.Dg, x: Sym.Sym, w: Hs.Where): Hs.Dg = + val Hs.Cx(hm, mem, pass) = cx + val pos: Coll.Option[I64] = w match + case Hs.Local => Hs.index(env, x, 0) + case Hs.Global => Coll.None + pos match + case Coll.Some(i) => Hs.add(Hs.add(g, 3), i) + case Coll.None => Hs.index(mem, x, 0) match + case Coll.Some(i) => pass match + case Hs.First => Hs.add(g, 5) + case Hs.Second => Hs.add(Hs.add(g, 6), i) + case Coll.None => Coll.sLookup(hm, x) match + case Coll.Some(h) => Hs.dg(Hs.add(g, 4), h) + case Coll.None => Hs.str(Hs.add(g, 2), Sym.str(x)) + +def Hs.index {r: Region} (xs: Coll.List[Sym.Sym], x: Sym.Sym, i: I64): Coll.Option[I64] = xs match + case Coll.Nil => Coll.None + case Coll.Cons(y, rest) => if Sym.eq(x, y) then Coll.Some(i) else Hs.index(rest, x, i + 1) + +// a hash and the locals after it (binders pass their names on) +enum Hs.W: + case Hs.W(g: Hs.Dg, env: Coll.List[Sym.Sym]) + +def Hs.ty {r: Region} (cx: Hs.Cx, env: Coll.List[Sym.Sym], g: Hs.Dg, t: Ast.Ty): Hs.Dg = + val Ast.Ty(_, n, args, _, vals) = t + Hs.exprs(cx, env, Hs.tys(cx, env, Hs.name(cx, env, Hs.add(Hs.add(g, 9), Coll.length(args)), n, Hs.Local), args), vals) + +def Hs.tys {r: Region} (cx: Hs.Cx, env: Coll.List[Sym.Sym], g: Hs.Dg, ts: Coll.List[Ast.Ty]): Hs.Dg = ts match + case Coll.Nil => g + case Coll.Cons(t, rest) => Hs.tys(cx, env, Hs.ty(cx, env, g, t), rest) + +def Hs.binOp(op: Ast.BinOp): I64 = op match + case Ast.Add => 0 + case Ast.Sub => 1 + case Ast.Mul => 2 + case Ast.Div => 3 + case Ast.Mod => 4 + case Ast.Lt => 5 + case Ast.Le => 6 + case Ast.Gt => 7 + case Ast.Ge => 8 + case Ast.Eq => 9 + case Ast.Ne => 10 + case Ast.And => 11 + case Ast.Or => 12 + +def Hs.expr {r: Region} (cx: Hs.Cx, env: Coll.List[Sym.Sym], g: Hs.Dg, e: Ast.Expr): Hs.Dg = e match + case Ast.Int(_, v) => Hs.add(Hs.add(g, 32), v) + case Ast.Bool(_, v) => Hs.add(Hs.add(g, 33), if v then 1 else 0) + case Ast.Str(_, s) => Hs.str(Hs.add(g, 34), s) + case Ast.Unit(_) => Hs.add(g, 35) + case Ast.Name(_, x) => Hs.name(cx, env, Hs.add(g, 36), x, Hs.Local) + case Ast.Call(_, f, targs, chosen, xs) => + val g1 = Hs.name(cx, env, Hs.add(Hs.add(Hs.add(g, 37), Coll.length(xs)), Coll.length(targs)), f, Hs.Global) + Hs.exprs(cx, env, Hs.names(cx, env, Hs.tys(cx, env, g1, targs), chosen), xs) + case Ast.Method(_, recv, op, xs) => Hs.exprs(cx, env, Hs.str(Hs.name(cx, env, Hs.add(Hs.add(g, 42), Coll.length(xs)), recv, Hs.Local), Sym.str(op)), xs) + case Ast.Bin(_, op, l, x) => Hs.expr(cx, env, Hs.expr(cx, env, Hs.add(Hs.add(g, 43), Hs.binOp(op)), l), x) + case Ast.Un(_, op, x) => + val k = op match + case Ast.Neg => 0 + case Ast.Not => 1 + Hs.expr(cx, env, Hs.add(Hs.add(g, 44), k), x) + case Ast.If(_, c, t, x) => Hs.expr(cx, env, Hs.expr(cx, env, Hs.expr(cx, env, Hs.add(g, 45), c), t), x) + case Ast.Match(_, s, arms) => Hs.arms(cx, env, Hs.expr(cx, env, Hs.add(Hs.add(g, 46), Coll.length(arms)), s), arms) + case Ast.Block(_, ss, last) => + val Hs.W(g1, env1) = Hs.stmts(cx, Hs.W(Hs.add(Hs.add(g, 50), Coll.length(ss)), env), ss) + Hs.expr(cx, env1, g1, last) + case Ast.While(_, c, b) => Hs.expr(cx, env, Hs.expr(cx, env, Hs.add(g, 51), c), b) + case Ast.Assign(_, x, v) => Hs.expr(cx, env, Hs.name(cx, env, Hs.add(g, 52), x, Hs.Local), v) + case Ast.Quant(_, q, x, t, b) => + val k = q match + case Ast.Forall => 47 + case Ast.Exists => 48 + Hs.expr(cx, Coll.Cons(x, env), Hs.ty(cx, env, Hs.add(g, k), t), b) + +def Hs.exprs {r: Region} (cx: Hs.Cx, env: Coll.List[Sym.Sym], g: Hs.Dg, xs: Coll.List[Ast.Expr]): Hs.Dg = xs match + case Coll.Nil => g + case Coll.Cons(x, rest) => Hs.exprs(cx, env, Hs.expr(cx, env, g, x), rest) + +def Hs.names {r: Region} (cx: Hs.Cx, env: Coll.List[Sym.Sym], g: Hs.Dg, xs: Coll.List[Sym.Sym]): Hs.Dg = xs match + case Coll.Nil => g + case Coll.Cons(x, rest) => Hs.names(cx, env, Hs.name(cx, env, g, x, Hs.Local), rest) + +// an arm: its case (a ref), its binders bound in its body (each one, `_` too: positions stay fixed) +def Hs.arms {r: Region} (cx: Hs.Cx, env: Coll.List[Sym.Sym], g: Hs.Dg, as: Coll.List[Ast.Arm]): Hs.Dg = as match + case Coll.Nil => g + case Coll.Cons(a, rest) => + val Ast.Arm(_, p, b) = a + val g2 = p match + case Ast.PAny => Hs.expr(cx, env, Hs.add(g, 49), b) + case Ast.PCase(c, binds) => Hs.expr(cx, Coll.revOnto(binds, env), Hs.add(Hs.name(cx, env, Hs.add(g, 49), c, Hs.Global), Coll.length(binds)), b) + Hs.arms(cx, env, g2, rest) + +def Hs.stmts {r: Region} (cx: Hs.Cx, w: Hs.W, ss: Coll.List[Ast.Stmt]): Hs.W = ss match + case Coll.Nil => w + case Coll.Cons(s, rest) => + val Hs.W(g, env) = w + val w2 = s match + case Ast.Val(_, x, ann, e) => Hs.W(Hs.expr(cx, env, Hs.ann(cx, env, Hs.add(g, 53), ann), e), Coll.Cons(x, env)) + case Ast.Var(_, x, ann, e) => Hs.W(Hs.expr(cx, env, Hs.ann(cx, env, Hs.add(g, 57), ann), e), Coll.Cons(x, env)) + case Ast.Handle(_, x, h, xs) => Hs.W(Hs.exprs(cx, env, Hs.name(cx, env, Hs.add(g, 54), h, Hs.Global), xs), Coll.Cons(x, env)) + case Ast.Do(e) => Hs.W(Hs.expr(cx, env, Hs.add(g, 55), e), env) + case Ast.Check(_, k, e) => + val c = k match + case Ast.LInvariant => 0 + case Ast.LDecreases => 1 + Hs.W(Hs.expr(cx, env, Hs.add(Hs.add(g, 56), c), e), env) + Hs.stmts(cx, w2, rest) + +def Hs.ann {r: Region} (cx: Hs.Cx, env: Coll.List[Sym.Sym], g: Hs.Dg, a: Coll.Option[Ast.Ty]): Hs.Dg = a match + case Coll.None => Hs.add(g, 0) + case Coll.Some(t) => Hs.ty(cx, env, Hs.add(g, 1), t) + +// binders in order: each type sees the ones before, then its name is the next position +def Hs.binders {r: Region} (cx: Hs.Cx, w: Hs.W, bs: Coll.List[Ast.Binder]): Hs.W = bs match + case Coll.Nil => w + case Coll.Cons(b, rest) => + val Hs.W(g, env) = w + val Ast.Binder(_, x, t) = b + Hs.binders(cx, Hs.W(Hs.ty(cx, env, Hs.add(g, 28), t), Coll.Cons(x, env)), rest) + +def Hs.groups {r: Region} (cx: Hs.Cx, w: Hs.W, gs: Coll.List[Ast.Group]): Hs.W = gs match + case Coll.Nil => w + case Coll.Cons(gr, rest) => + val Hs.W(g, env) = w + val w2 = gr match + case Ast.Types(bs) => Hs.binders(cx, Hs.W(Hs.add(g, 26), env), bs) + case Ast.Evidence(bs) => Hs.binders(cx, Hs.W(Hs.add(g, 27), env), bs) + case Ast.Facts(as) => Hs.W(Hs.atoms(cx, env, Hs.add(g, 29), as), env) + Hs.groups(cx, w2, rest) + +def Hs.atoms {r: Region} (cx: Hs.Cx, env: Coll.List[Sym.Sym], g: Hs.Dg, as: Coll.List[Ast.Atom]): Hs.Dg = as match + case Coll.Nil => g + case Coll.Cons(a, rest) => + val Ast.Atom(_, rel, ts) = a + Hs.atoms(cx, env, Hs.terms(cx, env, Hs.str(Hs.add(g, Coll.length(ts)), Sym.str(rel)), ts), rest) + +def Hs.terms {r: Region} (cx: Hs.Cx, env: Coll.List[Sym.Sym], g: Hs.Dg, ts: Coll.List[Ast.Term]): Hs.Dg = ts match + case Coll.Nil => g + case Coll.Cons(t, rest) => + val g2 = t match + case Ast.TName(x) => Hs.name(cx, env, Hs.add(g, 30), x, Hs.Local) + case Ast.TNum(v) => Hs.add(Hs.add(g, 31), v) + Hs.terms(cx, env, g2, rest) + +def Hs.clauses {r: Region} (cx: Hs.Cx, env: Coll.List[Sym.Sym], g: Hs.Dg, cs: Coll.List[Ast.Clause]): Hs.Dg = cs match + case Coll.Nil => g + case Coll.Cons(c, rest) => + val g2 = c match + case Ast.CondC(_, k, e) => + val kc = k match + case Ast.Requires => 0 + case Ast.Ensures => 1 + case Ast.Returns => 2 + case Ast.Decreases => 3 + case Ast.Invariant => 4 + Hs.expr(cx, env, Hs.add(Hs.add(g, 58), kc), e) + case Ast.ProofUsing(_, xs) => Hs.names(cx, env, Hs.add(g, 59), xs) + case Ast.ProofInduction(_, x) => Hs.name(cx, env, Hs.add(g, 60), x, Hs.Local) + case Ast.ProofLean(_, s) => Hs.str(Hs.add(g, 61), s) + Hs.clauses(cx, env, g2, rest) + +// a def: its groups, params, result, exit facts, then its body and clauses (all see the params) +def Hs.fn {r: Region} (cx: Hs.Cx, f: Ast.Fn): Hs.Dg = + val Ast.Fn(_, _, gs, ps, ret, exit, body) = f + val Hs.W(g1, env1) = Hs.groups(cx, Hs.W(Hs.add(Hs.Dg(1, 2, 3, 4), 12), Coll.Nil), gs) + val Hs.W(g2, env2) = Hs.binders(cx, Hs.W(Hs.add(g1, Coll.length(ps)), env1), ps) + val g3 = Hs.atoms(cx, env2, Hs.ty(cx, env2, g2, ret), exit) + body match + case Ast.Extern => Hs.add(g3, 70) + case Ast.Def(cs, e) => Hs.clauses(cx, env2, Hs.expr(cx, env2, Hs.add(g3, 71), e), cs) + case Ast.Spec(cs, e) => Hs.clauses(cx, env2, Hs.expr(cx, env2, Hs.add(g3, 72), e), cs) + +// an enum: its groups, then each case's fields (the field and case names are metadata: positions only) +def Hs.enum_ {r: Region} (cx: Hs.Cx, e: Ast.Enum): Hs.Dg = + val Ast.Enum(_, _, gs, cases) = e + val Hs.W(g1, env1) = Hs.groups(cx, Hs.W(Hs.add(Hs.Dg(1, 2, 3, 4), 13), Coll.Nil), gs) + Hs.cases(cx, env1, Hs.add(g1, Coll.length(cases)), cases) + +def Hs.cases {r: Region} (cx: Hs.Cx, env: Coll.List[Sym.Sym], g: Hs.Dg, cs: Coll.List[Ast.Case]): Hs.Dg = cs match + case Coll.Nil => g + case Coll.Cons(c, rest) => + val Ast.Case(_, _, fs) = c + val Hs.W(g2, _) = Hs.binders(cx, Hs.W(Hs.add(Hs.add(g, 14), Coll.length(fs)), env), fs) + Hs.cases(cx, env, g2, rest) + +// ── the decls of one kind: what each refers to among them (a call names a fn, a type names an enum) ── +enum Hs.D: + case Hs.DF(f: Ast.Fn) + case Hs.DE(e: Ast.Enum) + +def Hs.dName(d: Hs.D): Sym.Sym = d match + case Hs.DF(f) => + val Ast.Fn(_, n, _, _, _, _, _) = f + n + case Hs.DE(e) => + val Ast.Enum(_, n, _, _) = e + n + +def Hs.hashD {r: Region} (cx: Hs.Cx, d: Hs.D): Hs.Dg = d match + case Hs.DF(f) => Hs.fn(cx, f) + case Hs.DE(e) => Hs.enum_(cx, e) + +// the names that d mentions (an over-approximation is fine: only the SCC split depends on it, and only names in ds count) +def Hs.refs {r: Region} (d: Hs.D, acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = d match + case Hs.DF(f) => + val Ast.Fn(_, _, _, _, _, _, body) = f + body match + case Ast.Def(_, e) => Hs.eRefs(e, acc) + case Ast.Spec(_, e) => Hs.eRefs(e, acc) + case Ast.Extern => acc + case Hs.DE(e) => + val Ast.Enum(_, _, _, cases) = e + Hs.caseRefs(cases, acc) + +def Hs.caseRefs {r: Region} (cs: Coll.List[Ast.Case], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = cs match + case Coll.Nil => acc + case Coll.Cons(c, rest) => + val Ast.Case(_, _, fs) = c + Hs.caseRefs(rest, Hs.binderRefs(fs, acc)) + +def Hs.binderRefs {r: Region} (bs: Coll.List[Ast.Binder], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = bs match + case Coll.Nil => acc + case Coll.Cons(b, rest) => + val Ast.Binder(_, _, t) = b + Hs.binderRefs(rest, Hs.tyRefs(t, acc)) + +def Hs.tyRefs {r: Region} (t: Ast.Ty, acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = + val Ast.Ty(_, n, args, _, _) = t + Hs.tysRefs(args, Coll.Cons(n, acc)) + +def Hs.tysRefs {r: Region} (ts: Coll.List[Ast.Ty], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = ts match + case Coll.Nil => acc + case Coll.Cons(t, rest) => Hs.tysRefs(rest, Hs.tyRefs(t, acc)) + +def Hs.eRefs {r: Region} (e: Ast.Expr, acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = e match + case Ast.Name(_, x) => Coll.Cons(x, acc) + case Ast.Call(_, f, _, _, xs) => Hs.esRefs(xs, Coll.Cons(f, acc)) + case Ast.Method(_, _, _, xs) => Hs.esRefs(xs, acc) + case Ast.Bin(_, _, l, x) => Hs.eRefs(x, Hs.eRefs(l, acc)) + case Ast.Un(_, _, x) => Hs.eRefs(x, acc) + case Ast.If(_, c, t, x) => Hs.eRefs(x, Hs.eRefs(t, Hs.eRefs(c, acc))) + case Ast.Match(_, s, arms) => Hs.armRefs(arms, Hs.eRefs(s, acc)) + case Ast.Block(_, ss, last) => Hs.eRefs(last, Hs.stmtRefs(ss, acc)) + case Ast.While(_, c, b) => Hs.eRefs(b, Hs.eRefs(c, acc)) + case Ast.Assign(_, _, x) => Hs.eRefs(x, acc) + case Ast.Quant(_, _, _, _, b) => Hs.eRefs(b, acc) + case _ => acc + +def Hs.esRefs {r: Region} (xs: Coll.List[Ast.Expr], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = xs match + case Coll.Nil => acc + case Coll.Cons(x, rest) => Hs.esRefs(rest, Hs.eRefs(x, acc)) + +def Hs.armRefs {r: Region} (as: Coll.List[Ast.Arm], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = as match + case Coll.Nil => acc + case Coll.Cons(a, rest) => + val Ast.Arm(_, _, b) = a + Hs.armRefs(rest, Hs.eRefs(b, acc)) + +def Hs.stmtRefs {r: Region} (ss: Coll.List[Ast.Stmt], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = ss match + case Coll.Nil => acc + case Coll.Cons(s, rest) => + val acc2 = s match + case Ast.Val(_, _, _, e) => Hs.eRefs(e, acc) + case Ast.Var(_, _, _, e) => Hs.eRefs(e, acc) + case Ast.Handle(_, _, _, xs) => Hs.esRefs(xs, acc) + case Ast.Do(e) => Hs.eRefs(e, acc) + case Ast.Check(_, _, e) => Hs.eRefs(e, acc) + Hs.stmtRefs(rest, acc2) + +// ── Tarjan's SCCs over the decls of one kind, callees first ── +enum Hs.T: + case Hs.T(next: I64, idx: Coll.SMap[I64], low: Coll.SMap[I64], stack: Coll.List[Sym.Sym], on: Coll.SMap[Bool], comps: Coll.List[Coll.List[Sym.Sym]]) + +// the edges of each decl: only names of decls in the map count +def Hs.edges {r: Region} (dm: Coll.SMap[Hs.D], x: Sym.Sym): Coll.List[Sym.Sym] = Coll.sLookup(dm, x) match + case Coll.None => Coll.Nil + case Coll.Some(d) => Hs.inMap(dm, Hs.refs(d, Coll.Nil), Coll.Nil) + +def Hs.inMap {r: Region} (dm: Coll.SMap[Hs.D], xs: Coll.List[Sym.Sym], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = xs match + case Coll.Nil => acc + case Coll.Cons(x, rest) => Coll.sLookup(dm, x) match + case Coll.Some(_) => Hs.inMap(dm, rest, Coll.Cons(x, acc)) + case Coll.None => Hs.inMap(dm, rest, acc) + +def Hs.geti {r: Region} (m: Coll.SMap[I64], x: Sym.Sym): I64 = Coll.sLookup(m, x) match + case Coll.Some(i) => i + case Coll.None => 0 - 1 + +def Hs.min(a: I64, b: I64): I64 = if a < b then a else b + +def Hs.visit {r: Region} (dm: Coll.SMap[Hs.D], v: Sym.Sym, t: Hs.T): Hs.T = + val Hs.T(n, idx, low, st, on, cs) = t + val t1 = Hs.T(n + 1, Coll.sInsert(idx, v, n), Coll.sInsert(low, v, n), Coll.Cons(v, st), Coll.sInsert(on, v, true), cs) + val t2 = Hs.succs(dm, v, Hs.edges(dm, v), t1) + val Hs.T(n2, idx2, low2, st2, on2, cs2) = t2 + if Hs.geti(low2, v) == Hs.geti(idx2, v) then + val Hs.Pop(comp, rest, on3) = Hs.pop(v, st2, on2, Coll.Nil) + Hs.T(n2, idx2, low2, rest, on3, Coll.Cons(comp, cs2)) + else t2 + +def Hs.succs {r: Region} (dm: Coll.SMap[Hs.D], v: Sym.Sym, ws: Coll.List[Sym.Sym], t: Hs.T): Hs.T = ws match + case Coll.Nil => t + case Coll.Cons(w, rest) => + val Hs.T(_, idx, _, _, on, _) = t + if Hs.geti(idx, w) < 0 then + val t2 = Hs.visit(dm, w, t) + val Hs.T(n2, idx2, low2, st2, on2, cs2) = t2 + Hs.succs(dm, v, rest, Hs.T(n2, idx2, Coll.sInsert(low2, v, Hs.min(Hs.geti(low2, v), Hs.geti(low2, w))), st2, on2, cs2)) + else if Hs.onStack(on, w) then + val Hs.T(n2, idx2, low2, st2, on2, cs2) = t + Hs.succs(dm, v, rest, Hs.T(n2, idx2, Coll.sInsert(low2, v, Hs.min(Hs.geti(low2, v), Hs.geti(idx2, w))), st2, on2, cs2)) + else Hs.succs(dm, v, rest, t) + +enum Hs.Pop: + case Hs.Pop(comp: Coll.List[Sym.Sym], rest: Coll.List[Sym.Sym], on: Coll.SMap[Bool]) + +// the stack down to v: one component (on-stack marks removed: set to false) +def Hs.pop {r: Region} (v: Sym.Sym, st: Coll.List[Sym.Sym], on: Coll.SMap[Bool], acc: Coll.List[Sym.Sym]): Hs.Pop = st match + case Coll.Nil => Hs.Pop(acc, Coll.Nil, on) + case Coll.Cons(x, rest) => + val on2 = Coll.sInsert(on, x, false) + if Sym.eq(x, v) then Hs.Pop(Coll.Cons(x, acc), rest, on2) else Hs.pop(v, rest, on2, Coll.Cons(x, acc)) + +// the components, callees first (Tarjan emits each after the ones it reaches) +def Hs.comps {r: Region} (dm: Coll.SMap[Hs.D], order: Coll.List[Sym.Sym], t: Hs.T): Coll.List[Coll.List[Sym.Sym]] = order match + case Coll.Nil => + val Hs.T(_, _, _, _, _, cs) = t + Coll.rev(cs) + case Coll.Cons(x, rest) => + val Hs.T(_, idx, _, _, _, _) = t + Hs.comps(dm, rest, if Hs.geti(idx, x) < 0 then Hs.visit(dm, x, t) else t) + +// ── one component: a decl alone hashes alone; a cycle hashes as one, each member = (component, position) ── +def Hs.comp {r: Region} (dm: Coll.SMap[Hs.D], hm: Coll.SMap[Hs.Dg], ms: Coll.List[Sym.Sym]): Coll.SMap[Hs.Dg] = ms match + case Coll.Nil => hm + case Coll.Cons(m, more) => + val selfRef = Ty.memberSym(m, Hs.edges(dm, m)) + if Coll.length(more) == 0 && !selfRef then Hs.put(dm, hm, m, Hs.hashOf(dm, Hs.Cx(hm, Coll.Nil, Hs.Second), m)) + else + val order = Hs.sorted(dm, hm, ms, ms, Coll.Nil) + val whole = Hs.whole(dm, Hs.Cx(hm, order, Hs.Second), order, Hs.Dg(9, 9, 9, 9)) + Hs.members(dm, hm, whole, order, 0) + +def Hs.hashOf {r: Region} (dm: Coll.SMap[Hs.D], cx: Hs.Cx, m: Sym.Sym): Hs.Dg = Coll.sLookup(dm, m) match + case Coll.Some(d) => Hs.hashD(cx, d) + case Coll.None => Hs.Dg(0, 0, 0, 0) + +// members by their first-pass hash (insertion sort: equal hashes keep component order) +enum Hs.M: + case Hs.M(name: Sym.Sym, g: Hs.Dg) + +def Hs.sorted {r: Region} (dm: Coll.SMap[Hs.D], hm: Coll.SMap[Hs.Dg], all: Coll.List[Sym.Sym], ms: Coll.List[Sym.Sym], acc: Coll.List[Hs.M]): Coll.List[Sym.Sym] = ms match + case Coll.Nil => Hs.mNames(acc, Coll.Nil) + case Coll.Cons(m, rest) => Hs.sorted(dm, hm, all, rest, Hs.ins(acc, Hs.M(m, Hs.hashOf(dm, Hs.Cx(hm, all, Hs.First), m)))) + +def Hs.ins {r: Region} (xs: Coll.List[Hs.M], m: Hs.M): Coll.List[Hs.M] = xs match + case Coll.Nil => Coll.Cons(m, Coll.Nil) + case Coll.Cons(x, rest) => + val Hs.M(_, g) = m + val Hs.M(_, h) = x + if Hs.less(g, h) then Coll.Cons(m, xs) else Coll.Cons(x, Hs.ins(rest, m)) + +def Hs.mNames {r: Region} (xs: Coll.List[Hs.M], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = xs match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(x, rest) => + val Hs.M(n, _) = x + Hs.mNames(rest, Coll.Cons(n, acc)) + +def Hs.whole {r: Region} (dm: Coll.SMap[Hs.D], cx: Hs.Cx, ms: Coll.List[Sym.Sym], g: Hs.Dg): Hs.Dg = ms match + case Coll.Nil => g + case Coll.Cons(m, rest) => Hs.whole(dm, cx, rest, Hs.dg(g, Hs.hashOf(dm, cx, m))) + +def Hs.members {r: Region} (dm: Coll.SMap[Hs.D], hm: Coll.SMap[Hs.Dg], whole: Hs.Dg, ms: Coll.List[Sym.Sym], i: I64): Coll.SMap[Hs.Dg] = ms match + case Coll.Nil => hm + case Coll.Cons(m, rest) => Hs.members(dm, Hs.put(dm, hm, m, Hs.add(Hs.add(whole, 10), i)), whole, rest, i + 1) + +// an enum's cases are refs too: (enum hash, tag) +def Hs.put {r: Region} (dm: Coll.SMap[Hs.D], hm: Coll.SMap[Hs.Dg], m: Sym.Sym, g: Hs.Dg): Coll.SMap[Hs.Dg] = + val hm2 = Coll.sInsert(hm, m, g) + Coll.sLookup(dm, m) match + case Coll.Some(d) => d match + case Hs.DE(e) => + val Ast.Enum(_, _, _, cases) = e + Hs.casesPut(hm2, g, cases, 0) + case Hs.DF(_) => hm2 + case Coll.None => hm2 + +def Hs.casesPut {r: Region} (hm: Coll.SMap[Hs.Dg], g: Hs.Dg, cs: Coll.List[Ast.Case], i: I64): Coll.SMap[Hs.Dg] = cs match + case Coll.Nil => hm + case Coll.Cons(c, rest) => + val Ast.Case(_, n, _) = c + Hs.casesPut(Coll.sInsert(hm, n, Hs.add(Hs.add(g, 8), i)), g, rest, i + 1) + +def Hs.compsPut {r: Region} (dm: Coll.SMap[Hs.D], hm: Coll.SMap[Hs.Dg], cs: Coll.List[Coll.List[Sym.Sym]]): Coll.SMap[Hs.Dg] = cs match + case Coll.Nil => hm + case Coll.Cons(c, rest) => Hs.compsPut(dm, Hs.comp(dm, hm, c), rest) + +// ── every def (not extern) and enum: enums first, then fns; the hashes by name ── +enum Hs.Split: + case Hs.Split(es: Coll.SMap[Hs.D], eo: Coll.List[Sym.Sym], fs: Coll.SMap[Hs.D], fo: Coll.List[Sym.Sym]) + +def Hs.split {r: Region} (ds: Coll.List[Ast.Decl], sp: Hs.Split): Hs.Split = ds match + case Coll.Nil => + val Hs.Split(es, eo, fs, fo) = sp + Hs.Split(es, Coll.rev(eo), fs, Coll.rev(fo)) + case Coll.Cons(d, rest) => + val Hs.Split(es, eo, fs, fo) = sp + d match + case Ast.DEnum(e) => + val Ast.Enum(_, n, _, _) = e + Hs.split(rest, Hs.Split(Coll.sInsert(es, n, Hs.DE(e)), Coll.Cons(n, eo), fs, fo)) + case Ast.DFn(f) => + val Ast.Fn(_, n, _, _, _, _, body) = f + val isExt: Bool = body match + case Ast.Extern => true + case _ => false + if isExt then Hs.split(rest, sp) else Hs.split(rest, Hs.Split(es, eo, Coll.sInsert(fs, n, Hs.DF(f)), Coll.Cons(n, fo))) + case _ => Hs.split(rest, sp) + +def Hs.all {r: Region} (ds: Coll.List[Ast.Decl]): Coll.SMap[Hs.Dg] = + val Hs.Split(es, eo, fs, fo) = Hs.split(ds, Hs.Split(Coll.sEmpty(), Coll.Nil, Coll.sEmpty(), Coll.Nil)) + val t0 = Hs.T(0, Coll.sEmpty(), Coll.sEmpty(), Coll.Nil, Coll.sEmpty(), Coll.Nil) + val hm1 = Hs.compsPut(es, Coll.sEmpty(), Hs.comps(es, eo, t0)) + Hs.compsPut(fs, hm1, Hs.comps(fs, fo, t0)) + +// `s2c --hash`: "name a.b.c.d" for every def (not extern) and enum, in program order +def Hs.print {r: Region} (ds: Coll.List[Ast.Decl]): Unit = Hs.printFrom(Hs.all(ds), ds) + +def Hs.printFrom {r: Region} (hm: Coll.SMap[Hs.Dg], ds: Coll.List[Ast.Decl]): Unit = ds match + case Coll.Nil => () + case Coll.Cons(d, rest) => + val n: Coll.Option[Sym.Sym] = d match + case Ast.DEnum(e) => + val Ast.Enum(_, en, _, _) = e + Coll.Some(en) + case Ast.DFn(f) => + val Ast.Fn(_, fn, _, _, _, _, _) = f + Coll.Some(fn) + case _ => Coll.None + n match + case Coll.Some(x) => Coll.sLookup(hm, x) match + case Coll.Some(g) => Hs.show(x, g) + case Coll.None => () + case Coll.None => () + Hs.printFrom(hm, rest) + +def Hs.show(n: Sym.Sym, g: Hs.Dg): Unit = + val Hs.Dg(a, b, c, d) = g + rt_print(Sym.str(n)) + rt_print(" ") + rt_print_i64(a) + rt_print(".") + rt_print_i64(b) + rt_print(".") + rt_print_i64(c) + rt_print(".") + rt_print_i64(d) + rt_print("\n") + +// on the stack now (a popped node is kept as false) +def Hs.onStack {r: Region} (on: Coll.SMap[Bool], w: Sym.Sym): Bool = Coll.sLookup(on, w) match + case Coll.Some(b) => b + case Coll.None => false diff --git a/bench/corpus/s2/kanren.srs b/bench/corpus/s2/kanren.srs new file mode 100644 index 00000000..be42b8c7 --- /dev/null +++ b/bench/corpus/s2/kanren.srs @@ -0,0 +1,66 @@ +// s2 component 3: Kanren core (vic 2026-11-06): terms, a substitution as a persistent map from variable to term +// (Coll.IMap: one O(log n) lookup per link of a walk; the s1 lib walks an association list), unify with the occurs +// check. a functor is a Sym: equal functors compare as integers. +enum K.Term: + case K.Var(n: I64) + case K.Con(f: Sym.Sym, args: Coll.List[K.Term]) + case K.Int(v: I64) + +// the term t stands for in s: a variable follows its bindings (a triangular substitution) +def K.walk {r: Region} (s: Coll.IMap[K.Term], t: K.Term): K.Term = t match + case K.Var(n) => Coll.node(s, n) match + case Coll.Tip => t + case Coll.Bin(_, _, u, _, _) => K.walk(s, u) + case K.Con(_, _) => t + case K.Int(_) => t + +// variable n occurs in t under s: binding n to t would build an infinite term +def K.occurs {r: Region} (s: Coll.IMap[K.Term], n: I64, t: K.Term): Bool = K.walk(s, t) match + case K.Var(m) => m == n + case K.Con(_, args) => K.occursIn(s, n, args) + case K.Int(_) => false + +def K.occursIn {r: Region} (s: Coll.IMap[K.Term], n: I64, ts: Coll.List[K.Term]): Bool = ts match + case Coll.Nil => false + case Coll.Cons(h, t) => if K.occurs(s, n, h) then true else K.occursIn(s, n, t) + +// s extended so a and b are equal, or None +def K.unify {r: Region} (s: Coll.IMap[K.Term], a: K.Term, b: K.Term): Coll.Option[Coll.IMap[K.Term]] = + val x = K.walk(s, a) + val y = K.walk(s, b) + x match + case K.Var(n) => K.bind(s, n, y) + case K.Con(f, xs) => y match + case K.Var(m) => K.bind(s, m, x) + case K.Con(g, ys) => if Sym.eq(f, g) then K.unifyAll(s, xs, ys) else Coll.None + case K.Int(_) => Coll.None + case K.Int(v) => y match + case K.Var(m) => K.bind(s, m, x) + case K.Int(w) => if v == w then Coll.Some(s) else Coll.None + case K.Con(_, _) => Coll.None + +def K.bind {r: Region} (s: Coll.IMap[K.Term], n: I64, t: K.Term): Coll.Option[Coll.IMap[K.Term]] = t match + case K.Var(m) => if m == n then Coll.Some(s) else Coll.Some(Coll.insert(s, n, t)) + case K.Con(_, _) => if K.occurs(s, n, t) then Coll.None else Coll.Some(Coll.insert(s, n, t)) + case K.Int(_) => Coll.Some(Coll.insert(s, n, t)) + +// pairwise; lists of other lengths do not unify (arity) +def K.unifyAll {r: Region} (s: Coll.IMap[K.Term], xs: Coll.List[K.Term], ys: Coll.List[K.Term]): Coll.Option[Coll.IMap[K.Term]] = xs match + case Coll.Nil => ys match + case Coll.Nil => Coll.Some(s) + case Coll.Cons(_, _) => Coll.None + case Coll.Cons(x, xt) => ys match + case Coll.Nil => Coll.None + case Coll.Cons(y, yt) => K.unify(s, x, y) match + case Coll.None => Coll.None + case Coll.Some(s2) => K.unifyAll(s2, xt, yt) + +// t with every bound variable replaced, all the way down (an answer) +def K.reify {r: Region} (s: Coll.IMap[K.Term], t: K.Term): K.Term = K.walk(s, t) match + case K.Var(n) => K.Var(n) + case K.Int(v) => K.Int(v) + case K.Con(f, args) => K.Con(f, Coll.rev(K.reifyOnto(s, args, Coll.Nil))) + +def K.reifyOnto {r: Region} (s: Coll.IMap[K.Term], ts: Coll.List[K.Term], acc: Coll.List[K.Term]): Coll.List[K.Term] = ts match + case Coll.Nil => acc + case Coll.Cons(h, t) => K.reifyOnto(s, t, Coll.Cons(K.reify(s, h), acc)) diff --git a/bench/corpus/s2/kfd.srs b/bench/corpus/s2/kfd.srs new file mode 100644 index 00000000..1335059a --- /dev/null +++ b/bench/corpus/s2/kfd.srs @@ -0,0 +1,332 @@ +// s2 component 5: disequality and finite domains (CLP(FD), Alvis et al. 2011), the semantics of lib/kanren.srs K3 K4: +// a branch settles its constraints in rounds until nothing changes. domains live in a Coll.IMap by variable (the s1 +// lib: a list); a disequality is its pair, violated when unify would add no binding (an O(1) map size check). +enum K.Neq: + case K.Neq(a: K.Term, b: K.Term) + +// a domain: ascending, never empty (h = its smallest value, hi its largest, n how many); size and bounds in O(1) +enum K.Dom: + case K.Dom(n: I64, hi: I64, h: I64, t: Coll.List[I64]) + +enum K.Bin: + case K.Le + case K.Lt + case K.Ne + +// propagators, run again in every round (bounds propagation) +enum K.Fd: + case K.FBin(op: K.Bin, x: K.Term, y: K.Term) + case K.FPlus(x: K.Term, y: K.Term, z: K.Term) + +enum K.DomOf: + case K.NoDom + case K.Has(d: K.Dom) + case K.NotInt + +def K.member(v: I64, xs: Coll.List[I64]): Bool = xs match + case Coll.Nil => false + case Coll.Cons(h, t) => if h == v then true else K.member(v, t) + +def K.ints {r: Region} (d: K.Dom): Coll.List[I64] = + val K.Dom(_, _, h, t) = d + Coll.Cons(h, t) + +def K.lo(d: K.Dom): I64 = + val K.Dom(_, _, h, _) = d + h + +def K.lastOf(h: I64, t: Coll.List[I64]): I64 = t match + case Coll.Nil => h + case Coll.Cons(h2, t2) => K.lastOf(h2, t2) + +def K.hi(d: K.Dom): I64 = + val K.Dom(_, x, _, _) = d + x + +def K.domSize(d: K.Dom): I64 = + val K.Dom(n, _, _, _) = d + n + +// v is a value of d (no allocation) +def K.inDom(v: I64, d: K.Dom): Bool = + val K.Dom(_, x, h, t) = d + v >= h && v <= x && (v == h || K.member(v, t)) + +// a..b ascending +def K.range {r: Region} (a: I64, b: I64): Coll.List[I64] = K.rangeOnto(a, b, Coll.Nil) +def K.rangeOnto {r: Region} (a: I64, b: I64, acc: Coll.List[I64]): Coll.List[I64] = if a > b then acc else K.rangeOnto(a, b - 1, Coll.Cons(b, acc)) + +// the values of xs in a..b; xs without v; xs in d (each in order) +def K.between {r: Region} (xs: Coll.List[I64], a: I64, b: I64): Coll.List[I64] = Coll.rev(K.betweenOnto(xs, a, b, Coll.Nil)) +def K.betweenOnto {r: Region} (xs: Coll.List[I64], a: I64, b: I64, acc: Coll.List[I64]): Coll.List[I64] = xs match + case Coll.Nil => acc + case Coll.Cons(h, t) => K.betweenOnto(t, a, b, if h >= a && h <= b then Coll.Cons(h, acc) else acc) +def K.withoutOnto {r: Region} (xs: Coll.List[I64], v: I64, acc: Coll.List[I64]): Coll.List[I64] = xs match + case Coll.Nil => acc + case Coll.Cons(h, t) => K.withoutOnto(t, v, if h == v then acc else Coll.Cons(h, acc)) +def K.meetInts {r: Region} (xs: Coll.List[I64], d: K.Dom): Coll.List[I64] = Coll.rev(K.meetOnto(xs, d, Coll.Nil)) +def K.meetOnto {r: Region} (xs: Coll.List[I64], d: K.Dom, acc: Coll.List[I64]): Coll.List[I64] = xs match + case Coll.Nil => acc + case Coll.Cons(h, t) => K.meetOnto(t, d, if K.inDom(h, d) then Coll.Cons(h, acc) else acc) + +// the domain of t: an integer has itself, a variable its entry (or none), a constructor is not an integer +def K.domOf {r: Region} (st: K.State, t: K.Term): K.DomOf = + val K.State(s, _, ds, _, _) = st + K.walk(s, t) match + case K.Var(n) => Coll.node(ds, n) match + case Coll.Tip => K.NoDom + case Coll.Bin(_, _, d, _, _) => K.Has(d) + case K.Int(v) => K.Has(K.Dom(1, v, v, Coll.Nil)) + case K.Con(_, _) => K.NotInt + +// t takes a value of xs (ascending; a subset of its domain, if it has one): None when none is left, bound (a fix event) +// when one is left, else narrowed (an event) unless as many values are left as before +def K.setDom {r: Region} (st: K.State, t: K.Term, xs: Coll.List[I64]): Coll.Option[K.State] = + val K.State(s, ns, ds, ps, nx) = st + xs match + case Coll.Nil => Coll.None + case Coll.Cons(h, rest) => K.walk(s, t) match + case K.Int(v) => if K.member(v, xs) then Coll.Some(st) else Coll.None + case K.Con(_, _) => Coll.None + case K.Var(n) => rest match + case Coll.Nil => K.unify(s, K.Var(n), K.Int(h)) match + case Coll.None => Coll.None + case Coll.Some(s2) => Coll.Some(K.State(s2, ns, ds, K.emit(ps, n, K.Fixed), nx)) + case Coll.Cons(_, _) => + val k = 1 + Coll.length(rest) + if K.hasSize(ds, n, k) then Coll.Some(st) + else Coll.Some(K.State(s, ns, Coll.insert(ds, n, K.Dom(k, K.lastOf(h, rest), h, rest)), K.emit(ps, n, K.Narrowed), nx)) + +// n has a domain of size k (no allocation); false when n has no domain +def K.hasSize(ds: Coll.IMap[K.Dom], n: I64, k: I64): Bool = ds match + case Coll.Tip => false + case Coll.Bin(_, key, d, l, r2) => if n < key then K.hasSize(l, n, k) else if n > key then K.hasSize(r2, n, k) else K.domSize(d) == k + +// t takes a value of xs and of the domain it already has +def K.meet {r: Region} (st: K.State, t: K.Term, xs: Coll.List[I64]): Coll.Option[K.State] = K.domOf(st, t) match + case K.NoDom => K.setDom(st, t, xs) + case K.Has(d) => K.setDom(st, t, K.meetInts(xs, d)) + case K.NotInt => Coll.None + +// ── propagators ── +// x <= y - k: k = 0 for <=, 1 for < +def K.leAt {r: Region} (st: K.State, x: K.Term, y: K.Term, dx: K.Dom, dy: K.Dom, k: I64): Coll.Option[K.State] = + // a bound that already holds builds no new domain + val sx: Coll.Option[K.State] = if K.hi(dx) <= K.hi(dy) - k then Coll.Some(st) else K.setDom(st, x, K.between(K.ints(dx), K.lo(dx), K.hi(dy) - k)) + sx match + case Coll.None => Coll.None + case Coll.Some(st2) => if K.lo(dy) >= K.lo(dx) + k then Coll.Some(st2) else K.setDom(st2, y, K.between(K.ints(dy), K.lo(dx) + k, K.hi(dy))) + +def K.neAt {r: Region} (st: K.State, x: K.Term, y: K.Term, dx: K.Dom, dy: K.Dom): Coll.Option[K.State] = + val nx = K.domSize(dx) + val ny = K.domSize(dy) + if nx == 1 && ny == 1 then (if K.lo(dx) == K.lo(dy) then Coll.None else Coll.Some(st)) + else if nx == 1 then (if K.inDom(K.lo(dx), dy) then K.setDom(st, y, Coll.rev(K.withoutOnto(K.ints(dy), K.lo(dx), Coll.Nil))) else Coll.Some(st)) + else if ny == 1 then (if K.inDom(K.lo(dy), dx) then K.setDom(st, x, Coll.rev(K.withoutOnto(K.ints(dx), K.lo(dy), Coll.Nil))) else Coll.Some(st)) + else Coll.Some(st) + +// x + y = z +def K.plusAt {r: Region} (st: K.State, x: K.Term, y: K.Term, z: K.Term, dx: K.Dom, dy: K.Dom, dz: K.Dom): Coll.Option[K.State] = + K.setDom(st, z, K.between(K.ints(dz), K.lo(dx) + K.lo(dy), K.hi(dx) + K.hi(dy))) match + case Coll.None => Coll.None + case Coll.Some(st1) => K.setDom(st1, x, K.between(K.ints(dx), K.lo(dz) - K.hi(dy), K.hi(dz) - K.lo(dy))) match + case Coll.None => Coll.None + case Coll.Some(st2) => K.setDom(st2, y, K.between(K.ints(dy), K.lo(dz) - K.hi(dx), K.hi(dz) - K.lo(dx))) + +// a propagator runs once every variable it reads has a domain +def K.fire {r: Region} (st: K.State, c: K.Fd): Coll.Option[K.State] = c match + case K.FBin(op, x, y) => K.domOf(st, x) match + case K.NoDom => Coll.Some(st) + case K.NotInt => Coll.None + case K.Has(dx) => K.domOf(st, y) match + case K.NoDom => Coll.Some(st) + case K.NotInt => Coll.None + case K.Has(dy) => op match + case K.Le => K.leAt(st, x, y, dx, dy, 0) + case K.Lt => K.leAt(st, x, y, dx, dy, 1) + case K.Ne => K.neAt(st, x, y, dx, dy) + case K.FPlus(x, y, z) => K.domOf(st, x) match + case K.NoDom => Coll.Some(st) + case K.NotInt => Coll.None + case K.Has(dx) => K.domOf(st, y) match + case K.NoDom => Coll.Some(st) + case K.NotInt => Coll.None + case K.Has(dy) => K.domOf(st, z) match + case K.NoDom => Coll.Some(st) + case K.NotInt => Coll.None + case K.Has(dz) => K.plusAt(st, x, y, z, dx, dy, dz) + + +// ── settling: an agenda of propagators (AC-3 with events, Mackworth 1977; Schulte & Stuckey 2008). setDom records an +// event per real change: a variable fixed (one value) or narrowed. a =/= propagator wakes on fix events only (it prunes +// nothing before), the others on every change. monotone narrowing reaches the same fixpoint in any fair order (Apt +// 1999), so the answers are those of full rounds (the s1 lib). +enum K.Change: + case K.Fixed + case K.Narrowed + +enum K.Ev: + case K.Ev(v: I64, change: K.Change) + +// the fd field of a state: the watch indexes (variable -> propagators) and the events not yet woken +enum K.Props: + case K.Props(fix: Coll.IMap[Coll.List[K.Fd]], any: Coll.IMap[Coll.List[K.Fd]], evs: Coll.List[K.Ev]) + +def K.emit {r: Region} (ps: K.Props, n: I64, change: K.Change): K.Props = + val K.Props(fx, an, evs) = ps + K.Props(fx, an, Coll.Cons(K.Ev(n, change), evs)) + +def K.fdTerms {r: Region} (c: K.Fd): Coll.List[K.Term] = c match + case K.FBin(_, x, y) => Coll.Cons(x, Coll.Cons(y, Coll.Nil)) + case K.FPlus(x, y, z) => Coll.Cons(x, Coll.Cons(y, Coll.Cons(z, Coll.Nil))) + +def K.watchers {r: Region} (w: Coll.IMap[Coll.List[K.Fd]], n: I64): Coll.List[K.Fd] = Coll.node(w, n) match + case Coll.Tip => Coll.Nil + case Coll.Bin(_, _, cs, _, _) => cs + +def K.watchIn {r: Region} (s: Coll.IMap[K.Term], w: Coll.IMap[Coll.List[K.Fd]], c: K.Fd, ts: Coll.List[K.Term]): Coll.IMap[Coll.List[K.Fd]] = ts match + case Coll.Nil => w + case Coll.Cons(t, rest) => K.walk(s, t) match + case K.Var(n) => K.watchIn(s, Coll.insert(w, n, Coll.Cons(c, K.watchers(w, n))), c, rest) + case _ => K.watchIn(s, w, c, rest) + +// c registered under the variables it reads (under s): =/= in the fix index, the others in the any index +def K.watch {r: Region} (s: Coll.IMap[K.Term], ps: K.Props, c: K.Fd): K.Props = + val K.Props(fx, an, evs) = ps + if K.isNe(c) then K.Props(K.watchIn(s, fx, c, K.fdTerms(c)), an, evs) else K.Props(fx, K.watchIn(s, an, c, K.fdTerms(c)), evs) + +def K.isNe(c: K.Fd): Bool = c match + case K.FBin(op, _, _) => op match + case K.Ne => true + case K.Le => false + case K.Lt => false + case K.FPlus(_, _, _) => false + +// the propagators each event wakes, onto agenda +def K.wakeAll {r: Region} (ps: K.Props, evs: Coll.List[K.Ev], agenda: Coll.List[K.Fd]): Coll.List[K.Fd] = evs match + case Coll.Nil => agenda + case Coll.Cons(e, rest) => + val K.Ev(n, change) = e + val K.Props(fx, an, _) = ps + val a1 = Coll.revOnto(K.watchers(an, n), agenda) + val a2 = change match + case K.Fixed => Coll.revOnto(K.watchers(fx, n), a1) + case K.Narrowed => a1 + K.wakeAll(ps, rest, a2) + +// fire the agenda; when it is empty, wake the events the fires left; done when both are empty +def K.prop {r: Region} (st: K.State, agenda: Coll.List[K.Fd]): Coll.Option[K.State] = agenda match + case Coll.Cons(c, rest) => K.fire(st, c) match + case Coll.None => Coll.None + case Coll.Some(st2) => K.prop(st2, rest) + case Coll.Nil => + val K.State(s, ns, ds, ps, nx) = st + val K.Props(fx, an, evs) = ps + evs match + case Coll.Nil => Coll.Some(st) + case Coll.Cons(_, _) => K.prop(K.State(s, ns, ds, K.Props(fx, an, Coll.Nil), nx), K.wakeAll(ps, evs, Coll.Nil)) + +// propagate, then check the disequality store +def K.settleFrom {r: Region} (st: K.State, agenda: Coll.List[K.Fd]): Coll.Option[K.State] = K.prop(st, agenda) match + case Coll.None => Coll.None + case Coll.Some(st2) => + val K.State(s, ns, ds, ps, nx) = st2 + K.recheck(s, ns, Coll.Nil) match + case Coll.None => Coll.None + case Coll.Some(ns2) => Coll.Some(K.State(s, ns2, ds, ps, nx)) + +// the variables of t (not walked) +def K.varsOf {r: Region} (t: K.Term, acc: Coll.List[I64]): Coll.List[I64] = t match + case K.Var(n) => Coll.Cons(n, acc) + case K.Int(_) => acc + case K.Con(_, args) => K.varsOfAll(args, acc) + +def K.varsOfAll {r: Region} (ts: Coll.List[K.Term], acc: Coll.List[I64]): Coll.List[I64] = ts match + case Coll.Nil => acc + case Coll.Cons(h, t) => K.varsOfAll(t, K.varsOf(h, acc)) + +// after unify (old substitution s0, the new one in st): a variable m that stood for itself under s0 and is bound now: +// bound to a variable k, its watchers move to k, its domain meets k's, and k's watchers wake; bound to a value, the +// value must be in its domain, and its watchers wake (a fix event) +def K.bound {r: Region} (s0: Coll.IMap[K.Term], ms: Coll.List[I64], st: K.State): Coll.Option[K.State] = ms match + case Coll.Nil => Coll.Some(st) + case Coll.Cons(v, rest) => + val K.State(s, ns, ds, ps, nx) = st + K.walk(s0, K.Var(v)) match + case K.Var(m) => K.walk(s, K.Var(m)) match + case K.Var(k) => + if k == m then K.bound(s0, rest, st) + else + val K.Props(fx, an, evs) = ps + val moved = K.Props(Coll.insert(fx, k, Coll.revOnto(K.watchers(fx, m), K.watchers(fx, k))), Coll.insert(an, k, Coll.revOnto(K.watchers(an, m), K.watchers(an, k))), Coll.Cons(K.Ev(k, K.Fixed), evs)) + val st1 = K.State(s, ns, ds, moved, nx) + val met: Coll.Option[K.State] = Coll.lookup(ds, m) match + case Coll.None => Coll.Some(st1) + case Coll.Some(d) => K.meet(st1, K.Var(k), K.ints(d)) + met match + case Coll.None => Coll.None + case Coll.Some(st2) => K.bound(s0, rest, st2) + case _ => + val st1 = K.State(s, ns, ds, K.emit(ps, m, K.Fixed), nx) + val met: Coll.Option[K.State] = Coll.lookup(ds, m) match + case Coll.None => Coll.Some(st1) + case Coll.Some(d) => K.meet(st1, K.Var(m), K.ints(d)) + met match + case Coll.None => Coll.None + case Coll.Some(st2) => K.bound(s0, rest, st2) + case _ => K.bound(s0, rest, st) + +// the state after unify of the terms ts gave u: dead on None, else the changed variables settle +def K.post {r: Region} (st: K.State, ts: Coll.List[K.Term], u: Coll.Option[Coll.IMap[K.Term]]): Coll.Option[K.State] = u match + case Coll.None => Coll.None + case Coll.Some(s2) => + val K.State(s, ns, ds, ps, nx) = st + if Coll.size(s2) == Coll.size(s) then Coll.Some(st) + else K.bound(s, K.varsOfAll(ts, Coll.Nil), K.State(s2, ns, ds, ps, nx)) match + case Coll.None => Coll.None + case Coll.Some(st2) => K.settleFrom(st2, Coll.Nil) + +// the store under s: a pair that can never unify is dropped; one that already is equal (unify adds no binding) fails +def K.recheck {r: Region} (s: Coll.IMap[K.Term], ns: Coll.List[K.Neq], kept: Coll.List[K.Neq]): Coll.Option[Coll.List[K.Neq]] = ns match + case Coll.Nil => Coll.Some(Coll.rev(kept)) + case Coll.Cons(h, t) => + val K.Neq(a, b) = h + K.unify(s, a, b) match + case Coll.None => K.recheck(s, t, kept) + case Coll.Some(s2) => if Coll.size(s2) == Coll.size(s) then Coll.None else K.recheck(s, t, Coll.Cons(h, kept)) + +def K.addNeq {r: Region} (st: K.State, a: K.Term, b: K.Term): Coll.Option[K.State] = + val K.State(s, ns, ds, fs, nx) = st + K.unify(s, a, b) match + case Coll.None => Coll.Some(st) + case Coll.Some(s2) => if Coll.size(s2) == Coll.size(s) then Coll.None else Coll.Some(K.State(s, Coll.Cons(K.Neq(a, b), ns), ds, fs, nx)) + +// ── labeling: the variable of xs with the smallest domain of 2 or more values (first-fail) ── +enum K.Pick: + case K.NoPick + case K.Pick(t: K.Term, d: K.Dom) + +def K.pickVar {r: Region} (st: K.State, xs: Coll.List[K.Term], best: K.Pick): K.Pick = xs match + case Coll.Nil => best + case Coll.Cons(h, t) => K.domOf(st, h) match + case K.Has(d) => if K.domSize(d) > 1 && K.smaller(d, best) then K.pickVar(st, t, K.Pick(h, d)) else K.pickVar(st, t, best) + case K.NoDom => K.pickVar(st, t, best) + case K.NotInt => K.pickVar(st, t, best) + +def K.smaller(d: K.Dom, best: K.Pick): Bool = best match + case K.NoPick => true + case K.Pick(_, e) => K.domSize(d) < K.domSize(e) + +// one branch per value, in order; the goals after keep the label goal, so the next variable is labeled +def K.labelBranches {r: Region} (st: K.State, t: K.Term, vs: Coll.List[I64], gs: Coll.List[K.Goal], acc: Coll.List[K.Branch]): Coll.List[K.Branch] = vs match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(v, more) => K.labelBranches(st, t, more, gs, Coll.Cons(K.Branch(st, Coll.Cons(K.Eq(t, K.Int(v)), gs)), acc)) + +// every two of xs differ +def K.distinct {r: Region} (xs: Coll.List[K.Term]): K.Goal = xs match + case Coll.Nil => K.True + case Coll.Cons(h, t) => K.Conj(K.neEach(h, t), K.distinct(t)) + +def K.neEach {r: Region} (x: K.Term, ys: Coll.List[K.Term]): K.Goal = ys match + case Coll.Nil => K.True + case Coll.Cons(y, t) => K.Conj(K.Post(K.FBin(K.Ne, x, y)), K.neEach(x, t)) diff --git a/bench/corpus/s2/ksearch.srs b/bench/corpus/s2/ksearch.srs new file mode 100644 index 00000000..1ee857a0 --- /dev/null +++ b/bench/corpus/s2/ksearch.srs @@ -0,0 +1,154 @@ +// s2 component 4: Kanren search (vic 2026-11-06 "go on K core."): goals as data, fair search over Queue (O(1) push, +// amortized O(1) pop; the s1 lib copies its queue per choice), rules indexed by relation hash, a clause head unified +// when the clause is picked (a clash never enters the queue). fuel: 1 per disj split, 1 per clause picked (vic B1). +enum K.Goal: + case K.True + case K.Eq(a: K.Term, b: K.Term) + case K.Conj(g: K.Goal, h: K.Goal) + case K.Disj(g: K.Goal, h: K.Goal) + case K.Call(rel: Sym.Sym, args: Coll.List[K.Term]) + case K.Diseq(a: K.Term, b: K.Term) + case K.In(x: K.Term, d: Coll.List[I64]) + case K.Post(c: K.Fd) + case K.Label(xs: Coll.List[K.Term]) + +// rel(head) :- body, over variables 0..nvars-1 +enum K.Rule: + case K.Rule(rel: Sym.Sym, head: Coll.List[K.Term], body: K.Goal, nvars: I64) + +// what a branch knows: substitution, disequalities, domains, propagators (s2/kfd.srs), the next fresh variable +enum K.State: + case K.State(s: Coll.IMap[K.Term], neq: Coll.List[K.Neq], dom: Coll.IMap[K.Dom], fd: K.Props, next: I64) + +enum K.Branch: + case K.Branch(st: K.State, gs: Coll.List[K.Goal]) + +enum K.Step: + case K.Done(st: K.State) + case K.Dead + case K.More(b: K.Branch) + case K.Split(bs: Coll.List[K.Branch], cost: I64) + +enum K.Status: + case K.Ended + case K.Limit + case K.NoFuel + +enum K.Run: + case K.Run(answers: Coll.List[K.State], status: K.Status) + +// relation hash -> its clauses, in written order +def K.index {r: Region} (rules: Coll.List[K.Rule]): Coll.IMap[Coll.List[K.Rule]] = K.indexOnto(Coll.rev(rules), Coll.Tip) + +def K.indexOnto {r: Region} (rs: Coll.List[K.Rule], ix: Coll.IMap[Coll.List[K.Rule]]): Coll.IMap[Coll.List[K.Rule]] = rs match + case Coll.Nil => ix + case Coll.Cons(h, t) => + val K.Rule(rel, _, _, _) = h + val k = Sym.hash(rel) + val old: Coll.List[K.Rule] = Coll.lookup(ix, k) match + case Coll.None => Coll.Nil + case Coll.Some(xs) => xs + K.indexOnto(t, Coll.insert(ix, k, Coll.Cons(h, old))) + +// rename apart: every variable moved by k +def K.shift {r: Region} (t: K.Term, k: I64): K.Term = t match + case K.Var(n) => K.Var(n + k) + case K.Int(v) => K.Int(v) + case K.Con(f, args) => K.Con(f, Coll.rev(K.shiftOnto(args, k, Coll.Nil))) + +def K.shiftOnto {r: Region} (ts: Coll.List[K.Term], k: I64, acc: Coll.List[K.Term]): Coll.List[K.Term] = ts match + case Coll.Nil => acc + case Coll.Cons(h, t) => K.shiftOnto(t, k, Coll.Cons(K.shift(h, k), acc)) + +def K.shiftGoal {r: Region} (g: K.Goal, k: I64): K.Goal = g match + case K.True => K.True + case K.Eq(a, b) => K.Eq(K.shift(a, k), K.shift(b, k)) + case K.Conj(x, y) => K.Conj(K.shiftGoal(x, k), K.shiftGoal(y, k)) + case K.Disj(x, y) => K.Disj(K.shiftGoal(x, k), K.shiftGoal(y, k)) + case K.Call(f, args) => K.Call(f, Coll.rev(K.shiftOnto(args, k, Coll.Nil))) + case K.Diseq(a, b) => K.Diseq(K.shift(a, k), K.shift(b, k)) + case K.In(x, d) => K.In(K.shift(x, k), d) + case K.Post(c) => K.Post(K.shiftFd(c, k)) + case K.Label(xs) => K.Label(Coll.rev(K.shiftOnto(xs, k, Coll.Nil))) + +def K.shiftFd {r: Region} (c: K.Fd, k: I64): K.Fd = c match + case K.FBin(op, x, y) => K.FBin(op, K.shift(x, k), K.shift(y, k)) + case K.FPlus(x, y, z) => K.FPlus(K.shift(x, k), K.shift(y, k), K.shift(z, k)) + +// K.unify(s, K.shift(h, k), y) without the copy: a head subterm is shifted only when it is bound into s, so a head +// that clashes allocates nothing. The binding direction is that of K.unify, so s is the same. +def K.unifyOff {r: Region} (s: Coll.IMap[K.Term], h: K.Term, k: I64, y: K.Term): Coll.Option[Coll.IMap[K.Term]] = h match + case K.Var(n) => K.unify(s, K.Var(n + k), y) + case K.Int(_) => K.unify(s, h, y) + case K.Con(f, hs) => K.walk(s, y) match + case K.Var(m) => K.bind(s, m, K.shift(h, k)) + case K.Con(g, ys) => if Sym.eq(f, g) then K.unifyAllOff(s, hs, k, ys) else Coll.None + case K.Int(_) => Coll.None + +def K.unifyAllOff {r: Region} (s: Coll.IMap[K.Term], hs: Coll.List[K.Term], k: I64, ys: Coll.List[K.Term]): Coll.Option[Coll.IMap[K.Term]] = hs match + case Coll.Nil => ys match + case Coll.Nil => Coll.Some(s) + case Coll.Cons(_, _) => Coll.None + case Coll.Cons(h, ht) => ys match + case Coll.Nil => Coll.None + case Coll.Cons(y, yt) => K.unifyOff(s, h, k, y) match + case Coll.None => Coll.None + case Coll.Some(s2) => K.unifyAllOff(s2, ht, k, yt) + +// the branches of the clauses of rel whose heads unify with args (in clause order), and the clauses picked +def K.picks {r: Region} (rs: Coll.List[K.Rule], rel: Sym.Sym, args: Coll.List[K.Term], st: K.State, rest: Coll.List[K.Goal], out: Coll.List[K.Branch], cost: I64): K.Step = rs match + case Coll.Nil => K.Split(Coll.rev(out), cost) + case Coll.Cons(h, t) => + val K.Rule(f, head, body, nv) = h + val K.State(s, ns, ds, fs, nx) = st + if !Sym.eq(f, rel) then K.picks(t, rel, args, st, rest, out, cost) + else K.post(st, args, K.unifyAllOff(s, head, nx, args)) match + case Coll.None => K.picks(t, rel, args, st, rest, out, cost + 1) + case Coll.Some(st2) => + val K.State(s2, ns2, ds2, fs2, _) = st2 + K.picks(t, rel, args, st, rest, Coll.Cons(K.Branch(K.State(s2, ns2, ds2, fs2, nx + nv), Coll.Cons(K.shiftGoal(body, nx), rest)), out), cost + 1) + +// after a domain on x: the events it left wake their propagators +def K.settled {r: Region} (c: Coll.Option[K.State]): Coll.Option[K.State] = c match + case Coll.None => Coll.None + case Coll.Some(st) => K.settleFrom(st, Coll.Nil) + +def K.onward {r: Region} (c: Coll.Option[K.State], rest: Coll.List[K.Goal]): K.Step = c match + case Coll.None => K.Dead + case Coll.Some(st) => K.More(K.Branch(st, rest)) + +def K.kstep {r: Region} (ix: Coll.IMap[Coll.List[K.Rule]], b: K.Branch): K.Step = + val K.Branch(st, gs) = b + val K.State(s, ns, ds, fs, nx) = st + gs match + case Coll.Nil => K.Done(st) + case Coll.Cons(g, rest) => g match + case K.True => K.More(K.Branch(st, rest)) + case K.Eq(a, c) => K.onward(K.post(st, Coll.Cons(a, Coll.Cons(c, Coll.Nil)), K.unify(s, a, c)), rest) + case K.Diseq(a, c) => K.onward(K.addNeq(st, a, c), rest) + case K.In(x, xs) => K.onward(K.settled(K.meet(st, x, xs)), rest) + case K.Post(c) => K.onward(K.settleFrom(K.State(s, ns, ds, K.watch(s, fs, c), nx), Coll.Cons(c, Coll.Nil)), rest) + case K.Label(xs) => K.pickVar(st, xs, K.NoPick) match + case K.NoPick => K.More(K.Branch(st, rest)) + case K.Pick(t, d) => K.Split(K.labelBranches(st, t, K.ints(d), gs, Coll.Nil), K.domSize(d)) + case K.Conj(x, y) => K.More(K.Branch(st, Coll.Cons(x, Coll.Cons(y, rest)))) + case K.Disj(x, y) => K.Split(Coll.Cons(K.Branch(st, Coll.Cons(x, rest)), Coll.Cons(K.Branch(st, Coll.Cons(y, rest)), Coll.Nil)), 1) + case K.Call(f, args) => Coll.node(ix, Sym.hash(f)) match + case Coll.Tip => K.Split(Coll.Nil, 0) + case Coll.Bin(_, _, rs, _, _) => K.picks(rs, f, args, st, rest, Coll.Nil, 0) + +// the driver: the current branch runs until a choice; the choice's branches go to the back of the queue (fair, so +// complete); a choice that costs more than the fuel left stops the run (vic §17) +def K.loop {r: Region} (ix: Coll.IMap[Coll.List[K.Rule]], cur: Coll.Option[K.Branch], q: Queue.Queue[K.Branch], fuel: I64, limit: I64, found: Coll.List[K.State], n: I64): K.Run = cur match + case Coll.None => Queue.pop(q) match + case Queue.Empty => K.Run(Coll.rev(found), K.Ended) + case Queue.Got(b, rest) => K.loop(ix, Coll.Some(b), rest, fuel, limit, found, n) + case Coll.Some(b) => K.kstep(ix, b) match + case K.Done(st) => if n + 1 >= limit then K.Run(Coll.rev(Coll.Cons(st, found)), K.Limit) else K.loop(ix, Coll.None, q, fuel, limit, Coll.Cons(st, found), n + 1) + case K.Dead => K.loop(ix, Coll.None, q, fuel, limit, found, n) + case K.More(b2) => K.loop(ix, Coll.Some(b2), q, fuel, limit, found, n) + case K.Split(bs, cost) => if cost > fuel then K.Run(Coll.rev(found), K.NoFuel) else K.loop(ix, Coll.None, Queue.pushAll(q, bs), fuel - cost, limit, found, n) + +// prove g (variables 0..nvars-1) over rules: at most limit answers, within fuel +def K.solve {r: Region} (rules: Coll.List[K.Rule], g: K.Goal, nvars: I64, fuel: I64, limit: I64): K.Run = + K.loop(K.index(rules), Coll.Some(K.Branch(K.State(Coll.Tip, Coll.Nil, Coll.Tip, K.Props(Coll.Tip, Coll.Tip, Coll.Nil), nvars), Coll.Cons(g, Coll.Nil))), Queue.empty(), fuel, limit, Coll.Nil, 0) diff --git a/bench/corpus/s2/lex.srs b/bench/corpus/s2/lex.srs new file mode 100644 index 00000000..07c382e5 --- /dev/null +++ b/bench/corpus/s2/lex.srs @@ -0,0 +1,129 @@ +// s2 P6 FRONT (vic-m5r.27): the lexer. tokens and layout as s1/lex.srs (TNl, TIndent, TDedent): a deeper line opens an +// indent, a shallower one closes every indent above it, a newline inside ( or [ is not a token. a module member +// Upper.name is one identifier (vic 2026-11-06). an error is data (Lex.Bad), never an exit. + +// a token and its line; an int carries its value +enum Lex.Tok: + case Lex.TIdent(s: Str, line: I64) + case Lex.TInt(v: I64, line: I64) + case Lex.TStr(s: Str, line: I64) + case Lex.TChar(s: Str, line: I64) + case Lex.TOp(s: Str, line: I64) + case Lex.TNl(line: I64) + case Lex.TIndent(line: I64) + case Lex.TDedent(line: I64) + case Lex.TEof(line: I64) + +// why a source does not lex +enum Lex.Why: + case Lex.Tab + case Lex.BadDedent + case Lex.Unterminated + case Lex.BadChar + +enum Lex.Result: + case Lex.Toks(ts: Coll.List[Lex.Tok]) + case Lex.Bad(line: I64, why: Lex.Why) + +def Lex.isAlpha(c: I64): Bool = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' +def Lex.isDigit(c: I64): Bool = c >= '0' && c <= '9' +def Lex.isPunct(c: I64): Bool = + c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' || c == ':' || c == '=' || c == '+' || c == '-' || c == '*' || c == '/' || c == '%' || c == '<' || c == '>' || c == '!' || c == '.' || c == '^' || c == '@' +def Lex.isTwo(a: I64, b: I64): Bool = + (a == '=' && b == '>') || (a == '=' && b == '=') || (a == '!' && b == '=') || (a == '<' && b == '=') || (a == '>' && b == '=') || (a == '&' && b == '&') || (a == '|' && b == '|') || (a == '~' && b == '>') + +// the last token is a layout token (no TNl after it) +def Lex.layoutLast(out: Coll.List[Lex.Tok]): Bool = out match + case Coll.Nil => true + case Coll.Cons(t, _) => t match + case Lex.TNl(_) => true + case Lex.TIndent(_) => true + case Lex.TDedent(_) => true + case _ => false + +// the end of a run of spaces from i +def Lex.spaces(src: Str, i: I64): I64 = if rt_str_at(src, i) == ' ' then Lex.spaces(src, i + 1) else i + +// the end of a run of letters and digits from i +def Lex.word(src: Str, i: I64): I64 = if Lex.isAlpha(rt_str_at(src, i)) || Lex.isDigit(rt_str_at(src, i)) then Lex.word(src, i + 1) else i + +// the end of an identifier that starts with an upper case letter: Upper(.name)* +def Lex.dotted(src: Str, i: I64): I64 = + if rt_str_at(src, i) == '.' && Lex.isAlpha(rt_str_at(src, i + 1)) then Lex.dotted(src, Lex.word(src, i + 1)) else i + +// the value of the digits from i (and where they end) +def Lex.digits(src: Str, i: I64, v: I64): I64 = if Lex.isDigit(rt_str_at(src, i)) then Lex.digits(src, i + 1, v * 10 + (rt_str_at(src, i) - '0')) else v +def Lex.digitsEnd(src: Str, i: I64): I64 = if Lex.isDigit(rt_str_at(src, i)) then Lex.digitsEnd(src, i + 1) else i + +// the closing quote q of a literal from i (a backslash skips the next character), or the line end +def Lex.litEnd(src: Str, i: I64, n: I64, q: I64): I64 = + if i >= n then i + else if rt_str_at(src, i) == q || rt_str_at(src, i) == '\n' then i + else if rt_str_at(src, i) == '\\' then Lex.litEnd(src, i + 2, n, q) + else Lex.litEnd(src, i + 1, n, q) + +// the end of a comment from i (the newline stays) +def Lex.lineEnd(src: Str, i: I64, n: I64): I64 = if i < n && rt_str_at(src, i) != '\n' then Lex.lineEnd(src, i + 1, n) else i + +def Lex.top(ind: Coll.List[I64]): I64 = ind match + case Coll.Nil => 0 + case Coll.Cons(c, _) => c + +def Lex.lex {r: Region} (src: Str): Lex.Result = Lex.lexFrom(src, 1) + +// src whose first line has number line (a file after others: its lines continue the numbering, so a line names a file) +def Lex.lexFrom {r: Region} (src: Str, line: I64): Lex.Result = Lex.go(src, rt_str_len(src), 0, line, 0, true, Coll.Cons(0, Coll.Nil), Coll.Nil) + +// the scan from i: depth = open ( and [, bol = at the start of a line, ind = the indent stack, out = tokens, newest first +def Lex.go {r: Region} (src: Str, n: I64, i: I64, line: I64, depth: I64, bol: Bool, ind: Coll.List[I64], out: Coll.List[Lex.Tok]): Lex.Result = + if i >= n then Lex.finish(line, ind, out) + else if bol && depth == 0 then + val j = Lex.spaces(src, i) + val col = j - i + val c = rt_str_at(src, j) + if c == '\t' then Lex.Bad(line, Lex.Tab) + else if c == -1 || c == '\n' || (c == '/' && rt_str_at(src, j + 1) == '/') then Lex.go(src, n, j, line, depth, false, ind, out) + else if col > Lex.top(ind) then Lex.go(src, n, j, line, depth, false, Coll.Cons(col, ind), Coll.Cons(Lex.TIndent(line), out)) + else Lex.dedent(src, n, j, line, col, ind, out) + else + val c = rt_str_at(src, i) + if c == '\n' then Lex.go(src, n, i + 1, line + 1, depth, true, ind, if depth == 0 && !Lex.layoutLast(out) then Coll.Cons(Lex.TNl(line), out) else out) + else if c == ' ' || c == '\r' then Lex.go(src, n, i + 1, line, depth, bol, ind, out) + else if c == '/' && rt_str_at(src, i + 1) == '/' then Lex.go(src, n, Lex.lineEnd(src, i, n), line, depth, bol, ind, out) + else if Lex.isAlpha(c) then + val e0 = Lex.word(src, i) + val e = if c >= 'A' && c <= 'Z' then Lex.dotted(src, e0) else e0 + Lex.go(src, n, e, line, depth, bol, ind, Coll.Cons(Lex.TIdent(rt_str_slice(src, i, e), line), out)) + else if Lex.isDigit(c) then Lex.go(src, n, Lex.digitsEnd(src, i), line, depth, bol, ind, Coll.Cons(Lex.TInt(Lex.digits(src, i, 0), line), out)) + else if c == '"' || c == '\'' then + val e = Lex.litEnd(src, i + 1, n, c) + if rt_str_at(src, e) != c then Lex.Bad(line, Lex.Unterminated) + else Lex.go(src, n, e + 1, line, depth, bol, ind, Coll.Cons(if c == '"' then Lex.TStr(rt_str_slice(src, i + 1, e), line) else Lex.TChar(rt_str_slice(src, i + 1, e), line), out)) + else + val w = if Lex.isTwo(c, rt_str_at(src, i + 1)) then 2 else 1 + if w == 1 && !Lex.isPunct(c) then Lex.Bad(line, Lex.BadChar) + else + val d = if c == '(' || c == '[' then depth + 1 else if (c == ')' || c == ']') && depth > 0 then depth - 1 else depth + Lex.go(src, n, i + w, line, d, bol, ind, Coll.Cons(Lex.TOp(rt_str_slice(src, i, i + w), line), out)) + +// a line at column col, shallower than or as deep as the indent: close every deeper indent; col must be on the stack +def Lex.dedent {r: Region} (src: Str, n: I64, j: I64, line: I64, col: I64, ind: Coll.List[I64], out: Coll.List[Lex.Tok]): Lex.Result = ind match + case Coll.Nil => Lex.Bad(line, Lex.BadDedent) + case Coll.Cons(t, rest) => + if col < t then Lex.dedent(src, n, j, line, col, rest, Coll.Cons(Lex.TDedent(line), out)) + else if col == t then Lex.go(src, n, j, line, 0, false, ind, out) + else Lex.Bad(line, Lex.BadDedent) + +// the end: a last TNl, a TDedent for each open indent, TEof +def Lex.finish {r: Region} (line: I64, ind: Coll.List[I64], out: Coll.List[Lex.Tok]): Lex.Result = + val out1: Coll.List[Lex.Tok] = out match + case Coll.Nil => out + case Coll.Cons(t, _) => t match + case Lex.TNl(_) => out + case Lex.TDedent(_) => out + case _ => Coll.Cons(Lex.TNl(line), out) + Lex.Toks(Lex.closeAll(line, ind, out1)) + +def Lex.closeAll {r: Region} (line: I64, ind: Coll.List[I64], out: Coll.List[Lex.Tok]): Coll.List[Lex.Tok] = ind match + case Coll.Nil => Coll.rev(Coll.Cons(Lex.TEof(line), out)) + case Coll.Cons(t, rest) => if t > 0 then Lex.closeAll(line, rest, Coll.Cons(Lex.TDedent(line), out)) else Coll.rev(Coll.Cons(Lex.TEof(line), out)) diff --git a/bench/corpus/s2/mono.srs b/bench/corpus/s2/mono.srs new file mode 100644 index 00000000..0b6f955e --- /dev/null +++ b/bench/corpus/s2/mono.srs @@ -0,0 +1,232 @@ +// s2 self-host rung B1 (vic/c/s2-selfhost.md): the instances, as s1/mono.srs. the roots are the non-generic defs; a +// generic def is reached at concrete type args from a call and made once per distinct args. an instance is the def and +// its binders' args (a generic body holds its binders as rigid K.Cons named by them); every type in it is the term +// reified with the final substitution, then the binders replaced. +enum Mono.Inst: + case Mono.Inst(f: El.Fn, sub: Coll.List[Ty.Bind], site: Mono.Site) + +// where an instance's fn lives: a top-level def, or a method of the given picked for a ground goal (C names it by the goal) +enum Mono.Site: + case Mono.Top + case Mono.Impl(goal: K.Term) + +// what a body reaches: a generic call (callee and ground type args), or a trait goal (a method call on {} evidence) +enum Mono.Key: + case Mono.Call(f: Sym.Sym, targs: Coll.List[K.Term]) + case Mono.Goal(t: K.Term) + +// t reified, then each binder of sub replaced by its arg +def Mono.ground {r: Region} (s: Coll.IMap[K.Term], sub: Coll.List[Ty.Bind], t: K.Term): K.Term = Mono.apply(sub, K.reify(s, t)) + +def Mono.apply {r: Region} (sub: Coll.List[Ty.Bind], t: K.Term): K.Term = t match + case K.Con(n, args) => args match + case Coll.Nil => Ty.lookup(sub, n) match + case Coll.Some(a) => a + case Coll.None => t + case Coll.Cons(_, _) => K.Con(n, Mono.applyAll(sub, args, Coll.Nil)) + case _ => t + +def Mono.applyAll {r: Region} (sub: Coll.List[Ty.Bind], ts: Coll.List[K.Term], acc: Coll.List[K.Term]): Coll.List[K.Term] = ts match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(t, rest) => Mono.applyAll(sub, rest, Coll.Cons(Mono.apply(sub, t), acc)) + +def Mono.groundAll {r: Region} (s: Coll.IMap[K.Term], sub: Coll.List[Ty.Bind], ts: Coll.List[K.Term], acc: Coll.List[K.Term]): Coll.List[K.Term] = ts match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(t, rest) => Mono.groundAll(s, sub, rest, Coll.Cons(Mono.ground(s, sub, t), acc)) + +def Mono.termEq(a: K.Term, b: K.Term): Bool = a match + case K.Var(m) => b match + case K.Var(n) => m == n + case _ => false + case K.Int(m) => b match + case K.Int(n) => m == n + case _ => false + case K.Con(f, xs) => b match + case K.Con(g, ys) => Sym.eq(f, g) && Mono.termsEq(xs, ys) + case _ => false + +def Mono.termsEq(xs: Coll.List[K.Term], ys: Coll.List[K.Term]): Bool = xs match + case Coll.Nil => ys match + case Coll.Nil => true + case Coll.Cons(_, _) => false + case Coll.Cons(x, xt) => ys match + case Coll.Nil => false + case Coll.Cons(y, yt) => if Mono.termEq(x, y) then Mono.termsEq(xt, yt) else false + +// a hash of a key (made-set buckets): products stay below 2^63 (D.mult, D.modulus) +def Mono.thash(t: K.Term, h: I64): I64 = t match + case K.Var(n) => (h * D.mult() + n % D.modulus() + D.modulus()) % D.modulus() + case K.Int(n) => (h * D.mult() + n % D.modulus() + D.modulus()) % D.modulus() + case K.Con(f, xs) => Mono.thashAll(xs, (h * D.mult() + Sym.hash(f)) % D.modulus()) + +def Mono.thashAll(ts: Coll.List[K.Term], h: I64): I64 = ts match + case Coll.Nil => h + case Coll.Cons(t, rest) => Mono.thashAll(rest, Mono.thash(t, h)) + +def Mono.keyHash(k: Mono.Key): I64 = k match + case Mono.Call(f, ts) => Mono.thashAll(ts, Sym.hash(f) % D.modulus()) + case Mono.Goal(t) => Mono.thash(t, 1) + +def Mono.keyEq(a: Mono.Key, b: Mono.Key): Bool = a match + case Mono.Call(f, xs) => b match + case Mono.Call(g, ys) => Sym.eq(f, g) && Mono.termsEq(xs, ys) + case Mono.Goal(_) => false + case Mono.Goal(t) => b match + case Mono.Call(_, _) => false + case Mono.Goal(u) => Mono.termEq(t, u) + +def Mono.inBucket(ks: Coll.List[Mono.Key], k: Mono.Key): Bool = ks match + case Coll.Nil => false + case Coll.Cons(x, rest) => if Mono.keyEq(x, k) then true else Mono.inBucket(rest, k) + +// ── the worklist: roots first, then every generic call they reach, each key once ── +def Mono.run {r: Region} (res: Ty.Result): Coll.List[Mono.Inst] = + val Ty.Result(_, _, s, fs, _, gvs) = res + Mono.loop(Mono.Cx(s, Mono.fnMap(fs, Coll.sEmpty()), gvs), Mono.roots(fs, Coll.Nil), Coll.BTip, Coll.Nil) + +// what the worklist reads: the final substitution, the defs, the givens +enum Mono.Cx: + case Mono.Cx(s: Coll.IMap[K.Term], fs: Coll.SMap[El.Fn], gvs: Coll.List[El.Given]) + +def Mono.fnMap {r: Region} (fs: Coll.List[El.Fn], m: Coll.SMap[El.Fn]): Coll.SMap[El.Fn] = fs match + case Coll.Nil => m + case Coll.Cons(f, rest) => + val El.Fn(_, n, _, _, _, _, _) = f + Mono.fnMap(rest, Coll.sInsert(m, n, f)) + +def Mono.roots {r: Region} (fs: Coll.List[El.Fn], acc: Coll.List[Mono.Inst]): Coll.List[Mono.Inst] = fs match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(f, rest) => + val El.Fn(_, _, tps, _, _, _, _) = f + tps match + case Coll.Nil => Mono.roots(rest, Coll.Cons(Mono.Inst(f, Coll.Nil, Mono.Top), acc)) + case Coll.Cons(_, _) => Mono.roots(rest, acc) + +// todo: instances whose bodies are not yet scanned; made: keys already instantiated (by hash bucket); out: the result +def Mono.loop {r: Region} (cx: Mono.Cx, todo: Coll.List[Mono.Inst], made: Coll.BTree[Coll.List[Mono.Key]], out: Coll.List[Mono.Inst]): Coll.List[Mono.Inst] = todo match + case Coll.Nil => Coll.rev(out) + case Coll.Cons(i, rest) => + val Mono.Inst(f, sub, _) = i + val Mono.Cx(s, _, _) = cx + val El.Fn(_, _, _, _, _, _, body) = f + val ks: Coll.List[Mono.Key] = body match + case El.Def(e) => Mono.calls(s, sub, e, Coll.Nil) + case _ => Coll.Nil + val Mono.Grow(todo2, made2) = Mono.enqueue(cx, ks, rest, made) + Mono.loop(cx, todo2, made2, Coll.Cons(i, out)) + +enum Mono.Grow: + case Mono.Grow(todo: Coll.List[Mono.Inst], made: Coll.BTree[Coll.List[Mono.Key]]) + +// each new key becomes instances to scan: a generic def at its args, or every method of the given picked for a goal +def Mono.enqueue {r: Region} (cx: Mono.Cx, ks: Coll.List[Mono.Key], todo: Coll.List[Mono.Inst], made: Coll.BTree[Coll.List[Mono.Key]]): Mono.Grow = ks match + case Coll.Nil => Mono.Grow(todo, made) + case Coll.Cons(k, rest) => + val h = Mono.keyHash(k) + if Mono.inBucket(Coll.bTGetOr(made, h, Coll.Nil), k) then Mono.enqueue(cx, rest, todo, made) + else + val Mono.Cx(_, fs, gvs) = cx + val todo2 = k match + case Mono.Call(name, targs) => Coll.sLookup(fs, name) match + case Coll.None => todo + case Coll.Some(f) => + val El.Fn(_, _, tps, _, _, _, _) = f + Coll.Cons(Mono.Inst(f, Ty.zipBind(tps, targs, Coll.Nil), Mono.Top), todo) + case Mono.Goal(t) => Mono.pick(gvs, t, Coll.None) match + case Coll.None => todo + case Coll.Some(m) => + val Mono.Match(g, sub) = m + val El.Given(_, _, _, gfs) = g + Mono.implInsts(gfs, sub, t, todo) + Mono.enqueue(cx, rest, todo2, Coll.bPushT(made, h, k)) + +def Mono.implInsts {r: Region} (fs: Coll.List[El.Fn], sub: Coll.List[Ty.Bind], goal: K.Term, todo: Coll.List[Mono.Inst]): Coll.List[Mono.Inst] = fs match + case Coll.Nil => todo + case Coll.Cons(f, rest) => Mono.implInsts(rest, sub, goal, Coll.Cons(Mono.Inst(f, sub, Mono.Impl(goal)), todo)) + +// ── the given for a ground goal, as Scala3 ranks them (tests/s2/prog/given_rank.srs): the more specific head wins; on a draw the +// given with fewer {} evidence binders wins ── +enum Mono.Match: + case Mono.Match(g: El.Given, sub: Coll.List[Ty.Bind]) + +def Mono.pick {r: Region} (gvs: Coll.List[El.Given], t: K.Term, best: Coll.Option[Mono.Match]): Coll.Option[Mono.Match] = gvs match + case Coll.Nil => best + case Coll.Cons(g, rest) => + val El.Given(tps, _, head, _) = g + Mono.matchT(tps, head, t, Coll.Some(Coll.Nil)) match + case Coll.None => Mono.pick(rest, t, best) + case Coll.Some(sub) => + val m = Mono.Match(g, sub) + best match + case Coll.None => Mono.pick(rest, t, Coll.Some(m)) + case Coll.Some(b) => + val Mono.Match(bg, _) = b + Mono.pick(rest, t, if Mono.better(g, bg) then Coll.Some(m) else best) + +def Mono.better {r: Region} (a: El.Given, b: El.Given): Bool = + val El.Given(atps, aev, ah, _) = a + val El.Given(btps, bev, bh, _) = b + val ab = Mono.isSome(Mono.matchT(btps, bh, ah, Coll.Some(Coll.Nil))) + val ba = Mono.isSome(Mono.matchT(atps, ah, bh, Coll.Some(Coll.Nil))) + if ab && !ba then true else if ab && ba then Coll.length(aev) < Coll.length(bev) else false + +def Mono.isSome(o: Coll.Option[Coll.List[Ty.Bind]]): Bool = o match + case Coll.Some(_) => true + case Coll.None => false + +// t is an instance of the pattern p whose vars are the binder names xs: the binding (one-way match) +def Mono.matchT {r: Region} (xs: Coll.List[Sym.Sym], p: K.Term, t: K.Term, acc: Coll.Option[Coll.List[Ty.Bind]]): Coll.Option[Coll.List[Ty.Bind]] = acc match + case Coll.None => Coll.None + case Coll.Some(bs) => p match + case K.Con(n, pargs) => + if Coll.length(pargs) == 0 && Ty.memberSym(n, xs) then + Ty.lookup(bs, n) match + case Coll.Some(u) => if Mono.termEq(u, t) then acc else Coll.None + case Coll.None => Coll.Some(Coll.Cons(Ty.Bind(n, t), bs)) + else t match + case K.Con(m, targs) => if Sym.eq(n, m) && Coll.length(pargs) == Coll.length(targs) then Mono.matchAll(xs, pargs, targs, acc) else Coll.None + case _ => Coll.None + case _ => if Mono.termEq(p, t) then acc else Coll.None + +def Mono.matchAll {r: Region} (xs: Coll.List[Sym.Sym], ps: Coll.List[K.Term], ts: Coll.List[K.Term], acc: Coll.Option[Coll.List[Ty.Bind]]): Coll.Option[Coll.List[Ty.Bind]] = ps match + case Coll.Nil => acc + case Coll.Cons(p, prest) => ts match + case Coll.Nil => acc + case Coll.Cons(t, trest) => Mono.matchAll(xs, prest, trest, Mono.matchT(xs, p, t, acc)) + +// the generic calls of e, at ground args under sub +def Mono.calls {r: Region} (s: Coll.IMap[K.Term], sub: Coll.List[Ty.Bind], e: El.Expr, acc: Coll.List[Mono.Key]): Coll.List[Mono.Key] = e match + case El.CallFn(_, f, ts, _, args) => + val acc2 = ts match + case Coll.Nil => acc + case Coll.Cons(_, _) => Coll.Cons(Mono.Call(f, Mono.groundAll(s, sub, ts, Coll.Nil)), acc) + Mono.callsAll(s, sub, args, acc2) + case El.New(_, _, _, _, _, args) => Mono.callsAll(s, sub, args, acc) + case El.Op(_, _, ty, _, args) => Mono.callsAll(s, sub, args, Coll.Cons(Mono.Goal(Mono.ground(s, sub, ty)), acc)) + case El.Bin(_, _, l, rhs) => Mono.calls(s, sub, rhs, Mono.calls(s, sub, l, acc)) + case El.Un(_, _, x) => Mono.calls(s, sub, x, acc) + case El.If(_, c, t, x) => Mono.calls(s, sub, x, Mono.calls(s, sub, t, Mono.calls(s, sub, c, acc))) + case El.Match(_, x, _, arms) => Mono.armCalls(s, sub, arms, Mono.calls(s, sub, x, acc)) + case El.Block(_, ss, last) => Mono.calls(s, sub, last, Mono.stmtCalls(s, sub, ss, acc)) + case El.While(_, c, b) => Mono.calls(s, sub, b, Mono.calls(s, sub, c, acc)) + case El.Assign(_, _, x) => Mono.calls(s, sub, x, acc) + case _ => acc + +def Mono.callsAll {r: Region} (s: Coll.IMap[K.Term], sub: Coll.List[Ty.Bind], xs: Coll.List[El.Expr], acc: Coll.List[Mono.Key]): Coll.List[Mono.Key] = xs match + case Coll.Nil => acc + case Coll.Cons(x, rest) => Mono.callsAll(s, sub, rest, Mono.calls(s, sub, x, acc)) + +def Mono.armCalls {r: Region} (s: Coll.IMap[K.Term], sub: Coll.List[Ty.Bind], xs: Coll.List[El.Arm], acc: Coll.List[Mono.Key]): Coll.List[Mono.Key] = xs match + case Coll.Nil => acc + case Coll.Cons(a, rest) => + val El.Arm(_, _, b) = a + Mono.armCalls(s, sub, rest, Mono.calls(s, sub, b, acc)) + +def Mono.stmtCalls {r: Region} (s: Coll.IMap[K.Term], sub: Coll.List[Ty.Bind], xs: Coll.List[El.Stmt], acc: Coll.List[Mono.Key]): Coll.List[Mono.Key] = xs match + case Coll.Nil => acc + case Coll.Cons(x, rest) => + val acc2 = x match + case El.Val(_, _, _, _, e) => Mono.calls(s, sub, e, acc) + case El.Do(e) => Mono.calls(s, sub, e, acc) + case El.Handle(_, _, _, args) => Mono.callsAll(s, sub, args, acc) + Mono.stmtCalls(s, sub, rest, acc2) diff --git a/bench/corpus/s2/names.srs b/bench/corpus/s2/names.srs new file mode 100644 index 00000000..5a914553 --- /dev/null +++ b/bench/corpus/s2/names.srs @@ -0,0 +1,470 @@ +// s2 P4 NAMES + DECL (vic-m5r.25, vic/c/s2-port-plan.md S-NAMES, S-DECL; parity D1-D3, D7, D8): the declarations of +// the whole program as facts, one D.solve, every clash a derived fact read back as data. Names.facts walks the decls +// once: what each declares (by namespace), what each body uses, every type it names, every protocol state and +// transition, every handler fn and its arity. Names.rules derives the clashes. + +// a clash: the line it is at and the name it is about +enum Names.Clash: + // two declarations of one name in one namespace (calls: defs and enum cases; types: enums, protocols, handlers) + case Names.Dup(line: I64, name: Sym.Sym) + // a call or a name that no declaration and no local binds + case Names.Unknown(line: I64, name: Sym.Sym) + // a type that is not a builtin, an enum, a protocol or a [] binder in scope + case Names.NoType(line: I64, name: Sym.Sym) + // a protocol start or transition state that the protocol does not declare + case Names.BadState(line: I64, name: Sym.Sym) + // a drop op that the protocol does not declare + case Names.NoDrop(line: I64, name: Sym.Sym) + // a handler for a name that is not a protocol + case Names.NoProto(line: I64, name: Sym.Sym) + // a handler without init + case Names.NoInit(line: I64, name: Sym.Sym) + // a protocol op that the handler does not implement (name = the op) + case Names.NoOp(line: I64, name: Sym.Sym) + // a handler fn whose arity is not the op's arity + 1 (self) + case Names.BadArity(line: I64, name: Sym.Sym) + +enum Names.Verdict: + case Names.Ok + case Names.Bad(clashes: Coll.List[Names.Clash]) + // the rule library is not a Datalog program, or a clash relation holds another shape (a bug in Names.rules) + case Names.RulesBad(rel: Sym.Sym) + +// every relation; Names.relSym is the only place a relation name is a string +enum Names.Rel: + case Names.RDecl + case Names.RDeclLine + case Names.RDeclared + case Names.RUseCall + case Names.RTyRef + case Names.RState + case Names.RStart + case Names.RTrans + case Names.RDropOp + case Names.ROpOf + case Names.RIsProto + case Names.RHandlerFor + case Names.RImpl + case Names.RImplArity + case Names.RWantArity + case Names.RSame + case Names.RDupAt + case Names.RUnknownAt + case Names.RNoTypeAt + case Names.RBadStateAt + case Names.RNoDropAt + case Names.RNoProtoAt + case Names.RNoInitAt + case Names.RNoOpAt + case Names.RBadArityAt + +def Names.relSym {r: Region} (x: Names.Rel): Sym.Sym = x match + case Names.RDecl => Sym.of("decl") + case Names.RDeclLine => Sym.of("declLine") + case Names.RDeclared => Sym.of("declared") + case Names.RUseCall => Sym.of("useCall") + case Names.RTyRef => Sym.of("tyRef") + case Names.RState => Sym.of("state") + case Names.RStart => Sym.of("start") + case Names.RTrans => Sym.of("trans") + case Names.RDropOp => Sym.of("dropOp") + case Names.ROpOf => Sym.of("opOf") + case Names.RIsProto => Sym.of("isProto") + case Names.RHandlerFor => Sym.of("handlerFor") + case Names.RImpl => Sym.of("impl") + case Names.RImplArity => Sym.of("implArity") + case Names.RWantArity => Sym.of("wantArity") + case Names.RSame => Sym.of("same") + case Names.RDupAt => Sym.of("dupAt") + case Names.RUnknownAt => Sym.of("unknownAt") + case Names.RNoTypeAt => Sym.of("noTypeAt") + case Names.RBadStateAt => Sym.of("badStateAt") + case Names.RNoDropAt => Sym.of("noDropAt") + case Names.RNoProtoAt => Sym.of("noProtoAt") + case Names.RNoInitAt => Sym.of("noInitAt") + case Names.RNoOpAt => Sym.of("noOpAt") + case Names.RBadArityAt => Sym.of("badArityAt") + +// a namespace: calls (defs, enum cases) or types (enums, protocols, handlers, builtins) +enum Names.Ns: + case Names.NCall + case Names.NType + +def Names.nsVal {r: Region} (n: Names.Ns): D.Val = n match + case Names.NCall => D.VInt(0) + case Names.NType => D.VInt(1) + +// ── facts: one constructor per relation ── +def Names.i {r: Region} (n: I64): D.Val = D.VInt(n) +def Names.s {r: Region} (x: Sym.Sym): D.Val = D.VSym(x) +def Names.f2 {r: Region} (rel: Names.Rel, a: D.Val, b: D.Val): D.Fact = D.Fact(Names.relSym(rel), Coll.Cons(a, Coll.Cons(b, Coll.Nil))) +def Names.f3 {r: Region} (rel: Names.Rel, a: D.Val, b: D.Val, c: D.Val): D.Fact = D.Fact(Names.relSym(rel), Coll.Cons(a, Coll.Cons(b, Coll.Cons(c, Coll.Nil)))) +def Names.f5 {r: Region} (rel: Names.Rel, a: D.Val, b: D.Val, c: D.Val, d: D.Val, e: D.Val): D.Fact = D.Fact(Names.relSym(rel), Coll.Cons(a, Coll.Cons(b, Coll.Cons(c, Coll.Cons(d, Coll.Cons(e, Coll.Nil)))))) +def Names.fDecl {r: Region} (ns: Names.Ns, n: Sym.Sym, id: I64): D.Fact = Names.f3(Names.RDecl, Names.nsVal(ns), Names.s(n), Names.i(id)) +def Names.fDeclLine {r: Region} (id: I64, line: I64): D.Fact = Names.f2(Names.RDeclLine, Names.i(id), Names.i(line)) +def Names.fUseCall {r: Region} (n: Sym.Sym, line: I64): D.Fact = Names.f2(Names.RUseCall, Names.s(n), Names.i(line)) +def Names.fTyRef {r: Region} (n: Sym.Sym, line: I64): D.Fact = Names.f2(Names.RTyRef, Names.s(n), Names.i(line)) +def Names.fState {r: Region} (p: Sym.Sym, s: Sym.Sym): D.Fact = Names.f2(Names.RState, Names.s(p), Names.s(s)) +def Names.fStart {r: Region} (p: Sym.Sym, s: Sym.Sym, line: I64): D.Fact = Names.f3(Names.RStart, Names.s(p), Names.s(s), Names.i(line)) +def Names.fTrans {r: Region} (p: Sym.Sym, op: Sym.Sym, a: Sym.Sym, b: Sym.Sym, line: I64): D.Fact = Names.f5(Names.RTrans, Names.s(p), Names.s(op), Names.s(a), Names.s(b), Names.i(line)) +def Names.fDropOp {r: Region} (p: Sym.Sym, op: Sym.Sym, line: I64): D.Fact = Names.f3(Names.RDropOp, Names.s(p), Names.s(op), Names.i(line)) +def Names.fOpOf {r: Region} (p: Sym.Sym, op: Sym.Sym): D.Fact = Names.f2(Names.ROpOf, Names.s(p), Names.s(op)) +def Names.fIsProto {r: Region} (p: Sym.Sym): D.Fact = D.Fact(Names.relSym(Names.RIsProto), Coll.Cons(Names.s(p), Coll.Nil)) +def Names.fHandlerFor {r: Region} (h: Sym.Sym, p: Sym.Sym, line: I64): D.Fact = Names.f3(Names.RHandlerFor, Names.s(h), Names.s(p), Names.i(line)) +def Names.fImpl {r: Region} (h: Sym.Sym, f: Sym.Sym): D.Fact = Names.f2(Names.RImpl, Names.s(h), Names.s(f)) +def Names.fImplArity {r: Region} (h: Sym.Sym, f: Sym.Sym, n: I64, line: I64): D.Fact = D.Fact(Names.relSym(Names.RImplArity), Coll.Cons(Names.s(h), Coll.Cons(Names.s(f), Coll.Cons(Names.i(n), Coll.Cons(Names.i(line), Coll.Nil))))) +def Names.fWantArity {r: Region} (p: Sym.Sym, op: Sym.Sym, n: I64): D.Fact = Names.f3(Names.RWantArity, Names.s(p), Names.s(op), Names.i(n)) +def Names.fSameI {r: Region} (n: I64): D.Fact = Names.f2(Names.RSame, Names.i(n), Names.i(n)) + +// the walk: the next declaration id and the facts +enum Names.St: + case Names.St(next: I64, facts: Coll.List[D.Fact]) + +def Names.add {r: Region} (st: Names.St, f: D.Fact): Names.St = + val Names.St(n, fs) = st + Names.St(n, Coll.Cons(f, fs)) + +// a declaration of n in ns at line: a fresh id, so two declarations of one name are two rows +def Names.declare {r: Region} (st: Names.St, ns: Names.Ns, n: Sym.Sym, line: I64): Names.St = + val Names.St(id, fs) = st + Names.St(id + 1, Coll.Cons(Names.fSameI(id), Coll.Cons(Names.fDeclLine(id, line), Coll.Cons(Names.fDecl(ns, n, id), fs)))) + +// the builtin types (parity D14): one declaration each, at line 0 +def Names.builtins {r: Region} (st: Names.St): Names.St = + Names.declare(Names.declare(Names.declare(Names.declare(Names.declare(st, Names.NType, Sym.of("I64"), 0), Names.NType, Sym.of("Bool"), 0), Names.NType, Sym.of("Unit"), 0), Names.NType, Sym.of("Str"), 0), Names.NType, Sym.of("Ptr"), 0) + +def Names.facts {r: Region} (ds: Coll.List[Ast.Decl]): Coll.List[D.Fact] = + val Names.St(_, fs) = Names.decls(ds, Names.builtins(Names.St(0, Coll.Nil))) + fs + +def Names.decls {r: Region} (ds: Coll.List[Ast.Decl], st: Names.St): Names.St = ds match + case Coll.Nil => st + case Coll.Cons(d, rest) => Names.decls(rest, Names.decl(d, st)) + +def Names.decl {r: Region} (d: Ast.Decl, st: Names.St): Names.St = d match + case Ast.DFn(f) => + val Ast.Fn(line, name, _, _, _, _, _) = f + Names.fn(f, Coll.Nil, Names.declare(st, Names.NCall, name, line)) + case Ast.DEnum(e) => + val Ast.Enum(line, name, gs, cases) = e + Names.cases(cases, Names.tparams(gs, Coll.Nil), Names.declare(st, Names.NType, name, line)) + case Ast.DProto(p) => Names.proto(p, st) + case Ast.DHandler(h) => Names.handler(h, st) + // a trait is a type name; its method signatures name types in its [] binders + case Ast.DTrait(tr) => + val Ast.Trait(line, name, gs, sigs) = tr + Names.fnsIn(sigs, Names.tparams(gs, Coll.Nil), Names.declare(st, Names.NType, name, line)) + // a type decl is a type name; its body names types in its [] binders, its value args see its value binders + case Ast.DType(td) => + val Ast.TypeDecl(line, name, gs, vals, body) = td + val tps = Names.tparams(gs, Coll.Nil) + val ls = Names.binderNames(vals, Coll.Nil) + val st1 = Names.binderTys(vals, tps, Names.groupTys(gs, tps, Names.declare(st, Names.NType, name, line))) + body match + case Ast.Alias(t) => Names.tyIn(t, tps, ls, st1) + case Ast.TyMatch(s, arms) => Names.tyArms(arms, tps, ls, Names.tyIn(s, tps, ls, st1)) + case Ast.ValMatch(_, arms) => Names.valArms(arms, tps, ls, st1) + // a given names its trait head (in its [] binders); its methods are checked in them + case Ast.DGiven(g) => + val Ast.Given(_, gs, head, fs) = g + val tps = Names.tparams(gs, Coll.Nil) + Names.fnsIn(fs, tps, Names.ty(head, tps, st)) + +def Names.tyArms {r: Region} (as: Coll.List[Ast.TyArm], tps: Coll.List[Sym.Sym], ls: Coll.List[Sym.Sym], st: Names.St): Names.St = as match + case Coll.Nil => st + case Coll.Cons(a, rest) => + val Ast.TyArm(_, p, res) = a + Names.tyArms(rest, tps, ls, Names.tyIn(res, tps, ls, Names.tyIn(p, tps, ls, st))) + +def Names.valArms {r: Region} (as: Coll.List[Ast.ValArm], tps: Coll.List[Sym.Sym], ls: Coll.List[Sym.Sym], st: Names.St): Names.St = as match + case Coll.Nil => st + case Coll.Cons(a, rest) => + val Ast.ValArm(_, _, res) = a + Names.valArms(rest, tps, ls, Names.tyIn(res, tps, ls, st)) + +def Names.fnsIn {r: Region} (fs: Coll.List[Ast.Fn], tps: Coll.List[Sym.Sym], st: Names.St): Names.St = fs match + case Coll.Nil => st + case Coll.Cons(f, rest) => Names.fnsIn(rest, tps, Names.fn(f, tps, st)) + +// the [] binder names of groups gs (types in scope) +def Names.tparams {r: Region} (gs: Coll.List[Ast.Group], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = gs match + case Coll.Nil => acc + case Coll.Cons(g, rest) => g match + case Ast.Types(bs) => Names.tparams(rest, Names.binderNames(bs, acc)) + case Ast.Evidence(_) => Names.tparams(rest, acc) + case Ast.Facts(_) => Names.tparams(rest, acc) + +def Names.binderNames {r: Region} (bs: Coll.List[Ast.Binder], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = bs match + case Coll.Nil => acc + case Coll.Cons(b, rest) => + val Ast.Binder(_, x, _) = b + Names.binderNames(rest, Coll.Cons(x, acc)) + +def Names.member(x: Sym.Sym, xs: Coll.List[Sym.Sym]): Bool = xs match + case Coll.Nil => false + case Coll.Cons(h, t) => if Sym.eq(h, x) then true else Names.member(x, t) + +// every type a type names: its name (unless a [] binder in scope tps) and its args +def Names.ty {r: Region} (t: Ast.Ty, tps: Coll.List[Sym.Sym], st: Names.St): Names.St = Names.tyIn(t, tps, Coll.Nil, st) + +// a type with the locals ls in scope of its value args (the value binders of a type decl) +def Names.tyIn {r: Region} (t: Ast.Ty, tps: Coll.List[Sym.Sym], ls: Coll.List[Sym.Sym], st: Names.St): Names.St = + val Ast.Ty(line, n, args, _, vs) = t + Names.exprs(vs, ls, tps, Names.tys(args, tps, if Names.member(n, tps) then st else Names.add(st, Names.fTyRef(n, line)))) + +def Names.tys {r: Region} (ts: Coll.List[Ast.Ty], tps: Coll.List[Sym.Sym], st: Names.St): Names.St = ts match + case Coll.Nil => st + case Coll.Cons(t, rest) => Names.tys(rest, tps, Names.ty(t, tps, st)) + +def Names.binderTys {r: Region} (bs: Coll.List[Ast.Binder], tps: Coll.List[Sym.Sym], st: Names.St): Names.St = bs match + case Coll.Nil => st + case Coll.Cons(b, rest) => + val Ast.Binder(_, _, t) = b + Names.binderTys(rest, tps, Names.ty(t, tps, st)) + +// every case is a call name; its field types are named in the enum's [] binders +def Names.cases {r: Region} (cs: Coll.List[Ast.Case], tps: Coll.List[Sym.Sym], st: Names.St): Names.St = cs match + case Coll.Nil => st + case Coll.Cons(c, rest) => + val Ast.Case(line, name, fields) = c + Names.cases(rest, tps, Names.binderTys(fields, tps, Names.declare(st, Names.NCall, name, line))) + +// a def: its signature's types, then its body with its params and binders as locals (outer = types in scope from an +// enclosing decl) +def Names.fn {r: Region} (f: Ast.Fn, outer: Coll.List[Sym.Sym], st: Names.St): Names.St = + val Ast.Fn(_, _, gs, params, ret, _, body) = f + val tps = Names.tparams(gs, outer) + val st1 = Names.ty(ret, tps, Names.binderTys(params, tps, Names.groupTys(gs, tps, st))) + val locals = Names.binderNames(params, Names.evidenceNames(gs, Coll.Nil)) + body match + case Ast.Extern => st1 + case Ast.Def(cs, e) => Names.expr(e, locals, tps, Names.clauses(cs, locals, tps, st1)) + case Ast.Spec(cs, e) => Names.expr(e, locals, tps, Names.clauses(cs, locals, tps, st1)) + +// the types of the {} binders (a {} binder names a trait or a protocol) +def Names.groupTys {r: Region} (gs: Coll.List[Ast.Group], tps: Coll.List[Sym.Sym], st: Names.St): Names.St = gs match + case Coll.Nil => st + case Coll.Cons(g, rest) => g match + case Ast.Evidence(bs) => Names.groupTys(rest, tps, Names.binderTys(bs, tps, st)) + case Ast.Types(_) => Names.groupTys(rest, tps, st) + case Ast.Facts(_) => Names.groupTys(rest, tps, st) + +def Names.evidenceNames {r: Region} (gs: Coll.List[Ast.Group], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = gs match + case Coll.Nil => acc + case Coll.Cons(g, rest) => g match + case Ast.Evidence(bs) => Names.evidenceNames(rest, Names.binderNames(bs, acc)) + case Ast.Types(_) => Names.evidenceNames(rest, acc) + case Ast.Facts(_) => Names.evidenceNames(rest, acc) + +// contract clauses: their expressions see the params and result (s1 binds result in an ensures) +def Names.clauses {r: Region} (cs: Coll.List[Ast.Clause], ls: Coll.List[Sym.Sym], tps: Coll.List[Sym.Sym], st: Names.St): Names.St = cs match + case Coll.Nil => st + case Coll.Cons(c, rest) => c match + case Ast.CondC(_, _, e) => Names.clauses(rest, ls, tps, Names.expr(e, Coll.Cons(Sym.of("result"), ls), tps, st)) + case Ast.ProofUsing(line, xs) => Names.clauses(rest, ls, tps, Names.useAll(xs, line, st)) + case Ast.ProofInduction(_, _) => Names.clauses(rest, ls, tps, st) + case Ast.ProofLean(_, _) => Names.clauses(rest, ls, tps, st) + +// proof using f, g: each is a use of a def +def Names.useAll {r: Region} (xs: Coll.List[Sym.Sym], line: I64, st: Names.St): Names.St = xs match + case Coll.Nil => st + case Coll.Cons(x, rest) => Names.useAll(rest, line, Names.add(st, Names.fUseCall(x, line))) + +// a body: a call or a name that is not local is a use of the call namespace (a def, a case, a nullary case) +def Names.expr {r: Region} (e: Ast.Expr, ls: Coll.List[Sym.Sym], tps: Coll.List[Sym.Sym], st: Names.St): Names.St = e match + case Ast.Name(line, x) => if Names.member(x, ls) then st else Names.add(st, Names.fUseCall(x, line)) + case Ast.Call(line, f, targs, _, xs) => Names.exprs(xs, ls, tps, Names.tys(targs, tps, Names.add(st, Names.fUseCall(f, line)))) + case Ast.Method(_, _, _, xs) => Names.exprs(xs, ls, tps, st) + case Ast.Bin(_, _, l, rhs) => Names.expr(rhs, ls, tps, Names.expr(l, ls, tps, st)) + case Ast.Un(_, _, x) => Names.expr(x, ls, tps, st) + case Ast.If(_, c, t, x) => Names.expr(x, ls, tps, Names.expr(t, ls, tps, Names.expr(c, ls, tps, st))) + case Ast.While(_, c, b) => Names.expr(b, ls, tps, Names.expr(c, ls, tps, st)) + case Ast.Assign(_, _, x) => Names.expr(x, ls, tps, st) + case Ast.Quant(_, _, x, t, b) => Names.expr(b, Coll.Cons(x, ls), tps, Names.ty(t, tps, st)) + case Ast.Match(_, s, arms) => Names.arms(arms, ls, tps, Names.expr(s, ls, tps, st)) + case Ast.Block(_, ss, last) => Names.block(ss, last, ls, tps, st) + case _ => st + +def Names.exprs {r: Region} (xs: Coll.List[Ast.Expr], ls: Coll.List[Sym.Sym], tps: Coll.List[Sym.Sym], st: Names.St): Names.St = xs match + case Coll.Nil => st + case Coll.Cons(x, rest) => Names.exprs(rest, ls, tps, Names.expr(x, ls, tps, st)) + +// an arm: its case is a use; its binders are locals of its body +def Names.arms {r: Region} (as: Coll.List[Ast.Arm], ls: Coll.List[Sym.Sym], tps: Coll.List[Sym.Sym], st: Names.St): Names.St = as match + case Coll.Nil => st + case Coll.Cons(a, rest) => + val Ast.Arm(line, p, b) = a + val st1: Names.St = p match + case Ast.PCase(c, binds) => Names.expr(b, Names.binderSyms(binds, ls), tps, Names.add(st, Names.fUseCall(c, line))) + case Ast.PAny => Names.expr(b, ls, tps, st) + Names.arms(rest, ls, tps, st1) + +def Names.binderSyms {r: Region} (xs: Coll.List[Sym.Sym], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = xs match + case Coll.Nil => acc + case Coll.Cons(x, rest) => Names.binderSyms(rest, Coll.Cons(x, acc)) + +// a block: each statement in turn; a val, var or handle binds its name for the statements after it and the value +def Names.block {r: Region} (ss: Coll.List[Ast.Stmt], last: Ast.Expr, ls: Coll.List[Sym.Sym], tps: Coll.List[Sym.Sym], st: Names.St): Names.St = ss match + case Coll.Nil => Names.expr(last, ls, tps, st) + case Coll.Cons(s, rest) => s match + case Ast.Val(_, x, ann, e) => Names.block(rest, last, Coll.Cons(x, ls), tps, Names.annTy(ann, tps, Names.expr(e, ls, tps, st))) + case Ast.Var(_, x, ann, e) => Names.block(rest, last, Coll.Cons(x, ls), tps, Names.annTy(ann, tps, Names.expr(e, ls, tps, st))) + case Ast.Handle(line, x, h, xs) => Names.block(rest, last, Coll.Cons(x, ls), tps, Names.exprs(xs, ls, tps, Names.add(st, Names.fTyRef(h, line)))) + case Ast.Do(e) => Names.block(rest, last, ls, tps, Names.expr(e, ls, tps, st)) + case Ast.Check(_, _, e) => Names.block(rest, last, ls, tps, Names.expr(e, ls, tps, st)) + +def Names.annTy {r: Region} (ann: Coll.Option[Ast.Ty], tps: Coll.List[Sym.Sym], st: Names.St): Names.St = ann match + case Coll.None => st + case Coll.Some(t) => Names.ty(t, tps, st) + +// a protocol: a type name; its states, start, transitions, ops and drop op as facts; its op signatures' types +def Names.proto {r: Region} (p: Ast.Proto, st: Names.St): Names.St = + val Ast.Proto(line, name, states, start, _, dropOp, ops, _) = p + val st1 = Names.add(Names.add(Names.declare(st, Names.NType, name, line), Names.fIsProto(name)), Names.fStart(name, start, line)) + val st2 = Names.statesF(name, states, st1) + val st3: Names.St = dropOp match + case Coll.None => st2 + case Coll.Some(d) => Names.add(st2, Names.fDropOp(name, d, line)) + Names.ops(name, ops, st3) + +def Names.statesF {r: Region} (p: Sym.Sym, ss: Coll.List[Sym.Sym], st: Names.St): Names.St = ss match + case Coll.Nil => st + case Coll.Cons(s, rest) => Names.statesF(p, rest, Names.add(st, Names.fState(p, s))) + +// each op: declared in its protocol, wanted with arity params + 1 (self) in a handler, its transitions, its types +def Names.ops {r: Region} (p: Sym.Sym, os: Coll.List[Ast.Op], st: Names.St): Names.St = os match + case Coll.Nil => st + case Coll.Cons(o, rest) => + val Ast.Op(line, name, params, ret, trs) = o + val n = Coll.length(params) + 1 + val st1 = Names.add(Names.add(Names.add(st, Names.fOpOf(p, name)), Names.fWantArity(p, name, n)), Names.fSameI(n)) + Names.ops(p, rest, Names.transF(p, name, trs, line, Names.ty(ret, Coll.Nil, Names.binderTys(params, Coll.Nil, st1)))) + +def Names.transF {r: Region} (p: Sym.Sym, op: Sym.Sym, trs: Coll.List[Ast.Trans], line: I64, st: Names.St): Names.St = trs match + case Coll.Nil => st + case Coll.Cons(t, rest) => + val Ast.Trans(a, b) = t + Names.transF(p, op, rest, line, Names.add(st, Names.fTrans(p, op, a, b, line))) + +// a handler: a type name for a protocol; each fn implements an op (or init) with its arity +def Names.handler {r: Region} (h: Ast.Handler, st: Names.St): Names.St = + val Ast.Handler(line, name, p, fns) = h + Names.hfns(name, fns, Names.add(Names.declare(st, Names.NType, name, line), Names.fHandlerFor(name, p, line))) + +def Names.hfns {r: Region} (h: Sym.Sym, fs: Coll.List[Ast.Fn], st: Names.St): Names.St = fs match + case Coll.Nil => st + case Coll.Cons(f, rest) => + val Ast.Fn(line, name, _, params, _, _, _) = f + val n = Coll.length(params) + Names.hfns(h, rest, Names.fn(f, Coll.Nil, Names.add(Names.add(Names.add(st, Names.fImpl(h, name)), Names.fImplArity(h, name, n, line)), Names.fSameI(n)))) + +// ── rules (variables: ns 0, n 1, i 2, j 3, line 4, p 5, s 6, op 7, a 8, b 9, h 10, k 11, m 12) ── +def Names.v {r: Region} (n: I64): D.Arg = D.AVar(n) +def Names.atom {r: Region} (rel: Names.Rel, xs: Coll.List[I64]): D.Atom = D.Atom(Names.relSym(rel), Names.vars(xs)) +def Names.vars {r: Region} (xs: Coll.List[I64]): Coll.List[D.Arg] = xs match + case Coll.Nil => Coll.Nil + case Coll.Cons(x, rest) => Coll.Cons(Names.v(x), Names.vars(rest)) +def Names.pos {r: Region} (rel: Names.Rel, xs: Coll.List[I64]): D.Lit = D.Pos(Names.atom(rel, xs)) +def Names.neg {r: Region} (rel: Names.Rel, xs: Coll.List[I64]): D.Lit = D.Neg(Names.atom(rel, xs)) +def Names.rule {r: Region} (rel: Names.Rel, xs: Coll.List[I64], body: Coll.List[D.Lit]): D.Rule = D.Rule(Names.atom(rel, xs), body) +def Names.l1 [A: Type] {r: Region} (a: A): Coll.List[A] = Coll.Cons(a, Coll.Nil) +def Names.l2 [A: Type] {r: Region} (a: A, b: A): Coll.List[A] = Coll.Cons(a, Names.l1(b)) +def Names.l3 [A: Type] {r: Region} (a: A, b: A, c: A): Coll.List[A] = Coll.Cons(a, Names.l2(b, c)) +def Names.l4 [A: Type] {r: Region} (a: A, b: A, c: A, d: A): Coll.List[A] = Coll.Cons(a, Names.l3(b, c, d)) +def Names.l5 [A: Type] {r: Region} (a: A, b: A, c: A, d: A, e: A): Coll.List[A] = Coll.Cons(a, Names.l4(b, c, d, e)) + +// a call-namespace value: the ns column as a constant +def Names.callNs {r: Region} (): D.Arg = D.AVal(D.VInt(0)) +def Names.typeNs {r: Region} (): D.Arg = D.AVal(D.VInt(1)) + +def Names.rules {r: Region} (): Coll.List[D.Rule] = + val declared = Names.rule(Names.RDeclared, Names.l2(0, 1), Names.l1(Names.pos(Names.RDecl, Names.l3(0, 1, 2)))) + // every declaration of a name declared twice in one namespace (declaration ids differ) + val dup = Names.rule(Names.RDupAt, Names.l2(4, 1), Names.l4(Names.pos(Names.RDecl, Names.l3(0, 1, 2)), Names.pos(Names.RDecl, Names.l3(0, 1, 3)), Names.neg(Names.RSame, Names.l2(2, 3)), Names.pos(Names.RDeclLine, Names.l2(2, 4)))) + val unknown = D.Rule(Names.atom(Names.RUnknownAt, Names.l2(4, 1)), Names.l2(Names.pos(Names.RUseCall, Names.l2(1, 4)), D.Neg(D.Atom(Names.relSym(Names.RDeclared), Coll.Cons(Names.callNs(), Names.l1(Names.v(1))))))) + val noType = D.Rule(Names.atom(Names.RNoTypeAt, Names.l2(4, 1)), Names.l2(Names.pos(Names.RTyRef, Names.l2(1, 4)), D.Neg(D.Atom(Names.relSym(Names.RDeclared), Coll.Cons(Names.typeNs(), Names.l1(Names.v(1))))))) + // protocol well-formed: start and transition states are its states; its drop op is its op + val badStart = Names.rule(Names.RBadStateAt, Names.l2(4, 6), Names.l2(Names.pos(Names.RStart, Names.l3(5, 6, 4)), Names.neg(Names.RState, Names.l2(5, 6)))) + val badFrom = Names.rule(Names.RBadStateAt, Names.l2(4, 8), Names.l2(Names.pos(Names.RTrans, Names.l5(5, 7, 8, 9, 4)), Names.neg(Names.RState, Names.l2(5, 8)))) + val badTo = Names.rule(Names.RBadStateAt, Names.l2(4, 9), Names.l2(Names.pos(Names.RTrans, Names.l5(5, 7, 8, 9, 4)), Names.neg(Names.RState, Names.l2(5, 9)))) + val noDrop = Names.rule(Names.RNoDropAt, Names.l2(4, 7), Names.l2(Names.pos(Names.RDropOp, Names.l3(5, 7, 4)), Names.neg(Names.ROpOf, Names.l2(5, 7)))) + // handler: for a protocol, with init, every op implemented with arity + 1 + val noProto = Names.rule(Names.RNoProtoAt, Names.l2(4, 5), Names.l2(Names.pos(Names.RHandlerFor, Names.l3(10, 5, 4)), Names.neg(Names.RIsProto, Names.l1(5)))) + val noInit = D.Rule(Names.atom(Names.RNoInitAt, Names.l2(4, 10)), Names.l2(Names.pos(Names.RHandlerFor, Names.l3(10, 5, 4)), D.Neg(D.Atom(Names.relSym(Names.RImpl), Names.l2(Names.v(10), D.AVal(D.VSym(Sym.of("init")))))))) + val noOp = Names.rule(Names.RNoOpAt, Names.l2(4, 7), Names.l3(Names.pos(Names.RHandlerFor, Names.l3(10, 5, 4)), Names.pos(Names.ROpOf, Names.l2(5, 7)), Names.neg(Names.RImpl, Names.l2(10, 7)))) + val badArity = Names.rule(Names.RBadArityAt, Names.l2(4, 7), Names.l4(Names.pos(Names.RHandlerFor, Names.l3(10, 5, 11)), Names.pos(Names.RWantArity, Names.l3(5, 7, 12)), Names.pos(Names.RImplArity, Names.l4(10, 7, 2, 4)), Names.neg(Names.RSame, Names.l2(2, 12)))) + Coll.Cons(declared, Coll.Cons(dup, Coll.Cons(unknown, Coll.Cons(noType, Coll.Cons(badStart, Coll.Cons(badFrom, Coll.Cons(badTo, Coll.Cons(noDrop, Coll.Cons(noProto, Coll.Cons(noInit, Coll.Cons(noOp, Names.l1(badArity)))))))))))) + +// ── the verdict: each clash relation read as (line, name); another shape is a bug in Names.rules (RulesBad) ── +enum Names.Kind: + case Names.KDup + case Names.KUnknown + case Names.KNoType + case Names.KBadState + case Names.KNoDrop + case Names.KNoProto + case Names.KNoInit + case Names.KNoOp + case Names.KBadArity + +def Names.relOf(k: Names.Kind): Names.Rel = k match + case Names.KDup => Names.RDupAt + case Names.KUnknown => Names.RUnknownAt + case Names.KNoType => Names.RNoTypeAt + case Names.KBadState => Names.RBadStateAt + case Names.KNoDrop => Names.RNoDropAt + case Names.KNoProto => Names.RNoProtoAt + case Names.KNoInit => Names.RNoInitAt + case Names.KNoOp => Names.RNoOpAt + case Names.KBadArity => Names.RBadArityAt + +def Names.make {r: Region} (k: Names.Kind, line: I64, n: Sym.Sym): Names.Clash = k match + case Names.KDup => Names.Dup(line, n) + case Names.KUnknown => Names.Unknown(line, n) + case Names.KNoType => Names.NoType(line, n) + case Names.KBadState => Names.BadState(line, n) + case Names.KNoDrop => Names.NoDrop(line, n) + case Names.KNoProto => Names.NoProto(line, n) + case Names.KNoInit => Names.NoInit(line, n) + case Names.KNoOp => Names.NoOp(line, n) + case Names.KBadArity => Names.BadArity(line, n) + +enum Names.Read: + case Names.Got(cs: Coll.List[Names.Clash]) + case Names.IllTyped(rel: Sym.Sym) + +def Names.read {r: Region} (m: D.Model, k: Names.Kind, prev: Names.Read): Names.Read = prev match + case Names.IllTyped(_) => prev + case Names.Got(acc) => Names.readList(k, D.tuples(m, Names.relSym(Names.relOf(k))), acc) + +def Names.readList {r: Region} (k: Names.Kind, ts: Coll.List[Coll.List[D.Val]], acc: Coll.List[Names.Clash]): Names.Read = ts match + case Coll.Nil => Names.Got(acc) + case Coll.Cons(t, rest) => Names.clashOf(k, t) match + case Coll.None => Names.IllTyped(Names.relSym(Names.relOf(k))) + case Coll.Some(c) => Names.readList(k, rest, Coll.Cons(c, acc)) + +def Names.clashOf {r: Region} (k: Names.Kind, t: Coll.List[D.Val]): Coll.Option[Names.Clash] = t match + case Coll.Cons(a, rest) => rest match + case Coll.Cons(b, more) => more match + case Coll.Nil => a match + case D.VInt(line) => b match + case D.VSym(n) => Coll.Some(Names.make(k, line, n)) + case D.VInt(_) => Coll.None + case D.VSym(_) => Coll.None + case Coll.Cons(_, _) => Coll.None + case Coll.Nil => Coll.None + case Coll.Nil => Coll.None + +def Names.readAll {r: Region} (m: D.Model): Names.Read = + val r1 = Names.read(m, Names.KDup, Names.read(m, Names.KUnknown, Names.read(m, Names.KNoType, Names.Got(Coll.Nil)))) + val r2 = Names.read(m, Names.KBadState, Names.read(m, Names.KNoDrop, Names.read(m, Names.KNoProto, r1))) + Names.read(m, Names.KNoInit, Names.read(m, Names.KNoOp, Names.read(m, Names.KBadArity, r2))) + +def Names.check {r: Region} (ds: Coll.List[Ast.Decl]): Names.Verdict = D.solve(Names.rules(), Names.facts(ds)) match + case D.Solved(m) => Names.readAll(m) match + case Names.IllTyped(rel) => Names.RulesBad(rel) + case Names.Got(cs) => cs match + case Coll.Nil => Names.Ok + case Coll.Cons(_, _) => Names.Bad(cs) + case D.Unsafe(rel) => Names.RulesBad(rel) + case D.NegCycle(rel) => Names.RulesBad(rel) diff --git a/bench/corpus/s2/parse.srs b/bench/corpus/s2/parse.srs new file mode 100644 index 00000000..0ae98f56 --- /dev/null +++ b/bench/corpus/s2/parse.srs @@ -0,0 +1,833 @@ +// s2 P6 FRONT (vic-m5r.27, vic/c/s2-front-spec.md): the parser, recursive descent over Lex tokens into the s2 Ast, as +// s1/parse.srs. each production returns Parse.Ok(value, rest) or Parse.Err(line, what was expected): an error is data. +// this rung: def, extern def, enum, protocol (states, start, end, drop, ops, rule defs), handler; binder groups +// [] {} <>; exit facts; types T[args]^; every expression and statement s1 parses except forall/exists. + +enum Parse.R [A: Type]: + case Parse.Ok(v: A, ts: Coll.List[Lex.Tok]) + case Parse.Err(line: I64, want: Str) + +// ── tokens ── +def Parse.eof {r: Region} (): Lex.Tok = Lex.TEof(0) + +def Parse.peek {r: Region} (ts: Coll.List[Lex.Tok]): Lex.Tok = ts match + case Coll.Nil => Parse.eof() + case Coll.Cons(t, _) => t + +def Parse.next {r: Region} (ts: Coll.List[Lex.Tok]): Coll.List[Lex.Tok] = ts match + case Coll.Nil => ts + case Coll.Cons(_, rest) => rest + +def Parse.second {r: Region} (ts: Coll.List[Lex.Tok]): Lex.Tok = Parse.peek(Parse.next(ts)) + +def Parse.lineOf(t: Lex.Tok): I64 = t match + case Lex.TIdent(_, l) => l + case Lex.TInt(_, l) => l + case Lex.TStr(_, l) => l + case Lex.TChar(_, l) => l + case Lex.TOp(_, l) => l + case Lex.TNl(l) => l + case Lex.TIndent(l) => l + case Lex.TDedent(l) => l + case Lex.TEof(l) => l + +def Parse.line {r: Region} (ts: Coll.List[Lex.Tok]): I64 = Parse.lineOf(Parse.peek(ts)) + +def Parse.opIs(t: Lex.Tok, s: Str): Bool = t match + case Lex.TOp(x, _) => rt_str_eq(x, s) + case _ => false + +def Parse.kwIs(t: Lex.Tok, s: Str): Bool = t match + case Lex.TIdent(x, _) => rt_str_eq(x, s) + case _ => false + +def Parse.isOp {r: Region} (ts: Coll.List[Lex.Tok], s: Str): Bool = Parse.opIs(Parse.peek(ts), s) +def Parse.isKw {r: Region} (ts: Coll.List[Lex.Tok], s: Str): Bool = Parse.kwIs(Parse.peek(ts), s) + +def Parse.isNl {r: Region} (ts: Coll.List[Lex.Tok]): Bool = Parse.peek(ts) match + case Lex.TNl(_) => true + case _ => false + +def Parse.isIndent {r: Region} (ts: Coll.List[Lex.Tok]): Bool = Parse.peek(ts) match + case Lex.TIndent(_) => true + case _ => false + +def Parse.isDedent {r: Region} (ts: Coll.List[Lex.Tok]): Bool = Parse.peek(ts) match + case Lex.TDedent(_) => true + case _ => false + +def Parse.isEof {r: Region} (ts: Coll.List[Lex.Tok]): Bool = Parse.peek(ts) match + case Lex.TEof(_) => true + case _ => false + +def Parse.skipNl {r: Region} (ts: Coll.List[Lex.Tok]): Coll.List[Lex.Tok] = if Parse.isNl(ts) then Parse.skipNl(Parse.next(ts)) else ts + +// the token after an op s, or Err +def Parse.op {r: Region} (ts: Coll.List[Lex.Tok], s: Str): Parse.R[I64] = + if Parse.isOp(ts, s) then Parse.Ok(Parse.line(ts), Parse.next(ts)) else Parse.Err(Parse.line(ts), s) + +def Parse.kw {r: Region} (ts: Coll.List[Lex.Tok], s: Str): Parse.R[I64] = + if Parse.isKw(ts, s) then Parse.Ok(Parse.line(ts), Parse.next(ts)) else Parse.Err(Parse.line(ts), s) + +def Parse.ident {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Sym.Sym] = Parse.peek(ts) match + case Lex.TIdent(x, _) => Parse.Ok(Sym.of(x), Parse.next(ts)) + case _ => Parse.Err(Parse.line(ts), "name") + +// `:` NL IND: a layout block opens +def Parse.layoutOpen {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[I64] = Parse.op(ts, ":") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t1) => + if Parse.isNl(t1) && Parse.isIndent(Parse.next(t1)) then Parse.Ok(Parse.line(t1), Parse.next(Parse.next(t1))) else Parse.Err(Parse.line(t1), "indented block") + +// the end of a line in a layout block: NL (consumed) or a DED that closes the block (left) +def Parse.endLine {r: Region} (ts: Coll.List[Lex.Tok]): Coll.List[Lex.Tok] = if Parse.isNl(ts) then Parse.next(ts) else ts + +// ── the file ── +def Parse.file {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Coll.List[Ast.Decl]] = Parse.decls(ts, Coll.Nil) + +def Parse.decls {r: Region} (ts: Coll.List[Lex.Tok], acc: Coll.List[Ast.Decl]): Parse.R[Coll.List[Ast.Decl]] = + if Parse.isNl(ts) then Parse.decls(Parse.next(ts), acc) + else if Parse.isEof(ts) then Parse.Ok(Coll.rev(acc), ts) + else Parse.decl(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(d, t1) => Parse.decls(t1, Coll.Cons(d, acc)) + +def Parse.decl {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Ast.Decl] = + if Parse.isKw(ts, "def") then Parse.wrapFn(Parse.fn(Parse.next(ts), Parse.line(ts), Parse.FDef)) + else if Parse.isKw(ts, "extern") || Parse.isKw(ts, "spec") then + Parse.kw(Parse.next(ts), "def") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t1) => Parse.wrapFn(Parse.fn(t1, Parse.line(ts), if Parse.isKw(ts, "spec") then Parse.FSpec else Parse.FExtern)) + else if Parse.isKw(ts, "enum") then Parse.enumDecl(Parse.next(ts), Parse.line(ts)) + else if Parse.isKw(ts, "protocol") then Parse.proto(Parse.next(ts), Parse.line(ts)) + else if Parse.isKw(ts, "handler") then Parse.handler(Parse.next(ts), Parse.line(ts)) + else if Parse.isKw(ts, "trait") then Parse.traitDecl(Parse.next(ts), Parse.line(ts)) + else if Parse.isKw(ts, "given") then Parse.givenDecl(Parse.next(ts), Parse.line(ts)) + else if Parse.isKw(ts, "type") then Parse.typeDecl(Parse.next(ts), Parse.line(ts)) + else Parse.Err(Parse.line(ts), "declaration") + +// type Name groups [(value binders)] = body (s1/parse.srs:297-346) +def Parse.typeDecl {r: Region} (ts: Coll.List[Lex.Tok], line: I64): Parse.R[Ast.Decl] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(name, t1) => Parse.groups(t1, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(gs, t2) => + val rv: Parse.R[Coll.List[Ast.Binder]] = if Parse.isOp(t2, "(") then Parse.params(t2) else Parse.Ok(Coll.Nil, t2) + rv match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(vals, t3) => Parse.op(t3, "=") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t4) => Parse.typeBody(t4, vals) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(b, t5) => Parse.Ok(Ast.DType(Ast.TypeDecl(line, name, gs, vals, b)), t5) + +// a value binder name followed by match: a value match; else a type, then match arms or not +def Parse.typeBody {r: Region} (ts: Coll.List[Lex.Tok], vals: Coll.List[Ast.Binder]): Parse.R[Ast.TBody] = Parse.peek(ts) match + case Lex.TIdent(x, _) => + if Parse.kwIs(Parse.second(ts), "match") && Parse.binderNamed(vals, x) then + Parse.armsOpen(Parse.next(Parse.next(ts))) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t1) => Parse.valArms(t1, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(as, t2) => Parse.Ok(Ast.ValMatch(Sym.of(x), as), t2) + else Parse.tyBody(ts) + case _ => Parse.tyBody(ts) + +def Parse.binderNamed(bs: Coll.List[Ast.Binder], x: Str): Bool = bs match + case Coll.Nil => false + case Coll.Cons(b, rest) => + val Ast.Binder(_, n, _) = b + if rt_str_eq(Sym.str(n), x) then true else Parse.binderNamed(rest, x) + +def Parse.tyBody {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Ast.TBody] = Parse.ty(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(t, t1) => + if Parse.isKw(t1, "match") then + Parse.armsOpen(Parse.next(t1)) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t2) => Parse.tyArms(t2, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(as, t3) => Parse.Ok(Ast.TyMatch(t, as), t3) + else Parse.Ok(Ast.Alias(t), t1) + +// NL IND after match +def Parse.armsOpen {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[I64] = + if Parse.isNl(ts) && Parse.isIndent(Parse.next(ts)) then Parse.Ok(Parse.line(ts), Parse.next(Parse.next(ts))) else Parse.Err(Parse.line(ts), "match arms") + +def Parse.tyArms {r: Region} (ts: Coll.List[Lex.Tok], acc: Coll.List[Ast.TyArm]): Parse.R[Coll.List[Ast.TyArm]] = + if Parse.isDedent(ts) then Parse.Ok(Coll.rev(acc), Parse.next(ts)) + else Parse.kw(ts, "case") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(line, t1) => Parse.ty(t1) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(p, t2) => Parse.op(t2, "=>") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t3) => Parse.ty(t3) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(res, t4) => Parse.tyArms(Parse.endLine(t4), Coll.Cons(Ast.TyArm(line, p, res), acc)) + +def Parse.valArms {r: Region} (ts: Coll.List[Lex.Tok], acc: Coll.List[Ast.ValArm]): Parse.R[Coll.List[Ast.ValArm]] = + if Parse.isDedent(ts) then Parse.Ok(Coll.rev(acc), Parse.next(ts)) + else Parse.kw(ts, "case") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(line, t1) => Parse.valuePat(t1) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(p, t2) => Parse.op(t2, "=>") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t3) => Parse.ty(t3) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(res, t4) => Parse.valArms(Parse.endLine(t4), Coll.Cons(Ast.ValArm(line, p, res), acc)) + +// an int, a string, true, false or _ +def Parse.valuePat {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Ast.VPat] = Parse.peek(ts) match + case Lex.TInt(v, _) => Parse.Ok(Ast.VInt(v), Parse.next(ts)) + case Lex.TStr(s, _) => Parse.Ok(Ast.VStr(s), Parse.next(ts)) + case Lex.TIdent(x, line) => + if rt_str_eq(x, "true") then Parse.Ok(Ast.VBool(true), Parse.next(ts)) + else if rt_str_eq(x, "false") then Parse.Ok(Ast.VBool(false), Parse.next(ts)) + else if rt_str_eq(x, "_") then Parse.Ok(Ast.VAny, Parse.next(ts)) + else Parse.Err(line, "a value pattern (int, string, true, false, _)") + case _ => Parse.Err(Parse.line(ts), "a value pattern (int, string, true, false, _)") + +// trait Name groups: NL IND (def signature, no body)* DED +def Parse.traitDecl {r: Region} (ts: Coll.List[Lex.Tok], line: I64): Parse.R[Ast.Decl] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(name, t1) => Parse.groups(t1, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(gs, t2) => Parse.layoutOpen(t2) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t3) => Parse.defs(t3, true, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(sigs, t4) => Parse.Ok(Ast.DTrait(Ast.Trait(line, name, gs, sigs)), t4) + +// given groups Head[args]: NL IND (def ...)* DED +def Parse.givenDecl {r: Region} (ts: Coll.List[Lex.Tok], line: I64): Parse.R[Ast.Decl] = Parse.groups(ts, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(gs, t1) => Parse.ty(t1) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(head, t2) => Parse.layoutOpen(t2) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t3) => Parse.defs(t3, false, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(fs, t4) => Parse.Ok(Ast.DGiven(Ast.Given(line, gs, head, fs)), t4) + +// defs until DED; sig = signatures only (a trait) +def Parse.defs {r: Region} (ts: Coll.List[Lex.Tok], sig: Bool, acc: Coll.List[Ast.Fn]): Parse.R[Coll.List[Ast.Fn]] = + if Parse.isDedent(ts) then Parse.Ok(Coll.rev(acc), Parse.next(ts)) + else Parse.kw(ts, "def") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(line, t1) => Parse.fn(t1, line, if sig then Parse.FExtern else Parse.FDef) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(f, t2) => Parse.defs(Parse.endLine(t2), sig, Coll.Cons(f, acc)) + +def Parse.wrapFn {r: Region} (rf: Parse.R[Ast.Fn]): Parse.R[Ast.Decl] = rf match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(f, t1) => Parse.Ok(Ast.DFn(f), t1) + +// which def: a def with a body, an extern def (or a trait method: no body), a spec def (a body, no binder groups) +enum Parse.FnKind: + case Parse.FDef + case Parse.FExtern + case Parse.FSpec + +// def name groups (params) groups : ty [] [= rhs] +def Parse.fn {r: Region} (ts: Coll.List[Lex.Tok], line: I64, k: Parse.FnKind): Parse.R[Ast.Fn] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(name, t1) => Parse.groups(t1, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(g1, t2) => Parse.params(t2) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(ps, t3) => Parse.groups(t3, Coll.rev(g1)) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(gs, t4) => Parse.op(t4, ":") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t5) => Parse.ty(t5) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(ret, t6) => Parse.exitFacts(t6) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(exit, t7) => Parse.fnBody(t7, Ast.Fn(line, name, gs, ps, ret, exit, Ast.Extern), k) + +// the body of a def by its kind; a spec def with binder groups is an error (vic 2026-11-05) +def Parse.fnBody {r: Region} (ts: Coll.List[Lex.Tok], f: Ast.Fn, k: Parse.FnKind): Parse.R[Ast.Fn] = + val Ast.Fn(line, name, gs, ps, ret, exit, _) = f + k match + case Parse.FExtern => Parse.Ok(f, ts) + case Parse.FDef => Parse.bodyOf(ts, f, false) + case Parse.FSpec => gs match + case Coll.Nil => Parse.bodyOf(ts, f, true) + case Coll.Cons(_, _) => Parse.Err(line, "a spec def without binder groups") + +// [NL IND clauses DED] = rhs (s1/parse.srs:88-89: the clauses sit between the signature and =) +def Parse.bodyOf {r: Region} (ts: Coll.List[Lex.Tok], f: Ast.Fn, spec: Bool): Parse.R[Ast.Fn] = + val Ast.Fn(line, name, gs, ps, ret, exit, _) = f + val rc: Parse.R[Coll.List[Ast.Clause]] = if Parse.isNl(ts) && Parse.isIndent(Parse.next(ts)) then Parse.clauses(Parse.next(Parse.next(ts)), Coll.Nil) else Parse.Ok(Coll.Nil, ts) + rc match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(cs, t0) => Parse.op(t0, "=") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t1) => Parse.rhs(t1) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(e, t2) => Parse.Ok(Ast.Fn(line, name, gs, ps, ret, exit, if spec then Ast.Spec(cs, e) else Ast.Def(cs, e)), t2) + +// clauses until DED, one per line +def Parse.clauses {r: Region} (ts: Coll.List[Lex.Tok], acc: Coll.List[Ast.Clause]): Parse.R[Coll.List[Ast.Clause]] = + if Parse.isDedent(ts) then Parse.Ok(Coll.rev(acc), Parse.next(ts)) + else Parse.clause(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(c, t1) => Parse.clauses(Parse.endLine(t1), Coll.Cons(c, acc)) + +// requires|ensures|returns|decreases|invariant expr | proof using f, ... | proof by induction x | proof lean "..." +def Parse.clause {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Ast.Clause] = + val line = Parse.line(ts) + if Parse.isKw(ts, "proof") then Parse.proof(Parse.next(ts), line) + else Parse.condOf(Parse.peek(ts)) match + case Coll.None => Parse.Err(line, "requires, ensures, returns, decreases, invariant or proof") + case Coll.Some(k) => Parse.expr(Parse.next(ts)) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(e, t1) => Parse.Ok(Ast.CondC(line, k, e), t1) + +def Parse.condOf {r: Region} (t: Lex.Tok): Coll.Option[Ast.Cond] = + if Parse.kwIs(t, "requires") then Coll.Some(Ast.Requires) + else if Parse.kwIs(t, "ensures") then Coll.Some(Ast.Ensures) + else if Parse.kwIs(t, "returns") then Coll.Some(Ast.Returns) + else if Parse.kwIs(t, "decreases") then Coll.Some(Ast.Decreases) + else if Parse.kwIs(t, "invariant") then Coll.Some(Ast.Invariant) + else Coll.None + +def Parse.proof {r: Region} (ts: Coll.List[Lex.Tok], line: I64): Parse.R[Ast.Clause] = + if Parse.isKw(ts, "using") then + Parse.nameLine(Parse.next(ts), Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(xs, t1) => Parse.Ok(Ast.ProofUsing(line, xs), t1) + else if Parse.isKw(ts, "by") then + Parse.kw(Parse.next(ts), "induction") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t1) => Parse.ident(t1) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(x, t2) => Parse.Ok(Ast.ProofInduction(line, x), t2) + else Parse.kw(ts, "lean") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t1) => Parse.peek(t1) match + case Lex.TStr(s, _) => Parse.Ok(Ast.ProofLean(line, s), Parse.next(t1)) + case _ => Parse.Err(Parse.line(t1), "a string of Lean tactics") + +// binder groups in written order: [binders] {binders} ; acc holds them reversed +def Parse.groups {r: Region} (ts: Coll.List[Lex.Tok], acc: Coll.List[Ast.Group]): Parse.R[Coll.List[Ast.Group]] = + if Parse.isOp(ts, "[") then Parse.moreGroups(Parse.binders(Parse.next(ts), "]", Coll.Nil), Parse.GTypes, acc) + else if Parse.isOp(ts, "{") then Parse.moreGroups(Parse.binders(Parse.next(ts), "}", Coll.Nil), Parse.GEvidence, acc) + else if Parse.isOp(ts, "<") then + Parse.atoms(Parse.next(ts), Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(as, t1) => Parse.groups(t1, Coll.Cons(Ast.Facts(as), acc)) + else Parse.Ok(Coll.rev(acc), ts) + +// which binder group: [] types or {} evidence +enum Parse.GKind: + case Parse.GTypes + case Parse.GEvidence + +def Parse.moreGroups {r: Region} (rb: Parse.R[Coll.List[Ast.Binder]], kind: Parse.GKind, acc: Coll.List[Ast.Group]): Parse.R[Coll.List[Ast.Group]] = rb match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(bs, t1) => Parse.groups(t1, Coll.Cons(Parse.groupOf(kind, bs), acc)) + +def Parse.groupOf {r: Region} (k: Parse.GKind, bs: Coll.List[Ast.Binder]): Ast.Group = k match + case Parse.GTypes => Ast.Types(bs) + case Parse.GEvidence => Ast.Evidence(bs) + +// name: ty, ... up to close +def Parse.binders {r: Region} (ts: Coll.List[Lex.Tok], close: Str, acc: Coll.List[Ast.Binder]): Parse.R[Coll.List[Ast.Binder]] = + if Parse.isOp(ts, close) then Parse.Ok(Coll.rev(acc), Parse.next(ts)) + else Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(x, t1) => Parse.op(t1, ":") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t2) => Parse.ty(t2) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(t, t3) => + val acc2 = Coll.Cons(Ast.Binder(Parse.line(ts), x, t), acc) + if Parse.isOp(t3, ",") then Parse.binders(Parse.next(t3), close, acc2) else Parse.binders(t3, close, acc2) + +def Parse.params {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Coll.List[Ast.Binder]] = Parse.op(ts, "(") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t1) => Parse.binders(t1, ")", Coll.Nil) + +// after the result type: the exit facts +def Parse.exitFacts {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Coll.List[Ast.Atom]] = + if Parse.isOp(ts, "<") then Parse.atoms(Parse.next(ts), Coll.Nil) else Parse.Ok(Coll.Nil, ts) + +// rel(term, ...) , ... up to > +def Parse.atoms {r: Region} (ts: Coll.List[Lex.Tok], acc: Coll.List[Ast.Atom]): Parse.R[Coll.List[Ast.Atom]] = + if Parse.isOp(ts, ">") then Parse.Ok(Coll.rev(acc), Parse.next(ts)) + else Parse.atom(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(a, t1) => if Parse.isOp(t1, ",") then Parse.atoms(Parse.next(t1), Coll.Cons(a, acc)) else Parse.atoms(t1, Coll.Cons(a, acc)) + +def Parse.atom {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Ast.Atom] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(rel, t1) => Parse.op(t1, "(") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t2) => Parse.terms(t2, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(xs, t3) => Parse.Ok(Ast.Atom(Parse.line(ts), rel, xs), t3) + +def Parse.terms {r: Region} (ts: Coll.List[Lex.Tok], acc: Coll.List[Ast.Term]): Parse.R[Coll.List[Ast.Term]] = + if Parse.isOp(ts, ")") then Parse.Ok(Coll.rev(acc), Parse.next(ts)) + else + val tm: Parse.R[Ast.Term] = Parse.peek(ts) match + case Lex.TInt(v, _) => Parse.Ok(Ast.TNum(v), Parse.next(ts)) + case Lex.TIdent(x, _) => Parse.Ok(Ast.TName(Sym.of(x)), Parse.next(ts)) + case _ => Parse.Err(Parse.line(ts), "term") + tm match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(t, t1) => if Parse.isOp(t1, ",") then Parse.terms(Parse.next(t1), Coll.Cons(t, acc)) else Parse.terms(t1, Coll.Cons(t, acc)) + +// ty := name [ [ty, ...] ] [ (expr, ...) ] [ ^ ]: type args, compile-time value args, caps +def Parse.ty {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Ast.Ty] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(name, t1) => + val targs: Parse.R[Coll.List[Ast.Ty]] = if Parse.isOp(t1, "[") then Parse.tys(Parse.next(t1), "]", Coll.Nil) else Parse.Ok(Coll.Nil, t1) + targs match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(args, t2) => + val tvals: Parse.R[Coll.List[Ast.Expr]] = if Parse.isOp(t2, "(") then Parse.args(t2) else Parse.Ok(Coll.Nil, t2) + tvals match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(vals, t3) => + if Parse.isOp(t3, "^") then + Parse.op(Parse.next(t3), "<") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t4) => Parse.names(t4, ">", Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(cs, t5) => Parse.Ok(Ast.Ty(Parse.line(ts), name, args, Ast.Stated(cs), vals), t5) + else Parse.Ok(Ast.Ty(Parse.line(ts), name, args, Ast.Inferred, vals), t3) + +def Parse.tys {r: Region} (ts: Coll.List[Lex.Tok], close: Str, acc: Coll.List[Ast.Ty]): Parse.R[Coll.List[Ast.Ty]] = + if Parse.isOp(ts, close) then Parse.Ok(Coll.rev(acc), Parse.next(ts)) + else Parse.ty(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(t, t1) => if Parse.isOp(t1, ",") then Parse.tys(Parse.next(t1), close, Coll.Cons(t, acc)) else Parse.tys(t1, close, Coll.Cons(t, acc)) + +// names separated by commas up to close (close consumed) +def Parse.names {r: Region} (ts: Coll.List[Lex.Tok], close: Str, acc: Coll.List[Sym.Sym]): Parse.R[Coll.List[Sym.Sym]] = + if Parse.isOp(ts, close) then Parse.Ok(Coll.rev(acc), Parse.next(ts)) + else Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(x, t1) => if Parse.isOp(t1, ",") then Parse.names(Parse.next(t1), close, Coll.Cons(x, acc)) else Parse.names(t1, close, Coll.Cons(x, acc)) + +// names separated by commas to the end of a line (at least one) +def Parse.nameLine {r: Region} (ts: Coll.List[Lex.Tok], acc: Coll.List[Sym.Sym]): Parse.R[Coll.List[Sym.Sym]] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(x, t1) => if Parse.isOp(t1, ",") then Parse.nameLine(Parse.next(t1), Coll.Cons(x, acc)) else Parse.Ok(Coll.rev(Coll.Cons(x, acc)), t1) + +// ── enum: enum Name groups: NL IND (case Name [(fields)] NL)* DED ── +def Parse.enumDecl {r: Region} (ts: Coll.List[Lex.Tok], line: I64): Parse.R[Ast.Decl] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(name, t1) => Parse.groups(t1, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(gs, t2) => Parse.layoutOpen(t2) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t3) => Parse.cases(t3, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(cs, t4) => Parse.Ok(Ast.DEnum(Ast.Enum(line, name, gs, cs)), t4) + +def Parse.cases {r: Region} (ts: Coll.List[Lex.Tok], acc: Coll.List[Ast.Case]): Parse.R[Coll.List[Ast.Case]] = + if Parse.isDedent(ts) then Parse.Ok(Coll.rev(acc), Parse.next(ts)) + else Parse.kw(ts, "case") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(line, t1) => Parse.ident(t1) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(name, t2) => + if Parse.isOp(t2, "(") then + Parse.params(t2) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(fs, t3) => Parse.cases(Parse.endLine(t3), Coll.Cons(Ast.Case(line, name, fs), acc)) + else Parse.cases(Parse.endLine(t2), Coll.Cons(Ast.Case(line, name, Coll.Nil), acc)) + +// ── protocol: items until DED (state, start, end, drop, op, rule def) ── +enum Parse.Pr: + case Parse.Pr(states: Coll.List[Sym.Sym], start: Sym.Sym, ends: Coll.List[Sym.Sym], drop: Coll.Option[Sym.Sym], ops: Coll.List[Ast.Op], rules: Coll.List[Ast.RuleDef]) + +def Parse.proto {r: Region} (ts: Coll.List[Lex.Tok], line: I64): Parse.R[Ast.Decl] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(name, t1) => Parse.layoutOpen(t1) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t2) => Parse.items(t2, Parse.Pr(Coll.Nil, Sym.of(""), Coll.Nil, Coll.None, Coll.Nil, Coll.Nil)) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(pr, t3) => + val Parse.Pr(ss, st, es, dr, os, rs) = pr + Parse.Ok(Ast.DProto(Ast.Proto(line, name, ss, st, es, dr, Coll.rev(os), Coll.rev(rs))), t3) + +def Parse.items {r: Region} (ts: Coll.List[Lex.Tok], pr: Parse.Pr): Parse.R[Parse.Pr] = + val Parse.Pr(ss, st, es, dr, os, rs) = pr + if Parse.isDedent(ts) then Parse.Ok(pr, Parse.next(ts)) + else if Parse.isKw(ts, "state") then + Parse.nameLine(Parse.next(ts), Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(xs, t1) => Parse.items(Parse.endLine(t1), Parse.Pr(xs, st, es, dr, os, rs)) + else if Parse.isKw(ts, "start") then + Parse.ident(Parse.next(ts)) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(x, t1) => Parse.items(Parse.endLine(t1), Parse.Pr(ss, x, es, dr, os, rs)) + else if Parse.isKw(ts, "end") then + Parse.nameLine(Parse.next(ts), Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(xs, t1) => Parse.items(Parse.endLine(t1), Parse.Pr(ss, st, xs, dr, os, rs)) + else if Parse.isKw(ts, "drop") then + Parse.ident(Parse.next(ts)) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(x, t1) => Parse.items(Parse.endLine(t1), Parse.Pr(ss, st, es, Coll.Some(x), os, rs)) + else if Parse.isKw(ts, "op") then + Parse.opDecl(Parse.next(ts), Parse.line(ts)) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(o, t1) => Parse.items(Parse.endLine(t1), Parse.Pr(ss, st, es, dr, Coll.Cons(o, os), rs)) + else if Parse.isKw(ts, "rule") then + Parse.kw(Parse.next(ts), "def") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t1) => Parse.ruleDecl(t1, Parse.line(ts)) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(rd, t2) => Parse.items(Parse.endLine(t2), Parse.Pr(ss, st, es, dr, os, Coll.Cons(rd, rs))) + else Parse.Err(Parse.line(ts), "protocol item") + +// op name(params): ty : A -> B, ... +def Parse.opDecl {r: Region} (ts: Coll.List[Lex.Tok], line: I64): Parse.R[Ast.Op] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(name, t1) => Parse.params(t1) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(ps, t2) => Parse.op(t2, ":") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t3) => Parse.ty(t3) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(ret, t4) => Parse.op(t4, ":") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t5) => Parse.trans(t5, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(trs, t6) => Parse.Ok(Ast.Op(line, name, ps, ret, trs), t6) + +def Parse.trans {r: Region} (ts: Coll.List[Lex.Tok], acc: Coll.List[Ast.Trans]): Parse.R[Coll.List[Ast.Trans]] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(a, t1) => Parse.op(t1, "-") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t2) => Parse.op(t2, ">") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t3) => Parse.ident(t3) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(b, t4) => + val acc2 = Coll.Cons(Ast.Trans(a, b), acc) + if Parse.isOp(t4, ",") then Parse.trans(Parse.next(t4), acc2) else Parse.Ok(Coll.rev(acc2), t4) + +// rule def name(params) = atom, ... +def Parse.ruleDecl {r: Region} (ts: Coll.List[Lex.Tok], line: I64): Parse.R[Ast.RuleDef] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(name, t1) => Parse.op(t1, "(") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t2) => Parse.names(t2, ")", Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(ps, t3) => Parse.op(t3, "=") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t4) => Parse.ruleBody(t4, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(as, t5) => Parse.Ok(Ast.RuleDef(line, name, ps, as), t5) + +def Parse.ruleBody {r: Region} (ts: Coll.List[Lex.Tok], acc: Coll.List[Ast.Atom]): Parse.R[Coll.List[Ast.Atom]] = Parse.atom(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(a, t1) => if Parse.isOp(t1, ",") then Parse.ruleBody(Parse.next(t1), Coll.Cons(a, acc)) else Parse.Ok(Coll.rev(Coll.Cons(a, acc)), t1) + +// ── handler: handler Name for Proto: NL IND (def ...)* DED ── +def Parse.handler {r: Region} (ts: Coll.List[Lex.Tok], line: I64): Parse.R[Ast.Decl] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(name, t1) => Parse.kw(t1, "for") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t2) => Parse.ident(t2) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(proto, t3) => Parse.layoutOpen(t3) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t4) => Parse.defs(t4, false, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(fs, t5) => Parse.Ok(Ast.DHandler(Ast.Handler(line, name, proto, fs)), t5) + +// ── bodies: rhs := NL IND block | expr ── +def Parse.rhs {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Ast.Expr] = + if Parse.isNl(ts) && Parse.isIndent(Parse.next(ts)) then Parse.block(Parse.next(Parse.next(ts)), Parse.line(Parse.next(ts))) + else Parse.expr(ts) + +// a block: statements until DED (a NL between them is optional); its value is the last statement when it is an +// expression, else Unit. val C(a, b) = e takes the rest of the block as the body of a one-arm match +def Parse.block {r: Region} (ts: Coll.List[Lex.Tok], line: I64): Parse.R[Ast.Expr] = Parse.stmts(ts, line, Coll.Nil) + +def Parse.stmts {r: Region} (ts: Coll.List[Lex.Tok], line: I64, acc: Coll.List[Ast.Stmt]): Parse.R[Ast.Expr] = + val t0 = Parse.skipNl(ts) + if Parse.isDedent(t0) then Parse.Ok(Parse.blockOf(line, acc), Parse.next(t0)) + else if Parse.isKw(t0, "val") && Parse.isPatVal(Parse.next(t0)) then Parse.patVal(Parse.next(t0), Parse.line(t0), line, acc) + else Parse.stmt(t0) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(s, t1) => Parse.stmts(t1, line, Coll.Cons(s, acc)) + +// the block of the statements acc (reversed): a last expression statement is the value +def Parse.blockOf {r: Region} (line: I64, acc: Coll.List[Ast.Stmt]): Ast.Expr = acc match + case Coll.Nil => Ast.Block(line, Coll.Nil, Ast.Unit(line)) + case Coll.Cons(s, rest) => s match + case Ast.Do(e) => Ast.Block(line, Coll.rev(rest), e) + case _ => Ast.Block(line, Coll.rev(acc), Ast.Unit(line)) + +// val Upper(...) = e: the name starts with an upper case letter and ( follows +def Parse.isPatVal {r: Region} (ts: Coll.List[Lex.Tok]): Bool = Parse.peek(ts) match + case Lex.TIdent(x, _) => rt_str_at(x, 0) >= 'A' && rt_str_at(x, 0) <= 'Z' && Parse.opIs(Parse.second(ts), "(") + case _ => false + +def Parse.patVal {r: Region} (ts: Coll.List[Lex.Tok], vline: I64, line: I64, acc: Coll.List[Ast.Stmt]): Parse.R[Ast.Expr] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(c, t1) => Parse.op(t1, "(") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t2) => Parse.names(t2, ")", Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(bs, t3) => Parse.op(t3, "=") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t4) => Parse.rhs(t4) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(e, t5) => Parse.stmts(t5, vline, Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(body, t6) => + val m = Ast.Match(vline, e, Coll.Cons(Ast.Arm(vline, Ast.PCase(c, bs), body), Coll.Nil)) + Parse.Ok(Parse.blockOf(line, Coll.Cons(Ast.Do(m), acc)), t6) + +def Parse.stmt {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Ast.Stmt] = + if Parse.isKw(ts, "val") || Parse.isKw(ts, "var") then Parse.valStmt(Parse.next(ts), Parse.line(ts), Parse.isKw(ts, "var")) + else if Parse.isKw(ts, "handle") then Parse.handleStmt(Parse.next(ts), Parse.line(ts)) + else if Parse.isKw(ts, "invariant") || Parse.isKw(ts, "decreases") then + Parse.expr(Parse.next(ts)) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(e, t1) => Parse.Ok(Ast.Check(Parse.line(ts), if Parse.isKw(ts, "invariant") then Ast.LInvariant else Ast.LDecreases, e), t1) + else Parse.expr(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(e, t1) => Parse.Ok(Ast.Do(e), t1) + +// val x [: ty] = rhs +def Parse.valStmt {r: Region} (ts: Coll.List[Lex.Tok], line: I64, isVar: Bool): Parse.R[Ast.Stmt] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(x, t1) => + val ann: Parse.R[Coll.Option[Ast.Ty]] = if Parse.isOp(t1, ":") then Parse.someTy(Parse.ty(Parse.next(t1))) else Parse.Ok(Coll.None, t1) + ann match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(a, t2) => Parse.op(t2, "=") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t3) => Parse.rhs(t3) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(e, t4) => Parse.Ok(if isVar then Ast.Var(line, x, a, e) else Ast.Val(line, x, a, e), t4) + +def Parse.someTy {r: Region} (rt: Parse.R[Ast.Ty]): Parse.R[Coll.Option[Ast.Ty]] = rt match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(t, t1) => Parse.Ok(Coll.Some(t), t1) + +// handle x = H(args) +def Parse.handleStmt {r: Region} (ts: Coll.List[Lex.Tok], line: I64): Parse.R[Ast.Stmt] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(x, t1) => Parse.op(t1, "=") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t2) => Parse.ident(t2) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(h, t3) => Parse.args(t3) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(xs, t4) => Parse.Ok(Ast.Handle(line, x, h, xs), t4) + +// ── expressions ── +def Parse.expr {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Ast.Expr] = + if Parse.isKw(ts, "if") then Parse.ifExpr(Parse.next(ts), Parse.line(ts)) + else if Parse.isKw(ts, "while") then Parse.whileExpr(Parse.next(ts), Parse.line(ts)) + else if Parse.isKw(ts, "forall") || Parse.isKw(ts, "exists") then Parse.quant(Parse.next(ts), Parse.line(ts), if Parse.isKw(ts, "forall") then Ast.Forall else Ast.Exists) + else Parse.peek(ts) match + case Lex.TIdent(x, line) => + if Parse.opIs(Parse.second(ts), "=") then + Parse.rhs(Parse.next(Parse.next(ts))) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(e, t1) => Parse.Ok(Ast.Assign(line, Sym.of(x), e), t1) + else Parse.matchOf(Parse.binary(ts, 0)) + case _ => Parse.matchOf(Parse.binary(ts, 0)) + +// forall x: ty => expr, exists x: ty => expr (s1/parse.srs:544-548) +def Parse.quant {r: Region} (ts: Coll.List[Lex.Tok], line: I64, q: Ast.Q): Parse.R[Ast.Expr] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(x, t1) => Parse.op(t1, ":") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t2) => Parse.ty(t2) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(t, t3) => Parse.op(t3, "=>") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t4) => Parse.expr(t4) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(b, t5) => Parse.Ok(Ast.Quant(line, q, x, t, b), t5) + +// e match NL IND (case pat => rhs)* DED: match is postfix on a whole binary expression +def Parse.matchOf {r: Region} (re: Parse.R[Ast.Expr]): Parse.R[Ast.Expr] = re match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(e, t1) => + if Parse.isKw(t1, "match") then + val t2 = Parse.next(t1) + if Parse.isNl(t2) && Parse.isIndent(Parse.next(t2)) then + Parse.arms(Parse.next(Parse.next(t2)), Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(as, t3) => Parse.Ok(Ast.Match(Parse.line(t1), e, as), t3) + else Parse.Err(Parse.line(t2), "match arms") + else re + +def Parse.arms {r: Region} (ts: Coll.List[Lex.Tok], acc: Coll.List[Ast.Arm]): Parse.R[Coll.List[Ast.Arm]] = + if Parse.isDedent(ts) then Parse.Ok(Coll.rev(acc), Parse.next(ts)) + else Parse.kw(ts, "case") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(line, t1) => Parse.pat(t1) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(p, t2) => Parse.op(t2, "=>") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t3) => Parse.rhs(t3) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(b, t4) => Parse.arms(Parse.endLine(t4), Coll.Cons(Ast.Arm(line, p, b), acc)) + +// _ | Name [(names)] +def Parse.pat {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Ast.Pat] = Parse.ident(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(c, t1) => + if rt_str_eq(Sym.str(c), "_") then Parse.Ok(Ast.PAny, t1) + else if Parse.isOp(t1, "(") then + Parse.names(Parse.next(t1), ")", Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(bs, t2) => Parse.Ok(Ast.PCase(c, bs), t2) + else Parse.Ok(Ast.PCase(c, Coll.Nil), t1) + +// if c then rhs [NL] else rhs +def Parse.ifExpr {r: Region} (ts: Coll.List[Lex.Tok], line: I64): Parse.R[Ast.Expr] = Parse.expr(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(c, t1) => Parse.kw(t1, "then") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t2) => Parse.rhs(t2) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(t, t3) => + val t4 = if Parse.isNl(t3) && Parse.kwIs(Parse.second(t3), "else") then Parse.next(t3) else t3 + Parse.kw(t4, "else") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t5) => Parse.rhs(t5) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(e, t6) => Parse.Ok(Ast.If(line, c, t, e), t6) + +// while c do rhs +def Parse.whileExpr {r: Region} (ts: Coll.List[Lex.Tok], line: I64): Parse.R[Ast.Expr] = Parse.expr(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(c, t1) => Parse.kw(t1, "do") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t2) => Parse.rhs(t2) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(b, t3) => Parse.Ok(Ast.While(line, c, b), t3) + +// the binary operator of a token and its level (lowest first), or None (s1/parse.srs:593 opLevel) +enum Parse.BinTok: + case Parse.BinTok(op: Ast.BinOp, level: I64) + +def Parse.binOf {r: Region} (t: Lex.Tok): Coll.Option[Parse.BinTok] = t match + case Lex.TOp(s, _) => + if rt_str_eq(s, "||") then Coll.Some(Parse.BinTok(Ast.Or, 0)) + else if rt_str_eq(s, "&&") then Coll.Some(Parse.BinTok(Ast.And, 1)) + else if rt_str_eq(s, "==") then Coll.Some(Parse.BinTok(Ast.Eq, 2)) + else if rt_str_eq(s, "!=") then Coll.Some(Parse.BinTok(Ast.Ne, 2)) + else if rt_str_eq(s, "<") then Coll.Some(Parse.BinTok(Ast.Lt, 3)) + else if rt_str_eq(s, "<=") then Coll.Some(Parse.BinTok(Ast.Le, 3)) + else if rt_str_eq(s, ">") then Coll.Some(Parse.BinTok(Ast.Gt, 3)) + else if rt_str_eq(s, ">=") then Coll.Some(Parse.BinTok(Ast.Ge, 3)) + else if rt_str_eq(s, "+") then Coll.Some(Parse.BinTok(Ast.Add, 4)) + else if rt_str_eq(s, "-") then Coll.Some(Parse.BinTok(Ast.Sub, 4)) + else if rt_str_eq(s, "*") then Coll.Some(Parse.BinTok(Ast.Mul, 5)) + else if rt_str_eq(s, "/") then Coll.Some(Parse.BinTok(Ast.Div, 5)) + else if rt_str_eq(s, "%") then Coll.Some(Parse.BinTok(Ast.Mod, 5)) + else Coll.None + case _ => Coll.None + +// operators of level >= lvl, left associative +def Parse.binary {r: Region} (ts: Coll.List[Lex.Tok], lvl: I64): Parse.R[Ast.Expr] = Parse.unary(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(lhs, t1) => Parse.binLoop(lhs, t1, lvl) + +def Parse.binLoop {r: Region} (lhs: Ast.Expr, ts: Coll.List[Lex.Tok], lvl: I64): Parse.R[Ast.Expr] = Parse.binOf(Parse.peek(ts)) match + case Coll.None => Parse.Ok(lhs, ts) + case Coll.Some(bt) => + val Parse.BinTok(op, l) = bt + if l < lvl then Parse.Ok(lhs, ts) + else Parse.binary(Parse.next(ts), l + 1) match + case Parse.Err(el, w) => Parse.Err(el, w) + case Parse.Ok(rhs, t2) => Parse.binLoop(Ast.Bin(Parse.line(ts), op, lhs, rhs), t2, lvl) + +def Parse.unary {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Ast.Expr] = + if Parse.isOp(ts, "-") then Parse.unOf(Parse.line(ts), Ast.Neg, Parse.unary(Parse.next(ts))) + else if Parse.isOp(ts, "!") then Parse.unOf(Parse.line(ts), Ast.Not, Parse.unary(Parse.next(ts))) + else Parse.primary(ts) + +def Parse.unOf {r: Region} (line: I64, op: Ast.UnOp, re: Parse.R[Ast.Expr]): Parse.R[Ast.Expr] = re match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(e, t1) => Parse.Ok(Ast.Un(line, op, e), t1) + +// the value of a char literal: one character, or a backslash escape (s1/parse.srs charValue) +def Parse.charValue(s: Str): I64 = + if rt_str_len(s) == 1 then rt_str_at(s, 0) + else + val c = rt_str_at(s, 1) + if c == 'n' then 10 else if c == 't' then 9 else if c == 'r' then 13 else if c == '0' then 0 else c + +def Parse.primary {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Ast.Expr] = Parse.peek(ts) match + case Lex.TInt(v, line) => Parse.Ok(Ast.Int(line, v), Parse.next(ts)) + case Lex.TStr(s, line) => Parse.Ok(Ast.Str(line, s), Parse.next(ts)) + case Lex.TChar(s, line) => Parse.Ok(Ast.Int(line, Parse.charValue(s)), Parse.next(ts)) + case Lex.TIdent(x, line) => + val t1 = Parse.next(ts) + if rt_str_eq(x, "true") then Parse.Ok(Ast.Bool(line, true), t1) + else if rt_str_eq(x, "false") then Parse.Ok(Ast.Bool(line, false), t1) + else if Parse.isOp(t1, "(") then Parse.callOf(line, Sym.of(x), Coll.Nil, Coll.Nil, Parse.args(t1)) + else if Parse.isOp(t1, "[") || Parse.isOp(t1, "{") then Parse.callGroups(t1, line, Sym.of(x), Coll.Nil, Coll.Nil) + else if Parse.isOp(t1, ".") then + Parse.ident(Parse.next(t1)) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(op, t2) => Parse.args(t2) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(xs, t3) => Parse.Ok(Ast.Method(line, Sym.of(x), op, xs), t3) + else Parse.Ok(Ast.Name(line, Sym.of(x)), t1) + case Lex.TOp(s, line) => + if rt_str_eq(s, "(") then + val t1 = Parse.next(ts) + if Parse.isOp(t1, ")") then Parse.Ok(Ast.Unit(line), Parse.next(t1)) + else Parse.expr(t1) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(e, t2) => Parse.op(t2, ")") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t3) => Parse.Ok(e, t3) + else Parse.Err(line, "expression") + case _ => Parse.Err(Parse.line(ts), "expression") + +// f[T, ...]{a, ...}(args): the groups in any order, then the args +def Parse.callGroups {r: Region} (ts: Coll.List[Lex.Tok], line: I64, f: Sym.Sym, targs: Coll.List[Ast.Ty], chosen: Coll.List[Sym.Sym]): Parse.R[Ast.Expr] = + if Parse.isOp(ts, "[") then + Parse.tys(Parse.next(ts), "]", Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(tys, t1) => Parse.callGroups(t1, line, f, Coll.revOnto(Coll.rev(targs), tys), chosen) + else if Parse.isOp(ts, "{") then + Parse.names(Parse.next(ts), "}", Coll.Nil) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(ns, t1) => Parse.callGroups(t1, line, f, targs, Coll.revOnto(Coll.rev(chosen), ns)) + else Parse.callOf(line, f, targs, chosen, Parse.args(ts)) + +def Parse.callOf {r: Region} (line: I64, f: Sym.Sym, targs: Coll.List[Ast.Ty], chosen: Coll.List[Sym.Sym], ra: Parse.R[Coll.List[Ast.Expr]]): Parse.R[Ast.Expr] = ra match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(xs, t1) => Parse.Ok(Ast.Call(line, f, targs, chosen, xs), t1) + +// (expr, ...) +def Parse.args {r: Region} (ts: Coll.List[Lex.Tok]): Parse.R[Coll.List[Ast.Expr]] = Parse.op(ts, "(") match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(_, t1) => Parse.exprs(t1, Coll.Nil) + +def Parse.exprs {r: Region} (ts: Coll.List[Lex.Tok], acc: Coll.List[Ast.Expr]): Parse.R[Coll.List[Ast.Expr]] = + if Parse.isOp(ts, ")") then Parse.Ok(Coll.rev(acc), Parse.next(ts)) + else Parse.expr(ts) match + case Parse.Err(l, w) => Parse.Err(l, w) + case Parse.Ok(e, t1) => if Parse.isOp(t1, ",") then Parse.exprs(Parse.next(t1), Coll.Cons(e, acc)) else Parse.exprs(t1, Coll.Cons(e, acc)) + +// a source: lex, then parse; a lex error is a parse error at its line +def Parse.source {r: Region} (src: Str): Parse.R[Coll.List[Ast.Decl]] = Parse.sourceFrom(src, 1) + +// src whose first line has number line (Lex.lexFrom) +def Parse.sourceFrom {r: Region} (src: Str, line: I64): Parse.R[Coll.List[Ast.Decl]] = Lex.lexFrom(src, line) match + case Lex.Bad(l, _) => Parse.Err(l, "lexable source") + case Lex.Toks(ts) => Parse.file(ts) diff --git a/bench/corpus/s2/pure.srs b/bench/corpus/s2/pure.srs new file mode 100644 index 00000000..191b2a56 --- /dev/null +++ b/bench/corpus/s2/pure.srs @@ -0,0 +1,197 @@ +// s2 PURE (s1/purity.srs, vic-u2d U1b; vic 2026-11-05: pure = no effects): which fns have effects, a Datalog program +// over the source bodies. a protocol is effect-free when every fn of each of its handlers is pure (vic Q-U5). +// impure(F) :- direct(F) | calls(F, G), impure(G) | uses(F, P), effectful(P) +// effectful(P) :- handles(H, P), impureH(H) +// impureH(H) :- hdirect(H) | hcalls(H, G), impure(G) | huses(H, P), effectful(P) + +// every relation; Pure.relSym is the only place a relation name is a string +enum Pure.Rel: + case Pure.RDirect + case Pure.RCalls + case Pure.RUses + case Pure.RHandles + case Pure.RHDirect + case Pure.RHCalls + case Pure.RHUses + case Pure.RImpure + case Pure.REffectful + case Pure.RImpureH + +def Pure.relSym {r: Region} (rel: Pure.Rel): Sym.Sym = rel match + case Pure.RDirect => Sym.of("direct") + case Pure.RCalls => Sym.of("calls") + case Pure.RUses => Sym.of("uses") + case Pure.RHandles => Sym.of("handles") + case Pure.RHDirect => Sym.of("hdirect") + case Pure.RHCalls => Sym.of("hcalls") + case Pure.RHUses => Sym.of("huses") + case Pure.RImpure => Sym.of("impure") + case Pure.REffectful => Sym.of("effectful") + case Pure.RImpureH => Sym.of("impureH") + +// whose facts: a def (direct, calls, uses) or a handler's fn (hdirect, hcalls, huses: the handler is the subject) +enum Pure.Who: + case Pure.Def(f: Sym.Sym) + case Pure.In(h: Sym.Sym) + +def Pure.subj(w: Pure.Who): Sym.Sym = w match + case Pure.Def(f) => f + case Pure.In(h) => h + +def Pure.direct(w: Pure.Who): Pure.Rel = w match + case Pure.Def(_) => Pure.RDirect + case Pure.In(_) => Pure.RHDirect + +def Pure.calls(w: Pure.Who): Pure.Rel = w match + case Pure.Def(_) => Pure.RCalls + case Pure.In(_) => Pure.RHCalls + +def Pure.uses(w: Pure.Who): Pure.Rel = w match + case Pure.Def(_) => Pure.RUses + case Pure.In(_) => Pure.RHUses + +def Pure.f1 {r: Region} (rel: Pure.Rel, a: Sym.Sym): D.Fact = D.Fact(Pure.relSym(rel), Coll.Cons(D.VSym(a), Coll.Nil)) +def Pure.f2 {r: Region} (rel: Pure.Rel, a: Sym.Sym, b: Sym.Sym): D.Fact = D.Fact(Pure.relSym(rel), Coll.Cons(D.VSym(a), Coll.Cons(D.VSym(b), Coll.Nil))) + +def Pure.atom {r: Region} (rel: Pure.Rel, xs: Coll.List[I64]): D.Atom = D.Atom(Pure.relSym(rel), Pure.vars(xs)) +def Pure.vars {r: Region} (xs: Coll.List[I64]): Coll.List[D.Arg] = xs match + case Coll.Nil => Coll.Nil + case Coll.Cons(x, rest) => Coll.Cons(D.AVar(x), Pure.vars(rest)) +def Pure.pos {r: Region} (rel: Pure.Rel, xs: Coll.List[I64]): D.Lit = D.Pos(Pure.atom(rel, xs)) +def Pure.one {r: Region} (x: I64): Coll.List[I64] = Coll.Cons(x, Coll.Nil) +def Pure.two {r: Region} (x: I64, y: I64): Coll.List[I64] = Coll.Cons(x, Pure.one(y)) +def Pure.rule1 {r: Region} (h: Pure.Rel, b: Pure.Rel): D.Rule = D.Rule(Pure.atom(h, Pure.one(0)), Coll.Cons(Pure.pos(b, Pure.one(0)), Coll.Nil)) +// h(0) :- b(0, 1), c(1) +def Pure.rule2 {r: Region} (h: Pure.Rel, b: Pure.Rel, c: Pure.Rel): D.Rule = D.Rule(Pure.atom(h, Pure.one(0)), Coll.Cons(Pure.pos(b, Pure.two(0, 1)), Coll.Cons(Pure.pos(c, Pure.one(1)), Coll.Nil))) + +def Pure.rules {r: Region} (): Coll.List[D.Rule] = + val i1 = Pure.rule1(Pure.RImpure, Pure.RDirect) + val i2 = Pure.rule2(Pure.RImpure, Pure.RCalls, Pure.RImpure) + val i3 = Pure.rule2(Pure.RImpure, Pure.RUses, Pure.REffectful) + // effectful(P) :- handles(H, P), impureH(H): written with P first as the head var + val e1 = D.Rule(Pure.atom(Pure.REffectful, Pure.one(0)), Coll.Cons(Pure.pos(Pure.RHandles, Pure.two(1, 0)), Coll.Cons(Pure.pos(Pure.RImpureH, Pure.one(1)), Coll.Nil))) + val h1 = Pure.rule1(Pure.RImpureH, Pure.RHDirect) + val h2 = Pure.rule2(Pure.RImpureH, Pure.RHCalls, Pure.RImpure) + val h3 = Pure.rule2(Pure.RImpureH, Pure.RHUses, Pure.REffectful) + Coll.Cons(i1, Coll.Cons(i2, Coll.Cons(i3, Coll.Cons(e1, Coll.Cons(h1, Coll.Cons(h2, Coll.Cons(h3, Coll.Nil))))))) + +// the externs with no effect (s1/check.srs:640) +def Pure.pureExtern(n: Sym.Sym): Bool = + val s = Sym.str(n) + rt_str_eq(s, "rt_str_len") || rt_str_eq(s, "rt_str_at") || rt_str_eq(s, "rt_str_slice") || rt_str_eq(s, "rt_str_eq") + +// ── facts ── +def Pure.facts {r: Region} (ds: Coll.List[Ast.Decl]): Coll.List[D.Fact] = Pure.decls(Pure.protos(ds, Coll.Nil), Pure.hprotos(ds, Coll.sEmpty()), ds, Coll.Nil) + +def Pure.protos {r: Region} (ds: Coll.List[Ast.Decl], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = ds match + case Coll.Nil => acc + case Coll.Cons(d, rest) => d match + case Ast.DProto(p) => + val Ast.Proto(_, n, _, _, _, _, _, _) = p + Pure.protos(rest, Coll.Cons(n, acc)) + case _ => Pure.protos(rest, acc) + +def Pure.hprotos {r: Region} (ds: Coll.List[Ast.Decl], m: Coll.SMap[Sym.Sym]): Coll.SMap[Sym.Sym] = ds match + case Coll.Nil => m + case Coll.Cons(d, rest) => d match + case Ast.DHandler(h) => + val Ast.Handler(_, n, p, _) = h + Pure.hprotos(rest, Coll.sInsert(m, n, p)) + case _ => Pure.hprotos(rest, m) + +def Pure.decls {r: Region} (ps: Coll.List[Sym.Sym], hp: Coll.SMap[Sym.Sym], ds: Coll.List[Ast.Decl], acc: Coll.List[D.Fact]): Coll.List[D.Fact] = ds match + case Coll.Nil => acc + case Coll.Cons(d, rest) => d match + case Ast.DFn(f) => + val Ast.Fn(_, n, _, _, _, _, _) = f + Pure.decls(ps, hp, rest, Pure.fn(ps, hp, Pure.Def(n), f, acc)) + case Ast.DHandler(h) => + val Ast.Handler(_, n, p, fs) = h + Pure.decls(ps, hp, rest, Pure.fns(ps, hp, Pure.In(n), fs, Coll.Cons(Pure.f2(Pure.RHandles, n, p), acc))) + case _ => Pure.decls(ps, hp, rest, acc) + +def Pure.fns {r: Region} (ps: Coll.List[Sym.Sym], hp: Coll.SMap[Sym.Sym], w: Pure.Who, fs: Coll.List[Ast.Fn], acc: Coll.List[D.Fact]): Coll.List[D.Fact] = fs match + case Coll.Nil => acc + case Coll.Cons(f, rest) => Pure.fns(ps, hp, w, rest, Pure.fn(ps, hp, w, f, acc)) + +// an extern not in the pure set is a direct effect; a {} binder of a protocol uses it, any other {} binder is evidence +def Pure.fn {r: Region} (ps: Coll.List[Sym.Sym], hp: Coll.SMap[Sym.Sym], w: Pure.Who, f: Ast.Fn, acc: Coll.List[D.Fact]): Coll.List[D.Fact] = + val Ast.Fn(_, n, gs, _, _, _, body) = f + val Pure.Ev(ev, acc2) = Pure.binders(ps, w, Ty.evidence(gs, Coll.Nil), Coll.Nil, acc) + body match + case Ast.Extern => if Pure.pureExtern(n) then acc2 else Coll.Cons(Pure.f1(Pure.direct(w), Pure.subj(w)), acc2) + case Ast.Def(_, e) => Pure.expr(hp, w, ev, e, acc2) + case Ast.Spec(_, e) => Pure.expr(hp, w, ev, e, acc2) + +enum Pure.Ev: + case Pure.Ev(ev: Coll.List[Sym.Sym], acc: Coll.List[D.Fact]) + +def Pure.binders {r: Region} (ps: Coll.List[Sym.Sym], w: Pure.Who, bs: Coll.List[Ast.Binder], ev: Coll.List[Sym.Sym], acc: Coll.List[D.Fact]): Pure.Ev = bs match + case Coll.Nil => Pure.Ev(ev, acc) + case Coll.Cons(b, rest) => + val Ast.Binder(_, x, t) = b + val Ast.Ty(_, tn, _, _, _) = t + if Ty.memberSym(tn, ps) then Pure.binders(ps, w, rest, ev, Coll.Cons(Pure.f2(Pure.uses(w), Pure.subj(w), tn), acc)) + else Pure.binders(ps, w, rest, Coll.Cons(x, ev), acc) + +// a call is calls(who, f); a handle uses the handler's protocol; a method on {} evidence is a direct effect (the given +// that answers it is not known before mono) +def Pure.expr {r: Region} (hp: Coll.SMap[Sym.Sym], w: Pure.Who, ev: Coll.List[Sym.Sym], e: Ast.Expr, acc: Coll.List[D.Fact]): Coll.List[D.Fact] = e match + case Ast.Name(_, x) => Coll.Cons(Pure.f2(Pure.calls(w), Pure.subj(w), x), acc) + case Ast.Call(_, f, _, _, xs) => Pure.exprs(hp, w, ev, xs, Coll.Cons(Pure.f2(Pure.calls(w), Pure.subj(w), f), acc)) + case Ast.Method(_, recv, _, xs) => + val acc2 = if Ty.memberSym(recv, ev) then Coll.Cons(Pure.f1(Pure.direct(w), Pure.subj(w)), acc) else acc + Pure.exprs(hp, w, ev, xs, acc2) + case Ast.Bin(_, _, l, x) => Pure.expr(hp, w, ev, x, Pure.expr(hp, w, ev, l, acc)) + case Ast.Un(_, _, x) => Pure.expr(hp, w, ev, x, acc) + case Ast.If(_, c, t, x) => Pure.expr(hp, w, ev, x, Pure.expr(hp, w, ev, t, Pure.expr(hp, w, ev, c, acc))) + case Ast.Match(_, s, arms) => Pure.arms(hp, w, ev, arms, Pure.expr(hp, w, ev, s, acc)) + case Ast.Block(_, ss, last) => Pure.expr(hp, w, ev, last, Pure.stmts(hp, w, ev, ss, acc)) + case Ast.While(_, c, b) => Pure.expr(hp, w, ev, b, Pure.expr(hp, w, ev, c, acc)) + case Ast.Assign(_, _, x) => Pure.expr(hp, w, ev, x, acc) + case _ => acc + +def Pure.exprs {r: Region} (hp: Coll.SMap[Sym.Sym], w: Pure.Who, ev: Coll.List[Sym.Sym], xs: Coll.List[Ast.Expr], acc: Coll.List[D.Fact]): Coll.List[D.Fact] = xs match + case Coll.Nil => acc + case Coll.Cons(x, rest) => Pure.exprs(hp, w, ev, rest, Pure.expr(hp, w, ev, x, acc)) + +def Pure.arms {r: Region} (hp: Coll.SMap[Sym.Sym], w: Pure.Who, ev: Coll.List[Sym.Sym], as: Coll.List[Ast.Arm], acc: Coll.List[D.Fact]): Coll.List[D.Fact] = as match + case Coll.Nil => acc + case Coll.Cons(a, rest) => + val Ast.Arm(_, _, b) = a + Pure.arms(hp, w, ev, rest, Pure.expr(hp, w, ev, b, acc)) + +def Pure.stmts {r: Region} (hp: Coll.SMap[Sym.Sym], w: Pure.Who, ev: Coll.List[Sym.Sym], ss: Coll.List[Ast.Stmt], acc: Coll.List[D.Fact]): Coll.List[D.Fact] = ss match + case Coll.Nil => acc + case Coll.Cons(s, rest) => s match + case Ast.Val(_, _, _, e) => Pure.stmts(hp, w, ev, rest, Pure.expr(hp, w, ev, e, acc)) + case Ast.Var(_, _, _, e) => Pure.stmts(hp, w, ev, rest, Pure.expr(hp, w, ev, e, acc)) + case Ast.Handle(_, _, h, xs) => + val acc2 = Coll.sLookup(hp, h) match + case Coll.Some(p) => Coll.Cons(Pure.f2(Pure.uses(w), Pure.subj(w), p), acc) + case Coll.None => acc + Pure.stmts(hp, w, ev, rest, Pure.exprs(hp, w, ev, xs, acc2)) + case Ast.Do(e) => Pure.stmts(hp, w, ev, rest, Pure.expr(hp, w, ev, e, acc)) + case Ast.Check(_, _, e) => Pure.stmts(hp, w, ev, rest, Pure.expr(hp, w, ev, e, acc)) + +// ── the fns with effects, by name; a rule library that is not Datalog is a bug, as data ── +enum Pure.Set: + case Pure.Got(impure: Coll.SMap[Bool]) + case Pure.RulesBad(rel: Sym.Sym) + +def Pure.impure {r: Region} (ds: Coll.List[Ast.Decl]): Pure.Set = D.solve(Pure.rules(), Pure.facts(ds)) match + case D.Solved(m) => Pure.Got(Pure.names(D.tuples(m, Pure.relSym(Pure.RImpure)), Coll.sEmpty())) + case D.Unsafe(rel) => Pure.RulesBad(rel) + case D.NegCycle(rel) => Pure.RulesBad(rel) + +def Pure.names {r: Region} (ts: Coll.List[Coll.List[D.Val]], m: Coll.SMap[Bool]): Coll.SMap[Bool] = ts match + case Coll.Nil => m + case Coll.Cons(t, rest) => t match + case Coll.Cons(v, _) => v match + case D.VSym(n) => Pure.names(rest, Coll.sInsert(m, n, true)) + case D.VInt(_) => Pure.names(rest, m) + case Coll.Nil => Pure.names(rest, m) + +def Pure.has {r: Region} (m: Coll.SMap[Bool], n: Sym.Sym): Bool = Coll.sLookup(m, n) match + case Coll.Some(_) => true + case Coll.None => false diff --git a/bench/corpus/s2/queue.srs b/bench/corpus/s2/queue.srs new file mode 100644 index 00000000..a01ff061 --- /dev/null +++ b/bench/corpus/s2/queue.srs @@ -0,0 +1,28 @@ +// a persistent FIFO queue (s2 component 2, vic 2026-11-06): Okasaki's two lists, front in order, back reversed. +// push O(1); pop O(1) amortized (the back is reversed once, when the front runs out). the fair search queue. +enum Queue.Queue [A: Type]: + case Queue.Queue(front: Coll.List[A], back: Coll.List[A]) + +// a pop: the queue was empty, or its first element and the rest +enum Queue.Popped [A: Type]: + case Queue.Empty + case Queue.Got(x: A, rest: Queue.Queue[A]) + +def Queue.empty [A: Type] {r: Region} (): Queue.Queue[A] = Queue.Queue(Coll.Nil, Coll.Nil) + +def Queue.push [A: Type] {r: Region} (q: Queue.Queue[A], x: A): Queue.Queue[A] = + val Queue.Queue(f, b) = q + Queue.Queue(f, Coll.Cons(x, b)) + +// each of xs pushed, in order +def Queue.pushAll [A: Type] {r: Region} (q: Queue.Queue[A], xs: Coll.List[A]): Queue.Queue[A] = xs match + case Coll.Nil => q + case Coll.Cons(x, t) => Queue.pushAll(Queue.push(q, x), t) + +def Queue.pop [A: Type] {r: Region} (q: Queue.Queue[A]): Queue.Popped[A] = + val Queue.Queue(f, b) = q + f match + case Coll.Cons(x, t) => Queue.Got(x, Queue.Queue(t, b)) + case Coll.Nil => Coll.rev(b) match + case Coll.Nil => Queue.Empty + case Coll.Cons(x, t) => Queue.Got(x, Queue.Queue(t, Coll.Nil)) diff --git a/bench/corpus/s2/store.srs b/bench/corpus/s2/store.srs new file mode 100644 index 00000000..802a296e --- /dev/null +++ b/bench/corpus/s2/store.srs @@ -0,0 +1,103 @@ +// s2 store (s1/store.srs, vic-uw3 H2; vic 2026-11-06: Nix-like, content addressed): an entry = one decl as the printer +// writes it (Ast.decl; parse(print(d)) prints as d, the printer fixpoint), keyed by its content hash (s2/hash.srs). +// IO driver: an entry is written only through protocol StoreOut, so a write that does not commit does not compile. +extern def rt_store_dir(): Str +extern def rt_out_new(dir: Str, a: I64, b: I64, c: I64, d: I64): Ptr +extern def rt_out_str(self: Ptr, s: Str): Unit +extern def rt_out_i64(self: Ptr, n: I64): Unit +extern def rt_out_commit(self: Ptr): Unit +extern def rt_store_read(dir: Str, a: I64, b: I64, c: I64, d: I64): Str +// what rt_print and rt_print_i64 write between begin and end, as one string +extern def rt_capture_begin(): Unit +extern def rt_capture_end(): Str + +// an entry is open until commit renames it into place +protocol StoreOut: + state Writing, Done + start Writing + end Done + op put(s: Str): Unit : Writing -> Writing + op commit(): Unit : Writing -> Done + +handler StoreFile for StoreOut: + def init(dir: Str, a: I64, b: I64, c: I64, d: I64): Ptr = rt_out_new(dir, a, b, c, d) + def put(self: Ptr, s: Str): Unit = rt_out_str(self, s) + def commit(self: Ptr): Unit = rt_out_commit(self) + +// a decl as the printer writes it +def Store.text {r: Region} (d: Ast.Decl): Str = + rt_capture_begin() + Ast.decl(d) + rt_capture_end() + +def Store.write {r: Region} (dir: Str, g: Hs.Dg, s: Str): Unit = + val Hs.Dg(a, b, c, d) = g + handle o = StoreFile(dir, a, b, c, d) + o.put(s) + o.commit() + +def Store.read {r: Region} (dir: Str, g: Hs.Dg): Str = + val Hs.Dg(a, b, c, d) = g + rt_store_read(dir, a, b, c, d) + +// an entry reads back as the decl when it parses to exactly one decl that prints as the original +def Store.same {r: Region} (entry: Str, want: Str): Bool = + if rt_str_len(entry) < 0 then false + else Parse.source(entry) match + case Parse.Ok(ds, _) => ds match + case Coll.Cons(x, rest) => rest match + case Coll.Nil => rt_str_eq(Store.text(x), want) + case Coll.Cons(_, _) => false + case Coll.Nil => false + case Parse.Err(_, _) => false + +enum Store.Tally: + case Store.Tally(wrote: I64, same: I64, shared: I64, bad: I64, seen: Coll.List[Hs.Dg]) + +def Store.seen(gs: Coll.List[Hs.Dg], g: Hs.Dg): Bool = gs match + case Coll.Nil => false + case Coll.Cons(h, rest) => if !Hs.less(g, h) && !Hs.less(h, g) then true else Store.seen(rest, g) + +// `s2c --store-check`: write every hashed decl, read each back, compare (vic-uw3 H2 oracle); a later decl with a hash +// met before shares the entry (names are metadata) +def Store.check {r: Region} (ds: Coll.List[Ast.Decl]): Unit = + val Store.Tally(w, s, sh, b, _) = Store.decls(rt_store_dir(), Hs.all(ds), ds, Store.Tally(0, 0, 0, 0, Coll.Nil)) + rt_print("store: wrote ") + rt_print_i64(w) + rt_print(", read equal ") + rt_print_i64(s) + rt_print(", shared ") + rt_print_i64(sh) + rt_print(", bad ") + rt_print_i64(b) + rt_print("\n") + +def Store.decls {r: Region} (dir: Str, hm: Coll.SMap[Hs.Dg], ds: Coll.List[Ast.Decl], t: Store.Tally): Store.Tally = ds match + case Coll.Nil => t + case Coll.Cons(d, rest) => + val n: Coll.Option[Sym.Sym] = d match + case Ast.DEnum(e) => + val Ast.Enum(_, en, _, _) = e + Coll.Some(en) + case Ast.DFn(f) => + val Ast.Fn(_, fname, _, _, _, _, _) = f + Coll.Some(fname) + case _ => Coll.None + val g: Coll.Option[Hs.Dg] = n match + case Coll.Some(x) => Coll.sLookup(hm, x) + case Coll.None => Coll.None + g match + case Coll.None => Store.decls(dir, hm, rest, t) + case Coll.Some(h) => Store.decls(dir, hm, rest, Store.one(dir, h, Store.text(d), t)) + +def Store.one {r: Region} (dir: Str, g: Hs.Dg, want: Str, t: Store.Tally): Store.Tally = + val Store.Tally(w, s, sh, b, seen) = t + val w2 = if rt_str_len(Store.read(dir, g)) < 0 then Store.wrote(dir, g, want, w) else w + val seen2 = Coll.Cons(g, seen) + if Store.seen(seen, g) then Store.Tally(w2, s, sh + 1, b, seen2) + else if Store.same(Store.read(dir, g), want) then Store.Tally(w2, s + 1, sh, b, seen2) + else Store.Tally(w2, s, sh, b + 1, seen2) + +def Store.wrote {r: Region} (dir: Str, g: Hs.Dg, s: Str, w: I64): I64 = + Store.write(dir, g, s) + w + 1 diff --git a/bench/corpus/s2/sym.srs b/bench/corpus/s2/sym.srs new file mode 100644 index 00000000..bebd2cad --- /dev/null +++ b/bench/corpus/s2/sym.srs @@ -0,0 +1,19 @@ +// a name with its hash (s2 component 1, vic 2026-11-06): two names compare as integers; their strings are compared +// only on a hash tie. no global table: a Sym carries its own hash. +enum Sym.Sym: + case Sym.Sym(h: I64, s: Str) + +def Sym.of {r: Region} (s: Str): Sym.Sym = Sym.Sym(strHash(s), s) + +def Sym.hash(a: Sym.Sym): I64 = + val Sym.Sym(h, _) = a + h + +def Sym.str(a: Sym.Sym): Str = + val Sym.Sym(_, s) = a + s + +def Sym.eq(a: Sym.Sym, b: Sym.Sym): Bool = + val Sym.Sym(h1, s1) = a + val Sym.Sym(h2, s2) = b + h1 == h2 && rt_str_eq(s1, s2) diff --git a/bench/corpus/s2/tlevel.srs b/bench/corpus/s2/tlevel.srs new file mode 100644 index 00000000..a06317fa --- /dev/null +++ b/bench/corpus/s2/tlevel.srs @@ -0,0 +1,607 @@ +// s2 type level (vic-m5r.30, s1/types.srs:1-134): every type of the program with its type decls applied, before typing. +// type F [A: Type] = T: F[X] is T with A := X; a match type reduces by its first case whose pattern is the scrutinee; +// a value match (type B (n: I64) = n match ...) by its first case that the value arg, evaluated at compile time, fits. +// each reduction step and each evaluated call costs fuel: a loop is a reject. every error is data (Tl.Err). + +enum Tl.Err: + case Tl.Fuel(line: I64, n: Sym.Sym) + case Tl.NoCase(line: I64, n: Sym.Sym) + case Tl.BadVal(line: I64, n: Sym.Sym) + case Tl.Arity(line: I64, n: Sym.Sym) + // value args on a type with no () binders; a value arg that does not fit its binder's type; a () binder of a type that + // has no compile-time values (I64, Bool and Str have); a value match pattern that does not fit its binder's type + case Tl.NoVals(line: I64, n: Sym.Sym) + case Tl.ArgType(line: I64, n: Sym.Sym) + case Tl.BinderType(line: I64, x: Sym.Sym) + case Tl.PatType(line: I64, n: Sym.Sym) + +// a value and the errors so far +enum Tl.W [A: Type]: + case Tl.W(v: A, es: Coll.List[Tl.Err]) + +// a compile-time value +enum Tl.V: + case Tl.VI(v: I64) + case Tl.VB(v: Bool) + case Tl.VS(s: Str) + +enum Tl.Bv: + case Tl.Bv(x: Sym.Sym, v: Tl.V) + +// a [] binder of a type decl bound to its arg +enum Tl.Bt: + case Tl.Bt(x: Sym.Sym, t: Ast.Ty) + +// the type decls and the defs (value args call pure defs), by name +enum Tl.Cx: + case Tl.Cx(ts: Coll.SMap[Ast.TypeDecl], fs: Coll.SMap[Ast.Fn]) + +def Tl.fuel(): I64 = 1000 + +// ── the program ── +def Tl.expand {r: Region} (ds: Coll.List[Ast.Decl]): Tl.W[Coll.List[Ast.Decl]] = + val cx = Tl.cxOf(ds, Coll.sEmpty(), Coll.sEmpty()) + Tl.decls(cx, ds, Coll.Nil, Coll.Nil) + +def Tl.cxOf {r: Region} (ds: Coll.List[Ast.Decl], ts: Coll.SMap[Ast.TypeDecl], fs: Coll.SMap[Ast.Fn]): Tl.Cx = ds match + case Coll.Nil => Tl.Cx(ts, fs) + case Coll.Cons(d, rest) => d match + case Ast.DType(td) => + val Ast.TypeDecl(_, n, _, _, _) = td + Tl.cxOf(rest, Coll.sInsert(ts, n, td), fs) + case Ast.DFn(f) => + val Ast.Fn(_, n, _, _, _, _, _) = f + Tl.cxOf(rest, ts, Coll.sInsert(fs, n, f)) + case _ => Tl.cxOf(rest, ts, fs) + +def Tl.decls {r: Region} (cx: Tl.Cx, ds: Coll.List[Ast.Decl], acc: Coll.List[Ast.Decl], es: Coll.List[Tl.Err]): Tl.W[Coll.List[Ast.Decl]] = ds match + case Coll.Nil => Tl.W(Coll.rev(acc), es) + case Coll.Cons(d, rest) => + val Tl.W(d2, es2) = Tl.decl(cx, d, es) + Tl.decls(cx, rest, Coll.Cons(d2, acc), es2) + +def Tl.decl {r: Region} (cx: Tl.Cx, d: Ast.Decl, es: Coll.List[Tl.Err]): Tl.W[Ast.Decl] = d match + case Ast.DFn(f) => + val Tl.W(f2, es2) = Tl.fn(cx, f, es) + Tl.W(Ast.DFn(f2), es2) + case Ast.DEnum(e) => + val Ast.Enum(line, n, gs, cases) = e + val Tl.W(gs2, es2) = Tl.groups(cx, gs, Coll.Nil, es) + val Tl.W(cs2, es3) = Tl.cases(cx, cases, Coll.Nil, es2) + Tl.W(Ast.DEnum(Ast.Enum(line, n, gs2, cs2)), es3) + case Ast.DProto(p) => + val Ast.Proto(line, n, sts, st, ends, dop, ops, rules) = p + val Tl.W(ops2, es2) = Tl.ops(cx, ops, Coll.Nil, es) + Tl.W(Ast.DProto(Ast.Proto(line, n, sts, st, ends, dop, ops2, rules)), es2) + case Ast.DHandler(h) => + val Ast.Handler(line, n, p, fs) = h + val Tl.W(fs2, es2) = Tl.fns(cx, fs, Coll.Nil, es) + Tl.W(Ast.DHandler(Ast.Handler(line, n, p, fs2)), es2) + case Ast.DTrait(t) => + val Ast.Trait(line, n, gs, sigs) = t + val Tl.W(gs2, es2) = Tl.groups(cx, gs, Coll.Nil, es) + val Tl.W(sigs2, es3) = Tl.fns(cx, sigs, Coll.Nil, es2) + Tl.W(Ast.DTrait(Ast.Trait(line, n, gs2, sigs2)), es3) + case Ast.DGiven(g) => + val Ast.Given(line, gs, head, fs) = g + val Tl.W(gs2, es2) = Tl.groups(cx, gs, Coll.Nil, es) + val Tl.W(h2, es3) = Tl.ty(cx, Coll.Nil, Coll.Nil, head, Tl.fuel(), es2) + val Tl.W(fs2, es4) = Tl.fns(cx, fs, Coll.Nil, es3) + Tl.W(Ast.DGiven(Ast.Given(line, gs2, h2, fs2)), es4) + case Ast.DType(td) => Tl.W(d, Tl.typeDecl(td, es)) + +def Tl.fns {r: Region} (cx: Tl.Cx, fs: Coll.List[Ast.Fn], acc: Coll.List[Ast.Fn], es: Coll.List[Tl.Err]): Tl.W[Coll.List[Ast.Fn]] = fs match + case Coll.Nil => Tl.W(Coll.rev(acc), es) + case Coll.Cons(f, rest) => + val Tl.W(f2, es2) = Tl.fn(cx, f, es) + Tl.fns(cx, rest, Coll.Cons(f2, acc), es2) + +def Tl.fn {r: Region} (cx: Tl.Cx, f: Ast.Fn, es: Coll.List[Tl.Err]): Tl.W[Ast.Fn] = + val Ast.Fn(line, n, gs, ps, ret, exit, body) = f + val Tl.W(gs2, es2) = Tl.groups(cx, gs, Coll.Nil, es) + val Tl.W(ps2, es3) = Tl.binders(cx, ps, Coll.Nil, es2) + val Tl.W(ret2, es4) = Tl.ty(cx, Coll.Nil, Coll.Nil, ret, Tl.fuel(), es3) + val Tl.W(b2, es5) = Tl.body(cx, body, es4) + Tl.W(Ast.Fn(line, n, gs2, ps2, ret2, exit, b2), es5) + +def Tl.body {r: Region} (cx: Tl.Cx, b: Ast.Body, es: Coll.List[Tl.Err]): Tl.W[Ast.Body] = b match + case Ast.Def(cs, e) => + val Tl.W(e2, es2) = Tl.expr(cx, e, es) + Tl.W(Ast.Def(cs, e2), es2) + case Ast.Spec(cs, e) => + val Tl.W(e2, es2) = Tl.expr(cx, e, es) + Tl.W(Ast.Spec(cs, e2), es2) + case Ast.Extern => Tl.W(b, es) + +def Tl.groups {r: Region} (cx: Tl.Cx, gs: Coll.List[Ast.Group], acc: Coll.List[Ast.Group], es: Coll.List[Tl.Err]): Tl.W[Coll.List[Ast.Group]] = gs match + case Coll.Nil => Tl.W(Coll.rev(acc), es) + case Coll.Cons(g, rest) => g match + case Ast.Types(bs) => + val Tl.W(bs2, es2) = Tl.binders(cx, bs, Coll.Nil, es) + Tl.groups(cx, rest, Coll.Cons(Ast.Types(bs2), acc), es2) + case Ast.Evidence(bs) => + val Tl.W(bs2, es2) = Tl.binders(cx, bs, Coll.Nil, es) + Tl.groups(cx, rest, Coll.Cons(Ast.Evidence(bs2), acc), es2) + case Ast.Facts(_) => Tl.groups(cx, rest, Coll.Cons(g, acc), es) + +def Tl.binders {r: Region} (cx: Tl.Cx, bs: Coll.List[Ast.Binder], acc: Coll.List[Ast.Binder], es: Coll.List[Tl.Err]): Tl.W[Coll.List[Ast.Binder]] = bs match + case Coll.Nil => Tl.W(Coll.rev(acc), es) + case Coll.Cons(b, rest) => + val Ast.Binder(line, x, t) = b + val Tl.W(t2, es2) = Tl.ty(cx, Coll.Nil, Coll.Nil, t, Tl.fuel(), es) + Tl.binders(cx, rest, Coll.Cons(Ast.Binder(line, x, t2), acc), es2) + +def Tl.cases {r: Region} (cx: Tl.Cx, cs: Coll.List[Ast.Case], acc: Coll.List[Ast.Case], es: Coll.List[Tl.Err]): Tl.W[Coll.List[Ast.Case]] = cs match + case Coll.Nil => Tl.W(Coll.rev(acc), es) + case Coll.Cons(c, rest) => + val Ast.Case(line, n, fs) = c + val Tl.W(fs2, es2) = Tl.binders(cx, fs, Coll.Nil, es) + Tl.cases(cx, rest, Coll.Cons(Ast.Case(line, n, fs2), acc), es2) + +def Tl.ops {r: Region} (cx: Tl.Cx, os: Coll.List[Ast.Op], acc: Coll.List[Ast.Op], es: Coll.List[Tl.Err]): Tl.W[Coll.List[Ast.Op]] = os match + case Coll.Nil => Tl.W(Coll.rev(acc), es) + case Coll.Cons(o, rest) => + val Ast.Op(line, n, ps, ret, tr) = o + val Tl.W(ps2, es2) = Tl.binders(cx, ps, Coll.Nil, es) + val Tl.W(ret2, es3) = Tl.ty(cx, Coll.Nil, Coll.Nil, ret, Tl.fuel(), es2) + Tl.ops(cx, rest, Coll.Cons(Ast.Op(line, n, ps2, ret2, tr), acc), es3) + +// ── expressions: the types written in them (call type args, val annotations, quantifiers) ── +def Tl.expr {r: Region} (cx: Tl.Cx, e: Ast.Expr, es: Coll.List[Tl.Err]): Tl.W[Ast.Expr] = e match + case Ast.Call(line, f, targs, ch, xs) => + val Tl.W(ts2, es2) = Tl.tys(cx, targs, Coll.Nil, es) + val Tl.W(xs2, es3) = Tl.exprs(cx, xs, Coll.Nil, es2) + Tl.W(Ast.Call(line, f, ts2, ch, xs2), es3) + case Ast.Method(line, recv, op, xs) => + val Tl.W(xs2, es2) = Tl.exprs(cx, xs, Coll.Nil, es) + Tl.W(Ast.Method(line, recv, op, xs2), es2) + case Ast.Bin(line, op, l, x) => + val Tl.W(l2, es2) = Tl.expr(cx, l, es) + val Tl.W(x2, es3) = Tl.expr(cx, x, es2) + Tl.W(Ast.Bin(line, op, l2, x2), es3) + case Ast.Un(line, op, x) => + val Tl.W(x2, es2) = Tl.expr(cx, x, es) + Tl.W(Ast.Un(line, op, x2), es2) + case Ast.If(line, c, t, x) => + val Tl.W(c2, es2) = Tl.expr(cx, c, es) + val Tl.W(t2, es3) = Tl.expr(cx, t, es2) + val Tl.W(x2, es4) = Tl.expr(cx, x, es3) + Tl.W(Ast.If(line, c2, t2, x2), es4) + case Ast.Match(line, s, arms) => + val Tl.W(s2, es2) = Tl.expr(cx, s, es) + val Tl.W(as2, es3) = Tl.arms(cx, arms, Coll.Nil, es2) + Tl.W(Ast.Match(line, s2, as2), es3) + case Ast.Block(line, ss, last) => + val Tl.W(ss2, es2) = Tl.stmts(cx, ss, Coll.Nil, es) + val Tl.W(l2, es3) = Tl.expr(cx, last, es2) + Tl.W(Ast.Block(line, ss2, l2), es3) + case Ast.While(line, c, b) => + val Tl.W(c2, es2) = Tl.expr(cx, c, es) + val Tl.W(b2, es3) = Tl.expr(cx, b, es2) + Tl.W(Ast.While(line, c2, b2), es3) + case Ast.Assign(line, x, v) => + val Tl.W(v2, es2) = Tl.expr(cx, v, es) + Tl.W(Ast.Assign(line, x, v2), es2) + case Ast.Quant(line, q, x, t, b) => + val Tl.W(t2, es2) = Tl.ty(cx, Coll.Nil, Coll.Nil, t, Tl.fuel(), es) + val Tl.W(b2, es3) = Tl.expr(cx, b, es2) + Tl.W(Ast.Quant(line, q, x, t2, b2), es3) + case _ => Tl.W(e, es) + +def Tl.exprs {r: Region} (cx: Tl.Cx, xs: Coll.List[Ast.Expr], acc: Coll.List[Ast.Expr], es: Coll.List[Tl.Err]): Tl.W[Coll.List[Ast.Expr]] = xs match + case Coll.Nil => Tl.W(Coll.rev(acc), es) + case Coll.Cons(x, rest) => + val Tl.W(x2, es2) = Tl.expr(cx, x, es) + Tl.exprs(cx, rest, Coll.Cons(x2, acc), es2) + +def Tl.arms {r: Region} (cx: Tl.Cx, as: Coll.List[Ast.Arm], acc: Coll.List[Ast.Arm], es: Coll.List[Tl.Err]): Tl.W[Coll.List[Ast.Arm]] = as match + case Coll.Nil => Tl.W(Coll.rev(acc), es) + case Coll.Cons(a, rest) => + val Ast.Arm(line, p, b) = a + val Tl.W(b2, es2) = Tl.expr(cx, b, es) + Tl.arms(cx, rest, Coll.Cons(Ast.Arm(line, p, b2), acc), es2) + +def Tl.stmts {r: Region} (cx: Tl.Cx, ss: Coll.List[Ast.Stmt], acc: Coll.List[Ast.Stmt], es: Coll.List[Tl.Err]): Tl.W[Coll.List[Ast.Stmt]] = ss match + case Coll.Nil => Tl.W(Coll.rev(acc), es) + case Coll.Cons(s, rest) => + val Tl.W(s2, es2) = Tl.stmt(cx, s, es) + Tl.stmts(cx, rest, Coll.Cons(s2, acc), es2) + +def Tl.stmt {r: Region} (cx: Tl.Cx, s: Ast.Stmt, es: Coll.List[Tl.Err]): Tl.W[Ast.Stmt] = s match + case Ast.Val(line, x, ann, e) => + val Tl.W(a2, es2) = Tl.ann(cx, ann, es) + val Tl.W(e2, es3) = Tl.expr(cx, e, es2) + Tl.W(Ast.Val(line, x, a2, e2), es3) + case Ast.Var(line, x, ann, e) => + val Tl.W(a2, es2) = Tl.ann(cx, ann, es) + val Tl.W(e2, es3) = Tl.expr(cx, e, es2) + Tl.W(Ast.Var(line, x, a2, e2), es3) + case Ast.Handle(line, x, h, xs) => + val Tl.W(xs2, es2) = Tl.exprs(cx, xs, Coll.Nil, es) + Tl.W(Ast.Handle(line, x, h, xs2), es2) + case Ast.Do(e) => + val Tl.W(e2, es2) = Tl.expr(cx, e, es) + Tl.W(Ast.Do(e2), es2) + case Ast.Check(line, k, e) => + val Tl.W(e2, es2) = Tl.expr(cx, e, es) + Tl.W(Ast.Check(line, k, e2), es2) + +def Tl.ann {r: Region} (cx: Tl.Cx, a: Coll.Option[Ast.Ty], es: Coll.List[Tl.Err]): Tl.W[Coll.Option[Ast.Ty]] = a match + case Coll.None => Tl.W(a, es) + case Coll.Some(t) => + val Tl.W(t2, es2) = Tl.ty(cx, Coll.Nil, Coll.Nil, t, Tl.fuel(), es) + Tl.W(Coll.Some(t2), es2) + +// ── a type: its args normalized; a type decl applied and reduced; the use keeps its caps (s1 normTyV) ── +def Tl.tys {r: Region} (cx: Tl.Cx, ts: Coll.List[Ast.Ty], acc: Coll.List[Ast.Ty], es: Coll.List[Tl.Err]): Tl.W[Coll.List[Ast.Ty]] = ts match + case Coll.Nil => Tl.W(Coll.rev(acc), es) + case Coll.Cons(t, rest) => + val Tl.W(t2, es2) = Tl.ty(cx, Coll.Nil, Coll.Nil, t, Tl.fuel(), es) + Tl.tys(cx, rest, Coll.Cons(t2, acc), es2) + +// t inside a type decl's body: sub = its [] binders, cv = its () value params +def Tl.ty {r: Region} (cx: Tl.Cx, sub: Coll.List[Tl.Bt], cv: Coll.List[Tl.Bv], t: Ast.Ty, fuel: I64, es: Coll.List[Tl.Err]): Tl.W[Ast.Ty] = + val Ast.Ty(line, n, args, caps, vals) = t + if fuel <= 0 then Tl.W(t, Coll.Cons(Tl.Fuel(line, n), es)) + else + val Tl.W(args2, es2) = Tl.tyArgs(cx, sub, cv, args, fuel, Coll.Nil, es) + val Tl.Cx(tds, _) = cx + Tl.btLookup(sub, n) match + case Coll.Some(b) => Tl.W(b, es2) + case Coll.None => Coll.sLookup(tds, n) match + case Coll.None => Tl.W(Ast.Ty(line, n, args2, caps, vals), if Coll.length(vals) == 0 then es2 else Coll.Cons(Tl.NoVals(line, n), es2)) + case Coll.Some(td) => if Tl.nominal(td) then Tl.W(Ast.Ty(line, n, args2, caps, vals), es2) else Tl.apply(cx, cv, td, line, args2, caps, vals, fuel, es2) + +def Tl.tyArgs {r: Region} (cx: Tl.Cx, sub: Coll.List[Tl.Bt], cv: Coll.List[Tl.Bv], ts: Coll.List[Ast.Ty], fuel: I64, acc: Coll.List[Ast.Ty], es: Coll.List[Tl.Err]): Tl.W[Coll.List[Ast.Ty]] = ts match + case Coll.Nil => Tl.W(Coll.rev(acc), es) + case Coll.Cons(t, rest) => + val Tl.W(t2, es2) = Tl.ty(cx, sub, cv, t, fuel - 1, es) + Tl.tyArgs(cx, sub, cv, rest, fuel, Coll.Cons(t2, acc), es2) + +def Tl.btLookup {r: Region} (bs: Coll.List[Tl.Bt], x: Sym.Sym): Coll.Option[Ast.Ty] = bs match + case Coll.Nil => Coll.None + case Coll.Cons(b, rest) => + val Tl.Bt(y, t) = b + if Sym.eq(x, y) then Coll.Some(t) else Tl.btLookup(rest, x) + +// a use of type decl td at args (normalized) and value args vals (evaluated under the enclosing value params cv) +def Tl.apply {r: Region} (cx: Tl.Cx, cv: Coll.List[Tl.Bv], td: Ast.TypeDecl, line: I64, args: Coll.List[Ast.Ty], caps: Ast.Caps, vals: Coll.List[Ast.Expr], fuel: I64, es: Coll.List[Tl.Err]): Tl.W[Ast.Ty] = + val Ast.TypeDecl(_, n, gs, vbs, body) = td + val tps = Ty.tparams(gs, Coll.Nil) + if Coll.length(tps) != Coll.length(args) || Coll.length(vbs) != Coll.length(vals) then Tl.W(Ast.Ty(line, n, args, caps, Coll.Nil), Coll.Cons(Tl.Arity(line, n), es)) + else Tl.bindVals(cx, cv, vbs, vals, Coll.Nil) match + case Tl.NoValue => Tl.W(Ast.Ty(line, n, args, caps, Coll.Nil), Coll.Cons(Tl.BadVal(line, n), es)) + case Tl.Misfit => Tl.W(Ast.Ty(line, n, args, caps, Coll.Nil), Coll.Cons(Tl.ArgType(line, n), es)) + case Tl.Bound(cv2) => + val sub = Tl.zipBt(tps, args, Coll.Nil) + val Tl.W(res, es2) = Tl.reduce(cx, sub, cv2, n, line, body, fuel, es) + val Ast.Ty(_, rn, rargs, _, _) = res + Tl.W(Ast.Ty(line, rn, rargs, caps, Coll.Nil), es2) + +def Tl.zipBt {r: Region} (xs: Coll.List[Sym.Sym], ts: Coll.List[Ast.Ty], acc: Coll.List[Tl.Bt]): Coll.List[Tl.Bt] = xs match + case Coll.Nil => acc + case Coll.Cons(x, rest) => ts match + case Coll.Nil => acc + case Coll.Cons(t, trest) => Tl.zipBt(rest, trest, Coll.Cons(Tl.Bt(x, t), acc)) + +def Tl.reduce {r: Region} (cx: Tl.Cx, sub: Coll.List[Tl.Bt], cv: Coll.List[Tl.Bv], n: Sym.Sym, line: I64, body: Ast.TBody, fuel: I64, es: Coll.List[Tl.Err]): Tl.W[Ast.Ty] = body match + case Ast.Alias(t) => Tl.ty(cx, sub, cv, t, fuel - 1, es) + case Ast.TyMatch(scrut, arms) => + val Tl.W(s, es2) = Tl.ty(cx, sub, cv, scrut, fuel - 1, es) + Tl.tyArm(cx, sub, cv, n, line, s, arms, fuel, es2) + case Ast.ValMatch(x, arms) => Tl.bvLookup(cv, x) match + case Coll.None => Tl.W(Ast.Ty(line, n, Coll.Nil, Ast.Inferred, Coll.Nil), Coll.Cons(Tl.BadVal(line, n), es)) + case Coll.Some(v) => Tl.valArm(cx, sub, cv, n, line, v, arms, fuel, es) + +// the first case whose pattern (under sub) is s +def Tl.tyArm {r: Region} (cx: Tl.Cx, sub: Coll.List[Tl.Bt], cv: Coll.List[Tl.Bv], n: Sym.Sym, line: I64, s: Ast.Ty, arms: Coll.List[Ast.TyArm], fuel: I64, es: Coll.List[Tl.Err]): Tl.W[Ast.Ty] = arms match + case Coll.Nil => Tl.W(s, Coll.Cons(Tl.NoCase(line, n), es)) + case Coll.Cons(a, rest) => + val Ast.TyArm(_, pat, res) = a + val Tl.W(p, es2) = Tl.ty(cx, sub, cv, pat, fuel - 1, es) + if Tl.tyEq(p, s) then Tl.ty(cx, sub, cv, res, fuel - 1, es2) else Tl.tyArm(cx, sub, cv, n, line, s, rest, fuel, es2) + +def Tl.valArm {r: Region} (cx: Tl.Cx, sub: Coll.List[Tl.Bt], cv: Coll.List[Tl.Bv], n: Sym.Sym, line: I64, v: Tl.V, arms: Coll.List[Ast.ValArm], fuel: I64, es: Coll.List[Tl.Err]): Tl.W[Ast.Ty] = arms match + case Coll.Nil => Tl.W(Ast.Ty(line, n, Coll.Nil, Ast.Inferred, Coll.Nil), Coll.Cons(Tl.NoCase(line, n), es)) + case Coll.Cons(a, rest) => + val Ast.ValArm(_, pat, res) = a + if Tl.fits(pat, v) then Tl.ty(cx, sub, cv, res, fuel - 1, es) else Tl.valArm(cx, sub, cv, n, line, v, rest, fuel, es) + +def Tl.fits(p: Ast.VPat, v: Tl.V): Bool = p match + case Ast.VAny => true + case Ast.VInt(i) => v match + case Tl.VI(j) => i == j + case _ => false + case Ast.VBool(b) => v match + case Tl.VB(c) => b == c + case _ => false + case Ast.VStr(s) => v match + case Tl.VS(u) => rt_str_eq(s, u) + case _ => false + +def Tl.tyEq(a: Ast.Ty, b: Ast.Ty): Bool = + val Ast.Ty(_, m, xs, _, _) = a + val Ast.Ty(_, n, ys, _, _) = b + Sym.eq(m, n) && Tl.tysEq(xs, ys) + +def Tl.tysEq(xs: Coll.List[Ast.Ty], ys: Coll.List[Ast.Ty]): Bool = xs match + case Coll.Nil => ys match + case Coll.Nil => true + case Coll.Cons(_, _) => false + case Coll.Cons(x, xt) => ys match + case Coll.Nil => false + case Coll.Cons(y, yt) => if Tl.tyEq(x, y) then Tl.tysEq(xt, yt) else false + +// ── value args: each evaluated at compile time under the enclosing value params, bound to the decl's () params ── +enum Tl.Vals: + case Tl.Bound(cv: Coll.List[Tl.Bv]) + case Tl.NoValue + case Tl.Misfit + +def Tl.bindVals {r: Region} (cx: Tl.Cx, cv: Coll.List[Tl.Bv], bs: Coll.List[Ast.Binder], xs: Coll.List[Ast.Expr], acc: Coll.List[Tl.Bv]): Tl.Vals = bs match + case Coll.Nil => Tl.Bound(acc) + case Coll.Cons(b, rest) => xs match + case Coll.Nil => Tl.Bound(acc) + case Coll.Cons(x, xrest) => + val Ast.Binder(_, y, t) = b + Tl.eval(cx, cv, x, Tl.fuel()) match + case Coll.None => Tl.NoValue + case Coll.Some(v) => if Tl.fitsTy(t, v) then Tl.bindVals(cx, cv, rest, xrest, Coll.Cons(Tl.Bv(y, v), acc)) else Tl.Misfit + +// a value of the binder's type: I64, Bool or Str +def Tl.fitsTy(t: Ast.Ty, v: Tl.V): Bool = + val Ast.Ty(_, n, _, _, _) = t + val s = Sym.str(n) + v match + case Tl.VI(_) => rt_str_eq(s, "I64") + case Tl.VB(_) => rt_str_eq(s, "Bool") + case Tl.VS(_) => rt_str_eq(s, "Str") + +// a type decl: its () binders have compile-time values; each value match pattern fits its binder's type +def Tl.typeDecl {r: Region} (td: Ast.TypeDecl, es: Coll.List[Tl.Err]): Coll.List[Tl.Err] = + val Ast.TypeDecl(line, n, _, vbs, body) = td + val es2 = Tl.binderTys(line, vbs, es) + body match + case Ast.ValMatch(x, arms) => Tl.binderTyOf(vbs, x) match + case Coll.Some(t) => Tl.patTys(line, n, t, arms, es2) + case Coll.None => es2 + case _ => es2 + +def Tl.binderTys {r: Region} (line: I64, bs: Coll.List[Ast.Binder], es: Coll.List[Tl.Err]): Coll.List[Tl.Err] = bs match + case Coll.Nil => es + case Coll.Cons(b, rest) => + val Ast.Binder(_, x, t) = b + val Ast.Ty(_, tn, _, _, _) = t + val s = Sym.str(tn) + val ok = rt_str_eq(s, "I64") || rt_str_eq(s, "Bool") || rt_str_eq(s, "Str") + Tl.binderTys(line, rest, if ok then es else Coll.Cons(Tl.BinderType(line, x), es)) + +def Tl.binderTyOf {r: Region} (bs: Coll.List[Ast.Binder], x: Sym.Sym): Coll.Option[Ast.Ty] = bs match + case Coll.Nil => Coll.None + case Coll.Cons(b, rest) => + val Ast.Binder(_, y, t) = b + if Sym.eq(x, y) then Coll.Some(t) else Tl.binderTyOf(rest, x) + +def Tl.patTys {r: Region} (line: I64, n: Sym.Sym, t: Ast.Ty, arms: Coll.List[Ast.ValArm], es: Coll.List[Tl.Err]): Coll.List[Tl.Err] = arms match + case Coll.Nil => es + case Coll.Cons(a, rest) => + val Ast.ValArm(al, p, _) = a + val ok: Bool = p match + case Ast.VAny => true + case Ast.VInt(v) => Tl.fitsTy(t, Tl.VI(v)) + case Ast.VBool(v) => Tl.fitsTy(t, Tl.VB(v)) + case Ast.VStr(v) => Tl.fitsTy(t, Tl.VS(v)) + Tl.patTys(line, n, t, rest, if ok then es else Coll.Cons(Tl.PatType(al, n), es)) + +def Tl.bvLookup {r: Region} (bs: Coll.List[Tl.Bv], x: Sym.Sym): Coll.Option[Tl.V] = bs match + case Coll.Nil => Coll.None + case Coll.Cons(b, rest) => + val Tl.Bv(y, v) = b + if Sym.eq(x, y) then Coll.Some(v) else Tl.bvLookup(rest, x) + +// a pure expression's value: literals, the env, operators, if, blocks of vals, calls of defs (each call costs fuel); +// anything else has no compile-time value (None) +def Tl.eval {r: Region} (cx: Tl.Cx, env: Coll.List[Tl.Bv], e: Ast.Expr, fuel: I64): Coll.Option[Tl.V] = + if fuel <= 0 then Coll.None + else e match + case Ast.Int(_, v) => Coll.Some(Tl.VI(v)) + case Ast.Bool(_, v) => Coll.Some(Tl.VB(v)) + case Ast.Str(_, s) => Coll.Some(Tl.VS(s)) + case Ast.Name(_, x) => Tl.bvLookup(env, x) match + case Coll.Some(v) => Coll.Some(v) + case Coll.None => Tl.call(cx, env, x, Coll.Nil, fuel) + case Ast.Call(_, f, _, _, xs) => Tl.call(cx, env, f, xs, fuel) + case Ast.Bin(_, op, l, x) => Tl.bin(op, Tl.eval(cx, env, l, fuel), Tl.eval(cx, env, x, fuel)) + case Ast.Un(_, op, x) => Tl.un(op, Tl.eval(cx, env, x, fuel)) + case Ast.If(_, c, t, x) => Tl.eval(cx, env, c, fuel) match + case Coll.Some(cv) => cv match + case Tl.VB(b) => if b then Tl.eval(cx, env, t, fuel) else Tl.eval(cx, env, x, fuel) + case _ => Coll.None + case Coll.None => Coll.None + case Ast.Block(_, ss, last) => Tl.evalBlock(cx, env, ss, last, fuel) + case _ => Coll.None + +def Tl.evalBlock {r: Region} (cx: Tl.Cx, env: Coll.List[Tl.Bv], ss: Coll.List[Ast.Stmt], last: Ast.Expr, fuel: I64): Coll.Option[Tl.V] = ss match + case Coll.Nil => Tl.eval(cx, env, last, fuel) + case Coll.Cons(s, rest) => s match + case Ast.Val(_, x, _, e) => Tl.eval(cx, env, e, fuel) match + case Coll.Some(v) => Tl.evalBlock(cx, Coll.Cons(Tl.Bv(x, v), env), rest, last, fuel) + case Coll.None => Coll.None + case _ => Coll.None + +// a call of a def: its args evaluated, bound to its params, its body evaluated with less fuel +def Tl.call {r: Region} (cx: Tl.Cx, env: Coll.List[Tl.Bv], f: Sym.Sym, xs: Coll.List[Ast.Expr], fuel: I64): Coll.Option[Tl.V] = + val Tl.Cx(_, fs) = cx + Coll.sLookup(fs, f) match + case Coll.None => Coll.None + case Coll.Some(g) => + val Ast.Fn(_, _, _, ps, _, _, body) = g + body match + case Ast.Def(_, b) => Tl.args(cx, env, ps, xs, fuel, Coll.Nil) match + case Coll.Some(env2) => Tl.eval(cx, env2, b, fuel - 1) + case Coll.None => Coll.None + case _ => Coll.None + +def Tl.args {r: Region} (cx: Tl.Cx, env: Coll.List[Tl.Bv], ps: Coll.List[Ast.Binder], xs: Coll.List[Ast.Expr], fuel: I64, acc: Coll.List[Tl.Bv]): Coll.Option[Coll.List[Tl.Bv]] = ps match + case Coll.Nil => xs match + case Coll.Nil => Coll.Some(acc) + case Coll.Cons(_, _) => Coll.None + case Coll.Cons(p, prest) => xs match + case Coll.Nil => Coll.None + case Coll.Cons(x, xrest) => + val Ast.Binder(_, y, _) = p + Tl.eval(cx, env, x, fuel) match + case Coll.Some(v) => Tl.args(cx, env, prest, xrest, fuel, Coll.Cons(Tl.Bv(y, v), acc)) + case Coll.None => Coll.None + +def Tl.bin {r: Region} (op: Ast.BinOp, a: Coll.Option[Tl.V], b: Coll.Option[Tl.V]): Coll.Option[Tl.V] = a match + case Coll.None => Coll.None + case Coll.Some(x) => b match + case Coll.None => Coll.None + case Coll.Some(y) => Tl.binV(op, x, y) + +def Tl.binV {r: Region} (op: Ast.BinOp, a: Tl.V, b: Tl.V): Coll.Option[Tl.V] = a match + case Tl.VI(x) => b match + case Tl.VI(y) => Tl.binI(op, x, y) + case _ => Coll.None + case Tl.VB(x) => b match + case Tl.VB(y) => op match + case Ast.And => Coll.Some(Tl.VB(x && y)) + case Ast.Or => Coll.Some(Tl.VB(x || y)) + case Ast.Eq => Coll.Some(Tl.VB(x == y)) + case Ast.Ne => Coll.Some(Tl.VB(x != y)) + case _ => Coll.None + case _ => Coll.None + case Tl.VS(x) => b match + case Tl.VS(y) => op match + case Ast.Eq => Coll.Some(Tl.VB(rt_str_eq(x, y))) + case Ast.Ne => Coll.Some(Tl.VB(!rt_str_eq(x, y))) + case _ => Coll.None + case _ => Coll.None + +// a division by zero has no value +def Tl.binI {r: Region} (op: Ast.BinOp, x: I64, y: I64): Coll.Option[Tl.V] = op match + case Ast.Add => Coll.Some(Tl.VI(x + y)) + case Ast.Sub => Coll.Some(Tl.VI(x - y)) + case Ast.Mul => Coll.Some(Tl.VI(x * y)) + case Ast.Div => if y == 0 then Coll.None else Coll.Some(Tl.VI(x / y)) + case Ast.Mod => if y == 0 then Coll.None else Coll.Some(Tl.VI(x % y)) + case Ast.Lt => Coll.Some(Tl.VB(x < y)) + case Ast.Le => Coll.Some(Tl.VB(x <= y)) + case Ast.Gt => Coll.Some(Tl.VB(x > y)) + case Ast.Ge => Coll.Some(Tl.VB(x >= y)) + case Ast.Eq => Coll.Some(Tl.VB(x == y)) + case Ast.Ne => Coll.Some(Tl.VB(x != y)) + case _ => Coll.None + +def Tl.un {r: Region} (op: Ast.UnOp, a: Coll.Option[Tl.V]): Coll.Option[Tl.V] = a match + case Coll.None => Coll.None + case Coll.Some(v) => v match + case Tl.VI(x) => op match + case Ast.Neg => Coll.Some(Tl.VI(0 - x)) + case Ast.Not => Coll.None + case Tl.VB(x) => op match + case Ast.Not => Coll.Some(Tl.VB(!x)) + case Ast.Neg => Coll.None + case _ => Coll.None + +// ── the {} goals of the types a def names (vic-jxk): SortedBox[A] {o: Ord[A]} named at Bool needs Ord[Bool], a +// capability binder {f: File} needs a File in scope; Ty resolves each with the def's own {} binders ── +enum Tl.Goal: + case Tl.Goal(line: I64, fn: Sym.Sym, goal: Ast.Ty) + +def Tl.typeGoals {r: Region} (ds: Coll.List[Ast.Decl]): Coll.List[Tl.Goal] = + val cx = Tl.cxOf(ds, Coll.sEmpty(), Coll.sEmpty()) + Tl.declGoals(cx, ds, Coll.Nil) + +def Tl.declGoals {r: Region} (cx: Tl.Cx, ds: Coll.List[Ast.Decl], acc: Coll.List[Tl.Goal]): Coll.List[Tl.Goal] = ds match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(d, rest) => d match + case Ast.DFn(f) => + val Ast.Fn(_, n, _, ps, ret, _, body) = f + val acc2 = Tl.tyGoals(cx, n, ret, Tl.bindersGoals(cx, n, ps, acc)) + val acc3 = body match + case Ast.Def(_, e) => Tl.exprGoals(cx, n, e, acc2) + case Ast.Spec(_, e) => Tl.exprGoals(cx, n, e, acc2) + case Ast.Extern => acc2 + Tl.declGoals(cx, rest, acc3) + case _ => Tl.declGoals(cx, rest, acc) + +def Tl.bindersGoals {r: Region} (cx: Tl.Cx, f: Sym.Sym, bs: Coll.List[Ast.Binder], acc: Coll.List[Tl.Goal]): Coll.List[Tl.Goal] = bs match + case Coll.Nil => acc + case Coll.Cons(b, rest) => + val Ast.Binder(_, _, t) = b + Tl.bindersGoals(cx, f, rest, Tl.tyGoals(cx, f, t, acc)) + +// t and its args: each name of a type decl with {} binders gives their types at t's args +def Tl.tyGoals {r: Region} (cx: Tl.Cx, f: Sym.Sym, t: Ast.Ty, acc: Coll.List[Tl.Goal]): Coll.List[Tl.Goal] = + val Ast.Ty(line, n, args, _, _) = t + val acc2 = Tl.tysGoals(cx, f, args, acc) + val Tl.Cx(tds, _) = cx + Coll.sLookup(tds, n) match + case Coll.None => acc2 + case Coll.Some(td) => + val Ast.TypeDecl(_, _, gs, _, _) = td + val Tl.W(args2, _) = Tl.tyArgs(cx, Coll.Nil, Coll.Nil, args, Tl.fuel(), Coll.Nil, Coll.Nil) + Tl.evGoals(cx, f, line, Tl.zipBt(Ty.tparams(gs, Coll.Nil), args2, Coll.Nil), Ty.evidence(gs, Coll.Nil), acc2) + +def Tl.tysGoals {r: Region} (cx: Tl.Cx, f: Sym.Sym, ts: Coll.List[Ast.Ty], acc: Coll.List[Tl.Goal]): Coll.List[Tl.Goal] = ts match + case Coll.Nil => acc + case Coll.Cons(t, rest) => Tl.tysGoals(cx, f, rest, Tl.tyGoals(cx, f, t, acc)) + +def Tl.evGoals {r: Region} (cx: Tl.Cx, f: Sym.Sym, line: I64, sub: Coll.List[Tl.Bt], ev: Coll.List[Ast.Binder], acc: Coll.List[Tl.Goal]): Coll.List[Tl.Goal] = ev match + case Coll.Nil => acc + case Coll.Cons(b, rest) => + val Ast.Binder(_, _, bt) = b + val Tl.W(g, _) = Tl.ty(cx, sub, Coll.Nil, bt, Tl.fuel(), Coll.Nil) + Tl.evGoals(cx, f, line, sub, rest, Coll.Cons(Tl.Goal(line, f, g), acc)) + +// the types written in a body: val annotations and call type args +def Tl.exprGoals {r: Region} (cx: Tl.Cx, f: Sym.Sym, e: Ast.Expr, acc: Coll.List[Tl.Goal]): Coll.List[Tl.Goal] = e match + case Ast.Call(_, _, targs, _, xs) => Tl.exprsGoals(cx, f, xs, Tl.tysGoals(cx, f, targs, acc)) + case Ast.Method(_, _, _, xs) => Tl.exprsGoals(cx, f, xs, acc) + case Ast.Bin(_, _, l, x) => Tl.exprGoals(cx, f, x, Tl.exprGoals(cx, f, l, acc)) + case Ast.Un(_, _, x) => Tl.exprGoals(cx, f, x, acc) + case Ast.If(_, c, t, x) => Tl.exprGoals(cx, f, x, Tl.exprGoals(cx, f, t, Tl.exprGoals(cx, f, c, acc))) + case Ast.Match(_, s, arms) => Tl.armsGoals(cx, f, arms, Tl.exprGoals(cx, f, s, acc)) + case Ast.Block(_, ss, last) => Tl.exprGoals(cx, f, last, Tl.stmtsGoals(cx, f, ss, acc)) + case Ast.While(_, c, b) => Tl.exprGoals(cx, f, b, Tl.exprGoals(cx, f, c, acc)) + case Ast.Assign(_, _, x) => Tl.exprGoals(cx, f, x, acc) + case _ => acc + +def Tl.exprsGoals {r: Region} (cx: Tl.Cx, f: Sym.Sym, xs: Coll.List[Ast.Expr], acc: Coll.List[Tl.Goal]): Coll.List[Tl.Goal] = xs match + case Coll.Nil => acc + case Coll.Cons(x, rest) => Tl.exprsGoals(cx, f, rest, Tl.exprGoals(cx, f, x, acc)) + +def Tl.armsGoals {r: Region} (cx: Tl.Cx, f: Sym.Sym, as: Coll.List[Ast.Arm], acc: Coll.List[Tl.Goal]): Coll.List[Tl.Goal] = as match + case Coll.Nil => acc + case Coll.Cons(a, rest) => + val Ast.Arm(_, _, b) = a + Tl.armsGoals(cx, f, rest, Tl.exprGoals(cx, f, b, acc)) + +def Tl.stmtsGoals {r: Region} (cx: Tl.Cx, f: Sym.Sym, ss: Coll.List[Ast.Stmt], acc: Coll.List[Tl.Goal]): Coll.List[Tl.Goal] = ss match + case Coll.Nil => acc + case Coll.Cons(s, rest) => + val acc2 = s match + case Ast.Val(_, _, ann, e) => Tl.exprGoals(cx, f, e, Tl.annGoals(cx, f, ann, acc)) + case Ast.Var(_, _, ann, e) => Tl.exprGoals(cx, f, e, Tl.annGoals(cx, f, ann, acc)) + case Ast.Handle(_, _, _, xs) => Tl.exprsGoals(cx, f, xs, acc) + case Ast.Do(e) => Tl.exprGoals(cx, f, e, acc) + case Ast.Check(_, _, e) => Tl.exprGoals(cx, f, e, acc) + Tl.stmtsGoals(cx, f, rest, acc2) + +def Tl.annGoals {r: Region} (cx: Tl.Cx, f: Sym.Sym, ann: Coll.Option[Ast.Ty], acc: Coll.List[Tl.Goal]): Coll.List[Tl.Goal] = ann match + case Coll.None => acc + case Coll.Some(t) => Tl.tyGoals(cx, f, t, acc) + +// a type with <> facts stays nominal (vic-jxk): a value of it carries the facts, so a plain value of its body type does +// not fit it; C gives it its body's type (s2/emit.srs Emit.nominalOf) +def Tl.nominal(td: Ast.TypeDecl): Bool = + val Ast.TypeDecl(_, _, gs, _, _) = td + Tl.hasFacts(gs) + +def Tl.hasFacts(gs: Coll.List[Ast.Group]): Bool = gs match + case Coll.Nil => false + case Coll.Cons(g, rest) => g match + case Ast.Facts(_) => true + case _ => Tl.hasFacts(rest) diff --git a/bench/corpus/s2/types.srs b/bench/corpus/s2/types.srs new file mode 100644 index 00000000..c21d1ba0 --- /dev/null +++ b/bench/corpus/s2/types.srs @@ -0,0 +1,1086 @@ +// s2 self-host rung T1 (vic/c/s2-selfhost.md, vic/c/s2-typing-spec.md): the types of a program, as s1/check.srs infers +// them. a type is a K.Term: K.Con(name, args). a callee's [] binders open to fresh K.Vars at each call and are solved +// by K.unify (check mode first: the expected type binds them before the args, s1 vic-m5r.18); inside a generic body +// they are rigid, a K.Con named by the binder. every error is a Ty.Clash (data); every generic call and constructor +// records its instance (callee + type args), the input of mono and emit. + +enum Ty.Clash: + case Ty.Mismatch(line: I64, got: K.Term, want: K.Term) + case Ty.Unknown(line: I64, name: Sym.Sym) + case Ty.Arity(line: I64, name: Sym.Sym) + case Ty.NotEnum(line: I64, got: K.Term) + case Ty.NoOp(line: I64, name: Sym.Sym) + case Ty.CannotInfer(line: I64, name: Sym.Sym) + // a {} binder of protocol p with no capability of p in scope, or more than one (s1 theCap) + case Ty.NoCap(line: I64, p: Sym.Sym) + // a spec body calls a fn with effects (s2/pure.srs), or opens a handler + case Ty.Impure(line: I64, f: Sym.Sym) + case Ty.SpecHandle(line: I64, h: Sym.Sym) + // the purity rules are not a Datalog program: a bug in s2, as data + case Ty.PureRules(rel: Sym.Sym) + // a match with no `_` arm that misses a case of its enum (the first one missed) + case Ty.NotExhaustive(line: I64, missing: Sym.Sym) + // a pattern with another number of binders than its case has fields + case Ty.PatArity(line: I64, c: Sym.Sym) + // a trait goal: no local evidence and no given proves it; two givens tie; two locals prove it; the search of given + // clauses ran out of fuel; the chosen name does not prove it; f{...} with another count than f's {} binders + case Ty.NoGiven(line: I64, goal: K.Term) + case Ty.AmbigGivens(line: I64, goal: K.Term) + case Ty.AmbigEvidence(line: I64, goal: K.Term) + case Ty.GivenFuel(line: I64, goal: K.Term) + case Ty.ChosenBad(line: I64, goal: K.Term) + case Ty.ChosenCount(line: I64, f: Sym.Sym) + // shapes: a chosen name that is not a capability of p; evidence or a capability used as a value; a [] binder that + // hides a type; a capability as a value param; a given that does not fit its trait; an extern slot at a non-pointer + case Ty.ChosenNotCap(line: I64, p: Sym.Sym) + case Ty.EvidenceValue(line: I64, x: Sym.Sym) + case Ty.CapValue(line: I64, x: Sym.Sym) + case Ty.BinderHides(line: I64, x: Sym.Sym) + case Ty.CapParam(line: I64, x: Sym.Sym) + case Ty.TraitArity(line: I64, t: Sym.Sym) + case Ty.NotMethod(line: I64, m: Sym.Sym) + case Ty.MissingMethod(line: I64, m: Sym.Sym) + case Ty.SigDiffers(line: I64, m: Sym.Sym) + case Ty.NotInHead(line: I64, x: Sym.Sym) + case Ty.ExternSlot(line: I64, t: K.Term) + +// a {} goal of a trait at a call (the binder's type under the call's type args), the locals in scope there and the chosen +// name if f{x}(...) wrote one: resolved after the whole program, with the final substitution +enum Ty.Goal: + case Ty.Goal(line: I64, goal: K.Term, locals: Coll.List[Ty.Bind], chosen: Coll.Option[Sym.Sym]) + +// a generic callee at a call line, with its type args (vars until solved) +enum Ty.Inst: + case Ty.Inst(line: I64, f: Sym.Sym, targs: Coll.List[K.Term]) + +enum Ty.Bind: + case Ty.Bind(x: Sym.Sym, t: K.Term) + +// the declarations the inference reads +enum Ty.Cx: + case Ty.Cx(fns: Coll.List[Ast.Fn], es: Coll.List[Ast.Enum], ps: Coll.List[Ast.Proto], hs: Coll.List[Ast.Handler], trs: Coll.List[Ast.Trait], mode: Ty.Mode, impure: Coll.SMap[Bool]) + +// a body that runs (a constructor allocates in a Region) or a spec body, evaluated at compile time (no Region, vic Q-U4) +enum Ty.Mode: + case Ty.Run + case Ty.Comptime + +// the substitution, the next fresh var, the clashes, the instances +enum Ty.St: + case Ty.St(s: Coll.IMap[K.Term], next: I64, cs: Coll.List[Ty.Clash], is: Coll.List[Ty.Inst], gs: Coll.List[Ty.Goal], nom: Coll.SMap[K.Term]) + +enum Ty.At: + case Ty.At(st: Ty.St, t: K.Term) + +def Ty.con {r: Region} (n: Str): K.Term = K.Con(Sym.of(n), Coll.Nil) + +def Ty.fresh {r: Region} (st: Ty.St): Ty.At = + val Ty.St(s, n, cs, is, gs, nm) = st + Ty.At(Ty.St(s, n + 1, cs, is, gs, nm), K.Var(n)) + +def Ty.clash {r: Region} (st: Ty.St, c: Ty.Clash): Ty.St = + val Ty.St(s, n, cs, is, gs, nm) = st + Ty.St(s, n, Coll.Cons(c, cs), is, gs, nm) + +// got must equal want: unify, or a Mismatch (the state keeps its substitution). a value of a type with <> facts is +// a value of its body (it only refines it, vic-jxk): got widens to the body when it does not unify as it is +def Ty.expect {r: Region} (st: Ty.St, line: I64, got: K.Term, want: K.Term): Ty.St = + val Ty.St(s, n, cs, is, gs, nm) = st + K.unify(s, got, want) match + case Coll.Some(s2) => Ty.St(s2, n, cs, is, gs, nm) + case Coll.None => Ty.widen(nm, K.walk(s, got)) match + case Coll.Some(body) => K.unify(s, body, want) match + case Coll.Some(s3) => Ty.St(s3, n, cs, is, gs, nm) + case Coll.None => Ty.St(s, n, Coll.Cons(Ty.Mismatch(line, got, want), cs), is, gs, nm) + case Coll.None => Ty.St(s, n, Coll.Cons(Ty.Mismatch(line, got, want), cs), is, gs, nm) + +def Ty.widen {r: Region} (nm: Coll.SMap[K.Term], t: K.Term): Coll.Option[K.Term] = t match + case K.Con(n, _) => Coll.sLookup(nm, n) + case _ => Coll.None + +// the types with <> facts (kept nominal by Tl) and their bodies +def Ty.nominals {r: Region} (ds: Coll.List[Ast.Decl], m: Coll.SMap[K.Term]): Coll.SMap[K.Term] = ds match + case Coll.Nil => m + case Coll.Cons(d, rest) => d match + case Ast.DType(td) => + val Ast.TypeDecl(_, n, gs, _, body) = td + val m2 = body match + case Ast.Alias(t) => if Tl.hasFacts(gs) then Coll.sInsert(m, n, Ty.term(t, Coll.Nil)) else m + case _ => m + Ty.nominals(rest, m2) + case _ => Ty.nominals(rest, m) + +// unify when want is known (check mode), else nothing +def Ty.expectOpt {r: Region} (st: Ty.St, line: I64, got: K.Term, want: Coll.Option[K.Term]): Ty.St = want match + case Coll.None => st + case Coll.Some(w) => Ty.expect(st, line, got, w) + +def Ty.lookup {r: Region} (bs: Coll.List[Ty.Bind], x: Sym.Sym): Coll.Option[K.Term] = bs match + case Coll.Nil => Coll.None + case Coll.Cons(b, rest) => + val Ty.Bind(y, t) = b + if Sym.eq(x, y) then Coll.Some(t) else Ty.lookup(rest, x) + +// ── Ast.Ty as a term: a name bound in tv (a [] binder: a var at a call, a rigid con in a body) is its term ── +def Ty.term {r: Region} (t: Ast.Ty, tv: Coll.List[Ty.Bind]): K.Term = + val Ast.Ty(_, n, args, _, _) = t + args match + case Coll.Nil => Ty.lookup(tv, n) match + case Coll.Some(x) => x + case Coll.None => K.Con(n, Coll.Nil) + case Coll.Cons(_, _) => K.Con(n, Ty.terms(args, tv, Coll.Nil)) + +def Ty.terms {r: Region} (ts: Coll.List[Ast.Ty], tv: Coll.List[Ty.Bind], acc: Coll.List[K.Term]): Coll.List[K.Term] = ts match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(t, rest) => Ty.terms(rest, tv, Coll.Cons(Ty.term(t, tv), acc)) + +// the [] binder names of groups +def Ty.tparams {r: Region} (gs: Coll.List[Ast.Group], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = gs match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(g, rest) => g match + case Ast.Types(bs) => Ty.tparams(rest, Ty.names(bs, acc)) + case Ast.Evidence(_) => Ty.tparams(rest, acc) + case Ast.Facts(_) => Ty.tparams(rest, acc) + +def Ty.names {r: Region} (bs: Coll.List[Ast.Binder], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = bs match + case Coll.Nil => acc + case Coll.Cons(b, rest) => + val Ast.Binder(_, x, _) = b + Ty.names(rest, Coll.Cons(x, acc)) + +// each binder name to a fresh var (a call site), in order; the vars are the instance's type args +enum Ty.Open: + case Ty.Open(st: Ty.St, tv: Coll.List[Ty.Bind], vars: Coll.List[K.Term]) + +def Ty.open {r: Region} (st: Ty.St, xs: Coll.List[Sym.Sym], tv: Coll.List[Ty.Bind], vars: Coll.List[K.Term]): Ty.Open = xs match + case Coll.Nil => Ty.Open(st, tv, Coll.rev(vars)) + case Coll.Cons(x, rest) => + val Ty.At(st1, v) = Ty.fresh(st) + Ty.open(st1, rest, Coll.Cons(Ty.Bind(x, v), tv), Coll.Cons(v, vars)) + +// each binder name to a rigid con named by it (inside a generic body) +def Ty.rigid {r: Region} (xs: Coll.List[Sym.Sym], acc: Coll.List[Ty.Bind]): Coll.List[Ty.Bind] = xs match + case Coll.Nil => acc + case Coll.Cons(x, rest) => Ty.rigid(rest, Coll.Cons(Ty.Bind(x, K.Con(x, Coll.Nil)), acc)) + +// ── lookups ── +def Ty.fnNamed {r: Region} (fs: Coll.List[Ast.Fn], f: Sym.Sym): Coll.Option[Ast.Fn] = fs match + case Coll.Nil => Coll.None + case Coll.Cons(g, rest) => + val Ast.Fn(_, n, _, _, _, _, _) = g + if Sym.eq(n, f) then Coll.Some(g) else Ty.fnNamed(rest, f) + +// the enum a case belongs to, and the case +enum Ty.CaseOf: + case Ty.CaseOf(e: Ast.Enum, c: Ast.Case) + +def Ty.caseNamed {r: Region} (es: Coll.List[Ast.Enum], f: Sym.Sym): Coll.Option[Ty.CaseOf] = es match + case Coll.Nil => Coll.None + case Coll.Cons(e, rest) => + val Ast.Enum(_, _, _, cases) = e + Ty.caseIn(cases, e, f) match + case Coll.Some(c) => Coll.Some(Ty.CaseOf(e, c)) + case Coll.None => Ty.caseNamed(rest, f) + +def Ty.caseIn {r: Region} (cs: Coll.List[Ast.Case], e: Ast.Enum, f: Sym.Sym): Coll.Option[Ast.Case] = cs match + case Coll.Nil => Coll.None + case Coll.Cons(c, rest) => + val Ast.Case(_, n, _) = c + if Sym.eq(n, f) then Coll.Some(c) else Ty.caseIn(rest, e, f) + +// the enum's type at fresh vars: E[v1..vn], with the binders bound for its fields +def Ty.openEnum {r: Region} (st: Ty.St, e: Ast.Enum): Ty.Open = + val Ast.Enum(_, _, gs, _) = e + Ty.open(st, Ty.tparams(gs, Coll.Nil), Coll.Nil, Coll.Nil) + +def Ty.enumTerm {r: Region} (e: Ast.Enum, vars: Coll.List[K.Term]): K.Term = + val Ast.Enum(_, n, _, _) = e + K.Con(n, vars) + +// ── expressions: the type and the elaborated form of e under locals bs, want = the expected type (check mode) ── +enum Ty.Ex: + case Ty.Ex(st: Ty.St, t: K.Term, e: El.Expr) + +enum Ty.Es: + case Ty.Es(st: Ty.St, es: Coll.List[El.Expr]) + +def Ty.expr {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], e: Ast.Expr, want: Coll.Option[K.Term]): Ty.Ex = e match + case Ast.Int(line, v) => Ty.lit(st, line, Ty.con("I64"), want, El.Int(line, v)) + case Ast.Bool(line, v) => Ty.lit(st, line, Ty.con("Bool"), want, El.Bool(line, v)) + case Ast.Str(line, s) => Ty.lit(st, line, Ty.con("Str"), want, El.Str(line, s)) + case Ast.Unit(line) => Ty.lit(st, line, Ty.con("Unit"), want, El.Unit(line)) + case Ast.Name(line, x) => Ty.lookup(bs, x) match + case Coll.Some(t) => Ty.lit(Ty.nameUse(cx, st, line, x, t), line, t, want, El.Local(line, x)) + case Coll.None => Ty.call(cx, st, bs, line, x, Coll.Nil, Coll.Nil, Coll.Nil, want) + case Ast.Call(line, f, targs, chosen, xs) => Ty.call(cx, st, bs, line, f, targs, chosen, xs, want) + case Ast.Method(line, recv, op, xs) => Ty.method(cx, st, bs, line, recv, op, xs, want) + case Ast.Bin(line, op, l, rhs) => Ty.bin(cx, st, bs, line, op, l, rhs, want) + case Ast.Un(line, op, x) => + val t = Ty.con(Ty.unTy(op)) + val Ty.Ex(st1, _, ex) = Ty.expr(cx, st, bs, x, Coll.Some(t)) + Ty.lit(st1, line, t, want, El.Un(line, op, ex)) + case Ast.If(line, c, t, x) => + val Ty.Ex(st1, _, ec) = Ty.expr(cx, st, bs, c, Coll.Some(Ty.con("Bool"))) + val Ty.Ex(st2, tt, et) = Ty.expr(cx, st1, bs, t, want) + val Ty.Ex(st3, _, ex) = Ty.expr(cx, st2, bs, x, Coll.Some(tt)) + Ty.Ex(st3, tt, El.If(line, ec, et, ex)) + case Ast.Match(line, s, arms) => + val Ty.Ex(st1, ts, es) = Ty.expr(cx, st, bs, s, Coll.None) + Ty.arms(cx, st1, bs, line, ts, es, arms, want) + case Ast.Block(line, ss, last) => Ty.block(cx, st, bs, line, ss, last, want, Coll.Nil) + case Ast.While(line, c, b) => + val Ty.Ex(st1, _, ec) = Ty.expr(cx, st, bs, c, Coll.Some(Ty.con("Bool"))) + val Ty.Ex(st2, _, eb) = Ty.expr(cx, st1, bs, b, Coll.None) + Ty.lit(st2, line, Ty.con("Unit"), want, El.While(line, ec, eb)) + case Ast.Assign(line, x, v) => Ty.lookup(bs, x) match + case Coll.None => Ty.Ex(Ty.clash(st, Ty.Unknown(line, x)), Ty.con("Unit"), El.Bad(line)) + case Coll.Some(tx) => + val Ty.Ex(st1, _, ev) = Ty.expr(cx, st, bs, v, Coll.Some(tx)) + Ty.lit(st1, line, Ty.con("Unit"), want, El.Assign(line, x, ev)) + // a quantifier is a contract: checked, erased (no C) + case Ast.Quant(line, _, x, t, b) => + val Ty.Ex(st1, _, _) = Ty.expr(cx, st, Coll.Cons(Ty.Bind(x, Ty.term(t, Coll.Nil)), bs), b, Coll.Some(Ty.con("Bool"))) + Ty.lit(st1, line, Ty.con("Bool"), want, El.Bool(line, true)) + +// a type that is known: checked against want +def Ty.lit {r: Region} (st: Ty.St, line: I64, t: K.Term, want: Coll.Option[K.Term], e: El.Expr): Ty.Ex = Ty.Ex(Ty.expectOpt(st, line, t, want), t, e) + +// an expression that did not type: a fresh type, El.Bad +def Ty.bad {r: Region} (st: Ty.St, line: I64): Ty.Ex = + val Ty.At(st1, v) = Ty.fresh(st) + Ty.Ex(st1, v, El.Bad(line)) + +// ── calls: a def or a constructor (a name with no args is a nullary case) ── +def Ty.call {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, f: Sym.Sym, targs: Coll.List[Ast.Ty], chosen: Coll.List[Sym.Sym], xs: Coll.List[Ast.Expr], want: Coll.Option[K.Term]): Ty.Ex = + val Ty.Cx(fns, es, _, _, _, _, _) = cx + Ty.fnNamed(fns, f) match + case Coll.Some(g) => Ty.callFn(cx, Ty.pureCall(cx, st, line, f), bs, line, g, targs, chosen, xs, want) + case Coll.None => Ty.caseNamed(es, f) match + case Coll.Some(co) => Ty.callCase(cx, st, bs, line, co, xs, want) + case Coll.None => Ty.bad(Ty.args(cx, Ty.clash(st, Ty.Unknown(line, f)), bs, xs), line) + +// the args alone (an unknown callee: still checked) +def Ty.args {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], xs: Coll.List[Ast.Expr]): Ty.St = xs match + case Coll.Nil => st + case Coll.Cons(x, rest) => + val Ty.Ex(st1, _, _) = Ty.expr(cx, st, bs, x, Coll.None) + Ty.args(cx, st1, bs, rest) + +// f[T]{caps}(args): open the binders, explicit type args, check mode (want binds the result first), args left to right; +// each protocol {} binder takes a caller capability (the chosen name, else the one of its protocol in scope) +def Ty.callFn {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, g: Ast.Fn, targs: Coll.List[Ast.Ty], chosen: Coll.List[Sym.Sym], xs: Coll.List[Ast.Expr], want: Coll.Option[K.Term]): Ty.Ex = + val Ast.Fn(_, name, gs, ps, ret, _, _) = g + val tps = Ty.tparams(gs, Coll.Nil) + val Ty.Open(st1, tv, vars) = Ty.open(st, tps, Coll.Nil, Coll.Nil) + val st2 = Ty.explicit(st1, line, vars, Ty.terms(targs, Coll.Nil, Coll.Nil)) + val rt = Ty.term(ret, tv) + val st3 = Ty.expectOpt(st2, line, rt, want) + if Coll.length(ps) != Coll.length(xs) then Ty.Ex(Ty.args(cx, Ty.clash(st3, Ty.Arity(line, name)), bs, xs), rt, El.Bad(line)) + else + val Ty.Es(st4, eargs) = Ty.params(cx, st3, bs, line, ps, tv, xs, Coll.Nil) + val ev = Ty.evidence(gs, Coll.Nil) + val st4b = if Coll.length(chosen) > 0 && Coll.length(chosen) != Coll.length(ev) then Ty.clash(st4, Ty.ChosenCount(line, name)) else st4 + val Ty.Caps(st5, caps) = Ty.capArgs(cx, st4b, bs, line, tv, ev, chosen, 0, Coll.Nil) + Ty.Ex(Ty.inst(st5, line, name, vars), rt, El.CallFn(line, name, vars, caps, eargs)) + +// record a generic instance (no binders: nothing to instantiate) +def Ty.inst {r: Region} (st: Ty.St, line: I64, name: Sym.Sym, vars: Coll.List[K.Term]): Ty.St = vars match + case Coll.Nil => st + case Coll.Cons(_, _) => + val Ty.St(s, n, cs, is, gs, nm) = st + Ty.St(s, n, cs, Coll.Cons(Ty.Inst(line, name, vars), is), gs, nm) + +// f[T1, ...]: each written type arg binds its binder (too many: Arity) +def Ty.explicit {r: Region} (st: Ty.St, line: I64, vars: Coll.List[K.Term], ts: Coll.List[K.Term]): Ty.St = ts match + case Coll.Nil => st + case Coll.Cons(t, rest) => vars match + case Coll.Nil => Ty.clash(st, Ty.Arity(line, Sym.of("[]"))) + case Coll.Cons(v, vs) => Ty.explicit(Ty.expect(st, line, v, t), line, vs, rest) + +// each arg against its param type (binders as opened); the elaborated args in order +def Ty.params {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, ps: Coll.List[Ast.Binder], tv: Coll.List[Ty.Bind], xs: Coll.List[Ast.Expr], acc: Coll.List[El.Expr]): Ty.Es = ps match + case Coll.Nil => Ty.Es(st, Coll.rev(acc)) + case Coll.Cons(p, prest) => xs match + case Coll.Nil => Ty.Es(st, Coll.rev(acc)) + case Coll.Cons(x, xrest) => + val Ast.Binder(_, _, pt) = p + val Ty.Ex(st1, _, ex) = Ty.expr(cx, st, bs, x, Coll.Some(Ty.term(pt, tv))) + Ty.params(cx, st1, bs, line, prest, tv, xrest, Coll.Cons(ex, acc)) + +// ── capabilities at a call: each {} binder of a protocol type takes a caller capability ── +enum Ty.Caps: + case Ty.Caps(st: Ty.St, caps: Coll.List[Sym.Sym]) + +// i = the binder's index among all {} binders (f{a, b}(x) picks by it) +def Ty.capArgs {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, tv: Coll.List[Ty.Bind], ev: Coll.List[Ast.Binder], chosen: Coll.List[Sym.Sym], i: I64, acc: Coll.List[Sym.Sym]): Ty.Caps = ev match + case Coll.Nil => Ty.Caps(st, Coll.rev(acc)) + case Coll.Cons(b, rest) => + val Ast.Binder(_, _, t) = b + val Ast.Ty(_, pn, _, _, _) = t + val Ty.Cx(_, _, ps, _, _, _, _) = cx + if !Ty.isProto(ps, pn) then Ty.capArgs(cx, Ty.addGoal(st, Ty.Goal(line, Ty.term(t, tv), bs, Ty.nthSym(chosen, i))), bs, line, tv, rest, chosen, i + 1, acc) + else Ty.capFor(st, bs, line, pn, chosen, i) match + case Ty.Caps(st1, c) => Ty.capArgs(cx, st1, bs, line, tv, rest, chosen, i + 1, Coll.revOnto(c, acc)) + +// the cap of protocol p: the chosen name at index i, else the one local of type p in scope (none or two: NoCap) +def Ty.capFor {r: Region} (st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, p: Sym.Sym, chosen: Coll.List[Sym.Sym], i: I64): Ty.Caps = chosen match + case Coll.Cons(_, _) => Ty.nthSym(chosen, i) match + case Coll.Some(x) => Ty.Caps(if Ty.isCapOf(Ty.subst(st), bs, x, p) then st else Ty.clash(st, Ty.ChosenNotCap(line, p)), Coll.Cons(x, Coll.Nil)) + case Coll.None => Ty.Caps(Ty.clash(st, Ty.NoCap(line, p)), Coll.Nil) + case Coll.Nil => Ty.capsOf(Ty.subst(st), bs, p, Coll.Nil) match + case Coll.Cons(x, more) => more match + case Coll.Nil => Ty.Caps(st, Coll.Cons(x, Coll.Nil)) + case Coll.Cons(_, _) => Ty.Caps(Ty.clash(st, Ty.NoCap(line, p)), Coll.Nil) + case Coll.Nil => Ty.Caps(Ty.clash(st, Ty.NoCap(line, p)), Coll.Nil) + +// the distinct local names of type p (a shadowed name counts once) +def Ty.capsOf {r: Region} (s: Coll.IMap[K.Term], bs: Coll.List[Ty.Bind], p: Sym.Sym, acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = bs match + case Coll.Nil => acc + case Coll.Cons(b, rest) => + val Ty.Bind(x, t) = b + val isP: Bool = K.walk(s, t) match + case K.Con(n, args) => Sym.eq(n, p) && Coll.length(args) == 0 + case _ => false + if isP && !Ty.memberSym(x, acc) then Ty.capsOf(s, rest, p, Coll.Cons(x, acc)) else Ty.capsOf(s, rest, p, acc) + +def Ty.memberSym(x: Sym.Sym, xs: Coll.List[Sym.Sym]): Bool = xs match + case Coll.Nil => false + case Coll.Cons(h, t) => if Sym.eq(h, x) then true else Ty.memberSym(x, t) + +def Ty.nthSym {r: Region} (xs: Coll.List[Sym.Sym], i: I64): Coll.Option[Sym.Sym] = xs match + case Coll.Nil => Coll.None + case Coll.Cons(x, rest) => if i == 0 then Coll.Some(x) else Ty.nthSym(rest, i - 1) + +def Ty.isProto(ps: Coll.List[Ast.Proto], n: Sym.Sym): Bool = ps match + case Coll.Nil => false + case Coll.Cons(p, rest) => + val Ast.Proto(_, pn, _, _, _, _, _, _) = p + if Sym.eq(pn, n) then true else Ty.isProto(rest, n) + +// a constructor: the enum at fresh vars, check mode first, then the fields; it allocates in the one Region in scope (a +// spec body allocates nothing at run time) +def Ty.callCase {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, co: Ty.CaseOf, xs: Coll.List[Ast.Expr], want: Coll.Option[K.Term]): Ty.Ex = + val Ty.CaseOf(e, c) = co + val Ast.Enum(_, en, _, _) = e + val Ast.Case(_, name, fields) = c + val Ty.Open(st1, tv, vars) = Ty.openEnum(st, e) + val et = Ty.enumTerm(e, vars) + val st2 = Ty.expectOpt(st1, line, et, want) + if Coll.length(fields) != Coll.length(xs) then Ty.Ex(Ty.args(cx, Ty.clash(st2, Ty.Arity(line, name)), bs, xs), et, El.Bad(line)) + else + val st3 = Ty.inst(st2, line, name, vars) + fields match + case Coll.Nil => Ty.Ex(st3, et, El.Nullary(line, en, vars, name)) + case Coll.Cons(_, _) => + val Ty.Es(st4, eargs) = Ty.params(cx, st3, bs, line, fields, tv, xs, Coll.Nil) + val Ty.Cx(_, _, _, _, _, mode, _) = cx + mode match + case Ty.Comptime => Ty.Ex(st4, et, El.New(line, en, vars, name, El.Comptime, eargs)) + case Ty.Run => Ty.capFor(st4, bs, line, Sym.of("Region"), Coll.Nil, 0) match + case Ty.Caps(st5, rs) => rs match + case Coll.Cons(reg, _) => Ty.Ex(st5, et, El.New(line, en, vars, name, El.In(reg), eargs)) + case Coll.Nil => Ty.Ex(st5, et, El.Bad(line)) + +// recv.op(args): recv is a capability (op of its protocol) or {} evidence of a trait (the trait method, trait args +// bound from the evidence type) +def Ty.method {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, recv: Sym.Sym, op: Sym.Sym, xs: Coll.List[Ast.Expr], want: Coll.Option[K.Term]): Ty.Ex = + val Ty.Cx(_, _, ps, _, trs, _, _) = cx + Ty.lookup(bs, recv) match + case Coll.None => Ty.bad(Ty.args(cx, Ty.clash(st, Ty.Unknown(line, recv)), bs, xs), line) + case Coll.Some(rt) => K.walk(Ty.subst(st), rt) match + case K.Con(tn, targs) => Ty.protoOp(ps, tn, op) match + case Coll.Some(o) => + val Ast.Op(_, _, ops, oret, _) = o + Ty.callSig(cx, st, bs, line, recv, rt, op, ops, oret, Coll.Nil, xs, want) + case Coll.None => Ty.traitMethod(trs, tn, op) match + case Coll.Some(tm) => + val Ty.TM(tr, m) = tm + val Ast.Trait(_, _, tgs, _) = tr + val Ast.Fn(_, _, _, mps, mret, _, _) = m + Ty.callSig(cx, st, bs, line, recv, rt, op, mps, mret, Ty.zipBind(Ty.tparams(tgs, Coll.Nil), targs, Coll.Nil), xs, want) + case Coll.None => Ty.bad(Ty.args(cx, Ty.clash(st, Ty.NoOp(line, op)), bs, xs), line) + case _ => Ty.bad(Ty.args(cx, Ty.clash(st, Ty.NoOp(line, op)), bs, xs), line) + +def Ty.subst(st: Ty.St): Coll.IMap[K.Term] = + val Ty.St(s, _, _, _, _, _) = st + s + +// a signature with its binders bound to tv: arity, args, result +def Ty.callSig {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, recv: Sym.Sym, rty: K.Term, name: Sym.Sym, ps: Coll.List[Ast.Binder], ret: Ast.Ty, tv: Coll.List[Ty.Bind], xs: Coll.List[Ast.Expr], want: Coll.Option[K.Term]): Ty.Ex = + val rt = Ty.term(ret, tv) + if Coll.length(ps) != Coll.length(xs) then Ty.Ex(Ty.args(cx, Ty.clash(st, Ty.Arity(line, name)), bs, xs), rt, El.Bad(line)) + else + val Ty.Es(st1, eargs) = Ty.params(cx, st, bs, line, ps, tv, xs, Coll.Nil) + Ty.lit(st1, line, rt, want, El.Op(line, recv, rty, name, eargs)) + +def Ty.zipBind {r: Region} (xs: Coll.List[Sym.Sym], ts: Coll.List[K.Term], acc: Coll.List[Ty.Bind]): Coll.List[Ty.Bind] = xs match + case Coll.Nil => acc + case Coll.Cons(x, rest) => ts match + case Coll.Nil => acc + case Coll.Cons(t, trest) => Ty.zipBind(rest, trest, Coll.Cons(Ty.Bind(x, t), acc)) + +def Ty.protoOp {r: Region} (ps: Coll.List[Ast.Proto], p: Sym.Sym, op: Sym.Sym): Coll.Option[Ast.Op] = ps match + case Coll.Nil => Coll.None + case Coll.Cons(x, rest) => + val Ast.Proto(_, n, _, _, _, _, ops, _) = x + if Sym.eq(n, p) then Ty.opIn(ops, op) else Ty.protoOp(rest, p, op) + +def Ty.opIn {r: Region} (os: Coll.List[Ast.Op], op: Sym.Sym): Coll.Option[Ast.Op] = os match + case Coll.Nil => Coll.None + case Coll.Cons(o, rest) => + val Ast.Op(_, n, _, _, _) = o + if Sym.eq(n, op) then Coll.Some(o) else Ty.opIn(rest, op) + +enum Ty.TM: + case Ty.TM(t: Ast.Trait, m: Ast.Fn) + +def Ty.traitMethod {r: Region} (trs: Coll.List[Ast.Trait], t: Sym.Sym, op: Sym.Sym): Coll.Option[Ty.TM] = trs match + case Coll.Nil => Coll.None + case Coll.Cons(tr, rest) => + val Ast.Trait(_, n, _, sigs) = tr + if Sym.eq(n, t) then + Ty.fnNamed(sigs, op) match + case Coll.Some(m) => Coll.Some(Ty.TM(tr, m)) + case Coll.None => Coll.None + else Ty.traitMethod(rest, t, op) + +// ── operators: arithmetic on I64, comparison gives Bool (== and != on any one type), && || on Bool ── +def Ty.bin {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, op: Ast.BinOp, l: Ast.Expr, rhs: Ast.Expr, want: Coll.Option[K.Term]): Ty.Ex = op match + case Ast.Eq => Ty.eqOp(cx, st, bs, line, op, l, rhs, want) + case Ast.Ne => Ty.eqOp(cx, st, bs, line, op, l, rhs, want) + case Ast.And => Ty.both(cx, st, bs, line, op, l, rhs, Ty.con("Bool"), Ty.con("Bool"), want) + case Ast.Or => Ty.both(cx, st, bs, line, op, l, rhs, Ty.con("Bool"), Ty.con("Bool"), want) + case Ast.Lt => Ty.both(cx, st, bs, line, op, l, rhs, Ty.con("I64"), Ty.con("Bool"), want) + case Ast.Le => Ty.both(cx, st, bs, line, op, l, rhs, Ty.con("I64"), Ty.con("Bool"), want) + case Ast.Gt => Ty.both(cx, st, bs, line, op, l, rhs, Ty.con("I64"), Ty.con("Bool"), want) + case Ast.Ge => Ty.both(cx, st, bs, line, op, l, rhs, Ty.con("I64"), Ty.con("Bool"), want) + case _ => Ty.both(cx, st, bs, line, op, l, rhs, Ty.con("I64"), Ty.con("I64"), want) + +// both operands of type arg, the result of type res +def Ty.both {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, op: Ast.BinOp, l: Ast.Expr, rhs: Ast.Expr, arg: K.Term, res: K.Term, want: Coll.Option[K.Term]): Ty.Ex = + val Ty.Ex(st1, _, el) = Ty.expr(cx, st, bs, l, Coll.Some(arg)) + val Ty.Ex(st2, _, er) = Ty.expr(cx, st1, bs, rhs, Coll.Some(arg)) + Ty.lit(st2, line, res, want, El.Bin(line, op, el, er)) + +def Ty.eqOp {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, op: Ast.BinOp, l: Ast.Expr, rhs: Ast.Expr, want: Coll.Option[K.Term]): Ty.Ex = + val Ty.Ex(st1, tl, el) = Ty.expr(cx, st, bs, l, Coll.None) + val Ty.Ex(st2, _, er) = Ty.expr(cx, st1, bs, rhs, Coll.Some(tl)) + Ty.lit(st2, line, Ty.con("Bool"), want, El.Bin(line, op, el, er)) + +// ── match: the scrutinee is an enum E[args]; each arm binds its case fields with E's binders at args ── +def Ty.arms {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, ts: K.Term, es: El.Expr, as: Coll.List[Ast.Arm], want: Coll.Option[K.Term]): Ty.Ex = as match + case Coll.Nil => Ty.bad(st, line) + case Coll.Cons(a, rest) => + val Ty.Cx(_, enums, _, _, _, _, _) = cx + val st0 = Ty.missingCase(enums, as) match + case Coll.Some(c) => Ty.clash(st, Ty.NotExhaustive(line, c)) + case Coll.None => st + val Ty.AEx(st1, t1, ea) = Ty.arm(cx, st0, bs, ts, a, want) + Ty.armsSame(cx, st1, bs, line, ts, es, rest, t1, Coll.Cons(ea, Coll.Nil)) + +// the arms after the first: each must have the first's type; the elaborated arms in order +def Ty.armsSame {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, ts: K.Term, es: El.Expr, as: Coll.List[Ast.Arm], t: K.Term, acc: Coll.List[El.Arm]): Ty.Ex = as match + case Coll.Nil => Ty.Ex(st, t, El.Match(line, es, ts, Coll.rev(acc))) + case Coll.Cons(a, rest) => + val Ty.AEx(st1, _, ea) = Ty.arm(cx, st, bs, ts, a, Coll.Some(t)) + Ty.armsSame(cx, st1, bs, line, ts, es, rest, t, Coll.Cons(ea, acc)) + +// an arm: its type and its elaborated form +enum Ty.AEx: + case Ty.AEx(st: Ty.St, t: K.Term, a: El.Arm) + +def Ty.arm {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], ts: K.Term, a: Ast.Arm, want: Coll.Option[K.Term]): Ty.AEx = + val Ast.Arm(line, p, b) = a + val Ty.Cx(_, es, _, _, _, _, _) = cx + val Ty.Ex(st9, t9, e9) = p match + case Ast.PAny => Ty.expr(cx, st, bs, b, want) + case Ast.PCase(c, binds) => Ty.caseNamed(es, c) match + case Coll.None => Ty.expr(cx, Ty.clash(st, Ty.Unknown(line, c)), bs, b, want) + case Coll.Some(co) => + val Ty.CaseOf(e, cs) = co + val Ast.Case(_, _, fields) = cs + val Ty.Open(st1, tv, vars) = Ty.openEnum(st, e) + val st1b = if Coll.length(binds) == Coll.length(fields) then st1 else Ty.clash(st1, Ty.PatArity(line, c)) + val st2 = Ty.expect(st1b, line, ts, Ty.enumTerm(e, vars)) + Ty.expr(cx, st2, Ty.bindFields(binds, fields, tv, bs), b, want) + Ty.AEx(st9, t9, El.Arm(line, p, e9)) + +def Ty.bindFields {r: Region} (xs: Coll.List[Sym.Sym], fs: Coll.List[Ast.Binder], tv: Coll.List[Ty.Bind], bs: Coll.List[Ty.Bind]): Coll.List[Ty.Bind] = xs match + case Coll.Nil => bs + case Coll.Cons(x, rest) => fs match + case Coll.Nil => bs + case Coll.Cons(f, frest) => + val Ast.Binder(_, _, ft) = f + Ty.bindFields(rest, frest, tv, if rt_str_eq(Sym.str(x), "_") then bs else Coll.Cons(Ty.Bind(x, Ty.term(ft, tv)), bs)) + +// ── blocks: val/var bind (an annotation is the expected type), handle binds a capability of the handler's protocol; +// acc = the elaborated statements so far, reversed ── +def Ty.block {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, ss: Coll.List[Ast.Stmt], last: Ast.Expr, want: Coll.Option[K.Term], acc: Coll.List[El.Stmt]): Ty.Ex = ss match + case Coll.Nil => + val Ty.Ex(st1, t, el) = Ty.expr(cx, st, bs, last, want) + Ty.Ex(st1, t, El.Block(line, Coll.rev(acc), el)) + case Coll.Cons(s, rest) => s match + case Ast.Val(sl, x, ann, e) => Ty.bindStmt(cx, st, bs, line, sl, x, ann, e, false, rest, last, want, acc) + case Ast.Var(sl, x, ann, e) => Ty.bindStmt(cx, st, bs, line, sl, x, ann, e, true, rest, last, want, acc) + case Ast.Handle(sl, x, h, xs) => + val Ty.Cx(_, _, _, hs, _, mode, _) = cx + val Ty.Es(st1, eargs) = Ty.exprs(cx, Ty.pureHandle(mode, st, sl, h), bs, xs, Coll.Nil) + Ty.block(cx, st1, Coll.Cons(Ty.Bind(x, K.Con(Ty.protoOf(hs, h), Coll.Nil)), bs), line, rest, last, want, Coll.Cons(El.Handle(sl, x, h, eargs), acc)) + case Ast.Do(e) => + val Ty.Ex(st1, _, ee) = Ty.expr(cx, st, bs, e, Coll.None) + Ty.block(cx, st1, bs, line, rest, last, want, Coll.Cons(El.Do(ee), acc)) + // a loop invariant or measure: checked, erased + case Ast.Check(_, k, e) => + val want2 = k match + case Ast.LInvariant => Ty.con("Bool") + case Ast.LDecreases => Ty.con("I64") + val Ty.Ex(st1, _, _) = Ty.expr(cx, st, bs, e, Coll.Some(want2)) + Ty.block(cx, st1, bs, line, rest, last, want, acc) + +def Ty.exprs {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], xs: Coll.List[Ast.Expr], acc: Coll.List[El.Expr]): Ty.Es = xs match + case Coll.Nil => Ty.Es(st, Coll.rev(acc)) + case Coll.Cons(x, rest) => + val Ty.Ex(st1, _, ex) = Ty.expr(cx, st, bs, x, Coll.None) + Ty.exprs(cx, st1, bs, rest, Coll.Cons(ex, acc)) + +def Ty.bindStmt {r: Region} (cx: Ty.Cx, st: Ty.St, bs: Coll.List[Ty.Bind], line: I64, sl: I64, x: Sym.Sym, ann: Coll.Option[Ast.Ty], e: Ast.Expr, mut: Bool, rest: Coll.List[Ast.Stmt], last: Ast.Expr, want: Coll.Option[K.Term], acc: Coll.List[El.Stmt]): Ty.Ex = + val wa: Coll.Option[K.Term] = ann match + case Coll.None => Coll.None + case Coll.Some(t) => Coll.Some(Ty.term(t, Coll.Nil)) + val Ty.Ex(st1, te, ee) = Ty.expr(cx, st, bs, e, wa) + val tx = wa match + case Coll.None => te + case Coll.Some(w) => w + Ty.block(cx, st1, Coll.Cons(Ty.Bind(x, tx), bs), line, rest, last, want, Coll.Cons(El.Val(sl, x, tx, mut, ee), acc)) + +def Ty.protoOf(hs: Coll.List[Ast.Handler], h: Sym.Sym): Sym.Sym = hs match + case Coll.Nil => h + case Coll.Cons(x, rest) => + val Ast.Handler(_, n, p, _) = x + if Sym.eq(n, h) then p else Ty.protoOf(rest, h) + +// ── a def: params and {} binders as locals, binders rigid, the body checked against the declared result ── +enum Ty.FnEx: + case Ty.FnEx(st: Ty.St, f: El.Fn) + +def Ty.fn {r: Region} (cx: Ty.Cx, st0: Ty.St, f: Ast.Fn): Ty.FnEx = + val Ast.Fn(line, name, gs, ps, ret, _, body) = f + val Ty.Cx(_, _, protos, _, _, _, _) = cx + val tps = Ty.tparams(gs, Coll.Nil) + val tv = Ty.rigid(tps, Coll.Nil) + val ev = Ty.evidence(gs, Coll.Nil) + val bs = Ty.binds(ps, tv, Ty.binds(ev, tv, Coll.Nil)) + val rt = Ty.term(ret, tv) + val caps = Ty.capNames(protos, ev, Coll.Nil) + val eps = Ty.elParams(ps, tv, Coll.Nil) + val st = Ty.fnShape(cx, st0, line, tps, ps) + body match + case Ast.Extern => Ty.FnEx(st, El.Fn(line, name, tps, caps, eps, rt, El.Extern)) + case Ast.Def(_, e) => + val Ty.Ex(st1, _, eb) = Ty.expr(cx, st, bs, e, Coll.Some(rt)) + Ty.FnEx(st1, El.Fn(line, name, tps, caps, eps, rt, El.Def(eb))) + case Ast.Spec(_, e) => + val Ty.Ex(st1, _, eb) = Ty.expr(Ty.comptime(cx), st, bs, e, Coll.Some(rt)) + Ty.FnEx(st1, El.Fn(line, name, tps, caps, eps, rt, El.Spec(eb))) + +// the {} binders of a protocol type, in written order (leading C params) +def Ty.capNames {r: Region} (ps: Coll.List[Ast.Proto], ev: Coll.List[Ast.Binder], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = ev match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(b, rest) => + val Ast.Binder(_, x, t) = b + val Ast.Ty(_, n, _, _, _) = t + Ty.capNames(ps, rest, if Ty.isProto(ps, n) then Coll.Cons(x, acc) else acc) + +def Ty.elParams {r: Region} (ps: Coll.List[Ast.Binder], tv: Coll.List[Ty.Bind], acc: Coll.List[El.Param]): Coll.List[El.Param] = ps match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(p, rest) => + val Ast.Binder(_, x, t) = p + Ty.elParams(rest, tv, Coll.Cons(El.Param(x, Ty.term(t, tv)), acc)) + +def Ty.binds {r: Region} (ps: Coll.List[Ast.Binder], tv: Coll.List[Ty.Bind], acc: Coll.List[Ty.Bind]): Coll.List[Ty.Bind] = ps match + case Coll.Nil => acc + case Coll.Cons(p, rest) => + val Ast.Binder(_, x, t) = p + Ty.binds(rest, tv, Coll.Cons(Ty.Bind(x, Ty.term(t, tv)), acc)) + +def Ty.evidence {r: Region} (gs: Coll.List[Ast.Group], acc: Coll.List[Ast.Binder]): Coll.List[Ast.Binder] = gs match + case Coll.Nil => acc + case Coll.Cons(g, rest) => g match + case Ast.Evidence(bs) => Ty.evidence(rest, Coll.revOnto(Coll.rev(bs), acc)) + case Ast.Types(_) => Ty.evidence(rest, acc) + case Ast.Facts(_) => Ty.evidence(rest, acc) + +// ── the program: every def and handler fn; then each instance must be solved ── +enum Ty.Result: + case Ty.Result(clashes: Coll.List[Ty.Clash], insts: Coll.List[Ty.Inst], s: Coll.IMap[K.Term], fns: Coll.List[El.Fn], hs: Coll.List[El.Handler], gvs: Coll.List[El.Given]) + +def Ty.cxOf {r: Region} (ds: Coll.List[Ast.Decl], fns: Coll.List[Ast.Fn], es: Coll.List[Ast.Enum], ps: Coll.List[Ast.Proto], hs: Coll.List[Ast.Handler], trs: Coll.List[Ast.Trait]): Ty.Cx = ds match + case Coll.Nil => Ty.Cx(fns, es, ps, hs, trs, Ty.Run, Coll.sEmpty()) + case Coll.Cons(d, rest) => d match + case Ast.DFn(f) => Ty.cxOf(rest, Coll.Cons(f, fns), es, ps, hs, trs) + case Ast.DEnum(e) => Ty.cxOf(rest, fns, Coll.Cons(e, es), ps, hs, trs) + case Ast.DProto(p) => Ty.cxOf(rest, fns, es, Coll.Cons(p, ps), hs, trs) + case Ast.DHandler(h) => Ty.cxOf(rest, fns, es, ps, Coll.Cons(h, hs), trs) + case Ast.DTrait(t) => Ty.cxOf(rest, fns, es, ps, hs, Coll.Cons(t, trs)) + case Ast.DGiven(_) => Ty.cxOf(rest, fns, es, ps, hs, trs) + case Ast.DType(_) => Ty.cxOf(rest, fns, es, ps, hs, trs) + +// the fns with effects first (s2/pure.srs): a spec body may call none of them +def Ty.check {r: Region} (ds: Coll.List[Ast.Decl]): Ty.Result = Ty.checkWith(ds, Coll.Nil) + +// tgs: the {} goals of the types the defs name (Tl.typeGoals), resolved with the goals of the calls +def Ty.checkWith {r: Region} (ds: Coll.List[Ast.Decl], tgs: Coll.List[Tl.Goal]): Ty.Result = + val Ty.Cx(fns0, es0, ps0, hs0, trs0, mode0, _) = Ty.cxOf(ds, Coll.Nil, Coll.Nil, Coll.Nil, Coll.Nil, Coll.Nil) + val nom = Ty.nominals(ds, Coll.sEmpty()) + val pr = if Ty.hasSpec(ds) then Pure.impure(ds) else Pure.Got(Coll.sEmpty()) + val imp: Coll.SMap[Bool] = pr match + case Pure.Got(m) => m + case Pure.RulesBad(_) => Coll.sEmpty() + val st0 = pr match + case Pure.Got(_) => Ty.St(Coll.Tip, 0, Coll.Nil, Coll.Nil, Coll.Nil, nom) + case Pure.RulesBad(rel) => Ty.St(Coll.Tip, 0, Coll.Cons(Ty.PureRules(rel), Coll.Nil), Coll.Nil, Coll.Nil, nom) + val cx = Ty.Cx(fns0, es0, ps0, hs0, trs0, mode0, imp) + val Ty.Fns(st1, fs, hs, gvs) = Ty.decls(cx, st0, ds, Coll.Nil, Coll.Nil, Coll.Nil) + val Ty.St(s, _, cs, is, gs, _) = st1 + val allGoals = Ty.typeGoals(fns0, tgs, Coll.rev(gs)) + val cs2 = Ty.externSlots(es0, Ty.externs(fns0, Coll.sEmpty()), s, is, Ty.goals(ps0, Ty.cands(ps0, ds, Coll.Nil), s, allGoals, cs)) + Ty.Result(Ty.unsolved(s, is, cs2), is, s, fs, hs, gvs) + +// the elaborated defs, handlers and givens so far (reversed while walking) +enum Ty.Fns: + case Ty.Fns(st: Ty.St, fs: Coll.List[El.Fn], hs: Coll.List[El.Handler], gvs: Coll.List[El.Given]) + +// top-level defs, handler fns (the prelude has Arena and Heap, lib/prelude.srs:38) and given fns +def Ty.decls {r: Region} (cx: Ty.Cx, st: Ty.St, ds: Coll.List[Ast.Decl], acc: Coll.List[El.Fn], hacc: Coll.List[El.Handler], gacc: Coll.List[El.Given]): Ty.Fns = ds match + case Coll.Nil => Ty.Fns(st, Coll.rev(acc), Coll.rev(hacc), Coll.rev(gacc)) + case Coll.Cons(d, rest) => d match + case Ast.DFn(f) => + val Ty.FnEx(st1, ef) = Ty.fn(cx, st, f) + Ty.decls(cx, st1, rest, Coll.Cons(ef, acc), hacc, gacc) + case Ast.DHandler(h) => + val Ast.Handler(_, hn, p, fs) = h + val Ty.Fns(st1, efs, _, _) = Ty.fnsEl(cx, st, fs, Coll.Nil) + Ty.decls(cx, st1, rest, acc, Coll.Cons(El.Handler(hn, p, efs), hacc), gacc) + // a given's fns see its binders: its [] binders are theirs, its {} evidence is local + case Ast.DGiven(g) => + val Ast.Given(_, gs, head, fs) = g + val Ty.Fns(st1, efs, _, _) = Ty.fnsEl(cx, Ty.givenShape(cx, st, g), Ty.underGroups(gs, fs, Coll.Nil), Coll.Nil) + val gv = El.Given(Ty.tparams(gs, Coll.Nil), Ty.binderNames(Ty.evidence(gs, Coll.Nil), Coll.Nil), Ty.term(head, Coll.Nil), efs) + Ty.decls(cx, st1, rest, acc, hacc, Coll.Cons(gv, gacc)) + case _ => Ty.decls(cx, st, rest, acc, hacc, gacc) + +def Ty.underGroups {r: Region} (gs: Coll.List[Ast.Group], fs: Coll.List[Ast.Fn], acc: Coll.List[Ast.Fn]): Coll.List[Ast.Fn] = fs match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(f, rest) => + val Ast.Fn(line, name, fgs, ps, ret, exit, body) = f + Ty.underGroups(gs, rest, Coll.Cons(Ast.Fn(line, name, Coll.revOnto(Coll.rev(gs), fgs), ps, ret, exit, body), acc)) + +def Ty.binderNames {r: Region} (bs: Coll.List[Ast.Binder], acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = bs match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(b, rest) => + val Ast.Binder(_, x, _) = b + Ty.binderNames(rest, Coll.Cons(x, acc)) + +// fns of a handler or given, elaborated in order +def Ty.fnsEl {r: Region} (cx: Ty.Cx, st: Ty.St, fs: Coll.List[Ast.Fn], acc: Coll.List[El.Fn]): Ty.Fns = fs match + case Coll.Nil => Ty.Fns(st, Coll.rev(acc), Coll.Nil, Coll.Nil) + case Coll.Cons(f, rest) => + val Ty.FnEx(st1, ef) = Ty.fn(cx, st, f) + Ty.fnsEl(cx, st1, rest, Coll.Cons(ef, acc)) + +// an instance with a type arg that is still a var after the whole program: CannotInfer +def Ty.unsolved {r: Region} (s: Coll.IMap[K.Term], is: Coll.List[Ty.Inst], cs: Coll.List[Ty.Clash]): Coll.List[Ty.Clash] = is match + case Coll.Nil => cs + case Coll.Cons(i, rest) => + val Ty.Inst(line, f, ts) = i + if Ty.ground(s, ts) then Ty.unsolved(s, rest, cs) else Ty.unsolved(s, rest, Coll.Cons(Ty.CannotInfer(line, f), cs)) + +def Ty.ground {r: Region} (s: Coll.IMap[K.Term], ts: Coll.List[K.Term]): Bool = ts match + case Coll.Nil => true + case Coll.Cons(t, rest) => if Ty.groundT(K.reify(s, t)) then Ty.ground(s, rest) else false + +def Ty.groundT(t: K.Term): Bool = t match + case K.Var(_) => false + case K.Int(_) => true + case K.Con(_, args) => Ty.groundAll(args) + +def Ty.groundAll(ts: Coll.List[K.Term]): Bool = ts match + case Coll.Nil => true + case Coll.Cons(t, rest) => if Ty.groundT(t) then Ty.groundAll(rest) else false + +def Ty.unTy(op: Ast.UnOp): Str = op match + case Ast.Neg => "I64" + case Ast.Not => "Bool" + +def Ty.lineOf(e: Ast.Expr): I64 = e match + case Ast.Int(l, _) => l + case Ast.Bool(l, _) => l + case Ast.Str(l, _) => l + case Ast.Unit(l) => l + case Ast.Name(l, _) => l + case Ast.Call(l, _, _, _, _) => l + case Ast.Method(l, _, _, _) => l + case Ast.Bin(l, _, _, _) => l + case Ast.Un(l, _, _) => l + case Ast.If(l, _, _, _) => l + case Ast.Match(l, _, _) => l + case Ast.Block(l, _, _) => l + case Ast.While(l, _, _) => l + case Ast.Assign(l, _, _) => l + case Ast.Quant(l, _, _, _, _) => l + +def Ty.comptime {r: Region} (cx: Ty.Cx): Ty.Cx = + val Ty.Cx(fns, es, ps, hs, trs, _, imp) = cx + Ty.Cx(fns, es, ps, hs, trs, Ty.Comptime, imp) + +// in a spec body (vic Q-U4) a call of a fn with effects, and any handle, is a clash +def Ty.pureCall {r: Region} (cx: Ty.Cx, st: Ty.St, line: I64, f: Sym.Sym): Ty.St = + val Ty.Cx(_, _, _, _, _, mode, imp) = cx + mode match + case Ty.Run => st + case Ty.Comptime => if Pure.has(imp, f) then Ty.clash(st, Ty.Impure(line, f)) else st + +def Ty.pureHandle {r: Region} (mode: Ty.Mode, st: Ty.St, line: I64, h: Sym.Sym): Ty.St = mode match + case Ty.Run => st + case Ty.Comptime => Ty.clash(st, Ty.SpecHandle(line, h)) + +// ── a match covers every case of its enum, or has a `_` arm: the first case no arm names ── +def Ty.missingCase {r: Region} (es: Coll.List[Ast.Enum], as: Coll.List[Ast.Arm]): Coll.Option[Sym.Sym] = + if Ty.hasAny(as) then Coll.None + else Ty.firstCase(as) match + case Coll.None => Coll.None + case Coll.Some(c) => Ty.caseNamed(es, c) match + case Coll.None => Coll.None + case Coll.Some(co) => + val Ty.CaseOf(e, _) = co + val Ast.Enum(_, _, _, cases) = e + Ty.uncovered(cases, as) + +def Ty.hasAny(as: Coll.List[Ast.Arm]): Bool = as match + case Coll.Nil => false + case Coll.Cons(a, rest) => + val Ast.Arm(_, p, _) = a + p match + case Ast.PAny => true + case Ast.PCase(_, _) => Ty.hasAny(rest) + +def Ty.firstCase {r: Region} (as: Coll.List[Ast.Arm]): Coll.Option[Sym.Sym] = as match + case Coll.Nil => Coll.None + case Coll.Cons(a, rest) => + val Ast.Arm(_, p, _) = a + p match + case Ast.PCase(c, _) => Coll.Some(c) + case Ast.PAny => Ty.firstCase(rest) + +def Ty.uncovered {r: Region} (cs: Coll.List[Ast.Case], as: Coll.List[Ast.Arm]): Coll.Option[Sym.Sym] = cs match + case Coll.Nil => Coll.None + case Coll.Cons(c, rest) => + val Ast.Case(_, n, _) = c + if Ty.armNames(n, as) then Ty.uncovered(rest, as) else Coll.Some(n) + +def Ty.armNames(n: Sym.Sym, as: Coll.List[Ast.Arm]): Bool = as match + case Coll.Nil => false + case Coll.Cons(a, rest) => + val Ast.Arm(_, p, _) = a + p match + case Ast.PCase(c, _) => if Sym.eq(c, n) then true else Ty.armNames(n, rest) + case Ast.PAny => Ty.armNames(n, rest) + +def Ty.addGoal {r: Region} (st: Ty.St, g: Ty.Goal): Ty.St = + val Ty.St(s, n, cs, is, gs, nm) = st + Ty.St(s, n, cs, is, Coll.Cons(g, gs), nm) + +// ── trait goals (s1/given.srs): local evidence first, else the givens whose head matches, each with its own {} goals +// proved (fuel per step); the most specific head wins, on a draw the one with fewer {} binders (Scala3) ── +enum Ty.Cand: + case Ty.Cand(id: I64, tps: Coll.List[Sym.Sym], head: K.Term, evs: Coll.List[K.Term]) + +// a given's [] binders as rigid names in its head and in its {} goals of traits +def Ty.cands {r: Region} (ps: Coll.List[Ast.Proto], ds: Coll.List[Ast.Decl], acc: Coll.List[Ty.Cand]): Coll.List[Ty.Cand] = ds match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(d, rest) => d match + case Ast.DGiven(g) => + val Ast.Given(_, gs, head, _) = g + val tps = Ty.tparams(gs, Coll.Nil) + val tv = Ty.rigid(tps, Coll.Nil) + Ty.cands(ps, rest, Coll.Cons(Ty.Cand(Coll.length(acc), tps, Ty.term(head, tv), Ty.traitGoals(ps, Ty.evidence(gs, Coll.Nil), tv, Coll.Nil)), acc)) + case _ => Ty.cands(ps, rest, acc) + +def Ty.traitGoals {r: Region} (ps: Coll.List[Ast.Proto], bs: Coll.List[Ast.Binder], tv: Coll.List[Ty.Bind], acc: Coll.List[K.Term]): Coll.List[K.Term] = bs match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(b, rest) => + val Ast.Binder(_, _, t) = b + val Ast.Ty(_, n, _, _, _) = t + Ty.traitGoals(ps, rest, tv, if Ty.isProto(ps, n) then acc else Coll.Cons(Ty.term(t, tv), acc)) + +enum Ty.Res: + case Ty.Proved + case Ty.NoneFound + case Ty.Tie + case Ty.TwoLocals + case Ty.OutOfFuel + +def Ty.givenFuel(): I64 = 1000 + +// every goal of the program, with the final substitution; a goal that is not ground has a CannotInfer already +def Ty.goals {r: Region} (ps: Coll.List[Ast.Proto], cands: Coll.List[Ty.Cand], s: Coll.IMap[K.Term], gs: Coll.List[Ty.Goal], cs: Coll.List[Ty.Clash]): Coll.List[Ty.Clash] = gs match + case Coll.Nil => cs + case Coll.Cons(g, rest) => + val Ty.Goal(line, t0, locals, chosen) = g + val t = K.reify(s, t0) + if !Ty.groundT(t) then Ty.goals(ps, cands, s, rest, cs) + else if Ty.isProtoT(ps, t) then Ty.goals(ps, cands, s, rest, if Coll.length(Ty.localsOf(s, locals, t, Coll.Nil)) == 1 then cs else Coll.Cons(Ty.NoCap(line, Ty.headOf(t)), cs)) + else chosen match + case Coll.Some(x) => Ty.goals(ps, cands, s, rest, if Ty.localProves(s, locals, x, t) then cs else Coll.Cons(Ty.ChosenBad(line, t), cs)) + case Coll.None => Ty.goals(ps, cands, s, rest, Ty.resClash(line, t, Ty.resolve(cands, s, locals, t, Ty.givenFuel()), cs)) + +def Ty.resClash {r: Region} (line: I64, t: K.Term, res: Ty.Res, cs: Coll.List[Ty.Clash]): Coll.List[Ty.Clash] = res match + case Ty.Proved => cs + case Ty.NoneFound => Coll.Cons(Ty.NoGiven(line, t), cs) + case Ty.Tie => Coll.Cons(Ty.AmbigGivens(line, t), cs) + case Ty.TwoLocals => Coll.Cons(Ty.AmbigEvidence(line, t), cs) + case Ty.OutOfFuel => Coll.Cons(Ty.GivenFuel(line, t), cs) + +def Ty.localProves {r: Region} (s: Coll.IMap[K.Term], locals: Coll.List[Ty.Bind], x: Sym.Sym, t: K.Term): Bool = Ty.lookup(locals, x) match + case Coll.Some(u) => Mono.termEq(K.reify(s, u), t) + case Coll.None => false + +def Ty.resolve {r: Region} (cands: Coll.List[Ty.Cand], s: Coll.IMap[K.Term], locals: Coll.List[Ty.Bind], t: K.Term, fuel: I64): Ty.Res = + if fuel <= 0 then Ty.OutOfFuel + else + val n = Coll.length(Ty.localsOf(s, locals, t, Coll.Nil)) + if n > 1 then Ty.TwoLocals + else if n == 1 then Ty.Proved + else Ty.viable(cands, cands, s, locals, t, fuel, Coll.Nil) match + case Ty.Viable(vs) => Ty.best(vs, vs) + case Ty.ViableFuel => Ty.OutOfFuel + +// the distinct local names whose type is t (a shadowed name counts once) +def Ty.localsOf {r: Region} (s: Coll.IMap[K.Term], bs: Coll.List[Ty.Bind], t: K.Term, acc: Coll.List[Sym.Sym]): Coll.List[Sym.Sym] = bs match + case Coll.Nil => acc + case Coll.Cons(b, rest) => + val Ty.Bind(x, u) = b + if !Ty.memberSym(x, acc) && Mono.termEq(K.reify(s, u), t) then Ty.localsOf(s, rest, t, Coll.Cons(x, acc)) else Ty.localsOf(s, rest, t, acc) + +enum Ty.Vs: + case Ty.Viable(cs: Coll.List[Ty.Cand]) + case Ty.ViableFuel + +// the givens whose head matches t and whose own goals are proved +def Ty.viable {r: Region} (all: Coll.List[Ty.Cand], cs: Coll.List[Ty.Cand], s: Coll.IMap[K.Term], locals: Coll.List[Ty.Bind], t: K.Term, fuel: I64, acc: Coll.List[Ty.Cand]): Ty.Vs = cs match + case Coll.Nil => Ty.Viable(Coll.rev(acc)) + case Coll.Cons(c, rest) => + val Ty.Cand(_, tps, head, evs) = c + Mono.matchT(tps, head, t, Coll.Some(Coll.Nil)) match + case Coll.None => Ty.viable(all, rest, s, locals, t, fuel, acc) + case Coll.Some(sub) => Ty.allProved(all, s, locals, Mono.applyAll(sub, evs, Coll.Nil), fuel - 1) match + case Ty.Proved => Ty.viable(all, rest, s, locals, t, fuel, Coll.Cons(c, acc)) + case Ty.OutOfFuel => Ty.ViableFuel + case _ => Ty.viable(all, rest, s, locals, t, fuel, acc) + +def Ty.allProved {r: Region} (all: Coll.List[Ty.Cand], s: Coll.IMap[K.Term], locals: Coll.List[Ty.Bind], gs: Coll.List[K.Term], fuel: I64): Ty.Res = gs match + case Coll.Nil => Ty.Proved + case Coll.Cons(g, rest) => Ty.resolve(all, s, locals, g, fuel) match + case Ty.Proved => Ty.allProved(all, s, locals, rest, fuel) + case Ty.NoneFound => Ty.NoneFound + case Ty.Tie => Ty.Tie + case Ty.TwoLocals => Ty.TwoLocals + case Ty.OutOfFuel => Ty.OutOfFuel + +// the one candidate better than every other one, else a tie (none: NoneFound) +def Ty.best {r: Region} (vs: Coll.List[Ty.Cand], all: Coll.List[Ty.Cand]): Ty.Res = vs match + case Coll.Nil => if Coll.length(all) == 0 then Ty.NoneFound else Ty.Tie + case Coll.Cons(c, rest) => if Ty.beatsAll(c, all) then Ty.Proved else Ty.best(rest, all) + +def Ty.beatsAll {r: Region} (c: Ty.Cand, all: Coll.List[Ty.Cand]): Bool = all match + case Coll.Nil => true + case Coll.Cons(d, rest) => if Ty.sameCand(c, d) || Ty.better(c, d) then Ty.beatsAll(c, rest) else false + +// the same given decl (two decls with one head are two candidates: a tie) +def Ty.sameCand(a: Ty.Cand, b: Ty.Cand): Bool = + val Ty.Cand(i, _, _, _) = a + val Ty.Cand(j, _, _, _) = b + i == j + +def Ty.better {r: Region} (a: Ty.Cand, b: Ty.Cand): Bool = + val Ty.Cand(_, atps, ah, aev) = a + val Ty.Cand(_, btps, bh, bev) = b + val ab = Mono.isSome(Mono.matchT(btps, bh, ah, Coll.Some(Coll.Nil))) + val ba = Mono.isSome(Mono.matchT(atps, ah, bh, Coll.Some(Coll.Nil))) + if ab && !ba then true else if ab && ba then Coll.length(aev) < Coll.length(bev) else false + +// ── shapes (s1/check.srs, s1/given.srs): what a use of a name, a def's binders and a given must look like ── +// evidence is only a method receiver, a capability only a {} arg: neither is a value +def Ty.nameUse {r: Region} (cx: Ty.Cx, st: Ty.St, line: I64, x: Sym.Sym, t: K.Term): Ty.St = + val Ty.Cx(_, _, ps, _, trs, _, _) = cx + K.walk(Ty.subst(st), t) match + case K.Con(n, _) => + if Ty.isProto(ps, n) then Ty.clash(st, Ty.CapValue(line, x)) + else if Ty.isTrait(trs, n) then Ty.clash(st, Ty.EvidenceValue(line, x)) + else st + case _ => st + +def Ty.isTrait(trs: Coll.List[Ast.Trait], n: Sym.Sym): Bool = trs match + case Coll.Nil => false + case Coll.Cons(t, rest) => + val Ast.Trait(_, m, _, _) = t + if Sym.eq(m, n) then true else Ty.isTrait(rest, n) + +def Ty.isEnum(es: Coll.List[Ast.Enum], n: Sym.Sym): Bool = es match + case Coll.Nil => false + case Coll.Cons(e, rest) => + val Ast.Enum(_, m, _, _) = e + if Sym.eq(m, n) then true else Ty.isEnum(rest, n) + +def Ty.isBuiltin(n: Sym.Sym): Bool = + val s = Sym.str(n) + rt_str_eq(s, "I64") || rt_str_eq(s, "Bool") || rt_str_eq(s, "Str") || rt_str_eq(s, "Unit") || rt_str_eq(s, "Ptr") || rt_str_eq(s, "Type") + +// x is a local whose type is protocol p +def Ty.isCapOf {r: Region} (s: Coll.IMap[K.Term], bs: Coll.List[Ty.Bind], x: Sym.Sym, p: Sym.Sym): Bool = Ty.lookup(bs, x) match + case Coll.None => false + case Coll.Some(t) => K.walk(s, t) match + case K.Con(n, args) => Sym.eq(n, p) && Coll.length(args) == 0 + case _ => false + +// a [] binder may not hide a type; a capability is a {} binder, never a value param +def Ty.fnShape {r: Region} (cx: Ty.Cx, st: Ty.St, line: I64, tps: Coll.List[Sym.Sym], ps: Coll.List[Ast.Binder]): Ty.St = + Ty.capParams(cx, Ty.hides(cx, st, line, tps), ps) + +def Ty.hides {r: Region} (cx: Ty.Cx, st: Ty.St, line: I64, tps: Coll.List[Sym.Sym]): Ty.St = tps match + case Coll.Nil => st + case Coll.Cons(x, rest) => + val Ty.Cx(_, es, ps, _, trs, _, _) = cx + val known = Ty.isBuiltin(x) || Ty.isEnum(es, x) || Ty.isProto(ps, x) || Ty.isTrait(trs, x) + Ty.hides(cx, if known then Ty.clash(st, Ty.BinderHides(line, x)) else st, line, rest) + +def Ty.capParams {r: Region} (cx: Ty.Cx, st: Ty.St, ps: Coll.List[Ast.Binder]): Ty.St = ps match + case Coll.Nil => st + case Coll.Cons(b, rest) => + val Ast.Binder(line, x, t) = b + val Ast.Ty(_, n, _, _, _) = t + val Ty.Cx(_, _, protos, _, _, _, _) = cx + Ty.capParams(cx, if Ty.isProto(protos, n) then Ty.clash(st, Ty.CapParam(line, x)) else st, rest) + +// a given: its head names a trait with that many args; its fns are exactly the trait's methods, each with the trait's +// signature at the head's args; each [] binder occurs in the head +def Ty.givenShape {r: Region} (cx: Ty.Cx, st: Ty.St, g: Ast.Given): Ty.St = + val Ast.Given(line, gs, head, fs) = g + val Ast.Ty(_, tn, targs, _, _) = head + val Ty.Cx(_, _, _, _, trs, _, _) = cx + val st1 = Ty.inHead(st, line, Ty.tparams(gs, Coll.Nil), head) + Ty.traitNamed(trs, tn) match + case Coll.None => Ty.clash(st1, Ty.Unknown(line, tn)) + case Coll.Some(tr) => + val Ast.Trait(_, _, tgs, sigs) = tr + val ttps = Ty.tparams(tgs, Coll.Nil) + if Coll.length(ttps) != Coll.length(targs) then Ty.clash(st1, Ty.TraitArity(line, tn)) + else + val tps = Ty.tparams(gs, Coll.Nil) + val tv = Ty.rigid(tps, Coll.Nil) + val sub = Ty.zipBind(ttps, Ty.terms(targs, tv, Coll.Nil), Coll.Nil) + Ty.missing(sigs, fs, line, Ty.methods(sigs, fs, sub, tv, st1)) + +def Ty.traitNamed {r: Region} (trs: Coll.List[Ast.Trait], n: Sym.Sym): Coll.Option[Ast.Trait] = trs match + case Coll.Nil => Coll.None + case Coll.Cons(t, rest) => + val Ast.Trait(_, m, _, _) = t + if Sym.eq(m, n) then Coll.Some(t) else Ty.traitNamed(rest, n) + +def Ty.inHead {r: Region} (st: Ty.St, line: I64, tps: Coll.List[Sym.Sym], head: Ast.Ty): Ty.St = tps match + case Coll.Nil => st + case Coll.Cons(x, rest) => Ty.inHead(if Ty.occurs(x, head) then st else Ty.clash(st, Ty.NotInHead(line, x)), line, rest, head) + +def Ty.occurs(x: Sym.Sym, t: Ast.Ty): Bool = + val Ast.Ty(_, n, args, _, _) = t + if Sym.eq(x, n) then true else Ty.occursAll(x, args) + +def Ty.occursAll(x: Sym.Sym, ts: Coll.List[Ast.Ty]): Bool = ts match + case Coll.Nil => false + case Coll.Cons(t, rest) => if Ty.occurs(x, t) then true else Ty.occursAll(x, rest) + +// each fn of the given: a method of the trait, with its signature (params and result at the head's args) +def Ty.methods {r: Region} (sigs: Coll.List[Ast.Fn], fs: Coll.List[Ast.Fn], sub: Coll.List[Ty.Bind], tv: Coll.List[Ty.Bind], st: Ty.St): Ty.St = fs match + case Coll.Nil => st + case Coll.Cons(f, rest) => + val Ast.Fn(line, n, _, ps, ret, _, _) = f + val st1 = Ty.fnNamed(sigs, n) match + case Coll.None => Ty.clash(st, Ty.NotMethod(line, n)) + case Coll.Some(m) => + val Ast.Fn(_, _, _, mps, mret, _, _) = m + val same = Mono.termEq(Ty.term(ret, tv), Ty.term(mret, sub)) && Mono.termsEq(Ty.binderTerms(ps, tv, Coll.Nil), Ty.binderTerms(mps, sub, Coll.Nil)) + if same then st else Ty.clash(st, Ty.SigDiffers(line, n)) + Ty.methods(sigs, rest, sub, tv, st1) + +def Ty.binderTerms {r: Region} (bs: Coll.List[Ast.Binder], tv: Coll.List[Ty.Bind], acc: Coll.List[K.Term]): Coll.List[K.Term] = bs match + case Coll.Nil => Coll.rev(acc) + case Coll.Cons(b, rest) => + val Ast.Binder(_, _, t) = b + Ty.binderTerms(rest, tv, Coll.Cons(Ty.term(t, tv), acc)) + +def Ty.missing {r: Region} (sigs: Coll.List[Ast.Fn], fs: Coll.List[Ast.Fn], line: I64, st: Ty.St): Ty.St = sigs match + case Coll.Nil => st + case Coll.Cons(m, rest) => + val Ast.Fn(_, n, _, _, _, _, _) = m + val st1 = Ty.fnNamed(fs, n) match + case Coll.Some(_) => st + case Coll.None => Ty.clash(st, Ty.MissingMethod(line, n)) + Ty.missing(rest, fs, line, st1) + +// a generic extern's [] slots are void*: each type arg it is called at must be a pointer (an enum or Ptr) +def Ty.externSlots {r: Region} (es: Coll.List[Ast.Enum], ext: Coll.SMap[Bool], s: Coll.IMap[K.Term], is: Coll.List[Ty.Inst], cs: Coll.List[Ty.Clash]): Coll.List[Ty.Clash] = is match + case Coll.Nil => cs + case Coll.Cons(i, rest) => + val Ty.Inst(line, f, ts) = i + Ty.externSlots(es, ext, s, rest, if Pure.has(ext, f) then Ty.ptrSlots(es, s, line, ts, cs) else cs) + +// the generic externs, by name +def Ty.externs {r: Region} (fs: Coll.List[Ast.Fn], m: Coll.SMap[Bool]): Coll.SMap[Bool] = fs match + case Coll.Nil => m + case Coll.Cons(g, rest) => + val Ast.Fn(_, n, _, _, _, _, body) = g + val m2 = body match + case Ast.Extern => Coll.sInsert(m, n, true) + case _ => m + Ty.externs(rest, m2) + +def Ty.ptrSlots {r: Region} (es: Coll.List[Ast.Enum], s: Coll.IMap[K.Term], line: I64, ts: Coll.List[K.Term], cs: Coll.List[Ty.Clash]): Coll.List[Ty.Clash] = ts match + case Coll.Nil => cs + case Coll.Cons(t0, rest) => + val t = K.reify(s, t0) + val ok: Bool = t match + case K.Con(n, _) => Ty.isEnum(es, n) || rt_str_eq(Sym.str(n), "Ptr") + case _ => true + Ty.ptrSlots(es, s, line, rest, if ok then cs else Coll.Cons(Ty.ExternSlot(line, t), cs)) + +// the impure set is read only in spec bodies: a program without a spec def needs none +def Ty.hasSpec(ds: Coll.List[Ast.Decl]): Bool = ds match + case Coll.Nil => false + case Coll.Cons(d, rest) => d match + case Ast.DFn(f) => + val Ast.Fn(_, _, _, _, _, _, body) = f + body match + case Ast.Spec(_, _) => true + case _ => Ty.hasSpec(rest) + case _ => Ty.hasSpec(rest) + +// a protocol goal (a type's {f: File} binder) is a capability in scope, not a given +def Ty.isProtoT(ps: Coll.List[Ast.Proto], t: K.Term): Bool = t match + case K.Con(n, _) => Ty.isProto(ps, n) + case _ => false + +def Ty.headOf {r: Region} (t: K.Term): Sym.Sym = t match + case K.Con(n, _) => n + case _ => Sym.of("?") + +// each type goal under its def's binders: [] rigid, {} the locals that may prove it +def Ty.typeGoals {r: Region} (fns: Coll.List[Ast.Fn], tgs: Coll.List[Tl.Goal], acc: Coll.List[Ty.Goal]): Coll.List[Ty.Goal] = tgs match + case Coll.Nil => acc + case Coll.Cons(g, rest) => + val Tl.Goal(line, f, goal) = g + Ty.fnNamed(fns, f) match + case Coll.None => Ty.typeGoals(fns, rest, acc) + case Coll.Some(fd) => + val Ast.Fn(_, _, gs, _, _, _, _) = fd + val tv = Ty.rigid(Ty.tparams(gs, Coll.Nil), Coll.Nil) + Ty.typeGoals(fns, rest, Coll.Cons(Ty.Goal(line, Ty.term(goal, tv), Ty.binds(Ty.evidence(gs, Coll.Nil), tv, Coll.Nil), Coll.None), acc)) diff --git a/bench/corpus/s2c/main.srs b/bench/corpus/s2c/main.srs new file mode 100644 index 00000000..cc769237 --- /dev/null +++ b/bench/corpus/s2c/main.srs @@ -0,0 +1,376 @@ +// the s2 compiler (self-host rung B3, vic/c/s2-selfhost.md): `s2c a.srs b.srs ... > out.c`. the decls of all files form +// one program. errors are data until main: every one is reported on stderr, and the exit code is 1. + +// a file that did not read or parse (line: numbered across files, as every line of the program) +enum S2c.Err: + case S2c.NoFile(path: Str) + case S2c.Syntax(line: I64, want: Str) + +// a source file: its path, the number of its first line, its text. lines are numbered across the files, so a line +// names its file (Parse.sourceFrom) +enum S2c.File: + case S2c.File(path: Str, base: I64, text: Str) + +enum S2c.Read: + case S2c.Read(ds: Coll.List[Ast.Decl], errs: Coll.List[S2c.Err], files: Coll.List[S2c.File]) + +// the args from i on, each a source file, in order; base = the number of the next file's first line +def S2c.read {r: Region} (i: I64, base: I64, ds: Coll.List[Ast.Decl], errs: Coll.List[S2c.Err], fs: Coll.List[S2c.File]): S2c.Read = + if i >= rt_argc() then S2c.Read(Coll.rev(ds), Coll.rev(errs), fs) + else + val p = rt_arg(i) + val src = rt_read_file(p) + if rt_str_len(src) < 0 then S2c.read(i + 1, base, ds, Coll.Cons(S2c.NoFile(p), errs), fs) + else + val fs2 = Coll.Cons(S2c.File(p, base, src), fs) + val next = base + S2c.lineCount(src, 0, 1) + Parse.sourceFrom(src, base) match + case Parse.Ok(fds, _) => S2c.read(i + 1, next, Coll.revOnto(fds, ds), errs, fs2) + case Parse.Err(line, want) => S2c.read(i + 1, next, ds, Coll.Cons(S2c.Syntax(line, want), errs), fs2) + +def S2c.lineCount(s: Str, i: I64, n: I64): I64 = + if i >= rt_str_len(s) then n else S2c.lineCount(s, i + 1, if rt_str_at(s, i) == 10 then n + 1 else n) + +// ── diagnostics (vic Q-E1, 2026-11-09): error[code]: what / --> file:line / the source line / expected, found / help ── +// what a diagnostic names after its title: nothing, a name, a type, or the type wanted and the type found +enum S2c.What: + case S2c.Plain + case S2c.Name(n: Sym.Sym) + case S2c.Type(t: K.Term) + case S2c.Want(want: K.Term, got: K.Term) + case S2c.Text(s: Str) + +def S2c.diag {r: Region} (fs: Coll.List[S2c.File], code: Str, line: I64, title: Str, w: S2c.What, help: Str): Unit = + rt_eprint("error[") + rt_eprint(code) + rt_eprint("]: ") + rt_eprint(title) + w match + case S2c.Name(n) => + rt_eprint(" '") + rt_eprint(Sym.str(n)) + rt_eprint("'") + case S2c.Text(x) => + rt_eprint(" ") + rt_eprint(x) + case S2c.Type(t) => + rt_eprint(" ") + S2c.term(t) + case _ => () + rt_eprint("\n") + S2c.fileOf(fs, line) match + case Coll.Some(f) => + val S2c.File(p, base, text) = f + val k = line - base + 1 + rt_eprint(" --> ") + rt_eprint(p) + rt_eprint(":") + rt_eprint_i64(k) + rt_eprint("\n |\n") + S2c.pad(k) + rt_eprint_i64(k) + rt_eprint(" | ") + rt_eprint(S2c.lineText(text, k, 0, 1)) + rt_eprint("\n |\n") + case Coll.None => () + w match + case S2c.Want(want, got) => + rt_eprint(" = expected: ") + S2c.term(want) + rt_eprint("\n = found: ") + S2c.term(got) + rt_eprint("\n") + case _ => () + rt_eprint(" = help: ") + rt_eprint(help) + rt_eprint("\n") + +// the file a line is in: the last one whose first line is at or before it (files are kept latest first) +def S2c.fileOf {r: Region} (fs: Coll.List[S2c.File], line: I64): Coll.Option[S2c.File] = fs match + case Coll.Nil => Coll.None + case Coll.Cons(f, rest) => + val S2c.File(_, base, _) = f + if line >= base then Coll.Some(f) else S2c.fileOf(rest, line) + +def S2c.pad(k: I64): Unit = if k < 10 then rt_eprint(" ") else if k < 100 then rt_eprint(" ") else () + +// line k of s (1-based), without its newline +def S2c.lineText(s: Str, k: I64, i: I64, n: I64): Str = + if n == k then rt_str_slice(s, i, S2c.lineEnd(s, i)) + else if i >= rt_str_len(s) then "" + else S2c.lineText(s, k, i + 1, if rt_str_at(s, i) == 10 then n + 1 else n) + +def S2c.lineEnd(s: Str, i: I64): I64 = if i >= rt_str_len(s) || rt_str_at(s, i) == 10 then i else S2c.lineEnd(s, i + 1) + +def S2c.showErrs {r: Region} (fs: Coll.List[S2c.File], es: Coll.List[S2c.Err]): Unit = es match + case Coll.Nil => () + case Coll.Cons(e, rest) => + e match + case S2c.NoFile(p) => + rt_eprint("error[no-file]: cannot read ") + rt_eprint(p) + rt_eprint("\n = help: check the path and that the file is readable\n") + case S2c.Syntax(line, want) => S2c.diag(fs, "parse", line, "parse error, expected", S2c.Text(want), "fix the syntax on this line") + S2c.showErrs(fs, rest) + +def S2c.showClashes {r: Region} (fs: Coll.List[S2c.File], s: Coll.IMap[K.Term], cs: Coll.List[Ty.Clash]): Unit = cs match + case Coll.Nil => () + case Coll.Cons(c, rest) => + c match + case Ty.Mismatch(l, got, want) => S2c.diag(fs, "mismatch", l, "the value has the wrong type", S2c.Want(K.reify(s, want), K.reify(s, got)), "give a value of the expected type, or change the declared type") + case Ty.Unknown(l, n) => S2c.diag(fs, "unknown-name", l, "unknown name", S2c.Name(n), "declare it, or fix its spelling (module members are written qualified: Foo.bar)") + case Ty.Arity(l, n) => S2c.diag(fs, "arity", l, "wrong number of args to", S2c.Name(n), "pass one arg per param of its declaration") + case Ty.NotEnum(l, t) => S2c.diag(fs, "not-enum", l, "a match needs an enum, not", S2c.Type(K.reify(s, t)), "match on a value of an enum type") + case Ty.NoOp(l, n) => S2c.diag(fs, "no-op", l, "no op or trait method", S2c.Name(n), "call an op of the capability's protocol, or a method of the evidence's trait") + case Ty.CannotInfer(l, n) => S2c.diag(fs, "cannot-infer", l, "cannot infer the type args of", S2c.Name(n), "write them: f[T](x), or annotate the val") + case Ty.NoCap(l, p) => S2c.diag(fs, "no-capability", l, "no single capability in scope of", S2c.Name(p), "open one (handle r = Arena()) or take it as a {} binder; with two, choose one: f{a}(x)") + case Ty.Impure(l, n) => S2c.diag(fs, "impure-call", l, "a spec def calls only pure fns, not", S2c.Name(n), "a spec def runs at compile time: call only fns with no effects") + case Ty.SpecHandle(l, h) => S2c.diag(fs, "spec-handle", l, "a spec def opens no handler, not", S2c.Name(h), "a spec def has no Region: build data without one") + case Ty.PureRules(rel) => S2c.diag(fs, "internal", 0, "the purity rules are ill-formed at", S2c.Name(rel), "a bug in s2: report it") + case Ty.NotExhaustive(l, n) => S2c.diag(fs, "not-exhaustive", l, "the match misses the case", S2c.Name(n), "add an arm for it, or a `_` arm") + case Ty.PatArity(l, n) => S2c.diag(fs, "pattern-arity", l, "the pattern binds another number of fields than", S2c.Name(n), "bind one name (or _) per field of the case") + case Ty.NoGiven(l, t) => S2c.diag(fs, "no-given", l, "no given for", S2c.Type(t), "declare a given for this type, or take the evidence as a {} binder") + case Ty.AmbigGivens(l, t) => S2c.diag(fs, "ambiguous-givens", l, "two givens tie for", S2c.Type(t), "make one head more specific, or choose the evidence: f{e}(x)") + case Ty.AmbigEvidence(l, t) => S2c.diag(fs, "ambiguous-evidence", l, "two local evidences prove", S2c.Type(t), "choose one: f{e}(x)") + case Ty.GivenFuel(l, t) => S2c.diag(fs, "given-fuel", l, "the given search ran out of fuel at", S2c.Type(t), "a given clause needs itself at a bigger type: break the loop") + case Ty.ChosenBad(l, t) => S2c.diag(fs, "chosen-evidence", l, "the chosen evidence does not prove", S2c.Type(t), "choose a local whose type is the goal") + case Ty.ChosenCount(l, n) => S2c.diag(fs, "chosen-count", l, "wrong number of chosen evidence for", S2c.Name(n), "choose one name per {} binder of the callee") + case Ty.ChosenNotCap(l, p) => S2c.diag(fs, "chosen-not-capability", l, "the chosen name is not a capability of", S2c.Name(p), "choose a local opened by a handler of this protocol") + case Ty.EvidenceValue(l, x) => S2c.diag(fs, "evidence-value", l, "evidence is only a method receiver, not a value:", S2c.Name(x), "call its methods: e.m(x)") + case Ty.CapValue(l, x) => S2c.diag(fs, "capability-value", l, "a capability is second-class, not a value:", S2c.Name(x), "pass it as a {} binder: f{c}(x)") + case Ty.BinderHides(l, x) => S2c.diag(fs, "binder-hides-type", l, "a [] binder hides the type", S2c.Name(x), "rename the binder") + case Ty.CapParam(l, x) => S2c.diag(fs, "capability-param", l, "a capability is a {} binder, not a param:", S2c.Name(x), "write it as {x: P} before the params") + case Ty.TraitArity(l, t) => S2c.diag(fs, "trait-arity", l, "wrong number of type args for the trait", S2c.Name(t), "give one type arg per [] binder of the trait") + case Ty.NotMethod(l, m) => S2c.diag(fs, "not-a-method", l, "not a method of the trait:", S2c.Name(m), "a given defines exactly the trait's methods") + case Ty.MissingMethod(l, m) => S2c.diag(fs, "missing-method", l, "the given misses the trait method", S2c.Name(m), "define it in the given") + case Ty.SigDiffers(l, m) => S2c.diag(fs, "method-signature", l, "the given method's signature differs from its trait:", S2c.Name(m), "use the trait's params and result at the given's head") + case Ty.NotInHead(l, x) => S2c.diag(fs, "binder-not-in-head", l, "a given [] binder is not in its head:", S2c.Name(x), "use each [] binder in the given's head") + case Ty.ExternSlot(l, t) => S2c.diag(fs, "extern-slot", l, "an extern [] binder is a pointer (void*), not", S2c.Type(t), "call the extern at an enum or Ptr type") + S2c.showClashes(fs, s, rest) + +def S2c.showTl {r: Region} (fs: Coll.List[S2c.File], es: Coll.List[Tl.Err]): Unit = es match + case Coll.Nil => () + case Coll.Cons(e, rest) => + e match + case Tl.Fuel(l, n) => S2c.diag(fs, "type-fuel", l, "type reduction ran out of fuel at", S2c.Name(n), "a type that names itself never ends: break the loop") + case Tl.NoCase(l, n) => S2c.diag(fs, "no-type-case", l, "no case of the match type matches in", S2c.Name(n), "add a case for this arg, or a `_` case") + case Tl.BadVal(l, n) => S2c.diag(fs, "no-compile-time-value", l, "a value arg has no compile-time value in", S2c.Name(n), "use literals, value params and pure defs (no effects, fuel bounded)") + case Tl.Arity(l, n) => S2c.diag(fs, "type-arity", l, "wrong number of type or value args for", S2c.Name(n), "give one arg per binder of the type") + case Tl.NoVals(l, n) => S2c.diag(fs, "value-args", l, "value args on a type that takes none:", S2c.Name(n), "drop the (...) after the type") + case Tl.ArgType(l, n) => S2c.diag(fs, "value-arg-type", l, "a value arg does not fit its binder's type in", S2c.Name(n), "give a value of the binder's type") + case Tl.BinderType(l, x) => S2c.diag(fs, "value-binder-type", l, "a value binder takes I64, Bool or Str:", S2c.Name(x), "use one of those types") + case Tl.PatType(l, n) => S2c.diag(fs, "value-pattern-type", l, "a value match pattern does not fit its binder's type in", S2c.Name(n), "use patterns of the binder's type") + S2c.showTl(fs, rest) + +// ── the phases: names, type level, types, flow (protocols, regions), then C; the first phase with errors stops ── +def S2c.compile {r: Region} (m: S2c.Mode, fs: Coll.List[S2c.File], ds: Coll.List[Ast.Decl]): I64 = Names.check(ds) match + case Names.Ok => S2c.facts(m, fs, ds) + case Names.Bad(cs) => + S2c.showNames(fs, cs) + 1 + case Names.RulesBad(rel) => S2c.internal("names", rel) + +def S2c.facts {r: Region} (m: S2c.Mode, fs: Coll.List[S2c.File], ds: Coll.List[Ast.Decl]): I64 = Fx.check(ds) match + case Fx.Ok => S2c.typed(m, fs, ds) + case Fx.Bad(cs) => + S2c.showFx(fs, cs) + 1 + case Fx.RulesBad(rel) => S2c.internal("facts", rel) + +def S2c.showFx {r: Region} (fs: Coll.List[S2c.File], cs: Coll.List[Fx.Clash]): Unit = cs match + case Coll.Nil => () + case Coll.Cons(c, rest) => + c match + case Fx.NotCap(l, x) => S2c.diag(fs, "fact-not-capability", l, "at: not a {} capability of this def or type:", S2c.Name(x), "name a {} capability binder of the def or type") + case Fx.BadState(l, s) => S2c.diag(fs, "unknown-state", l, "unknown protocol state", S2c.Name(s), "use a state the protocol declares") + case Fx.Twice(l, x) => S2c.diag(fs, "fact-twice", l, "two states of one capability in a fact group:", S2c.Name(x), "give each capability one state per group") + case Fx.NotOp(l, op) => S2c.diag(fs, "fact-not-op", l, "next: not an op of a capability of this def:", S2c.Name(op), "use an op of the protocol of one of the def's capabilities") + case Fx.UnknownRel(l, rel) => S2c.diag(fs, "unknown-relation", l, "unknown relation in facts:", S2c.Name(rel), "use at, next, or a rule def of a capability's protocol") + case Fx.RelArity(l, rel) => S2c.diag(fs, "relation-arity", l, "wrong number of args for relation", S2c.Name(rel), "give the rule def's number of args") + case Fx.Unbound(l, v) => S2c.diag(fs, "fact-unbound", l, "an exit fact variable is not bound by the entry facts:", S2c.Name(v), "bind it in an entry fact") + case Fx.ExitOther(l, rel) => S2c.diag(fs, "exit-fact", l, "an exit fact is an at, not", S2c.Name(rel), "write the exit state as at(cap, State)") + case Fx.Reserved(l, rel) => S2c.diag(fs, "reserved-relation", l, "reserved relation name:", S2c.Name(rel), "at and next are built in: rename the rule def") + case Fx.ClauseArity(l, rel) => S2c.diag(fs, "rule-arity", l, "rule defs of one relation differ in arity:", S2c.Name(rel), "give every rule def of a relation one arity") + case Fx.Unsafe(l, x) => S2c.diag(fs, "rule-unsafe", l, "a rule def param is not in its body:", S2c.Name(x), "use each param in the body") + case Fx.RuleUnknown(l, rel) => S2c.diag(fs, "rule-unknown", l, "unknown relation in rule:", S2c.Name(rel), "use next, at, or a rule def of this protocol") + case Fx.RuleOp(l, op) => S2c.diag(fs, "rule-op", l, "next: not an op of the protocol:", S2c.Name(op), "use an op of this protocol") + S2c.showFx(fs, rest) + +def S2c.typed {r: Region} (m: S2c.Mode, fs: Coll.List[S2c.File], ds: Coll.List[Ast.Decl]): I64 = + val Tl.W(xds, tes) = Tl.expand(ds) + tes match + case Coll.Cons(_, _) => + S2c.showTl(fs, Coll.rev(tes)) + 1 + case Coll.Nil => + val res = Ty.checkWith(xds, Tl.typeGoals(ds)) + val Ty.Result(cs, _, s, _, _, _) = res + cs match + case Coll.Cons(_, _) => + S2c.showClashes(fs, s, Coll.rev(cs)) + 1 + case Coll.Nil => S2c.flowed(m, fs, xds, res) + +def S2c.flowed {r: Region} (m: S2c.Mode, fs: Coll.List[S2c.File], ds: Coll.List[Ast.Decl], res: Ty.Result): I64 = + S2c.flowAll(S2c.flowCx(ds, Coll.Nil, Coll.Nil, Coll.Nil, Coll.Nil, Coll.Nil), ds, Coll.Nil) match + case S2c.FlowBad(rel) => S2c.internal("flow", rel) + case S2c.FlowOk(cs) => cs match + case Coll.Cons(_, _) => + S2c.showFlow(fs, Coll.rev(cs)) + 1 + case Coll.Nil => S2c.finish(m, fs, ds, res) + +enum S2c.Flowed: + case S2c.FlowOk(cs: Coll.List[Flow.Clash]) + case S2c.FlowBad(rel: Sym.Sym) + +def S2c.flowCx {r: Region} (ds: Coll.List[Ast.Decl], ps: Coll.List[Ast.Proto], hs: Coll.List[Ast.Handler], fs: Coll.List[Ast.Fn], es: Coll.List[Ast.Enum], ts: Coll.List[Ast.TypeDecl]): Flow.Cx = ds match + case Coll.Nil => Flow.Cx(ps, hs, fs, es, ts) + case Coll.Cons(d, rest) => d match + case Ast.DProto(p) => S2c.flowCx(rest, Coll.Cons(p, ps), hs, fs, es, ts) + case Ast.DHandler(h) => S2c.flowCx(rest, ps, Coll.Cons(h, hs), fs, es, ts) + case Ast.DFn(f) => S2c.flowCx(rest, ps, hs, Coll.Cons(f, fs), es, ts) + case Ast.DEnum(e) => S2c.flowCx(rest, ps, hs, fs, Coll.Cons(e, es), ts) + case Ast.DType(td) => S2c.flowCx(rest, ps, hs, fs, es, Coll.Cons(td, ts)) + case _ => S2c.flowCx(rest, ps, hs, fs, es, ts) + +// every def with a body: its flow clashes (all of them, in order) +def S2c.flowAll {r: Region} (cx: Flow.Cx, ds: Coll.List[Ast.Decl], acc: Coll.List[Flow.Clash]): S2c.Flowed = ds match + case Coll.Nil => S2c.FlowOk(acc) + case Coll.Cons(d, rest) => d match + case Ast.DFn(f) => + val Ast.Fn(_, _, _, _, _, _, body) = f + body match + case Ast.Def(_, _) => Flow.check(cx, f) match + case Flow.Ok => S2c.flowAll(cx, rest, acc) + case Flow.Bad(cs) => S2c.flowAll(cx, rest, Coll.revOnto(cs, acc)) + case Flow.RulesUnsafe(rel) => S2c.FlowBad(rel) + case Flow.RulesNegCycle(rel) => S2c.FlowBad(rel) + case Flow.RulesIllTyped(rel) => S2c.FlowBad(rel) + case _ => S2c.flowAll(cx, rest, acc) + case _ => S2c.flowAll(cx, rest, acc) + +def S2c.showNames {r: Region} (fs: Coll.List[S2c.File], cs: Coll.List[Names.Clash]): Unit = cs match + case Coll.Nil => () + case Coll.Cons(c, rest) => + c match + case Names.Dup(l, n) => S2c.diag(fs, "duplicate", l, "duplicate name", S2c.Name(n), "rename one of them") + case Names.Unknown(l, n) => S2c.diag(fs, "unknown-name", l, "unknown name", S2c.Name(n), "declare it, or fix its spelling (module members are written qualified: Foo.bar)") + case Names.NoType(l, n) => S2c.diag(fs, "unknown-type", l, "unknown type", S2c.Name(n), "declare it, or fix its spelling") + case Names.BadState(l, n) => S2c.diag(fs, "unknown-state", l, "unknown protocol state", S2c.Name(n), "use a state the protocol declares") + case Names.NoDrop(l, n) => S2c.diag(fs, "unknown-drop", l, "unknown drop op", S2c.Name(n), "drop one of the protocol's ops") + case Names.NoProto(l, n) => S2c.diag(fs, "not-a-protocol", l, "a handler of a name that is not a protocol:", S2c.Name(n), "write a handler for a protocol") + case Names.NoInit(l, n) => S2c.diag(fs, "handler-no-init", l, "a handler without init:", S2c.Name(n), "define def init(...): Ptr") + case Names.NoOp(l, n) => S2c.diag(fs, "handler-missing-op", l, "a handler misses the op", S2c.Name(n), "define every op of the protocol") + case Names.BadArity(l, n) => S2c.diag(fs, "handler-arity", l, "a handler fn has the wrong arity:", S2c.Name(n), "take self: Ptr first, then the op's params") + S2c.showNames(fs, rest) + +def S2c.showFlow {r: Region} (fs: Coll.List[S2c.File], cs: Coll.List[Flow.Clash]): Unit = cs match + case Coll.Nil => () + case Coll.Cons(c, rest) => + c match + case Flow.Stuck(l, n) => S2c.diag(fs, "op-not-allowed", l, "op not allowed in this state of the capability", S2c.Name(n), "call the ops in the order the protocol allows") + case Flow.Split(l, n) => S2c.diag(fs, "branch-states", l, "branches leave the capability in different states:", S2c.Name(n), "bring it to one state on every branch") + case Flow.Unended(l, n) => S2c.diag(fs, "capability-not-ended", l, "the capability does not end in its declared state:", S2c.Name(n), "end it (its drop op or an op into an end state) before its scope ends") + case Flow.Ambig(l, n) => S2c.diag(fs, "entry-facts-ambiguous", l, "entry facts with more than one solution at the call of", S2c.Name(n), "fix the capability states before the call") + case Flow.ExitBad(l, n) => S2c.diag(fs, "exit-state", l, "a capability ends in another state than the exit fact of", S2c.Name(n), "end it in the state the exit fact names") + case Flow.NoSol(l, n) => S2c.diag(fs, "entry-facts-unsolvable", l, "entry facts with no solution in", S2c.Name(n), "make the entry facts satisfiable") + case Flow.Dead(l, n) => S2c.diag(fs, "use-after-free", l, "use of a value after its region ended:", S2c.Name(n), "use it before the region ends, or allocate it in a longer region") + case Flow.Escape(l, n) => S2c.diag(fs, "region-escape", l, "a value escapes the scope of its region", S2c.Name(n), "allocate it in a region that outlives the block") + case Flow.Stale(l, x) => S2c.diag(fs, "stale-value", l, "the value needs its capability in the state its type names; it is in another state:", S2c.Name(x), "use it before the capability changes state") + S2c.showFlow(fs, rest) + +// a rule library that is not a Datalog program, or a clash of another shape: a bug in s2, reported as one +def S2c.internal(phase: Str, rel: Sym.Sym): I64 = + rt_eprint("srs internal: the ") + rt_eprint(phase) + rt_eprint(" rules are ill-formed at relation ") + rt_eprint(Sym.str(rel)) + rt_eprint("\n") + 2 + +// what a checked program becomes: C (the default), or the output of an s1 flag (vic 2026-11-09: s2 has every s1 flag) +enum S2c.Mode: + case S2c.EmitC + // --eval: "name value" for each nullary pure def but main, run at compile time + case S2c.EvalAll + // --hash: "name a.b.c.d", the content hash of every def and enum + case S2c.HashAll + // --store-check: write every hashed decl to the store, read it back, compare + case S2c.StoreCheck + +def S2c.finish {r: Region} (m: S2c.Mode, fs: Coll.List[S2c.File], ds: Coll.List[Ast.Decl], res: Ty.Result): I64 = m match + case S2c.StoreCheck => + Store.check(ds) + 0 + case S2c.HashAll => + Hs.print(ds) + 0 + case S2c.EmitC => + Emit.program(ds, res) + 0 + case S2c.EvalAll => Pure.impure(ds) match + case Pure.RulesBad(rel) => S2c.internal("purity", rel) + case Pure.Got(imp) => Ev.all(ds, imp) match + case Ev.Lines(ls) => + S2c.showLines(ls) + 0 + case Ev.Failed(e) => + e match + case Ev.Fuel(l, f) => S2c.diag(fs, "comptime-fuel", l, "comptime evaluation ran out of fuel at", S2c.Name(f), "the evaluation loops or runs too long: bound it") + case Ev.DivZero(l, f) => S2c.diag(fs, "comptime-div-zero", l, "comptime division by zero in", S2c.Name(f), "divide by a nonzero value") + case Ev.NoValue(l, f) => S2c.diag(fs, "comptime-no-value", l, "no compile-time value at", S2c.Name(f), "call only pure fns at compile time") + 1 + +def S2c.showLines(ls: Coll.List[Ev.Line]): Unit = ls match + case Coll.Nil => () + case Coll.Cons(l, rest) => + val Ev.Shown(n, v) = l + rt_print(Sym.str(n)) + rt_print(" ") + Ev.show(v) + rt_print("\n") + S2c.showLines(rest) + +// the flag in arg 1, if any; the files follow it +enum S2c.Args: + case S2c.Args(m: S2c.Mode, first: I64) + +def S2c.args {r: Region} (): S2c.Args = + if rt_argc() > 1 && rt_str_eq(rt_arg(1), "--eval") then S2c.Args(S2c.EvalAll, 2) + else if rt_argc() > 1 && rt_str_eq(rt_arg(1), "--hash") then S2c.Args(S2c.HashAll, 2) + else if rt_argc() > 1 && rt_str_eq(rt_arg(1), "--store-check") then S2c.Args(S2c.StoreCheck, 2) + else S2c.Args(S2c.EmitC, 1) + +def main(): I64 = + handle r = Arena() + val S2c.Args(m, first) = S2c.args() + val S2c.Read(ds, errs, fs) = S2c.read(first, 1, Coll.Nil, Coll.Nil, Coll.Nil) + errs match + case Coll.Cons(_, _) => + S2c.showErrs(fs, errs) + 1 + case Coll.Nil => S2c.compile(m, fs, ds) + +// a type as written: Name[arg, ...] +def S2c.term(t: K.Term): Unit = t match + case K.Con(n, args) => + rt_eprint(Sym.str(n)) + args match + case Coll.Nil => () + case Coll.Cons(a, rest) => + rt_eprint("[") + S2c.term(a) + S2c.terms(rest) + rt_eprint("]") + case K.Int(v) => rt_eprint_i64(v) + case K.Var(v) => + rt_eprint("?") + rt_eprint_i64(v) + +def S2c.terms(ts: Coll.List[K.Term]): Unit = ts match + case Coll.Nil => () + case Coll.Cons(t, rest) => + rt_eprint(", ") + S2c.term(t) + S2c.terms(rest) diff --git a/bench/corpus/tests/caps.out b/bench/corpus/tests/caps.out deleted file mode 100644 index f599e28b..00000000 --- a/bench/corpus/tests/caps.out +++ /dev/null @@ -1 +0,0 @@ -10 diff --git a/bench/corpus/tests/contracts.out b/bench/corpus/tests/contracts.out deleted file mode 100644 index 7ed6ff82..00000000 --- a/bench/corpus/tests/contracts.out +++ /dev/null @@ -1 +0,0 @@ -5 diff --git a/bench/corpus/tests/datalog.out b/bench/corpus/tests/datalog.out deleted file mode 100644 index eb2c7947..00000000 --- a/bench/corpus/tests/datalog.out +++ /dev/null @@ -1,17 +0,0 @@ -path(a, b) path(b, c) path(c, d) path(a, c) path(b, d) path(a, d) -unreach(e) -negcycle p -unsafe p -unsafe p -self(e) -from_a(b) -big(2) -valid -valid -invalid edge(x, y) -invalid path(a, d) -invalid path(a, d) -invalid path(a, b) -invalid path(c, a) -invalid unreach(a) -invalid p(a) diff --git a/bench/corpus/tests/facts.out b/bench/corpus/tests/facts.out deleted file mode 100644 index 7f8f011e..00000000 --- a/bench/corpus/tests/facts.out +++ /dev/null @@ -1 +0,0 @@ -7 diff --git a/bench/corpus/tests/facts_vars.out b/bench/corpus/tests/facts_vars.out deleted file mode 100644 index 8351c193..00000000 --- a/bench/corpus/tests/facts_vars.out +++ /dev/null @@ -1 +0,0 @@ -14 diff --git a/bench/corpus/tests/file_ok.out b/bench/corpus/tests/file_ok.out deleted file mode 100644 index aabe6ec3..00000000 --- a/bench/corpus/tests/file_ok.out +++ /dev/null @@ -1 +0,0 @@ -21 diff --git a/bench/corpus/tests/generic.out b/bench/corpus/tests/generic.out deleted file mode 100644 index edd536a3..00000000 --- a/bench/corpus/tests/generic.out +++ /dev/null @@ -1,4 +0,0 @@ -42 -0 -3 -3 diff --git a/bench/corpus/tests/generic_enum.out b/bench/corpus/tests/generic_enum.out deleted file mode 100644 index 0c9975ac..00000000 --- a/bench/corpus/tests/generic_enum.out +++ /dev/null @@ -1,4 +0,0 @@ -42 -1 -7 -5 diff --git a/bench/corpus/tests/given_local.out b/bench/corpus/tests/given_local.out deleted file mode 100644 index f599e28b..00000000 --- a/bench/corpus/tests/given_local.out +++ /dev/null @@ -1 +0,0 @@ -10 diff --git a/bench/corpus/tests/given_rank.out b/bench/corpus/tests/given_rank.out deleted file mode 100644 index ad1bcece..00000000 --- a/bench/corpus/tests/given_rank.out +++ /dev/null @@ -1,2 +0,0 @@ -123 -10 diff --git a/bench/corpus/tests/givens.out b/bench/corpus/tests/givens.out deleted file mode 100644 index 67727a37..00000000 --- a/bench/corpus/tests/givens.out +++ /dev/null @@ -1,5 +0,0 @@ -42 -10 -220 -2 -2 diff --git a/bench/corpus/tests/kanren.out b/bench/corpus/tests/kanren.out deleted file mode 100644 index e2bb8093..00000000 --- a/bench/corpus/tests/kanren.out +++ /dev/null @@ -1,8 +0,0 @@ -f(a, b) -c -_0 -fail -fail -fail -fail -fail diff --git a/bench/corpus/tests/kanren_fd.out b/bench/corpus/tests/kanren_fd.out deleted file mode 100644 index 7de7e7a1..00000000 --- a/bench/corpus/tests/kanren_fd.out +++ /dev/null @@ -1,36 +0,0 @@ -1 -2 -3 -ended -2 ; 3 -1 ; 2 -1 ; 3 -ended -2 ; 2 ; 4 -ended -ended -ended -2 -ended -2 -3 -ended -ended -2 -ended -1 -ended -ended -3 ; 3 -ended -2 ; 2 -3 ; 3 -ended -nofuel -1 ; 1 -2 ; 1 -3 ; 1 -1 ; 2 -2 ; 2 -3 ; 2 -ended diff --git a/bench/corpus/tests/kanren_neq.out b/bench/corpus/tests/kanren_neq.out deleted file mode 100644 index 1ee15bc6..00000000 --- a/bench/corpus/tests/kanren_neq.out +++ /dev/null @@ -1,16 +0,0 @@ --- --- -b --- -a ; _1 {_1=b} --- --- -b --- --- -a ; b --- -_0 --- -a ; _1 {_1=b} --- diff --git a/bench/corpus/tests/kanren_search.out b/bench/corpus/tests/kanren_search.out deleted file mode 100644 index 63b14868..00000000 --- a/bench/corpus/tests/kanren_search.out +++ /dev/null @@ -1,18 +0,0 @@ -cons(a, cons(b, nil)) -ended -nil ; cons(a, cons(b, nil)) -cons(a, nil) ; cons(b, nil) -cons(a, cons(b, nil)) ; nil -ended -nil ; cons(a, cons(b, nil)) -cons(a, nil) ; cons(b, nil) -limit -nil ; cons(a, cons(b, nil)) -cons(a, nil) ; cons(b, nil) -nofuel -nofuel -a -b -ended -a -nofuel diff --git a/bench/corpus/tests/list.out b/bench/corpus/tests/list.out deleted file mode 100644 index c3f407c0..00000000 --- a/bench/corpus/tests/list.out +++ /dev/null @@ -1 +0,0 @@ -55 diff --git a/bench/corpus/tests/purity.out b/bench/corpus/tests/purity.out deleted file mode 100644 index a3bfa694..00000000 --- a/bench/corpus/tests/purity.out +++ /dev/null @@ -1 +0,0 @@ -9 even diff --git a/bench/corpus/tests/region_ok.out b/bench/corpus/tests/region_ok.out deleted file mode 100644 index f599e28b..00000000 --- a/bench/corpus/tests/region_ok.out +++ /dev/null @@ -1 +0,0 @@ -10 diff --git a/bench/corpus/tests/rules.out b/bench/corpus/tests/rules.out deleted file mode 100644 index ec635144..00000000 --- a/bench/corpus/tests/rules.out +++ /dev/null @@ -1 +0,0 @@ -9 diff --git a/bench/corpus/tests/s2/prog/body_want.srs b/bench/corpus/tests/s2/prog/body_want.srs new file mode 100644 index 00000000..b35547f7 --- /dev/null +++ b/bench/corpus/tests/s2/prog/body_want.srs @@ -0,0 +1,23 @@ +// pass: the declared result is the expected type of a fn body (vic-m5r.17): a nullary case of a generic enum infers +// its binders from it, as the whole body, in a match arm, in an if branch; was 'cannot infer A' +enum W.O [A: Type]: + case W.No + case W.Yes(v: A) + +def W.none [A: Type] {r: Region} (x: A): W.O[A] = W.No + +def W.keepIf [A: Type] {r: Region} (ok: Bool, x: A): W.O[A] = if ok then W.Yes(x) else W.No + +def W.flip [A: Type] {r: Region} (o: W.O[A], x: A): W.O[A] = o match + case W.No => W.Yes(x) + case W.Yes(_) => W.No + +def W.or(o: W.O[I64], d: I64): I64 = o match + case W.No => d + case W.Yes(v) => v + +def main(): I64 = + handle r = Arena() + rt_print_i64(W.or(W.none(5), 1) + W.or(W.keepIf(true, 20), 0) + W.or(W.keepIf(false, 20), 300) + W.or(W.flip(W.none(0), 4000), 0)) + rt_print("\n") + 0 diff --git a/bench/corpus/tests/caps.srs b/bench/corpus/tests/s2/prog/caps.srs similarity index 100% rename from bench/corpus/tests/caps.srs rename to bench/corpus/tests/s2/prog/caps.srs diff --git a/bench/corpus/tests/s2/prog/check_mode.srs b/bench/corpus/tests/s2/prog/check_mode.srs new file mode 100644 index 00000000..db5a4858 --- /dev/null +++ b/bench/corpus/tests/s2/prog/check_mode.srs @@ -0,0 +1,26 @@ +// pass: check mode at a generic case and call (vic-m5r.18): the expected type binds the [] binders before the args, +// so args that are all nullary generic cases (G.N) get their types; was 'cannot infer A' +enum G.L [A: Type]: + case G.N + case G.C(h: A, t: G.L[A]) + +enum G.P [A: Type]: + case G.P(a: G.L[A], b: G.L[A]) + +def G.two [A: Type] {r: Region} (a: G.L[A], b: G.L[A]): G.P[A] = G.P(a, b) +def G.mk [A: Type] {r: Region} (x: A): G.P[A] = G.P(G.N, G.N) +def G.mk2 [A: Type] {r: Region} (x: A): G.P[A] = G.two(G.N, G.N) + +def G.len(xs: G.L[I64]): I64 = xs match + case G.N => 0 + case G.C(_, t) => 1 + G.len(t) + +def G.lens(p: G.P[I64]): I64 = p match + case G.P(a, b) => G.len(a) * 10 + G.len(b) + +def main(): I64 = + handle r = Arena() + val p: G.P[I64] = G.P(G.N, G.C(7, G.N)) + rt_print_i64(G.lens(G.mk(1)) + G.lens(G.mk2(2)) + G.lens(p)) + rt_print("\n") + 0 diff --git a/bench/corpus/tests/contracts.srs b/bench/corpus/tests/s2/prog/contracts.srs similarity index 100% rename from bench/corpus/tests/contracts.srs rename to bench/corpus/tests/s2/prog/contracts.srs diff --git a/bench/corpus/tests/datalog.srs b/bench/corpus/tests/s2/prog/datalog.srs similarity index 100% rename from bench/corpus/tests/datalog.srs rename to bench/corpus/tests/s2/prog/datalog.srs diff --git a/bench/corpus/tests/facts.srs b/bench/corpus/tests/s2/prog/facts.srs similarity index 100% rename from bench/corpus/tests/facts.srs rename to bench/corpus/tests/s2/prog/facts.srs diff --git a/bench/corpus/tests/facts_vars.srs b/bench/corpus/tests/s2/prog/facts_vars.srs similarity index 100% rename from bench/corpus/tests/facts_vars.srs rename to bench/corpus/tests/s2/prog/facts_vars.srs diff --git a/bench/corpus/tests/file.lib b/bench/corpus/tests/s2/prog/file.lib similarity index 100% rename from bench/corpus/tests/file.lib rename to bench/corpus/tests/s2/prog/file.lib diff --git a/bench/corpus/tests/file_ok.srs b/bench/corpus/tests/s2/prog/file_ok.srs similarity index 100% rename from bench/corpus/tests/file_ok.srs rename to bench/corpus/tests/s2/prog/file_ok.srs diff --git a/bench/corpus/tests/s2/prog/fold.srs b/bench/corpus/tests/s2/prog/fold.srs new file mode 100644 index 00000000..fa5f629c --- /dev/null +++ b/bench/corpus/tests/s2/prog/fold.srs @@ -0,0 +1,33 @@ +// pass: higher-order without closures (vic-m5r.12): a function is a given of a trait (defunctionalization, Reynolds +// 1972); a marker type F picks which one, so two folds over the same types do not clash; Ho.fold is a generic self tail call +enum Ho.List [A: Type]: + case Ho.Nil + case Ho.Cons(h: A, t: Ho.List[A]) + +enum Ho.Sum: + case Ho.Sum +enum Ho.Longest: + case Ho.Longest + +trait Ho.Fold [F: Type] [A: Type] [B: Type]: + def step(acc: B, x: A): B + +given Ho.Fold[Ho.Sum, I64, I64]: + def step(acc: I64, x: I64): I64 = acc + x + +given Ho.Fold[Ho.Longest, Str, I64]: + def step(acc: I64, x: Str): I64 = if rt_str_len(x) > acc then rt_str_len(x) else acc + +def Ho.fold [F: Type] [A: Type] [B: Type] {f: Ho.Fold[F, A, B]} (xs: Ho.List[A], acc: B): B = xs match + case Ho.Nil => acc + case Ho.Cons(h, t) => Ho.fold[F, A, B](t, f.step(acc, h)) + +def main(): I64 = + handle r = Arena() + val ns: Ho.List[I64] = Ho.Cons(1, Ho.Cons(2, Ho.Cons(3, Ho.Nil))) + rt_print_i64(Ho.fold[Ho.Sum, I64, I64](ns, 0)) + rt_print("\n") + val ws: Ho.List[Str] = Ho.Cons("a", Ho.Cons("abcd", Ho.Cons("ab", Ho.Nil))) + rt_print_i64(Ho.fold[Ho.Longest, Str, I64](ws, 0)) + rt_print("\n") + 0 diff --git a/bench/corpus/tests/generic.srs b/bench/corpus/tests/s2/prog/generic.srs similarity index 100% rename from bench/corpus/tests/generic.srs rename to bench/corpus/tests/s2/prog/generic.srs diff --git a/bench/corpus/tests/s2/prog/generic_capture.srs b/bench/corpus/tests/s2/prog/generic_capture.srs new file mode 100644 index 00000000..ce68d856 --- /dev/null +++ b/bench/corpus/tests/s2/prog/generic_capture.srs @@ -0,0 +1,25 @@ +// pass: a caller binder with the name of a callee binder (vic-m5r.16): rev's A is not onto's A; the nullary G.N gets +// its expected type G.L[A] from the caller; was 'cannot infer A' (also with explicit onto[A]) +enum G.L [A: Type]: + case G.N + case G.C(h: A, t: G.L[A]) + +def G.onto [A: Type] {r: Region} (xs: G.L[A], acc: G.L[A]): G.L[A] = xs match + case G.N => acc + case G.C(h, t) => G.onto(t, G.C(h, acc)) + +def G.rev [A: Type] {r: Region} (xs: G.L[A]): G.L[A] = G.onto(xs, G.N) +def G.rev2 [A: Type] {r: Region} (xs: G.L[A]): G.L[A] = G.onto[A](xs, G.N) +// a case field: G.N gets G.L[A] (the caller A) as its expected type +def G.one [A: Type] {r: Region} (x: A): G.L[A] = G.C(x, G.N) + +def G.first(xs: G.L[I64]): I64 = xs match + case G.N => 0 + case G.C(h, _) => h + +def main(): I64 = + handle r = Arena() + val xs = G.C(1, G.C(2, G.C(3, G.N))) + rt_print_i64(G.first(G.rev(xs)) * 10 + G.first(G.rev2(G.rev(xs))) + G.first(G.one(100))) + rt_print("\n") + 0 diff --git a/bench/corpus/tests/generic_enum.srs b/bench/corpus/tests/s2/prog/generic_enum.srs similarity index 100% rename from bench/corpus/tests/generic_enum.srs rename to bench/corpus/tests/s2/prog/generic_enum.srs diff --git a/bench/corpus/tests/given_local.srs b/bench/corpus/tests/s2/prog/given_local.srs similarity index 100% rename from bench/corpus/tests/given_local.srs rename to bench/corpus/tests/s2/prog/given_local.srs diff --git a/bench/corpus/tests/given_rank.srs b/bench/corpus/tests/s2/prog/given_rank.srs similarity index 100% rename from bench/corpus/tests/given_rank.srs rename to bench/corpus/tests/s2/prog/given_rank.srs diff --git a/bench/corpus/tests/givens.srs b/bench/corpus/tests/s2/prog/givens.srs similarity index 100% rename from bench/corpus/tests/givens.srs rename to bench/corpus/tests/s2/prog/givens.srs diff --git a/bench/corpus/tests/kanren.srs b/bench/corpus/tests/s2/prog/kanren.srs similarity index 100% rename from bench/corpus/tests/kanren.srs rename to bench/corpus/tests/s2/prog/kanren.srs diff --git a/bench/corpus/tests/kanren_fd.srs b/bench/corpus/tests/s2/prog/kanren_fd.srs similarity index 90% rename from bench/corpus/tests/kanren_fd.srs rename to bench/corpus/tests/s2/prog/kanren_fd.srs index 74f362b4..127c9b96 100644 --- a/bench/corpus/tests/kanren_fd.srs +++ b/bench/corpus/tests/s2/prog/kanren_fd.srs @@ -38,21 +38,21 @@ def main(): I64 = show(solve(RNil, both(both(both(in(x, 1, 3), in(y, 1, 3)), lt(x, y)), GLabel(xs)), 2, 1000, 10), 2) // X, Y in 0..2, X + Y = Z, Z == 4 => 2 ; 2 ; 4 by propagation, no label val sum = both(both(in(x, 0, 2), in(y, 0, 2)), GFd(FPlus(x, y, z))) - show(solve(RNil, both(sum, GEq(z, TInt(4))), 3, 1000, 10), 3) + show(solve(RNil, both(sum, GEq(z, KInt(4))), 3, 1000, 10), 3) // X, Y, Z in 1..2, distinct, label => none show(solve(RNil, both(both(both(both(in(x, 1, 2), in(y, 1, 2)), in(z, 1, 2)), distinct(xs)), GLabel(xs)), 3, 1000, 10), 3) // X in 1..3, X == 5 => none - show(solve(RNil, both(in(x, 1, 3), GEq(x, TInt(5))), 1, 1000, 10), 1) + show(solve(RNil, both(in(x, 1, 3), GEq(x, KInt(5))), 1, 1000, 10), 1) // X == 2, X in 1..3 => 2 - show(solve(RNil, both(GEq(x, TInt(2)), in(x, 1, 3)), 1, 1000, 10), 1) + show(solve(RNil, both(GEq(x, KInt(2)), in(x, 1, 3)), 1, 1000, 10), 1) // X in 1..3, X in 2..5, label => 2, 3 show(solve(RNil, both(both(in(x, 1, 3), in(x, 2, 5)), GLabel(xs)), 1, 1000, 10), 1) // X == f(a), X in 1..3 => none show(solve(RNil, both(GEq(x, c1("f", c0("a"))), in(x, 1, 3)), 1, 1000, 10), 1) // X in 1..2, X =/= 1, label => 2 - show(solve(RNil, both(both(in(x, 1, 2), GNeq(x, TInt(1))), GLabel(xs)), 1, 1000, 10), 1) + show(solve(RNil, both(both(in(x, 1, 2), GNeq(x, KInt(1))), GLabel(xs)), 1, 1000, 10), 1) // X in 1..5, X < 2 => 1 by propagation; X <= Y, Y in 0..0 => none - show(solve(RNil, both(in(x, 1, 5), lt(x, TInt(2))), 1, 1000, 10), 1) + show(solve(RNil, both(in(x, 1, 5), lt(x, KInt(2))), 1, 1000, 10), 1) show(solve(RNil, both(both(in(x, 1, 5), in(y, 0, 0)), le(x, y)), 2, 1000, 10), 2) // X == Y, X in 1..3, Y in 3..5 => 3 ; 3 (unified variables meet) show(solve(RNil, both(both(GEq(x, y), in(x, 1, 3)), in(y, 3, 5)), 2, 1000, 10), 2) diff --git a/bench/corpus/tests/kanren_neq.srs b/bench/corpus/tests/s2/prog/kanren_neq.srs similarity index 100% rename from bench/corpus/tests/kanren_neq.srs rename to bench/corpus/tests/s2/prog/kanren_neq.srs diff --git a/bench/corpus/tests/kanren_search.srs b/bench/corpus/tests/s2/prog/kanren_search.srs similarity index 99% rename from bench/corpus/tests/kanren_search.srs rename to bench/corpus/tests/s2/prog/kanren_search.srs index fc44270f..008a05a0 100644 --- a/bench/corpus/tests/kanren_search.srs +++ b/bench/corpus/tests/s2/prog/kanren_search.srs @@ -6,7 +6,7 @@ def c3 {r: Region} (f: Str, a: Term, b: Term, c: Term): Term = TCon(f, TCons(a, def args(t: Term): Terms = t match case TVar(_) => TNil case TCon(_, xs) => xs - case TInt(_) => TNil + case KInt(_) => TNil // append(nil, L, L). append(cons(H, T), L, cons(H, R)) :- append(T, L, R). def appendo {r: Region} (): Rules = diff --git a/bench/corpus/tests/list.lib b/bench/corpus/tests/s2/prog/list.lib similarity index 100% rename from bench/corpus/tests/list.lib rename to bench/corpus/tests/s2/prog/list.lib diff --git a/bench/corpus/tests/list.srs b/bench/corpus/tests/s2/prog/list.srs similarity index 100% rename from bench/corpus/tests/list.srs rename to bench/corpus/tests/s2/prog/list.srs diff --git a/bench/corpus/tests/s2/prog/modules.srs b/bench/corpus/tests/s2/prog/modules.srs new file mode 100644 index 00000000..d0ad231b --- /dev/null +++ b/bench/corpus/tests/s2/prog/modules.srs @@ -0,0 +1,37 @@ +// pass: modules as dotted symbols (vic 2026-11-06: "`Foo.bar` is a symbol (string constant) for us. the `.` is part of +// the symbol."): two modules define the same short names (Term, TInt, step) with no clash; a generic member; C names +// print `.` as `__` +enum Kanren.Term: + case Kanren.TVar(n: I64) + case Kanren.TInt(v: I64) + +enum S1.Term: + case S1.TInt(v: I64) + case S1.TName(n: I64) + +def Kanren.step(t: Kanren.Term): I64 = t match + case Kanren.TVar(n) => n + case Kanren.TInt(v) => v + 100 + +def S1.step(t: S1.Term): I64 = t match + case S1.TInt(v) => v * 2 + case S1.TName(n) => n + +enum Gen.Opt [A: Type]: + case Gen.None + case Gen.Some(v: A) + +def Gen.get [A: Type] (o: Gen.Opt[A], d: A): A = o match + case Gen.None => d + case Gen.Some(v) => v + +def main(): I64 = + handle r = Arena() + rt_print_i64(Kanren.step(Kanren.TInt(1)) + Kanren.step(Kanren.TVar(2))) + rt_print("\n") + rt_print_i64(S1.step(S1.TInt(21))) + rt_print("\n") + val n: Gen.Opt[I64] = Gen.None + rt_print_i64(Gen.get(Gen.Some(5), 0) + Gen.get(n, 1)) + rt_print("\n") + 0 diff --git a/bench/corpus/tests/purity.srs b/bench/corpus/tests/s2/prog/purity.srs similarity index 100% rename from bench/corpus/tests/purity.srs rename to bench/corpus/tests/s2/prog/purity.srs diff --git a/bench/corpus/tests/region_ok.srs b/bench/corpus/tests/s2/prog/region_ok.srs similarity index 100% rename from bench/corpus/tests/region_ok.srs rename to bench/corpus/tests/s2/prog/region_ok.srs diff --git a/bench/corpus/tests/rules.srs b/bench/corpus/tests/s2/prog/rules.srs similarity index 100% rename from bench/corpus/tests/rules.srs rename to bench/corpus/tests/s2/prog/rules.srs diff --git a/bench/corpus/tests/s2/prog/tailcall.srs b/bench/corpus/tests/s2/prog/tailcall.srs new file mode 100644 index 00000000..0589dbe5 --- /dev/null +++ b/bench/corpus/tests/s2/prog/tailcall.srs @@ -0,0 +1,57 @@ +// pass: self tail calls run in constant C stack (vic-m5r.10): 10M deep through each tail position: the body, an if +// branch, a match arm, the last statement of a block, a generic instance. tests/run.sh also runs this one at -O0. +enum Nat: + case Z + case S(n: I64) + +def down(n: I64, acc: I64): I64 = if n == 0 then acc else down(n - 1, acc + 1) + +def viaMatch(m: Nat, n: I64, acc: I64): I64 = m match + case Z => acc + case S(k) => if n == 0 then acc + k else viaMatch(m, n - 1, acc + 2) + +def viaBlock(n: I64, acc: I64): I64 = + val next = n - 1 + if n == 0 then acc else viaBlock(next, acc + 3) + +def keep [A: Type] (x: A, n: I64): A = if n == 0 then x else keep(x, n - 1) + +// not a tail call: the multiply runs after the call returns +def fact(n: I64): I64 = if n == 0 then 1 else n * fact(n - 1) + +protocol Bell: + state Up, Down + start Up + end Down + drop ring + op ring(): Unit : Up -> Down + +handler LoudBell for Bell: + def init(): Ptr = rt_arena_new() + def ring(self: Ptr): Unit = + rt_print("ring\n") + rt_arena_free(self) + +// not a jump: a handle block ends its scope (rings its bell) after the call +def rings(n: I64): I64 = + handle b = LoudBell() + if n == 0 then 0 else rings(n - 1) + +// the args are read before any param changes: swap(b, a) swaps +def swap(a: I64, b: I64, n: I64): I64 = if n == 0 then a * 10 + b else swap(b, a, n - 1) + +def main(): I64 = + handle r = Arena() + rt_print_i64(down(10000000, 0)) + rt_print("\n") + rt_print_i64(viaMatch(S(1), 10000000, 0)) + rt_print("\n") + rt_print_i64(viaBlock(10000000, 0)) + rt_print("\n") + rt_print_i64(keep(7, 10000000)) + rt_print("\n") + rt_print_i64(fact(10)) + rt_print("\n") + rt_print_i64(rings(2) + swap(1, 2, 3)) + rt_print("\n") + 0 diff --git a/bench/corpus/tests/traits.srs b/bench/corpus/tests/s2/prog/traits.srs similarity index 100% rename from bench/corpus/tests/traits.srs rename to bench/corpus/tests/s2/prog/traits.srs diff --git a/bench/corpus/tests/turnstile.srs b/bench/corpus/tests/s2/prog/turnstile.srs similarity index 99% rename from bench/corpus/tests/turnstile.srs rename to bench/corpus/tests/s2/prog/turnstile.srs index 5f0142b1..b99e578e 100644 --- a/bench/corpus/tests/turnstile.srs +++ b/bench/corpus/tests/s2/prog/turnstile.srs @@ -78,8 +78,8 @@ def main(): I64 = val bool = c0("Bool") val nil = c0("nil") val g = c2("cons", c2("bind", c0("f"), c2("fn", i64, bool)), c2("cons", c2("bind", c0("x"), i64), c2("cons", c2("bind", c0("b"), bool), nil))) - val one = c1("int", TInt(1)) - val two = c1("int", TInt(2)) + val one = c1("int", KInt(1)) + val two = c1("int", KInt(2)) val vb = c1("var", c0("b")) val vx = c1("var", c0("x")) check(rules, g, one) diff --git a/bench/corpus/tests/type_evidence.srs b/bench/corpus/tests/s2/prog/type_evidence.srs similarity index 100% rename from bench/corpus/tests/type_evidence.srs rename to bench/corpus/tests/s2/prog/type_evidence.srs diff --git a/bench/corpus/tests/type_facts.srs b/bench/corpus/tests/s2/prog/type_facts.srs similarity index 100% rename from bench/corpus/tests/type_facts.srs rename to bench/corpus/tests/s2/prog/type_facts.srs diff --git a/bench/corpus/tests/s2/prog/type_values.srs b/bench/corpus/tests/s2/prog/type_values.srs new file mode 100644 index 00000000..e1a557f4 --- /dev/null +++ b/bench/corpus/tests/s2/prog/type_values.srs @@ -0,0 +1,20 @@ +// pass: vic-u2d.3 U3 value params on types (vic Q-U3 a: a type body branches on values by match on literals); +// value args are evaluated at compile time (U2): literals, pure def calls, the type's own value params +type Bits (n: I64) = n match + case 8 => Bool + case _ => I64 +type Twice (n: I64) = Bits(n * 2) +type TPick (b: Bool) = b match + case true => Str + case false => I64 +def dbl(x: I64): I64 = x * 2 +def tb1(x: Bits(8)): Bool = x +def tb2(x: Bits(12)): I64 = x + 1 +def tb3(x: Bits(dbl(4))): Bool = !x +def tb4(x: Twice(4)): Bool = x +def tb5(x: TPick(true)): Str = x +def tb6(x: TPick(1 == 2)): I64 = x +def main(): I64 = + if tb1(true) && tb3(false) && tb4(true) then rt_print_i64(tb2(41) + tb6(0)) else () + rt_print(tb5(" ok\n")) + 0 diff --git a/bench/corpus/tests/typelambda.srs b/bench/corpus/tests/s2/prog/typelambda.srs similarity index 100% rename from bench/corpus/tests/typelambda.srs rename to bench/corpus/tests/s2/prog/typelambda.srs diff --git a/bench/corpus/tests/s2/prog/val_pattern.srs b/bench/corpus/tests/s2/prog/val_pattern.srs new file mode 100644 index 00000000..1576009b --- /dev/null +++ b/bench/corpus/tests/s2/prog/val_pattern.srs @@ -0,0 +1,34 @@ +// pass: val patterns (vic-m5r.11): `val C(a, b) = e` binds the fields of a single-case enum, so state threads through +// vals with no var; nested pattern vals, a dotted case, a generic case, a pattern val as the last statement +enum Acc: + case Acc(sum: I64, count: I64) + +enum Gen.Pair [A: Type] [B: Type]: + case Gen.Pair(a: A, b: B) + +def add {r: Region} (s: Acc, x: I64): Acc = + val Acc(sum, count) = s + Acc(sum + x, count + 1) + +def run {r: Region} (n: I64, s: Acc): Acc = if n == 0 then s else run(n - 1, add(s, n)) + +def swapped [A: Type] [B: Type] {r: Region} (p: Gen.Pair[A, B]): Gen.Pair[B, A] = + val Gen.Pair(a, b) = p + Gen.Pair(b, a) + +def lastVal(s: Acc): Unit = + val Acc(x, _y) = s + +def main(): I64 = + handle r = Arena() + val Acc(total, n) = run(10, Acc(0, 0)) + rt_print_i64(total) + rt_print("\n") + rt_print_i64(n) + rt_print("\n") + val Gen.Pair(k, v) = swapped(Gen.Pair(true, 42)) + val Acc(t2, _c) = add(Acc(k, 1), 0) + rt_print_i64(if v then t2 + 1 else 0) + rt_print("\n") + lastVal(Acc(1, 2)) + 0 diff --git a/bench/corpus/tests/var_ok.srs b/bench/corpus/tests/s2/prog/var_ok.srs similarity index 100% rename from bench/corpus/tests/var_ok.srs rename to bench/corpus/tests/s2/prog/var_ok.srs diff --git a/bench/corpus/tests/traits.out b/bench/corpus/tests/traits.out deleted file mode 100644 index d00491fd..00000000 --- a/bench/corpus/tests/traits.out +++ /dev/null @@ -1 +0,0 @@ -1 diff --git a/bench/corpus/tests/turnstile.out b/bench/corpus/tests/turnstile.out deleted file mode 100644 index 498bb580..00000000 --- a/bench/corpus/tests/turnstile.out +++ /dev/null @@ -1,15 +0,0 @@ -cint(1) : I64 -cif(cvar(b), cint(1), cint(2)) : I64 -ccall(f, cadd(cvar(x), cint(1))) : Bool -cint(1) : I64 -cint(1) : I64 -reject -reject -reject -reject -reject -reject: fuel -reject -reject -cvar(x) : Bool -reject: ambiguous diff --git a/bench/corpus/tests/type_evidence.out b/bench/corpus/tests/type_evidence.out deleted file mode 100644 index d81cc071..00000000 --- a/bench/corpus/tests/type_evidence.out +++ /dev/null @@ -1 +0,0 @@ -42 diff --git a/bench/corpus/tests/type_facts.out b/bench/corpus/tests/type_facts.out deleted file mode 100644 index ec635144..00000000 --- a/bench/corpus/tests/type_facts.out +++ /dev/null @@ -1 +0,0 @@ -9 diff --git a/bench/corpus/tests/typelambda.out b/bench/corpus/tests/typelambda.out deleted file mode 100644 index d81cc071..00000000 --- a/bench/corpus/tests/typelambda.out +++ /dev/null @@ -1 +0,0 @@ -42 diff --git a/bench/corpus/tests/var_ok.out b/bench/corpus/tests/var_ok.out deleted file mode 100644 index 00750edc..00000000 --- a/bench/corpus/tests/var_ok.out +++ /dev/null @@ -1 +0,0 @@ -3 diff --git a/nix/commands.nix b/nix/commands.nix index 9237e8ff..f8d0c7f9 100644 --- a/nix/commands.nix +++ b/nix/commands.nix @@ -36,7 +36,7 @@ in '' ) (cmd "test" "srs-bench" - "the speed oracle: hyperfine S1 self-compile, S1 Lean gen, all pass tests; fails when slower than bench/baseline.txt (srs-test first)" + "the speed oracle: hyperfine s2c self-compile and all program tests on the frozen corpus; fails when slower than bench/baseline.txt (srs-test first)" "${build}; bash tests/bench.sh" ) (cmd "test" "bench-update" "after a faster delivery: save this run as bench/baseline.txt" @@ -50,7 +50,7 @@ in "after an s2 change: bootstrap/s2c-seed.c = the s2c self-compile (s2c1.c) of the last srs-test" ''${build}; cp "$B/s2c1.c" bootstrap/s2c-seed.c'' ) - (cmd "test" "srs-test" "the gate, self-hosted: seed -> S1 -> fixpoint, pass and neg programs" + (cmd "test" "srs-test" "the gate (s2 only): s2c seed -> s2c -> fixpoint, then tests/s2 (components, prog, neg, eval, hash, store)" "./tests/run.sh" ) (cmd "test" "lean-check" diff --git a/tests/bench.sh b/tests/bench.sh index 345da825..a6901c13 100644 --- a/tests/bench.sh +++ b/tests/bench.sh @@ -5,28 +5,24 @@ # info-* cases time the current source: they are reported, never a gate. # slower = mean above the baseline mean by more than 2 combined standard deviations (noise of both runs). # usage: tests/bench.sh [update] (update: save this run as the new baseline, after a faster delivery or a refreeze) -# needs $B/s2 (tests/run.sh builds it). +# needs $B/s2c1 (tests/run.sh builds it from the s2c seed). set -u B=${B:-${XDG_RUNTIME_DIR:-/tmp}/srs-build} C=bench/corpus # benchmarks never touch the user store (vic 2026-11-06) export SRS_STORE="$B/store-bench" -S1SRC=$(sed -n 's/^S1SRC="\(.*\)"$/\1/p' tests/run.sh) -LIBS=$(sed -n 's/^LIBS="\(.*\)"$/\1/p' tests/run.sh) -# the corpus has the S1 file list of its own time: every lib/ and s1/ file it holds, in the order of S1SRC -CS1=""; for f in $S1SRC; do [ -f "$C/$f" ] && CS1="$CS1 $C/$f"; done -CLEAN=${CS1% "$C"/s1/main.srs} -# the corpus keeps the test libs at their old path tests/ -CLIBS=""; for f in $LIBS; do CLIBS="$CLIBS $C/${f/tests\/s1\//tests/}"; done -test -x "$B/s2" || { echo "no $B/s2: run tests/run.sh first" >&2; exit 1; } -# every pass test of the corpus checked and emitted in one command -printf '%s\n' "for t in $C/tests/*.srs; do \"$B/s2\" $CLIBS \"\$t\" > /dev/null; done" > "$B/bench-tests.sh" -timeout 300 hyperfine -N -w 3 -m 10 --export-json "$B/bench.json" \ - -n corpus-self "$B/s2 $CS1" \ - -n corpus-lean "$B/s2 --lean Impl $CLEAN" \ +# the compiler is s2c (tests/run.sh builds $B/s2c1 from bootstrap/s2c-seed.c); the corpus is s2 at its freeze +SC="$B/s2c1" +CSRC="$C/lib/prelude.srs $(ls $C/s2/*.srs | tr '\n' ' ') $C/s2c/main.srs" +CLIBS="$C/lib/prelude.srs $C/lib/kanren.srs $C/lib/datalog.srs $C/tests/s2/prog/list.lib $C/tests/s2/prog/file.lib" +NOW="lib/prelude.srs $(ls s2/*.srs | tr '\n' ' ') s2c/main.srs" +test -x "$SC" || { echo "no $SC: run tests/run.sh first" >&2; exit 1; } +# every program test of the corpus checked and emitted in one command +printf '%s\n' "for t in $C/tests/s2/prog/*.srs; do \"$SC\" $CLIBS \"\$t\" > /dev/null; done" > "$B/bench-tests.sh" +timeout 300 hyperfine -N -w 2 -m 5 --export-json "$B/bench.json" \ + -n corpus-self "$SC $CSRC" \ -n corpus-tests "bash $B/bench-tests.sh" \ - -n info-s1-self "$B/s2 $S1SRC" \ - -n info-s1-lean "$B/s2 --lean Impl ${S1SRC% s1/main.srs}" > "$B/bench.log" 2>&1 || { cat "$B/bench.log"; exit 1; } + -n info-s2c-self "$SC $NOW" > "$B/bench.log" 2>&1 || { cat "$B/bench.log"; exit 1; } # per case: name, wall mean + sd (s), instructions mean + sd, peak memory (bytes); hyperfine 2 json jq -r '.results[] | .summary as $s | "\(.name) wall \($s.time_wall_clock.mean) \($s.time_wall_clock.stddev)\n\(.name) instr \($s.instructions.mean) \($s.instructions.stddev)\n\(.name) mem \($s.memory_peak_resident.mean) \($s.memory_peak_resident.stddev)"' \ "$B/bench.json" > "$B/bench.now" diff --git a/tests/run.sh b/tests/run.sh index b68588de..da87e347 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash -# srs gate. s2 (the compiler): bootstrap/s2c-seed.c builds s2c, s2c compiles itself (fixpoint, seed fresh), then -# tests/s2: prog (compile, run, == .out), neg (rejected with the expected error[code] and location), eval, hash, store. -# s1 (being removed by vic): bootstrap/seed.c builds S1 (fixpoint), tests/s1 the same way. S0 (zig): s0-bootstrap. +# srs gate (s2 only; vic 2026-11-09): bootstrap/s2c-seed.c builds s2c; s2c compiles itself (fixpoint, seed fresh); then +# tests/s2: the s2 component tests, prog (compile, run, == .out), neg (rejected with the expected error[code] and +# location), eval, hash, store, tail calls at -O0. no s0 or s1 on any path. set -u B=${B:-${XDG_RUNTIME_DIR:-/tmp}/srs-build}; mkdir -p "$B" # tests never touch the user store (vic 2026-11-06): the store of this run lives under $B @@ -9,22 +9,7 @@ export SRS_STORE="$B/store-gate" CC="zig cc -std=gnu11 -O1 -w" # the compiler links static on Linux (musl): no dynamic loader per compile (vic-5r9: -13% instr on a small program) case "$(uname -s)" in Linux) CCS="$CC -static -target $(uname -m)-linux-musl";; *) CCS="$CC";; esac -S1SRC="lib/prelude.srs lib/kanren.srs lib/datalog.srs s1/node.srs s1/lex.srs s1/parse.srs s1/check.srs s1/types.srs s1/given.srs s1/facts.srs s1/purity.srs s1/hash.srs s1/eval.srs s1/mono.srs s1/emit.srs s1/lean.srs s1/leanspec.srs s1/store.srs s1/main.srs" -LIBS="lib/prelude.srs lib/kanren.srs lib/datalog.srs tests/s1/list.lib tests/s1/file.lib" fail=0 -timeout 120 $CCS -o "$B/seed" bootstrap/seed.c rt/srs_rt.c || exit 1 -timeout 10 "$B/seed" $S1SRC > "$B/s1.c" && timeout 120 $CCS -o "$B/s1" "$B/s1.c" rt/srs_rt.c || exit 1 -timeout 10 "$B/s1" $S1SRC > "$B/s2.c" && timeout 120 $CCS -o "$B/s2" "$B/s2.c" rt/srs_rt.c || exit 1 -timeout 10 "$B/s2" $S1SRC > "$B/s3.c" || exit 1 -if cmp -s "$B/s2.c" "$B/s3.c"; then echo "ok fixpoint s2.c == s3.c"; else echo "FAIL fixpoint"; fail=1; fi -if cmp -s bootstrap/seed.c "$B/s2.c"; then echo "ok seed == s2.c"; else echo "FAIL seed stale: seed-update"; fail=1; fi -for t in tests/s1/*.srs; do - n=$(basename "$t" .srs) - timeout 2 "$B/s2" $LIBS "$t" > "$B/$n.c" || { echo "FAIL $n (s1)"; fail=1; continue; } - timeout 60 $CC -o "$B/$n" "$B/$n.c" rt/srs_rt.c || { echo "FAIL $n (cc)"; fail=1; continue; } - out=$(timeout 1 "$B/$n"); code=$? - if [ $code -ne 0 ] || [ "$out" != "$(cat tests/s1/$n.out)" ]; then echo "FAIL $n exit=$code out=$out"; fail=1; else echo "ok $n"; fi -done # s2 is functional (vic-m5r.14, vic: "NO `var` everything `val`"): no var, no while, no assignment in s2/*.srs; # armed: the pattern must hit 3 known bad lines and no good line, else the check proves nothing FX='^[[:space:]]*(var[[:space:]]|while[[:space:]]|[a-z_][A-Za-z0-9_.]*[[:space:]]*=([^=>]|$))' @@ -32,15 +17,7 @@ armed=$(printf ' var x = 1\n while c do\n x = 2\n' | grep -Ec "$FX"); good=$( if [ "$armed" != 3 ] || [ "$good" != 0 ]; then echo "FAIL s2 functional check unarmed ($armed, $good)"; fail=1 elif grep -nE "$FX" s2/*.srs; then echo "FAIL s2 functional: var/while/assignment above"; fail=1 else echo "ok s2 functional (no var, while, assignment)"; fi -# s2 (vic-m5r.13): tests/s2/*.srs compile with the prelude and s2/*.srs only (not the s1 test libs) S2SRC=$(ls s2/*.srs | tr '\n' ' ') -for t in tests/s2/*.srs; do - n=s2_$(basename "$t" .srs) - timeout 2 "$B/s2" lib/prelude.srs $S2SRC "$t" > "$B/$n.c" || { echo "FAIL $n (s1)"; fail=1; continue; } - timeout 60 $CC -o "$B/$n" "$B/$n.c" rt/srs_rt.c || { echo "FAIL $n (cc)"; fail=1; continue; } - out=$(timeout 1 "$B/$n"); code=$? - if [ $code -ne 0 ] || [ "$out" != "$(cat "${t%.srs}.out")" ]; then echo "FAIL $n exit=$code out=$out"; fail=1; else echo "ok $n"; fi -done # s2 self-host (vic/c/s2-selfhost.md B2, B3): bootstrap/s2c-seed.c (s2c's own C) builds s2c0; s2c0 compiles s2c to # s2c1.c, which must be the seed (else s2c-seed-update); s2c1 compiles itself to the same C (fixpoint); then s2c1 # compiles every tests/s2 program. no s0 or s1 on this path @@ -134,61 +111,4 @@ else echo "FAIL s2c type level errors $c1 $m1 / $c2 $m2"; fail=1; fi # s2c self tail calls loop: coll folds a 1M list, at -O0 (C -O1 hides a missing loop) timeout 60 $CC -O0 -o "$B/s2c_coll0" "$B/s2c_coll.c" rt/srs_rt.c && out=$(timeout 2 "$B/s2c_coll0") && [ "$out" = "$(cat tests/s2/coll.out)" ] && echo "ok s2c tailcall -O0" || { echo "FAIL s2c tailcall -O0"; fail=1; } timeout 60 $CC -O0 -o "$B/s2c1_tailcall0" "$B/s2c1_tailcall.c" rt/srs_rt.c && out=$(timeout 2 "$B/s2c1_tailcall0") && [ "$out" = "$(cat tests/s2/prog/tailcall.out)" ] && echo "ok s2c prog tailcall -O0" || { echo "FAIL s2c prog tailcall -O0"; fail=1; } -# self tail calls run in constant C stack with no C optimization (vic-m5r.10): tailcall at -O0 (C -O1 hides a missing loop) -timeout 60 $CC -O0 -o "$B/tailcall0" "$B/tailcall.c" rt/srs_rt.c && out=$(timeout 2 "$B/tailcall0") && [ "$out" = "$(cat tests/s1/tailcall.out)" ] && echo "ok tailcall -O0" || { echo "FAIL tailcall -O0"; fail=1; } -# every "// expect: msg" line must be printed: errors are data, main reports them all (vic-ngq); armed: 0 lines = FAIL -for t in tests/s1/neg/*.srs; do - n=$(basename "$t" .srs) - msg=$(timeout 2 "$B/s2" $LIBS "$t" 2>&1 >/dev/null); code=$? - bad=""; [ $code -eq 1 ] || bad=" exit=$code" - wants=$(sed -n "s|^// expect: ||p" "$t"); [ -n "$wants" ] || bad="$bad no-expect" - while IFS= read -r want; do case "$msg" in *"$want"*) ;; *) bad="$bad missing=$want";; esac; done <<< "$wants" - if [ -z "$bad" ]; then echo "ok neg/$n"; else echo "FAIL neg/$n$bad msg=$msg"; fail=1; fi -done -# content hashes (vic-uw3 H1): `s1 --hash` prints "name hash"; each "// same: a b" / "// differ: a b" line must hold -for t in tests/s1/hash/*.srs; do - n=$(basename "$t" .srs) - timeout 2 "$B/s2" --hash lib/prelude.srs "$t" > "$B/$n.hash" 2>&1 || { echo "FAIL hash/$n $(head -1 "$B/$n.hash")"; fail=1; continue; } - bad="" - # armed: a test with no relation line proves nothing - [ "$(sed -n 's#^// \(same:\|differ:\) #\1 #p' "$t" | wc -l)" -gt 0 ] || bad=" no-relations" - while read -r rel a b; do - ha=$(awk -v n="$a" '$1 == n {print $2}' "$B/$n.hash"); hb=$(awk -v n="$b" '$1 == n {print $2}' "$B/$n.hash") - if [ -z "$ha" ] || [ -z "$hb" ]; then bad="$bad missing($a $b)" - elif [ "$rel" = same: ] && [ "$ha" != "$hb" ]; then bad="$bad $a!=$b" - elif [ "$rel" = differ: ] && [ "$ha" = "$hb" ]; then bad="$bad $a==$b"; fi - done < <(sed -n 's#^// \(same:\|differ:\) #\1 #p' "$t") - if [ -n "$bad" ]; then echo "FAIL hash/$n$bad"; fail=1; else echo "ok hash/$n"; fi -done -# the comptime evaluator (vic-u2d.2): `s1 --eval` prints "name value" for each nullary pure def; each -# "// eval: name value" line must be printed; a test whose first line is "// expect: msg" must be rejected with msg -for t in tests/s1/eval/*.srs; do - n=$(basename "$t" .srs); want=$(sed -n "1s|^// expect: ||p" "$t") - out=$(timeout 2 "$B/s2" --eval lib/prelude.srs "$t" 2>&1); code=$? - if [ -n "$want" ]; then - case "$out" in *"$want"*) [ $code -eq 1 ] && { echo "ok eval/$n"; continue; };; esac - echo "FAIL eval/$n exit=$code out=$out"; fail=1; continue - fi - bad=""; nrel=0 - while read -r name val; do - nrel=$((nrel + 1)) - printf '%s\n' "$out" | grep -Fxq "$name $val" || bad="$bad $name" - done < <(sed -n 's#^// eval: ##p' "$t") - [ $nrel -gt 0 ] || bad=" no-eval-lines" - if [ $code -ne 0 ] || [ -n "$bad" ]; then echo "FAIL eval/$n exit=$code$bad"; fail=1; else echo "ok eval/$n"; fi -done -# the store (vic-uw3 H2): cold writes every entry, warm writes none, a cut entry reads as bad (a miss) -rm -rf "$SRS_STORE" -st() { timeout 2 "$B/s2" --store-check lib/prelude.srs tests/s1/hash/basic.srs 2>&1; } -cold=$(st); warm=$(st) -e=$(grep -rl I64 "$SRS_STORE" | head -1); cp "$e" "$B/store.keep" -head -c 30 "$B/store.keep" > "$e"; cut=$(st) -# a byte of a name changed (still parses, not equal); bytes after the node (not one whole entry) -sed '0,/I64/s//I65/' "$B/store.keep" > "$e"; flip=$(st) -{ cat "$B/store.keep"; printf 'x'; } > "$e"; trail=$(st) -case "$cold" in "store: wrote "[1-9]*", read equal "[1-9]*", bad 0") ok1=1;; *) ok1=0;; esac -case "$warm" in "store: wrote 0, read equal "[1-9]*", bad 0") ok2=1;; *) ok2=0;; esac -case "$cut$flip$trail" in *", bad 1"*", bad 1"*", bad 1") ok3=1;; *) ok3=0;; esac -if [ $ok1 = 1 ] && [ $ok2 = 1 ] && [ $ok3 = 1 ] && ! cmp -s "$e" "$B/store.keep"; then echo "ok store cold/warm/cut/flip/trail" -else echo "FAIL store cold=[$cold] warm=[$warm] cut=[$cut] flip=[$flip] trail=[$trail]"; fail=1; fi exit $fail From e19cde991a46cfc12951917a3bf7750c56d39b6e Mon Sep 17 00:00:00 2001 From: Victor Borja Date: Mon, 9 Nov 2026 04:11:30 -0600 Subject: [PATCH 2/2] s2 only: AGENTS.md (CLAUDE.md) rewritten for s2, seed-update builds the s2c seed, s0/s1 commands removed (s0 and s1 are historic), README wording --- README.md | 4 ++-- nix/ci.nix | 2 +- nix/commands.nix | 42 +++--------------------------------------- tests/run.sh | 4 ++-- 4 files changed, 8 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 68fefcf6..1b75f547 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ s2 is the compiler. It is purely functional (`val` and recursion, no `var` or `w * **Flags**: `--eval` runs pure defs at compile time, `--hash` prints content hashes, and `--store-check` writes and reads the content-addressed store. * **Errors** have the shape of Rust's: `error[code]`, then the file and line, the source line, the expected and found types, and a help line. -s1, the first compiler (imperative, written in srs), and s0, its Zig bootstrap, are still in the tree and are being removed. Lean generation (`--lean`) waits until the core is stable. The known rough edges of s2 are tracked before s3. +s1, the first compiler (imperative, written in srs), and s0, its Zig bootstrap, are historic: they stay in the tree, and nothing builds or runs them. Lean generation (`--lean`) waits until the core is stable. The known rough edges of s2 are tracked before s3. The s2 libraries live in `s2/`: persistent collections, miniKanren with disequality and finite domains, and Datalog with stratified negation. The checker phases also live there, and the driver lives in `s2c/`. @@ -314,7 +314,7 @@ The test runner validates every feature across positive and negative cases: * `tests/s2/neg/`: Programs that s2 must reject. Each one names the error code and the exact file and line it expects. * `tests/s2/eval/` and `tests/s2/hash/`: the compile-time values and the content hashes they must give. * `tests/s2/*.srs`: tests of the s2 components themselves. -* `tests/s1/` is the suite of the old compiler, removed with it. +* `tests/s1/` is the historic suite of s1. --- diff --git a/nix/ci.nix b/nix/ci.nix index d211369e..c086c8fb 100644 --- a/nix/ci.nix +++ b/nix/ci.nix @@ -59,7 +59,7 @@ in run = "nix flake check -L"; } ]; - # lean-check = job 30 [ (dev "Lean soundness proofs of the effect checker" "lean-check") ]; + # lean-check returns with s2 --lean, once vic rules the core stable srs-test = job 20 [ (dev "srs gate: fixpoint, seed, programs" "srs-test") ]; }; }; diff --git a/nix/commands.nix b/nix/commands.nix index f8d0c7f9..e3aa8d3c 100644 --- a/nix/commands.nix +++ b/nix/commands.nix @@ -43,49 +43,13 @@ in "${build}; bash tests/bench.sh update" ) (cmd "srs" "seed-update" - "after an S1 change: bootstrap/seed.c = the S1 self-compile of the last srs-test" - ''${build}; cp "$B/s2.c" bootstrap/seed.c'' - ) - (cmd "srs" "s2c-seed-update" "after an s2 change: bootstrap/s2c-seed.c = the s2c self-compile (s2c1.c) of the last srs-test" ''${build}; cp "$B/s2c1.c" bootstrap/s2c-seed.c'' ) - (cmd "test" "srs-test" "the gate (s2 only): s2c seed -> s2c -> fixpoint, then tests/s2 (components, prog, neg, eval, hash, store)" + (cmd "test" "srs-test" + "the gate (s2 only): s2c seed -> s2c -> fixpoint, then tests/s2 (components, prog, neg, eval, hash, store)" "./tests/run.sh" ) - (cmd "test" "lean-check" - "Lean: Impl = s1/*.srs via s1 --lean (fresh, must match the committed file), Impl verdicts = S1, model soundness proof (no sorry)" - '' - ${build} - ${cc} -o "$B/seed" bootstrap/seed.c rt/srs_rt.c - S1SRC="lib/prelude.srs lib/kanren.srs lib/datalog.srs s1/node.srs s1/lex.srs s1/parse.srs s1/check.srs s1/types.srs s1/given.srs s1/facts.srs s1/purity.srs s1/hash.srs s1/eval.srs s1/mono.srs s1/emit.srs s1/lean.srs s1/leanspec.srs" - gen() { # gen NS OUT files...: generated Lean must match the committed file - ns=$1; out=$2; shift 2 - timeout 10 "$B/seed" --lean "$ns" "$@" > "$B/gen.lean" || exit 1 - cmp -s "$B/gen.lean" "$out" || { cp "$B/gen.lean" "$out"; echo "$out was stale: regenerated, commit it" >&2; exit 1; } - } - gen Impl lean/Srs/Impl/S1.lean $S1SRC - gen Contracts lean/Srs/Contracts.lean lib/prelude.srs tests/s1/list.lib tests/s1/contracts.srs - gen Kanren lean/Srs/Kanren.lean lib/prelude.srs lib/kanren.srs - gen Datalog lean/Srs/Datalog.lean lib/prelude.srs lib/datalog.srs - echo "proof lean (debt): $(grep -cE '^ +proof lean' s1/*.srs lib/*.srs tests/s1/*.srs | awk -F: '{s+=$2} END{print s}')" - ! grep -rn --include='*.lean' -w -e sorry -e admit -e axiom lean/Srs || { echo "unproven step" >&2; exit 1; } - # ImplRun reads tests/s1/ by IO, which lake does not track: drop its outputs so the verdicts always run again - rm -f lean/.lake/build/lib/lean/Srs/ImplRun.* - cd lean && timeout 600 lake build - '' - ) - # bootstrap only when absolutely necessary (C10): the seed cannot build the S1 src - (cmd "bootstrap" "s0-bootstrap" "S0 (zig) -> S1 -> bootstrap/seed.c, then srs-test" '' - ${build} - timeout 120 zig test s0/main.zig - timeout 120 zig build-exe s0/main.zig -femit-bin="$B/s0" - S1SRC="lib/prelude.srs lib/kanren.srs lib/datalog.srs s1/node.srs s1/lex.srs s1/parse.srs s1/check.srs s1/types.srs s1/given.srs s1/facts.srs s1/purity.srs s1/hash.srs s1/eval.srs s1/mono.srs s1/emit.srs s1/lean.srs s1/store.srs s1/main.srs" - "$B/s0" $S1SRC > "$B/s1.c" - ${cc} -o "$B/s1" "$B/s1.c" rt/srs_rt.c - "$B/s1" $S1SRC > bootstrap/seed.c - ./tests/run.sh - '') (cmd "fmt" "fmt" "format every tracked nix file (nixfmt)" "git ls-files -z '*.nix' | xargs -0 nixfmt" ) @@ -99,7 +63,7 @@ in "nix run .#write-files" ) (cmd "ci" "ci" "run the CI jobs locally, in order" - ''for c in fmt-check lint srs-test lean-check; do echo "== $c"; $c; done'' + ''for c in fmt-check lint srs-test; do echo "== $c"; $c; done'' ) ]; }; diff --git a/tests/run.sh b/tests/run.sh index da87e347..868be1bd 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -19,14 +19,14 @@ elif grep -nE "$FX" s2/*.srs; then echo "FAIL s2 functional: var/while/assignmen else echo "ok s2 functional (no var, while, assignment)"; fi S2SRC=$(ls s2/*.srs | tr '\n' ' ') # s2 self-host (vic/c/s2-selfhost.md B2, B3): bootstrap/s2c-seed.c (s2c's own C) builds s2c0; s2c0 compiles s2c to -# s2c1.c, which must be the seed (else s2c-seed-update); s2c1 compiles itself to the same C (fixpoint); then s2c1 +# s2c1.c, which must be the seed (else seed-update); s2c1 compiles itself to the same C (fixpoint); then s2c1 # compiles every tests/s2 program. no s0 or s1 on this path S2C="lib/prelude.srs $S2SRC s2c/main.srs" if timeout 120 $CCS -o "$B/s2c0" bootstrap/s2c-seed.c rt/srs_rt.c \ && timeout 5 "$B/s2c0" $S2C > "$B/s2c1.c" && timeout 120 $CCS -o "$B/s2c1" "$B/s2c1.c" rt/srs_rt.c \ && timeout 5 "$B/s2c1" $S2C > "$B/s2c2.c" && cmp -s "$B/s2c1.c" "$B/s2c2.c"; then echo "ok s2c fixpoint" else echo "FAIL s2c fixpoint"; fail=1; fi -if cmp -s bootstrap/s2c-seed.c "$B/s2c1.c"; then echo "ok s2c seed == s2c1.c"; else echo "FAIL s2c seed stale: s2c-seed-update"; fail=1; fi +if cmp -s bootstrap/s2c-seed.c "$B/s2c1.c"; then echo "ok s2c seed == s2c1.c"; else echo "FAIL s2c seed stale: seed-update"; fail=1; fi for t in tests/s2/*.srs; do n=s2c_$(basename "$t" .srs) timeout 5 "$B/s2c1" lib/prelude.srs $S2SRC "$t" > "$B/$n.c" || { echo "FAIL $n (s2c)"; fail=1; continue; }