-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathProgramBuilder.java
More file actions
302 lines (263 loc) · 10.2 KB
/
ProgramBuilder.java
File metadata and controls
302 lines (263 loc) · 10.2 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
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
package CBuilder;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import CBuilder.objects.MPyClass;
import CBuilder.objects.functions.Function;
import CBuilder.objects.functions.ReturnStatement;
import CBuilder.variables.VariableDeclaration;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** Entrypoint to creating C code from a MiniPython AST. */
public class ProgramBuilder {
/** Definition of the c-runtime header files. */
private static final String[] headers = {
// allow usage of assertions
"assert",
// aliases mapping python names to the internal c names
"mpy_aliases",
// ref-counting
"mpy_obj",
// initialisation
"builtins-setup",
// building function args
"function-args",
"literals/tuple",
"literals/int",
"literals/boolean",
"literals/str",
"type-hierarchy/object",
// custom objects
"type-hierarchy/type",
};
/** A list of all statements in the global scope. */
private final List<Statement> statements;
/** A list of all defined variables in the global scope. */
private final List<VariableDeclaration> globalVariables;
/** A list of all defined functions in the global scope. */
private final List<Function> globalFunctions;
/** A list of all defined classes in th global scope. */
private final List<MPyClass> classes;
/**
* Create a new program with empty global scope. Allows to manually specify options regarding
* c-code generation.
*/
public ProgramBuilder() {
statements = new LinkedList<>();
globalVariables = new java.util.LinkedList<>();
globalFunctions = new LinkedList<>();
classes = new LinkedList<>();
}
/**
* Add a new statement to the global scope. The resulting statement list more or less represents
* the program's main method.
*
* @param statement The statement to add.
*/
public void addStatement(Statement statement) {
if (statement instanceof ReturnStatement) {
// I'd prefer to have this type safe (i. e. different statement interfaces for
// global/non-global scope,
// but this is just a prototype after all and shouldn't happen too often anyway)
throw new IllegalArgumentException("Cannot return from global scope");
}
statements.add(statement);
}
/**
* Add a new variable to the global scope.
*
* @param variable The variable to add.
*/
public void addVariable(VariableDeclaration variable) {
globalVariables.add(variable);
}
/**
* Add a new function definition to the global scope.
*
* @param function The function to add.
*/
public void addFunction(Function function) {
globalFunctions.add(function);
}
/**
* Add a new class definition to the global scope.
*
* @param mPyClass The class to add.
*/
public void addClass(MPyClass mPyClass) {
classes.add(mPyClass);
}
/**
* Generate a c-program of the containing elements.
*
* @return A string which containing the generated c-program.
*/
public String buildProgram() {
StringBuilder program = new StringBuilder();
program.append("#include <stddef.h>\n");
program.append('\n');
for (String headerName : headers) {
program.append("#include \"" + headerName + ".h\"\n");
}
program.append('\n');
for (VariableDeclaration v : globalVariables) {
program.append(v.build(false));
}
program.append('\n');
for (Function f : globalFunctions) {
program.append(f.buildFuncObjectDeclaration());
program.append(f.buildCFunction());
}
program.append('\n');
for (MPyClass c : classes) {
program.append(c.buildDeclaration());
}
program.append('\n');
program.append("int main(int argc, char *argv[]) {\n");
StringBuilder body = new StringBuilder();
// setup builtins written in C
body.append("__mpy_builtins_setup();\n");
// first init global variables
// cannot be done above due to c's notion of 'const' variables/initializers
for (VariableDeclaration v : globalVariables) {
// but does not init the global var
body.append(v.buildInitialisation());
}
body.append('\n');
// then init the global functions
for (Function f : globalFunctions) {
body.append(f.buildInitialisation());
}
body.append('\n');
for (MPyClass c : classes) {
body.append(c.buildInitialisation());
}
body.append('\n');
// then the statements
for (Statement s : statements) {
body.append(s.buildStatement());
}
body.append('\n');
// finally decrement refcount of all global variables
for (VariableDeclaration v : globalVariables) {
body.append(v.buildRefDec());
}
body.append('\n');
for (Function f : globalFunctions) {
body.append(f.buildRefDec());
}
body.append('\n');
for (MPyClass c : classes) {
body.append(c.buildRefDec());
}
body.append('\n');
// and cleanup behind builtin setup
body.append("__mpy_builtins_cleanup();\n");
body.append("return 0;\n");
program.append(
body.toString()
.lines()
.map(string -> "\t" + string + "\n")
.collect(Collectors.joining()));
program.append("}\n");
return program.toString();
}
/**
* Emit the c-program as file and copy the c-runtime into the destination directory.
*
* @param destDir The directory reveiving the files.
*/
public void writeProgram(Path destDir) {
try {
// make sure to create the target folder
if (!destDir.toFile().exists()) destDir.toFile().mkdirs();
// copy all files to target folder
if (getClass().getResource("/c-runtime").toURI().getScheme().equals("file")) {
Path srcDir = Path.of(ProgramBuilder.class.getResource("/c-runtime").toURI());
copyFolder(srcDir, destDir);
} else {
copyFolderFromJar("/c-runtime", destDir);
}
} catch (URISyntaxException e) {
throw new RuntimeException("Failed to get resource URI for template folder", e);
} catch (IOException e) {
throw new RuntimeException("Failed to copy template folder to output directory", e);
}
try {
Path output = Path.of(destDir.toString(), "src/program.c");
java.nio.file.Files.writeString(
output,
this.buildProgram(),
java.nio.file.StandardOpenOption.CREATE,
java.nio.file.StandardOpenOption.WRITE,
java.nio.file.StandardOpenOption.TRUNCATE_EXISTING);
} catch (java.io.IOException e) {
throw new RuntimeException("Failed to write 'program.c'!", e);
}
}
/**
* Copy the c-runtime folder into the target location.
*
* @param srcDir The Path to the jar archive.
* @param destDir The output directory.
* @throws IOException Will be thrown if a needed file or folder is not accessible.
*/
public void copyFolder(Path srcDir, Path destDir) throws IOException {
try (Stream<Path> stream = Files.walk(srcDir)) {
stream.forEach(
source -> {
try {
Files.copy(
source,
destDir.resolve(srcDir.relativize(source)),
REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException(
"Failed to copy template folder to output directory", e);
}
});
}
}
/**
* Copy the c-runtime folder from jar into the target location.
*
* @param resourcePath The Path to the jar archive.
* @param targetLocation The output directory.
* @throws URISyntaxException Will be thrown if the c-runtime can not be found in the
* application resources.
* @throws IOException Will be thrown if a needed file or folder is not accessible.
*/
public void copyFolderFromJar(String resourcePath, final Path targetLocation)
throws URISyntaxException, IOException {
URI resource = getClass().getResource("/c-runtime").toURI();
try (FileSystem fileSystem = FileSystems.newFileSystem(resource, Map.of())) {
final Path jarArchive = fileSystem.getPath(resourcePath);
Files.walkFileTree(
jarArchive,
new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(
Path dir, BasicFileAttributes attrs) throws IOException {
Files.createDirectories(
targetLocation.resolve(jarArchive.relativize(dir).toString()));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.copy(
file,
targetLocation.resolve(jarArchive.relativize(file).toString()),
REPLACE_EXISTING);
return FileVisitResult.CONTINUE;
}
});
}
}
}