export_rot8 导出测试:全 opcode 字符表 + 宏路径 + builtin + repeat + 空树(6 断言)

This commit is contained in:
hermes committed 2026-08-26 15:09:39 +00:00
1 parent ec8c07e11f
commit e21a831f4e
1 file changed
+61 -1
+61 -1
View File
@@ -134,6 +134,66 @@ int main() {
data_test("3--2", op("op_sub", {cst(3), op("op_neg", {cst(2)})}), 5);
data_test("1+2*3", op("op_add", {cst(1), op("op_mul", {cst(2), cst(3)})}), 7);
// export_rot8:AST → ROT8 字节码字符串(字符表映射首次被测试)
{
r8asm r;
r.main_tree.macros = a.macros; // 复用已注册的库宏
auto tape = [&](ast_node root) -> std::string {
r.main_tree.root = std::move(root);
r.main_tree.dataptr = 0; // 每个用例从 dp=0 起跑,保持确定性
return r.export_rot8();
};
auto expect_tape = [&](const char *name, ast_node root,
const std::string &expect) {
try {
std::string got = tape(std::move(root));
bool ok = (got == expect);
std::cout << "tape " << name << ": \"" << got << "\""
<< (ok ? "" : " FAIL") << " (expect \"" << expect << "\")\n";
if (!ok)
fail++;
} catch (const std::exception &e) {
std::cout << "tape " << name << ": EXCEPTION: " << e.what() << "\n";
fail++;
}
};
auto rot8 = [](const char *name) {
return ast_node{ast_node_t::ROT8, std::string("rot8_") + name, {}};
};
// 全 opcode 字符表:rot8_t 枚举序 vs 字符表一致(表错位是最经典的 bug)
expect_tape("all opcodes",
{ast_node_t::CODEBLOCK, "",
{rot8("stp"), rot8("btp"), rot8("ror"), rot8("flb"),
rot8("biz"), rot8("rnz"), rot8("out"), rot8("inp")}},
"><+-[].,");
// 宏路径:set_0 = biz flb rnz
expect_tape("set_0", {ast_node_t::CODEBLOCK, "",
{{ast_node_t::MACROCALL, "set_0", {}}}},
"[-]");
// REPEAT 平铺
expect_tape("repeat 2x stp",
{ast_node_t::CODEBLOCK, "",
{{ast_node_t::REPEAT, "",
{ast_node{ast_node_t::CONSTANT, "2", {}},
{ast_node_t::CODEBLOCK, "", {rot8("stp")}}}}}},
">>");
// .tp 2:dp 0 -> 2
expect_tape(".tp 2",
{ast_node_t::CODEBLOCK, "",
{{ast_node_t::BUILTIN, "builtin_tp",
{{ast_node_t::CONSTANT, "2", {}}}}}},
">>");
// .xor 5:0b101 → flb,ror,ror,flb,ror×6 → "-++-++++++"
expect_tape(".xor 5",
{ast_node_t::CODEBLOCK, "",
{{ast_node_t::BUILTIN, "builtin_xor",
{{ast_node_t::CONSTANT, "5", {}}}}}},
"-++-++++++");
// 空 root
expect_tape("empty", {ast_node_t::CODEBLOCK, "", {}}, "");
}
std::cout << (fail ? "FAILED: " : "ALL OK: ") << fail << " failures\n";
return fail ? 1 : 0;
}
}