comparison python/outstream.py @ 219:1fa3e0050b49

Expanded ad hoc code generator
author Windel Bouwman
date Sat, 06 Jul 2013 12:38:09 +0200
parents 4cb47d80fd1f
children 1c7364bd74c7
comparison
equal deleted inserted replaced
218:494828a7adf1 219:1fa3e0050b49
3 """ 3 """
4 The output stream is a stream of instructions that can be output 4 The output stream is a stream of instructions that can be output
5 to a file or binary or hexfile. 5 to a file or binary or hexfile.
6 """ 6 """
7 7
8 class Alignment:
9 def __init__(self, a):
10 self.align = a
11
8 class OutputStream: 12 class OutputStream:
9 def __init__(self): 13 def __init__(self):
10 self.sections = {} 14 self.sections = {}
11 self.currentSection = None 15 self.currentSection = None
12 def emit(self, item): 16 def emit(self, item):
13 self.sections[self.currentSection].append(item) 17 self.sections[self.currentSection].append(item)
18
19 def align(self, alignment):
20 self.emit(Alignment(alignment))
21
14 def selectSection(self, s): 22 def selectSection(self, s):
15 self.currentSection = s 23 self.currentSection = s
16 if not s in self.sections: 24 if not s in self.sections:
17 self.sections[s] = [] 25 self.sections[s] = []
18 26
28 address = 0x0 36 address = 0x0
29 for i in self.sections[s]: 37 for i in self.sections[s]:
30 i.address = address 38 i.address = address
31 if type(i) is ALabel: 39 if type(i) is ALabel:
32 continue 40 continue
41 if type(i) is Alignment:
42 while (address % i.align) != 0:
43 address += 1
44 continue
33 bts = i.encode() 45 bts = i.encode()
34 address += len(bts) 46 address += len(bts)
35 47
36 def dump(self): 48 def dump(self):
37 self.backpatch() 49 self.backpatch()
41 def dumpSection(self, s): 53 def dumpSection(self, s):
42 print('.section '+s) 54 print('.section '+s)
43 for i in self.sections[s]: 55 for i in self.sections[s]:
44 if type(i) is ALabel: 56 if type(i) is ALabel:
45 print(i) 57 print(i)
58 elif type(i) is Alignment:
59 pass
46 else: 60 else:
47 addr = i.address 61 addr = i.address
48 insword = i.encode() 62 insword = i.encode()
49 assert type(insword) is bytes 63 assert type(insword) is bytes
50 insword = binascii.hexlify(bytes(reversed(insword))).decode('ascii') 64 insword = binascii.hexlify(bytes(reversed(insword))).decode('ascii')