kasi-compiler 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
kasi/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """KASI Compiler: Python AST -> inferred types -> C -> native executable."""
2
+
3
+ from .driver import compile_file
4
+ from .version import __version__
5
+
6
+ __all__ = ["compile_file", "__version__"]
kasi/__main__.py ADDED
@@ -0,0 +1,321 @@
1
+ """Command line interface for KASI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from .driver import (
11
+ analyze_source,
12
+ compile_file,
13
+ find_compiler,
14
+ read_metadata,
15
+ train_profile,
16
+ )
17
+ from .version import __version__
18
+
19
+
20
+ def _compile(*args, **kwargs):
21
+ try:
22
+ return compile_file(*args, **kwargs)
23
+ except RuntimeError as exc:
24
+ print(f"kasi: error: {exc}", file=sys.stderr)
25
+ raise SystemExit(2) from None
26
+ except subprocess.CalledProcessError as exc:
27
+ print(f"kasi: compiler failed (exit {exc.returncode})", file=sys.stderr)
28
+ raise SystemExit(2) from None
29
+
30
+
31
+ def _analysis(path: Path, *, comptime: bool = True):
32
+ try:
33
+ return analyze_source(path, comptime=comptime)
34
+ except SyntaxError as exc:
35
+ print(f"kasi: error: {exc.msg} (line {exc.lineno})", file=sys.stderr)
36
+ raise SystemExit(2) from None
37
+ except OSError as exc:
38
+ print(f"kasi: error: {exc}", file=sys.stderr)
39
+ raise SystemExit(2) from None
40
+
41
+
42
+ def _parse_size(value: str) -> int:
43
+ text = value.strip().lower()
44
+ multiplier = 1
45
+ for suffix, factor in (("k", 1024), ("m", 1024 * 1024), ("g", 1024 * 1024 * 1024)):
46
+ if text.endswith(suffix):
47
+ multiplier = factor
48
+ text = text[:-1]
49
+ break
50
+ try:
51
+ return int(text) * multiplier
52
+ except ValueError:
53
+ raise argparse.ArgumentTypeError(f"invalid size: {value}") from None
54
+
55
+
56
+ def main(argv: list[str] | None = None) -> int:
57
+ parser = argparse.ArgumentParser(
58
+ prog="kasi",
59
+ description="KASI Compiler: compile Python to a native executable.",
60
+ )
61
+ parser.add_argument("--version", action="version", version=f"kasi {__version__}")
62
+ sub = parser.add_subparsers(dest="command", required=True)
63
+
64
+ compile_cmd = sub.add_parser("compile", help="compile a .py file to a native executable")
65
+ compile_cmd.add_argument("source", type=Path)
66
+ compile_cmd.add_argument("-o", "--output", type=Path)
67
+ compile_cmd.add_argument("--emit-c", type=Path, help="save the generated C source")
68
+ compile_cmd.add_argument("--emit-llvm", type=Path, help="save LLVM IR (requires Zig/Clang)")
69
+ compile_cmd.add_argument("-O", type=int, choices=range(0, 4), default=3)
70
+ compile_cmd.add_argument("--compiler", help="path to zig or a C compiler")
71
+ compile_cmd.add_argument(
72
+ "--target",
73
+ help="Zig target triple, e.g. x86_64-linux-musl, wasm32-wasi, thumbv7m-none-eabi",
74
+ )
75
+ compile_cmd.add_argument("--explain", type=Path, help="write an HTML speed map")
76
+ compile_cmd.add_argument("--guards", action="store_true", help="emit guarded dual entry points")
77
+ compile_cmd.add_argument(
78
+ "--train", nargs="?", const="", default=None, metavar="INPUT",
79
+ help="collect a type profile from an instrumented run, then rebuild",
80
+ )
81
+ compile_cmd.add_argument("--profile", type=Path, help="apply a saved .kprofile")
82
+ compile_cmd.add_argument("--deterministic", action="store_true", help="reject dynamic fallbacks")
83
+ compile_cmd.add_argument("--arena-size", type=_parse_size, help="arena size, e.g. 64M")
84
+ compile_cmd.add_argument("--emit-lib", choices=("static", "shared"), help="build a library instead")
85
+ compile_cmd.add_argument("--repro", action="store_true", help="reproducible build")
86
+ compile_cmd.add_argument("--no-comptime", action="store_true", help="disable compile-time execution")
87
+ compile_cmd.add_argument("--include-dir", action="append", default=[], help="native header search path")
88
+ compile_cmd.add_argument("-D", "--define", action="append", default=[], help="pass -D to the C compiler")
89
+ compile_cmd.add_argument("-W", "--Wall", action="store_true", help="print compile-time diagnostics")
90
+ compile_cmd.add_argument("-v", "--verbose", action="store_true")
91
+ compile_cmd.add_argument("-q", "--quiet", action="store_true")
92
+
93
+ run_cmd = sub.add_parser("run", help="compile and immediately run a Python file")
94
+ run_cmd.add_argument("source", type=Path)
95
+ run_cmd.add_argument("-O", type=int, choices=range(0, 4), default=3)
96
+ run_cmd.add_argument("--compiler")
97
+ run_cmd.add_argument("args", nargs=argparse.REMAINDER)
98
+
99
+ sub.add_parser("compiler", help="show which native compiler KASI will use")
100
+ sub.add_parser("bench", help="compare CPython and KASI native execution")
101
+
102
+ types_cmd = sub.add_parser("types", help="print inferred types with their rules")
103
+ types_cmd.add_argument("source", type=Path)
104
+ types_cmd.add_argument("--json", action="store_true", help="emit JSON")
105
+ types_cmd.add_argument("--no-comptime", action="store_true")
106
+
107
+ explain_cmd = sub.add_parser("explain", help="write an HTML speed map")
108
+ explain_cmd.add_argument("source", type=Path)
109
+ explain_cmd.add_argument("-o", "--output", type=Path)
110
+ explain_cmd.add_argument("--no-comptime", action="store_true")
111
+
112
+ lint_cmd = sub.add_parser("lint", help="run compile-time diagnostics")
113
+ lint_cmd.add_argument("source", type=Path)
114
+ lint_cmd.add_argument("--no-comptime", action="store_true")
115
+
116
+ transpile_cmd = sub.add_parser("transpile", help="print readable, commented C")
117
+ transpile_cmd.add_argument("source", type=Path)
118
+ transpile_cmd.add_argument("-o", "--output", type=Path)
119
+ transpile_cmd.add_argument("--no-comptime", action="store_true")
120
+
121
+ info_cmd = sub.add_parser("info", help="show provenance embedded in a KASI binary")
122
+ info_cmd.add_argument("binary", type=Path)
123
+
124
+ tune_cmd = sub.add_parser("tune", help="benchmark compiler variants and keep the fastest")
125
+ tune_cmd.add_argument("source", type=Path)
126
+ tune_cmd.add_argument("-o", "--output", type=Path)
127
+ tune_cmd.add_argument("--reps", type=int, default=3, help="runs per variant")
128
+ tune_cmd.add_argument("--compiler")
129
+ tune_cmd.add_argument("--target")
130
+ tune_cmd.add_argument("--input", type=Path, help="stdin data for benchmark runs")
131
+ tune_cmd.add_argument("-v", "--verbose", action="store_true")
132
+
133
+ args = parser.parse_args(argv)
134
+
135
+ if args.command == "compiler":
136
+ try:
137
+ path, kind = find_compiler(getattr(args, "compiler", None))
138
+ except RuntimeError as exc:
139
+ print(f"kasi: error: {exc}", file=sys.stderr)
140
+ return 2
141
+ print(f"{kind}: {path}")
142
+ return 0
143
+
144
+ if args.command == "bench":
145
+ from .bench import main as bench_main
146
+
147
+ bench_main()
148
+ return 0
149
+
150
+ if args.command == "run":
151
+ result = _compile(args.source, opt=args.O, compiler=args.compiler)
152
+ try:
153
+ return subprocess.run([str(result.executable), *args.args]).returncode
154
+ except OSError as exc:
155
+ print(f"kasi: error: {exc}", file=sys.stderr)
156
+ return 2
157
+
158
+ if args.command == "info":
159
+ metadata = read_metadata(args.binary)
160
+ if metadata is None:
161
+ print("kasi: error: not a KASI binary", file=sys.stderr)
162
+ return 2
163
+ for key in ("version", "source", "sha256", "target", "flags"):
164
+ if key in metadata:
165
+ print(f"{key}: {metadata[key]}")
166
+ return 0
167
+
168
+ if args.command == "tune":
169
+ from .tune import tune as tune_file
170
+
171
+ try:
172
+ result = tune_file(
173
+ args.source,
174
+ output=args.output,
175
+ reps=args.reps,
176
+ compiler=args.compiler,
177
+ target=args.target,
178
+ input_path=args.input,
179
+ verbose=args.verbose,
180
+ )
181
+ except RuntimeError as exc:
182
+ print(f"kasi: error: {exc}", file=sys.stderr)
183
+ return 2
184
+ except subprocess.CalledProcessError as exc:
185
+ print(f"kasi: compiler failed (exit {exc.returncode})", file=sys.stderr)
186
+ return 2
187
+ print(f"best: {result.best.name}")
188
+ for name, seconds in result.timings.items():
189
+ print(f" {name}: {seconds:.4f}s")
190
+ for note in result.notes:
191
+ print(f"note: {note}", file=sys.stderr)
192
+ print(f"native executable: {result.executable}")
193
+ return 0
194
+
195
+ if args.command == "types":
196
+ from .explain import json_report, text_report
197
+
198
+ analysis = _analysis(args.source, comptime=not args.no_comptime)
199
+ print(
200
+ json_report(analysis.infos)
201
+ if args.json
202
+ else text_report(analysis.source, analysis.infos),
203
+ end="",
204
+ )
205
+ return 0
206
+
207
+ if args.command == "explain":
208
+ from .explain import html_report
209
+
210
+ analysis = _analysis(args.source, comptime=not args.no_comptime)
211
+ document = html_report(analysis.source, analysis.infos, analysis.warnings)
212
+ if args.output:
213
+ path = args.output.resolve()
214
+ path.parent.mkdir(parents=True, exist_ok=True)
215
+ path.write_text(document, encoding="utf-8")
216
+ print(f"speed map: {path}")
217
+ else:
218
+ print(document, end="")
219
+ return 0
220
+
221
+ if args.command == "lint":
222
+ analysis = _analysis(args.source, comptime=not args.no_comptime)
223
+ for diagnostic in analysis.diagnostics:
224
+ print(diagnostic)
225
+ return 1 if analysis.diagnostics else 0
226
+
227
+ if args.command == "transpile":
228
+ from .codegen import CodeGen
229
+
230
+ analysis = _analysis(args.source, comptime=not args.no_comptime)
231
+ code = CodeGen(
232
+ analysis.funcs, analysis.warnings, analysis.inferencer,
233
+ transpile=True, source_text=analysis.source,
234
+ ).generate(analysis.tree)
235
+ if args.output:
236
+ path = args.output.resolve()
237
+ path.parent.mkdir(parents=True, exist_ok=True)
238
+ path.write_text(code, encoding="utf-8")
239
+ print(f"C source: {path}")
240
+ else:
241
+ print(code, end="")
242
+ return 0
243
+
244
+ profile = None
245
+ if args.profile:
246
+ from .profile import Profile
247
+
248
+ try:
249
+ profile = Profile.load(args.profile)
250
+ except (OSError, ValueError) as exc:
251
+ print(f"kasi: error: {exc}", file=sys.stderr)
252
+ return 2
253
+
254
+ try:
255
+ if args.train is not None:
256
+ result = train_profile(
257
+ args.source,
258
+ output=args.output,
259
+ input_path=(Path(args.train) if args.train else None),
260
+ compiler=args.compiler,
261
+ opt=args.O,
262
+ target=args.target,
263
+ )
264
+ else:
265
+ result = _compile(
266
+ args.source,
267
+ output=args.output,
268
+ emit_c=args.emit_c,
269
+ opt=args.O,
270
+ compiler=args.compiler,
271
+ emit_llvm=args.emit_llvm,
272
+ target=args.target,
273
+ verbose=args.verbose,
274
+ guards=args.guards,
275
+ profile=profile,
276
+ deterministic=args.deterministic,
277
+ arena_size=args.arena_size,
278
+ emit_lib=args.emit_lib,
279
+ repro=args.repro,
280
+ extra_flags=[f"-D{item}" for item in args.define],
281
+ comptime=not args.no_comptime,
282
+ include_dirs=args.include_dir,
283
+ )
284
+ except RuntimeError as exc:
285
+ print(f"kasi: error: {exc}", file=sys.stderr)
286
+ return 2
287
+ except subprocess.CalledProcessError as exc:
288
+ print(f"kasi: compiler failed (exit {exc.returncode})", file=sys.stderr)
289
+ return 2
290
+
291
+ if args.explain:
292
+ from .explain import html_report
293
+
294
+ path = args.explain.resolve()
295
+ path.parent.mkdir(parents=True, exist_ok=True)
296
+ path.write_text(
297
+ html_report(Path(args.source).read_text(encoding="utf-8"), result.infos, result.warnings),
298
+ encoding="utf-8",
299
+ )
300
+ print(f"speed map: {path}")
301
+
302
+ if not args.quiet:
303
+ if args.Wall:
304
+ for diagnostic in result.diagnostics:
305
+ print(diagnostic, file=sys.stderr)
306
+ for warning in result.warnings:
307
+ print(f"warning: {warning}", file=sys.stderr)
308
+ if result.folded:
309
+ print(f"comptime: folded {result.folded} constant expression(s)")
310
+ if result.comptime_calls:
311
+ print(f"comptime: inlined {result.comptime_calls} call(s)")
312
+ if result.profile:
313
+ print(f"type profile: {result.profile}")
314
+ if result.launcher:
315
+ print(f"launcher: {result.launcher}")
316
+ print(f"native executable: {result.executable}")
317
+ return 0
318
+
319
+
320
+ if __name__ == "__main__":
321
+ raise SystemExit(main())
kasi/bench.py ADDED
@@ -0,0 +1,82 @@
1
+ """Compare CPython and KASI-native execution on the same source."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import time
10
+ from pathlib import Path
11
+
12
+ from .driver import compile_file
13
+
14
+ LOOP_SOURCE = """\
15
+ total = 0
16
+ for i in range(2000000):
17
+ total += i
18
+ print(total)
19
+ """
20
+
21
+
22
+ def run(command: list[str], repeats: int = 3) -> tuple[float, str]:
23
+ best = float("inf")
24
+ output = ""
25
+ for _ in range(repeats):
26
+ start = time.perf_counter()
27
+ completed = subprocess.run(command, capture_output=True, text=True, check=False)
28
+ elapsed = time.perf_counter() - start
29
+ if completed.returncode != 0:
30
+ detail = completed.stderr.strip() or f"exit code {completed.returncode}"
31
+ raise RuntimeError(detail)
32
+ best = min(best, elapsed)
33
+ output = completed.stdout
34
+ return best, output
35
+
36
+
37
+ def benchmark(source: Path, repeats: int = 3) -> None:
38
+ if os.environ.get("KASI_SKIP_NATIVE_RUN") == "1":
39
+ print(f"{source.name}: native run disabled by KASI_SKIP_NATIVE_RUN")
40
+ return
41
+
42
+ native_time = float("inf")
43
+ native_out = ""
44
+ last_error: OSError | RuntimeError | None = None
45
+
46
+ # Device Guard can intermittently block a freshly linked executable.
47
+ # Recompiling under a fresh name usually gets a runnable binary.
48
+ for attempt in range(3):
49
+ with tempfile.TemporaryDirectory() as directory:
50
+ work = Path(directory)
51
+ name = f"{source.stem}_{attempt}_{time.time_ns()}.exe"
52
+ native = compile_file(source, output=work / name)
53
+ try:
54
+ native_time, native_out = run([str(native.executable)], repeats)
55
+ break
56
+ except (OSError, RuntimeError) as exc:
57
+ last_error = exc
58
+
59
+ if last_error is not None and native_time == float("inf"):
60
+ print(f"{source.name}: native run unavailable: {last_error}")
61
+ return
62
+
63
+ py_time, py_out = run([sys.executable, str(source)], repeats)
64
+
65
+ print(f"{source.name}:")
66
+ print(f" CPython: {py_time * 1000:9.2f} ms")
67
+ print(f" KASI: {native_time * 1000:9.2f} ms ({py_time / native_time:.1f}x)")
68
+ print(f" outputs match: {py_out == native_out} ({py_out.strip()!r})")
69
+
70
+
71
+ def main() -> None:
72
+ examples = Path(__file__).resolve().parents[1] / "examples"
73
+ for name in ("fib.py", "lists.py"):
74
+ benchmark(examples / name)
75
+ with tempfile.TemporaryDirectory() as directory:
76
+ path = Path(directory) / "loop.py"
77
+ path.write_text(LOOP_SOURCE, encoding="utf-8")
78
+ benchmark(path)
79
+
80
+
81
+ if __name__ == "__main__":
82
+ main()