summaryrefslogtreecommitdiff
path: root/mmasm.py
blob: 973aafaf3807dc9913e0fc224d66397a40941a20 (plain)
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
import sys

if len(sys.argv) != 2:
	print("no source file")
	sys.exit(1)

lines = []
with open(sys.argv[1], 'r') as file:
	lines = file.readlines()

opcodes = {
	"AND": 0, "ADD": 1, "LDA": 2, "STA": 3, "BUN": 4, "BSA": 5, "ISZ": 6,
	"CLA": 0x7800, "CLE": 0x7400, "CMA": 0x7200, "CME": 0x7100, "CIR": 0x7080,
	"CIL": 0x7040, "INC": 0x7020, "SPA": 0x7010, "SNA": 0x7008, "SZA": 0x7004,
	"SZE": 0x7002, "HLT": 0x7001, "INP": 0xF800, "OUT": 0xF400, "SKI": 0xF200,
	"SKO": 0xF100, "ION": 0xF080, "IOF": 0xF040
}
labels = {}

# collect all labels in the file
lc = 0
for i, line in enumerate(lines):
	comment_index = line.find('/')
	if (comment_index != -1):
		line = line[:comment_index]
		lines[i] = lines[i][:comment_index]

	parts = line.split()

	if (len(parts) == 0):
		continue

	if (parts[0][-1] == ','):
		labels[parts[0][:-1]] = lc
		k = line.find(',')
		lines[i] = lines[i][k+1:]

	lines[i] = lines[i].strip()

	if (parts[0].upper() == "ORG"):
		lc = int(parts[1], 16)
		continue

	lc += 1

print(labels)
# print hex equivalent line by line
lc = 0
for line in lines:
	parts = line.split()
	n = len(parts)
	if (n == 0): continue
	ins = -1

	parts[0] = parts[0].upper()
	match parts[0]:
		case "ORG":
			lc = int(parts[1], 16)
			continue
		case "HEX":
			ins = int(parts[1], 16)
			n = 0
		case "DEC":
			ins = int(parts[1])
			n = 0
		case "END":
			break

	if n > 0:
		if parts[0] not in opcodes:
			print(f"line {lines.index(line)}: {line}")
			print("error: wrong mnemonic")
			break;
		ins = opcodes[parts[0]]
	if n > 2:
		parts[2] = parts[2].upper()
		if parts[2] == 'I': ins += 8;
	if n > 1:
		if parts[1] not in labels:
			print(f"line {lines.index(line)}: {line}")
			print("error: label not found")
			break;
		ins = ins << 12
		ins = ins | labels[parts[1]]

	if ins != -1:
		print(f"{lc:03x}: {ins & 0xffff:04x}")

	lc += 1