diff --git a/Justfile b/Justfile index 357ebb41..ef65c0c8 100644 --- a/Justfile +++ b/Justfile @@ -128,6 +128,11 @@ varint-proofs: figures: cargo run --locked -q -p figures -- check +# Generate the native modules that state the wire model's quantities +# (crates/uorc/src/model/*.rs) from its sources; `just figures` rejects a stale one. +figures-native: + cargo run --locked -q -p figures -- native + # Record figures a change derived or removed (never admits a new one). figures-write: cargo run --locked -q -p figures -- write diff --git a/client/gen/domains.py b/client/gen/domains.py new file mode 100644 index 00000000..75408dad --- /dev/null +++ b/client/gen/domains.py @@ -0,0 +1,264 @@ +# The domains of a coder's quantities, and the pass that derives the figures its IR states from them. +# +# A coder's numbers are not free: a probability is a 16-bit slot, a logistic value lives in the +# stretch domain, a weight in its offset form, a stored cell spans its width in bytes. A model declares +# those domains once, each by its extent (a format identity, stated as a named numeral of the wire +# module the coder lowers to), and which tables and globals hold each one. This pass infers the domain +# of every operand of the IR to a fixpoint (a table or global takes the domains of what is stored in +# it), and then states each literal that is a characteristic quantity of the domain of the operand it +# acts on (the extent, its top, its half, an origin, a rescale between two domains in scope) as that +# quantity, derived from the extent. A literal the pass cannot place keeps its numeral, and is reported +# with the domains in scope, so the figures it leaves are the next declarations to make. +import collections + +import ir +from ir import K + +BYTE = K('byteBase', 256) +RADIX = K('radix', 2) # the coder is binary: one decision per coding step + + +class Domain: + """A declared domain: its name and extent (a named quantity); an origin if the domain is in offset + form (the value that stands for zero, by default its half); a unit if it is fixed point (the value + that stands for one).""" + + def __init__(self, name, extent, origin=None, unit=None, offset=False): + self.name, self.extent, self.unit = name, extent, unit + self.half = K(name + 'Half', ('div', extent, RADIX)) + self.origin = self.half if offset and origin is None else origin + + def quantities(self): + n, r = self.name, self.extent + half = self.half + out = [r, K(n + 'Last', ('sub', r, 1)), half, K(n + 'HalfLast', ('sub', half, 1))] + if self.unit is not None: + out += [self.unit, K(n + 'UnitLast', ('sub', self.unit, 1))] + if self.origin is not None and self.origin is not half: + o = self.origin # an offset domain's zero; its top, the most it holds above zero + out += [o, K(n + 'OriginLast', ('sub', o, 1)), K(n + 'Top', ('add', o, o))] + return out + + +def origins(n, *ds): + """The constant term of a sum of n products of offset-form values, one from each domain of ds: + n times the product of their origins (what (x + ox)(w + ow) = xw + x ow + w ox + ox ow leaves).""" + e = n + for d in ds: + e = K('%s%s' % (e.name if isinstance(e, K) else 'n%d' % int(e), d.name.capitalize() + 'Origin'), ('mul', e, d.origin)) + return e + + +def cell(w): + """The domain of a stored cell of w bytes: w byte lanes.""" + e = BYTE + for _ in range(int(w) - 1): + e = K('cell%dBase' % (_ + 2), ('mul', e, BYTE)) + d = Domain('cell%d' % int(w), e) + d.lanes = w + return d + + +def lanes(d): + """A cell's byte lanes: the radix of each byte place.""" + out, e = [], BYTE + for j in range(1, getattr(d, 'lanes', 0)): + out.append(e) + e = K('cell%dBase' % (j + 1), ('mul', e, BYTE)) + return out + + +def rescale(a, b): + """A rescale from domain b to domain a (a the wider), when the extents divide.""" + if int(a.extent) > int(b.extent) and int(a.extent) % int(b.extent) == 0: + return [K('%sPer%s' % (a.name, b.name[0].upper() + b.name[1:]), ('div', a.extent, b.extent))] + return [] + + +class Pass: + """Infer every operand's domains over prog (tables and globals seeded by tables, globals) and + derive the literals. Domains are ordered: the first declared wins a value two of them share.""" + + def __init__(self, prog, domains, tables, globals_): + self.p, self.dom = prog, {d.name: d for d in domains} + self.order = [d.name for d in domains] + self.seed_t = {t: set(ds) for t, ds in tables.items()} + self.seed_g = {g: set(ds) for g, ds in globals_.items()} + self.cells = {} + self.residue = collections.Counter() + self.derived = collections.Counter() + + def cell(self, w): + w = int(w) + if w not in self.cells: + self.cells[w] = cell(w) + return self.cells[w] + + def domains(self, names): + ds = [self.dom[n] for n in self.order if n in names] + ds += [self.cells[w] for w in sorted(self.cells) if ('cell', w) in names] + return ds + + def place(self, v, names, want=frozenset()): + """The quantity of value v among the domains names (of the operands it acts with) and want (of + where the value goes), or a rescale between two of them; None if there is none.""" + ds = self.domains(names | want) + for d in ds: + for q in d.quantities() + lanes(d): + if int(q) == v: + return q + for a in ds: + for b in ds: + for q in rescale(a, b): + if int(q) == v: + return q + return None + + def lit(self, e, names, want=frozenset()): + if isinstance(e, K) or int(e) <= 1: + return e + q = self.place(int(e), set(names), set(want)) + if q is None: + self.residue[(int(e), tuple(sorted(map(str, names))))] += 1 + return e + self.derived[q.name] += 1 + return q + + # expressions: (domains, rewritten expression) + def ex(self, e, env, want=frozenset()): + """(domains of e, e with its literals derived); want is the domains of where e's value goes + (the cell or table it is stored in, the squash it feeds), which a literal factor may rescale to.""" + if isinstance(e, bool) or isinstance(e, int): + return set(), e + k = e[0] + if k == 'v': + return env.get(e[1], set()), e + if k == 'g': + self.cell(self.p.globals[e[1]]) + return {('cell', int(self.p.globals[e[1]]))} | self.gd.get(e[1], set()), e + if k == 'ld': + _, i = self.ex(e[3], env) + self.cell(e[2]) + return {('cell', int(e[2]))} | self.td.get(e[1], set()), (k, e[1], e[2], i) + if k == 'rom': + _, i = self.ex(e[3], env) + w = self.p.roms[e[1]][0] + self.cell(w) + return {('cell', int(w))}, (k, e[1], e[2], i) + if k == 'in': + _, i = self.ex(e[1], env) + return {('cell', 1)}, (k, i) + if k == 'hash': + _, i = self.ex(e[1], env) + self.cell(4) + return {('cell', 4)}, (k, i) + if k == 'squash': + return {'stretch'}, (k, self.operands([e[1]], {'stretch'}, env, {'stretch'})[1][0]) + if k == 'not': + _, a = self.ex(e[1], env) + return set(), (k, a) + if k == 'sel': + _, c = self.ex(e[1], env) + both, (a, b) = self.operands(e[2:], set(), env, want) + return both, (k, c, a, b) + if k in ('mod', 'div') and type(e[2]) is int and e[2] == int(RADIX): + # a quotient or remainder by 2 takes a word's binary digits apart: the radix + self.derived[RADIX.name] += 1 + e = (k, e[1], RADIX) + arith = k in ('add', 'sub', 'mod', 'mul', 'div') + both, (a, b) = self.operands(e[1:], set(), env, want if arith else frozenset()) + return (both if arith else set()), (k, a, b) + + def operands(self, es, extra, env, want): + """Operands that share a domain: each literal among them is placed in the domains of the rest.""" + got = [None if (isinstance(x, int) and not isinstance(x, bool)) else self.ex(x, env, want) for x in es] + both = set(extra) + for g in got: + if g is not None: + both |= g[0] + out = [self.lit(x, both, want) if g is None else g[1] for x, g in zip(es, got)] + return both, out + + def st(self, ss, env): + env, out = dict(env), [] + for s in ss: + k = s[0] + if k == 'let': + d, v = self.ex(s[2], env) if not isinstance(s[2], int) else (set(), s[2]) + env[s[1]] = d + out.append((k, s[1], v)) + elif k == 'set': + gd = {('cell', int(self.p.globals[s[1]]))} | self.gd.get(s[1], set()) + self.cell(self.p.globals[s[1]]) + if isinstance(s[2], int): + out.append((k, s[1], self.lit(s[2], gd))) + else: + d, v = self.ex(s[2], env, gd) + self.ng.setdefault(s[1], set()).update(d - {('cell', int(self.p.globals[s[1]]))}) + out.append((k, s[1], v)) + elif k == 'store': + c = ('cell', int(s[2])) + self.cell(s[2]) + _, i = self.ex(s[3], env) if not isinstance(s[3], int) else (set(), s[3]) + if isinstance(s[4], int): + v = self.lit(s[4], {c} | self.td.get(s[1], set())) + else: + d, v = self.ex(s[4], env, {c} | self.td.get(s[1], set())) + self.nt.setdefault(s[1], set()).update(d - {c}) + out.append((k, s[1], s[2], i, v) + tuple(s[5:])) + elif k == 'if': + out.append((k, self.ex(s[1], env)[1], self.st(s[2], env), self.st(s[3], env))) + elif k == 'loop': + out.append((k, self.ex(s[1], env)[1] if not isinstance(s[1], int) else s[1], s[2], self.st(s[3], env))) + elif k == 'loopw': + out.append((k, self.ex(s[1], env)[1] if not isinstance(s[1], int) else s[1], + self.ex(s[2], env)[1], s[3], self.st(s[4], env))) + elif k == 'call': + out.append((k, s[1], [self.ex(a, env)[1] if not isinstance(a, int) else a for a in s[2]]) + tuple(s[3:])) + elif k == 'gcopy': + out.append((k, s[1], self.ex(s[2], env)[1] if not isinstance(s[2], int) else s[2]) + tuple(s[3:])) + else: + out.append(s) + return out + + def run(self): + self.td, self.gd = dict(self.seed_t), dict(self.seed_g) + for _ in range(16): + self.nt, self.ng = {}, {} + self.residue.clear() + self.derived.clear() + funcs = {f: (pb[0], self.st(pb[1], {})) for f, pb in self.p.funcs.items()} + td = {t: self.nt.get(t, set()) | self.seed_t.get(t, set()) for t in set(self.nt) | set(self.seed_t)} + gd = {g: self.ng.get(g, set()) | self.seed_g.get(g, set()) for g in set(self.ng) | set(self.seed_g)} + if td == self.td and gd == self.gd: + return funcs + self.td, self.gd = td, gd + raise RuntimeError('domains: no fixpoint') + + +def derive(prog, domains, tables, globals_): + """Rewrite prog's functions in place; return the pass (its derived and residue counts).""" + p = Pass(prog, domains, tables, globals_) + prog.funcs = p.run() + return p + + +def report(p, top=40): + """The pass's outcome: the quantities it derived (uses each) and the literals it left, by value, + with the domains in scope at each (the declarations the residue asks for).""" + lines = ['derived %d literal uses as %d quantities' % (sum(p.derived.values()), len(p.derived))] + by = collections.defaultdict(collections.Counter) + for (v, names), n in p.residue.items(): + by[v][names] += n + lines.append('left %d literal uses of %d values' % (sum(p.residue.values()), len(by))) + for v, cs in sorted(by.items(), key=lambda kv: -sum(kv[1].values()))[:top]: + scope = ', '.join('%s x%d' % ('/'.join(n) or '(none)', c) for n, c in cs.most_common(3)) + lines.append(' %12d %5d %s' % (v, sum(cs.values()), scope)) + return '\n'.join(lines) + + +if __name__ == '__main__': + import importlib + import sys + for name in sys.argv[1:] or ['ncm_model']: + print(name + ':\n' + report(importlib.import_module(name).DERIVED)) diff --git a/client/gen/gen_dec.py b/client/gen/gen_dec.py index 4dc5dd43..77b36306 100644 --- a/client/gen/gen_dec.py +++ b/client/gen/gen_dec.py @@ -21,17 +21,73 @@ D('byteAt', ['data : Bytes', 'at : Nat'], 'Nat', RB('data', 'at')) D('singleton', ['value : Nat'], 'Bytes', "(match (prim slice (alphabet) value 1 : (Option Bytes))\n | Option.none => 0x\n | Option.some piece => piece)") D('pow2', ['k : Nat'], 'Nat', "(match k\n | Nat.zero => 1\n | Nat.succ m => (2 * (pow2 m)))", 'k') +# The decoder's layout, named once. Each probability block follows the one +# before it (its base is the previous base plus that block's size); the base +# counts are the format's own (states, context bits, tree depths). +def K(name, body): + D(name, [], 'Nat', str(body)) + return f"({name})" # a reference to a quantity is parenthesised +STATES = K('states', 12) +IS_REP = K('isRepBase', STATES) +IS_REP_G0 = K('isRepG0Base', f"({IS_REP} + {STATES})") +IS_REP_G1 = K('isRepG1Base', f"({IS_REP_G0} + {STATES})") +IS_REP_G2 = K('isRepG2Base', f"({IS_REP_G1} + {STATES})") +IS_REP0_LONG = K('isRep0LongBase', f"({IS_REP_G2} + {STATES})") +LIT = K('literalBase', f"({IS_REP0_LONG} + {STATES})") +RADIX = K('radix', 2) +BYTE_BITS = K('byteBits', 8) +BYTE_BASE = K('byteBase', f"(pow2 {BYTE_BITS})") +LC = K('literalContextBits', 3) +# a literal's coder: the plain tree and the two matched trees (match bit 0, 1) +LIT_CODER = K('literalCoder', f"(({RADIX} + 1) * {BYTE_BASE})") +LIT_SHIFT = K('literalContextShift', f"(pow2 (prim subtract {BYTE_BITS} {LC} : Nat))") +SLOT = K('slotBase', f"({LIT} + ({LIT_CODER} * (pow2 {LC})))") +LEN_STATES = K('lengthStates', 4) +SLOT_BITS = K('slotBits', 6) +SLOT_TREE = K('slotTree', f"(pow2 {SLOT_BITS})") +SPEC = K('specBase', f"({SLOT} + ({LEN_STATES} * {SLOT_TREE}))") +START_SLOT = K('startSlot', 4) +END_SLOT = K('endSlot', 14) +ALIGN_BITS = K('alignBits', 4) +ALIGN_TREE = K('alignTree', f"(pow2 {ALIGN_BITS})") +# the reverse trees of slots startSlot..endSlot index from 1 up to the full distances less endSlot +ALIGN = K('alignBase', f"({SPEC} + (prim subtract ((pow2 (prim quotient {END_SLOT} {RADIX} 0 : Nat)) + 1) {END_SLOT} : Nat))") +LENL = K('lengthBase', f"({ALIGN} + {ALIGN_TREE})") +LOW_BITS = K('lowBits', 3) +HIGH_BITS = K('highBits', 8) +LOW = K('lowSymbols', f"(pow2 {LOW_BITS})") +# each length tree's block holds twice its symbols (index m from 1 doubles each level) +LOW_AT = K('lowAt', RADIX) +MID_AT = K('midAt', f"({LOW_AT} + ({RADIX} * {LOW}))") +HIGH_AT = K('highAt', f"({MID_AT} + ({RADIX} * {LOW}))") +LENR = K('repLengthBase', f"({LENL} + ({HIGH_AT} + ({RADIX} * (pow2 {HIGH_BITS}))))") +MIN_MATCH = K('minMatch', 2) +PROB_BITS = K('probabilityBits', 11) +PROB_RANGE = K('probabilityRange', f"(pow2 {PROB_BITS})") + +PROB_COUNT_BITS = K('probabilityCountBits', 13) +PROB_CELL = K('probabilityCell', RADIX) +OUT_AT = K('outputBase', f"({PROB_CELL} * (pow2 {PROB_COUNT_BITS}))") +LENGTH_BYTES = K('lengthBytes', BYTE_BITS) +# the header: the output length, the coder's zero byte, then its code word +START_POS = K('startPosition', 13) +CODE_AT = K('codeAt', f"({LENGTH_BYTES} + 1)") +CODE_BYTES = K('codeBytes', f"(prim subtract {START_POS} {CODE_AT} : Nat)") +CODE_BITS = f"({CODE_BYTES} * {BYTE_BITS})" +TOP = K('rangeTop', f"(pow2 (prim subtract {CODE_BITS} {BYTE_BITS} : Nat))") +MOVE = K('moveScale', 32) + D('depthFor', ['fuel : Nat', 'n : Nat', 'depth : Nat'], 'Nat', "(match fuel\n | Nat.zero => depth\n | Nat.succ m => (if (n <=? (pow2 depth)) then depth else (depthFor m n (depth + 1))))", 'fuel') -_n = upd('d', range=f"({P('d','range')} * 256)", code=f"(({P('d','code')} * 256) + {RB(P('d','input'), P('d','pos'))})", pos=f"({P('d','pos')} + 1)") -D('normalize', ['d : Dec'], 'Dec', f"(if ({P('d','range')} (acc, d)\n | Nat.succ m => (let half : Nat := (prim quotient {P('d','range')} 2 0 : Nat); " - f"(if ({P('d','code')} (acc, d)\n | Nat.succ m => (let half : Nat := (prim quotient {P('d','range')} {RADIX} 0 : Nat); " + f"(if ({P('d','code')} (m, d)\n | Nat.succ k => (let r : (Nat * Dec) := (decodeBit d (base + m)); (let bit : Nat := (first r); (treeLoop k (second r) base ((2 * m) + bit)))))", 'fuel') @@ -39,56 +95,59 @@ D('reverseLoop', ['fuel : Nat', 'd : Dec', 'base : Nat', 'm : Nat', 'weight : Nat', 'acc : Nat'], '(Nat * Dec)', "(match fuel\n | Nat.zero => (acc, d)\n | Nat.succ k => (let r : (Nat * Dec) := (decodeBit d (base + m)); (let bit : Nat := (first r); (reverseLoop k (second r) base ((2 * m) + bit) (2 * weight) (acc + (weight * bit))))))", 'fuel') D('matchedLoop', ['fuel : Nat', 'd : Dec', 'base : Nat', 'matchByte : Nat', 'sym : Nat'], '(Nat * Dec)', - "(match fuel\n | Nat.zero => (sym, d)\n | Nat.succ k => (let mbit : Nat := (prim remainder (prim quotient matchByte (pow2 k) 0 : Nat) 2 0 : Nat); (let r : (Nat * Dec) := (decodeBit d ((base + ((1 + mbit) * 256)) + sym)); (let bit : Nat := (first r); (let next : Nat := ((2 * sym) + bit); (if (bit =? mbit) then (matchedLoop k (second r) base matchByte next) else (let rest : (Nat * Dec) := (treeLoop k (second r) base next); rest)))))))", 'fuel') -LC = ("(let c : (Nat * Dec) := (decodeBit d base); (let cb : Nat := (first c); (if (cb =? 0) then (tree (second c) (base + 2) 3) else (let c2 : (Nat * Dec) := (decodeBit (second c) (base + 1)); (let cb2 : Nat := (first c2); " - "(if (cb2 =? 0) then (let t : (Nat * Dec) := (tree (second c2) (base + 18) 3); (let tv : Nat := (first t); ((8 + tv), (second t)))) else (let t : (Nat * Dec) := (tree (second c2) (base + 34) 8); (let tv : Nat := (first t); ((16 + tv), (second t))))))))))") -D('lengthCode', ['d : Dec', 'base : Nat'], '(Nat * Dec)', LC) -SLOT = 6216; SPEC = 6472; ALIGN = 6587; LENL = 6603; LENR = 7149; LIT = 72 -DS = (f"(let ls : Nat := (if (lenCode (sym, d)\n | Nat.succ k => (let mbit : Nat := (prim remainder (prim quotient matchByte (pow2 k) 0 : Nat) {RADIX} 0 : Nat); (let r : (Nat * Dec) := (decodeBit d ((base + ((1 + mbit) * {BYTE_BASE})) + sym)); (let bit : Nat := (first r); (let next : Nat := (({RADIX} * sym) + bit); (if (bit =? mbit) then (matchedLoop k (second r) base matchByte next) else (let rest : (Nat * Dec) := (treeLoop k (second r) base next); rest)))))))", 'fuel') +LC_ = (f"(let c : (Nat * Dec) := (decodeBit d base); (let cb : Nat := (first c); (if (cb =? 0) then (tree (second c) (base + {LOW_AT}) {LOW_BITS}) else (let c2 : (Nat * Dec) := (decodeBit (second c) (base + 1)); (let cb2 : Nat := (first c2); " + f"(if (cb2 =? 0) then (let t : (Nat * Dec) := (tree (second c2) (base + {MID_AT}) {LOW_BITS}); (let tv : Nat := (first t); (({LOW} + tv), (second t)))) else (let t : (Nat * Dec) := (tree (second c2) (base + {HIGH_AT}) {HIGH_BITS}); (let tv : Nat := (first t); ((({RADIX} * {LOW}) + tv), (second t))))))))))") +D('lengthCode', ['d : Dec', 'base : Nat'], '(Nat * Dec)', LC_) +LS_LAST = f"(prim subtract {LEN_STATES} 1 : Nat)" +DS = (f"(let ls : Nat := (if (lenCode d\n | Nat.succ k => (if ({P('d','total')} <=? {P('d','size')}) then d else (let b : Nat := {BACK('d')}; (copyLoop k (emit d b)))))", 'fuel') lit = (f"(let s0 : Nat := {P('d','state')}; (let size0 : Nat := {P('d','size')}; (let prev : Nat := (if (size0 =? 0) then 0 else (outAt d (prim subtract size0 1 : Nat))); " - f"(let base : Nat := ({LIT} + (768 * (prim quotient prev 32 0 : Nat))); " + f"(let base : Nat := ({LIT} + ({LIT_CODER} * (prim quotient prev {LIT_SHIFT} 0 : Nat))); " f"(let mb : Nat := (if ({P('d','rep0')} d\n | Nat.succ k => (let t : Nat := {P('d','total')}; (let s : Nat := {P('d','size')}; (if (t <=? s) then d else (decodeLoop k (step d))))))", 'fuel') # little-endian, read from the top byte down so that no weight passes 2^56 D('readLength', ['data : Bytes', 'fuel : Nat', 'at : Nat', 'acc : Nat'], 'Nat', - "(match fuel\n | Nat.zero => acc\n | Nat.succ k => (readLength data k at ((256 * acc) + (byteAt data (at + k)))))", 'fuel') + f"(match fuel\n | Nat.zero => acc\n | Nat.succ k => (readLength data k at (({BYTE_BASE} * acc) + (byteAt data (at + k)))))", 'fuel') +# big-endian, the code word after the length and the coder's zero byte +D('readBig', ['data : Bytes', 'fuel : Nat', 'at : Nat', 'acc : Nat'], 'Nat', + f"(match fuel\n | Nat.zero => acc\n | Nat.succ k => (readBig data k (at + 1) (({BYTE_BASE} * acc) + (byteAt data at))))", 'fuel') # the output starts as `history` (h bytes); matches may reach into it and only the bytes after it are returned -startW = ("(let h : Nat := (prim length history : Nat); (let total : Nat := (readLength input 8 0 0); (let code : Nat := ((256 * ((256 * ((256 * (byteAt input 9)) + (byteAt input 10))) + (byteAt input 11))) + (byteAt input 12)); " - + L.make({'mem': f"(prim append (prim append ({T}::fill 2 13 1024) history : Bytes) ({T}::fill 1 (depthFor 64 total 0) 0) : Bytes)"}, - dict(input='input', pos='13', range='4294967295', code='code', size='h', total='(h + total)', state='0', rep0='0', rep1='0', rep2='0', rep3='0')) + ")))") +startW = (f"(let h : Nat := (prim length history : Nat); (let total : Nat := (readLength input {LENGTH_BYTES} 0 0); (let code : Nat := (readBig input {CODE_BYTES} {CODE_AT} 0); " + + L.make({'mem': f"(prim append (prim append ({T}::fill {PROB_CELL} {PROB_COUNT_BITS} (prim quotient {PROB_RANGE} {RADIX} 0 : Nat)) history : Bytes) ({T}::fill 1 (depthFor ({LENGTH_BYTES} * {BYTE_BITS}) total 0) 0) : Bytes)"}, + dict(input='input', pos=START_POS, range=f"(prim subtract (pow2 {CODE_BITS}) 1 : Nat)", code='code', size='h', total='(h + total)', state='0', rep0='0', rep1='0', rep2='0', rep3='0')) + ")))") D('startWith', ['history : Bytes', 'input : Bytes'], 'Dec', startW) decW = (f"(let h : Nat := (prim length history : Nat); (let d : Dec := (startWith history input); (let steps : Nat := ((prim subtract {P('d','total')} h : Nat) + 1); " - f"(let f : Dec := (decodeLoop steps d); (let size : Nat := {P('f','size')}; (match (prim slice {P('f','mem')} (16384 + h) (prim subtract size h : Nat) : (Option Bytes))\n | Option.none => 0x\n | Option.some b => b))))))") + f"(let f : Dec := (decodeLoop steps d); (let size : Nat := {P('f','size')}; (match (prim slice {P('f','mem')} ({OUT_AT} + h) (prim subtract size h : Nat) : (Option Bytes))\n | Option.none => 0x\n | Option.some b => b))))))") D('decodeWith', ['history : Bytes', 'input : Bytes'], 'Bytes', decW) D('decode', ['input : Bytes'], 'Bytes', "(decodeWith 0x input)") src = ("\\begin{lexlean}{Uorc.Codec.LzDecode}\n\\importmodule{Uorc.Codec.Table}\n\\title{Parameters}\n\\begin{semanticmodule}\n" diff --git a/client/gen/gen_ncm.py b/client/gen/gen_ncm.py index fe51d686..2bb3a34c 100644 --- a/client/gen/gen_ncm.py +++ b/client/gen/gen_ncm.py @@ -22,9 +22,9 @@ def sizing(L): # the context table's bits: the ones the profile word records in bits 20-25 (TABLE_SHIFT), else the length's own; # the match tables' bits: the ones it records in bits 26-30 (MATCH_SHIFT), else the default context table's D('tbOf', ['n : Nat', 'profile : Nat'], 'Nat', - f"(let t : Nat := (prim remainder (prim quotient profile {ncm_model.TABLE_UNIT} 0 : Nat) 64 0 : Nat); (if (0 1\n | Nat.succ m => (prim multiply 2 (pow2 m) : Nat))", 'k') + radix = need(ir.RADIX) + D('pow2', ['k : Nat'], 'Nat', f"(match k\n | Nat.zero => 1\n | Nat.succ m => (prim multiply {radix} (pow2 m) : Nat))", 'k') D('getAt', ['w : Nat', 't : Bytes', 'at : Nat'], 'Nat', f"({TB}::getLoop w t at 0)") D('putAt', ['w : Nat', 't : Bytes', 'at : Nat', 'v : Nat'], 'Bytes', f"({TB}::setLoop w t (prim subtract (at + w) 1 : Nat) v)") - D('sqt', [], 'Bytes', '0x' + b''.join(v.to_bytes(2, 'big') for v in ir.SQT).hex()) - D('squash', ['d : Nat'], 'Nat', - "(let i : Nat := (prim quotient d 128 0 : Nat); (let w : Nat := (prim remainder d 128 0 : Nat); " - "(prim quotient ((prim multiply (getAt 2 (sqt) (prim multiply 2 i : Nat)) (prim subtract 128 w : Nat) : Nat) + " - "((prim multiply (getAt 2 (sqt) (prim multiply 2 (i + 1) : Nat)) w : Nat) + 64)) 128 0 : Nat)))") - body = 'a' - steps = [] - for j, (k, s) in enumerate(zip(ir.HK, ir.HS)): - steps.append(f"(let m{j} : Nat := (prim remainder (prim multiply {k} {body} : Nat) 4294967296 0 : Nat); " - f"(let a{j} : Nat := (prim remainder (m{j} + (prim quotient m{j} {1 << s} 0 : Nat)) 4294967296 0 : Nat); ") - body = f'a{j}' - D('hash', ['a : Nat'], 'Nat', ''.join(steps) + body + ')' * (2 * len(ir.HK))) + used = self.uses() + if 'squash' in used: + # squash interpolates the table sqt (cells of sqtCell bytes) at abscissae squashStep apart + step, half, cell = need(ir.SQUASH_STEP), need(ir.SQUASH_HALF), need(ir.SQT_CELL) + D('sqt', [], 'Bytes', '0x' + b''.join(v.to_bytes(int(ir.SQT_CELL), 'big') for v in ir.SQT).hex()) + D('squash', ['d : Nat'], 'Nat', + f"(let i : Nat := (prim quotient d {step} 0 : Nat); (let w : Nat := (prim remainder d {step} 0 : Nat); " + f"(prim quotient ((prim multiply (getAt {cell} (sqt) (prim multiply {cell} i : Nat)) (prim subtract {step} w : Nat) : Nat) + " + f"((prim multiply (getAt {cell} (sqt) (prim multiply {cell} (i + 1) : Nat)) w : Nat) + {half})) {step} 0 : Nat)))") + if 'hash' in used: + # the context hash: each round multiplies by its multiplier and folds the word down by its fold + word = need(ir.HASH_WORD) + body = 'a' + steps = [] + for j, (k, f) in enumerate(zip(ir.HK, ir.HF)): + k, f = need(k), need(f) + steps.append(f"(let m{j} : Nat := (prim remainder (prim multiply {k} {body} : Nat) {word} 0 : Nat); " + f"(let a{j} : Nat := (prim remainder (m{j} + (prim quotient m{j} {f} 0 : Nat)) {word} 0 : Nat); ") + body = f'a{j}' + D('hash', ['a : Nat'], 'Nat', ''.join(steps) + body + ')' * (2 * len(ir.HK))) # one writer per table: moves the table out of the state, writes it in place, rebuilds the state for t in self.tables: D(self.writer(t), [f's : {self.St}', 'w : Nat', 'k : Nat', 'v : Nat'], self.St, @@ -195,6 +204,19 @@ def base(self, table): b = self.p.tables[table] return b if isinstance(b, ir.K) or b <= 1 else ir.K('base' + re.sub(r'[^A-Za-z0-9]', 'X', table), b) + def uses(self): + """The expression kinds the program's functions use.""" + out = set() + def walk(e): + if isinstance(e, tuple) and e and isinstance(e[0], str): + out.add(e[0]) + if isinstance(e, (tuple, list)): + for a in e: + walk(a) + for params, body in self.p.funcs.values(): + walk(body) + return out + def need(self, x): """A named quantity's numeral or name, defining it (after those its body reads) on first use: a numeral, or arithmetic of names, with no axiom (as atX, widthX, Archive.planField).""" diff --git a/client/gen/ncm_model.py b/client/gen/ncm_model.py index 8a26f3a6..196dcc0b 100644 --- a/client/gen/ncm_model.py +++ b/client/gen/ncm_model.py @@ -18,16 +18,20 @@ HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) from ir import * -from ir import K +from ir import K, RADIX +import ir NC = 17 # hashed contexts -NIN = NC + 7 # mixer inputs: contexts, match probability, match vote, bias, short match (2), repeat (2) -F_SHORT = 1 << 17 # profile bit: the short match model -F_REP = 1 << 18 # profile bit: the repeat-distance model (its inputs and context 13) -F_SEL = 1 << 19 # profile bit: mixer 1 and the first APM selected by the match states too +# The profile word's layout: each field's unit is the unit of the field before it times that field's +# range; the ranges are the format's identities. +F_SHORT = K('shortBit', 1 << NC) # profile bit: the short match model (after a bit per context) +F_REP = K('repBit', ('mul', F_SHORT, RADIX)) # profile bit: the repeat-distance model (its inputs and context 13) +F_SEL = K('selBit', ('mul', F_REP, RADIX)) # profile bit: mixer 1 and the first APM selected by the match states too TBMAX = 24 -TABLE_UNIT = 1 << 20 # the profile word's context table field (6 bits) starts here (ncm::TABLE_SHIFT) -MATCH_UNIT = 1 << 26 # and its match table field (5 bits) here (ncm::MATCH_SHIFT) +TABLE_UNIT = K('tableUnit', ('mul', F_SEL, RADIX)) # the profile word's context table field starts here (ncm::TABLE_SHIFT) +TABLE_FIELD = K('tableField', 64) # its range (6 bits) +MATCH_UNIT = K('matchUnit', ('mul', TABLE_UNIT, TABLE_FIELD)) # and its match table field here (ncm::MATCH_SHIFT) +MATCH_FIELD = K('matchField', 32) # its range (5 bits) SQT = [1, 2, 3, 6, 10, 16, 27, 45, 73, 120, 194, 310, 488, 747, 1101, 1546, 2047, 2549, 2994, 3348, 3607, 3785, 3901, 3975, 4022, 4050, 4068, 4079, 4085, 4089, 4092, 4093, 4094] WRANGE = K('weightRange', 1 << 24) # a stored weight, offset form @@ -39,9 +43,20 @@ WINIT0 = WORIGIN KW0 = K('weightKeyZero', ('sub', WRANGE, WORIGIN)) EARNED = K('earnedInputs', ('add', K('contexts', NC), K('matchInputs', 3))) # inputs that start at WINIT +NIN = K('mixerInputs', ('add', EARNED, K('slotModelInputs', 4))) # mixer inputs: contexts, match probability, match vote, bias, short match (2), repeat (2) +# The domains of the coder's quantities (see domains.py): each declared once by its extent, and the +# tables and globals that hold it; every literal that is a characteristic quantity of the domain it acts +# on is then stated as that quantity, derived from the extent. +import domains +STRETCH = domains.Domain('stretch', K('stretchRange', 1 << 12), offset=True) # the logistic domain +SLOT = domains.Domain('slot', K('slotRange', 1 << 16)) # a probability slot, offset form +WEIGHT = domains.Domain('weight', WRANGE, WORIGIN, unit=K('weightUnit', 1 << 16)) # a mixer weight, 1.0 = unit +XW = domains.origins(NIN, STRETCH, WEIGHT) # a mixer dot product's constant term +XW1 = domains.origins(K('mixerInputsBut1', ('sub', NIN, 1)), STRETCH, WEIGHT) def winit(i): return sel(lt(i, EARNED), WINIT, WINIT0) def kw(i): return sel(lt(i, EARNED), KW, KW0) M32 = 1 << 32 +ROLL = K('rollMultiplier', 0x2F0B4C27) # the rolling context hashes' multiplier: an identity of the format P = Prog() for name, w in [('n', 4), ('tb', 1), ('mb', 1), ('pos', 4), ('c4', 4), ('c8', 4), ('wordh', 4), ('word1', 4), @@ -84,7 +99,7 @@ def hist(i): return ld('H', 1, i) def coded(i): return hist(add(G('hoff'), i)) def has(bit): - return eq(mod(div(G('prof'), bit), 2), 1) + return eq(mod(div(G('prof'), bit), RADIX), 1) # Profile bits 0..NC-1 keep context k. A context left out is never looked up or adapted and feeds every mixer # the stretch 0 (2048 in offset form), which moves no dot product and trains no weight. @@ -97,7 +112,7 @@ def match_key2(p, body): last = 'mq0' for i in range(1, 5): nxt = fresh('mq') - body.append(('let', nxt, u32(add(add(mul(0x2F0B4C27, V(last)), hist(sub(p, i))), 1)))) + body.append(('let', nxt, u32(add(add(mul(ROLL, V(last)), hist(sub(p, i))), 1)))) last = nxt hash_('mqh', V(last), body) body.append(('let', 'mk2', div(V('mqh'), rom('POW2', 4, sub(32, G('mb')))))) @@ -108,7 +123,7 @@ def match_key(p, body): last = 'mh0' for i in range(1, 8): nxt = fresh('mh') - body.append(('let', nxt, u32(add(add(mul(0x2F0B4C27, V(last)), hist(sub(p, i))), 1)))) + body.append(('let', nxt, u32(add(add(mul(ROLL, V(last)), hist(sub(p, i))), 1)))) last = nxt hash_('mhh', V(last), body) body.append(('let', 'mk', div(V('mhh'), rom('POW2', 4, sub(32, G('mb')))))) @@ -120,8 +135,8 @@ def match_key(p, body): init += [('set', 'tb', 16), ('loop', TBMAX - 16, 'k', [('if', lt(rom('POW2', 4, G('tb')), mul(1024, G('n'))), [('set', 'tb', add(G('tb'), 1))], [])]), ('set', 'mb', sel(lt(22, G('tb')), 22, sub(G('tb'), 2))), - ('if', lt(0, mod(div(G('prof'), TABLE_UNIT), 64)), [('set', 'tb', mod(div(G('prof'), TABLE_UNIT), 64))], []), - ('if', lt(0, mod(div(G('prof'), MATCH_UNIT), 32)), [('set', 'mb', mod(div(G('prof'), MATCH_UNIT), 32))], []), + ('if', lt(0, mod(div(G('prof'), TABLE_UNIT), TABLE_FIELD)), [('set', 'tb', mod(div(G('prof'), TABLE_UNIT), TABLE_FIELD))], []), + ('if', lt(0, mod(div(G('prof'), MATCH_UNIT), MATCH_FIELD)), [('set', 'mb', mod(div(G('prof'), MATCH_UNIT), MATCH_FIELD))], []), ('set', 'c0', 1), ('set', 'x2', M32 - 1)] # stretch: STR[j] = the least x with squash(x) >= j, else 2047 (offset form) sb = [] @@ -217,7 +232,7 @@ def match_key(p, body): pr = [] bk = [('let', 'nc', sel(eq(G('bit'), 0), 0, add(mod(G('c0'), 16), 16)))] bkl = [] -hash_('bh', u32(add(ld('HB', 4, V('k')), mul(0x2F0B4C27, V('nc')))), bkl) +hash_('bh', u32(add(ld('HB', 4, V('k')), mul(ROLL, V('nc')))), bkl) bkl += [('let', 'bm', mod(V('bh'), rom('POW2', 4, G('tb')))), ('let', 'b0', sub(V('bm'), mod(V('bm'), 16))), ('let', 'h24', div(V('bh'), 1 << 24)), ('let', 'ck', add(V('h24'), sub(1, mod(V('h24'), 2)))), ('let', 'alt', sel(eq(mod(div(V('b0'), 16), 2), 1), monus(V('b0'), 16), add(V('b0'), 16)))] @@ -280,8 +295,8 @@ def match_key(p, body): def dot(out, accv, swv, body): a = fresh('da'); b = fresh('db') - body.append(('let', a, add(accv, NIN * 2048 * (1 << 22)))) - body.append(('let', b, add(mul(1 << 22, G('sso')), mul(2048, swv)))) + body.append(('let', a, add(accv, XW))) + body.append(('let', b, add(mul(WEIGHT.origin, G('sso')), mul(STRETCH.origin, swv)))) body.append(('let', out, sel(le(V(b), V(a)), add(2048, mn(div(monus(V(a), V(b)), 65536), 2047)), sub(2048, mn(div(add(monus(V(b), V(a)), 65535), 65536), 2047))))) dot('d1', G('acc'), G('sw'), pr) @@ -295,14 +310,22 @@ def dot(out, accv, swv, body): # adaptive probability maps: rows of 33 points over the stretch domain, stored as offsets from their # initial values (point j starts at 16 * squash(128 j - 2048)) so that a fresh table holds the start +APM_STEP = ir.SQUASH_STEP # the points' spacing +APM_INTERVALS = K('apmIntervals', ('div', STRETCH.extent, APM_STEP)) +APM_POINTS = K('apmPoints', ('add', APM_INTERVALS, 1)) +SLOT_PER_STRETCH = K('slotPerStretch', ('div', SLOT.extent, STRETCH.extent)) # a 12-bit probability as a slot +APM_TOP = K('apmTop', ('mul', K('stretchLast', ('sub', STRETCH.extent, 1)), SLOT_PER_STRETCH)) +APM_SCALE = K('apmScale', ('mul', APM_STEP, SLOT_PER_STRETCH)) # an interpolated slot, back to 12 bits + def ainit(j): sq = fresh('sq') - return sq, [('let', sq, ('squash', mn(mul(128, j), 4095)))], sel(eq(j, 0), 0, sel(eq(j, 32), 4095 * 16, mul(16, V(sq)))) + return sq, [('let', sq, ('squash', mn(mul(APM_STEP, j), K('stretchLast', ('sub', STRETCH.extent, 1)))))], \ + sel(eq(j, 0), 0, sel(eq(j, APM_INTERVALS), APM_TOP, mul(SLOT_PER_STRETCH, V(sq)))) def apm_get(table, idx, j, body): sq, pre, init = ainit(j) body += pre - return mod(add(ld(table, 2, idx), init), 65536) + return mod(add(ld(table, 2, idx), init), SLOT.extent) # The probability's scale over 12 bits: 1, or 16 under a frame word's probability field 16 (pz 15; every # frame coder's pz is 0): a map refines at 16 bits, the coder splits its range in 65536ths. @@ -311,16 +334,16 @@ def apm_get(table, idx, j, body): def refine(out, table, cx, gi, gj, body): s, l, w = fresh('as'), fresh('al'), fresh('aw') - body += [('let', s, ld('STR', 2, V('pa'))), ('let', l, div(V(s), 128)), ('let', w, mod(V(s), 128))] + body += [('let', s, ld('STR', 2, V('pa'))), ('let', l, div(V(s), APM_STEP)), ('let', w, mod(V(s), APM_STEP))] base = fresh('ab') - body += [('let', base, add(mul(33, cx), V(l)))] + body += [('let', base, add(mul(APM_POINTS, cx), V(l)))] t0 = apm_get(table, V(base), V(l), body) t1 = apm_get(table, add(V(base), 1), add(V(l), 1), body) - body += [('let', out, div(mul(PS, add(mul(t0, sub(128, V(w))), mul(t1, V(w)))), 2048)), - ('set', gi, add(V(base), div(V(w), 64))), ('set', gj, add(V(l), div(V(w), 64)))] + body += [('let', out, div(mul(PS, add(mul(t0, sub(APM_STEP, V(w))), mul(t1, V(w)))), APM_SCALE)), + ('set', gi, add(V(base), div(V(w), ir.SQUASH_HALF))), ('set', gj, add(V(l), div(V(w), ir.SQUASH_HALF)))] refine('r1', 'A1', add(G('c0'), mul(256, G('msel'))), 'ai1', 'aj1', pr) -hash_('ah2', u32(add(mul(0x2F0B4C27, mod(G('c4'), 1 << 24)), G('c0'))), pr) +hash_('ah2', u32(add(mul(ROLL, mod(G('c4'), 1 << 24)), G('c0'))), pr) refine('r2', 'A2', div(V('ah2'), 65536), 'ai2', 'aj2', pr) pr += [('set', 'pr', mx(mn(div(add(add(mul(PS, V('pa')), V('r1')), mul(2, V('r2'))), 4), sub(mul(4096, PS), 1)), 1))] P.func('predict', [], pr) @@ -462,14 +485,14 @@ def dot_of(out, a, b, body): ('let', 'gs2', mul(NIN, add(mul(8, mod(G('c4'), 256)), G('bit')))), ('let', 'gs3', mul(NIN, add(mul(8, mod(div(G('c4'), 256), 256)), G('bit'))))] for m, acc, sw in ((1, 'acc', 'sw'), (2, 'acc2', 'sw2'), (3, 'acc3', 'sw3')): - dot_of(f'gd{m}', add(G(acc), NIN * 2048 * (1 << 22)), add(mul(1 << 22, G('sso')), mul(2048, G(sw))), gk) + dot_of(f'gd{m}', add(G(acc), XW), add(mul(WEIGHT.origin, G('sso')), mul(STRETCH.origin, G(sw))), gk) squash_('gq', div(mul(21846, add(add(V('gd1'), V('gd2')), V('gd3'))), 65536), gk) gk += [('let', 'gbase', cost(mx(mn(V('gq'), 4095), 1)))] gl = [('let', 'gso', ld('ST', 2, V('k')))] for m, tab, acc, sw in ((1, 'W1', 'acc', 'sw'), (2, 'W2', 'acc2', 'sw2'), (3, 'W3', 'acc3', 'sw3')): gl += [('let', f'gw{m}', mod(add(ld(tab, 3, add(V(f'gs{m}'), V('k'))), winit(V('k'))), 1 << 24))] - dot_of(f'ge{m}', add(sub(G(acc), mul(V('gso'), V(f'gw{m}'))), (NIN - 1) * 2048 * (1 << 22)), - add(mul(1 << 22, sub(G('sso'), V('gso'))), mul(2048, sub(G(sw), V(f'gw{m}')))), gl) + dot_of(f'ge{m}', add(sub(G(acc), mul(V('gso'), V(f'gw{m}'))), XW1), + add(mul(WEIGHT.origin, sub(G('sso'), V('gso'))), mul(STRETCH.origin, sub(G(sw), V(f'gw{m}')))), gl) squash_('gp', div(mul(21846, add(add(V('ge1'), V('ge2')), V('ge3'))), 65536), gl) gl += [('let', 'gv', mod(add(ld('GN', 8, V('k')), GOFF), 1 << 48)), ('store', 'GN', 8, V('k'), mod(sub(add(monus(add(V('gv'), cost(mx(mn(V('gp'), 4095), 1))), V('gbase')), 1 << 48), GOFF), 1 << 48))] @@ -511,6 +534,12 @@ def dot_of(out, a, b, body): ('set', 'lmask', V('pf')), ('loop', NC, 'k', lm)]) +DERIVED = domains.derive( + P, [STRETCH, SLOT, WEIGHT], + tables={'STR': {'stretch'}, 'ST': {'stretch'}, 'A1': {'slot'}, 'A2': {'slot'}, 'T': {'slot'}, 'MS': {'slot'}, + 'M2S': {'slot'}, 'RS': {'slot'}, 'W1': {'weight'}, 'W2': {'weight'}, 'W3': {'weight'}}, + globals_={'pm1': {'stretch'}, 'pm2': {'stretch'}, 'pm3': {'stretch'}, 'pr': {'stretch'}, 'pi': {'stretch'}}) + FULL = (1 << 20) - 1 # every context and every match feature V03 = (1 << NC) - 1 # the v0.3 coder: every context, neither match feature diff --git a/client/src/Uorc/Codec/LzDecode.lex.tex b/client/src/Uorc/Codec/LzDecode.lex.tex index 87d87fb9..d0668d22 100644 --- a/client/src/Uorc/Codec/LzDecode.lex.tex +++ b/client/src/Uorc/Codec/LzDecode.lex.tex @@ -62,6 +62,393 @@ recursive_argument: k } +definition{ + name: states, + parameters: [], + result: Nat, + body: 12, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: isRepBase, + parameters: [], + result: Nat, + body: (states), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: isRepG0Base, + parameters: [], + result: Nat, + body: ((isRepBase) + (states)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: isRepG1Base, + parameters: [], + result: Nat, + body: ((isRepG0Base) + (states)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: isRepG2Base, + parameters: [], + result: Nat, + body: ((isRepG1Base) + (states)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: isRep0LongBase, + parameters: [], + result: Nat, + body: ((isRepG2Base) + (states)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: literalBase, + parameters: [], + result: Nat, + body: ((isRep0LongBase) + (states)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: radix, + parameters: [], + result: Nat, + body: 2, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: byteBits, + parameters: [], + result: Nat, + body: 8, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: byteBase, + parameters: [], + result: Nat, + body: (pow2 (byteBits)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: literalContextBits, + parameters: [], + result: Nat, + body: 3, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: literalCoder, + parameters: [], + result: Nat, + body: (prim multiply ((radix) + 1) (byteBase) : Nat), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: literalContextShift, + parameters: [], + result: Nat, + body: (pow2 (prim subtract (byteBits) (literalContextBits) : Nat)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: slotBase, + parameters: [], + result: Nat, + body: ((literalBase) + (prim multiply (literalCoder) (pow2 (literalContextBits)) : Nat)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: lengthStates, + parameters: [], + result: Nat, + body: 4, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: slotBits, + parameters: [], + result: Nat, + body: 6, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: slotTree, + parameters: [], + result: Nat, + body: (pow2 (slotBits)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: specBase, + parameters: [], + result: Nat, + body: ((slotBase) + (prim multiply (lengthStates) (slotTree) : Nat)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: startSlot, + parameters: [], + result: Nat, + body: 4, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: endSlot, + parameters: [], + result: Nat, + body: 14, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: alignBits, + parameters: [], + result: Nat, + body: 4, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: alignTree, + parameters: [], + result: Nat, + body: (pow2 (alignBits)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: alignBase, + parameters: [], + result: Nat, + body: ((specBase) + (prim subtract ((pow2 (prim quotient (endSlot) (radix) 0 : Nat)) + 1) (endSlot) : Nat)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: lengthBase, + parameters: [], + result: Nat, + body: ((alignBase) + (alignTree)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: lowBits, + parameters: [], + result: Nat, + body: 3, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: highBits, + parameters: [], + result: Nat, + body: 8, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: lowSymbols, + parameters: [], + result: Nat, + body: (pow2 (lowBits)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: lowAt, + parameters: [], + result: Nat, + body: (radix), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: midAt, + parameters: [], + result: Nat, + body: ((lowAt) + (prim multiply (radix) (lowSymbols) : Nat)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: highAt, + parameters: [], + result: Nat, + body: ((midAt) + (prim multiply (radix) (lowSymbols) : Nat)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: repLengthBase, + parameters: [], + result: Nat, + body: ((lengthBase) + ((highAt) + (prim multiply (radix) (pow2 (highBits)) : Nat))), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: minMatch, + parameters: [], + result: Nat, + body: 2, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: probabilityBits, + parameters: [], + result: Nat, + body: 11, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: probabilityRange, + parameters: [], + result: Nat, + body: (pow2 (probabilityBits)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: probabilityCountBits, + parameters: [], + result: Nat, + body: 13, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: probabilityCell, + parameters: [], + result: Nat, + body: (radix), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: outputBase, + parameters: [], + result: Nat, + body: (prim multiply (probabilityCell) (pow2 (probabilityCountBits)) : Nat), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: lengthBytes, + parameters: [], + result: Nat, + body: (byteBits), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: startPosition, + parameters: [], + result: Nat, + body: 13, + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: codeAt, + parameters: [], + result: Nat, + body: ((lengthBytes) + 1), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: codeBytes, + parameters: [], + result: Nat, + body: (prim subtract (startPosition) (codeAt) : Nat), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: rangeTop, + parameters: [], + result: Nat, + body: (pow2 (prim subtract (prim multiply (codeBytes) (byteBits) : Nat) (byteBits) : Nat)), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: moveScale, + parameters: [], + result: Nat, + body: 32, + executable: true, + axioms: [Quot.sound, propext] +} + definition{ name: depthFor, parameters: [fuel : Nat, n : Nat, depth : Nat], @@ -78,7 +465,7 @@ name: normalize, parameters: [d : (Bytes * DecS)], result: (Bytes * DecS), - body: (if ((project (second d) range) (acc, d) - | Nat.succ m => (let half : Nat := (prim quotient (project (second d) range) 2 0 : Nat); (if ((project (second d) code) (let half : Nat := (prim quotient (project (second d) range) (radix) 0 : Nat); (if ((project (second d) code) (sym, d) - | Nat.succ k => (let mbit : Nat := (prim remainder (prim quotient matchByte (pow2 k) 0 : Nat) 2 0 : Nat); (let r : (Nat * (Bytes * DecS)) := (decodeBit d ((base + (prim multiply 256 (1 + mbit) : Nat)) + sym)); (let bit : Nat := (first r); (let next : Nat := ((prim multiply 2 sym : Nat) + bit); (if (bit =? mbit) then (matchedLoop k (second r) base matchByte next) else (let rest : (Nat * (Bytes * DecS)) := (treeLoop k (second r) base next); rest))))))), + | Nat.succ k => (let mbit : Nat := (prim remainder (prim quotient matchByte (pow2 k) 0 : Nat) (radix) 0 : Nat); (let r : (Nat * (Bytes * DecS)) := (decodeBit d ((base + (prim multiply (1 + mbit) (byteBase) : Nat)) + sym)); (let bit : Nat := (first r); (let next : Nat := ((prim multiply (radix) sym : Nat) + bit); (if (bit =? mbit) then (matchedLoop k (second r) base matchByte next) else (let rest : (Nat * (Bytes * DecS)) := (treeLoop k (second r) base next); rest))))))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -162,7 +549,7 @@ name: lengthCode, parameters: [d : (Bytes * DecS), base : Nat], result: (Nat * (Bytes * DecS)), - body: (let c : (Nat * (Bytes * DecS)) := (decodeBit d base); (let cb : Nat := (first c); (if (cb =? 0) then (tree (second c) (base + 2) 3) else (let c2 : (Nat * (Bytes * DecS)) := (decodeBit (second c) (base + 1)); (let cb2 : Nat := (first c2); (if (cb2 =? 0) then (let t : (Nat * (Bytes * DecS)) := (tree (second c2) (base + 18) 3); (let tv : Nat := (first t); ((8 + tv), (second t)))) else (let t : (Nat * (Bytes * DecS)) := (tree (second c2) (base + 34) 8); (let tv : Nat := (first t); ((16 + tv), (second t)))))))))), + body: (let c : (Nat * (Bytes * DecS)) := (decodeBit d base); (let cb : Nat := (first c); (if (cb =? 0) then (tree (second c) (base + (lowAt)) (lowBits)) else (let c2 : (Nat * (Bytes * DecS)) := (decodeBit (second c) (base + 1)); (let cb2 : Nat := (first c2); (if (cb2 =? 0) then (let t : (Nat * (Bytes * DecS)) := (tree (second c2) (base + (midAt)) (lowBits)); (let tv : Nat := (first t); (((lowSymbols) + tv), (second t)))) else (let t : (Nat * (Bytes * DecS)) := (tree (second c2) (base + (highAt)) (highBits)); (let tv : Nat := (first t); (((prim multiply (radix) (lowSymbols) : Nat) + tv), (second t)))))))))), executable: true, axioms: [Quot.sound, propext] } @@ -171,7 +558,7 @@ name: distance, parameters: [d : (Bytes * DecS), lenCode : Nat], result: (Nat * (Bytes * DecS)), - body: (let ls : Nat := (if (lenCode acc - | Nat.succ k => (readLength data k at ((prim multiply 256 acc : Nat) + (byteAt data (at + k))))), + | Nat.succ k => (readLength data k at ((prim multiply (byteBase) acc : Nat) + (byteAt data (at + k))))), + executable: true, + axioms: [Quot.sound, propext], + recursive_argument: fuel +} + +definition{ + name: readBig, + parameters: [data : Bytes, fuel : Nat, at : Nat, acc : Nat], + result: Nat, + body: (match fuel + | Nat.zero => acc + | Nat.succ k => (readBig data k (at + 1) ((prim multiply (byteBase) acc : Nat) + (byteAt data at)))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -315,7 +714,7 @@ name: startWith, parameters: [history : Bytes, input : Bytes], result: (Bytes * DecS), - body: (let h : Nat := (prim length history : Nat); (let total : Nat := (readLength input 8 0 0); (let code : Nat := ((prim multiply 256 ((prim multiply 256 ((prim multiply 256 (byteAt input 9) : Nat) + (byteAt input 10)) : Nat) + (byteAt input 11)) : Nat) + (byteAt input 12)); ((prim append (prim append (Uorc.Codec.Table::fill 2 13 1024) history : Bytes) (Uorc.Codec.Table::fill 1 (depthFor 64 total 0) 0) : Bytes), (record DecS {input := input, pos := 13, range := 4294967295, code := code, size := h, total := (h + total), state := 0, rep0 := 0, rep1 := 0, rep2 := 0, rep3 := 0}))))), + body: (let h : Nat := (prim length history : Nat); (let total : Nat := (readLength input (lengthBytes) 0 0); (let code : Nat := (readBig input (codeBytes) (codeAt) 0); ((prim append (prim append (Uorc.Codec.Table::fill (probabilityCell) (probabilityCountBits) (prim quotient (probabilityRange) (radix) 0 : Nat)) history : Bytes) (Uorc.Codec.Table::fill 1 (depthFor (prim multiply (lengthBytes) (byteBits) : Nat) total 0) 0) : Bytes), (record DecS {input := input, pos := (startPosition), range := (prim subtract (pow2 (prim multiply (codeBytes) (byteBits) : Nat)) 1 : Nat), code := code, size := h, total := (h + total), state := 0, rep0 := 0, rep1 := 0, rep2 := 0, rep3 := 0}))))), executable: true, axioms: [Quot.sound, propext] } @@ -324,7 +723,7 @@ name: decodeWith, parameters: [history : Bytes, input : Bytes], result: Bytes, - body: (let h : Nat := (prim length history : Nat); (let d : (Bytes * DecS) := (startWith history input); (let steps : Nat := ((prim subtract (project (second d) total) h : Nat) + 1); (let f : (Bytes * DecS) := (decodeLoop steps d); (let size : Nat := (project (second f) size); (match (prim slice (first f) (16384 + h) (prim subtract size h : Nat) : (Option Bytes)) + body: (let h : Nat := (prim length history : Nat); (let d : (Bytes * DecS) := (startWith history input); (let steps : Nat := ((prim subtract (project (second d) total) h : Nat) + 1); (let f : (Bytes * DecS) := (decodeLoop steps d); (let size : Nat := (project (second f) size); (match (prim slice (first f) ((outputBase) + h) (prim subtract size h : Nat) : (Option Bytes)) | Option.none => 0x | Option.some b => b)))))), executable: true, diff --git a/client/src/Uorc/Codec/NcmDecode.lex.tex b/client/src/Uorc/Codec/NcmDecode.lex.tex index 98cfb320..42aac62a 100644 --- a/client/src/Uorc/Codec/NcmDecode.lex.tex +++ b/client/src/Uorc/Codec/NcmDecode.lex.tex @@ -11,6 +11,123 @@ ] } +definition{ + name: shortBit, + parameters: [], + result: Nat, + body: 131072, + executable: true, + axioms: [] +} + +definition{ + name: radix, + parameters: [], + result: Nat, + body: 2, + executable: true, + axioms: [] +} + +definition{ + name: repBit, + parameters: [], + result: Nat, + body: (prim multiply (shortBit) (radix) : Nat), + executable: true, + axioms: [] +} + +definition{ + name: selBit, + parameters: [], + result: Nat, + body: (prim multiply (repBit) (radix) : Nat), + executable: true, + axioms: [] +} + +definition{ + name: tableUnit, + parameters: [], + result: Nat, + body: (prim multiply (selBit) (radix) : Nat), + executable: true, + axioms: [] +} + +definition{ + name: tableField, + parameters: [], + result: Nat, + body: 64, + executable: true, + axioms: [] +} + +definition{ + name: matchUnit, + parameters: [], + result: Nat, + body: (prim multiply (tableUnit) (tableField) : Nat), + executable: true, + axioms: [] +} + +definition{ + name: matchField, + parameters: [], + result: Nat, + body: 32, + executable: true, + axioms: [] +} + +definition{ + name: byteBase, + parameters: [], + result: Nat, + body: 256, + executable: true, + axioms: [] +} + +definition{ + name: cell2Base, + parameters: [], + result: Nat, + body: (prim multiply (byteBase) (byteBase) : Nat), + executable: true, + axioms: [] +} + +definition{ + name: cell3Base, + parameters: [], + result: Nat, + body: (prim multiply (cell2Base) (byteBase) : Nat), + executable: true, + axioms: [] +} + +definition{ + name: cell4Base, + parameters: [], + result: Nat, + body: (prim multiply (cell3Base) (byteBase) : Nat), + executable: true, + axioms: [] +} + +definition{ + name: cell4Last, + parameters: [], + result: Nat, + body: (prim subtract (cell4Base) 1 : Nat), + executable: true, + axioms: [] +} + definition{ name: cellSTR, parameters: [], @@ -20,6 +137,24 @@ axioms: [] } +definition{ + name: stretchRange, + parameters: [], + result: Nat, + body: 4096, + executable: true, + axioms: [] +} + +definition{ + name: stretchLast, + parameters: [], + result: Nat, + body: (prim subtract (stretchRange) 1 : Nat), + executable: true, + axioms: [] +} + definition{ name: cellMS, parameters: [], @@ -47,6 +182,24 @@ axioms: [] } +definition{ + name: cell3Half, + parameters: [], + result: Nat, + body: (prim quotient (cell3Base) (radix) 0 : Nat), + executable: true, + axioms: [] +} + +definition{ + name: rollMultiplier, + parameters: [], + result: Nat, + body: 789269543, + executable: true, + axioms: [] +} + definition{ name: cellMT, parameters: [], @@ -344,6 +497,15 @@ axioms: [] } +definition{ + name: cell4Half, + parameters: [], + result: Nat, + body: (prim quotient (cell4Base) (radix) 0 : Nat), + executable: true, + axioms: [] +} + definition{ name: cellT, parameters: [], @@ -398,6 +560,24 @@ axioms: [] } +definition{ + name: slotRange, + parameters: [], + result: Nat, + body: 65536, + executable: true, + axioms: [] +} + +definition{ + name: slotHalf, + parameters: [], + result: Nat, + body: (prim quotient (slotRange) (radix) 0 : Nat), + executable: true, + axioms: [] +} + definition{ name: cellPL2, parameters: [], @@ -426,10 +606,10 @@ } definition{ - name: cellW1, + name: stretchHalf, parameters: [], result: Nat, - body: 3, + body: (prim quotient (stretchRange) (radix) 0 : Nat), executable: true, axioms: [] } @@ -461,6 +641,33 @@ axioms: [] } +definition{ + name: slotModelInputs, + parameters: [], + result: Nat, + body: 4, + executable: true, + axioms: [] +} + +definition{ + name: mixerInputs, + parameters: [], + result: Nat, + body: ((earnedInputs) + (slotModelInputs)), + executable: true, + axioms: [] +} + +definition{ + name: cellW1, + parameters: [], + result: Nat, + body: 3, + executable: true, + axioms: [] +} + definition{ name: weightOrigin, parameters: [], @@ -488,6 +695,15 @@ axioms: [] } +definition{ + name: weightRange, + parameters: [], + result: Nat, + body: 16777216, + executable: true, + axioms: [] +} + definition{ name: cellW2, parameters: [], @@ -506,6 +722,78 @@ axioms: [] } +definition{ + name: mixerInputsStretchOrigin, + parameters: [], + result: Nat, + body: (prim multiply (mixerInputs) (stretchHalf) : Nat), + executable: true, + axioms: [] +} + +definition{ + name: mixerInputsStretchOriginWeightOrigin, + parameters: [], + result: Nat, + body: (prim multiply (mixerInputsStretchOrigin) (weightOrigin) : Nat), + executable: true, + axioms: [] +} + +definition{ + name: weightUnit, + parameters: [], + result: Nat, + body: 65536, + executable: true, + axioms: [] +} + +definition{ + name: stretchHalfLast, + parameters: [], + result: Nat, + body: (prim subtract (stretchHalf) 1 : Nat), + executable: true, + axioms: [] +} + +definition{ + name: weightUnitLast, + parameters: [], + result: Nat, + body: (prim subtract (weightUnit) 1 : Nat), + executable: true, + axioms: [] +} + +definition{ + name: squashStep, + parameters: [], + result: Nat, + body: 128, + executable: true, + axioms: [] +} + +definition{ + name: apmIntervals, + parameters: [], + result: Nat, + body: (prim quotient (stretchRange) (squashStep) 0 : Nat), + executable: true, + axioms: [] +} + +definition{ + name: apmPoints, + parameters: [], + result: Nat, + body: ((apmIntervals) + 1), + executable: true, + axioms: [] +} + definition{ name: cellA1, parameters: [], @@ -515,6 +803,42 @@ axioms: [] } +definition{ + name: slotPerStretch, + parameters: [], + result: Nat, + body: (prim quotient (slotRange) (stretchRange) 0 : Nat), + executable: true, + axioms: [] +} + +definition{ + name: apmTop, + parameters: [], + result: Nat, + body: (prim multiply (stretchLast) (slotPerStretch) : Nat), + executable: true, + axioms: [] +} + +definition{ + name: apmScale, + parameters: [], + result: Nat, + body: (prim multiply (squashStep) (slotPerStretch) : Nat), + executable: true, + axioms: [] +} + +definition{ + name: squashHalfStep, + parameters: [], + result: Nat, + body: (prim quotient (squashStep) (radix) 0 : Nat), + executable: true, + axioms: [] +} + definition{ name: cellA2, parameters: [], @@ -542,6 +866,15 @@ axioms: [] } +definition{ + name: slotLast, + parameters: [], + result: Nat, + body: (prim subtract (slotRange) 1 : Nat), + executable: true, + axioms: [] +} + definition{ name: tidMS, parameters: [], @@ -570,10 +903,19 @@ } definition{ - name: weightRange, + name: weightHalf, parameters: [], result: Nat, - body: 16777216, + body: (prim quotient (weightRange) (radix) 0 : Nat), + executable: true, + axioms: [] +} + +definition{ + name: cell2Last, + parameters: [], + result: Nat, + body: (prim subtract (cell2Base) 1 : Nat), executable: true, axioms: [] } @@ -632,6 +974,15 @@ axioms: [] } +definition{ + name: cell1Half, + parameters: [], + result: Nat, + body: (prim quotient (byteBase) (radix) 0 : Nat), + executable: true, + axioms: [] +} + definition{ name: laneBlockInLPL, parameters: [], @@ -687,10 +1038,10 @@ } definition{ - name: byteBase, + name: cell1Last, parameters: [], result: Nat, - body: 256, + body: (prim subtract (byteBase) 1 : Nat), executable: true, axioms: [] } @@ -776,6 +1127,33 @@ axioms: [] } +definition{ + name: mixerInputsBut1, + parameters: [], + result: Nat, + body: (prim subtract (mixerInputs) 1 : Nat), + executable: true, + axioms: [] +} + +definition{ + name: mixerInputsBut1StretchOrigin, + parameters: [], + result: Nat, + body: (prim multiply (mixerInputsBut1) (stretchHalf) : Nat), + executable: true, + axioms: [] +} + +definition{ + name: mixerInputsBut1StretchOriginWeightOrigin, + parameters: [], + result: Nat, + body: (prim multiply (mixerInputsBut1StretchOrigin) (weightOrigin) : Nat), + executable: true, + axioms: [] +} + definition{ name: cellGN, parameters: [], @@ -785,6 +1163,24 @@ axioms: [] } +definition{ + name: cell5Base, + parameters: [], + result: Nat, + body: (prim multiply (cell4Base) (byteBase) : Nat), + executable: true, + axioms: [] +} + +definition{ + name: cell6Base, + parameters: [], + result: Nat, + body: (prim multiply (cell5Base) (byteBase) : Nat), + executable: true, + axioms: [] +} + definition{ name: cellZ8, parameters: [], @@ -1145,15 +1541,6 @@ axioms: [] } -definition{ - name: radix, - parameters: [], - result: Nat, - body: 2, - executable: true, - axioms: [] -} - definition{ name: probabilityRange, parameters: [], @@ -1226,24 +1613,6 @@ axioms: [] } -definition{ - name: slotModelInputs, - parameters: [], - result: Nat, - body: 4, - executable: true, - axioms: [] -} - -definition{ - name: mixerInputs, - parameters: [], - result: Nat, - body: ((earnedInputs) + (slotModelInputs)), - executable: true, - axioms: [] -} - definition{ name: weightTop, parameters: [], @@ -3869,7 +4238,7 @@ result: Nat, body: (match k | Nat.zero => 1 - | Nat.succ m => (prim multiply 2 (pow2 m) : Nat)), + | Nat.succ m => (prim multiply (radix) (pow2 m) : Nat)), executable: true, axioms: [], recursive_argument: k @@ -3893,6 +4262,15 @@ axioms: [Quot.sound, propext] } +definition{ + name: sqtCell, + parameters: [], + result: Nat, + body: 2, + executable: true, + axioms: [] +} + definition{ name: sqt, parameters: [], @@ -3906,16 +4284,79 @@ name: squash, parameters: [d : Nat], result: Nat, - body: (let i : Nat := (prim quotient d 128 0 : Nat); (let w : Nat := (prim remainder d 128 0 : Nat); (prim quotient ((prim multiply (getAt 2 (sqt) (prim multiply 2 i : Nat)) (prim subtract 128 w : Nat) : Nat) + ((prim multiply (getAt 2 (sqt) (prim multiply 2 (i + 1) : Nat)) w : Nat) + 64)) 128 0 : Nat))), + body: (let i : Nat := (prim quotient d (squashStep) 0 : Nat); (let w : Nat := (prim remainder d (squashStep) 0 : Nat); (prim quotient ((prim multiply (getAt (sqtCell) (sqt) (prim multiply (sqtCell) i : Nat)) (prim subtract (squashStep) w : Nat) : Nat) + ((prim multiply (getAt (sqtCell) (sqt) (prim multiply (sqtCell) (i + 1) : Nat)) w : Nat) + (squashHalfStep))) (squashStep) 0 : Nat))), executable: true, axioms: [Quot.sound, propext] } +definition{ + name: hashWord, + parameters: [], + result: Nat, + body: 4294967296, + executable: true, + axioms: [] +} + +definition{ + name: hashMultiplier0, + parameters: [], + result: Nat, + body: 2654435761, + executable: true, + axioms: [] +} + +definition{ + name: hashFold0, + parameters: [], + result: Nat, + body: 32768, + executable: true, + axioms: [] +} + +definition{ + name: hashMultiplier1, + parameters: [], + result: Nat, + body: 739982445, + executable: true, + axioms: [] +} + +definition{ + name: hashFold1, + parameters: [], + result: Nat, + body: 4096, + executable: true, + axioms: [] +} + +definition{ + name: hashMultiplier2, + parameters: [], + result: Nat, + body: 695872825, + executable: true, + axioms: [] +} + +definition{ + name: hashFold2, + parameters: [], + result: Nat, + body: 32768, + executable: true, + axioms: [] +} + definition{ name: hash, parameters: [a : Nat], result: Nat, - body: (let m0 : Nat := (prim remainder (prim multiply 2654435761 a : Nat) 4294967296 0 : Nat); (let a0 : Nat := (prim remainder (m0 + (prim quotient m0 32768 0 : Nat)) 4294967296 0 : Nat); (let m1 : Nat := (prim remainder (prim multiply 739982445 a0 : Nat) 4294967296 0 : Nat); (let a1 : Nat := (prim remainder (m1 + (prim quotient m1 4096 0 : Nat)) 4294967296 0 : Nat); (let m2 : Nat := (prim remainder (prim multiply 695872825 a1 : Nat) 4294967296 0 : Nat); (let a2 : Nat := (prim remainder (m2 + (prim quotient m2 32768 0 : Nat)) 4294967296 0 : Nat); a2)))))), + body: (let m0 : Nat := (prim remainder (prim multiply (hashMultiplier0) a : Nat) (hashWord) 0 : Nat); (let a0 : Nat := (prim remainder (m0 + (prim quotient m0 (hashFold0) 0 : Nat)) (hashWord) 0 : Nat); (let m1 : Nat := (prim remainder (prim multiply (hashMultiplier1) a0 : Nat) (hashWord) 0 : Nat); (let a1 : Nat := (prim remainder (m1 + (prim quotient m1 (hashFold1) 0 : Nat)) (hashWord) 0 : Nat); (let m2 : Nat := (prim remainder (prim multiply (hashMultiplier2) a1 : Nat) (hashWord) 0 : Nat); (let a2 : Nat := (prim remainder (m2 + (prim quotient m2 (hashFold2) 0 : Nat)) (hashWord) 0 : Nat); a2)))))), executable: true, axioms: [] } @@ -4113,7 +4554,7 @@ name: newByteTPart69, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), vmh16 : Nat], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), - body: (let vmh1770 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh16 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract ((getAt (widthHoff) (first s) (atHoff)) + (getAt (widthPos) (first s) (atPos))) 6 : Nat)))) 4294967296 0 : Nat); (let vmh1871 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh1770 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract ((getAt (widthHoff) (first s) (atHoff)) + (getAt (widthPos) (first s) (atPos))) 7 : Nat)))) 4294967296 0 : Nat); (let vmhh72 : Nat := (hash vmh1871); (let vmk73 : Nat := (prim quotient vmhh72 (pow2 (prim subtract 32 (getAt (widthMb) (first s) (atMb)) : Nat)) 0 : Nat); (let s97 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (if ((getAt (widthMlen) (first s) (atMlen)) =? 0) then (let vcand74 : Nat := (getAt (cellMT) (first (second (second (second (second s))))) (prim multiply (cellMT) vmk73 : Nat)); (let s96 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (if ((0 s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let k240 : Nat := (prim multiply (cellPL4) (((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat); (let t241 : Nat := (hash (prim remainder ((getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)) + (prim multiply 16777619 vk : Nat)) 4294967296 0 : Nat)); (let s242 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putPL s (cellPL4) k240 t241); s242))); (newBytePart176Part183Part200Part219Part238Loop239 m (vk + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let k240 : Nat := (prim multiply (cellPL4) (((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat); (let t241 : Nat := (hash (prim remainder ((getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)) + (prim multiply 16777619 vk : Nat)) (cell4Base) 0 : Nat)); (let s242 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putPL s (cellPL4) k240 t241); s242))); (newBytePart176Part183Part200Part219Part238Loop239 m (vk + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4164,7 +4605,7 @@ name: newBytePart176Part183Part200Part219, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), vb1 : Nat, vp3 : Nat, vab : Nat, vab1 : Nat, vab2 : Nat], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), - body: (let k220 : Nat := (prim multiply (cellPL4) (11 + ((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s) (atLane)) : Nat))) : Nat); (let t221 : Nat := (8388608 + (vb1 + (prim multiply 256 vp3 : Nat))); (let s222 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putPL s (cellPL4) k220 t221); (let k223 : Nat := (prim multiply (cellPL4) (12 + ((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s222) (atLane)) : Nat))) : Nat); (let t224 : Nat := (67108864 + ((prim remainder (getAt (widthC4) (first s222) (atC4)) 65536 0 : Nat) + (prim multiply 65536 vp3 : Nat))); (let s225 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putPL s222 (cellPL4) k223 t224); (let k226 : Nat := (prim multiply (cellPL4) (13 + ((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s225) (atLane)) : Nat))) : Nat); (let t227 : Nat := (if ((prim remainder (prim quotient (getAt (widthProf) (first s225) (atProf)) 262144 0 : Nat) 2 0 : Nat) =? 1) then (1426063360 + ((if ((getAt (widthRok) (first s225) (atRok)) =? 1) then ((256 + (getAt (widthRexp) (first s225) (atRexp))) + (prim multiply 512 (if ((getAt (widthRrun) (first s225) (atRrun)) s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let k278 : Nat := ((baseSTR) + (prim multiply (cellSTR) ((getAt (widthPi) (first s) (atPi)) + vj) : Nat)); (let t279 : Nat := 4095; (let s280 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putMem s (cellSTR) k278 t279); s280))); (setupPart261Loop277 m (vj + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let k278 : Nat := ((baseSTR) + (prim multiply (cellSTR) ((getAt (widthPi) (first s) (atPi)) + vj) : Nat)); (let t279 : Nat := (stretchLast); (let s280 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putMem s (cellSTR) k278 t279); s280))); (setupPart261Loop277 m (vj + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4259,7 +4700,7 @@ result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), body: (match fuel | Nat.zero => s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let k283 : Nat := ((baseMS) + (prim multiply (cellMS) vk : Nat)); (let t284 : Nat := (if ((prim remainder vk 2 0 : Nat) =? 1) then 15360000 else 1417216); (let s285 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putMem s (cellMS) k283 t284); (let k286 : Nat := (prim multiply (cellM2S) vk : Nat); (let t287 : Nat := (if ((prim remainder vk 2 0 : Nat) =? 1) then 15360000 else 1417216); (let s288 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putM2S s285 (cellM2S) k286 t287); s288)))))); (setupPart261Loop282 m (vk + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let k283 : Nat := ((baseMS) + (prim multiply (cellMS) vk : Nat)); (let t284 : Nat := (if ((prim remainder vk (radix) 0 : Nat) =? 1) then 15360000 else 1417216); (let s285 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putMem s (cellMS) k283 t284); (let k286 : Nat := (prim multiply (cellM2S) vk : Nat); (let t287 : Nat := (if ((prim remainder vk (radix) 0 : Nat) =? 1) then 15360000 else 1417216); (let s288 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putM2S s285 (cellM2S) k286 t287); s288)))))); (setupPart261Loop282 m (vk + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4271,7 +4712,7 @@ result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), body: (match fuel | Nat.zero => s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let k291 : Nat := (prim multiply (cellRS) vk : Nat); (let t292 : Nat := 8388608; (let s293 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putRS s (cellRS) k291 t292); s293))); (setupPart261Loop290 m (vk + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let k291 : Nat := (prim multiply (cellRS) vk : Nat); (let t292 : Nat := (cell3Half); (let s293 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putRS s (cellRS) k291 t292); s293))); (setupPart261Loop290 m (vk + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4281,7 +4722,7 @@ name: setupPart261Part295Loop296Part303, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), vmh5 : Nat, vj : Nat], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), - body: (let vmh6304 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh5 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 6 : Nat)))) 4294967296 0 : Nat); (let vmh7305 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh6304 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 7 : Nat)))) 4294967296 0 : Nat); (let vmhh306 : Nat := (hash vmh7305); (let vmk307 : Nat := (prim quotient vmhh306 (pow2 (prim subtract 32 (getAt (widthMb) (first s) (atMb)) : Nat)) 0 : Nat); (let k308 : Nat := (prim multiply (cellMT) vmk307 : Nat); (let t309 : Nat := (7 + vj); (let s310 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putMT s (cellMT) k308 t309); s310))))))), + body: (let vmh6304 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmh5 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 6 : Nat)))) (cell4Base) 0 : Nat); (let vmh7305 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmh6304 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 7 : Nat)))) (cell4Base) 0 : Nat); (let vmhh306 : Nat := (hash vmh7305); (let vmk307 : Nat := (prim quotient vmhh306 (pow2 (prim subtract 32 (getAt (widthMb) (first s) (atMb)) : Nat)) 0 : Nat); (let k308 : Nat := (prim multiply (cellMT) vmk307 : Nat); (let t309 : Nat := (7 + vj); (let s310 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putMT s (cellMT) k308 t309); s310))))))), executable: true, axioms: [Quot.sound, propext] } @@ -4292,7 +4733,7 @@ result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), body: (match fuel | Nat.zero => s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let vmh0297 : Nat := 0; (let vmh1298 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh0297 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 1 : Nat)))) 4294967296 0 : Nat); (let vmh2299 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh1298 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 2 : Nat)))) 4294967296 0 : Nat); (let vmh3300 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh2299 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 3 : Nat)))) 4294967296 0 : Nat); (let vmh4301 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh3300 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 4 : Nat)))) 4294967296 0 : Nat); (let vmh5302 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh4301 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 5 : Nat)))) 4294967296 0 : Nat); (setupPart261Part295Loop296Part303 s vmh5302 vj))))))); (setupPart261Part295Loop296 m (vj + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let vmh0297 : Nat := 0; (let vmh1298 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmh0297 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 1 : Nat)))) (cell4Base) 0 : Nat); (let vmh2299 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmh1298 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 2 : Nat)))) (cell4Base) 0 : Nat); (let vmh3300 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmh2299 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 3 : Nat)))) (cell4Base) 0 : Nat); (let vmh4301 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmh3300 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 4 : Nat)))) (cell4Base) 0 : Nat); (let vmh5302 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmh4301 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 5 : Nat)))) (cell4Base) 0 : Nat); (setupPart261Part295Loop296Part303 s vmh5302 vj))))))); (setupPart261Part295Loop296 m (vj + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4313,7 +4754,7 @@ result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), body: (match fuel | Nat.zero => s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let vmq0313 : Nat := 85; (let vmq8314 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmq0313 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 1 : Nat)))) 4294967296 0 : Nat); (let vmq9315 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmq8314 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 2 : Nat)))) 4294967296 0 : Nat); (let vmq10316 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmq9315 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 3 : Nat)))) 4294967296 0 : Nat); (let vmq11317 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmq10316 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 4 : Nat)))) 4294967296 0 : Nat); (let vmqh318 : Nat := (hash vmq11317); (setupPart261Part295TLoop312Part319 s vmqh318 vj))))))); (setupPart261Part295TLoop312 m (vj + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let vmq0313 : Nat := 85; (let vmq8314 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmq0313 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 1 : Nat)))) (cell4Base) 0 : Nat); (let vmq9315 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmq8314 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 2 : Nat)))) (cell4Base) 0 : Nat); (let vmq10316 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmq9315 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 3 : Nat)))) (cell4Base) 0 : Nat); (let vmq11317 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmq10316 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 4 : Nat)))) (cell4Base) 0 : Nat); (let vmqh318 : Nat := (hash vmq11317); (setupPart261Part295TLoop312Part319 s vmqh318 vj))))))); (setupPart261Part295TLoop312 m (vj + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4323,7 +4764,7 @@ name: setupPart261Part295, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS)))))))))))))], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), - body: (let s311 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (setupPart261Part295Loop296 (prim subtract (getAt (widthHoff) (first s) (atHoff)) (if (7 s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let s370 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (if ((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) 2 0 : Nat) =? 1) then (let vbh336 : Nat := (hash (prim remainder ((getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)) + (prim multiply 789269543 vnc : Nat)) 4294967296 0 : Nat)); (let vbm337 : Nat := (prim remainder vbh336 (pow2 (getAt (widthTb) (first s) (atTb))) 0 : Nat); (let vb0338 : Nat := (prim subtract vbm337 (prim remainder vbm337 16 0 : Nat) : Nat); (let vh24339 : Nat := (prim quotient vbh336 16777216 0 : Nat); (let vck340 : Nat := (vh24339 + (prim subtract 1 (prim remainder vh24339 2 0 : Nat) : Nat)); (let valt341 : Nat := (if ((prim remainder (prim quotient vb0338 16 0 : Nat) 2 0 : Nat) =? 1) then (prim subtract vb0338 (if (16 (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let s370 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (if ((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) (radix) 0 : Nat) =? 1) then (let vbh336 : Nat := (hash (prim remainder ((getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)) + (prim multiply (rollMultiplier) vnc : Nat)) (cell4Base) 0 : Nat)); (let vbm337 : Nat := (prim remainder vbh336 (pow2 (getAt (widthTb) (first s) (atTb))) 0 : Nat); (let vb0338 : Nat := (prim subtract vbm337 (prim remainder vbm337 16 0 : Nat) : Nat); (let vh24339 : Nat := (prim quotient vbh336 (cell3Base) 0 : Nat); (let vck340 : Nat := (vh24339 + (prim subtract 1 (prim remainder vh24339 (radix) 0 : Nat) : Nat)); (let valt341 : Nat := (if ((prim remainder (prim quotient vb0338 16 0 : Nat) (radix) 0 : Nat) =? 1) then (prim subtract vb0338 (if (16 s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let s386 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (if ((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) 2 0 : Nat) =? 1) then (let vix375 : Nat := ((getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndHBLInBBL) + (prim multiply (laneBlockInBBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)) + vpart); (let k376 : Nat := (prim multiply (cellPL4) (((laneEndBBLInIXL) + (prim multiply (laneBlockInIXL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat); (let t377 : Nat := vix375; (let s378 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putPL s (cellPL4) k376 t377); (let vsp379 : Nat := (prim remainder (32768 + (prim quotient (getAt (cellT) (first (second (second s378))) (prim multiply (cellT) vix375 : Nat)) 256 0 : Nat)) 65536 0 : Nat); (let k380 : Nat := (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s378) (atLane)) : Nat)) + vk) : Nat); (let t381 : Nat := (getAt (cellSTR) (first (second s378)) ((baseSTR) + (prim multiply (cellSTR) (prim quotient vsp379 16 0 : Nat) : Nat))); (let s382 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putPL s378 (cellPL2) k380 t381); s382)))))))) else (let k383 : Nat := (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat); (let t384 : Nat := 2048; (let s385 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putPL s (cellPL2) k383 t384); s385)))); s386); (predictLoop374 m (vk + 1) next vpart))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let s386 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (if ((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) (radix) 0 : Nat) =? 1) then (let vix375 : Nat := ((getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndHBLInBBL) + (prim multiply (laneBlockInBBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)) + vpart); (let k376 : Nat := (prim multiply (cellPL4) (((laneEndBBLInIXL) + (prim multiply (laneBlockInIXL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat); (let t377 : Nat := vix375; (let s378 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putPL s (cellPL4) k376 t377); (let vsp379 : Nat := (prim remainder ((slotHalf) + (prim quotient (getAt (cellT) (first (second (second s378))) (prim multiply (cellT) vix375 : Nat)) (byteBase) 0 : Nat)) (slotRange) 0 : Nat); (let k380 : Nat := (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s378) (atLane)) : Nat)) + vk) : Nat); (let t381 : Nat := (getAt (cellSTR) (first (second s378)) ((baseSTR) + (prim multiply (cellSTR) (prim quotient vsp379 16 0 : Nat) : Nat))); (let s382 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putPL s378 (cellPL2) k380 t381); s382)))))))) else (let k383 : Nat := (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat); (let t384 : Nat := (stretchHalf); (let s385 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putPL s (cellPL2) k383 t384); s385)))); s386); (predictLoop374 m (vk + 1) next vpart))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4422,7 +4863,7 @@ name: predictPart399Part420Part435Part450Part463Loop467Part477, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), vw1 : Nat, vw2 : Nat, vs3 : Nat, vi : Nat, vso : Nat], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), - body: (let t478 : Nat := ((getAt (widthSw) (first s) (atSw)) + vw1); (let s479 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putGlob s (widthSw) (atSw) t478); (let t480 : Nat := ((getAt (widthSw2) (first s479) (atSw2)) + vw2); (let s481 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putGlob s479 (widthSw2) (atSw2) t480); (let vw3482 : Nat := (prim remainder ((getAt (cellW3) (first (second s481)) ((baseW3) + (prim multiply (cellW3) (vs3 + vi) : Nat))) + (if (vi s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let vso468 : Nat := (getAt (cellPL2) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vi) : Nat)); (let vw1469 : Nat := (prim remainder ((getAt (cellW1) (first (second s)) ((baseW1) + (prim multiply (cellW1) (vs1 + vi) : Nat))) + (if (vi (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let vso468 : Nat := (getAt (cellPL2) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vi) : Nat)); (let vw1469 : Nat := (prim remainder ((getAt (cellW1) (first (second s)) ((baseW1) + (prim multiply (cellW1) (vs1 + vi) : Nat))) + (if (vi s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let s573 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (if ((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) 2 0 : Nat) =? 1) then (let vix560 : Nat := (getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndBBLInIXL) + (prim multiply (laneBlockInIXL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)); (let vsv561 : Nat := (getAt (cellT) (first (second (second s))) (prim multiply (cellT) vix560 : Nat)); (let vcn562 : Nat := (prim remainder vsv561 256 0 : Nat); (let vpp563 : Nat := (prim remainder (32768 + (prim quotient vsv561 256 0 : Nat)) 65536 0 : Nat); (let vrt564 : Nat := (prim quotient 131072 (3 + (prim multiply 2 vcn562 : Nat)) 0 : Nat); (let vnp565 : Nat := (if ((getAt (widthY) (first s) (atY)) =? 1) then (vpp563 + (prim quotient (prim multiply (prim subtract 65535 vpp563 : Nat) vrt564 : Nat) 65536 0 : Nat)) else (prim subtract vpp563 (prim quotient (65535 + (prim multiply vpp563 vrt564 : Nat)) 65536 0 : Nat) : Nat)); (updatePart545Part554Loop559TPart566 s vix560 vnp565 vcn562))))))) else s); s573); (updatePart545Part554Loop559 m (vk + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let s573 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (if ((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) (radix) 0 : Nat) =? 1) then (let vix560 : Nat := (getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndBBLInIXL) + (prim multiply (laneBlockInIXL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)); (let vsv561 : Nat := (getAt (cellT) (first (second (second s))) (prim multiply (cellT) vix560 : Nat)); (let vcn562 : Nat := (prim remainder vsv561 (byteBase) 0 : Nat); (let vpp563 : Nat := (prim remainder ((slotHalf) + (prim quotient vsv561 (byteBase) 0 : Nat)) (slotRange) 0 : Nat); (let vrt564 : Nat := (prim quotient 131072 (3 + (prim multiply 2 vcn562 : Nat)) 0 : Nat); (let vnp565 : Nat := (if ((getAt (widthY) (first s) (atY)) =? 1) then (vpp563 + (prim quotient (prim multiply (prim subtract (slotLast) vpp563 : Nat) vrt564 : Nat) (slotRange) 0 : Nat)) else (prim subtract vpp563 (prim quotient ((slotLast) + (prim multiply vpp563 vrt564 : Nat)) (slotRange) 0 : Nat) : Nat)); (updatePart545Part554Loop559TPart566 s vix560 vnp565 vcn562))))))) else s); s573); (updatePart545Part554Loop559 m (vk + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4572,7 +5013,7 @@ name: updatePart545Part554TPart581, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), vmi : Nat, vnp : Nat, vcn : Nat], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), - body: (let vlk68582 : Nat := vmi; (let vlv69583 : Nat := ((prim multiply 256 vnp : Nat) + (if ((1 + vcn) s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let vso625 : Nat := (getAt (cellPL2) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vi) : Nat)); (let vmag626 : Nat := ((prim subtract vso625 (if (2048 (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let vso625 : Nat := (getAt (cellPL2) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vi) : Nat)); (let vmag626 : Nat := ((prim subtract vso625 (if ((stretchHalf) s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let s730 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (if ((prim quotient (getAt (widthX1) (first s) (atX1)) 16777216 0 : Nat) =? (prim quotient (getAt (widthX2) (first s) (atX2)) 16777216 0 : Nat)) then (let t722 : Nat := (prim remainder (prim multiply 256 (getAt (widthX1) (first s) (atX1)) : Nat) 4294967296 0 : Nat); (let s723 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putGlob s (widthX1) (atX1) t722); (let t724 : Nat := (255 + (prim remainder (prim multiply 256 (getAt (widthX2) (first s723) (atX2)) : Nat) 4294967296 0 : Nat)); (let s725 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putGlob s723 (widthX2) (atX2) t724); (let t726 : Nat := ((prim remainder (prim multiply 256 (getAt (widthX) (first s725) (atX)) : Nat) 4294967296 0 : Nat) + (if ((getAt (widthIp) (first s725) (atIp)) (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let s730 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (if ((prim quotient (getAt (widthX1) (first s) (atX1)) (cell3Base) 0 : Nat) =? (prim quotient (getAt (widthX2) (first s) (atX2)) (cell3Base) 0 : Nat)) then (let t722 : Nat := (prim remainder (prim multiply (byteBase) (getAt (widthX1) (first s) (atX1)) : Nat) (cell4Base) 0 : Nat); (let s723 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putGlob s (widthX1) (atX1) t722); (let t724 : Nat := ((cell1Last) + (prim remainder (prim multiply (byteBase) (getAt (widthX2) (first s723) (atX2)) : Nat) (cell4Base) 0 : Nat)); (let s725 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putGlob s723 (widthX2) (atX2) t724); (let t726 : Nat := ((prim remainder (prim multiply (byteBase) (getAt (widthX) (first s725) (atX)) : Nat) (cell4Base) 0 : Nat) + (if ((getAt (widthIp) (first s725) (atIp)) s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let t762 : Nat := (prim remainder (prim quotient vwb (pow2 (prim subtract 7 vk : Nat)) 0 : Nat) 2 0 : Nat); (let s763 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putGlob s (widthY) (atY) t762); (let s764 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (predict s763 ); (let s765 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (update s764 ); s765)))); (warmStateLoop759Loop761 m (vk + 1) next vwb))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (let t762 : Nat := (prim remainder (prim quotient vwb (pow2 (prim subtract 7 vk : Nat)) 0 : Nat) (radix) 0 : Nat); (let s763 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putGlob s (widthY) (atY) t762); (let s764 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (predict s763 ); (let s765 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (update s764 ); s765)))); (warmStateLoop759Loop761 m (vk + 1) next vwb))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4845,7 +5286,7 @@ name: decodeWarmPart780, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), vpf : Nat, vw : Nat], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))), - body: (let t781 : Nat := (prim remainder (prim quotient vpf (epochBase) 0 : Nat) (epochRange) 0 : Nat); (let s782 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putGlob s (widthCb) (atCb) t781); (let t783 : Nat := 0; (let s784 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmDStS))))))))))))) := (putGlob s782 (widthHoff) (atHoff) t783); (let t785 : Nat := ((((prim multiply 16777216 (if (0 1 - | Nat.succ m => (prim multiply 2 (pow2 m) : Nat)), + | Nat.succ m => (prim multiply (radix) (pow2 m) : Nat)), executable: true, axioms: [], recursive_argument: k @@ -3893,6 +4262,15 @@ axioms: [Quot.sound, propext] } +definition{ + name: sqtCell, + parameters: [], + result: Nat, + body: 2, + executable: true, + axioms: [] +} + definition{ name: sqt, parameters: [], @@ -3906,16 +4284,79 @@ name: squash, parameters: [d : Nat], result: Nat, - body: (let i : Nat := (prim quotient d 128 0 : Nat); (let w : Nat := (prim remainder d 128 0 : Nat); (prim quotient ((prim multiply (getAt 2 (sqt) (prim multiply 2 i : Nat)) (prim subtract 128 w : Nat) : Nat) + ((prim multiply (getAt 2 (sqt) (prim multiply 2 (i + 1) : Nat)) w : Nat) + 64)) 128 0 : Nat))), + body: (let i : Nat := (prim quotient d (squashStep) 0 : Nat); (let w : Nat := (prim remainder d (squashStep) 0 : Nat); (prim quotient ((prim multiply (getAt (sqtCell) (sqt) (prim multiply (sqtCell) i : Nat)) (prim subtract (squashStep) w : Nat) : Nat) + ((prim multiply (getAt (sqtCell) (sqt) (prim multiply (sqtCell) (i + 1) : Nat)) w : Nat) + (squashHalfStep))) (squashStep) 0 : Nat))), executable: true, axioms: [Quot.sound, propext] } +definition{ + name: hashWord, + parameters: [], + result: Nat, + body: 4294967296, + executable: true, + axioms: [] +} + +definition{ + name: hashMultiplier0, + parameters: [], + result: Nat, + body: 2654435761, + executable: true, + axioms: [] +} + +definition{ + name: hashFold0, + parameters: [], + result: Nat, + body: 32768, + executable: true, + axioms: [] +} + +definition{ + name: hashMultiplier1, + parameters: [], + result: Nat, + body: 739982445, + executable: true, + axioms: [] +} + +definition{ + name: hashFold1, + parameters: [], + result: Nat, + body: 4096, + executable: true, + axioms: [] +} + +definition{ + name: hashMultiplier2, + parameters: [], + result: Nat, + body: 695872825, + executable: true, + axioms: [] +} + +definition{ + name: hashFold2, + parameters: [], + result: Nat, + body: 32768, + executable: true, + axioms: [] +} + definition{ name: hash, parameters: [a : Nat], result: Nat, - body: (let m0 : Nat := (prim remainder (prim multiply 2654435761 a : Nat) 4294967296 0 : Nat); (let a0 : Nat := (prim remainder (m0 + (prim quotient m0 32768 0 : Nat)) 4294967296 0 : Nat); (let m1 : Nat := (prim remainder (prim multiply 739982445 a0 : Nat) 4294967296 0 : Nat); (let a1 : Nat := (prim remainder (m1 + (prim quotient m1 4096 0 : Nat)) 4294967296 0 : Nat); (let m2 : Nat := (prim remainder (prim multiply 695872825 a1 : Nat) 4294967296 0 : Nat); (let a2 : Nat := (prim remainder (m2 + (prim quotient m2 32768 0 : Nat)) 4294967296 0 : Nat); a2)))))), + body: (let m0 : Nat := (prim remainder (prim multiply (hashMultiplier0) a : Nat) (hashWord) 0 : Nat); (let a0 : Nat := (prim remainder (m0 + (prim quotient m0 (hashFold0) 0 : Nat)) (hashWord) 0 : Nat); (let m1 : Nat := (prim remainder (prim multiply (hashMultiplier1) a0 : Nat) (hashWord) 0 : Nat); (let a1 : Nat := (prim remainder (m1 + (prim quotient m1 (hashFold1) 0 : Nat)) (hashWord) 0 : Nat); (let m2 : Nat := (prim remainder (prim multiply (hashMultiplier2) a1 : Nat) (hashWord) 0 : Nat); (let a2 : Nat := (prim remainder (m2 + (prim quotient m2 (hashFold2) 0 : Nat)) (hashWord) 0 : Nat); a2)))))), executable: true, axioms: [] } @@ -4122,7 +4563,7 @@ name: newByteTPart69, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), vmh16 : Nat], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), - body: (let vmh1770 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh16 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract ((getAt (widthHoff) (first s) (atHoff)) + (getAt (widthPos) (first s) (atPos))) 6 : Nat)))) 4294967296 0 : Nat); (let vmh1871 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh1770 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract ((getAt (widthHoff) (first s) (atHoff)) + (getAt (widthPos) (first s) (atPos))) 7 : Nat)))) 4294967296 0 : Nat); (let vmhh72 : Nat := (hash vmh1871); (let vmk73 : Nat := (prim quotient vmhh72 (pow2 (prim subtract 32 (getAt (widthMb) (first s) (atMb)) : Nat)) 0 : Nat); (let s97 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if ((getAt (widthMlen) (first s) (atMlen)) =? 0) then (let vcand74 : Nat := (getAt (cellMT) (first (second (second (second (second s))))) (prim multiply (cellMT) vmk73 : Nat)); (let s96 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if ((0 s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let k240 : Nat := (prim multiply (cellPL4) (((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat); (let t241 : Nat := (hash (prim remainder ((getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)) + (prim multiply 16777619 vk : Nat)) 4294967296 0 : Nat)); (let s242 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putPL s (cellPL4) k240 t241); s242))); (newBytePart176Part183Part200Part219Part238Loop239 m (vk + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let k240 : Nat := (prim multiply (cellPL4) (((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat); (let t241 : Nat := (hash (prim remainder ((getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)) + (prim multiply 16777619 vk : Nat)) (cell4Base) 0 : Nat)); (let s242 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putPL s (cellPL4) k240 t241); s242))); (newBytePart176Part183Part200Part219Part238Loop239 m (vk + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4173,7 +4614,7 @@ name: newBytePart176Part183Part200Part219, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), vb1 : Nat, vp3 : Nat, vab : Nat, vab1 : Nat, vab2 : Nat], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), - body: (let k220 : Nat := (prim multiply (cellPL4) (11 + ((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s) (atLane)) : Nat))) : Nat); (let t221 : Nat := (8388608 + (vb1 + (prim multiply 256 vp3 : Nat))); (let s222 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putPL s (cellPL4) k220 t221); (let k223 : Nat := (prim multiply (cellPL4) (12 + ((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s222) (atLane)) : Nat))) : Nat); (let t224 : Nat := (67108864 + ((prim remainder (getAt (widthC4) (first s222) (atC4)) 65536 0 : Nat) + (prim multiply 65536 vp3 : Nat))); (let s225 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putPL s222 (cellPL4) k223 t224); (let k226 : Nat := (prim multiply (cellPL4) (13 + ((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s225) (atLane)) : Nat))) : Nat); (let t227 : Nat := (if ((prim remainder (prim quotient (getAt (widthProf) (first s225) (atProf)) 262144 0 : Nat) 2 0 : Nat) =? 1) then (1426063360 + ((if ((getAt (widthRok) (first s225) (atRok)) =? 1) then ((256 + (getAt (widthRexp) (first s225) (atRexp))) + (prim multiply 512 (if ((getAt (widthRrun) (first s225) (atRrun)) s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let k278 : Nat := ((baseSTR) + (prim multiply (cellSTR) ((getAt (widthPi) (first s) (atPi)) + vj) : Nat)); (let t279 : Nat := 4095; (let s280 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putMem s (cellSTR) k278 t279); s280))); (setupPart261Loop277 m (vj + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let k278 : Nat := ((baseSTR) + (prim multiply (cellSTR) ((getAt (widthPi) (first s) (atPi)) + vj) : Nat)); (let t279 : Nat := (stretchLast); (let s280 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putMem s (cellSTR) k278 t279); s280))); (setupPart261Loop277 m (vj + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4268,7 +4709,7 @@ result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), body: (match fuel | Nat.zero => s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let k283 : Nat := ((baseMS) + (prim multiply (cellMS) vk : Nat)); (let t284 : Nat := (if ((prim remainder vk 2 0 : Nat) =? 1) then 15360000 else 1417216); (let s285 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putMem s (cellMS) k283 t284); (let k286 : Nat := (prim multiply (cellM2S) vk : Nat); (let t287 : Nat := (if ((prim remainder vk 2 0 : Nat) =? 1) then 15360000 else 1417216); (let s288 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putM2S s285 (cellM2S) k286 t287); s288)))))); (setupPart261Loop282 m (vk + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let k283 : Nat := ((baseMS) + (prim multiply (cellMS) vk : Nat)); (let t284 : Nat := (if ((prim remainder vk (radix) 0 : Nat) =? 1) then 15360000 else 1417216); (let s285 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putMem s (cellMS) k283 t284); (let k286 : Nat := (prim multiply (cellM2S) vk : Nat); (let t287 : Nat := (if ((prim remainder vk (radix) 0 : Nat) =? 1) then 15360000 else 1417216); (let s288 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putM2S s285 (cellM2S) k286 t287); s288)))))); (setupPart261Loop282 m (vk + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4280,7 +4721,7 @@ result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), body: (match fuel | Nat.zero => s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let k291 : Nat := (prim multiply (cellRS) vk : Nat); (let t292 : Nat := 8388608; (let s293 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putRS s (cellRS) k291 t292); s293))); (setupPart261Loop290 m (vk + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let k291 : Nat := (prim multiply (cellRS) vk : Nat); (let t292 : Nat := (cell3Half); (let s293 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putRS s (cellRS) k291 t292); s293))); (setupPart261Loop290 m (vk + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4290,7 +4731,7 @@ name: setupPart261Part295Loop296Part303, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), vmh5 : Nat, vj : Nat], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), - body: (let vmh6304 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh5 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 6 : Nat)))) 4294967296 0 : Nat); (let vmh7305 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh6304 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 7 : Nat)))) 4294967296 0 : Nat); (let vmhh306 : Nat := (hash vmh7305); (let vmk307 : Nat := (prim quotient vmhh306 (pow2 (prim subtract 32 (getAt (widthMb) (first s) (atMb)) : Nat)) 0 : Nat); (let k308 : Nat := (prim multiply (cellMT) vmk307 : Nat); (let t309 : Nat := (7 + vj); (let s310 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putMT s (cellMT) k308 t309); s310))))))), + body: (let vmh6304 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmh5 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 6 : Nat)))) (cell4Base) 0 : Nat); (let vmh7305 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmh6304 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 7 : Nat)))) (cell4Base) 0 : Nat); (let vmhh306 : Nat := (hash vmh7305); (let vmk307 : Nat := (prim quotient vmhh306 (pow2 (prim subtract 32 (getAt (widthMb) (first s) (atMb)) : Nat)) 0 : Nat); (let k308 : Nat := (prim multiply (cellMT) vmk307 : Nat); (let t309 : Nat := (7 + vj); (let s310 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putMT s (cellMT) k308 t309); s310))))))), executable: true, axioms: [Quot.sound, propext] } @@ -4301,7 +4742,7 @@ result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), body: (match fuel | Nat.zero => s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let vmh0297 : Nat := 0; (let vmh1298 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh0297 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 1 : Nat)))) 4294967296 0 : Nat); (let vmh2299 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh1298 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 2 : Nat)))) 4294967296 0 : Nat); (let vmh3300 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh2299 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 3 : Nat)))) 4294967296 0 : Nat); (let vmh4301 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh3300 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 4 : Nat)))) 4294967296 0 : Nat); (let vmh5302 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmh4301 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 5 : Nat)))) 4294967296 0 : Nat); (setupPart261Part295Loop296Part303 s vmh5302 vj))))))); (setupPart261Part295Loop296 m (vj + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let vmh0297 : Nat := 0; (let vmh1298 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmh0297 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 1 : Nat)))) (cell4Base) 0 : Nat); (let vmh2299 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmh1298 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 2 : Nat)))) (cell4Base) 0 : Nat); (let vmh3300 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmh2299 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 3 : Nat)))) (cell4Base) 0 : Nat); (let vmh4301 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmh3300 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 4 : Nat)))) (cell4Base) 0 : Nat); (let vmh5302 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmh4301 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (7 + vj) 5 : Nat)))) (cell4Base) 0 : Nat); (setupPart261Part295Loop296Part303 s vmh5302 vj))))))); (setupPart261Part295Loop296 m (vj + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4322,7 +4763,7 @@ result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), body: (match fuel | Nat.zero => s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let vmq0313 : Nat := 85; (let vmq8314 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmq0313 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 1 : Nat)))) 4294967296 0 : Nat); (let vmq9315 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmq8314 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 2 : Nat)))) 4294967296 0 : Nat); (let vmq10316 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmq9315 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 3 : Nat)))) 4294967296 0 : Nat); (let vmq11317 : Nat := (prim remainder (1 + ((prim multiply 789269543 vmq10316 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 4 : Nat)))) 4294967296 0 : Nat); (let vmqh318 : Nat := (hash vmq11317); (setupPart261Part295TLoop312Part319 s vmqh318 vj))))))); (setupPart261Part295TLoop312 m (vj + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let vmq0313 : Nat := 85; (let vmq8314 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmq0313 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 1 : Nat)))) (cell4Base) 0 : Nat); (let vmq9315 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmq8314 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 2 : Nat)))) (cell4Base) 0 : Nat); (let vmq10316 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmq9315 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 3 : Nat)))) (cell4Base) 0 : Nat); (let vmq11317 : Nat := (prim remainder (1 + ((prim multiply (rollMultiplier) vmq10316 : Nat) + (getAt 1 (first (second (second (second s)))) (prim subtract (4 + vj) 4 : Nat)))) (cell4Base) 0 : Nat); (let vmqh318 : Nat := (hash vmq11317); (setupPart261Part295TLoop312Part319 s vmqh318 vj))))))); (setupPart261Part295TLoop312 m (vj + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4332,7 +4773,7 @@ name: setupPart261Part295, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS))))))))))))))], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), - body: (let s311 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (setupPart261Part295Loop296 (prim subtract (getAt (widthHoff) (first s) (atHoff)) (if (7 s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let s363 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if ((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) 2 0 : Nat) =? 1) then (let vbh329 : Nat := (hash (prim remainder ((getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)) + (prim multiply 789269543 vnc : Nat)) 4294967296 0 : Nat)); (let vbm330 : Nat := (prim remainder vbh329 (pow2 (getAt (widthTb) (first s) (atTb))) 0 : Nat); (let vb0331 : Nat := (prim subtract vbm330 (prim remainder vbm330 16 0 : Nat) : Nat); (let vh24332 : Nat := (prim quotient vbh329 16777216 0 : Nat); (let vck333 : Nat := (vh24332 + (prim subtract 1 (prim remainder vh24332 2 0 : Nat) : Nat)); (let valt334 : Nat := (if ((prim remainder (prim quotient vb0331 16 0 : Nat) 2 0 : Nat) =? 1) then (prim subtract vb0331 (if (16 (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let s363 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if ((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) (radix) 0 : Nat) =? 1) then (let vbh329 : Nat := (hash (prim remainder ((getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndLGInHBL) + (prim multiply (laneBlockInHBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)) + (prim multiply (rollMultiplier) vnc : Nat)) (cell4Base) 0 : Nat)); (let vbm330 : Nat := (prim remainder vbh329 (pow2 (getAt (widthTb) (first s) (atTb))) 0 : Nat); (let vb0331 : Nat := (prim subtract vbm330 (prim remainder vbm330 16 0 : Nat) : Nat); (let vh24332 : Nat := (prim quotient vbh329 (cell3Base) 0 : Nat); (let vck333 : Nat := (vh24332 + (prim subtract 1 (prim remainder vh24332 (radix) 0 : Nat) : Nat)); (let valt334 : Nat := (if ((prim remainder (prim quotient vb0331 16 0 : Nat) (radix) 0 : Nat) =? 1) then (prim subtract vb0331 (if (16 s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let s379 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if ((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) 2 0 : Nat) =? 1) then (let vix368 : Nat := ((getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndHBLInBBL) + (prim multiply (laneBlockInBBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)) + vpart); (let k369 : Nat := (prim multiply (cellPL4) (((laneEndBBLInIXL) + (prim multiply (laneBlockInIXL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat); (let t370 : Nat := vix368; (let s371 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putPL s (cellPL4) k369 t370); (let vsp372 : Nat := (prim remainder (32768 + (prim quotient (getAt (cellT) (first (second (second s371))) (prim multiply (cellT) vix368 : Nat)) 256 0 : Nat)) 65536 0 : Nat); (let k373 : Nat := (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s371) (atLane)) : Nat)) + vk) : Nat); (let t374 : Nat := (getAt (cellSTR) (first (second s371)) ((baseSTR) + (prim multiply (cellSTR) (prim quotient vsp372 16 0 : Nat) : Nat))); (let s375 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putPL s371 (cellPL2) k373 t374); s375)))))))) else (let k376 : Nat := (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat); (let t377 : Nat := 2048; (let s378 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putPL s (cellPL2) k376 t377); s378)))); s379); (predictLoop367 m (vk + 1) next vpart))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let s379 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if ((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) (radix) 0 : Nat) =? 1) then (let vix368 : Nat := ((getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndHBLInBBL) + (prim multiply (laneBlockInBBL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)) + vpart); (let k369 : Nat := (prim multiply (cellPL4) (((laneEndBBLInIXL) + (prim multiply (laneBlockInIXL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat); (let t370 : Nat := vix368; (let s371 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putPL s (cellPL4) k369 t370); (let vsp372 : Nat := (prim remainder ((slotHalf) + (prim quotient (getAt (cellT) (first (second (second s371))) (prim multiply (cellT) vix368 : Nat)) (byteBase) 0 : Nat)) (slotRange) 0 : Nat); (let k373 : Nat := (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s371) (atLane)) : Nat)) + vk) : Nat); (let t374 : Nat := (getAt (cellSTR) (first (second s371)) ((baseSTR) + (prim multiply (cellSTR) (prim quotient vsp372 16 0 : Nat) : Nat))); (let s375 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putPL s371 (cellPL2) k373 t374); s375)))))))) else (let k376 : Nat := (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat); (let t377 : Nat := (stretchHalf); (let s378 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putPL s (cellPL2) k376 t377); s378)))); s379); (predictLoop367 m (vk + 1) next vpart))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4413,7 +4854,7 @@ name: predictPart392Part413Part428Part443Part456Loop460Part470, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), vw1 : Nat, vw2 : Nat, vs3 : Nat, vi : Nat, vso : Nat], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), - body: (let t471 : Nat := ((getAt (widthSw) (first s) (atSw)) + vw1); (let s472 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s (widthSw) (atSw) t471); (let t473 : Nat := ((getAt (widthSw2) (first s472) (atSw2)) + vw2); (let s474 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s472 (widthSw2) (atSw2) t473); (let vw3475 : Nat := (prim remainder ((getAt (cellW3) (first (second s474)) ((baseW3) + (prim multiply (cellW3) (vs3 + vi) : Nat))) + (if (vi s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let vso461 : Nat := (getAt (cellPL2) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vi) : Nat)); (let vw1462 : Nat := (prim remainder ((getAt (cellW1) (first (second s)) ((baseW1) + (prim multiply (cellW1) (vs1 + vi) : Nat))) + (if (vi (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let vso461 : Nat := (getAt (cellPL2) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vi) : Nat)); (let vw1462 : Nat := (prim remainder ((getAt (cellW1) (first (second s)) ((baseW1) + (prim multiply (cellW1) (vs1 + vi) : Nat))) + (if (vi s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let s574 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if ((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) 2 0 : Nat) =? 1) then (let vix561 : Nat := (getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndBBLInIXL) + (prim multiply (laneBlockInIXL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)); (let vsv562 : Nat := (getAt (cellT) (first (second (second s))) (prim multiply (cellT) vix561 : Nat)); (let vcn563 : Nat := (prim remainder vsv562 256 0 : Nat); (let vpp564 : Nat := (prim remainder (32768 + (prim quotient vsv562 256 0 : Nat)) 65536 0 : Nat); (let vrt565 : Nat := (prim quotient 131072 (3 + (prim multiply 2 vcn563 : Nat)) 0 : Nat); (let vnp566 : Nat := (if ((getAt (widthY) (first s) (atY)) =? 1) then (vpp564 + (prim quotient (prim multiply (prim subtract 65535 vpp564 : Nat) vrt565 : Nat) 65536 0 : Nat)) else (prim subtract vpp564 (prim quotient (65535 + (prim multiply vpp564 vrt565 : Nat)) 65536 0 : Nat) : Nat)); (updatePart546Part555Loop560TPart567 s vix561 vnp566 vcn563))))))) else s); s574); (updatePart546Part555Loop560 m (vk + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let s574 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if ((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) (radix) 0 : Nat) =? 1) then (let vix561 : Nat := (getAt (cellPL4) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL4) (((laneEndBBLInIXL) + (prim multiply (laneBlockInIXL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)); (let vsv562 : Nat := (getAt (cellT) (first (second (second s))) (prim multiply (cellT) vix561 : Nat)); (let vcn563 : Nat := (prim remainder vsv562 (byteBase) 0 : Nat); (let vpp564 : Nat := (prim remainder ((slotHalf) + (prim quotient vsv562 (byteBase) 0 : Nat)) (slotRange) 0 : Nat); (let vrt565 : Nat := (prim quotient 131072 (3 + (prim multiply 2 vcn563 : Nat)) 0 : Nat); (let vnp566 : Nat := (if ((getAt (widthY) (first s) (atY)) =? 1) then (vpp564 + (prim quotient (prim multiply (prim subtract (slotLast) vpp564 : Nat) vrt565 : Nat) (slotRange) 0 : Nat)) else (prim subtract vpp564 (prim quotient ((slotLast) + (prim multiply vpp564 vrt565 : Nat)) (slotRange) 0 : Nat) : Nat)); (updatePart546Part555Loop560TPart567 s vix561 vnp566 vcn563))))))) else s); s574); (updatePart546Part555Loop560 m (vk + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4572,7 +5013,7 @@ name: updatePart546Part555TPart582, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), vmi : Nat, vnp : Nat, vcn : Nat], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), - body: (let vlk68583 : Nat := vmi; (let vlv69584 : Nat := ((prim multiply 256 vnp : Nat) + (if ((1 + vcn) s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let vso626 : Nat := (getAt (cellPL2) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vi) : Nat)); (let vmag627 : Nat := ((prim subtract vso626 (if (2048 (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let vso626 : Nat := (getAt (cellPL2) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vi) : Nat)); (let vmag627 : Nat := ((prim subtract vso626 (if ((stretchHalf) s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let s737 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if ((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) 2 0 : Nat) =? 1) then (let vgso724 : Nat := (getAt (cellPL2) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)); (let vgw1725 : Nat := (prim remainder ((getAt (cellW1) (first (second s)) ((baseW1) + (prim multiply (cellW1) (vgs1 + vk) : Nat))) + (if (vk (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let s737 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if ((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) (radix) 0 : Nat) =? 1) then (let vgso724 : Nat := (getAt (cellPL2) (first (second (second (second (second (second (second (second (second (second s)))))))))) (prim multiply (cellPL2) (((laneEndLDLInSTL) + (prim multiply (laneBlockInSTL) (getAt (widthLane) (first s) (atLane)) : Nat)) + vk) : Nat)); (let vgw1725 : Nat := (prim remainder ((getAt (cellW1) (first (second s)) ((baseW1) + (prim multiply (cellW1) (vgs1 + vk) : Nat))) + (if (vk s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let s752 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if ((prim quotient (getAt (widthX1) (first s) (atX1)) 16777216 0 : Nat) =? (prim quotient (getAt (widthX2) (first s) (atX2)) 16777216 0 : Nat)) then (let s747 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (emit s (prim quotient (getAt (widthX2) (first s) (atX2)) 16777216 0 : Nat)); (let t748 : Nat := (prim remainder (prim multiply 256 (getAt (widthX1) (first s747) (atX1)) : Nat) 4294967296 0 : Nat); (let s749 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s747 (widthX1) (atX1) t748); (let t750 : Nat := (255 + (prim remainder (prim multiply 256 (getAt (widthX2) (first s749) (atX2)) : Nat) 4294967296 0 : Nat)); (let s751 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s749 (widthX2) (atX2) t750); s751))))) else s); s752); (encodeBitLoop746 m (vk + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let s752 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if ((prim quotient (getAt (widthX1) (first s) (atX1)) (cell3Base) 0 : Nat) =? (prim quotient (getAt (widthX2) (first s) (atX2)) (cell3Base) 0 : Nat)) then (let s747 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (emit s (prim quotient (getAt (widthX2) (first s) (atX2)) (cell3Base) 0 : Nat)); (let t748 : Nat := (prim remainder (prim multiply (byteBase) (getAt (widthX1) (first s747) (atX1)) : Nat) (cell4Base) 0 : Nat); (let s749 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s747 (widthX1) (atX1) t748); (let t750 : Nat := ((cell1Last) + (prim remainder (prim multiply (byteBase) (getAt (widthX2) (first s749) (atX2)) : Nat) (cell4Base) 0 : Nat)); (let s751 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s749 (widthX2) (atX2) t750); s751))))) else s); s752); (encodeBitLoop746 m (vk + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4743,7 +5184,7 @@ name: encodeBit, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS))))))))))))))], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), - body: (let s713 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (predict s ); (let s739 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if ((getAt (widthLearn) (first s713) (atLearn)) =? 1) then (let vgs1714 : Nat := (prim multiply 24 ((getAt (widthC0) (first s713) (atC0)) + (prim multiply 256 (getAt (widthMsel) (first s713) (atMsel)) : Nat)) : Nat); (let vgs2715 : Nat := (prim multiply 24 ((prim multiply 8 (prim remainder (getAt (widthC4) (first s713) (atC4)) 256 0 : Nat) : Nat) + (getAt (widthBit) (first s713) (atBit))) : Nat); (let vgs3716 : Nat := (prim multiply 24 ((prim multiply 8 (prim remainder (prim quotient (getAt (widthC4) (first s713) (atC4)) 256 0 : Nat) 256 0 : Nat) : Nat) + (getAt (widthBit) (first s713) (atBit))) : Nat); (let vgd1717 : Nat := (if (((prim multiply 4194304 (getAt (widthSso) (first s713) (atSso)) : Nat) + (prim multiply 2048 (getAt (widthSw) (first s713) (atSw)) : Nat)) <=? (206158430208 + (getAt (widthAcc) (first s713) (atAcc)))) then (2048 + (if ((prim quotient (prim subtract (206158430208 + (getAt (widthAcc) (first s713) (atAcc))) (if (((prim multiply 4194304 (getAt (widthSso) (first s713) (atSso)) : Nat) + (prim multiply 2048 (getAt (widthSw) (first s713) (atSw)) : Nat)) s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let t757 : Nat := (prim remainder (prim quotient vbyte (pow2 (prim subtract 7 vk : Nat)) 0 : Nat) 2 0 : Nat); (let s758 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s (widthY) (atY) t757); (let s759 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (encodeBit s758 ); s759))); (encodeByteLoop756 m (vk + 1) next vbyte))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let t757 : Nat := (prim remainder (prim quotient vbyte (pow2 (prim subtract 7 vk : Nat)) 0 : Nat) (radix) 0 : Nat); (let s758 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s (widthY) (atY) t757); (let s759 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (encodeBit s758 ); s759))); (encodeByteLoop756 m (vk + 1) next vbyte))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4794,7 +5235,7 @@ name: encode, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), vsize : Nat, vlimit : Nat], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), - body: (let t761 : Nat := vsize; (let s762 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s (widthN) (atN) t761); (let t763 : Nat := vlimit; (let s764 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s762 (widthCap) (atCap) t763); (let s765 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (setup s764 ); (let s768 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (encodeLoop766 (getAt (widthN) (first s765) (atN)) 0 s765 ); (let s769 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (emit s768 (prim quotient (getAt (widthX1) (first s768) (atX1)) 16777216 0 : Nat)); s769))))))), + body: (let t761 : Nat := vsize; (let s762 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s (widthN) (atN) t761); (let t763 : Nat := vlimit; (let s764 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s762 (widthCap) (atCap) t763); (let s765 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (setup s764 ); (let s768 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (encodeLoop766 (getAt (widthN) (first s765) (atN)) 0 s765 ); (let s769 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (emit s768 (prim quotient (getAt (widthX1) (first s768) (atX1)) (cell3Base) 0 : Nat)); s769))))))), executable: true, axioms: [Quot.sound, propext] } @@ -4844,7 +5285,7 @@ result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), body: (match fuel | Nat.zero => s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let t806 : Nat := (prim quotient (prim multiply (getAt (widthCm) (first s) (atCm)) (getAt (widthCm) (first s) (atCm)) : Nat) 32768 0 : Nat); (let s807 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s (widthCm) (atCm) t806); (let s812 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if (65536 <=? (getAt (widthCm) (first s807) (atCm))) then (let t808 : Nat := (prim quotient (getAt (widthCm) (first s807) (atCm)) 2 0 : Nat); (let s809 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s807 (widthCm) (atCm) t808); (let t810 : Nat := ((getAt (widthCfr) (first s809) (atCfr)) + (pow2 (prim subtract 7 vj : Nat))); (let s811 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s809 (widthCfr) (atCfr) t810); s811)))) else s807); s812))); (encodeLearnLoop791Loop805 m (vj + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let t806 : Nat := (prim quotient (prim multiply (getAt (widthCm) (first s) (atCm)) (getAt (widthCm) (first s) (atCm)) : Nat) 32768 0 : Nat); (let s807 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s (widthCm) (atCm) t806); (let s812 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if ((cell2Base) <=? (getAt (widthCm) (first s807) (atCm))) then (let t808 : Nat := (prim quotient (getAt (widthCm) (first s807) (atCm)) (radix) 0 : Nat); (let s809 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s807 (widthCm) (atCm) t808); (let t810 : Nat := ((getAt (widthCfr) (first s809) (atCfr)) + (pow2 (prim subtract 7 vj : Nat))); (let s811 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s809 (widthCfr) (atCfr) t810); s811)))) else s807); s812))); (encodeLearnLoop791Loop805 m (vj + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4856,7 +5297,7 @@ result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), body: (match fuel | Nat.zero => s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let t792 : Nat := (1 + vq); (let s793 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s (widthCm) (atCm) t792); (let t794 : Nat := 0; (let s795 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s793 (widthCe) (atCe) t794); (let t796 : Nat := 0; (let s797 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s795 (widthCfr) (atCfr) t796); (let s804 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (encodeLearnLoop791Loop798 (16 + (prim multiply 0 (getAt 1 (first s797) 0) : Nat)) 0 s797 ); (let s813 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (encodeLearnLoop791Loop805 (8 + (prim multiply 0 (getAt 1 (first s804) 0) : Nat)) 0 s804 ); (let k814 : Nat := ((baseCOST) + (prim multiply (cellCOST) (1 + vq) : Nat)); (let t815 : Nat := (prim subtract 3072 ((prim multiply 256 (prim subtract 15 (getAt (widthCe) (first s813) (atCe)) : Nat) : Nat) + (getAt (widthCfr) (first s813) (atCfr))) : Nat); (let s816 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putMem s813 (cellCOST) k814 t815); s816))))))))))); (encodeLearnLoop791 m (vq + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let t792 : Nat := (1 + vq); (let s793 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s (widthCm) (atCm) t792); (let t794 : Nat := 0; (let s795 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s793 (widthCe) (atCe) t794); (let t796 : Nat := 0; (let s797 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s795 (widthCfr) (atCfr) t796); (let s804 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (encodeLearnLoop791Loop798 (16 + (prim multiply 0 (getAt 1 (first s797) 0) : Nat)) 0 s797 ); (let s813 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (encodeLearnLoop791Loop805 (8 + (prim multiply 0 (getAt 1 (first s804) 0) : Nat)) 0 s804 ); (let k814 : Nat := ((baseCOST) + (prim multiply (cellCOST) (1 + vq) : Nat)); (let t815 : Nat := (prim subtract 3072 ((prim multiply (byteBase) (prim subtract 15 (getAt (widthCe) (first s813) (atCe)) : Nat) : Nat) + (getAt (widthCfr) (first s813) (atCfr))) : Nat); (let s816 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putMem s813 (cellCOST) k814 t815); s816))))))))))); (encodeLearnLoop791 m (vq + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4868,7 +5309,7 @@ result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), body: (match fuel | Nat.zero => s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let s824 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if (((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) 2 0 : Nat) =? 1) && ((prim remainder (70368744177664 + (getAt (cellGN) (first (second s)) ((baseGN) + (prim multiply (cellGN) vk : Nat)))) 281474976710656 0 : Nat) <=? 70368744177664)) then (let t822 : Nat := (prim subtract (getAt (widthLmask) (first s) (atLmask)) (pow2 vk) : Nat); (let s823 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s (widthLmask) (atLmask) t822); s823)) else s); s824); (encodeLearnLoop821 m (vk + 1) next ))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let s824 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (if (((prim remainder (prim quotient (getAt (widthProf) (first s) (atProf)) (pow2 vk) 0 : Nat) (radix) 0 : Nat) =? 1) && ((prim remainder (70368744177664 + (getAt (cellGN) (first (second s)) ((baseGN) + (prim multiply (cellGN) vk : Nat)))) (cell6Base) 0 : Nat) <=? 70368744177664)) then (let t822 : Nat := (prim subtract (getAt (widthLmask) (first s) (atLmask)) (pow2 vk) : Nat); (let s823 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s (widthLmask) (atLmask) t822); s823)) else s); s824); (encodeLearnLoop821 m (vk + 1) next ))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4889,7 +5330,7 @@ result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), body: (match fuel | Nat.zero => s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let t829 : Nat := (prim remainder (prim quotient vwb (pow2 (prim subtract 7 vk : Nat)) 0 : Nat) 2 0 : Nat); (let s830 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s (widthY) (atY) t829); (let s831 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (predict s830 ); (let s832 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (update s831 ); s832)))); (warmStateLoop826Loop828 m (vk + 1) next vwb))), + | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (let t829 : Nat := (prim remainder (prim quotient vwb (pow2 (prim subtract 7 vk : Nat)) 0 : Nat) (radix) 0 : Nat); (let s830 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (putGlob s (widthY) (atY) t829); (let s831 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (predict s830 ); (let s832 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (update s831 ); s832)))); (warmStateLoop826Loop828 m (vk + 1) next vwb))), executable: true, axioms: [Quot.sound, propext], recursive_argument: fuel @@ -4932,7 +5373,7 @@ name: encodeWarmPart847Part859, parameters: [s : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), vw : Nat], result: (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))), - body: (let s860 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (warmState s vw); (let s863 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (encodeWarmPart847Part859Loop861 (getAt (widthN) (first s860) (atN)) 0 s860 ); (let s864 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (emit s863 (prim quotient (getAt (widthX1) (first s863) (atX1)) 16777216 0 : Nat)); s864))), + body: (let s860 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (warmState s vw); (let s863 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (encodeWarmPart847Part859Loop861 (getAt (widthN) (first s860) (atN)) 0 s860 ); (let s864 : (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * (Bytes * NcmEStS)))))))))))))) := (emit s863 (prim quotient (getAt (widthX1) (first s863) (atX1)) (cell3Base) 0 : Nat)); s864))), executable: true, axioms: [Quot.sound, propext] } @@ -5817,7 +6258,7 @@ name: tbOf, parameters: [n : Nat, profile : Nat], result: Nat, - body: (let t : Nat := (prim remainder (prim quotient profile 1048576 0 : Nat) 64 0 : Nat); (if (0 1 - | Nat.succ m => (prim multiply 2 (pow2 m) : Nat)), + body: 8589934592, executable: true, - axioms: [], - recursive_argument: k + axioms: [] } definition{ - name: getAt, - parameters: [w : Nat, t : Bytes, at : Nat], + name: widthN, + parameters: [], result: Nat, - body: (Uorc.Codec.Table::getLoop w t at 0), + body: 4, executable: true, - axioms: [Quot.sound, propext] + axioms: [] } definition{ - name: putAt, - parameters: [w : Nat, t : Bytes, at : Nat, v : Nat], - result: Bytes, - body: (Uorc.Codec.Table::setLoop w t (prim subtract (at + w) 1 : Nat) v), + name: atN, + parameters: [], + result: Nat, + body: 0, executable: true, - axioms: [Quot.sound, propext] + axioms: [] } definition{ - name: sqt, + name: widthDir, parameters: [], - result: Bytes, - body: 0x0001000200030006000a0010001b002d0049007800c2013601e802eb044d060a07ff09f50bb20d140e170ec90f3d0f870fb60fd20fe40fef0ff50ff90ffc0ffd0ffe, + result: Nat, + body: 1, executable: true, axioms: [] } definition{ - name: squash, - parameters: [d : Nat], + name: atDir, + parameters: [], result: Nat, - body: (let i : Nat := (prim quotient d 128 0 : Nat); (let w : Nat := (prim remainder d 128 0 : Nat); (prim quotient ((prim multiply (getAt 2 (sqt) (prim multiply 2 i : Nat)) (prim subtract 128 w : Nat) : Nat) + ((prim multiply (getAt 2 (sqt) (prim multiply 2 (i + 1) : Nat)) w : Nat) + 64)) 128 0 : Nat))), + body: ((atN) + (widthN)), executable: true, - axioms: [Quot.sound, propext] + axioms: [] } definition{ - name: hash, - parameters: [a : Nat], + name: widthSkip, + parameters: [], result: Nat, - body: (let m0 : Nat := (prim remainder (prim multiply 2654435761 a : Nat) 4294967296 0 : Nat); (let a0 : Nat := (prim remainder (m0 + (prim quotient m0 32768 0 : Nat)) 4294967296 0 : Nat); (let m1 : Nat := (prim remainder (prim multiply 739982445 a0 : Nat) 4294967296 0 : Nat); (let a1 : Nat := (prim remainder (m1 + (prim quotient m1 4096 0 : Nat)) 4294967296 0 : Nat); (let m2 : Nat := (prim remainder (prim multiply 695872825 a1 : Nat) 4294967296 0 : Nat); (let a2 : Nat := (prim remainder (m2 + (prim quotient m2 32768 0 : Nat)) 4294967296 0 : Nat); a2)))))), + body: 1, executable: true, axioms: [] } +definition{ + name: atSkip, + parameters: [], + result: Nat, + body: ((atDir) + (widthDir)), + executable: true, + axioms: [] +} + +definition{ + name: widthBase, + parameters: [], + result: Nat, + body: 4, + executable: true, + axioms: [] +} + +definition{ + name: atBase, + parameters: [], + result: Nat, + body: ((atSkip) + (widthSkip)), + executable: true, + axioms: [] +} + +definition{ + name: widthHits, + parameters: [], + result: Nat, + body: 4, + executable: true, + axioms: [] +} + +definition{ + name: atHits, + parameters: [], + result: Nat, + body: ((atBase) + (widthBase)), + executable: true, + axioms: [] +} + +definition{ + name: radix, + parameters: [], + result: Nat, + body: 2, + executable: true, + axioms: [] +} + +definition{ + name: pow2, + parameters: [k : Nat], + result: Nat, + body: (match k + | Nat.zero => 1 + | Nat.succ m => (prim multiply (radix) (pow2 m) : Nat)), + executable: true, + axioms: [], + recursive_argument: k +} + +definition{ + name: getAt, + parameters: [w : Nat, t : Bytes, at : Nat], + result: Nat, + body: (Uorc.Codec.Table::getLoop w t at 0), + executable: true, + axioms: [Quot.sound, propext] +} + +definition{ + name: putAt, + parameters: [w : Nat, t : Bytes, at : Nat, v : Nat], + result: Bytes, + body: (Uorc.Codec.Table::setLoop w t (prim subtract (at + w) 1 : Nat) v), + executable: true, + axioms: [Quot.sound, propext] +} + definition{ name: putGlob, parameters: [s : (Bytes * (Bytes * (Bytes * X86StS))), w : Nat, k : Nat, v : Nat], @@ -95,6 +176,24 @@ axioms: [Quot.sound, propext] } +definition{ + name: byteBase, + parameters: [], + result: Nat, + body: 256, + executable: true, + axioms: [] +} + +definition{ + name: pastEnd, + parameters: [], + result: Nat, + body: (prim subtract (byteBase) 1 : Nat), + executable: true, + axioms: [] +} + definition{ name: filterLoop11FTPart24Loop28, parameters: [fuel : Nat, vk : Nat, s : (Bytes * (Bytes * (Bytes * X86StS))), vi : Nat, vw : Nat], @@ -111,7 +210,7 @@ name: filterLoop11FTPart24, parameters: [s : (Bytes * (Bytes * (Bytes * X86StS))), vhit : Nat, vwlow : Nat, vv : Nat, vi : Nat], result: (Bytes * (Bytes * (Bytes * X86StS))), - body: (let vw25 : Nat := (if (vhit =? 1) then (if (vwlow s - | Nat.succ m => (let next : (Bytes * (Bytes * (Bytes * X86StS))) := (let s36 : (Bytes * (Bytes * (Bytes * X86StS))) := (if (0 (let next : (Bytes * (Bytes * (Bytes * X86StS))) := (let s36 : (Bytes * (Bytes * (Bytes * X86StS))) := (if (0 [, …]`, and a function's +//! parameter by `Domain: : `. A domain is a name prefix of +//! the model's quantities (`stretch` holds `stretchRange`, `stretchHalfLast`, +//! …; a quantity stated as another less one, such as `cell1Last`, brings that +//! other, its extent, into the domain). +//! +//! The pass infers the domains of every expression of a file, to a fixpoint +//! (a local, field or static takes the domains of what is stored in it), the +//! way the model's own pass (`client/gen/domains.py`) does over the coder IR, +//! and then rewrites each literal whose value is a quantity of a domain in +//! scope at it (the domains of the operands it acts with, and of where its +//! value goes) as that quantity, read from the module generated from the model +//! ([`crate::native`]). A shift's count is placed among the base-two logarithms +//! of the quantities in scope. A literal it cannot place keeps its numeral and +//! is reported with the domains in scope, so the residue names the next +//! declarations to make. +//! +//! The rewritten site names the quantity in the integer view of the type the +//! literal had; that type is read back from the compiler (`cargo check`), which +//! is the only judge of a Rust literal's type, so the rewrite never changes a +//! value or a type, and the native output stays byte-identical. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +use syn::visit::{self, Visit}; + +use crate::native; + +/// The model module a native file reads its quantities from. +#[derive(Clone, Debug)] +pub struct Model { + /// Rust path of the generated module (`crate::model::ncm`). + pub path: String, + /// Quantity values by name, in the module's order. + pub values: Vec<(String, u128)>, + /// Constant tables read as cells: (view name, cells). + pub tables: Vec<(String, Vec)>, + /// Quantity bodies: the extent a `X - 1` quantity is stated from. + pub less_one: BTreeMap, +} + +impl Model { + /// Read a generated module's source: its model source and quantities. + pub fn load(root: &Path, generated: &str) -> Result { + let (_, src) = native::GENERATED + .iter() + .find(|(g, _)| *g == generated) + .ok_or_else(|| format!("{generated} is not a generated native module"))?; + let text = std::fs::read_to_string(root.join(src)).map_err(|e| format!("{src}: {e}"))?; + let (nats, raw) = native::quantities(&text); + let tables = native::table_cells(&raw) + .into_iter() + .map(|(n, w, vs)| (format!("{n}Cells{w}"), vs)) + .collect(); + let mut values = Vec::new(); + let mut less_one = BTreeMap::new(); + for (n, e, v) in &nats { + values.push((n.clone(), *v)); + if let native::Expr::Op(native::Op::Sub, a, b) = e { + if let (native::Expr::Name(x), native::Expr::Num(1)) = (&**a, &**b) { + less_one.insert(n.clone(), x.clone()); + } + } + } + let module = generated + .trim_start_matches("crates/uorc/src/") + .trim_end_matches(".rs") + .replace('/', "::"); + Ok(Model { + path: format!("crate::{module}"), + tables, + values, + less_one, + }) + } + + /// The quantities of a domain: those its name prefixes, and the extent + /// each `X - 1` among them is stated from. + pub fn domain(&self, d: &str) -> Vec<(String, u128)> { + let mut names: BTreeSet = BTreeSet::new(); + for (n, _) in &self.values { + if prefixed(n, d) { + names.insert(n.clone()); + if let Some(x) = self.less_one.get(n) { + names.insert(x.clone()); + } + } + } + self.values + .iter() + .filter(|(n, _)| names.contains(n)) + .cloned() + .collect() + } +} + +/// The characteristic quantities a domain's name may carry, as the model's +/// declarations name them: its extent (`Range`, `Base`), its unit, origin and +/// top, a map's step, points and scale, a count's limit, and a rescale to +/// another domain (`Per`), and a hash's multipliers and folds (each +/// numbered by its round); each also as its last value, its half and the +/// half's last value. +const CHARACTERISTIC: [&str; 11] = [ + "Range", + "Base", + "Unit", + "Origin", + "Top", + "Step", + "Points", + "Scale", + "Limit", + "Multiplier", + "Fold", +]; +const DERIVED: [&str; 3] = ["Last", "Half", "HalfLast"]; + +fn prefixed(name: &str, d: &str) -> bool { + let Some(rest) = name.strip_prefix(d) else { + return false; + }; + let rest = DERIVED + .iter() + .rev() + .find_map(|x| rest.strip_suffix(x)) + .unwrap_or(rest); + let rest = rest.trim_end_matches(|c: char| c.is_ascii_digit()); + rest.is_empty() + || CHARACTERISTIC.contains(&rest) + || rest + .strip_prefix("Per") + .and_then(|r| r.chars().next()) + .is_some_and(|c| c.is_ascii_uppercase()) +} + +/// A set of domain names. +type Ds = BTreeSet; + +/// A placed literal: its byte range in the file, the quantity, and whether it +/// is a base-two logarithm (a shift count). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Placed { + /// Byte range of the literal. + pub range: (usize, usize), + /// Line of the literal. + pub line: usize, + /// The literal's value. + pub value: String, + /// The literal's type suffix, if it has one. + pub suffix: String, + /// The quantity's name. + pub name: String, + /// A shift count: the quantity's base-two logarithm. + pub bits: bool, + /// Rendered as this expression instead of a model quantity (the width + /// of the integer type the bytes are read into). + pub raw: Option, +} + +/// What the pass finds in one file. +#[derive(Clone, Debug, Default)] +pub struct Outcome { + /// Literals restated as quantities. + pub placed: Vec, + /// Literals left, by (value, domains in scope). + pub residue: BTreeMap<(String, String), u64>, + /// Literals left: (line, value, domains in scope). + pub left: Vec<(usize, String, String)>, +} + +fn tags(attrs: &[syn::Attribute]) -> Vec { + let mut out = Vec::new(); + for a in attrs { + if let syn::Meta::NameValue(nv) = &a.meta { + if nv.path.is_ident("doc") { + if let syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(s), + .. + }) = &nv.value + { + if let Some(rest) = s.value().trim().strip_prefix("Domain:") { + out.push(rest.trim().to_string()); + } + } + } + } + } + out +} + +fn split(s: &str) -> Ds { + s.split(',') + .map(|x| x.trim().to_string()) + .filter(|x| !x.is_empty()) + .collect() +} + +/// Declarations read from a file's `Domain:` tags. +#[derive(Clone, Debug, Default)] +struct Decls { + /// Fields, constants and statics by name. + items: BTreeMap, + /// The domains of an array item's length (`Domain: len: `), by name. + lens: BTreeMap, + /// Function results by name. + results: BTreeMap, + /// Function parameters by (function, parameter). + params: BTreeMap<(String, String), Ds>, + /// Function parameter names in order. + order: BTreeMap>, + /// Every declared domain, in order of first declaration. + domains: Vec, +} + +impl Decls { + fn note(&mut self, ds: &Ds) { + for d in ds { + if !self.domains.contains(d) { + self.domains.push(d.clone()); + } + } + } + + fn func(&mut self, name: &str, attrs: &[syn::Attribute], sig: &syn::Signature) { + let names: Vec = sig + .inputs + .iter() + .map(|i| match i { + syn::FnArg::Receiver(_) => "self".to_string(), + syn::FnArg::Typed(t) => match &*t.pat { + syn::Pat::Ident(p) => p.ident.to_string(), + _ => String::new(), + }, + }) + .collect(); + self.order.insert(name.to_string(), names); + for t in tags(attrs) { + if let Some(l) = t.strip_prefix("len:") { + let ds = split(l); + self.note(&ds); + self.lens + .entry(format!("fn {name}")) + .or_default() + .extend(ds); + continue; + } + if let Some(l) = t.strip_prefix("body:") { + let ds = split(l); + self.note(&ds); + self.lens + .entry(format!("body {name}")) + .or_default() + .extend(ds); + continue; + } + match t.split_once(':') { + Some((p, d)) => { + let ds = split(d); + self.note(&ds); + self.params + .entry((name.to_string(), p.trim().to_string())) + .or_default() + .extend(ds); + } + None => { + let ds = split(&t); + self.note(&ds); + self.results.entry(name.to_string()).or_default().extend(ds); + } + } + } + } + + fn item(&mut self, name: &str, attrs: &[syn::Attribute]) { + for t in tags(attrs) { + if let Some(l) = t.strip_prefix("len:") { + let ds = split(l); + self.note(&ds); + self.lens.entry(name.to_string()).or_default().extend(ds); + continue; + } + let ds = split(&t); + self.note(&ds); + self.items.entry(name.to_string()).or_default().extend(ds); + } + } +} + +struct Collect<'a>(&'a mut Decls); + +impl<'ast> Visit<'ast> for Collect<'_> { + fn visit_field(&mut self, f: &'ast syn::Field) { + if let Some(i) = &f.ident { + self.0.item(&i.to_string(), &f.attrs); + } + visit::visit_field(self, f); + } + fn visit_item_struct(&mut self, st: &'ast syn::ItemStruct) { + self.0.item(&st.ident.to_string(), &st.attrs); + visit::visit_item_struct(self, st); + } + fn visit_item_const(&mut self, c: &'ast syn::ItemConst) { + self.0.item(&c.ident.to_string(), &c.attrs); + visit::visit_item_const(self, c); + } + fn visit_impl_item_const(&mut self, c: &'ast syn::ImplItemConst) { + self.0.item(&c.ident.to_string(), &c.attrs); + visit::visit_impl_item_const(self, c); + } + fn visit_item_static(&mut self, c: &'ast syn::ItemStatic) { + self.0.item(&c.ident.to_string(), &c.attrs); + visit::visit_item_static(self, c); + } + fn visit_item_fn(&mut self, f: &'ast syn::ItemFn) { + self.0.func(&f.sig.ident.to_string(), &f.attrs, &f.sig); + visit::visit_item_fn(self, f); + } + fn visit_impl_item_fn(&mut self, f: &'ast syn::ImplItemFn) { + self.0.func(&f.sig.ident.to_string(), &f.attrs, &f.sig); + visit::visit_impl_item_fn(self, f); + } + fn visit_trait_item_fn(&mut self, f: &'ast syn::TraitItemFn) { + self.0.func(&f.sig.ident.to_string(), &f.attrs, &f.sig); + visit::visit_trait_item_fn(self, f); + } +} + +/// Methods whose result is in the receiver's domains, and whose arguments act +/// in them. +const SAME: [&str; 16] = [ + "clamp", + "min", + "max", + "wrapping_add", + "wrapping_sub", + "wrapping_mul", + "saturating_add", + "saturating_sub", + "saturating_mul", + "abs", + "checked_add", + "checked_sub", + "abs_diff", + "div_ceil", + "next_multiple_of", + "rem_euclid", +]; + +/// Methods whose result is their receiver's value (a conversion, an unwrap). +const TRANSPARENT: [&str; 10] = [ + "into", + "try_into", + "unwrap", + "expect", + "unwrap_or", + "clone", + "copied", + "cloned", + "to_owned", + "unwrap_or_default", +]; + +/// Methods whose argument is a shift count in the receiver's domains. +const SHIFTS: [&str; 6] = [ + "wrapping_shl", + "wrapping_shr", + "checked_shl", + "checked_shr", + "rotate_left", + "rotate_right", +]; + +struct Pass<'a> { + model: &'a Model, + decls: &'a Decls, + /// Inferred domains of fields, constants and statics. + inferred: BTreeMap, + next: BTreeMap, + /// Locals of the function being read. + env: Vec>, + /// Domains locals are used in, by (function, local), from the last round + /// (a literal bound to a local acts in what the local is used with). + uses: BTreeMap<(String, String), Ds>, + next_uses: BTreeMap<(String, String), Ds>, + /// The function being read (for its result and parameters). + func: Option, + out: Outcome, + /// Skip: test code. + tests: bool, + /// Whether the literal being read multiplies or divides (a scale). + scaling: bool, + /// The array-length domains the function being read declares. + lens_now: Ds, + /// Literals that are the width of the type their bytes are read into. + widths_seen: Vec, + /// The domains every literal of the function being read acts in + /// (`Domain: body: `: a layout function's offsets). + body_now: Ds, +} + +/// Whether a quantity is a scale: a unit, a scale or a rescale, which only +/// multiplies or divides (or shifts, by its logarithm); it never stands where +/// a value is offset, bounded or masked. +fn is_scale(name: &str) -> bool { + let core = DERIVED + .iter() + .rev() + .find_map(|x| name.strip_suffix(x)) + .unwrap_or(name); + let core = core.trim_end_matches(|c: char| c.is_ascii_digit()); + core.ends_with("Unit") + || core.ends_with("Scale") + || core.ends_with("Multiplier") + || core.contains("Per") +} + +fn is_test(attrs: &[syn::Attribute]) -> bool { + attrs.iter().any(|a| { + a.path().is_ident("test") + || (a.path().is_ident("cfg") + && a.meta + .require_list() + .is_ok_and(|l| l.tokens.to_string().split_whitespace().any(|t| t == "test"))) + }) +} + +impl Pass<'_> { + fn item_ds(&self, name: &str) -> Ds { + let mut d = self.decls.items.get(name).cloned().unwrap_or_default(); + if let Some(i) = self.inferred.get(name) { + d.extend(i.iter().cloned()); + } + d + } + + fn local(&self, name: &str) -> Option { + self.env.iter().rev().find_map(|s| s.get(name).cloned()) + } + + fn bind(&mut self, name: String, ds: Ds) { + if let Some(s) = self.env.last_mut() { + s.insert(name, ds); + } + } + + fn store(&mut self, name: &str, ds: &Ds) { + if !ds.is_empty() { + self.next + .entry(name.to_string()) + .or_default() + .extend(ds.iter().cloned()); + } + } + + /// The domains declared for where a function's argument `i` goes. + fn param(&self, f: &str, i: usize, method: bool) -> Ds { + let Some(names) = self.decls.order.get(f) else { + return Ds::new(); + }; + let at = if method && names.first().is_some_and(|n| n == "self") { + i + 1 + } else { + i + }; + names + .get(at) + .and_then(|p| self.decls.params.get(&(f.to_string(), p.clone()))) + .cloned() + .unwrap_or_default() + } + + fn place(&mut self, lit: &syn::LitInt, scope: &Ds, shift: bool) { + let Ok(v) = lit.base10_parse::() else { + return; + }; + let mut scope = scope.clone(); + scope.extend(self.body_now.iter().cloned()); + let scope = &scope; + let r = lit.span().byte_range(); + let at = (r.start, r.end, lit.span().start().line); + if !self.place_value(v, at, lit.suffix(), scope, shift) { + let ordered = self.ordered(scope); + let key = ( + format!("{}{v}", if shift { "<<" } else { "" }), + ordered.join("/"), + ); + self.out.left.push((at.2, key.0.clone(), key.1.clone())); + *self.out.residue.entry(key).or_default() += 1; + } + } + + fn ordered(&self, scope: &Ds) -> Vec { + self.decls + .domains + .iter() + .filter(|d| scope.contains(*d)) + .cloned() + .collect() + } + + /// Place value `v` at `at` (byte range, line): true when it is a quantity + /// of a domain in scope (or, as a shift count, a quantity's logarithm; a + /// `log2 ` in scope holds the logarithms of that domain's). + fn place_value( + &mut self, + v: u128, + at: (usize, usize, usize), + suffix: &str, + scope: &Ds, + shift: bool, + ) -> bool { + if v <= 1 { + return true; + } + // every quantity in scope the value is; it is placed only when it is + // exactly one (two quantities of one value leave the choice open) + let mut hits: Vec<(String, bool)> = Vec::new(); + for d in self.ordered(scope) { + let (name, log) = match d.strip_prefix("log2 ") { + Some(x) => (x.to_string(), !shift), + None => (d.clone(), shift), + }; + for (n, q) in self.model.domain(&name) { + if is_scale(&n) && !(log || self.scaling) { + continue; + } + let hit = if log { + q.is_power_of_two() && u128::from(q.trailing_zeros()) == v + } else { + q == v + }; + if hit && !hits.contains(&(n.clone(), log)) { + hits.push((n, log)); + } + } + } + let [(name, bits)] = &hits[..] else { + return false; + }; + self.out.placed.push(Placed { + range: (at.0, at.1), + line: at.2, + value: v.to_string(), + suffix: suffix.to_string(), + name: name.clone(), + bits: *bits, + raw: None, + }); + true + } + + /// The domains of `e`; `want` is the domains of where its value goes. + fn ex(&mut self, e: &syn::Expr, want: &Ds) -> Ds { + use syn::Expr as E; + if !matches!(e, E::Lit(_) | E::Unary(_)) && self.scaling { + self.scaling = false; + let d = self.ex(e, want); + self.scaling = true; + return d; + } + match e { + E::Lit(l) => { + if let syn::Lit::Int(i) = &l.lit { + self.place(i, want, false); + } + Ds::new() + } + E::Path(p) => { + if let Some(i) = p.path.get_ident() { + let n = i.to_string(); + if let Some(d) = self.local(&n) { + return d; + } + return self.item_ds(&n); + } + p.path + .segments + .last() + .map(|s| self.item_ds(&s.ident.to_string())) + .unwrap_or_default() + } + E::Field(f) => { + self.ex(&f.base, &Ds::new()); + match &f.member { + syn::Member::Named(i) => self.item_ds(&i.to_string()), + syn::Member::Unnamed(_) => Ds::new(), + } + } + E::Index(i) => { + let d = self.ex(&i.expr, &Ds::new()); + self.ex(&i.index, &Ds::new()); + d + } + E::Paren(p) => self.ex(&p.expr, want), + E::Group(g) => self.ex(&g.expr, want), + E::Cast(c) => self.ex(&c.expr, want), + E::Reference(r) => self.ex(&r.expr, want), + E::Unary(u) => match u.op { + syn::UnOp::Neg(_) => self.ex(&u.expr, want), + syn::UnOp::Deref(_) => self.ex(&u.expr, want), + _ => { + self.ex(&u.expr, &Ds::new()); + Ds::new() + } + }, + E::Binary(b) => self.binary(b, want), + E::MethodCall(m) => { + let name = m.method.to_string(); + if SAME.contains(&name.as_str()) { + let mut scope = self.peek(&m.receiver); + for a in &m.args { + scope.extend(self.peek(a)); + } + scope.extend(want.iter().cloned()); + // a product's operands stand where a scale may + let saved = self.scaling; + self.scaling = matches!( + name.as_str(), + "wrapping_mul" | "saturating_mul" | "checked_mul" | "rem_euclid" + ); + let r = self.ex_operand(&m.receiver, &scope, saved); + for a in &m.args { + self.ex_operand(a, &scope, saved); + } + self.scaling = saved; + let mut out = r; + for a in &m.args { + out.extend(self.peek(a)); + } + return out; + } + if SHIFTS.contains(&name.as_str()) { + let mut scope = self.peek(&m.receiver); + scope.extend(want.iter().cloned()); + let r = self.ex(&m.receiver, want); + for a in &m.args { + self.shift_count(a, &scope); + } + return r; + } + if TRANSPARENT.contains(&name.as_str()) { + let r = self.ex(&m.receiver, want); + for a in &m.args { + self.ex(a, &r); + } + return r; + } + let r = self.ex(&m.receiver, &Ds::new()); + for (i, a) in m.args.iter().enumerate() { + let p = self.param(&name, i, true); + self.used(a, &p); + self.ex(a, &p); + } + let _ = r; + self.decls.results.get(&name).cloned().unwrap_or_default() + } + E::Call(c) => { + let name = match &*c.func { + E::Path(p) => p.path.segments.last().map(|s| s.ident.to_string()), + _ => None, + }; + if let (Some(n), E::Path(p)) = (name.as_deref(), &*c.func) { + if (n == "from_le_bytes" || n == "from_be_bytes") && p.path.segments.len() == 2 + { + let ty = p.path.segments[0].ident.to_string(); + for a in &c.args { + self.widths(a, &ty); + } + } + } + // a conversion carries its argument's domains + if name + .as_deref() + .is_some_and(|n| n == "from" || n == "try_from") + && c.args.len() == 1 + { + return self.ex(&c.args[0], want); + } + // a local closure: the domains of its body + if let E::Path(p) = &*c.func { + if let Some(local) = p.path.get_ident().and_then(|i| self.local(&i.to_string())) + { + for a in &c.args { + self.ex(a, &Ds::new()); + } + return local; + } + } + if name.is_none() { + self.ex(&c.func, &Ds::new()); + } + for (i, a) in c.args.iter().enumerate() { + let p = name + .as_deref() + .map(|n| self.param(n, i, false)) + .unwrap_or_default(); + self.used(a, &p); + self.ex(a, &p); + } + name.and_then(|n| self.decls.results.get(&n).cloned()) + .unwrap_or_default() + } + E::Assign(a) => { + let target = self.ex(&a.left, &Ds::new()); + let d = self.ex(&a.right, &target); + self.assign(&a.left, &d); + Ds::new() + } + E::Block(b) => self.block(&b.block, want), + E::Unsafe(b) => self.block(&b.block, want), + E::If(i) => { + self.ex(&i.cond, &Ds::new()); + let mut d = self.block(&i.then_branch, want); + if let Some((_, e)) = &i.else_branch { + d.extend(self.ex(e, want)); + } + d + } + E::Match(m) => { + let s = self.ex(&m.expr, &Ds::new()); + let mut d = Ds::new(); + for arm in &m.arms { + self.env.push(BTreeMap::new()); + self.pat(&arm.pat, &s); + d.extend(self.ex(&arm.body, want)); + self.env.pop(); + } + d + } + E::Array(a) if self.table(a) => Ds::new(), + E::Array(a) => { + let mut scope = want.clone(); + for x in &a.elems { + scope.extend(self.peek(x)); + } + let mut d = Ds::new(); + for x in &a.elems { + d.extend(self.ex(x, &scope)); + } + d + } + E::Repeat(r) => { + let d = self.ex(&r.expr, want); + self.ex(&r.len, want); + d + } + E::Tuple(t) => { + // a tuple's parts bound together (`let (a, b) = (x, y)`) share its domains + let mut d = Ds::new(); + for x in &t.elems { + d.extend(self.ex(x, &Ds::new())); + } + d + } + E::Range(r) => { + let mut scope = want.clone(); + for x in r.start.iter().chain(r.end.iter()) { + scope.extend(self.peek(x)); + } + let mut d = Ds::new(); + for x in r.start.iter().chain(r.end.iter()) { + d.extend(self.ex(x, &scope)); + } + d + } + E::Return(r) => { + let w = self + .func + .as_ref() + .and_then(|f| self.decls.results.get(f).cloned()) + .unwrap_or_default(); + if let Some(x) = &r.expr { + self.ex(x, &w); + } + Ds::new() + } + E::Closure(c) => { + self.env.push(BTreeMap::new()); + let d = self.ex(&c.body, &Ds::new()); + self.env.pop(); + d + } + E::Loop(l) => { + self.block(&l.body, &Ds::new()); + Ds::new() + } + E::While(w) => { + self.ex(&w.cond, &Ds::new()); + self.block(&w.body, &Ds::new()); + Ds::new() + } + E::ForLoop(f) => { + let d = self.ex(&f.expr, &Ds::new()); + self.env.push(BTreeMap::new()); + self.pat(&f.pat, &d); + self.block(&f.body, &Ds::new()); + self.env.pop(); + Ds::new() + } + E::Let(l) => { + let d = self.ex(&l.expr, &Ds::new()); + self.pat(&l.pat, &d); + Ds::new() + } + E::Struct(s) => { + for f in &s.fields { + let w = match &f.member { + syn::Member::Named(i) => self.item_ds(&i.to_string()), + syn::Member::Unnamed(_) => Ds::new(), + }; + self.used(&f.expr, &w); + // a field's array value: its length acts in the field's length domains + let d = match (&f.expr, &f.member) { + (E::Repeat(r), syn::Member::Named(i)) => { + let l = self + .decls + .lens + .get(&i.to_string()) + .cloned() + .unwrap_or_else(|| w.clone()); + self.ex(&r.len, &l); + self.ex(&r.expr, &w) + } + _ => self.ex(&f.expr, &w), + }; + if let syn::Member::Named(i) = &f.member { + self.store(&i.to_string(), &d); + } + } + if let Some(r) = &s.rest { + self.ex(r, &Ds::new()); + } + Ds::new() + } + E::Try(t) => self.ex(&t.expr, want), + E::Break(b) => { + if let Some(x) = &b.expr { + self.ex(x, &Ds::new()); + } + Ds::new() + } + E::Const(c) => self.block(&c.block, want), + _ => { + visit::visit_expr(&mut Inner(self), e); + Ds::new() + } + } + } + + /// An array of numerals that is a constant table of the model, read as + /// cells: placed whole. + fn table(&mut self, a: &syn::ExprArray) -> bool { + let mut vs = Vec::new(); + for e in &a.elems { + match e { + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Int(i), + .. + }) => match i.base10_parse::() { + Ok(v) => vs.push(v), + Err(_) => return false, + }, + _ => return false, + } + } + if vs.len() < 2 { + return false; + } + let Some((name, _)) = self.model.tables.iter().find(|(_, c)| *c == vs) else { + return false; + }; + let r = a.bracket_token.span.join().byte_range(); + self.out.placed.push(Placed { + range: (r.start, r.end), + line: a.bracket_token.span.join().start().line, + value: format!("[{} cells]", vs.len()), + suffix: String::new(), + name: name.clone(), + bits: false, + raw: None, + }); + true + } + + /// The literals of `e` that equal the width of `ty` (the integer the bytes + /// are read into by `ty::from_le_bytes` / `from_be_bytes`): they are that + /// width, `size_of::()`. + fn widths(&mut self, e: &syn::Expr, ty: &str) { + let w: u128 = match ty { + "u16" | "i16" => 2, + "u32" | "i32" => 4, + "u64" | "i64" => 8, + "u128" | "i128" => 16, + _ => return, + }; + type Lit = (Option, bool, std::ops::Range, usize); + struct Lits<'v>(&'v mut Vec); + impl<'ast> Visit<'ast> for Lits<'_> { + fn visit_lit_int(&mut self, i: &'ast syn::LitInt) { + self.0.push(( + i.base10_parse::().ok(), + i.suffix().is_empty(), + i.span().byte_range(), + i.span().start().line, + )); + } + } + let mut lits = Vec::new(); + Lits(&mut lits).visit_expr(e); + for (v, plain, r, line) in lits { + if v == Some(w) && plain { + self.widths_seen.push(Placed { + range: (r.start, r.end), + line, + value: w.to_string(), + suffix: String::new(), + name: format!("size_of::<{ty}>"), + bits: false, + raw: Some(format!("std::mem::size_of::<{ty}>()")), + }); + } + } + } + + /// The domains of `e` without placing anything. + fn peek(&mut self, e: &syn::Expr) -> Ds { + let widths = self.widths_seen.len(); + let saved = ( + self.out.placed.len(), + self.out.residue.clone(), + self.next.clone(), + self.out.left.len(), + ); + self.env.push(BTreeMap::new()); + let d = self.ex(e, &Ds::new()); + self.env.pop(); + self.out.placed.truncate(saved.0); + self.out.residue = saved.1; + self.next = saved.2; + self.out.left.truncate(saved.3); + self.widths_seen.truncate(widths); + d + } + + fn shift_count(&mut self, e: &syn::Expr, scope: &Ds) { + match e { + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Int(i), + .. + }) => self.place(i, scope, true), + syn::Expr::Paren(p) => self.shift_count(&p.expr, scope), + syn::Expr::Cast(c) => self.shift_count(&c.expr, scope), + syn::Expr::Binary(b) if matches!(b.op, syn::BinOp::Add(_) | syn::BinOp::Sub(_)) => { + // a count less another (`bits - 12`): a literal is a count of + // the other side's kind (a logarithm where that side's domain + // holds logarithms); beside a count of no declared kind it + // stays open + let lit = |e: &syn::Expr| { + matches!( + e, + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Int(_), + .. + }) + ) + }; + match (lit(&b.left), lit(&b.right)) { + (true, false) | (false, true) => { + let (l, other) = if lit(&b.left) { + (&b.left, &b.right) + } else { + (&b.right, &b.left) + }; + let kind = self.ex(other, &Ds::new()); + if let syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Int(i), + .. + }) = &**l + { + self.place(i, &kind, false); + } + } + _ => { + self.shift_count(&b.left, scope); + self.shift_count(&b.right, scope); + } + } + } + _ => { + self.ex(e, &Ds::new()); + } + } + } + + /// Read an operand: the scaling flag holds for a literal operand only; a + /// compound operand is read in its own operators' roles. + fn ex_operand(&mut self, e: &syn::Expr, scope: &Ds, outer: bool) -> Ds { + let lit = matches!(e, syn::Expr::Lit(_)) + || matches!(e, syn::Expr::Unary(u) if matches!(&*u.expr, syn::Expr::Lit(_))); + if lit { + return self.ex(e, scope); + } + let role = self.scaling; + self.scaling = false; + let d = self.ex(e, scope); + self.scaling = role; + let _ = outer; + d + } + + /// Note that a local operand acts in `scope`. + fn used(&mut self, e: &syn::Expr, scope: &Ds) { + let e = match e { + syn::Expr::Paren(p) => &*p.expr, + syn::Expr::Cast(c) => &*c.expr, + syn::Expr::Unary(u) => &*u.expr, + x => x, + }; + if let syn::Expr::Path(p) = e { + if let (Some(i), Some(f)) = (p.path.get_ident(), self.func.clone()) { + let n = i.to_string(); + if self.local(&n).is_some() && !scope.is_empty() { + self.next_uses + .entry((f, n)) + .or_default() + .extend(scope.iter().cloned()); + } + } + } + } + + fn binary(&mut self, b: &syn::ExprBinary, want: &Ds) -> Ds { + use syn::BinOp as B; + match b.op { + B::Shl(_) => { + // `1 << k`: the power of two itself, when it is a quantity in scope + if let ( + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Int(one), + .. + }), + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Int(kl), + .. + }), + ) = (&*b.left, &*b.right) + { + if let (Ok(1), Ok(k)) = (one.base10_parse::(), kl.base10_parse::()) { + let span = one.span().join(kl.span()).unwrap_or_else(|| one.span()); + let r = span.byte_range(); + if k < 127 + && self.place_value( + 1u128 << k, + (r.start, r.end, span.start().line), + one.suffix(), + want, + false, + ) + { + return Ds::new(); + } + } + } + self.shift(b, want) + } + B::Shr(_) | B::ShlAssign(_) | B::ShrAssign(_) => self.shift(b, want), + _ => self.binary_rest(b, want), + } + } + + fn shift(&mut self, b: &syn::ExprBinary, want: &Ds) -> Ds { + let mut scope = self.peek(&b.left); + scope.extend(want.iter().cloned()); + let d = self.ex(&b.left, want); + self.shift_count(&b.right, &scope); + d + } + + fn binary_rest(&mut self, b: &syn::ExprBinary, want: &Ds) -> Ds { + use syn::BinOp as B; + match b.op { + B::And(_) | B::Or(_) => { + self.ex(&b.left, &Ds::new()); + self.ex(&b.right, &Ds::new()); + Ds::new() + } + B::Eq(_) | B::Lt(_) | B::Le(_) | B::Ne(_) | B::Ge(_) | B::Gt(_) => { + let mut scope = self.peek(&b.left); + scope.extend(self.peek(&b.right)); + self.used(&b.left, &scope); + self.used(&b.right, &scope); + self.ex(&b.left, &scope); + self.ex(&b.right, &scope); + Ds::new() + } + B::AddAssign(_) + | B::SubAssign(_) + | B::MulAssign(_) + | B::DivAssign(_) + | B::RemAssign(_) + | B::BitAndAssign(_) + | B::BitOrAssign(_) + | B::BitXorAssign(_) => { + let mut scope = self.peek(&b.left); + scope.extend(self.peek(&b.right)); + self.ex(&b.left, &scope); + let d = self.ex(&b.right, &scope); + self.assign(&b.left, &d); + Ds::new() + } + _ => { + let mut scope = self.peek(&b.left); + scope.extend(self.peek(&b.right)); + scope.extend(want.iter().cloned()); + self.used(&b.left, &scope); + self.used(&b.right, &scope); + let saved = self.scaling; + self.scaling = matches!(b.op, B::Mul(_) | B::Div(_) | B::Rem(_)); + let mut d = self.ex_operand(&b.left, &scope, saved); + d.extend(self.ex_operand(&b.right, &scope, saved)); + self.scaling = saved; + d + } + } + } + + fn assign(&mut self, target: &syn::Expr, d: &Ds) { + match target { + syn::Expr::Path(p) => { + if let Some(i) = p.path.get_ident() { + let n = i.to_string(); + if self.local(&n).is_some() { + let mut ds = self.local(&n).unwrap_or_default(); + ds.extend(d.iter().cloned()); + for s in self.env.iter_mut().rev() { + if let Some(x) = s.get_mut(&n) { + *x = ds; + break; + } + } + } else { + self.store(&n, d); + } + } + } + syn::Expr::Field(f) => { + if let syn::Member::Named(i) = &f.member { + self.store(&i.to_string(), d); + } + } + syn::Expr::Index(i) => self.assign(&i.expr, d), + syn::Expr::Unary(u) => self.assign(&u.expr, d), + syn::Expr::Paren(p) => self.assign(&p.expr, d), + _ => {} + } + } + + fn pat(&mut self, p: &syn::Pat, d: &Ds) { + match p { + syn::Pat::Ident(i) => { + self.bind(i.ident.to_string(), d.clone()); + if let Some((_, s)) = &i.subpat { + self.pat(s, d); + } + } + syn::Pat::Type(t) => self.pat(&t.pat, d), + syn::Pat::Reference(r) => self.pat(&r.pat, d), + syn::Pat::Tuple(t) => { + for x in &t.elems { + self.pat(x, d); + } + } + syn::Pat::Slice(s) => { + for x in &s.elems { + self.pat(x, d); + } + } + syn::Pat::TupleStruct(t) => { + for x in &t.elems { + self.pat(x, d); + } + } + syn::Pat::Struct(s) => { + for f in &s.fields { + let w = match &f.member { + syn::Member::Named(i) => self.item_ds(&i.to_string()), + syn::Member::Unnamed(_) => Ds::new(), + }; + self.pat(&f.pat, &w); + } + } + syn::Pat::Or(o) => { + for x in &o.cases { + self.pat(x, d); + } + } + syn::Pat::Lit(l) => { + if let syn::Lit::Int(i) = &l.lit { + self.place(i, d, false); + } + } + syn::Pat::Range(r) => { + for x in r.start.iter().chain(r.end.iter()) { + self.ex(x, d); + } + } + _ => {} + } + } + + /// A type's array lengths: each acts in `ds` (a table's extent is its + /// domain's). + fn ty(&mut self, t: &syn::Type, ds: &Ds) { + match t { + syn::Type::Array(a) => { + self.ty(&a.elem, ds); + self.ex(&a.len, ds); + } + syn::Type::Reference(r) => self.ty(&r.elem, ds), + syn::Type::Paren(p) => self.ty(&p.elem, ds), + syn::Type::Slice(s) => self.ty(&s.elem, ds), + syn::Type::Tuple(t) => { + for e in &t.elems { + self.ty(e, ds); + } + } + syn::Type::Path(p) => { + for seg in &p.path.segments { + if let syn::PathArguments::AngleBracketed(a) = &seg.arguments { + for g in &a.args { + match g { + syn::GenericArgument::Type(t) => self.ty(t, ds), + syn::GenericArgument::Const(e) => { + self.ex(e, &Ds::new()); + } + _ => {} + } + } + } + } + } + _ => {} + } + } + + fn block(&mut self, b: &syn::Block, want: &Ds) -> Ds { + self.env.push(BTreeMap::new()); + let mut d = Ds::new(); + let n = b.stmts.len(); + for (i, s) in b.stmts.iter().enumerate() { + match s { + syn::Stmt::Local(l) => { + if let syn::Pat::Type(t) = &l.pat { + let lens = self.lens_now.clone(); + self.ty(&t.ty, &lens); + } + let used = match &l.pat { + syn::Pat::Ident(p) => self + .func + .as_ref() + .and_then(|f| self.uses.get(&(f.clone(), p.ident.to_string()))) + .cloned() + .unwrap_or_default(), + syn::Pat::Type(t) => match &*t.pat { + syn::Pat::Ident(p) => self + .func + .as_ref() + .and_then(|f| self.uses.get(&(f.clone(), p.ident.to_string()))) + .cloned() + .unwrap_or_default(), + _ => Ds::new(), + }, + _ => Ds::new(), + }; + let v = l + .init + .as_ref() + .map(|i| { + // a local's uses reach its value only when the value is a + // numeral or a choice of numerals, not through arithmetic + let direct = matches!( + &*i.expr, + syn::Expr::Lit(_) + | syn::Expr::Repeat(_) + | syn::Expr::Array(_) + | syn::Expr::If(_) + | syn::Expr::Match(_) + | syn::Expr::Unary(_) + | syn::Expr::Block(_) + ); + let w = if direct { used.clone() } else { Ds::new() }; + let v = self.ex(&i.expr, &w); + if let Some((_, e)) = &i.diverge { + self.ex(e, &Ds::new()); + } + v + }) + .unwrap_or_default(); + self.pat(&l.pat, &v); + } + syn::Stmt::Expr(e, semi) => { + let w = if i + 1 == n && semi.is_none() { + want.clone() + } else { + Ds::new() + }; + let x = self.ex(e, &w); + if i + 1 == n && semi.is_none() { + d = x; + } + } + syn::Stmt::Item(it) => self.item(it), + syn::Stmt::Macro(_) => {} + } + } + self.env.pop(); + d + } + + fn func(&mut self, name: &str, sig: &syn::Signature, body: &syn::Block) { + let saved = self.func.replace(name.to_string()); + self.env.push(BTreeMap::new()); + let result = self.decls.results.get(name).cloned().unwrap_or_default(); + // the signature's array lengths: its `len:` declaration, else the result's domains + let lens = self.decls.lens.get(&format!("fn {name}")).cloned(); + let saved_lens = std::mem::replace(&mut self.lens_now, lens.clone().unwrap_or_default()); + let body_ds = self + .decls + .lens + .get(&format!("body {name}")) + .cloned() + .unwrap_or_default(); + let saved_body = std::mem::replace(&mut self.body_now, body_ds); + if let syn::ReturnType::Type(_, t) = &sig.output { + self.ty(t, lens.as_ref().unwrap_or(&result)); + } + for i in &sig.inputs { + if let syn::FnArg::Typed(t) = i { + let pd = match &*t.pat { + syn::Pat::Ident(p) => self + .decls + .params + .get(&(name.to_string(), p.ident.to_string())) + .cloned() + .unwrap_or_default(), + _ => Ds::new(), + }; + let mut l = lens.clone().unwrap_or_default(); + l.extend(pd.iter().cloned()); + self.ty(&t.ty, &l); + if let syn::Pat::Ident(p) = &*t.pat { + let n = p.ident.to_string(); + let d = self + .decls + .params + .get(&(name.to_string(), n.clone())) + .cloned() + .unwrap_or_default(); + self.bind(n, d); + } + } + } + let want = self.decls.results.get(name).cloned().unwrap_or_default(); + self.block(body, &want); + self.env.pop(); + self.func = saved; + self.lens_now = saved_lens; + self.body_now = saved_body; + } + + fn item(&mut self, it: &syn::Item) { + match it { + syn::Item::Fn(f) if !is_test(&f.attrs) => { + self.func(&f.sig.ident.to_string(), &f.sig, &f.block) + } + syn::Item::Impl(i) if !is_test(&i.attrs) => { + for x in &i.items { + match x { + syn::ImplItem::Fn(f) if !is_test(&f.attrs) => { + self.func(&f.sig.ident.to_string(), &f.sig, &f.block) + } + syn::ImplItem::Const(c) => { + let w = self.item_ds(&c.ident.to_string()); + let d = self.ex(&c.expr, &w); + self.store(&c.ident.to_string(), &d); + } + _ => {} + } + } + } + syn::Item::Trait(t) => { + for x in &t.items { + if let syn::TraitItem::Fn(f) = x { + match &f.default { + Some(b) => self.func(&f.sig.ident.to_string(), &f.sig, b), + None => self.func( + &f.sig.ident.to_string(), + &f.sig, + &syn::Block { + brace_token: Default::default(), + stmts: Vec::new(), + }, + ), + } + } + } + } + syn::Item::Mod(m) if !is_test(&m.attrs) => { + if let Some((_, items)) = &m.content { + for x in items { + self.item(x); + } + } + } + syn::Item::Struct(st) if !is_test(&st.attrs) => { + let own = st.ident.to_string(); + for f in &st.fields { + // a named field's own declaration, an unnamed one's its struct's + let key = f.ident.as_ref().map_or(own.clone(), |i| i.to_string()); + let w = self + .decls + .lens + .get(&key) + .cloned() + .unwrap_or_else(|| self.item_ds(&key)); + self.ty(&f.ty, &w); + } + } + syn::Item::Const(c) => { + let w = self.item_ds(&c.ident.to_string()); + let l = self + .decls + .lens + .get(&c.ident.to_string()) + .cloned() + .unwrap_or_else(|| w.clone()); + self.ty(&c.ty, &l); + let d = self.ex(&c.expr, &w); + self.store(&c.ident.to_string(), &d); + } + syn::Item::Static(c) => { + let w = self.item_ds(&c.ident.to_string()); + self.ty(&c.ty, &w); + let d = self.ex(&c.expr, &w); + self.store(&c.ident.to_string(), &d); + } + _ => {} + } + let _ = self.tests; + } +} + +/// Visits the sub-expressions of an expression kind the pass does not type. +struct Inner<'p, 'a>(&'p mut Pass<'a>); + +impl<'ast> Visit<'ast> for Inner<'_, '_> { + fn visit_expr(&mut self, e: &'ast syn::Expr) { + self.0.ex(e, &Ds::new()); + } +} + +/// Run the pass over one file's source. +pub fn pass(model: &Model, text: &str, others: &[String]) -> Result { + let ast = syn::parse_file(text).map_err(|e| e.to_string())?; + let mut decls = Decls::default(); + Collect(&mut decls).visit_file(&ast); + // the declarations of the other files read together (a module's parent and children) + for o in others { + if let Ok(f) = syn::parse_file(o) { + Collect(&mut decls).visit_file(&f); + } + } + let mut p = Pass { + model, + decls: &decls, + inferred: BTreeMap::new(), + next: BTreeMap::new(), + uses: BTreeMap::new(), + next_uses: BTreeMap::new(), + env: Vec::new(), + func: None, + out: Outcome::default(), + tests: false, + scaling: false, + lens_now: Ds::new(), + body_now: Ds::new(), + widths_seen: Vec::new(), + }; + for _ in 0..32 { + p.next = BTreeMap::new(); + p.next_uses = BTreeMap::new(); + p.out = Outcome::default(); + p.widths_seen.clear(); + for it in &ast.items { + p.item(it); + } + let mut merged = p.inferred.clone(); + for (k, v) in &p.next { + merged + .entry(k.clone()) + .or_default() + .extend(v.iter().cloned()); + } + let mut uses = p.uses.clone(); + for (k, v) in &p.next_uses { + uses.entry(k.clone()).or_default().extend(v.iter().cloned()); + } + let settled = merged == p.inferred && uses == p.uses; + p.uses = uses; + if settled { + let mut ws = std::mem::take(&mut p.widths_seen); + ws.retain(|w| !p.out.placed.iter().any(|x| x.range == w.range)); + p.out.placed.extend(ws); + // a width's site was also counted as residue: drop it there + p.out.placed.sort_by_key(|x| x.range); + p.out.placed.dedup_by_key(|x| x.range); + return Ok(p.out); + } + p.inferred = merged; + } + Err("domains: no fixpoint".to_string()) +} + +/// The integer views a literal of unknown type is tried in, in the order the +/// compiler is asked. +pub const VIEWS: [&str; 9] = [ + "i32", "u32", "usize", "u64", "i64", "u16", "i16", "u8", "i128", +]; + +/// Render a placed literal in the view `ty`. +pub fn site(model: &Model, p: &Placed, ty: &str) -> String { + if let Some(r) = &p.raw { + return r.clone(); + } + if p.bits { + format!("{}::{ty}::bits::{}", model.path, p.name) + } else { + format!("{}::{ty}::{}", model.path, p.name) + } +} + +/// One rewritten site under the compiler's judgement. +#[derive(Clone, Debug)] +struct Site { + file: usize, + placed: Placed, + /// The views tried so far, the current last. + tried: Vec, + /// Left as a numeral: no view the compiler admits. + dropped: bool, +} + +fn render(model: &Model, text: &str, sites: &[&Site]) -> (String, Vec<(usize, usize)>) { + let mut out = String::with_capacity(text.len()); + let mut at = 0; + let mut ranges = Vec::new(); + for s in sites { + let (a, b) = s.placed.range; + out.push_str(&text[at..a]); + let start = out.len(); + if s.dropped { + out.push_str(&text[a..b]); + } else { + out.push_str(&site( + model, + &s.placed, + s.tried.last().map_or("i32", String::as_str), + )); + } + ranges.push((start, out.len())); + at = b; + } + out.push_str(&text[at..]); + (out, ranges) +} + +/// A compiler error: file, byte range, and every type named in it. +#[derive(Debug)] +struct Diagnostic { + file: String, + range: (usize, usize), + line: usize, + types: Vec, +} + +fn types_in(s: &str) -> Vec { + s.split('`') + .skip(1) + .step_by(2) + .filter(|t| VIEWS.contains(t) || *t == "{integer}") + .map(str::to_string) + .collect() +} + +fn diagnostics(root: &Path, packages: &[&str]) -> Result, crate::Error> { + let mut cmd = std::process::Command::new("cargo"); + cmd.current_dir(root).args([ + "check", + "--locked", + "--quiet", + "--message-format=json", + "--all-targets", + ]); + for p in packages { + cmd.args(["-p", p]); + } + let out = cmd.output().map_err(|e| format!("cargo check: {e}"))?; + let mut ds = Vec::new(); + for line in String::from_utf8_lossy(&out.stdout).lines() { + let Ok(v) = serde_json::from_str::(line) else { + continue; + }; + if v["reason"] != "compiler-message" || v["message"]["level"] != "error" { + continue; + } + let m = &v["message"]; + let mut text = m["message"].as_str().unwrap_or_default().to_string(); + for sp in m["spans"].as_array().into_iter().flatten() { + text.push(' '); + text.push_str(sp["label"].as_str().unwrap_or_default()); + } + for c in m["children"].as_array().into_iter().flatten() { + text.push(' '); + text.push_str(c["message"].as_str().unwrap_or_default()); + } + for sp in m["spans"].as_array().into_iter().flatten() { + if sp["is_primary"] != true { + continue; + } + ds.push(Diagnostic { + file: sp["file_name"].as_str().unwrap_or_default().to_string(), + range: ( + sp["byte_start"].as_u64().unwrap_or(0) as usize, + sp["byte_end"].as_u64().unwrap_or(0) as usize, + ), + line: sp["line_start"].as_u64().unwrap_or(0) as usize, + types: types_in(&text), + }); + } + if ds.is_empty() || m["spans"].as_array().is_none_or(Vec::is_empty) { + return Err(format!("cargo check: {text}")); + } + } + if !out.status.success() && ds.is_empty() { + return Err(format!( + "cargo check failed without a diagnostic:\n{}", + String::from_utf8_lossy(&out.stderr) + )); + } + Ok(ds) +} + +/// The report of a rewrite. +#[derive(Debug, Default)] +pub struct Report { + /// Sites restated, by file. + pub restated: BTreeMap, + /// Sites placed but left as numerals (no view the compiler admits). + pub dropped: usize, + /// Residue, by file, (value, scope). + pub residue: BTreeMap>, + /// Placed sites, by file: (line, value, quantity). + pub placed: BTreeMap>, + /// Residue sites, by file: (line, value, scope). + pub left: BTreeMap>, +} + +/// Rewrite `files` (repository-relative), each reading the generated module +/// `generated`, under the compiler's judgement of `packages`. +pub fn rewrite( + root: &Path, + generated: &str, + files: &[String], + packages: &[&str], + dry: bool, +) -> Result { + let model = Model::load(root, generated)?; + let mut texts = Vec::new(); + let mut sites = Vec::new(); + let mut report = Report::default(); + let all: Vec = files + .iter() + .map(|f| std::fs::read_to_string(root.join(f)).map_err(|e| format!("{f}: {e}"))) + .collect::>()?; + for (i, f) in files.iter().enumerate() { + let text = all[i].clone(); + let others: Vec = all + .iter() + .enumerate() + .filter(|(j, _)| *j != i) + .map(|(_, t)| t.clone()) + .collect(); + let o = pass(&model, &text, &others).map_err(|e| format!("{f}: {e}"))?; + report.residue.insert(f.clone(), o.residue); + let mut left = o.left; + left.sort(); + left.dedup(); + report.left.insert(f.clone(), left); + report.placed.insert( + f.clone(), + o.placed + .iter() + .map(|p| { + ( + p.line, + p.value.clone(), + format!("{}{}", if p.bits { "bits::" } else { "" }, p.name), + ) + }) + .collect(), + ); + for p in o.placed { + let first = if p.suffix.is_empty() { + "i32".to_string() + } else { + p.suffix.clone() + }; + sites.push(Site { + file: i, + placed: p, + tried: vec![first], + dropped: false, + }); + } + texts.push(text); + } + if dry { + for s in &sites { + *report.restated.entry(files[s.file].clone()).or_default() += 1; + } + return Ok(report); + } + let originals = texts.clone(); + let write = |sites: &[Site]| -> Result>, crate::Error> { + let mut all = Vec::new(); + for (i, f) in files.iter().enumerate() { + let mine: Vec<&Site> = sites.iter().filter(|s| s.file == i).collect(); + let (text, ranges) = render(&model, &texts[i], &mine); + std::fs::write(root.join(f), text).map_err(|e| format!("{f}: {e}"))?; + all.push(ranges); + } + Ok(all) + }; + let restore = || { + for (i, f) in files.iter().enumerate() { + let _ = std::fs::write(root.join(f), &originals[i]); + } + }; + for _round in 0..(VIEWS.len() + 2) { + let ranges = write(&sites)?; + let ds = match diagnostics(root, packages) { + Ok(d) => d, + Err(e) => { + restore(); + return Err(e); + } + }; + if ds.is_empty() { + for f in files { + let _ = std::process::Command::new("rustfmt") + .current_dir(root) + .args(["--edition", "2021", f]) + .status(); + } + for s in sites.iter().filter(|s| !s.dropped) { + *report.restated.entry(files[s.file].clone()).or_default() += 1; + } + report.dropped = sites.iter().filter(|s| s.dropped).count(); + return Ok(report); + } + // index sites by (file, rendered range) + let mut hit = vec![false; sites.len()]; + let mut want: Vec> = vec![None; sites.len()]; + let mut stray = Vec::new(); + for d in &ds { + let Some(fi) = files.iter().position(|f| d.file.ends_with(f.as_str())) else { + stray.push(d); + continue; + }; + let mut any = false; + let text_lines: Vec = Vec::new(); + let _ = text_lines; + for (k, s) in sites.iter().enumerate() { + if s.file != fi || s.dropped { + continue; + } + let idx = sites[..k].iter().filter(|x| x.file == fi).count(); + let r = ranges[fi][idx]; + let overlaps = r.0 < d.range.1 && d.range.0 < r.1; + if overlaps { + any = true; + hit[k] = true; + let cur = s.tried.last().cloned().unwrap_or_default(); + want[k] = d + .types + .iter() + .find(|t| **t != cur && *t != "{integer}") + .cloned(); + } + } + if !any { + // an operator's error (`cannot add`): the sites on its line + let line_of = + |text: &str, at: usize| text[..at.min(text.len())].matches('\n').count() + 1; + let rendered = std::fs::read_to_string(root.join(&files[fi])).unwrap_or_default(); + for (k, s) in sites.iter().enumerate() { + if s.file != fi || s.dropped { + continue; + } + let idx = sites[..k].iter().filter(|x| x.file == fi).count(); + if line_of(&rendered, ranges[fi][idx].0) == d.line { + any = true; + hit[k] = true; + let cur = s.tried.last().cloned().unwrap_or_default(); + if want[k].is_none() { + want[k] = d + .types + .iter() + .find(|t| **t != cur && *t != "{integer}") + .cloned(); + } + } + } + } + if !any { + stray.push(d); + } + } + let mut retyped_now: Vec = Vec::new(); + // errors a site explains come first: the rest may follow from them + if !stray.is_empty() && !hit.iter().any(|h| *h) { + // an error no site explains at its span: a site bound earlier (a local the + // error reads) whose view the error names takes the other view it names; + // else every site on the error's lines stays a numeral + let mut fixed = false; + for d in &stray { + if let Some(fi) = files.iter().position(|f| d.file.ends_with(f.as_str())) { + let rendered = + std::fs::read_to_string(root.join(&files[fi])).unwrap_or_default(); + let line_of = + |at: usize| rendered[..at.min(rendered.len())].matches('\n').count() + 1; + let mut retyped = false; + for k in 0..sites.len() { + if sites[k].file != fi || sites[k].dropped || hit[k] { + continue; + } + let idx = sites[..k].iter().filter(|x| x.file == fi).count(); + let l = line_of(ranges[fi][idx].0); + let cur = sites[k].tried.last().cloned().unwrap_or_default(); + if l <= d.line + 3 && l + 60 >= d.line && d.types.contains(&cur) { + if let Some(t) = d.types.iter().find(|t| { + **t != cur && *t != "{integer}" && !sites[k].tried.contains(t) + }) { + sites[k].tried.push(t.clone()); + hit[k] = true; + retyped_now.push(k); + want[k] = None; + retyped = true; + fixed = true; + } + } + } + if retyped { + continue; + } + for k in 0..sites.len() { + if sites[k].file != fi || sites[k].dropped { + continue; + } + let idx = sites[..k].iter().filter(|x| x.file == fi).count(); + let l = line_of(ranges[fi][idx].0); + if l + 3 >= d.line && l <= d.line + 3 { + sites[k].dropped = true; + fixed = true; + } + } + } + } + if !fixed { + if std::env::var_os("FIGURES_DERIVE_KEEP").is_none() { + restore(); + } + return Err(format!( + "cargo check: {} errors no rewritten site explains, first: {:?}", + stray.len(), + stray.iter().take(3).collect::>() + )); + } + } + for k in 0..sites.len() { + if !hit[k] || retyped_now.contains(&k) { + continue; + } + let next = want[k] + .clone() + .filter(|t| !sites[k].tried.contains(t)) + .or_else(|| { + VIEWS + .iter() + .map(|v| v.to_string()) + .find(|v| !sites[k].tried.contains(v)) + }); + match next { + Some(t) => sites[k].tried.push(t), + None => sites[k].dropped = true, + } + } + } + for s in sites.iter_mut() { + s.dropped = true; + } + restore(); + Err("the compiler admitted no view for some sites within the rounds".to_string()) +} diff --git a/crates/figures/src/lib.rs b/crates/figures/src/lib.rs index 36a7f4c8..9b211ce8 100644 --- a/crates/figures/src/lib.rs +++ b/crates/figures/src/lib.rs @@ -31,6 +31,11 @@ //! module is one of the wire modules (`Uorc.Wire.*`, `Uorc.Codec.*`), //! defines that parameterless `Nat`, and the constant's value equals it. //! The value is what old archives depend on; the model is where it is said. +//! In the model, a parameterless numeral of a wire module (`Uorc.Wire.*`) +//! is such a statement. A coder module (`Uorc.Codec.*`) is written by a +//! generator, so a numeral it names is an identity only where a wire module +//! states the same name and value (`Uorc.Wire.Coder`); any other is a fixed +//! figure the generator named, counted once at its definition. //! - a *fixed figure*: every other literal. Its site is listed in the register //! (`model/figures.toml`). A constant whose documentation names //! `Facet: ` attributes its sites to that facet record of @@ -52,6 +57,8 @@ use std::path::{Path, PathBuf}; use syn::visit::{self, Visit}; +pub mod derive; +pub mod native; pub mod sources; /// The register's path from the repository root. @@ -642,6 +649,21 @@ pub(crate) fn field<'a>(decl: &'a str, key: &str) -> Option<&'a str> { Some(rest[..end].trim()) } +/// The wire modules of the model (`src/Uorc/Wire/*.lex.tex`), as (module, path). +pub fn wire_modules(root: &Path) -> Result, Error> { + let dir = root.join("src/Uorc/Wire"); + let mut out = Vec::new(); + for e in std::fs::read_dir(&dir).map_err(|e| format!("{}: {e}", dir.display()))? { + let e = e.map_err(|e| e.to_string())?; + let f = e.file_name().to_string_lossy().to_string(); + if let Some(stem) = f.strip_suffix(".lex.tex") { + out.push((format!("Uorc.Wire.{stem}"), format!("src/Uorc/Wire/{f}"))); + } + } + out.sort(); + Ok(out) +} + /// The value a wire module gives a parameterless `Nat` definition. pub fn wire_value(root: &Path, target: &str) -> Result { let (module, name) = target @@ -799,15 +821,18 @@ pub fn check(root: &Path, register: Option<&Register>) -> Result let text = read(root, &f)?; sources::scan_js(&f, &text, &mut scan); } - for (module, path) in sources::model_modules(root, &reach)? { - let text = read(root, &path)?; - sources::scan_lean(&path, &module, &text, &mut scan); + let modules = sources::model_modules(root, &reach)?; + let stated = sources::stated(&wire_modules(root)?, |p| read(root, p))?; + for (module, path) in &modules { + let text = read(root, path)?; + sources::scan_lean(path, module, &text, &stated, &mut scan); } let mut out = Outcome { entries: entries(&scan), scan, ..Outcome::default() }; + out.rejected.extend(native::stale(root)); let performance = read(root, PERFORMANCE)?; let known = facets(&performance); if let Some(from) = parametric_release(&performance) { diff --git a/crates/figures/src/main.rs b/crates/figures/src/main.rs index 638b3e3f..4d3fe48b 100644 --- a/crates/figures/src/main.rs +++ b/crates/figures/src/main.rs @@ -1,11 +1,15 @@ -//! `figures [check|write|seed|report] [--root ]`: hold the numbers in +//! `figures [check|write|seed|report|native] [--root ]`: hold the numbers in //! uorc's implementation against the Prism model (see the library docs). use std::path::PathBuf; use std::process::ExitCode; fn main() -> ExitCode { - let mut args = std::env::args().skip(1); + let all: Vec = std::env::args().skip(1).collect(); + if all.first().is_some_and(|a| a == "derive") { + return derive(&all[1..]); + } + let mut args = all.into_iter(); let mut command = String::from("check"); let mut root = PathBuf::from("."); while let Some(a) = args.next() { @@ -14,7 +18,7 @@ fn main() -> ExitCode { Some(r) => root = PathBuf::from(r), None => return usage(), }, - "check" | "write" | "seed" | "report" => command = a, + "check" | "write" | "seed" | "report" | "native" => command = a, _ => return usage(), } } @@ -29,12 +33,19 @@ fn main() -> ExitCode { } fn usage() -> ExitCode { - eprintln!("usage: figures [check|write|seed|report] [--root ]"); + eprintln!("usage: figures [check|write|seed|report|native] [--root ]"); ExitCode::from(2) } fn run(command: &str, root: &std::path::Path) -> Result { match command { + "native" => { + figures::native::write(root)?; + for (out, src) in figures::native::GENERATED { + println!("figures: generated {out} from {src}"); + } + Ok(ExitCode::SUCCESS) + } "write" | "seed" => { let out = figures::write(root, command == "seed")?; print!("{}", figures::summary(&out)); @@ -66,3 +77,68 @@ fn run(command: &str, root: &std::path::Path) -> Result { } } } + +/// `figures derive [--dry] …`: restate the literals +/// of native files that are quantities of their domains as the model's +/// quantities (see `figures::derive`). +fn derive(args: &[String]) -> ExitCode { + let dry = args.iter().any(|a| a == "--dry"); + let lines = args.iter().any(|a| a == "--lines"); + let rest: Vec = args + .iter() + .filter(|a| *a != "--dry" && *a != "--lines") + .cloned() + .collect(); + let Some((generated, files)) = rest.split_first() else { + eprintln!("usage: figures derive [--dry] ..."); + return ExitCode::from(2); + }; + match figures::derive::rewrite( + std::path::Path::new("."), + generated, + files, + &["uorc", "uorc-wasm"], + dry, + ) { + Ok(r) => { + for (f, n) in &r.restated { + println!("figures: {f}: {n} literals restated as model quantities"); + } + if r.dropped > 0 { + println!( + "figures: {} placed literals kept (no type view the compiler admits)", + r.dropped + ); + } + if lines { + for (f, placed) in &r.placed { + for (l, v, q) in placed { + println!("{f}:{l} {v} -> {q}"); + } + } + for (f, left) in &r.left { + for (l, v, sc) in left { + println!("{f}:{l} {v} [{sc}]"); + } + } + } + for (f, res) in &r.residue { + let mut v: Vec<_> = res.iter().collect(); + v.sort_by(|a, b| b.1.cmp(a.1)); + let total: u64 = res.values().sum(); + println!("figures: {f}: {total} literals left; by value and domains in scope:"); + for ((val, scope), n) in v.iter().take(40) { + println!( + " {val:>12} {n:>4} {}", + if scope.is_empty() { "(none)" } else { scope } + ); + } + } + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("figures: {e}"); + ExitCode::FAILURE + } + } +} diff --git a/crates/figures/src/native.rs b/crates/figures/src/native.rs new file mode 100644 index 00000000..5e22021f --- /dev/null +++ b/crates/figures/src/native.rs @@ -0,0 +1,605 @@ +//! Native modules generated from the wire model. +//! +//! A wire module of the model (`Uorc.Codec.*`) states the coder's named +//! quantities: each a parameterless `Nat` whose body is a numeral (a format +//! identity: an extent, a field width) or an expression over other named +//! quantities, and each constant table a parameterless `Bytes`. The native +//! implementation reads those quantities from a Rust module generated here +//! from the model's source, so it states none of them itself: the generated +//! file carries `// @generated by \`figures native\` from `, and the +//! figures check regenerates it and rejects a copy that differs, so the +//! native values are always the model's. +//! +//! The generated module holds every quantity once, as `u128` with the body the +//! model gives it, and views of it for the integer types the native code works +//! in (a view lists the quantities whose value the type holds), plus `bits`, +//! the base-two logarithm of each power-of-two quantity (a shift by it is a +//! rescale by the quantity), derived by `trailing_zeros`. + +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::path::Path; + +/// The generated native modules: (output, model source). +pub const GENERATED: [(&str, &str); 8] = [ + ( + "crates/uorc/src/model/framing.rs", + "src/Uorc/Search/FramingOrder.lex.tex", + ), + ( + "crates/uorc/src/model/frame.rs", + "src/Uorc/Wire/Frame.lex.tex", + ), + ( + "crates/uorc/src/model/neuromorphic.rs", + "src/Uorc/Neuromorphic.lex.tex", + ), + ( + "crates/uorc/src/model/ncm.rs", + "client/src/Uorc/Codec/NcmEncode.lex.tex", + ), + ( + "crates/uorc/src/model/archive.rs", + "client/src/Uorc/Codec/Archive.lex.tex", + ), + ( + "crates/uorc/src/model/x86.rs", + "client/src/Uorc/Codec/X86.lex.tex", + ), + ( + "crates/uorc/src/model/graph.rs", + "src/Uorc/Wire/GraphEmit.lex.tex", + ), + ( + "crates/uorc/src/model/lz.rs", + "client/src/Uorc/Codec/LzDecode.lex.tex", + ), +]; + +/// The tool named on a generated file's first line. +pub const TOOL: &str = "`figures native`"; + +/// A body of a named quantity. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Expr { + /// A numeral. + Num(u128), + /// Another named quantity. + Name(String), + /// An operation on two. + Op(Op, Box, Box), +} + +/// The operations a quantity's body uses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Op { + /// `a + b`. + Add, + /// `prim subtract a b` (a >= b in every body the model states). + Sub, + /// `prim multiply a b`. + Mul, + /// `prim quotient a b 0`. + Div, + /// `prim remainder a b 0`. + Rem, + /// `pow2 b` (`a` is 1): `a` doubled `b` times. + Shl, +} + +/// One definition of a wire module the generator carries. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Def { + /// A named quantity. + Nat(Expr), + /// A constant table. + Bytes(Vec), +} + +fn field<'a>(decl: &'a str, key: &str) -> Option<&'a str> { + crate::field(decl, key) +} + +/// The parameterless `Nat` and `Bytes` definitions of a module's source, in +/// order; a body the generator does not read (a call, a match) is left out. +pub fn definitions(text: &str) -> Vec<(String, Def)> { + let mut out = Vec::new(); + for decl in text.split("definition{").skip(1) { + let decl = decl.split("\n}").next().unwrap_or(decl); + if !decl.contains("parameters: [],") { + continue; + } + let (Some(name), Some(result)) = (field(decl, "name"), field(decl, "result")) else { + continue; + }; + let Some(at) = decl.find("body: ") else { + continue; + }; + let rest = &decl[at + 6..]; + let body = match rest.find(",\n ") { + Some(e) => &rest[..e], + // the one-line form: `definition{name: n, …, body: b}` + None => rest + .lines() + .next() + .unwrap_or(rest) + .trim_end() + .trim_end_matches('}'), + } + .trim(); + let def = match result { + "Nat" => parse_expr(body).map(Def::Nat), + "Bytes" => hex(body).map(Def::Bytes), + _ => None, + }; + if let Some(d) = def { + out.push((name.to_string(), d)); + } + } + out +} + +fn hex(s: &str) -> Option> { + let h = s.strip_prefix("0x")?; + if h.len() % 2 != 0 || !h.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + (0..h.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&h[i..i + 2], 16).ok()) + .collect() +} + +fn tokens(s: &str) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + for c in s.chars() { + if c == '(' || c == ')' || c == '+' || c == ':' || c.is_whitespace() { + if !cur.is_empty() { + out.push(std::mem::take(&mut cur)); + } + if !c.is_whitespace() { + out.push(c.to_string()); + } + } else { + cur.push(c); + } + } + if !cur.is_empty() { + out.push(cur); + } + out +} + +/// Parse a quantity's body: a numeral, `(name)`, `(a + b)`, or +/// `(prim subtract|multiply|quotient|remainder a b [0] : Nat)`. +pub fn parse_expr(s: &str) -> Option { + let t = tokens(s); + let mut i = 0; + let e = expr(&t, &mut i)?; + (i == t.len()).then_some(e) +} + +fn expr(t: &[String], i: &mut usize) -> Option { + let tok = t.get(*i)?; + *i += 1; + if let Ok(n) = tok.parse::() { + return Some(Expr::Num(n)); + } + if tok != "(" { + // a bare name + return (tok.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) + && tok.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')) + .then(|| Expr::Name(tok.clone())); + } + let head = t.get(*i)?.clone(); + let e = if head == "prim" { + *i += 1; + let op = match t.get(*i)?.as_str() { + "subtract" => Op::Sub, + "multiply" => Op::Mul, + "quotient" => Op::Div, + "remainder" => Op::Rem, + _ => return None, + }; + *i += 1; + let a = expr(t, i)?; + let b = expr(t, i)?; + if matches!(op, Op::Div | Op::Rem) { + // the value at a zero divisor: the model's bodies give 0 and never divide by 0 + if t.get(*i)? != "0" { + return None; + } + *i += 1; + } + if t.get(*i)? != ":" || t.get(*i + 1)? != "Nat" { + return None; + } + *i += 2; + Expr::Op(op, Box::new(a), Box::new(b)) + } else if head == "pow2" && t.get(*i + 1).is_some_and(|x| x != ")") { + // the model's `pow2` (two to a power) + *i += 1; + let b = expr(t, i)?; + Expr::Op(Op::Shl, Box::new(Expr::Num(1)), Box::new(b)) + } else if head != "(" + && head.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + && t.get(*i + 1).is_some_and(|x| x == ")") + { + *i += 1; + Expr::Name(head) + } else { + let a = expr(t, i)?; + if t.get(*i)? != "+" { + return None; + } + *i += 1; + let b = expr(t, i)?; + Expr::Op(Op::Add, Box::new(a), Box::new(b)) + }; + if t.get(*i)? != ")" { + return None; + } + *i += 1; + Some(e) +} + +/// The value of a body over the values known so far. +pub fn value(e: &Expr, known: &BTreeMap) -> Option { + match e { + Expr::Num(n) => Some(*n), + Expr::Name(n) => known.get(n).copied(), + Expr::Op(op, a, b) => { + let (a, b) = (value(a, known)?, value(b, known)?); + match op { + Op::Add => a.checked_add(b), + Op::Sub => a.checked_sub(b), + Op::Mul => a.checked_mul(b), + Op::Div => a.checked_div(b), + Op::Rem => a.checked_rem(b), + Op::Shl => u32::try_from(b) + .ok() + .filter(|b| *b < u128::BITS) + .map(|b| a << b), + } + } + } +} + +fn rust(e: &Expr) -> String { + match e { + Expr::Num(n) => n.to_string(), + Expr::Name(n) => n.clone(), + Expr::Op(op, a, b) => { + let o = match op { + Op::Add => "+", + Op::Sub => "-", + Op::Mul => "*", + Op::Div => "/", + Op::Rem => "%", + Op::Shl => "<<", + }; + format!("({} {o} {})", rust(a), rust(b)) + } + } +} + +/// The integer views: (type, largest value it holds). `usize` is held to 32 +/// bits, the narrowest target the client builds (wasm32). +const VIEWS: [(&str, u128); 9] = [ + ("u8", u8::MAX as u128), + ("u16", u16::MAX as u128), + ("u32", u32::MAX as u128), + ("u64", u64::MAX as u128), + ("usize", u32::MAX as u128), + ("i16", i16::MAX as u128), + ("i32", i32::MAX as u128), + ("i64", i64::MAX as u128), + ("i128", i128::MAX as u128), +]; + +/// A named quantity: name, body, value. +pub type Quantity = (String, Expr, u128); +/// A constant table: name, bytes. +pub type Table = (String, Vec); + +/// The named quantities of a module's source, each with its body and value, +/// and its constant tables. Besides the quantities the model defines, each +/// extent it states as a numeral brings the characteristic quantities of its +/// domain the model's own pass derives (`client/gen/domains.py`): its last +/// value, its half (over the module's `radix`) and the half's last value, +/// named as that pass names them. +pub fn quantities(text: &str) -> (Vec, Vec) { + let mut tables = Vec::new(); + let mut bodies = Vec::new(); + for (name, def) in definitions(text) { + match def { + Def::Nat(e) => bodies.push((name, e)), + Def::Bytes(b) => tables.push((name, b)), + } + } + // a body may read a quantity the module defines after it: evaluate to a fixpoint + let mut known = BTreeMap::new(); + loop { + let before = known.len(); + for (name, e) in &bodies { + if !known.contains_key(name) { + if let Some(v) = value(e, &known) { + known.insert(name.clone(), v); + } + } + } + if known.len() == before { + break; + } + } + let mut nats: Vec = bodies + .into_iter() + .filter_map(|(n, e)| known.get(&n).map(|v| (n, e, *v))) + .collect(); + let radix = known.get(RADIX).copied(); + let extents: Vec<(String, u128)> = nats + .iter() + .filter(|(_, e, v)| matches!(e, Expr::Num(_)) && *v > 2) + .map(|(n, _, v)| (n.clone(), *v)) + .collect(); + let name = |e: &str| Box::new(Expr::Name(e.to_string())); + let one = || Box::new(Expr::Num(1)); + for (q, v) in extents { + let mut add = |n: String, e: Expr, x: u128| { + if x > 1 && !known.contains_key(&n) { + known.insert(n.clone(), x); + nats.push((n, e, x)); + } + }; + add( + format!("{q}Last"), + Expr::Op(Op::Sub, name(&q), one()), + v - 1, + ); + if let Some(r) = radix.filter(|r| *r > 1 && v % *r == 0) { + let half = format!("{q}Half"); + add( + half.clone(), + Expr::Op(Op::Div, name(&q), name(RADIX)), + v / r, + ); + add( + format!("{q}HalfLast"), + Expr::Op(Op::Sub, name(&half), one()), + v / r - 1, + ); + } + } + (nats, tables) +} + +/// Each table read as big-endian cells of 2, 4 and 8 bytes (each width that +/// divides it): (table, width, cells). +pub fn table_cells(tables: &[(String, Vec)]) -> Vec<(String, usize, Vec)> { + let mut out = Vec::new(); + for (name, b) in tables { + for w in [2usize, 4, 8] { + if b.len() % w == 0 && b.len() > w { + let vs = b + .chunks(w) + .map(|c| c.iter().fold(0u128, |a, x| (a << 8) | u128::from(*x))) + .collect(); + out.push((name.clone(), w, vs)); + } + } + } + out +} + +/// The module's binary radix (the coder makes one decision per step). +pub const RADIX: &str = "radix"; + +/// The model's selectors: a one-parameter `Nat` definition whose body is a +/// `match` from each constructor to a numeral (as `opcode` maps each +/// instruction to its code). Each is (definition, [(constructor, value)]). +pub fn selectors(text: &str) -> Vec<(String, Vec<(String, u128)>)> { + let mut out = Vec::new(); + for decl in text.split("definition{").skip(1) { + let decl = decl.split("\n}").next().unwrap_or(decl); + let (Some(name), Some("Nat")) = (field(decl, "name"), field(decl, "result")) else { + continue; + }; + let Some(params) = decl + .split("parameters: [") + .nth(1) + .and_then(|r| r.split(']').next()) + else { + continue; + }; + if params.is_empty() || params.contains(',') { + continue; + } + let Some(arms) = decl.split("body: (match ").nth(1) else { + continue; + }; + let mut cases = Vec::new(); + let mut whole = true; + for arm in arms.split("\n | ").skip(1) { + let Some((pat, val)) = arm.split_once(" => ") else { + whole = false; + break; + }; + let ctor = pat.split_whitespace().next().unwrap_or(""); + let ctor = ctor.rsplit('.').next().unwrap_or(ctor); + match val.trim_end().trim_end_matches(')').parse::() { + Ok(v) if !ctor.is_empty() => cases.push((ctor.to_string(), v)), + _ => { + whole = false; + break; + } + } + } + if whole && !cases.is_empty() { + out.push((name.to_string(), cases)); + } + } + out +} + +/// The Rust module generated from a wire module's source. +pub fn generate(source: &str, text: &str) -> String { + let module = source + .trim_start_matches("client/src/") + .trim_start_matches("src/") + .trim_end_matches(".lex.tex") + .replace('/', "."); + let (nats, tables) = quantities(text); + let mut s = String::new(); + let _ = writeln!(s, "// @generated by {TOOL} from {source}; do not edit."); + let _ = writeln!( + s, + "//! The named quantities and constant tables of `{module}`, as the model states them.\n//!\n//! Each quantity is the model's body over the others; a view module per\n//! integer type lists those the type holds, and [`bits`] the base-two\n//! logarithm of each power of two." + ); + let _ = writeln!(s, "#![allow(non_upper_case_globals, non_snake_case, dead_code, unused_parens, clippy::all, clippy::pedantic)]\n"); + for (name, e, _) in &nats { + let _ = writeln!( + s, + "/// `{module}::{name}`.\npub const {name}: u128 = {};", + rust(e) + ); + } + for (name, b) in &tables { + let bytes: Vec = b.iter().map(|x| format!("{x:#04x}")).collect(); + let _ = writeln!( + s, + "/// `{module}::{name}`.\npub const {name}: [u8; {}] = [{}];", + b.len(), + bytes.join(", ") + ); + } + let cells = table_cells(&tables); + if !cells.is_empty() { + let _ = writeln!( + s, + "\n/// The `n` big-endian cells of `w` bytes of a table.\nconst fn cells(b: &[u8], w: usize) -> [u128; N] {{\n let mut o = [0u128; N];\n let mut i = 0;\n while i < N {{\n let mut j = 0;\n while j < w {{\n o[i] = (o[i] << u8::BITS) | b[i * w + j] as u128;\n j += 1;\n }}\n i += 1;\n }}\n o\n}}" + ); + for (name, w, vs) in &cells { + let _ = writeln!( + s, + "/// `{module}::{name}` read as cells of {w} bytes.\npub const {name}Cells{w}: [u128; {n}] = cells::<{n}>(&{name}, {w});", + n = vs.len() + ); + } + } + for (ty, max) in VIEWS { + let _ = writeln!(s, "\n/// The quantities a `{ty}` holds.\npub mod {ty} {{"); + for (name, _, v) in &nats { + if v <= &max { + let _ = writeln!(s, " pub const {name}: {ty} = super::{name} as {ty};"); + } + } + for (name, w, vs) in &cells { + if vs.iter().all(|v| v <= &max) { + let n = vs.len(); + let _ = writeln!( + s, + " pub const {name}Cells{w}: [{ty}; {n}] = {{\n let c = super::{name}Cells{w};\n let mut o = [0; {n}];\n let mut i = 0;\n while i < {n} {{\n o[i] = c[i] as {ty};\n i += 1;\n }}\n o\n }};" + ); + } + } + let _ = writeln!(s, "\n /// The base-two logarithm of each power-of-two quantity, as a `{ty}`.\n pub mod bits {{"); + for (name, _, v) in &nats { + if v.is_power_of_two() { + let _ = writeln!(s, " pub const {name}: {ty} = super::super::{name}.trailing_zeros() as {ty};"); + } + } + let _ = writeln!(s, " }}\n}}"); + } + let _ = writeln!( + s, + "\n/// The base-two logarithm of each power-of-two quantity.\npub mod bits {{" + ); + for (name, _, v) in &nats { + if v.is_power_of_two() { + let _ = writeln!( + s, + " pub const {name}: u32 = super::{name}.trailing_zeros();" + ); + } + } + let _ = writeln!(s, "}}"); + for (name, cases) in selectors(text) { + let _ = writeln!( + s, + "\n/// `{module}::{name}` of each constructor, as the model maps it.\npub mod {name} {{" + ); + for (ty, max) in VIEWS { + if cases.iter().all(|(_, v)| *v <= max) { + let _ = writeln!(s, " /// As a `{ty}`.\n pub mod {ty} {{"); + for (c, v) in &cases { + let _ = writeln!(s, " pub const {c}: {ty} = {v};"); + } + let _ = writeln!(s, " }}"); + } + } + let _ = writeln!(s, "}}"); + } + s +} + +/// Regenerate every native module (`figures native`). +pub fn write(root: &Path) -> Result<(), crate::Error> { + for (out, src) in GENERATED { + let text = std::fs::read_to_string(root.join(src)).map_err(|e| format!("{src}: {e}"))?; + let path = root.join(out); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("{out}: {e}"))?; + } + std::fs::write(&path, generate(src, &text)).map_err(|e| format!("{out}: {e}"))?; + } + Ok(()) +} + +/// The generated modules that differ from their source's generation. +pub fn stale(root: &Path) -> Vec { + let mut out = Vec::new(); + for (file, src) in GENERATED { + // A missing module is the compiler's to reject (`mod model` names it). + if !root.join(file).exists() { + continue; + } + let want = std::fs::read_to_string(root.join(src)).map(|t| generate(src, &t)); + let have = std::fs::read_to_string(root.join(file)); + match (want, have) { + (Ok(w), Ok(h)) if w == h => {} + (Err(e), _) => out.push(format!("{src}: {e}")), + _ => out.push(format!( + "{file} is not the generation of {src}; regenerate it with `just figures-native`" + )), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bodies_parse_and_evaluate() { + let text = "definition{\n name: r,\n parameters: [],\n result: Nat,\n body: 4096,\n executable: true,\n axioms: []\n}\n\ + definition{\n name: h,\n parameters: [],\n result: Nat,\n body: (prim quotient (r) (two) 0 : Nat),\n executable: true,\n axioms: []\n}\n\ + definition{\n name: two,\n parameters: [],\n result: Nat,\n body: 2,\n executable: true,\n axioms: []\n}\n\ + definition{\n name: z,\n parameters: [],\n result: Nat,\n body: (prim quotient (r) (none) 0 : Nat),\n executable: true,\n axioms: []\n}\n\ + definition{\n name: l,\n parameters: [],\n result: Nat,\n body: (prim subtract ((r) + (r)) 1 : Nat),\n executable: true,\n axioms: []\n}\n\ + definition{\n name: t,\n parameters: [],\n result: Bytes,\n body: 0x0102,\n executable: true,\n axioms: []\n}"; + let d = definitions(text); + assert_eq!(d.len(), 6); + let g = generate("client/src/Uorc/Codec/X.lex.tex", text); + assert!(g.starts_with( + "// @generated by `figures native` from client/src/Uorc/Codec/X.lex.tex;" + )); + assert!(g.contains("pub const l: u128 = ((r + r) - 1);")); + assert!(g.contains("pub const t: [u8; 2] = [0x01, 0x02];")); + // h reads two before the model defines it; z reads a quantity the module does not define + assert!(g.contains("pub const h: u128 = (r / two);")); + assert!(!g.contains("pub const z")); + assert!(g.contains(" pub const r: u32 = super::r.trailing_zeros();")); + } +} diff --git a/crates/figures/src/sources.rs b/crates/figures/src/sources.rs index 8299adef..46b605c1 100644 --- a/crates/figures/src/sources.rs +++ b/crates/figures/src/sources.rs @@ -2,10 +2,10 @@ //! exported from: their scope, read from the factory graph, and their //! numerals. -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; -use crate::{Error, Scan, Site, WIRE_MODULES}; +use crate::{Error, Scan, Site}; /// A `closure:ROOTS@DIRS` input of the factory graph (`scripts/factory.mjs` /// reads it the same way): ROOTS are module names, `Prefix.*` names every @@ -352,23 +352,62 @@ pub fn scan_js(file: &str, text: &str, scan: &mut Scan) { } } +/// The format identities the wire model states: each parameterless `Nat` +/// definition of a `Uorc.Wire.*` module whose body is a numeral, by name. +pub type Stated = BTreeMap>; + +/// Read the identities the wire modules among `modules` state. +pub fn stated( + modules: &[(String, String)], + read: impl Fn(&str) -> Result, +) -> Result { + let mut out = Stated::new(); + for (module, path) in modules { + if !module.starts_with("Uorc.Wire.") { + continue; + } + let text = read(path)?; + for decl in text.split("definition{").skip(1) { + let decl = decl.split("\n}").next().unwrap_or(decl); + let (Some(name), Some(v)) = ( + crate::field(decl, "name"), + crate::field(decl, "body").and_then(|b| b.parse::().ok()), + ) else { + continue; + }; + if decl.contains("parameters: [],") && crate::field(decl, "result") == Some("Nat") { + out.entry(name.to_string()).or_default().insert(v); + } + } + } + Ok(out) +} + /// Scan a LexLean module's numerals inside its definitions (theorems state /// what a figure does; they fix none). A parameterless `Nat` definition of -/// a wire module whose body is a numeral is the model naming a format -/// identity, and is not a fixed figure. -pub fn scan_lean(file: &str, module: &str, text: &str, scan: &mut Scan) { +/// a wire module (`Uorc.Wire.*`) whose body is a numeral is the model naming +/// a format identity, and is not a fixed figure. A coder module +/// (`Uorc.Codec.*`) is written by a generator, so its named numerals are +/// identities only where the wire model states them ([`stated`]: a wire +/// module defines the same name with the same value); any other is a fixed +/// figure the generator named, counted once at its definition. +pub fn scan_lean(file: &str, module: &str, text: &str, stated: &Stated, scan: &mut Scan) { scan.files += 1; - let wire = WIRE_MODULES.iter().any(|p| module.starts_with(p)); + let wire = module.starts_with("Uorc.Wire."); + let coder = module.starts_with("Uorc.Codec."); for decl in text.split("definition{").skip(1) { let decl = decl.split("\n}").next().unwrap_or(decl); let name = crate::field(decl, "name") .unwrap_or("(definition)") .to_string(); - let numeral_body = crate::field(decl, "body").is_some_and(|b| b.parse::().is_ok()); - if wire - && numeral_body + let body = crate::field(decl, "body").and_then(|b| b.parse::().ok()); + let named = body.is_some() && decl.contains("parameters: [],") - && crate::field(decl, "result") == Some("Nat") + && crate::field(decl, "result") == Some("Nat"); + if named + && (wire + || (coder + && body.is_some_and(|v| stated.get(&name).is_some_and(|vs| vs.contains(&v))))) { continue; } @@ -462,7 +501,7 @@ mod tests { fn lean_numerals_inside_definitions_and_wire_names() { let src = "definition{name: v, parameters: [], result: Nat, body: 2}\n\ndefinition{\n name: f,\n parameters: [x : Nat],\n result: Nat,\n body: (prim add x 17 : Nat)\n}\n\ntheorem{\n name: t,\n statement: (f 3 = 20)\n}\n"; let mut s = Scan::default(); - scan_lean("w.lex.tex", "Uorc.Wire.Frame", src, &mut s); + scan_lean("w.lex.tex", "Uorc.Wire.Frame", src, &Stated::new(), &mut s); let got: Vec<_> = s .sites .iter() @@ -470,7 +509,7 @@ mod tests { .collect(); assert_eq!(got, [("f", "17")]); let mut s = Scan::default(); - scan_lean("p.lex.tex", "Uorc.Performance", src, &mut s); + scan_lean("p.lex.tex", "Uorc.Performance", src, &Stated::new(), &mut s); assert_eq!( s.sites.len(), 2, @@ -478,6 +517,29 @@ mod tests { ); } + #[test] + fn a_coder_modules_named_numeral_is_an_identity_only_where_the_wire_model_states_it() { + let src = "definition{name: v, parameters: [], result: Nat, body: 2}\n\ndefinition{name: w, parameters: [], result: Nat, body: 9}\n"; + let stated: Stated = [ + ("v".to_string(), [2u128].into_iter().collect()), + ("w".to_string(), [8u128].into_iter().collect()), + ] + .into_iter() + .collect(); + let mut s = Scan::default(); + scan_lean("c.lex.tex", "Uorc.Codec.Ncm", src, &stated, &mut s); + let got: Vec<_> = s + .sites + .iter() + .map(|s| (s.item.as_str(), s.value.as_str())) + .collect(); + assert_eq!( + got, + [("w", "9")], + "w is stated with another value, so it is the generator's figure" + ); + } + #[test] fn closure_inputs_parse_and_name_patterns() { let c = Closure::parse("Uorc.Integrity.*"); diff --git a/crates/figures/tests/repository.rs b/crates/figures/tests/repository.rs index 6405e5aa..8cb50aba 100644 --- a/crates/figures/tests/repository.rs +++ b/crates/figures/tests/repository.rs @@ -43,7 +43,13 @@ fn a_planted_figure_is_rejected_in_every_kind_of_source_uc_fig_01() { match kind { "rs" => figures::scan_source(file, &planted, &mut scan).unwrap(), "js" => figures::sources::scan_js(file, &planted, &mut scan), - _ => figures::sources::scan_lean(file, "Uorc.Codec.Table", &planted, &mut scan), + _ => figures::sources::scan_lean( + file, + "Uorc.Codec.Table", + &planted, + &figures::sources::Stated::new(), + &mut scan, + ), } assert!( scan.sites.iter().any(|s| s.value == "4093"), diff --git a/crates/uorc-wasm/src/lib.rs b/crates/uorc-wasm/src/lib.rs index 3c48476a..5264509f 100644 --- a/crates/uorc-wasm/src/lib.rs +++ b/crates/uorc-wasm/src/lib.rs @@ -36,16 +36,27 @@ pub extern "C" fn window_reset() { }); } +/// The status an export returns: its position in this list, which is the +/// order of the page's `ERRORS` (web/uorc.js reads a status as that index). +#[repr(i32)] +enum Status { + Ok, + Budget, + Overflow, + Decode, + Mismatch, +} + /// Operation succeeded; the result is in the output buffer. -pub const OK: i32 = 0; +pub const OK: i32 = Status::Ok as i32; /// See [`uorc::Error::Budget`]. -pub const BUDGET: i32 = 1; +pub const BUDGET: i32 = Status::Budget as i32; /// See [`uorc::Error::Overflow`]. -pub const OVERFLOW: i32 = 2; +pub const OVERFLOW: i32 = Status::Overflow as i32; /// See [`uorc::Error::Decode`]. -pub const DECODE: i32 = 3; +pub const DECODE: i32 = Status::Decode as i32; /// See [`uorc::Error::Mismatch`]. -pub const MISMATCH: i32 = 4; +pub const MISMATCH: i32 = Status::Mismatch as i32; fn resize(buffer: &RefCell>, len: usize) -> *mut u8 { let mut buffer = buffer.borrow_mut(); @@ -226,19 +237,18 @@ fn read_entries(bytes: &[u8]) -> Result, uorc::Error> { Ok(head) } fn word(&mut self) -> Result { - Ok(u32::from_le_bytes(self.take(4)?.try_into().expect("4 bytes")) as usize) + Ok(u32::from_le_bytes( + self.take(std::mem::size_of::())? + .try_into() + .expect("4 bytes"), + ) as usize) } } let mut c = Cursor(bytes); let count = c.word()?; let mut entries = Vec::new(); for _ in 0..count { - let kind = match c.take(1)?[0] { - 0 => Kind::File, - 1 => Kind::Executable, - 2 => Kind::Directory, - _ => return Err(uorc::Error::Decode), - }; + let kind = Kind::of_code(c.take(1)?[0]).ok_or(uorc::Error::Decode)?; let len = c.word()?; let path = String::from_utf8(c.take(len)?.to_vec()).map_err(|_| uorc::Error::Decode)?; let len = c.word()?; @@ -252,14 +262,9 @@ fn read_entries(bytes: &[u8]) -> Result, uorc::Error> { } fn write_entries(entries: &[uorc::tree::Entry]) -> Vec { - use uorc::tree::Kind; let mut out = (entries.len() as u32).to_le_bytes().to_vec(); for entry in entries { - out.push(match entry.kind { - Kind::File => 0, - Kind::Executable => 1, - Kind::Directory => 2, - }); + out.push(entry.kind.code()); out.extend((entry.path.len() as u32).to_le_bytes()); out.extend(entry.path.as_bytes()); out.extend((entry.data.len() as u32).to_le_bytes()); @@ -301,11 +306,17 @@ impl<'a> Fields<'a> { Ok(out) } fn u32(&mut self) -> Result { - Ok(u32::from_le_bytes(self.take(4)?.try_into().expect("4 bytes")) as usize) + Ok(u32::from_le_bytes( + self.take(std::mem::size_of::())? + .try_into() + .expect("4 bytes"), + ) as usize) } fn u64(&mut self) -> Result { Ok(u64::from_le_bytes( - self.take(8)?.try_into().expect("8 bytes"), + self.take(std::mem::size_of::())? + .try_into() + .expect("8 bytes"), )) } fn len(&mut self) -> Result { @@ -577,20 +588,19 @@ fn read_listing(bytes: &[u8]) -> Result, uo Ok(out) }; let word = |b: &[u8]| u32::from_le_bytes(b.try_into().expect("4 bytes")) as usize; - let count = word(take(4)?); + let count = word(take(std::mem::size_of::())?); let mut out = Vec::new(); for _ in 0..count { - let kind = match take(1)?[0] { - 0 => Kind::File, - 1 => Kind::Executable, - 2 => Kind::Directory, - _ => return Err(uorc::Error::Decode), - }; - let len = word(take(4)?); + let kind = Kind::of_code(take(1)?[0]).ok_or(uorc::Error::Decode)?; + let len = word(take(std::mem::size_of::())?); let path = std::str::from_utf8(take(len)?) .map_err(|_| uorc::Error::Decode)? .to_owned(); - let length = u64::from_le_bytes(take(8)?.try_into().expect("8 bytes")); + let length = u64::from_le_bytes( + take(std::mem::size_of::())? + .try_into() + .expect("8 bytes"), + ); out.push((path, kind, if kind == Kind::Directory { 0 } else { length })); } if at != bytes.len() { @@ -782,11 +792,7 @@ mod tests { ]; let mut listing = (entries.len() as u32).to_le_bytes().to_vec(); for e in &entries { - listing.push(match e.kind { - Kind::File => 0, - Kind::Executable => 1, - Kind::Directory => 2, - }); + listing.push(e.kind.code()); listing.extend((e.path.len() as u32).to_le_bytes()); listing.extend(e.path.as_bytes()); listing.extend((e.data.len() as u64).to_le_bytes()); diff --git a/crates/uorc/src/archive.rs b/crates/uorc/src/archive.rs index 7fd2b406..4e4e50ad 100644 --- a/crates/uorc/src/archive.rs +++ b/crates/uorc/src/archive.rs @@ -32,7 +32,8 @@ const ULZ_SUFFIX_HEX: &str = include_str!("linked-ulz-suffix.hex"); const NCM_SUFFIX_HEX: &str = include_str!("linked-ncm-suffix.hex"); /// Identity of the built-in standard basis (`Archive.basisIdentity`): the /// UORC-BASIS-V1 chain over its one root, the ulz and ncm decoder libraries. -pub const BASIS_ID: [u8; 32] = hex_literal(BASIS_ID_HEX); +/// Domain: len: integrityBytes +pub const BASIS_ID: [u8; crate::model::framing::usize::integrityBytes] = hex_literal(BASIS_ID_HEX); const LINKED_PREFIX: [u8; hex_len(LINKED_PREFIX_HEX)] = hex_literal(LINKED_PREFIX_HEX); const ULZ_SUFFIX: [u8; hex_len(ULZ_SUFFIX_HEX)] = hex_literal(ULZ_SUFFIX_HEX); const NCM_SUFFIX: [u8; hex_len(NCM_SUFFIX_HEX)] = hex_literal(NCM_SUFFIX_HEX); @@ -157,7 +158,8 @@ impl Era { Era::ALL.into_iter().find(|e| e.identity() == identity) } - fn identity(self) -> &'static [u8; 32] { + /// Domain: len: integrityBytes + fn identity(self) -> &'static [u8; crate::model::framing::usize::integrityBytes] { match self { Era::Current => &BASIS_ID, Era::V04 => &V04_BASIS_ID, @@ -325,6 +327,21 @@ fn profile_template(k: usize, x86: bool, era: Era) -> Option