Repository navigation
Expand file tree
/
Copy pathcompose.py
More file actions
112 lines (91 loc) · 4.04 KB
/
Copy pathcompose.py
File metadata and controls
112 lines (91 loc) · 4.04 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
102
103
104
105
106
107
108
109
110
111
112
"""
compose - the Shark toolchain (spec/12-toolchain.md), reference edition.
python compose.py build <file.shark> compile to target/<name>.exe
python compose.py run <file.shark> compile, then run it
python compose.py check <file.shark> check without writing anything
python compose.py version
`build` and `run` produce a native Windows x86-64 executable. The machine code
and the executable format are generated by Shark's own back end
(reference/shark_native.py and reference/x64.py). No C compiler, assembler,
linker or runtime library is involved, and the program that comes out imports
nothing except KERNEL32.dll, which is part of Windows.
"""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "reference"))
import shark_ref # noqa: E402
from shark_native import CompileError, compile_sir # noqa: E402
from x64 import read_imports # noqa: E402
VERSION = "0.1.0"
def compile_path(path: str) -> tuple:
"""Front end then back end. Returns (compilation, executable bytes)."""
comp = shark_ref.compile_file(path)
used = {name: inner.sir for name, inner in comp.modules().items() if inner is not comp}
return comp, compile_sir(comp.sir, used)
def target_path(path: str, output: str = "") -> str:
if output:
return output
stem = os.path.basename(path)
for suffix in (".shark",):
if stem.endswith(suffix):
stem = stem[: -len(suffix)]
return os.path.join("target", stem + ".exe")
def report(err: Exception, path: str) -> None:
if isinstance(err, shark_ref.SharkError):
source_line = ""
if err.line and os.path.exists(path):
with open(path, encoding="utf-8") as handle:
lines = handle.read().splitlines()
if 0 < err.line <= len(lines):
source_line = lines[err.line - 1]
print(err.render(path, source_line), file=sys.stderr)
else:
print("{} {}\n in {}".format(err.code, err.message, path), file=sys.stderr)
def build(path: str, output: str = "", quiet: bool = False) -> str:
comp, image = compile_path(path)
out = target_path(path, output)
os.makedirs(os.path.dirname(out) or ".", exist_ok=True)
with open(out, "wb") as handle:
handle.write(image)
if not quiet:
print("built {} ({} bytes, {}, imports {})".format(
out, len(image), comp.hash[:15], ", ".join(read_imports(image))))
return out
def main(argv: list = None) -> int:
shark_ref._force_utf8_output()
parser = argparse.ArgumentParser(prog="compose", description="The Shark toolchain.")
commands = parser.add_subparsers(dest="command")
for name, text in (("build", "compile to a native executable"),
("run", "compile, then run"),
("check", "check a program without writing anything")):
command = commands.add_parser(name, help=text)
command.add_argument("file")
if name != "check":
command.add_argument("-o", "--output", default="")
commands.add_parser("version", help="print the toolchain version")
args = parser.parse_args(argv)
if args.command == "version":
print("compose {} (Shark Edition 2026, reference toolchain)".format(VERSION))
return 0
if args.command is None:
parser.print_help()
return 2
try:
if args.command == "check":
comp, image = compile_path(args.file)
print("ok {} {} native: {} bytes".format(args.file, comp.hash, len(image)))
return 0
out = build(args.file, args.output, quiet=args.command == "run")
if args.command == "run":
sys.stdout.flush()
return subprocess.call([os.path.abspath(out)])
return 0
except (shark_ref.SharkError, CompileError) as err:
report(err, args.file)
return 1
if __name__ == "__main__":
sys.exit(main())