aboutsummaryrefslogtreecommitdiff
path: root/src/test/java/org/shedlang/compiler/backends/cranelift/PatioToCraneliftTests.java
blob: dc7aea6543fdef62fc02e30901ce035442afedbd (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
package org.shedlang.compiler.backends.cranelift;

import org.shedlang.compiler.backends.targets.NativeTarget;
import org.shedlang.compiler.backends.paths.PartialTargetPath;
import org.shedlang.compiler.patio.PatioCompilationUnit;
import org.shedlang.compiler.patio.PatioExampleTests;
import org.shedlang.compiler.patio.PatioFunctionDefinition;
import org.shedlang.compiler.patio.PatioVisibility;
import org.shedlang.compiler.patio.instructions.Patio;
import org.shedlang.compiler.patio.types.PatioTypes;
import org.shedlang.compiler.runtime.ShedRuntime;
import org.shedlang.compiler.sources.Sources;
import org.shedlang.compiler.testing.ExecutionResult;
import org.shedlang.compiler.testing.TestProcessRunner;
import org.shedlang.compiler.util.Lists;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;

public abstract class PatioToCraneliftTests extends PatioExampleTests {
    @Override
    protected ExecutionResult executeCompilationUnit(PatioCompilationUnit patio) throws IOException, InterruptedException {
        var main = new PatioFunctionDefinition(
            "main",
            PatioVisibility.PUBLIC,
            List.of(),
            List.of(PatioTypes.INT32),
            List.of(
                Patio.call(
                    Optional.empty(),
                    FUNCTION_NAME,
                    List.of()
                ),
                Patio.return_(Patio.int32Const(0))
            ),
            Sources.NULL
        );

        patio = new PatioCompilationUnit(
            Lists.concat(patio.elements(), List.of(main)),
            patio.source()
        );

        Files.createDirectories(Path.of("tests-tmp"));
        var workingDirectory = Files.createTempDirectory(Path.of("tests-tmp"), "PatioToCraneliftTests");

        var backend = CraneliftBackend.forTarget(this.target());
        var objectFilePath = backend.compileCompilationUnit(
            patio,
            new PartialTargetPath(workingDirectory.resolve("main"))
        );

        var executablePath = workingDirectory.resolve("main");

        var runtime = ShedRuntime.defaultRuntime(NativeTarget.AMD64.targetName());
        backend.link(
            List.of(
                objectFilePath,
                runtime.dir().resolve("libpatio_test.a")
            ),
            executablePath,
            runtime
        );

        return TestProcessRunner.runCaptureOutput(List.of(executablePath.toString()));
    }

    protected abstract NativeTarget target();
}