Files
R8Forge/include/r8forge/r8veritas.hh
T
dsh 94868be24f Name the two geometry numbers the same way everywhere: cell_size, cell_argc
The cell width was CELL_SIZE on the C++ side, and the searcher's CellBit count
was CELL_ARGC.  Both now match what the code and the docs around them already
called them:

  * include/r8forge/r8asm.hh + src/r8asm.cc: CELL_SIZE -> cell_size
    (set_cell_size assigns this->cell_size, its parameter already had that
    name);
  * include/r8forge/r8veritas.hh: the template parameter CELL_ARGC ->
    cell_argc, 34 uses, so the searcher reads r8veritas<cell_argc>;
  * AGENTS.md says which name means what, and why the name .r8asm programs
    see is still _CELL_SIZE: that one belongs to the macro library, not to
    the C++ side, and changing it would rewrite every macro in asm/;
  * the cross check entry now says which ROT-8-viz is which: the author's fork
    with --cell/--mem, and the upstream starcells/ROT-8 tree in the workspace,
    whose geometry is compile time cell_size/mem_size -- it is 11 / 259 too
    now, and `rot8_test <tape>` against `r8forge_derive ... -1` still gives
    1322 1786 1600 5 94 127 on the hash tape.

All six self checks pass unchanged: 28729 character hash tape, synth_test 8/8,
both verify_ tapes, byte_op_test 65536/65536 for clb_mul and the rest of the
library, macro docs test green.
2026-11-07 12:23:42 +08:00

842 lines
27 KiB
C++

