blob: c5ea3e3f49b0d9f31ac2b8559c47facf180e42b2 (
plain)
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
|
package org.zwobble.couscous.backends.python;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.zwobble.couscous.ast.TypeName;
import org.zwobble.couscous.ast.ClassNode;
import static java.util.Arrays.asList;
import static org.zwobble.couscous.backends.python.PythonCodeGenerator.generateCode;
import static org.zwobble.couscous.backends.python.PythonSerializer.serialize;
public class PythonCompiler {
private final Path root;
private final String packageName;
public PythonCompiler(Path root, String packageName) {
this.root = root;
this.packageName = packageName;
}
public void compile(List<ClassNode> classes) {
for (ClassNode classNode : classes) {
compileClass(classNode);
}
writeClass(TypeName.of("java.lang.Integer"), "class Integer(object):\n def parseInt(value):\n return int(value)");
}
private Path pathForClass(TypeName className) {
return root.resolve(packageName)
.resolve(className.getQualifiedName().replace(".", File.separator) + ".py");
}
private void compileClass(ClassNode classNode) {
writeClass(classNode.getName(), serialize(generateCode(classNode)));
}
private void writeClass(TypeName name, String contents) {
try {
final java.nio.file.Path path = pathForClass(name);
Files.createDirectories(path.getParent());
createPythonPackages(path.getParent());
Files.write(path, asList(contents));
} catch (final java.lang.Throwable $ex) {
throw new RuntimeException($ex);
}
}
private void createPythonPackages(Path packagePath) throws IOException {
while (packagePath.startsWith(root)) {
final java.nio.file.Path packageFile = packagePath.resolve("__init__.py");
if (!packageFile.toFile().exists()) {
Files.createFile(packageFile);
}
packagePath = packagePath.getParent();
}
}
}
|