forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhex2nbc.py
More file actions
executable file
·63 lines (49 loc) · 1.98 KB
/
Copy pathhex2nbc.py
File metadata and controls
executable file
·63 lines (49 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python3
"""hex2nbc.py — Convert hex bytecode text to .nbc binary.
Reads hex text output from fixup_hex.py (or compile_hex.nula) and writes
a .nbc binary file that the Nulang VM can load and run.
Usage:
nulang bootstrap/compile_hex.nula < expr | python3 bootstrap/fixup_hex.py | python3 bootstrap/hex2nbc.py > out.nbc
"""
import sys, re, json, struct
def main():
lines = sys.stdin.readlines()
# Parse hex instructions, constant pool, and function table markers
instructions = []
pool = []
fn_table = [0] # entry point is always at instruction 0
for i, line in enumerate(lines):
s = line.strip()
if not s: continue
if s.startswith("; constant pool:"):
try:
inside = s.split("[", 1)[1].rsplit("]", 1)[0]
pool = [int(x.strip()) for x in inside.split(",") if x.strip()]
except: pass
elif s.startswith("; FN_START"):
# Next non-comment line is the start of a function body
fn_table.append(len(instructions))
elif re.match(r'^[0-9a-fA-F]{8}$', s):
instructions.append(int(s, 16))
if not instructions:
print("Error: no hex instructions found", file=sys.stderr)
sys.exit(1)
# Build constant pool JSON
consts = [{"Int": v} for v in pool]
# Build .nbc binary
magic = b"NLBC"
header = struct.pack(">4sII32sI", magic, 1, 1, b"\x00" * 32, len(instructions))
sys.stdout.buffer.write(header)
for w in instructions:
sys.stdout.buffer.write(struct.pack(">I", w))
meta = {
"name": "main", "constants": consts, "instructions": [],
"behaviors": [], "function_table": fn_table, "exports": [],
"entry_point": None, "handler_tables": [], "actor_metadata": [],
"foreign_functions": [], "tools": [],
}
mb = json.dumps(meta).encode()
sys.stdout.buffer.write(struct.pack(">I", len(mb)))
sys.stdout.buffer.write(mb)
if __name__ == "__main__":
main()