#ifndef R8VERITAS
#define R8VERITAS
// R8Veritas -- shortest program search over the rot-8 "sacrifice block":
//
// .tp s
// biz
// .tp b ; once per b in the mask
// set_1 / flb ; OR / XOR
// .tp s
// flb
// rnz
//
// A state is the whole truth table of the working cell: for every input
// combination, what the cell holds. Written as bit planes -- plane b is bit
// b of the cell, over all inputs -- one block becomes a handful of 64-bit
// operations:
//
// cond = plane[s]; plane[s] = 0;
// for b in mask: plane[b] |= cond (set_1)
// plane[b] ^= cond (flb)
//
// Search strategy:
// * only the input bits that influence the answer survive (the old
// compress_stat_space), so a plane is a 2^K bit truth table instead of
// 2^cell_argc, and the whole state is cell_argc * 2^K bits
// * forward BFS keeps every reachable state of depth < d plus the block
// that produced it
// * the last block is not searched forward. A block clears its own
// plane, so the goal can only be its target if goal[s] == 0; for each
// such block every preimage of the goal is generated and looked up in
// the BFS table. A hit is the shortest program, and "nothing below d,
// something at d" is a proof.
//
// The backward step enumerates 2^K values of the condition, so it is only
// used while K <= 3; above that the last layer is expanded forward like the
// others (still a lot cheaper than the old implementation).
#include <algorithm>
#include <array>
#include <bit>
#include <bitset>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iostream>
#include <map>
#include <optional>
#include <ostream>
#include <set>
#include <atomic>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_set>
#include <utility>
#include <vector>
template <int cell_argc> class r8veritas {
public:
using cell = uint8_t;
using stat = std::array<cell, (size_t(1) << cell_argc)>;
using stat_ref = const stat *;
using truthtable = std::pair<stat_ref, stat_ref>;
using op = std::function<cell(cell)>;
// one biz block
struct instruction {
uint8_t sacrifice = 0; // plane whose bit is tested and cleared
uint8_t mask = 0; // bit b set: plane b is a destination
bool or_mode = false; // true: set_1 (|), false: flb (^)
};
struct options {
int max_depth = 5; // longest program to look for
size_t max_states = 80'000'000; // memory guard
bool verbose = false;
};
// Searching for the shortest *tape* instead of the fewest layers: the
// weight of a block is what it assembles to
// 1 (biz) + 1 (flb) + 1 (rnz) + travel + sum(op cost)
// with travel = 2 * span(cell addresses of the sacrifice and the mask)
// (the pointer walks out and comes back) and op cost 1 for flb, 4 for
// set_1. The inter-block hop from the previous sacrifice back to this one
// is not in the model -- the emitter charges it afterwards.
struct cost_options {
std::array<int, cell_argc> addr{}; // cell address of each plane
int max_cost = 4096; // give up above this tape length
size_t max_states = 600'000'000;
unsigned threads = 0; // 0 = one worker per hardware thread
bool verbose = false;
};
struct cost_result {
bool found = false;
bool proven = false; // nothing shorter than `cost` exists
std::vector<instruction> program;
int cost = 0;
size_t states = 0;
double seconds = 0;
std::string message;
};
struct result {
bool found = false;
// true when every program shorter than program.size() was ruled out
bool proven_optimal = false;
std::vector<instruction> program;
size_t states = 0; // states kept by the BFS
int depth_reached = 0; // deepest layer fully expanded
double seconds = 0;
std::string message;
};
std::array<std::string, cell_argc> nicknames;
std::array<std::string, cell_argc> tp_paths;
void initialize_nicknames() {
for (int i = 0; i < cell_argc; i++)
nicknames[i] = "%" + std::to_string(i + 1);
}
void initialize_tp_paths() {
for (int i = 0; i < cell_argc; i++)
tp_paths[i] = ".tp " + nicknames[i];
}
// ---------------------------------------------------------------- states
stat_ref generate_empty_stat() {
stat arr{};
arr.fill(0);
return keep(arr);
}
truthtable generate_truthtable(const op &operation) {
stat in{}, out{};
for (size_t i = 0; i < (size_t(1) << cell_argc); i++) {
in[i] = cell(i);
out[i] = operation(cell(i));
}
return {keep(in), keep(out)};
}
// Build a truthtable straight from two tables (a synth block knows the
// target stat, it does not have a callable function).
truthtable make_truthtable(const stat &in, const stat &out) {
return {keep(in), keep(out)};
}
// Clears the input bits that never influence the answer, so the search
// starts from a canonical state.
truthtable compress_stat_space(const truthtable &raw) {
stat start = *raw.first;
for (int i = 0; i < cell_argc; i++) {
bool influences = false;
for (size_t j = 0; j < (size_t(1) << cell_argc); j++)
if ((*raw.second)[j] != (*raw.second)[j ^ (size_t(1) << i)])
influences = true;
if (!influences)
for (size_t j = 0; j < (size_t(1) << cell_argc); j++)
start[j] = cell(start[j] & ~(1u << i));
}
return {keep(start), raw.second};
}
// Applies a program with the reference semantics (one state at a time) and
// tells whether it lands on the target.
bool run_program(const truthtable &raw, const std::vector<instruction> &p,
bool verbose = false) const {
stat cur = *raw.first;
for (const auto &i : p) {
for (size_t j = 0; j < cur.size(); j++)
if (cur[j] & (1u << i.sacrifice)) {
cur[j] = cell(cur[j] & ~(1u << i.sacrifice));
for (int b = 0; b < cell_argc; b++)
if (i.mask & (1 << b))
cur[j] = i.or_mode ? cell(cur[j] | (1u << b))
: cell(cur[j] ^ (1u << b));
}
if (verbose) {
output_stat(cur);
std::cout << "\n";
}
}
return cur == *raw.second;
}
// ---------------------------------------------------------------- output
void output_stat(const stat &s) const {
for (auto v : s)
std::cout << std::bitset<cell_argc>(v).to_string() << " ";
}
void output_ins(const instruction &ins, std::ostream &os,
bool debug_output = true) const {
if (debug_output) {
os << "SACRIFICE: " << int(ins.sacrifice);
if (ins.mask) {
os << (ins.or_mode ? ", SET1: {" : ", FLIP: {");
bool first = true;
for (int b = 0; b < cell_argc; b++)
if (ins.mask & (1 << b)) {
if (!first)
os << ',';
os << b;
first = false;
}
os << '}';
}
os << ';';
return;
}
os << tp_paths[ins.sacrifice] << "\n";
os << "biz\n";
for (int b = 0; b < cell_argc; b++)
if (ins.mask & (1 << b)) {
os << '\t' << tp_paths[b] << "\n";
os << '\t' << (ins.or_mode ? "set_1" : "flb") << "\n";
}
os << '\t' << tp_paths[ins.sacrifice] << "\n";
os << "\tflb\n";
os << "rnz\n";
}
void print_program(const std::vector<instruction> &p, std::ostream &os,
bool debug_output = false) const {
for (const auto &i : p) {
output_ins(i, os, debug_output);
os << "\n";
}
}
// ---------------------------------------------------------------- search
cost_result solve_cost(const truthtable &raw, const cost_options &opt) {
cost_result r;
const auto t0 = std::chrono::steady_clock::now();
auto finish = [&]() {
r.seconds =
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0)
.count();
return r;
};
std::array<int, cell_argc> bit_of{};
int k = 0;
for (int i = 0; i < cell_argc; i++)
for (size_t j = 0; j < (size_t(1) << cell_argc); j++)
if ((*raw.second)[j] != (*raw.second)[j ^ (size_t(1) << i)]) {
bit_of[k++] = i;
break;
}
if (k > 6) {
r.message = "more than 6 relevant inputs";
return finish();
}
std::vector<size_t> full(size_t(1) << k, 0);
for (size_t j = 0; j < full.size(); j++)
for (int b = 0; b < k; b++)
if (j & (size_t(1) << b))
full[j] |= size_t(1) << bit_of[b];
switch (k) {
case 0:
return solve_cost_with<0>(raw, full, opt);
case 1:
return solve_cost_with<1>(raw, full, opt);
case 2:
return solve_cost_with<2>(raw, full, opt);
case 3:
return solve_cost_with<3>(raw, full, opt);
case 4:
return solve_cost_with<4>(raw, full, opt);
case 5:
return solve_cost_with<5>(raw, full, opt);
default:
return solve_cost_with<6>(raw, full, opt);
}
}
result solve(const truthtable &raw, const options &opt = {}) {
result r;
const auto t0 = std::chrono::steady_clock::now();
auto finish = [&]() {
r.seconds =
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0)
.count();
return r;
};
// which input bits matter, in compression order
std::array<int, cell_argc> bit_of{};
int k = 0;
for (int i = 0; i < cell_argc; i++) {
for (size_t j = 0; j < (size_t(1) << cell_argc); j++)
if ((*raw.second)[j] != (*raw.second)[j ^ (size_t(1) << i)]) {
bit_of[k++] = i;
break;
}
}
if (k > 6) {
r.message = "the answer depends on more than 6 inputs; the packed state "
"does not fit and the search would be hopeless anyway";
return finish();
}
// compressed index j -> index in the full truth table
std::vector<size_t> full(size_t(1) << k, 0);
for (size_t j = 0; j < full.size(); j++)
for (int b = 0; b < k; b++)
if (j & (size_t(1) << b))
full[j] |= size_t(1) << bit_of[b];
switch (k) {
case 0:
return solve_with<0>(raw, full, opt, r, finish);
case 1:
return solve_with<1>(raw, full, opt, r, finish);
case 2:
return solve_with<2>(raw, full, opt, r, finish);
case 3:
return solve_with<3>(raw, full, opt, r, finish);
case 4:
return solve_with<4>(raw, full, opt, r, finish);
case 5:
return solve_with<5>(raw, full, opt, r, finish);
default:
return solve_with<6>(raw, full, opt, r, finish);
}
}
private:
std::set<stat> pool;
stat_ref keep(const stat &s) { return &*pool.insert(s).first; }
// ---------------------------------------------------------------- engine
// K relevant inputs: every plane is a 2^K bit truth table, the whole state
// is cell_argc * 2^K bits packed into KEYW words.
template <int K> struct engine {
static constexpr int M = 1 << K; // bits per plane
static constexpr int KEYW = (cell_argc * M + 63) / 64;
static constexpr uint64_t PMASK =
(M >= 64) ? ~uint64_t(0) : ((uint64_t(1) << (M & 63)) - 1);
using key = std::array<uint64_t, KEYW>;
static uint64_t get(const key &k, int b) {
const int off = b * M;
return (k[off >> 6] >> (off & 63)) & PMASK;
}
static void put(key &k, int b, uint64_t v) {
const int off = b * M;
k[off >> 6] =
(k[off >> 6] & ~(PMASK << (off & 63))) | ((v & PMASK) << (off & 63));
}
static key zero() {
key k{};
return k;
}
static uint64_t cond(const key &k, const instruction &i) {
return get(k, i.sacrifice);
}
static key step(const key &k, const instruction &i) {
key n = k;
const uint64_t c = get(k, i.sacrifice);
put(n, i.sacrifice, 0);
for (int b = 0; b < cell_argc; b++)
if (i.mask & (1 << b))
put(n, b, i.or_mode ? (get(k, b) | c) : (get(k, b) ^ c));
return n;
}
static uint64_t hash(const key &k) {
uint64_t h = 0xcbf29ce484222325ULL;
for (int i = 0; i < KEYW; i++) {
h ^= k[i];
h *= 0x100000001b3ULL;
h ^= h >> 29;
h *= 0xbf58476d1ce4e5b9ULL;
h ^= h >> 32;
}
return h;
}
struct slot {
key k{};
key parent{};
uint16_t ins = 0xFFFF; // 0xFFFF free, 0xFFFE start of a program
};
struct table {
std::vector<slot> v;
uint64_t mask = 0;
size_t used = 0;
static constexpr uint16_t FREE = 0xFFFF, ROOT = 0xFFFE;
static uint64_t capacity_for(size_t n) {
uint64_t c = 1 << 12;
while (c * 3 < n * 4 + 4)
c <<= 1;
return c;
}
void init(uint64_t cap) {
v.assign(cap, slot{});
mask = cap - 1;
used = 0;
}
void grow() {
std::vector<slot> old = std::move(v);
init(old.size() * 2);
for (const auto &s : old)
if (s.ins != FREE)
insert(s.k, s.parent, s.ins);
}
bool insert(const key &k, const key &parent, uint16_t ins) {
uint64_t j = hash(k) & mask;
while (v[j].ins != FREE) {
if (v[j].k == k)
return false;
j = (j + 1) & mask;
}
v[j].k = k;
v[j].parent = parent;
v[j].ins = ins;
if (++used * 4 > (mask + 1) * 3)
grow();
return true;
}
const slot *find(const key &k) const {
uint64_t j = hash(k) & mask;
while (v[j].ins != FREE) {
if (v[j].k == k)
return &v[j];
j = (j + 1) & mask;
}
return nullptr;
}
};
};
template <int K>
cost_result solve_cost_with(const truthtable &raw,
const std::vector<size_t> &full,
const cost_options &opt) {
using E = engine<K>;
using key = typename E::key;
cost_result r;
if (K <= 0 || K > 6) {
r.message = "K out of range";
return r;
}
// ---- what one block weighs on the tape
const std::vector<instruction> insns = build_instructions();
std::vector<uint16_t> w(insns.size());
int wmax = 0;
for (size_t i = 0; i < insns.size(); i++) {
const instruction &in = insns[i];
int lo = opt.addr[in.sacrifice], hi = lo, cnt = 0;
for (int b = 0; b < cell_argc; b++)
if (in.mask & (1 << b)) {
cnt++;
lo = std::min(lo, opt.addr[b]);
hi = std::max(hi, opt.addr[b]);
}
// biz + flb + rnz, the walk out and back, then the ops themselves
w[i] = uint16_t(3 + 2 * (hi - lo) + cnt * (in.or_mode ? 4 : 1));
wmax = std::max<int>(wmax, w[i]);
}
// start = identity over the compressed inputs, goal = the target
key start = E::zero(), goal = E::zero();
for (size_t j = 0; j < full.size(); j++)
for (int b = 0; b < cell_argc; b++) {
if (j & (size_t(1) << b))
E::put(start, b, E::get(start, b) | (uint64_t(1) << j));
if ((*raw.second)[full[j]] & (1u << b))
E::put(goal, b, E::get(goal, b) | (uint64_t(1) << j));
}
// ---- split by first block and run the workers in parallel.
// A program's first block is unique, so the answers do not overlap; the
// workers only have to agree on the best cost found so far, which doubles
// as every other worker's bound.
const unsigned hw = std::thread::hardware_concurrency();
// One worker by default: splitting by first block duplicates the whole
// middle of the search (every prefix reaches it), which measured three to
// four times the work and sixteen gigabytes. opt.threads > 1 still runs
// the split, it is just not the default.
unsigned nthreads = opt.threads ? unsigned(opt.threads) : 1u;
if (nthreads < 1u)
nthreads = 1u;
std::atomic<int> next_first{0};
std::atomic<int> best_done{0x7FFFFFFF};
std::mutex best_mutex;
std::vector<instruction> best_prog;
std::atomic<unsigned long long> states_total{0};
std::atomic<bool> budget_hit{false};
auto record = [&](int cost, std::vector<instruction> prog) {
std::lock_guard<std::mutex> guard(best_mutex);
if (cost < best_done.load()) {
best_done.store(cost);
best_prog = std::move(prog);
}
};
auto worker = [&]() {
std::vector<key> keys;
std::vector<uint16_t> dists;
std::vector<uint32_t> pars;
std::vector<uint16_t> hows;
std::vector<int32_t> tab;
size_t tabmask = (1u << 16) - 1;
tab.assign(tabmask + 1, -1);
auto find_id = [&](const key &k) -> int32_t {
size_t j = size_t(E::hash(k)) & tabmask;
while (tab[j] >= 0) {
if (keys[size_t(tab[j])] == k)
return tab[j];
j = (j + 1) & tabmask;
}
return -1;
};
auto rehash = [&]() {
tab.assign(tab.size() * 2, -1);
tabmask = tab.size() - 1;
for (size_t id = 0; id < keys.size(); id++) {
size_t j = size_t(E::hash(keys[id])) & tabmask;
while (tab[j] >= 0)
j = (j + 1) & tabmask;
tab[j] = int32_t(id);
}
};
auto add = [&](const key &k, int d, uint32_t parent,
uint16_t ins) -> uint32_t {
if ((keys.size() + 1) * 10 > (tabmask + 1) * 7)
rehash();
const uint32_t id = uint32_t(keys.size());
keys.push_back(k);
dists.push_back(uint16_t(d));
pars.push_back(parent);
hows.push_back(ins);
size_t j = size_t(E::hash(k)) & tabmask;
while (tab[j] >= 0)
j = (j + 1) & tabmask;
tab[j] = int32_t(id);
return id;
};
std::vector<std::vector<uint32_t>> ring(size_t(wmax) + 1);
const size_t budget = opt.max_states / nthreads;
for (;;) {
const int first = next_first.fetch_add(1);
if (first >= int(insns.size()))
break;
if (w[size_t(first)] >= best_done.load())
continue;
keys.clear();
dists.clear();
pars.clear();
hows.clear();
tab.assign(tabmask + 1, -1);
for (auto &b : ring)
b.clear();
const int limit = std::min(opt.max_cost, best_done.load() - 1);
if (w[size_t(first)] > limit)
continue;
const key s0 = E::step(start, insns[size_t(first)]);
const int d0 = w[size_t(first)];
if (s0 == goal) {
record(d0, {insns[size_t(first)]});
continue;
}
add(s0, d0, 0, 0xFFFE); // root of this sub search
ring[size_t(d0) % ring.size()].push_back(0);
auto backtrack = [&](uint32_t id) {
std::vector<instruction> p;
while (hows[id] != 0xFFFE) {
p.push_back(insns[hows[id]]);
id = pars[id];
}
p.push_back(insns[size_t(first)]);
std::reverse(p.begin(), p.end());
return p;
};
int d = d0;
while (d <= limit) {
auto &bucket = ring[size_t(d) % ring.size()];
if (bucket.empty()) {
d++; // plain Dial: the ring reuses slots every ring.size() steps
continue;
}
const uint32_t id = bucket.back();
bucket.pop_back();
if (dists[id] != d)
continue; // stale
if (keys[id] == goal) {
record(d, backtrack(id));
break;
}
if (d >= limit)
continue;
const key cur = keys[id];
for (size_t ii = 0; ii < insns.size(); ii++) {
if (E::get(cur, insns[ii].sacrifice) == 0)
continue;
const int nd = d + w[ii];
if (nd > limit)
continue;
const key nx = E::step(cur, insns[ii]);
const int32_t f = find_id(nx);
if (f < 0) {
const uint32_t nid = add(nx, nd, id, uint16_t(ii));
ring[size_t(nd) % ring.size()].push_back(nid);
} else if (nd < dists[size_t(f)]) {
dists[size_t(f)] = uint16_t(nd);
pars[size_t(f)] = id;
hows[size_t(f)] = uint16_t(ii);
ring[size_t(nd) % ring.size()].push_back(uint32_t(f));
}
}
if (keys.size() > budget) {
budget_hit.store(true);
break;
}
}
states_total.fetch_add(keys.size());
}
};
std::vector<std::thread> pool;
for (unsigned t = 1; t < nthreads; t++)
pool.emplace_back(worker);
worker();
for (auto &t : pool)
t.join();
r.states = size_t(states_total.load());
if (!best_prog.empty()) {
r.program = best_prog;
r.cost = best_done.load();
r.found = true;
r.proven = !budget_hit.load();
if (!r.proven)
r.message = "state budget exhausted before the search was complete";
return r;
}
r.proven = !budget_hit.load();
r.message =
r.proven ? ("no program with cost <= " + std::to_string(opt.max_cost))
: "state budget exhausted";
return r;
}
template <int K>
result solve_with(const truthtable &raw, const std::vector<size_t> &full,
const options &opt, result &r,
const std::function<result()> &finish) {
using E = engine<K>;
using table_t = typename E::table;
using key = typename E::key;
constexpr uint16_t ROOT = table_t::ROOT;
const std::vector<instruction> insns = build_instructions();
// start = identity over the compressed inputs, goal = the target
key start = E::zero(), goal = E::zero();
for (size_t j = 0; j < full.size(); j++)
for (int b = 0; b < cell_argc; b++) {
if (j & (size_t(1) << b))
E::put(start, b, E::get(start, b) | (uint64_t(1) << j));
if ((*raw.second)[full[j]] & (1u << b))
E::put(goal, b, E::get(goal, b) | (uint64_t(1) << j));
}
table_t tab;
tab.init(table_t::capacity_for(1 << 16));
tab.insert(start, E::zero(), ROOT);
std::vector<key> frontier{start};
auto path_to = [&](const key &k, int extra) {
std::vector<instruction> p;
if (extra >= 0)
p.push_back(insns[size_t(extra)]);
key cur = k;
while (true) {
const auto *s = tab.find(cur);
if (s == nullptr || s->ins == ROOT)
break;
p.push_back(insns[s->ins]);
cur = s->parent;
}
std::reverse(p.begin(), p.end());
return p;
};
if (start == goal) {
r.found = r.proven_optimal = true;
return finish();
}
for (int d = 1; d <= opt.max_depth; d++) {
// ---- close the last block: enumerate the goal's preimages ----
// Only worth it while 2^K is small enough to walk every condition.
if (K <= 3) {
for (uint16_t ii = 0; ii < insns.size(); ii++) {
const instruction &i = insns[ii];
if (E::get(goal, i.sacrifice) != 0)
continue; // the block clears its own plane
for (uint64_t c = 1; c <= E::PMASK; c++) {
bool hit = false;
for_each_preimage<E>(
goal, i, c, [&](const key &p) {
if (tab.find(p) != nullptr) {
r.program = path_to(p, int(ii));
r.found = true;
r.proven_optimal = true;
hit = true;
return true;
}
return false;
});
if (hit)
return finish();
}
}
// the backward step has covered this length already
if (d == opt.max_depth)
break;
}
// ---- expand the BFS by one layer ----
std::vector<key> next;
next.reserve(frontier.size());
for (const auto &k : frontier) {
for (uint16_t ii = 0; ii < insns.size(); ii++) {
if (E::cond(k, insns[ii]) == 0)
continue; // nothing to sacrifice, the block would do nothing
key n = E::step(k, insns[ii]);
if (n == goal) {
r.program = path_to(k, int(ii));
r.found = true;
r.proven_optimal = true;
r.states = tab.used;
r.depth_reached = d;
return finish();
}
if (tab.insert(n, k, ii))
next.push_back(n);
}
if (tab.used > opt.max_states) {
r.message = "state budget exhausted: the search is not complete";
r.states = tab.used;
r.depth_reached = d;
return finish();
}
}
r.states = tab.used;
r.depth_reached = d;
if (opt.verbose)
std::cout << " depth " << d << ": " << next.size() << " new, "
<< tab.used << " kept\n";
frontier.swap(next);
}
r.proven_optimal = (r.message.empty());
if (r.message.empty())
r.message = "no program of length <= " + std::to_string(opt.max_depth);
return finish();
}
// Calls f on every preimage of `post` under `ins` with condition `c`.
// XOR destinations are forced, OR destinations are free on the bits of c
// they contain, so walk the destinations and branch where needed.
template <class E, class F>
static bool for_each_preimage(const typename E::key &post,
const instruction &ins, uint64_t c, F &&f) {
using key = typename E::key;
key pre = post;
E::put(pre, ins.sacrifice, c);
return preimage_walk<E>(post, ins, c, pre, 0, f);
}
template <class E, class F>
static bool preimage_walk(const typename E::key &post,
const instruction &ins, uint64_t c,
typename E::key pre, int b, F &f) {
using key = typename E::key;
for (; b < cell_argc; b++)
if (ins.mask & (1 << b))
break;
if (b == cell_argc)
return f(pre);
const uint64_t T = E::get(post, b);
if (!ins.or_mode) {
E::put(pre, b, T ^ c);
return preimage_walk<E>(post, ins, c, pre, b + 1, f);
}
if ((T & c) != c)
return false; // a destination bit can only be set, not cleared
const uint64_t fixed = T & ~c, free = T & c;
for (uint64_t sub = free;; sub = (sub - 1) & free) {
E::put(pre, b, fixed | sub);
if (preimage_walk<E>(post, ins, c, pre, b + 1, f))
return true;
if (sub == 0)
break;
}
return false;
}
// ---------------------------------------------------------------- syntax
std::vector<instruction> build_instructions() const {
std::vector<instruction> out;
out.reserve(cell_argc * (2 * (1 << (cell_argc - 1)) + 1));
for (int s = 0; s < cell_argc; s++) {
out.push_back({uint8_t(s), 0, false}); // pure sacrifice: clear plane s
for (int sub = 1; sub < (1 << (cell_argc - 1)); sub++) {
uint8_t m = 0;
int bit = 0;
for (int b = 0; b < cell_argc; b++)
if (b != s)
m |= uint8_t(((sub >> bit++) & 1) << b);
out.push_back({uint8_t(s), m, false});
out.push_back({uint8_t(s), m, true});
}
}
return out;
}
};
#endif