-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisa.py
55 lines (42 loc) · 1.47 KB
/
isa.py
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
"""
Типы данных для представления и сериализации/десериализации машинного кода.
"""
import json
from collections import namedtuple
from enum import Enum
functions = ['setq', 'read', 'print', 'loop', 'if', 'return', '+', '-', '>', '<', '=', 'mod']
class Opcode(str, Enum):
"""Opcode для ISA."""
LOAD = 'load'
LOAD_CONST = 'loadc'
LOAD_INDIRECT = 'load_indir'
STORE = 'store'
STORE_INDIRECT = 'store_indir'
ADD = 'add'
ADD_CONST = 'addc'
SUB = 'sub'
PRINT = 'print'
PRINT_INT = 'print_int'
READ = 'read'
JMP = 'jmp'
JE = 'je'
JNE = 'jne'
JG = 'jg'
JL = 'jl'
HLT = 'halt'
class Term(namedtuple('Term', 'pos')):
"""Описание выражения из исходного текста программы."""
# сделано через класс, чтобы был docstring
def write_code(filename, code):
"""Записать машинный код в файл."""
with open(filename, "w", encoding="utf-8") as file:
file.write(json.dumps(code, indent=4))
def read_code(filename):
"""Прочесть машинный код из файла."""
with open(filename, encoding="utf-8") as file:
code = json.loads(file.read())
for instr in code:
# Конвертация строки в Opcode
instr['opcode'] = Opcode(instr['opcode'])
instr['term'] = Term(instr['term'])
return code