213
|
1 import re, argparse
|
191
|
2 import pyyacc
|
|
3 from ppci import Token, CompilerError, SourceLocation
|
199
|
4 from target import Target
|
200
|
5 from asmnodes import ALabel, AInstruction, ABinop, AUnop, ASymbol, ANumber
|
159
|
6
|
|
7 def tokenize(s):
|
|
8 """
|
|
9 Tokenizer, generates an iterator that
|
|
10 returns tokens!
|
|
11
|
|
12 This GREAT example was taken from python re doc page!
|
|
13 """
|
|
14 tok_spec = [
|
|
15 ('REAL', r'\d+\.\d+'),
|
|
16 ('HEXNUMBER', r'0x[\da-fA-F]+'),
|
|
17 ('NUMBER', r'\d+'),
|
|
18 ('ID', r'[A-Za-z][A-Za-z\d_]*'),
|
|
19 ('SKIP', r'[ \t]'),
|
206
|
20 ('LEESTEKEN', r':=|[\.,=:\-+*\[\]/\(\)]|>=|<=|<>|>|<|}|{'),
|
198
|
21 ('STRING', r"'.*?'"),
|
|
22 ('COMMENT', r";.*")
|
159
|
23 ]
|
|
24 tok_re = '|'.join('(?P<%s>%s)' % pair for pair in tok_spec)
|
|
25 gettok = re.compile(tok_re).match
|
|
26 line = 1
|
|
27 pos = line_start = 0
|
|
28 mo = gettok(s)
|
|
29 while mo is not None:
|
|
30 typ = mo.lastgroup
|
|
31 val = mo.group(typ)
|
|
32 if typ == 'NEWLINE':
|
|
33 line_start = pos
|
|
34 line += 1
|
|
35 elif typ != 'SKIP':
|
199
|
36 if typ == 'LEESTEKEN':
|
159
|
37 typ = val
|
|
38 elif typ == 'NUMBER':
|
|
39 val = int(val)
|
|
40 elif typ == 'HEXNUMBER':
|
|
41 val = int(val[2:], 16)
|
|
42 typ = 'NUMBER'
|
|
43 elif typ == 'REAL':
|
|
44 val = float(val)
|
|
45 elif typ == 'STRING':
|
|
46 val = val[1:-1]
|
191
|
47 col = mo.start() - line_start
|
|
48 loc = SourceLocation(line, col, 0) # TODO retrieve length?
|
|
49 yield Token(typ, val, loc)
|
159
|
50 pos = mo.end()
|
|
51 mo = gettok(s, pos)
|
|
52 if pos != len(s):
|
|
53 col = pos - line_start
|
191
|
54 loc = SourceLocation(line, col, 0)
|
|
55 raise CompilerError('Unexpected character {0}'.format(s[pos]), loc)
|
159
|
56
|
|
57 class Lexer:
|
|
58 def __init__(self, src):
|
|
59 self.tokens = tokenize(src)
|
|
60 self.curTok = self.tokens.__next__()
|
|
61 def eat(self):
|
|
62 t = self.curTok
|
|
63 self.curTok = self.tokens.__next__()
|
|
64 return t
|
|
65 @property
|
|
66 def Peak(self):
|
|
67 return self.curTok
|
|
68
|
218
|
69 class Parser:
|
|
70 def __init__(self):
|
191
|
71 # Construct a parser given a grammar:
|
195
|
72 ident = lambda x: x # Identity helper function
|
206
|
73 g = pyyacc.Grammar(['ID', 'NUMBER', ',', '[', ']', ':', '+', '-', '*', pyyacc.EPS, 'COMMENT', '{', '}'])
|
198
|
74 g.add_production('asmline', ['asmline2'])
|
|
75 g.add_production('asmline', ['asmline2', 'COMMENT'])
|
|
76 g.add_production('asmline2', ['label', 'instruction'])
|
|
77 g.add_production('asmline2', ['instruction'])
|
|
78 g.add_production('asmline2', ['label'])
|
|
79 g.add_production('asmline2', [])
|
|
80 g.add_production('optcomment', [])
|
|
81 g.add_production('optcomment', ['COMMENT'])
|
194
|
82 g.add_production('label', ['ID', ':'], self.p_label)
|
195
|
83 g.add_production('instruction', ['opcode', 'operands'], self.p_ins_1)
|
|
84 g.add_production('instruction', ['opcode'], self.p_ins_2)
|
|
85 g.add_production('opcode', ['ID'], ident)
|
|
86 g.add_production('operands', ['operand'], self.p_operands_1)
|
|
87 g.add_production('operands', ['operands', ',', 'operand'], self.p_operands_2)
|
|
88 g.add_production('operand', ['expression'], ident)
|
|
89 g.add_production('operand', ['[', 'expression', ']'], self.p_mem_op)
|
206
|
90 g.add_production('operand', ['{', 'listitems', '}'], self.p_list_op)
|
|
91 g.add_production('listitems', ['expression'], self.p_listitems_1)
|
|
92 g.add_production('listitems', ['listitems', ',', 'expression'], self.p_listitems_2)
|
195
|
93 g.add_production('expression', ['term'], ident)
|
|
94 g.add_production('expression', ['expression', 'addop', 'term'], self.p_binop)
|
|
95 g.add_production('addop', ['-'], ident)
|
|
96 g.add_production('addop', ['+'], ident)
|
|
97 g.add_production('mulop', ['*'], ident)
|
|
98 g.add_production('term', ['factor'], ident)
|
|
99 g.add_production('term', ['term', 'mulop', 'factor'], self.p_binop)
|
200
|
100 g.add_production('factor', ['ID'], lambda name: ASymbol(name))
|
|
101 g.add_production('factor', ['NUMBER'], lambda num: ANumber(int(num)))
|
191
|
102 g.start_symbol = 'asmline'
|
195
|
103 self.p = g.genParser()
|
159
|
104
|
195
|
105 # Parser handlers:
|
|
106 def p_ins_1(self, opc, ops):
|
|
107 ins = AInstruction(opc, ops)
|
|
108 self.emit(ins)
|
|
109 def p_ins_2(self, opc):
|
|
110 self.p_ins_1(opc, [])
|
|
111 def p_operands_1(self, op1):
|
|
112 return [op1]
|
|
113 def p_operands_2(self, ops, comma, op2):
|
|
114 assert type(ops) is list
|
|
115 ops.append(op2)
|
|
116 return ops
|
206
|
117
|
|
118 def p_listitems_1(self, li1):
|
|
119 return [li1]
|
|
120
|
|
121 def p_listitems_2(self, lis, comma, li2):
|
|
122 assert type(lis) is list
|
|
123 lis.append(li2)
|
|
124 return lis
|
|
125
|
|
126 def p_list_op(self, brace_open, lst, brace_close):
|
|
127 return AUnop('{}', lst)
|
195
|
128 def p_mem_op(self, brace_open, exp, brace_close):
|
|
129 return AUnop('[]', exp)
|
|
130 def p_label(self, lname, cn):
|
|
131 lab = ALabel(lname)
|
|
132 self.emit(lab)
|
|
133 def p_binop(self, exp1, op, exp2):
|
|
134 return ABinop(op, exp1, exp2)
|
|
135
|
218
|
136 def parse(self, tokens, emitter):
|
|
137 self.emit = emitter
|
|
138 self.p.parse(tokens)
|
|
139
|
219
|
140 # Pre construct parser to save time:
|
218
|
141 asmParser = Parser()
|
219
|
142
|
218
|
143 class Assembler:
|
|
144 def __init__(self, target=None):
|
|
145 self.target = target
|
|
146 self.restart()
|
|
147 self.p = asmParser
|
|
148
|
196
|
149 # Top level interface:
|
199
|
150 def restart(self):
|
200
|
151 self.output = []
|
|
152 self.binout = bytearray()
|
|
153 self.current_section = '.text'
|
199
|
154
|
195
|
155 def emit(self, a):
|
196
|
156 """ Emit a parsed instruction """
|
195
|
157 self.output.append(a)
|
196
|
158 # Determine the bit pattern from a lookup table:
|
|
159 # TODO
|
|
160
|
194
|
161 def parse_line(self, line):
|
|
162 """ Parse line into asm AST """
|
|
163 tokens = tokenize(line)
|
218
|
164 self.p.parse(tokens, self.emit)
|
191
|
165
|
|
166 def assemble(self, asmsrc):
|
196
|
167 """ Assemble this source snippet """
|
|
168 for line in asmsrc.split('\n'):
|
|
169 self.assemble_line(line)
|
|
170 self.back_patch()
|
159
|
171
|
196
|
172 def assemble_line(self, line):
|
191
|
173 """
|
|
174 Assemble a single source line.
|
|
175 Do not take newlines into account
|
|
176 """
|
196
|
177 self.parse_line(line)
|
|
178 self.assemble_aast()
|
191
|
179
|
198
|
180 def assemble_aast(self):
|
191
|
181 """ Assemble a parsed asm line """
|
199
|
182 # TODO
|
|
183 if not self.target:
|
|
184 raise CompilerError('Cannot assemble without target')
|
|
185 while self.output:
|
200
|
186 vi = self.output.pop(0)
|
203
|
187 if type(vi) is AInstruction:
|
|
188 ri = self.target.mapInstruction(vi)
|
|
189 b = ri.encode()
|
|
190 assert type(b) is bytes
|
|
191 self.binout.extend(b)
|
191
|
192
|
196
|
193 def back_patch(self):
|
|
194 """ Fix references to earlier labels """
|
|
195 pass
|
235
|
196 #self.output.backpatch()
|
191
|
197
|
196
|
198
|
|
199 if __name__ == '__main__':
|
|
200 # When run as main file, try to grab command line arguments:
|
|
201 parser = argparse.ArgumentParser(description="Assembler")
|
|
202 parser.add_argument('sourcefile', type=argparse.FileType('r'), help='the source file to assemble')
|
|
203 args = parser.parse_args()
|
|
204 a = Assembler()
|
|
205 obj = a.assemble(args.sourcefile.read())
|
|
206
|