blob: 2c3e7a783a6ae3c704c0fab41fe501930896251c (
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
79
80
81
82
83
84
|
package org.shedlang.compiler.cli;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.ext.java7.PathArgumentType;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import org.shedlang.compiler.ShedCompiler;
import org.shedlang.compiler.backends.Backends;
import org.shedlang.compiler.backends.targets.ShedTarget;
import org.shedlang.compiler.errors.CompilerError;
import org.shedlang.compiler.sources.NullSource;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;
public class ShedCli {
public static void main(String[] rawArgs) throws IOException, InterruptedException {
var args = parseArgs(rawArgs);
try {
compile(args);
} catch (CompilerError error) {
if (!(error.source() instanceof NullSource)) {
System.err.println(error.source().describe());
}
System.err.println(error.getMessage());
System.exit(2);
}
}
private static void compile(Namespace args) throws IOException, InterruptedException {
var sourcePath = args.<Path>get("source");
var compiler = new ShedCompiler();
switch (args.<Command>get("command")) {
case COMPILE -> {
var target = ShedTarget.fromString(args.getString("target")).orElseThrow();
var backend = Optional.ofNullable(args.getString("backend"))
.map(
backendName ->
Backends
.backendFactory(backendName)
// In principle, this should be prevented by the arg parsing.
.orElseThrow(() -> new UnsupportedOperationException("Unrecognised backend: " + backendName))
.backendForTarget(target)
.orElseThrow(() -> new UnsupportedTargetError(backendName, target))
)
.orElseGet(() -> Backends.backendForTarget(target));
var profile = Optional.ofNullable(args.getString("profile"));
compiler.compile(sourcePath, backend, profile);
}
}
}
private static Namespace parseArgs(String[] args) {
var parser = ArgumentParsers.newFor("shed").build()
.defaultHelp(true);
var subparsers = parser.addSubparsers();
var compileSubParser = subparsers.addParser("compile");
compileSubParser.setDefault("command", Command.COMPILE);
compileSubParser
.addArgument("source")
.type(new PathArgumentType())
.required(true);
compileSubParser.addArgument("--backend").choices(Backends.backendNames()).required(false);
compileSubParser.addArgument("--target").choices(ShedTarget.targetNames()).required(true);
compileSubParser.addArgument("--profile").required(false);
try {
return parser.parseArgs(args);
} catch (ArgumentParserException e) {
parser.handleError(e);
System.exit(1);
throw new RuntimeException(e);
}
}
private enum Command {
COMPILE,
}
}
|