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
|
|
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:
|
236
|
144 def __init__(self, target=None, stream=None):
|
218
|
145 self.target = target
|
236
|
146 self.stream = stream
|
218
|
147 self.restart()
|
|
148 self.p = asmParser
|
|
149
|
196
|
150 # Top level interface:
|
199
|
151 def restart(self):
|
236
|
152 self.stack = []
|
199
|
153
|
195
|
154 def emit(self, a):
|
196
|
155 """ Emit a parsed instruction """
|
236
|
156 self.stack.append(a)
|
196
|
157
|
194
|
158 def parse_line(self, line):
|
|
159 """ Parse line into asm AST """
|
|
160 tokens = tokenize(line)
|
218
|
161 self.p.parse(tokens, self.emit)
|
191
|
162
|
|
163 def assemble(self, asmsrc):
|
196
|
164 """ Assemble this source snippet """
|
|
165 for line in asmsrc.split('\n'):
|
|
166 self.assemble_line(line)
|
159
|
167
|
196
|
168 def assemble_line(self, line):
|
191
|
169 """
|
|
170 Assemble a single source line.
|
|
171 Do not take newlines into account
|
|
172 """
|
196
|
173 self.parse_line(line)
|
|
174 self.assemble_aast()
|
191
|
175
|
198
|
176 def assemble_aast(self):
|
191
|
177 """ Assemble a parsed asm line """
|
199
|
178 # TODO
|
|
179 if not self.target:
|
|
180 raise CompilerError('Cannot assemble without target')
|
236
|
181 while self.stack:
|
|
182 vi = self.stack.pop(0)
|
203
|
183 if type(vi) is AInstruction:
|
236
|
184 mi = self.target.mapInstruction(vi)
|
|
185 elif type(vi) is ALabel:
|
|
186 mi = Label(vi.name)
|
|
187 else:
|
|
188 raise NotImplementedError('{}'.format(vi))
|
|
189 if self.stream:
|
|
190 self.stream.emit(mi)
|
191
|
191
|
196
|
192
|
|
193 if __name__ == '__main__':
|
|
194 # When run as main file, try to grab command line arguments:
|
|
195 parser = argparse.ArgumentParser(description="Assembler")
|
|
196 parser.add_argument('sourcefile', type=argparse.FileType('r'), help='the source file to assemble')
|
|
197 args = parser.parse_args()
|
|
198 a = Assembler()
|
|
199 obj = a.assemble(args.sourcefile.read())
|
|
200
|