blob: b5882967fe4d85577bb18ae0833093f51e3958e5 (
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
|
package org.zwobble.couscous.backends.csharp;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.io.Resources;
import org.zwobble.couscous.Backend;
import org.zwobble.couscous.ast.ClassNode;
import org.zwobble.couscous.ast.MethodNode;
import org.zwobble.couscous.ast.ReturnNode;
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 com.google.common.collect.Iterables.transform;
public class CsharpBackend implements Backend {
private static final List<String> RUNTIME_FILES = ImmutableList.of(
"java/lang/String.cs");
private final Path directoryPath;
private final String namespace;
public CsharpBackend(Path directoryPath, String namespace) {
this.directoryPath = directoryPath;
this.namespace = namespace;
}
@Override
public void compile(List<ClassNode> classes) throws IOException {
Files.write(
directoryPath.resolve("Program.cs"),
Iterables.concat(
transform(
classes,
classNode -> compileClass(classNode)),
transform(
RUNTIME_FILES,
runtimeFile -> readRuntimeFile(runtimeFile))));
}
private String readRuntimeFile(String runtimeFile) {
try {
return Resources.toString(Resources.getResource("csharp/runtime/" + runtimeFile), StandardCharsets.UTF_8);
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
private String compileClass(ClassNode classNode) {
String namespace = this.namespace +
classNode.getName().getPackage()
.map(packageName -> packageName + ".")
.orElse("");
return "namespace " + namespace + " {" +
" internal class " + classNode.getSimpleName() + " {" +
String.join("\n", transform(classNode.getMethods(), method -> compileMethod(method))) +
" }" +
"}";
}
private String compileMethod(MethodNode method) {
ReturnNode returnNode = (ReturnNode) method.getBody().get(0);
return
"public static dynamic " + method.getName() + "() {" +
" return " + CsharpSerializer.serialize(returnNode.getValue(), namespace) + ";" +
"}";
}
}
|