Repository navigation
Expand file tree
/
Copy pathasm_ast.py
More file actions
107 lines (84 loc) · 2.38 KB
/
Copy pathasm_ast.py
File metadata and controls
107 lines (84 loc) · 2.38 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
from __future__ import annotations
import ast
from dataclasses import dataclass
from typing import Iterable
from x86_printer import X86Printer
# The assembly syntax tree shared by all architectures. x86_ast.py adds the
# x86-only nodes.
#
# The nodes don't print themselves. str(node) calls the method of `printer`
# named after the node's class (or the nearest base class that has one).
# The test harness in utils.py sets `printer` to the printer of the
# compiler's architecture, so the same tree prints as x86 (the default) or
# as another architecture's assembly.
printers = {'x86': X86Printer()}
printer = printers['x86']
class asm_node:
def __str__(self):
for c in type(self).__mro__:
show = getattr(printer, c.__name__, None)
if show:
return show(self)
return repr(self)
@dataclass
class X86Program(asm_node):
body: dict[str, list[instr]] | list[instr]
@dataclass
class X86ProgramDefs:
defs: list[ast.FunctionDef]
def __str__(self):
return "\n".join([str(d) for d in self.defs])
class instr(asm_node): ...
class arg(asm_node): ...
class location(arg): ...
@dataclass(frozen=True, eq=False)
class Instr(instr):
instr: str
args: tuple[arg, ...]
def __init__(self, name: str, args: Iterable[arg]):
# https://docs.python.org/3/library/dataclasses.html#frozen-instances
object.__setattr__(self, 'instr', name)
object.__setattr__(self, 'args', tuple(args))
# in x86's operand order
def source(self):
return self.args[0]
def target(self):
return self.args[-1]
@dataclass(frozen=True, eq=False)
class Callq(instr):
func: str
num_args: int
@dataclass(frozen=True, eq=False)
class IndirectCallq(instr):
func: arg
num_args: int
@dataclass(frozen=True, eq=False)
class JumpIf(instr):
cc: str
label: str
@dataclass(frozen=True, eq=False)
class Jump(instr):
label: str
@dataclass(frozen=True, eq=False)
class IndirectJump(instr):
target: location
@dataclass(frozen=True, eq=False)
class TailJump(instr):
func: arg
arity: int
@dataclass(frozen=True)
class Variable(location):
id: str
@dataclass(frozen=True)
class Immediate(arg):
value: int
@dataclass(frozen=True)
class Reg(location):
id: str
@dataclass(frozen=True)
class Deref(arg):
reg: str
offset: int
@dataclass(frozen=True)
class Global(arg):
name: str