-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcompiler.py
executable file
·319 lines (200 loc) · 8.8 KB
/
compiler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#! /usr/bin/env python
import logging
from logging import DEBUG, INFO, ERROR
from bytes import u1
from classfile import Code_attribute, ExceptionTableEntry, LineNumberTable_attribute
from jopcode import getOperation
log = logging.getLogger('compiler')
log.setLevel(INFO)
class ArgumentException(Exception):
def __init__(self, name, args, mess=None):
assert isinstance(name, basestring)
self.name = name
self.args = args
self.mess = mess
# FIXME this doesn't appear to be working correctly
def __str__(self):
ret = self.name + ' ( '
for arg in self.args:
ret += arg
ret += ' '
ret += ')'
if self.mess:
ret += ' : '
ret += self.mess
return ret
class InternalCompilerError(Exception):
def __init__(self, name):
self.name = name
def __str__(self):
return name
class UnknownSymbol(Exception):
def __init__(self, name):
self.name = name
def __str__(self):
return name
class UnknownLabel(UnknownSymbol):
def __init__(self, name):
UnknownSymbol.__init__(self, name)
class Symbol(object):
def __init__(self, owningClass):
self.owningClass = owningClass
# Now Symbols must be actually dereferenced to trigger creation of constant
# entries in the classfile - therefore they need to be typed. When
# dereferenced, they return the bytes appropriate to their index into the
# constant pool.
class ConstantSymbol(Symbol):
def __init__(self, owningClass, value):
Symbol.__init__(self, owningClass)
self.value = value
class StringSymbol(ConstantSymbol):
def get(self):
return [self.owningClass.stringConstant(self.value) & 0xff]
class ClassSymbol(ConstantSymbol):
def get(self):
const = self.owningClass.classConstant(self.value)
return [const >> 8 & 0xff, const & 0xff]
class IntegerSymbol(ConstantSymbol):
def get(self):
return [self.owningClass.integerConstant(self.value) & 0xff]
class FloatSymbol(ConstantSymbol):
def get(self):
return [self.owningClass.floatConstant(self.value) & 0xff]
# value is the method signature (or field desc)!
class FieldSymbol(ConstantSymbol):
def __init__(self, owningClass, targetClassName, fieldName, typeDesc):
ConstantSymbol.__init__(self, owningClass, typeDesc)
self.fieldName = fieldName
self.targetClassName = targetClassName
def get(self):
const = self.owningClass.fieldConstant(self.targetClassName, self.fieldName, self.value)
return [const >> 8 & 0xff, const & 0xff] ;
class MethodSymbol(FieldSymbol):
def get(self):
const = self.owningClass.methodConstant(self.targetClassName, self.fieldName, self.value)
return [const >> 8 & 0xff, const & 0xff] ;
class SymbolRef(object):
def __init__(self, name):
self.name = name
class LabelRef(SymbolRef):
None
class Instruction(object):
# (Operation, list of integer literals, symbols or labels)
def __init__(self, opName, args):
op = getOperation(opName)
# operand checking no longer happens here, as symbol resolution
# can change the number of argument slots
self.op = op
self.args = args
def byteString(self):
ret = u1(self.op.opcode)
for arg in self.args:
# TODO reconsider this, maybe just have local and global symbol tables
if isinstance(arg, LabelRef):
if not labelTable.has_key(arg):
raise UnknownLabel(arg)
ret += u1(labelTable[arg])
elif isinstance(arg, SymbolRef):
name = arg.name
if not symbolTable.has_key(name):
if log.getEffectiveLevel() <= ERROR:
log.error('Unknown symbol ' + name + ': ' + `symbolTable`)
raise UnknownSymbol(name)
if log.getEffectiveLevel() <= DEBUG:
log.debug('resolving symbol $' + name + ' to ' + `symbolTable[name]` + '(' + `symbolTable` + ')')
for b in symbolTable[name]: # list of bytes
ret += u1(b)
else:
ret += u1(arg) # arg is an integer
return ret
# shut up
def getAbsoluteOrLabelOffset(labels, offset):
if isinstance(offset, int):
return offset
elif isinstance(offset, basestring):
if not labels.has_key(offset):
raise UnknownLabel(offset)
return labels[offset]
else:
raise InternalCompilerError('The compiler attempted to create an offset that was neither a label or an integer')
class ExceptionDef(object):
def __init__(self, owningClass, startThing, endThing, throwableClass, target):
if log.getEffectiveLevel() <= DEBUG:
log.debug('ExceptionDef(' + `owningClass` + ', ' + `startThing` + ', ' + `endThing` + ', ' + `throwableClass` + ', ' + `target` + ')')
self.owningClass = owningClass
self.startThing = startThing
self.endThing = endThing
self.throwableClass = throwableClass
self.target = target
def getExceptionTableEntry(self, labels):
return ExceptionTableEntry(self.owningClass,
getAbsoluteOrLabelOffset(labels, self.startThing),
getAbsoluteOrLabelOffset(labels, self.endThing),
self.throwableClass,
getAbsoluteOrLabelOffset(labels, self.target))
# This is crude; FIXME
def calculateLabelOffset(name, instructionsSoFar):
offset = reduce(lambda x, y: x + y.op.operands + 1, instructionsSoFar, 0)
if log.getEffectiveLevel() <= DEBUG:
log.debug('Resolving label ' + `name` + ' to ' + `offset`)
return offset;
def buildExceptionTable(defs, labels):
return map(lambda x: x.getExceptionTableEntry(labels), defs)
def buildMethodBody(instructions, symbols, labels):
ret = ''
pc = 0
for instruction in instructions:
# first, convert symbol references to byte groups
args = instruction.args
newargs = []
for arg in args:
if isinstance(arg, LabelRef):
name = arg.name
if not labels.has_key(name):
if log.getEffectiveLevel() <= ERROR:
log.error('Unknown label ' + `name` + ': ' + `labels`)
raise UnknownLabel(name)
branchOffset = labels[name] - pc
if branchOffset < 0:
# agh, nail down two's compliment signed 16-bit
# TODO find out if there's a better way in Python?
branchOffset = ((~(-branchOffset)) + 1) & 0xffff
newargs.append((branchOffset >> 8) & 0xff)
newargs.append(branchOffset & 0xff)
elif isinstance(arg, SymbolRef):
name = arg.name
if not symbols.has_key(name):
if log.getEffectiveLevel() <= ERROR:
log.error('Unknown symbol ' + name + ': ' + `symbols`)
raise UnknownSymbol(name)
newargs += symbols[name].get()
else: # it's a byte literal
newargs.append(arg)
# check lengths
op = instruction.op
pc += 1 ;
pc += op.operands ;
if not len(newargs) == op.operands:
message = op.name + ' expected ' + `op.operands` + ' operands, got ' + `len(newargs)`
if log.getEffectiveLevel() <= ERROR:
log.error(message)
raise ArgumentException(op.name, newargs, message)
# add bytes
instruction.args = newargs
ret += instruction.byteString()
return ret
def buildMethod(owningClass, methodName, methodDesc, accessMask, stackSize, localSize, operations, symbols, labels, exceptionDefs, lineNumberTable, compileLineNumbers):
exceptionTable = buildExceptionTable(exceptionDefs, labels)
methodBody = buildMethodBody(operations, symbols, labels)
codeAttributeAttributes = []
if compileLineNumbers:
lineNumberPairs = []
for key in lineNumberTable.keys():
lineNumberPairs.append((lineNumberTable[key], key))
codeAttributeAttributes = [LineNumberTable_attribute(owningClass, lineNumberPairs)]
meth = owningClass.method(methodName,
methodDesc,
accessMask,
[Code_attribute(owningClass, stackSize, localSize, methodBody, exceptionTable, codeAttributeAttributes)]) ;
symbols[methodName] = MethodSymbol(owningClass, owningClass.name, methodName, methodDesc);
return meth