blob: 096bddd3b13162e1e402010d4e0b5ce156acbfd5 (
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
package org.zwobble.couscous.backends.python;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Resources;
import org.zwobble.couscous.Backend;
import org.zwobble.couscous.ast.TypeNode;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.zwobble.couscous.backends.python.PythonCodeGenerator.generateCode;
import static org.zwobble.couscous.backends.python.PythonSerializer.serialize;
import static org.zwobble.couscous.util.ExtraLists.list;
public class PythonBackend implements Backend {
private static final List<String> RUNTIME_FILES = ImmutableList.of(
"java.lang.Object",
"java.lang.Boolean",
"java.lang.Integer",
"java.lang.String",
"_couscous");
private final Path root;
private final String packageName;
public PythonBackend(Path root, String packageName) {
this.root = root;
this.packageName = packageName;
}
@Override
public void compile(List<TypeNode> classes) throws IOException {
for (TypeNode classNode : classes) {
compileClass(classNode);
}
for (String runtimeFile : RUNTIME_FILES) {
String path = relativePathForModule(runtimeFile);
writeModule(
runtimeFile,
Resources.toString(Resources.getResource("python/runtime/" + path), StandardCharsets.UTF_8));
}
}
private Path destinationPathForModule(String moduleName) {
return root.resolve(packageName).resolve(relativePathForModule(moduleName));
}
private String relativePathForModule(String moduleName) {
return moduleName.replace(".", File.separator) + ".py";
}
private void compileClass(TypeNode classNode) throws IOException {
writeModule(
classNode.getName().getQualifiedName(),
serialize(generateCode(classNode)));
}
private void writeModule(String name, String contents) throws IOException {
Path path = destinationPathForModule(name);
Files.createDirectories(path.getParent());
createPythonPackages(path.getParent());
Files.write(path, list(contents));
}
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();
}
}
}
|