forked from whaleygeek/MyLittleComputer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathassembler.py
103 lines (71 loc) · 2.14 KB
/
assembler.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
100
101
102
# assembler.py 03/11/2014 D.J.Whale
#
# Read a file and assemble it into a numeric representation
import parser
import instruction
import symtab
import io
# Extension mechanism
import extarch
# Set to True if you want addresses prefixed into the output file
PREFIX_ADDR = False
def trace(msg):
print(str(msg))
def parse(filename, memory=None, startaddr=0):
"""parse a whole file, storing each instruction in memory"""
addr = startaddr
f = open(filename, "rt")
if memory == None:
memory = {}
for line in f.readlines():
line = line.strip()
label, operator, operand, labelref = parser.parseLine(line)
#trace("parse:" + line + "=" + str((label, operator, operand, labelref)))
if line == "" or (label == None and operator == None):
# must be a comment
continue # go round to next line
instr = instruction.build(operator, operand)
#trace(" created:" + str(instr))
# dump any collected labels
if label != None:
symtab.define(label, addr)
if labelref != None:
addrref = symtab.use(labelref, addr)
if addrref != None:
# address of label already known, so fixup instruction operand now
#trace("info: Fixing label reference:" + labelref + " to:" + str(addrref))
instr = instruction.setOperand(instr, addrref)
# Store in memory
memory[addr] = instr
# Move to next memory location
addr += 1
f.close()
return memory
def write(memory, filename):
"""write the contents of memory to the file"""
f = open(filename, "wt")
size = len(memory)
startaddr = min(memory)
for addr in range(startaddr, startaddr+size):
#if PREFIX_ADDR:
# io.write(addr, file=f)
io.write(memory[addr], file=f)
f.close()
def main():
import sys
IN_NAME = sys.argv[1] #TODO if - or not present, use stdin
OUT_NAME = sys.argv[2] #TODO if - of not present, use stdout
SYM_NAME = OUT_NAME + ".sym"
m = parse(IN_NAME)
symtab.fixup(m)
sym_f = open(SYM_NAME, "w")
symtab.dumpLabels(sym_f)
symtab.dumpFixups(sym_f)
sym_f.close()
##loader.showmem(m)
##disassembler.disassemble(m)
write(m, OUT_NAME)
if __name__ == "__main__":
#TODO#### get encoder settings from command line args use io.configure()
main()
# END