213
|
1 import re, argparse
|
191
|
2 import pyyacc
|
|
3 from ppci import Token, CompilerError, SourceLocation
|
236
|
4 from target import Target, Label
|
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
|
287
|
48 loc = SourceLocation('', line, col, 0) # TODO retrieve length?
|
191
|
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
|
287
|
54 loc = SourceLocation('', line, col, 0)
|
191
|
55 raise CompilerError('Unexpected character {0}'.format(s[pos]), loc)
|
159
|
56
|
287
|
57
|
159
|
58 class Lexer:
|
|
59 def __init__(self, src):
|
|
60 self.tokens = tokenize(src)
|
|
61 self.curTok = self.tokens.__next__()
|
|
62 def eat(self):
|
|
63 t = self.curTok
|
|
64 self.curTok = self.tokens.__next__()
|
|
65 return t
|
|
66 @property
|
|
67 def Peak(self):
|
|
68 return self.curTok
|
|
69
|
287
|
70
|
218
|
71 class Parser:
|
|
72 def __init__(self):
|
191
|
73 # Construct a parser given a grammar:
|
195
|
74 ident = lambda x: x # Identity helper function
|
206
|
75 g = pyyacc.Grammar(['ID', 'NUMBER', ',', '[', ']', ':', '+', '-', '*', pyyacc.EPS, 'COMMENT', '{', '}'])
|
198
|
76 g.add_production('asmline', ['asmline2'])
|
|
77 g.add_production('asmline', ['asmline2', 'COMMENT'])
|
|
78 g.add_production('asmline2', ['label', 'instruction'])
|
|
79 g.add_production('asmline2', ['instruction'])
|
|
80 g.add_production('asmline2', ['label'])
|
|
81 g.add_production('asmline2', [])
|
|
82 g.add_production('optcomment', [])
|
|
83 g.add_production('optcomment', ['COMMENT'])
|
194
|
84 g.add_production('label', ['ID', ':'], self.p_label)
|
195
|
85 g.add_production('instruction', ['opcode', 'operands'], self.p_ins_1)
|
|
86 g.add_production('instruction', ['opcode'], self.p_ins_2)
|
|
87 g.add_production('opcode', ['ID'], ident)
|
|
88 g.add_production('operands', ['operand'], self.p_operands_1)
|
|
89 g.add_production('operands', ['operands', ',', 'operand'], self.p_operands_2)
|
|
90 g.add_production('operand', ['expression'], ident)
|
|
91 g.add_production('operand', ['[', 'expression', ']'], self.p_mem_op)
|
206
|
92 g.add_production('operand', ['{', 'listitems', '}'], self.p_list_op)
|
|
93 g.add_production('listitems', ['expression'], self.p_listitems_1)
|
|
94 g.add_production('listitems', ['listitems', ',', 'expression'], self.p_listitems_2)
|
195
|
95 g.add_production('expression', ['term'], ident)
|
|
96 g.add_production('expression', ['expression', 'addop', 'term'], self.p_binop)
|
|
97 g.add_production('addop', ['-'], ident)
|
|
98 g.add_production('addop', ['+'], ident)
|
|
99 g.add_production('mulop', ['*'], ident)
|
|
100 g.add_production('term', ['factor'], ident)
|
|
101 g.add_production('term', ['term', 'mulop', 'factor'], self.p_binop)
|
200
|
102 g.add_production('factor', ['ID'], lambda name: ASymbol(name))
|
|
103 g.add_production('factor', ['NUMBER'], lambda num: ANumber(int(num)))
|
191
|
104 g.start_symbol = 'asmline'
|
195
|
105 self.p = g.genParser()
|
159
|
106
|
195
|
107 # Parser handlers:
|
|
108 def p_ins_1(self, opc, ops):
|
|
109 ins = AInstruction(opc, ops)
|
|
110 self.emit(ins)
|
|
111 def p_ins_2(self, opc):
|
|
112 self.p_ins_1(opc, [])
|
|
113 def p_operands_1(self, op1):
|
|
114 return [op1]
|
|
115 def p_operands_2(self, ops, comma, op2):
|
|
116 assert type(ops) is list
|
|
117 ops.append(op2)
|
|
118 return ops
|
206
|
119
|
|
120 def p_listitems_1(self, li1):
|
|
121 return [li1]
|
|
122
|
|
123 def p_listitems_2(self, lis, comma, li2):
|
|
124 assert type(lis) is list
|
|
125 lis.append(li2)
|
|
126 return lis
|
|
127
|
|
128 def p_list_op(self, brace_open, lst, brace_close):
|
|
129 return AUnop('{}', lst)
|
195
|
130 def p_mem_op(self, brace_open, exp, brace_close):
|
|
131 return AUnop('[]', exp)
|
|
132 def p_label(self, lname, cn):
|
|
133 lab = ALabel(lname)
|
|
134 self.emit(lab)
|
|
135 def p_binop(self, exp1, op, exp2):
|
|
136 return ABinop(op, exp1, exp2)
|
|
137
|
218
|
138 def parse(self, tokens, emitter):
|
|
139 self.emit = emitter
|
|
140 self.p.parse(tokens)
|
|
141
|
219
|
142 # Pre construct parser to save time:
|
218
|
143 asmParser = Parser()
|
219
|
144
|
218
|
145 class Assembler:
|
236
|
146 def __init__(self, target=None, stream=None):
|
218
|
147 self.target = target
|
236
|
148 self.stream = stream
|
218
|
149 self.restart()
|
|
150 self.p = asmParser
|
|
151
|
196
|
152 # Top level interface:
|
199
|
153 def restart(self):
|
236
|
154 self.stack = []
|
199
|
155
|
195
|
156 def emit(self, a):
|
196
|
157 """ Emit a parsed instruction """
|
236
|
158 self.stack.append(a)
|
196
|
159
|
194
|
160 def parse_line(self, line):
|
|
161 """ Parse line into asm AST """
|
|
162 tokens = tokenize(line)
|
218
|
163 self.p.parse(tokens, self.emit)
|
191
|
164
|
|
165 def assemble(self, asmsrc):
|
196
|
166 """ Assemble this source snippet """
|
|
167 for line in asmsrc.split('\n'):
|
|
168 self.assemble_line(line)
|
159
|
169
|
196
|
170 def assemble_line(self, line):
|
191
|
171 """
|
|
172 Assemble a single source line.
|
|
173 Do not take newlines into account
|
|
174 """
|
196
|
175 self.parse_line(line)
|
|
176 self.assemble_aast()
|
191
|
177
|
198
|
178 def assemble_aast(self):
|
191
|
179 """ Assemble a parsed asm line """
|
199
|
180 # TODO
|
|
181 if not self.target:
|
|
182 raise CompilerError('Cannot assemble without target')
|
236
|
183 while self.stack:
|
|
184 vi = self.stack.pop(0)
|
203
|
185 if type(vi) is AInstruction:
|
236
|
186 mi = self.target.mapInstruction(vi)
|
|
187 elif type(vi) is ALabel:
|
|
188 mi = Label(vi.name)
|
|
189 else:
|
|
190 raise NotImplementedError('{}'.format(vi))
|
|
191 if self.stream:
|
|
192 self.stream.emit(mi)
|
191
|
193
|
196
|
194
|
|
195 if __name__ == '__main__':
|
|
196 # When run as main file, try to grab command line arguments:
|
|
197 parser = argparse.ArgumentParser(description="Assembler")
|
|
198 parser.add_argument('sourcefile', type=argparse.FileType('r'), help='the source file to assemble')
|
|
199 args = parser.parse_args()
|
|
200 a = Assembler()
|
|
201 obj = a.assemble(args.sourcefile.read())
|
|
202
|