Files

104 lines
3.8 KiB
Python

#!/usr/bin/env python3
"""lib.r8asm -> C++ ast_node aggregate-init code (one-shot test harness generator).
New-arch mapping:
%rep N ... %endrep -> REPEAT{count, CODEBLOCK{body}}
`stp %1` (param on ins) -> REPEAT{count=%1, CODEBLOCK{[stp]}} (ins are param-less now)
_CELL_SIZE/_ROL_STEP -> VARIABLE (resolved via global frame, preset in test)
ROT8 value -> "rot8_<name>" (prefixed canonical names, see operator_map)
BUILTIN value -> "builtin_<name>"
"""
import os
import re
import sys
ROT8 = {"stp", "btp", "ror", "flb", "biz", "rnz", "out", "inp"}
# lib.r8asm 路径:默认取本仓库旁 R8ASM/asm/lib.r8asm,可用参数覆盖:
# python3 tools/gen_macros.py [path/to/lib.r8asm]
HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT_LIB = os.path.normpath(os.path.join(HERE, "../../R8ASM/asm/lib.r8asm"))
LIB_PATH = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_LIB
def expr(tok):
"""Single-token -> ast_node initializer."""
if re.fullmatch(r"-?\d+", tok):
return f'ast_node{{ast_node_t::CONSTANT, "{tok}", {{}}}}'
if tok.startswith("%"):
return f'ast_node{{ast_node_t::PARAMETER, "{tok[1:]}", {{}}}}'
return f'ast_node{{ast_node_t::VARIABLE, "{tok}", {{}}}}'
def line_to_node(tokens):
head = tokens[0]
args = []
if head.startswith("."):
for i, t in enumerate(tokens[1:]):
# .anchor/.var 的第一个参数是名字字面量 -> STRING 节点
if head in (".anchor", ".var") and i == 0:
args.append(f'ast_node{{ast_node_t::STRING, "{t}", {{}}}}')
else:
args.append(expr(t))
return f'ast_node{{ast_node_t::BUILTIN, "builtin_{head[1:]}", {{{", ".join(args)}}}}}'
if head in ROT8:
if len(tokens) > 1:
body = (f'ast_node{{ast_node_t::CODEBLOCK, "", '
f'{{ast_node{{ast_node_t::ROT8, "rot8_{head}", {{}}}}}}}}')
return f'ast_node{{ast_node_t::REPEAT, "", {{{expr(tokens[1])}, {body}}}}}'
return f'ast_node{{ast_node_t::ROT8, "rot8_{head}", {{}}}}'
for t in tokens[1:]:
args.append(expr(t))
return f'ast_node{{ast_node_t::MACROCALL, "{head}", {{{", ".join(args)}}}}}'
def parse_body(lines):
"""Lines of a macro body -> list of node initializer strings (%rep handled)."""
nodes = []
i = 0
while i < len(lines):
line = lines[i]
m = re.match(r"^\s*%rep\s+(\S+)", line)
if m:
count = m.group(1)
j = i + 1
body = []
while j < len(lines) and not re.match(r"^\s*%endrep", lines[j]):
body.append(lines[j]); j += 1
inner = ", ".join(parse_body(body))
nodes.append(
f'ast_node{{ast_node_t::REPEAT, "", {{{expr(count)}, '
f'ast_node{{ast_node_t::CODEBLOCK, "", {{{inner}}}}}}}}}')
i = j + 1
continue
if re.match(r"^\s*%endrep", line):
i += 1
continue
nodes.append(line_to_node(line.split()))
i += 1
return nodes
def main():
raw = open(LIB_PATH).read()
lines = [l for l in raw.splitlines()
if l.strip() and not l.strip().startswith(";")]
macros = {}
cur = None
body = []
for l in lines:
m = re.match(r"^\s*%macro\s+(\S+)\s+(\d+)", l)
if m:
cur = m.group(1); body = []
continue
if re.match(r"^\s*%endmacro", l):
macros[cur] = body
cur = None
continue
if cur:
body.append(l)
for name, b in macros.items():
stmts = ",\n ".join(parse_body(b))
print(f' a.macros["{name}"] = ast_node{{ast_node_t::CODEBLOCK, "", {{')
print(f' {stmts}')
print(' }};')
if __name__ == "__main__":
main()