-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprogram_generation
More file actions
executable file
·273 lines (201 loc) · 7.48 KB
/
program_generation
File metadata and controls
executable file
·273 lines (201 loc) · 7.48 KB
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
#!/usr/bin/python
import argparse
import random
import subprocess
a_expressions = ["int", "id", "+", "-", "*", "input"]
b_expressions = ["true", "false", "<", "=", "not", "and", "or"]
statements = ["if", "while", "output", "ass", "skip", "semi"]
vars = []
max_int = 10
max_bexpr_depth = 2
max_aexpr_depth = 2
max_depth = 4
tab = " "
def rand_inst(arr):
return arr[random.randint(0, len(arr) - 1)]
def gen_if(cond, then_stmt, else_stmt, indent):
return f"{indent*tab}if {cond} then {{\n{then_stmt}\n{(indent) * tab}}} else {{\n{else_stmt}\n{(indent)*tab}}}"
def gen_while(cond, do_stmt, indent):
return f"{indent*tab}while ({cond}) do {{\n{do_stmt}\n{(indent)*tab}}}"
def gen_output(aexpr, indent):
return f"{indent*tab}output {aexpr}"
def gen_ass(var, aexpr, indent):
return f"{indent*tab}{var} := {aexpr}"
def gen_var_dec():
new_var = f"v{len(vars)}"
vars.append(new_var)
return f"var {new_var}"
def gen_skip(indent):
return f"{indent*tab}skip"
def gen_semi(first_stmt, second_stmt):
return f"{first_stmt};\n{second_stmt}"
def gen_op(op, lhs, rhs):
return f"{lhs} {op} {rhs}"
def gen_input():
return "input"
def random_var():
index = random.randint(0, len(vars) - 1)
if index >= 0:
return vars[index]
else:
raise Exception("Program had no variables to use")
def random_aexpr(max_depth):
if (max_depth > max_aexpr_depth):
max_depth = max_aexpr_depth
if (max_depth <= 1):
return random.randint(0, max_int)
aexpr = rand_inst(a_expressions)
match aexpr:
case "int":
return random.randint(0, max_int)
case "id":
return random_var()
case "+" | "-" | "*":
return f"({gen_op(aexpr, random_aexpr(max_depth - 1),
random_aexpr(max_depth - 1))})"
case "input":
return gen_input()
case _:
raise Exception("Error, generation of aexpr failed")
def random_bexpr(max_depth):
if (max_depth > max_bexpr_depth):
max_depth = max_bexpr_depth
if (max_depth <= 1):
if (random.randint(0, 1) == 0):
return "true"
else:
return "false"
bexpr = rand_inst(b_expressions)
match bexpr:
case "true":
return "true"
case "false":
return "false"
case "not":
return f"not({random_bexpr(max_depth - 1)})"
case "or" | "and":
return f"({gen_op(bexpr, random_bexpr(max_depth - 1),
random_bexpr(max_depth - 1))})"
case "<" | "=":
return f"({gen_op(bexpr, random_aexpr(max_depth - 1),
random_aexpr(max_depth - 1))})"
case _:
raise Exception("Error, generation of bexpr failed")
def random_stmt(max_depth, indent):
if (max_depth <= 1):
match random.randint(0, 2):
case 0:
return gen_skip(indent)
case 1:
return gen_ass(random_var(), random_aexpr(1), indent)
stmt = rand_inst(statements)
match stmt:
case "skip":
return gen_skip(indent)
case "if":
return gen_if(random_bexpr(max_depth - 1),
random_stmt(max_depth - 1, indent + 1),
random_stmt(max_depth - 1, indent + 1), indent)
case "while":
return gen_while(random_bexpr(max_depth - 1),
random_stmt(max_depth - 1, indent + 1), indent)
case "output":
return gen_output(random_aexpr(max_depth - 1), indent)
case "ass":
return gen_ass(random_var(), random_aexpr(max_depth - 1), indent)
case "semi":
return gen_semi(random_stmt(max_depth - 1, indent),
random_stmt(max_depth - 1, indent))
case _:
raise Exception("Error, generation of stmt failed")
def gen_fully_random_program(max_loc):
global max_depth
global tab
main_stmt = f"fun main() {{\n{tab}"
loc = 1
number_of_vars = 5
if max_loc < 100:
number_of_vars = 10
elif max_loc < 500:
number_of_vars = 20
else:
number_of_vars = 30
for i in range(number_of_vars):
main_stmt += gen_var_dec() + "; "
loc += 1
main_stmt += "\n"
while loc < max_loc:
new_stmt = f"{random_stmt(max_depth, 1)};\n"
main_stmt += new_stmt
loc += new_stmt.count("\n")
return main_stmt + "\n}"
def gen_partial_random_program(max_loc):
# Template blocks where generated by chat gpt
TEMPLATE_BLOCKS = [
# Constant folding and propagation
"x := 2 + 3 + 5;\ny := x + 1 - 2;\noutput y;",
# Constant folding with nested expressions
"a := 10;\nb := a + 0;\nc := b * 1;\noutput c;",
# Dead code elimination - if false branch
"if false then {\n x := 42;\n} else {\n skip;\n};",
# Dead code elimination - redundant else
"if true then {\n y := 1;\n} else {\n y := 999;\n};\noutput y;",
# Unused variable
"a := 5;\nb := a + 3;\n// b is never used",
# Redundant assignment
"x := 7;\nx := x;\nx := x + 0;\noutput x;",
# Assignment overwritten before use
"z := 1;\nz := 2;\noutput z;",
# Constant equality check
"x := 3;\nif x = 3 then {\n output 1;\n} else {\n output 0;\n};",
# Unreachable loop
"x := 10;\nwhile (x < 0) do {\n x := x + 1;\n};",
# Dead code inside branches
"if false then {\n y := 100;\n output y;\n} else {\n skip;\n};",
# Multiple constant uses
"a := 4;\nb := a + 4 + a;\nc := b * 2;\noutput c;",
# Constant comparison short-circuiting
"if 3 < 5 then {\n x := 1;\n} else {\n x := 2;\n};\noutput x;",
# Redundant operations in sequence
"x := 0;\nx := x + 1;\nx := x + 0;\nx := x - 0;\noutput x;",
# Conditional overwrite
"x := 5;\nif true then {\n x := 6;\n} else {\n x := 7;\n};\noutput x;"
# Factorial
"y := input;\nx := 1;\nwhile 1 < x do {\ny:=x * y;\n x:=x - 1\n};\noutput y;"
# For loop
"i := 1;\nwhile i < input do {i := i + 1};\noutput i;"
]
main_stmt = "var x; var y; var z; var a; var b; var c; var i;\n"
loc = 0
while loc < max_loc:
next_inst = rand_inst(TEMPLATE_BLOCKS) + "\n"
loc += next_inst.count("\n")
main_stmt += next_inst
return f"fun main() {{\n{main_stmt}\n}}"
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-loc", "--line-of-code", dest="loc", type=int)
parser.add_argument("-f", "--fully-random", dest="fully_random", type=bool)
parser.add_argument("-p", "--partial-random",
dest="partial_random", type=bool)
args = parser.parse_args()
max_loc = args.loc
if args.partial_random:
generated = gen_partial_random_program(max_loc)
elif args.fully_random:
generated = gen_fully_random_program(max_loc)
else:
print("Error, invalid mode.")
return
# Write to file
path = "generated/generated.while"
with open(path, "w") as f:
f.write(generated)
print(f"Generated program saved to {path}")
try:
subprocess.run(["./build/while", "-s", "-p",
path, "-l" "Debug"], check=True)
except subprocess.CalledProcessError as e:
print(f"Error running analyzer: {e}")
if __name__ == "__main__":
main()