forked from ovr/StaticScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
102 lines (79 loc) · 2.59 KB
/
cli.ts
File metadata and controls
102 lines (79 loc) · 2.59 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import * as ts from 'typescript';
import * as path from 'path';
import * as llvm from 'llvm-node';
import * as cli from "commander";
import {RUNTIME_ARCHIVE_FILE} from "@static-script/runtime";
import {initializeLLVM, generateModuleFromProgram} from './backend/llvm';
import DiagnosticHostInstance from "./diagnostic.host";
import UnsupportedError from "./backend/error/unsupported.error";
import {existsSync, mkdirSync, unlinkSync} from "fs";
import {execFileSync} from "child_process";
interface CommandLineArguments {
args: string[];
printIR?: boolean;
outputFile?: boolean;
}
function parseCommandLine(): CommandLineArguments {
cli
.version('next')
.option('-ir, --printIR', 'Print IR')
.option('-o, --outputFile', 'Name of the executable file')
.parse(process.argv);
return cli as any as CommandLineArguments;
}
const cliOptions = parseCommandLine();
const options = {
lib: [
path.join(__dirname, '..', 'packages', 'runtime', 'lib.runtime.d.ts'),
path.join(__dirname, '..', 'staticscript.d.ts')
],
types: []
};
const files = cliOptions.args;
const host = ts.createCompilerHost(options);
const program = ts.createProgram(files, options, host);
const diagnostics = ts.getPreEmitDiagnostics(program);
if (diagnostics.length) {
const format = ts.formatDiagnosticsWithColorAndContext(diagnostics, DiagnosticHostInstance);
console.log(format);
process.exit(1);
}
initializeLLVM();
try {
const llvmModule = generateModuleFromProgram(program);
llvm.verifyModule(llvmModule);
if (cliOptions.printIR) {
console.log(llvmModule.print());
}
const outputPath = path.join(process.cwd(), 'output');
if (!existsSync(outputPath)) {
mkdirSync(outputPath);
}
try {
llvm.writeBitcodeToFile(llvmModule, path.join(outputPath, 'main.ll'));
const optimizationLevel = "-O3";
execFileSync('llc', [
optimizationLevel,
'-filetype=obj', path.join(outputPath, 'main.ll'),
'-o', path.join(outputPath, 'main.o')
]);
execFileSync("cc", [
optimizationLevel,
path.join(outputPath, 'main.o'),
RUNTIME_ARCHIVE_FILE,
'-o', path.join(outputPath, 'main'),
'-lstdc++',
'-std=c++11',
'-Werror',
'-v',
]);
} finally {
// unlinkSync(outputPath);
}
} catch (e) {
if (e instanceof UnsupportedError) {
console.log(ts.formatDiagnostic(e.toDiagnostic(), DiagnosticHostInstance));
process.exit(1);
}
throw e;
}