xiiregexbuilder
FPGA-Accelerated Regular Expression Matching Engineprocessor/src/asm.py (2286B)
1import sys
2import re
3
4# Enhanced Assembler for Regex CPU
5# Layout: [31:24] char | [23:16] next1 | [15:8] next2 | [7:4] mid | [3] term | [0] any
6
7
8def pack(char_val, next1, next2, mid, term, any_bit):
9 return (
10 (char_val << 24)
11 | (next1 << 16)
12 | (next2 << 8)
13 | (mid << 4)
14 | (term << 3)
15 | any_bit
16 )
17
18
19def main():
20 input_file = sys.argv[1] if len(sys.argv) > 1 else "regexes.rasm"
21 output_file = sys.argv[2] if len(sys.argv) > 2 else "imem.hex"
22
23 mem = [0] * 256
24 with open(input_file, "r") as f:
25 for line in f:
26 line = line.strip()
27 if not line or line.startswith("#"):
28 continue
29
30 m = re.match(r"(\d+):\s+(\w+)(?:\((.*)\))?", line)
31 if not m:
32 continue
33
34 pc, instr, args_str = int(m.group(1)), m.group(2), m.group(3)
35 args = []
36 if args_str:
37 for arg in re.split(r",\s*", args_str):
38 arg = arg.strip()
39 if arg.startswith("'") and arg.endswith("'"):
40 args.append(ord(arg[1:-1]))
41 else:
42 args.append(int(arg))
43
44 if instr == "CHAR":
45 # Support: CHAR('a') OR CHAR('a', n1, n2, mid, term, any)
46 c = args[0]
47 n1 = args[1] if len(args) > 1 else pc + 1
48 n2 = args[2] if len(args) > 2 else 0
49 mid = args[3] if len(args) > 3 else 0
50 term = args[4] if len(args) > 4 else 0
51 any_b = args[5] if len(args) > 5 else 0
52 mem[pc] = pack(c, n1, n2, mid, term, any_b)
53 elif instr == "SPLIT":
54 mem[pc] = pack(0, args[0], args[1], 0, 0, 0)
55 elif instr == "JMP":
56 mem[pc] = pack(0, args[0], 0, 0, 0, 0)
57 elif instr == "MATCH":
58 mem[pc] = pack(0, 0, 0, args[0], 1, 0)
59 elif instr == "ANY":
60 n1 = args[0] if len(args) > 0 else pc + 1
61 mem[pc] = pack(0, n1, 0, 0, 0, 1)
62
63 with open(output_file, "w") as f:
64 for val in mem:
65 f.write(f"{val:08x}\n")
66 print(f"Assembled {input_file} to {output_file}")
67
68
69if __name__ == "__main__":
70 main()