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