repl.it
Python

No description

fork
loading
Files
  • main.py
  • code
  • machinecode.py
  • mnemonics.py
  • parse.py
main.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
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
import parse
import machinecode
import mnemonics

class Assembler():
	def __init__(self):
		self.defs = {}
		self.vals = machinecode.Values()
		self.code = machinecode.Code()
		self.pos = 0

	def get_code(self):
		return self.code.build()

	def parse(self, arg, sub=True):
		def _transform(node):
			if node.kind == "def":
				return self.defs[node.data[0]]
			elif node.kind == "var":
				return self.vals[node.data[0]]
			else:
				return node
		res = parse.parse(arg)
		if sub:
			res = res.walk(_transform)
		return res

	def assemble_op(self, name, args):
		args = [self.parse(arg) for arg in args]
		mnemonics.assemble(name, args, self.code)
	
	def special_op(self, op, args):
		if op == "def":
			name, val = args
			name.expect("def")
			name, = name.data
			self.defs[name] = self.parse(val)

		elif op == "at":
			pos, = args
			pos = self.parse(pos)
			pos.expect("num")
			self.code.pos, = pos.data
		
		elif op == "lbl":
			var, = args
			var = self.parse(var)
			var.expect("var")
			var, = var.data
			self.vals[var] = self.code.pos
		
		elif op == "string":
			data = " ".join(args)
			data = self.parse(data)
			data.expect("string")
			self.code.emit_bytes(data.data[0])
		
		elif op == "byte":
			data, = args
			data = self.parse(data)
			data.expect("num")
			self.code.emit_byte(data.data[0])
		
		elif op == "long":
			data, = args
			data = self.parse(data)
			data.expect("num")
			self.code.emit_long(data.data[0])

		else:
			raise SyntaxError(f"unknown special op {op}")

	def read_line(self, line):
		line = line.strip()
		if not line:
			return
		if line.startswith("#"):
			return
		if line.startswith("!"):
			line = line[1:]
			name, *args = line.split(" ")
			self.special_op(name, args)

		name, *args = line.split(" ")
		self.assemble_op(name, args)

	def read_code(self, code):
		for line in code.splitlines():
			self.read_line(line)
	
	def read_file(self, file):
		with open(file, "r") as f:
			for line in f.readlines():
				self.read_line(line)

a = Assembler()
a.read_file("code/ti84.ez")
a.read_file("code/code.ez")
print(a.get_code().hex())