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