aboutsummaryrefslogtreecommitdiff
path: root/src/test/java/org/zwobble/couscous/tests/backends/csharp/CsharpTestBackend.java
blob: fcf7ab5e97806f88e4724b2e8128f65073909eff (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
package org.zwobble.couscous.tests.backends.csharp;

import com.google.common.collect.ImmutableList;
import com.google.common.io.Resources;
import org.zwobble.couscous.Backend;
import org.zwobble.couscous.ast.TypeNode;
import org.zwobble.couscous.backends.csharp.CsharpBackend;

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 CsharpTestBackend implements Backend {
    private static final List<String> RUNTIME_FILES = ImmutableList.of(
        "java/lang/Integer.cs",
        "java/lang/Object.cs",
        "java/util/Arrays.cs",
        // TODO: implement Iterable/Iterator in Java
        "java/lang/Iterable.cs",
        "java/util/Iterator.cs");

    private final Path outputDirectory;
    private final String namespace;

    public CsharpTestBackend(Path outputDirectory, String namespace) {
        this.outputDirectory = outputDirectory;
        this.namespace = namespace;
    }

    @Override
    public void compile(List<TypeNode> classes) throws IOException {
        new CsharpBackend(outputDirectory.resolve("Program.cs"), namespace).compile(classes);
        Files.write(
            outputDirectory.resolve("Runtime.cs"),
            transform(
                RUNTIME_FILES,
                runtimeFile -> readRuntimeFile(runtimeFile)));
    }

    private String readRuntimeFile(String runtimeFile) {
        try {
            return Resources.toString(Resources.getResource("org/zwobble/couscous/tests/backends/csharp/runtime/" + runtimeFile), StandardCharsets.UTF_8)
                .replace("namespace Couscous", "namespace " + namespace);
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }
}