-
Notifications
You must be signed in to change notification settings - Fork 3
/
program_builder.py
354 lines (257 loc) · 11.1 KB
/
program_builder.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import program
import instructions
import typesData
import analyzer
import variable
import operation
import probability
import settings
from code_generators import CodeGenerator
class ProgramBuilder:
def __init__(self, prog=False):
if prog == False:
self.program = program.Program()
else:
self.program = prog
self.nextFreeVariable = self.program.nextVariable
self.instructionList = []
for i in self.program.instructionList:
self.instructionList.append(i)
self.seenIntegers = set([])
self.seenFloats = set([])
self.seenStrings = set([])
self.scopeAnalyzer = analyzer.ScopeAnalyzer(self.program)
self.scopeAnalyzer.doAnalyze()
self.contextAnalyzer = analyzer.ContextAnalyzer(self.program)
self.contextAnalyzer.doAnalyze()
self.typeAnalyzer = analyzer.TypeAnalyzer(self.program)
self.typeAnalyzer.doAnalyze()
'''Append a given instruction to the current program after performing analysis'''
def instructionAppend(self, inst):
# print inst
self.scopeAnalyzer.analyze(inst)
self.contextAnalyzer.analyze(inst)
self.typeAnalyzer.analyze(inst)
self.instructionList.append(inst)
''''Utility functions start'''
'''finish this program builder and save the instructions to the program'''
def finish(self):
for i in self.instructionList:
self.program.append(i)
return self.program
'''get variables of type "type" '''
def randVar(self, type=typesData.Types.Unknown, strict=0):
candidates = []
iter = 2*len(self.scopeAnalyzer.scopes)
while len(candidates) == 0 and iter > 0:
candidates = probability.Random.chooseBiased(self.scopeAnalyzer.scopes, 6)
candidates = filter(lambda x: self.typeAnalyzer.getType(x) == type or self.typeAnalyzer.getType(x) == typesData.Types.Unknown, candidates)
iter -= 1
if len(candidates) == 0:
if type == typesData.Types.Boolean:
candidates = [self.loadBoolean(probability.Random.randomBool())]
if type == typesData.Types.String:
candidates = [self.loadString(self.getString())]
if type == typesData.Types.Float:
candidates = [self.loadFloat(self.getFloat())]
if type == typesData.Types.Integer:
candidates = [self.loadInteger(self.getInt())]
if type == typesData.Types.Unknown:
while len(candidates) == 0:
candidates = probability.Random.chooseBiased(self.scopeAnalyzer.scopes, 5)
if len(candidates) == 0:
return False
# print candidates
ret = probability.Random.chooseUniform(candidates)
# print ret, self.typeAnalyzer.getType(ret)
return ret
def generateRandomInst(self):
ret = False
if len(self.scopeAnalyzer.getVisibleVars()) == 0:
codegens = [
CodeGenerator.nullValueGenerator,
CodeGenerator.booleanLiteralGenerator,
CodeGenerator.floatLiteralGenerator,
CodeGenerator.stringLiteralGenerator,
CodeGenerator.integerLiteralGenerator
]
return probability.Random.chooseBiased(codegens,1.5)(self)
while not ret:
choice = probability.Random.chooseWeightedBiased(settings.Settings.allCodeGenerators)
ret = choice(self)
def getInt(self):
def selectFromSeen():
return probability.Random.chooseUniform(list(self.seenIntegers))
def createNew():
return probability.Random.randomInt(-0x1000, 0x1000)
ret = None
while ret == None:
ret = probability.Random.withprobability(0.50, selectFromSeen, createNew)
self.seenIntegers.add(ret)
return ret
def getFloat(self):
def selectFromSeen():
return probability.Random.chooseUniform(list(self.seenFloats))
def createNew():
return probability.Random.randomFloat(-0x1000, 0x1000)
ret = None
while ret == None:
ret = probability.Random.withprobability(0.50, selectFromSeen, createNew)
self.seenFloats.add(ret)
return ret
def getString(self):
def selectFromSeen():
return probability.Random.chooseUniform(list(self.seenStrings))
def createNew():
return probability.Random.randomString(probability.Random.randomInt(0,10))
ret = None
while ret == None:
ret = probability.Random.withprobability(0.50, selectFromSeen, createNew)
self.seenStrings.add(ret)
return ret
def isInLoop(self):
return self.contextAnalyzer.isInLoopContext()
def isInFunction(self):
return self.contextAnalyzer.isInFunctionContext()
def lastContextisLoop(self):
return self.contextAnalyzer.lastContextisLoop()
def getOuterVars(self):
return self.scopeAnalyzer.getOuterVisibleVars()
def getVisibleVars(self):
return self.scopeAnalyzer.getVisibleVars()
def generateCallArguments(self, function):
signature = self.typeAnalyzer.getSignature(function)
if not isinstance(signature, typesData.FunctionSignature):
return False
argsTypes = signature.getInputTypes()
arguments = []
for type in argsTypes:
arguments.append(self.randVar(type))
return arguments
''''Utility functions end'''
'''Returns the next free variable for this program'''
def nextVariable(self):
self.nextFreeVariable += 1
return variable.Variable(self.nextFreeVariable-1)
'''Assign variables and convert the given operation into an instruction'''
def perform(self, ops, inputs=False):
outputs = []
tempVars = []
for i in range(ops.numOutputs):
outputs.append(self.nextVariable())
for i in range(ops.numTempvars):
tempVars.append(self.nextVariable())
if outputs == []:
outputs = False
if tempVars == []:
tempVars = False
inst = instructions.Instruction(ops, inputs, outputs, tempVars)
self.instructionAppend(inst)
return inst
'''Instructions in PHPIL added to this program'''
def nop(self):
return self.perform(operation.Nop()).getOutput()
def loadInteger(self, value):
return self.perform(operation.LoadInteger(value)).getOutput()
def loadFloat(self, value):
return self.perform(operation.LoadFloat(value)).getOutput()
def loadString(self, value):
return self.perform(operation.LoadString(value)).getOutput()
def loadBoolean(self, value):
return self.perform(operation.LoadBoolean(value)).getOutput()
def loadNull(self):
return self.perform(operation.LoadNull()).getOutput()
def createObject(self, object, args, fieldValues):
return self.perform(operation.CreateObject(object, args, fieldValues)).getOutput()
def createArray(self, initialValues):
return self.perform(operation.CreateArray(len(initialValues)), initialValues).getOutput()
def callFunction(self, funcName, args):
return self.perform(operation.CallFunction(len(args) + 1), [funcName] + args).getOutput()
def doPrint(self, value):
return self.perform(operation.Print(), [value]).getOutput()
#beginFunction is not finished in operation.py
def beginFunction(self):
return self.perform(operation.BeginFunction()).getOutput()
#endFunction is not finished in operation.py
def endFunction(self):
return self.perform(operation.EndFunction())
def beginIf(self, conditional):
return self.perform(operation.BeginIf(), [conditional])
def beginElse(self):
return self.perform(operation.BeginElse())
def endIf(self):
return self.perform(operation.EndIf())
def beginWhile(self, lhs, comparater, rhs):
return self.perform(operation.BeginWhile(comparater), [lhs, rhs])
def endWhile(self):
return self.perform(operation.EndWhile())
def beginFor(self, start, comparater, end, op, rhs):
return self.perform(operation.BeginFor(op, comparater), [start, end, rhs])
def copy(self, inp, out):
return self.perform(operation.Copy(), [inp, out])
def endFor(self):
self.perform(operation.EndFor())
def beginDoWhile(self):
return self.perform(operation.BeginDoWhile())
def endDoWhile(self, lhs, comparater, rhs):
return self.perform(operation.EndDoWhile(comparater), [lhs, rhs])
#beginForEach notDefined in operation.py
def beginForEach(self):
return self.perform(operation.BeginForEach())
def endForEach(self):
return self.perform(operation.EndForEach())
def doReturn(self, value):
return self.perform(operation.Return(), [value])
def doBreak(self):
return self.perform(operation.Break(), [])
def doContinue(self):
return self.perform(operation.Continue(), [])
def beginTry(self):
return self.perform(operation.BeginTry())
def beginCatch(self):
return self.perform(operation.BeginCatch())
def endTryCatch(self):
return self.perform(operation.EndTryCatch())
#BeginClass not completed in operation.py
def beginClass(self):
return self.perform(operation.BeginClass()).getOutput()
#EndClass not completed in operation.py
def endClass(self):
return self.perform(operation.EndClass()).getOutput()
def unaryOperation(self, op, input):
return self.perform(operation.UnaryOperation(op), [input]).getOutput()
#check binaryOperation function once again
def binaryOperation(self, lhs, rhs, op):
return self.perform(operation.BinaryOperation(op), [lhs, rhs]).getOutput()
def functionDefination(self, signature):
return self.perform(operation.BeginFunction(signature)).getOutput()
def doInclude(self, value):
return self.perform(operation.Include(), [value])
#check doEval
def doEval(self, string, arguments):
return self.perform(operation.Eval(string, len(argummets)), arguments).getOutput()
def phi(self, var):
return self.perform(operation.Phi(), [var]).getOutput()
def createDict(self, dictElements):
return self.perform(operation.CreateDict(len(dictElements)), dictElements).getOutput()
def getArrayElem(self, arr, elem):
return self.perform(operation.GetArrayElem(), [arr,elem]).getOutput()
def setArrayElem(self, arr, elem, value):
return self.perform(operation.SetArrayElem(), [arr,elem,value])
#ThrowException not completed in operation.py
def throwException(self, value):
return self.perform(operation.ThrowException(), [value])
if __name__ == '__main__':
def main():
a = ProgramBuilder()
out1 = []
out2 = []
out3 = []
for i in range(10):
out1.append(a.getInt())
out2.append(a.getFloat())
out3.append(a.getString())
print out1
print out2
print out3
main()