-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathir_macro_engine.py
More file actions
89 lines (63 loc) · 2.32 KB
/
ir_macro_engine.py
File metadata and controls
89 lines (63 loc) · 2.32 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class IRMacroEngine:
"""
Safe macro substitution layer for IR programs.
Responsibilities:
- apply learned macros safely
- prevent structural corruption
- validate opcode consistency
- ensure fallback integrity
"""
def __init__(self, macro_compiler):
self.macro_compiler = macro_compiler
# =====================================================
# MAIN APPLY FUNCTION
# =====================================================
def apply(self, program):
if not program:
return program
macros = getattr(self.macro_compiler, "macros", {})
if not macros:
return program
transformed = []
for instr in program:
# safety check
if not isinstance(instr, dict):
transformed.append(instr)
continue
replaced = False
for name, macro in macros.items():
if self._matches(instr, macro.get("pattern")):
transformed.append({
"opcode": name
})
replaced = True
break
if not replaced:
transformed.append(instr)
# final validation pass
return self._validate(transformed)
# =====================================================
# MATCHING LOGIC
# =====================================================
def _matches(self, instr, pattern):
if not pattern:
return False
# strict opcode match (prevents false compression)
if instr.get("opcode") != pattern.get("opcode"):
return False
return True
# =====================================================
# VALIDATION LAYER (CRITICAL SAFETY GUARD)
# =====================================================
def _validate(self, program):
safe_program = []
for instr in program:
if not isinstance(instr, dict):
continue
opcode = instr.get("opcode")
# reject malformed instructions
if not opcode or not isinstance(opcode, str):
continue
safe_program.append(instr)
# fallback safety: never return empty program
return safe_program if safe_program else program