Repository navigation
Expand file tree
/
Copy pathbuild.py
More file actions
executable file
·1882 lines (1672 loc) · 94.4 KB
/
Copy pathbuild.py
File metadata and controls
executable file
·1882 lines (1672 loc) · 94.4 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Stage 1 build of the Kairo toolchain, the stop-gap for kbld.
The repo is self-hosted: Compiler/ is Stage 1.5 source and the last good release
compiler builds it.
python3 build.py --release kairo kcc # N-1 -> staging -> release, then PATH (the gate)
python3 build.py --debug kairo kcc # debug profile (the edit/test loop)
Source Output Registry object
the repo build/<triple>/<mode> compiled here from build/registry, which
gen_diag.py writes (Stage 1) on every build
python3 build.py --print-jobs # show the clang jobs and the link, build nothing
This is build.k's logic restated for a Stage 1 compiler. kbld (Extras/BuildTool) drives
Stage 0 and is not ported to Stage 1 yet, and won't be for a while; until it is, this
script is the build of record once Stage 1 self-hosts. Keep it in step with build.k: same
targets, same prebuild/postbuild hooks, same toolchain linkage invariant.
TOOLCHAIN LINKAGE INVARIANT, as in build.k, do not violate:
Linux/macOS : shared (libLLVM.so / .dylib), one copy in lib/, thin bins.
Windows : static (.lib), forced; libLLVM.dll is unsupported there.
No system-LLVM fallback on any platform: we link the patched fork (custom Clang
PP-token injection); system LLVM lacks the patch. Absence is a hard error.
Stage 0 and Stage 1 flags are NOT the same, and where a Stage 0 flag has no Stage 1
counterpart this script says so instead of guessing (see STAGE1_GAPS):
- Stage 0 passed clang words for the WHOLE build (one transpiled TU). Stage 1's
--cxx-flags reach only C/C++ inputs (here, the generated *_meta.cpp); Kairo's own
codegen never sees them. So -fvisibility=hidden, the deterministic-FP set
(-fno-fast-math, -ffp-contract=off, ...), -Xclang -vectorize-* and
-gline-tables-only have no Stage 1 spelling yet.
- -D defines a KAIRO macro only; a C++ macro (VERSION, DEBUG, NDEBUG, NOMINMAX) is
--cxx-define. Debug builds pass DEBUG to both, as Compiler/Spec/BuildSystem.md#compile-line does.
- Stage 1 always links with its bundled lld (-fuse-ld=lld is implied), has no -w
(warnings stay on), and --lto is unimplemented (objects are not bitcode).
- Include roots: Stage 1 module identity depends on the -I set, so every tool gets
the SAME roots; `-I .` and the lib-helix core are gone (Compiler/Spec/SelfHosting.md#pre-migration-audits).
Portable: Linux, macOS, Windows. No shell; subprocess with argument lists only.
"""
import argparse, datetime, hashlib, json, os, platform, re, shlex, shutil, subprocess, sys, threading, time
from pathlib import Path
try: # a pty for the compiler's stderr (POSIX); elsewhere its events are re-drawn
import fcntl, pty, termios, tty
_HAVE_PTY = True
except ImportError:
_HAVE_PTY = False
ROOT = Path(__file__).resolve().parent
EXE = ".exe" if os.name == "nt" else ""
# The full registry source (declarations + bodies, one module), written by gen_diag.py on
# every build from Compiler/Diagnostic/TableGen; never committed.
REGISTRY_DIR = ROOT / "build" / "registry"
# The repo's own Compiler/ + Linker/ are the self-hosted (Stage 1 syntax) tree since the
# switch-over; kbld (Stage 0) cannot build it.
REPO_SELFHOSTED = True
# What Stage 1 cannot express yet, printed with --explain-gaps so nobody wonders
# why a build.k flag is missing below.
STAGE1_GAPS = [
("-fvisibility=hidden / -fvisibility-inlines-hidden", "no flag reaches Kairo codegen; --cxx-flags is C/C++ inputs only"),
("-fno-fast-math -fno-approx-func -ffp-contract=off -fno-associative-math -fno-rounding-math",
"same: Kairo's own FP semantics apply; check they match before relying on bit-identical FP"),
("-Xclang -vectorize-loops / -vectorize-slp", "same"),
("-gline-tables-only (release)", "Stage 1 has -g (full DWARF) only"),
("-flto, --lto-partitions, /opt:lldlto*", "--lto is unimplemented in Stage 1"),
("-Wl,--no-export-dynamic", "Stage 1 does not pass -rdynamic, so there is nothing to undo"),
("--reproducible: prebuild's registry.o and the clang jobs' own -frandom-seed",
"registry.o is shared (build/.kbld) and produced by gen_diag.py: not remapped or checked; "
"kairo has no -frandom-seed spelling, so anonymous-namespace/local-symbol naming relies on clang's default (content-derived)"),
("-w", "dropped on purpose (Compiler/Spec/BuildSystem.md#compile-line): warnings stay on"),
("-fsanitize=undefined,bounds,function (debug)", "-fsanitize-ub is accepted but unimplemented (U005W); opt in with --sanitize-ub"),
]
def die(msg: str) -> "NoReturn":
print(f"build.py: error: {msg}", file=sys.stderr)
sys.exit(1)
def say(msg: str) -> None:
print(f"[build] {msg}", flush=True)
# --- host -------------------------------------------------------------------
def host_os() -> str:
s = platform.system()
if s == "Linux":
return "linux"
if s == "Darwin":
return "macos"
if s == "Windows":
return "windows"
die(f"unsupported host OS '{s}'")
def host_arch() -> str:
a = platform.machine().lower()
if a in ("x86_64", "amd64"):
return "x86_64"
if a in ("aarch64", "arm64"):
return "aarch64"
die(f"unsupported host architecture '{a}'")
def host_triple() -> str:
"""The build/<triple> directory name, exactly as stage_tree.py / build_llvm.py
spell it (KBLD_TRIPLE overrides, as there)."""
t = os.environ.get("KBLD_TRIPLE")
if t:
return t
os_ = host_os()
if os_ == "linux":
return f"{host_arch()}-linux-gnu"
if os_ == "macos":
return ("arm64" if host_arch() == "aarch64" else "x86_64") + "-apple-macosx"
return f"{host_arch()}-windows-msvc"
# --- version / metadata ------------------------------------------------------
# The toolchain's version, one number for every binary (Stage 1.5 is
# v0.2.0). Builds carry +dev.<date>; a release build drops it.
KAIRO_VERSION = "0.3.0"
DEV = f"-{KAIRO_VERSION}+dev"
def version(target: str, suffix: str, epoch=None) -> str:
"""build.k version(): a +dev / +rc suffix gets the build date. Under --reproducible
the date comes from the source epoch, never from today."""
date = ""
if "+rc" in suffix or "+dev" in suffix:
day = datetime.date.today() if epoch is None else \
datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc).date()
date = day.strftime(".%Y%m%d")
return f"{target}{suffix}{date}"
PROJECT = {
"name": "Kairo",
"version": f"kairo-{KAIRO_VERSION}",
"author": "Dhruvan, Ojas and Arnav",
"license": "CC-BY-4.0",
}
_RUNTIMES_REV = None
def runtimes_revision() -> str:
"""The LLVM fork revision the runtimes come from, exactly as
Scripts/package_release.py writes it to share/kairo/runtimes/REVISION (one
function, imported, so the two can never spell it differently). Embedded in
every tool (`kairo --print-runtimes-revision`, `ksys --print-runtimes-revision`):
ksys refuses a share tree whose REVISION differs. "unknown" without the
Lib/llvm-runtimes checkout or git."""
global _RUNTIMES_REV
if _RUNTIMES_REV is None:
try:
import package_release
_RUNTIMES_REV = package_release.runtimes_revision()
except Exception:
_RUNTIMES_REV = "unknown"
return _RUNTIMES_REV
def write_meta(gen_dir: Path, name: str, os_: str, epoch=None, ver: str = None) -> Path:
"""The *_meta.cpp kbld generates: one string in a named section, read back by
tooling. Section syntax is per object format (ELF / Mach-O / COFF).
With `ver` it also defines kairo_version_cstr(), the tool's version string, which
Native/Shims.hh's version_string() returns under -D KAIRO_VERSION_EXTERN. It is not a
`-D VERSION="kcc+dev.<date>"` on every TU: that is a cc1 word, so in every
object key (Compiler/Spec/Incremental.md), and it differs per tool and per day, so
no two tools (and no two days) could share a cached object. It lives in the one
per-tool object that is never cached."""
when = datetime.datetime.now(datetime.timezone.utc) if epoch is None else \
datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc)
built = when.strftime("%Y-%m-%dT%H:%M:%SZ")
meta = "|".join(f"{k}={v}" for k, v in PROJECT.items()) + f"|built={built}"
meta = meta.replace("\\", "\\\\").replace('"', '\\"')
if os_ == "macos":
attr = '__attribute__((section("__DATA,__build_meta"), used))'
elif os_ == "windows":
attr = '#pragma section(".build_meta", read)\n__declspec(allocate(".build_meta"))'
else:
attr = '__attribute__((section(".build_meta"), used))'
gen_dir.mkdir(parents=True, exist_ok=True)
p = gen_dir / f"{name}_meta.cpp"
body = f'{attr}\nstatic const char kBuildMeta[] = "{meta}";\n'
if os_ == "windows":
# MSVC/clang-cl drops an unreferenced static; keep it like `used` does.
body += "extern \"C\" const char* kairo_build_meta() { return kBuildMeta; }\n"
if ver is not None:
lit = ver.replace("\\", "\\\\").replace('"', '\\"')
body += f'extern "C" const char *kairo_version_cstr() noexcept {{ return "{lit}"; }}\n'
rev = runtimes_revision().replace("\\", "\\\\").replace('"', '\\"')
body += f'extern "C" const char *kairo_runtimes_revision_cstr() noexcept {{ return "{rev}"; }}\n'
if not p.exists() or p.read_text() != body:
p.write_text(body)
return p
# --- targets (build.k main()) -------------------------------------------------
# name -> (entry, version string target, version suffix, extra include roots).
# Every tool gets the same Stage 1 roots: Compiler and Linker. KaTAR and kfmt
# add their own root. Tools whose sources are outside the self-host scope
# (Extras/BuildTool, PackageManager) are listed so the table matches build.k,
# but refused until their trees are migrated.
STAGE1_ROOTS = ["Compiler", "Linker"]
TARGETS = {
"kairo": ("Compiler/Driver/Kairo.k", "kairo", DEV, []),
"kcc": ("Compiler/Driver/Kcc.k", "kcc", DEV, []),
"kld": ("Linker/Driver/kld.k", "kld", DEV, []),
"kparse": ("Compiler/Tooling/ParseOnceTest.k", "kairo", DEV, []),
# The in-module Test() functions (Compiler/Tooling/UnitTests.k); not staged.
# Analyzer for the language server's text-only modules (DocComment.k).
"kunit": ("Compiler/Tooling/UnitTests.k", "kairo", DEV, ["Analyzer"]),
"katar": ("Extras/KaTAR/KTCompress.k", "kairo", DEV, ["Extras/KaTAR"]),
"kfmt": ("Extras/Formatter/Driver/kfmt.k", "kairo", DEV, ["Extras/Formatter"]),
"ksys": ("Linker/Sysroot/Driver/ksys.k", "ksys", DEV, []),
"clang-diag-identity": ("Compiler/Tooling/GenClangDiagIdentity.k", "kairo", DEV, []),
# kals formats through kfmt's own Formatter, so it takes that root too.
"kals": ("Analyzer/Driver/kals.k", "kairo", DEV, ["Analyzer", "Extras/Formatter"]),
}
NOT_MIGRATED = {
"kbld": "Extras/BuildTool",
"kpkg": "Extras/PackageManager",
}
# build.k stages the tree after these (post_build). kld, kfmt, ksys and kals ship in the
# staged tree beside kairo and kcc, so a build of it alone stages too.
STAGED = {"kairo", "kcc", "kld", "kfmt", "ksys", "kals"}
# --- kairo_compile.json (the language server's project file) ------------------
def write_compile_json(src: Path, common: list) -> Path:
"""kairo_compile.json at the source root: one entry per target, each with the roots
and the Kairo flags its build passes (Compiler/Spec/LanguageServer.md has the format).
kals type-checks an entry with exactly these, so what the editor reports is what the
build would. Paths under the source root are written relative to it, so the file
does not change with where the checkout lives; `directory` is "." (the file's own).
Outputs, the object cache and the thread count are the build's business and are
left out: an analysis writes nothing."""
def rel(arg: str) -> str:
try:
return Path(arg).resolve().relative_to(src).as_posix() if Path(arg).is_absolute() else arg
except ValueError:
return arg
entries = []
for t in sorted(TARGETS):
entry, _vname, _vsuffix, extra_roots = TARGETS[t]
args = []
for r in STAGE1_ROOTS + extra_roots:
args += ["-I", r]
args += ["--cxx-define", "KAIRO_VERSION_EXTERN=1", *[rel(c) for c in common]]
entries.append({"entry": entry, "args": args, "directory": "."})
doc = {"version": 1, "entries": entries,
# A file no target reaches yet (a new tool, a scratch file under the roots).
# It takes the tree's strict C++ moves opt-out, as every target does.
"default_args": [x for r in STAGE1_ROOTS for x in ("-I", r)] + ["-fno-strict-cxx-moves"]}
path = src / "kairo_compile.json"
text = json.dumps(doc, indent=2) + "\n"
if not path.exists() or path.read_text() != text:
path.write_text(text)
return path
# --- LLVM linkage (build.k llvm_static_components / clang_static_components) -
LLVM_STATIC_CORE = "Core Support Demangle Target TargetParser".split()
LLVM_STATIC = """
CodeGen CodeGenTypes AsmPrinter SelectionDAG GlobalISel MCA
ScalarOpts InstCombine AggressiveInstCombine TransformUtils Vectorize SandboxIR
Analysis ProfileData ipo Passes Plugins Linker CGData
IRReader IRPrinter AsmParser BitReader BitWriter BitstreamReader
MC MCParser MCDisassembler Object ObjectYAML BinaryFormat InterfaceStub
ExecutionEngine Interpreter MCJIT JITLink OrcJIT OrcDebugging OrcShared OrcTargetProcess RuntimeDyld
Remarks TextAPI TextAPIBinaryReader Option Coroutines Instrumentation WindowsDriver WindowsManifest
FrontendOpenMP FrontendOffloading FrontendOpenACC FrontendHLSL FrontendAtomic FrontendDirective FrontendDriver
LTO DTLTO CFGuard ObjCARCOpts HipStdPar Extensions
DebugInfoDWARF DebugInfoDWARFLowLevel DebugInfoCodeView DebugInfoMSF DebugInfoPDB DebugInfoGSYM
DebugInfoLogicalView DebugInfoBTF Debuginfod DWP DWARFLinker DWARFLinkerClassic DWARFLinkerParallel
DWARFCFIChecker Symbolize Coverage
ObjCopy XRay DlltoolDriver LibDriver CFIVerify Diff Exegesis ExegesisX86 ExegesisAArch64 ExegesisRISCV
OptDriver FuzzMutate FuzzerCLI FileCheck LineEditor Telemetry MIRParser ABI
""".split()
CLANG_STATIC = """
Basic Driver Options Frontend FrontendTool RewriteFrontend
CodeGen Sema Analysis AnalysisFlowSensitive AnalysisFlowSensitiveModels AnalysisLifetimeSafety AnalysisScalable
AST ASTMatchers DynamicASTMatchers Parse Lex Edit Rewrite APINotes
Serialization CrossTU Index IndexSerialization InstallAPI ExtractAPI
StaticAnalyzerCore StaticAnalyzerCheckers StaticAnalyzerFrontend
Format ToolingCore ToolingInclusions ToolingInclusionsStdlib ToolingRefactoring ToolingASTDiff
ToolingSyntax Transformer Tooling DependencyScanning DirectoryWatcher Support
""".split()
def clang_static_libs(llvm_build: Path) -> list:
"""CLANG_STATIC, adjusted to the libraries the LLVM release at llvm_build has.
From LLVM 23 clangIndex links clangUnifiedSymbolResolution (USR generation), so it
follows Index, and clangAnalysisScalable is split into the
clangScalableStaticAnalysis* libraries that Driver and FrontendTool link. A link
that named an archive the release does not have would fail."""
lib = llvm_build / "lib"
def has(name: str) -> bool:
return any((lib / n).is_file() for n in (f"libclang{name}.a", f"clang{name}.lib"))
out = []
for l in CLANG_STATIC:
if l == "AnalysisScalable" and not has(l) and has("ScalableStaticAnalysisCore"):
out += ["ScalableStaticAnalysisFrontend", "ScalableStaticAnalysisSourceTransformation",
"ScalableStaticAnalysisAnalyses", "ScalableStaticAnalysisCore"]
continue
out.append(l)
if l == "Index" and has("UnifiedSymbolResolution"):
out.append("UnifiedSymbolResolution")
return out
# Every component library a backend can have (lib/Target/<T>/**/CMakeLists.txt): not every
# backend has every one (NVPTX and SPIRV have no AsmParser or Disassembler; Utils,
# TargetMCA and SPIRV's Analysis are per target).
TARGET_COMPONENTS = ["CodeGen", "AsmParser", "Desc", "Disassembler", "Info", "Utils", "TargetMCA", "Analysis"]
def llvm_static_libs(llvm_build: Path) -> list:
"""The LLVM archives a static link names: the core, each built backend's components,
then the rest. The backends are read from the build's own Targets.def, the list
InitializeAllTargets() and friends expand at compile time, so a link names exactly the
backends its headers register (Scripts/build_llvm.py TARGETS, or LLVM_TARGETS for a
narrower build): a hardcoded list left every backend added to the build an undefined
LLVMInitialize<T>* on the static (Windows, cross) links. A component the backend does
not have is skipped by its absence from lib/."""
defs = llvm_build / "include" / "llvm" / "Config" / "Targets.def"
if not defs.is_file():
die(f"{defs} is missing; is {llvm_build} a configured LLVM build?")
lib = llvm_build / "lib"
targets = re.findall(r"^LLVM_TARGET\((\w+)\)", defs.read_text(), re.M)
have = {f.name for f in lib.iterdir()} if lib.is_dir() else set()
out = []
for t in targets:
for c in TARGET_COMPONENTS:
n = f"LLVM{t}{c}"
if f"lib{n}.a" in have or f"{n}.lib" in have:
out.append(f"{t}{c}")
return LLVM_STATIC_CORE + out + LLVM_STATIC
WINDOWS_SYSTEM_LIBS = ["version", "advapi32", "shell32", "ole32", "uuid", "ntdll",
"ws2_32", "psapi", "onecore", "zstd", "zlib"]
# LLD is not in llvm-config: a fixed bundle (the lldCommon <-> flavor cycle is the
# driver's to group).
LLD_LIBS = ["lldCommon", "lldELF", "lldCOFF", "lldMinGW", "lldMachO", "lldWasm"]
def llvm_args(llvm_src: Path, llvm_build: Path, out_lib: Path, os_: str) -> list:
if not (llvm_build / "include").is_dir():
die(f"vendored LLVM not found at {llvm_build}. The patched llvm-project fork is "
"REQUIRED; there is no system fallback. Run Scripts/build_llvm.py, or "
"`git submodule update --init --recursive Lib/llvm-runtimes`.")
a = []
for inc in (llvm_build / "include", llvm_src / "llvm" / "include", llvm_src / "lld" / "include",
llvm_src / "clang" / "include", llvm_build / "tools" / "clang" / "include"):
a += ["--cxx-include", str(inc)]
a += ["-L", str(llvm_build / "lib"), "-L", str(out_lib)]
a += ["--cxx-flags=-Wno-parentheses-equality", "--cxx-flags=-Werror=return-type"]
for l in LLD_LIBS:
a += ["-l", l]
if os_ == "windows":
# STATIC: libLLVM.dll is unsupported on Windows (invariant).
for d in ("NOMINMAX", "CLANG_BUILD_STATIC", "LLVM_BUILD_STATIC"):
a += ["--cxx-define", d]
for l in clang_static_libs(llvm_build):
a += ["-l", f"static:clang{l}"]
for l in llvm_static_libs(llvm_build):
a += ["-l", f"static:LLVM{l}"]
for l in WINDOWS_SYSTEM_LIBS:
a += ["-l", l]
else:
# SHARED: one libLLVM, thin bins (invariant).
a += ["-l", "clang-cpp", "-l", "LLVM", "-l", "zstd", "-l", "z"]
return a
# --- cross targets (Scripts/cross_llvm.py) -------------------------------------
#
# A shipping tree for another target, built on this host: the target's LLVM comes from
# Scripts/cross_llvm.py (kcc + our sysroot, static, ThinLTO, mimalloc), never from
# build/llvm. Linkage is STATIC on every cross target: there is no libLLVM.so to ship
# beside a static musl binary, and Windows is static anyway (invariant above).
# Every cross target, with its CPU floor, is Scripts/cross_llvm.py's FAMILIES: one table,
# so the LLVM a tree links and the tree itself always agree on the floor.
sys.path.insert(0, str(ROOT / "Scripts"))
import cross_llvm # noqa: E402
CROSS = {t: ({"Linux": "linux", "Windows": "windows", "Darwin": "macos", "FreeBSD": "freebsd", "NetBSD": "netbsd"}[f[0]], f[2])
for t, f in cross_llvm.FAMILIES.items()}
# A MinGW link names the Win32 libraries LLVM uses itself (no MSVC autolink pragmas).
MINGW_SYSTEM_LIBS = ["version", "advapi32", "shell32", "ole32", "uuid", "ntdll", "ws2_32", "psapi"]
def floor_args(flags: list) -> list:
"""cross_llvm.py's clang-spelled CPU floor as kairo flags (it compiles C++ inputs and
Kairo code alike with them)."""
out = []
for f in flags:
for clang, kairo in (("-march=", "--march"), ("-mcpu=", "--mcpu"), ("-mtune=", "--mtune")):
if f.startswith(clang):
out += [kairo, f[len(clang):]]
return out
def target_exe(target) -> str:
if target:
return ".exe" if CROSS[target][0] == "windows" else ""
return EXE
def llvm_include_args(llvm_src: Path, llvm_build: Path) -> list:
"""The fork's headers. The registry needs them too (Native/Types.hh includes
llvm/ADT/StringRef.h): without them a native build silently found the HOST's
/usr/include/llvm (another LLVM version), and a cross build found none."""
a = []
for inc in (llvm_build / "include", llvm_src / "llvm" / "include", llvm_src / "lld" / "include",
llvm_src / "clang" / "include", llvm_build / "tools" / "clang" / "include"):
a += ["--cxx-include", str(inc)]
return a
def cross_dir(target: str) -> Path:
return ROOT / "build" / "cross-llvm" / target
def bitcode_producer_major(archive: Path) -> int:
"""The major version of the clang that wrote the bitcode in archive (its first
llvm.ident), or 0 when it holds none (native objects, or no archive)."""
try:
with open(archive, "rb") as f:
head = f.read(8 << 20)
except OSError:
return 0
m = re.search(rb"clang version (\d+)\.", head)
return int(m.group(1)) if m else 0
def llvm_major(llvm_build: Path) -> int:
m = re.search(r"^#define LLVM_VERSION_MAJOR (\d+)",
(llvm_build / "include" / "llvm" / "Config" / "llvm-config.h").read_text(), re.M)
return int(m.group(1)) if m else 0
def cross_llvm_args(llvm_src: Path, target: str) -> list:
llvm_build = cross_dir(target) / "llvm"
deps = cross_dir(target) / "deps" / "prefix"
if not (llvm_build / "lib" / "libLLVMCore.a").exists():
die(f"no cross LLVM for {target} at {llvm_build}; run python3 Scripts/cross_llvm.py {target}")
tos, floor = CROSS[target]
a = []
for inc in (llvm_build / "include", llvm_src / "llvm" / "include", llvm_src / "lld" / "include",
llvm_src / "clang" / "include", llvm_build / "tools" / "clang" / "include"):
a += ["--cxx-include", str(inc)]
a += ["-L", str(llvm_build / "lib"), "-L", str(deps / "lib")]
a += ["--cxx-flags=-Wno-parentheses-equality", "--cxx-flags=-Werror=return-type"]
for d in ("CLANG_BUILD_STATIC", "LLVM_BUILD_STATIC"):
a += ["--cxx-define", d]
for l in LLD_LIBS:
a += ["-l", f"static:{l}"]
for l in clang_static_libs(llvm_build):
a += ["-l", f"static:clang{l}"]
for l in llvm_static_libs(llvm_build):
a += ["-l", f"static:LLVM{l}"]
a += ["-l", "static:zstd", "-l", "static:z"]
if tos == "linux":
# musl's default thread stack is 128 KiB; the compiler's pools and the LLVM in
# it recurse far deeper (cross_llvm.write_toolchain has the crash). PT_GNU_STACK
# sets musl's default; this is glibc's 8 MiB.
a += [f"--ld-flags=-zstack-size={cross_llvm.MUSL_THREAD_STACK}"]
if tos == "windows":
for l in MINGW_SYSTEM_LIBS:
a += ["-l", l]
# The archives are ThinLTO bitcode from the kcc that built them, and LLVM stores
# each global's GUID in bitcode only from 23 on. A linker at 23 or later reads an
# older archive's globals without one: its thin backend then keeps a dead weak
# definition in the object while it removes the dead symbols that definition
# refers to, and the link ends in undefined symbols. Nothing live refers to such a
# definition, so section GC discards it before lld scans its relocations.
a += ["-fgc-sections"]
# Section GC is not enough for such archives. The thin link also marks dead
# symbols that a kept definition still calls, and lld's COFF driver reports
# undefined symbols before it collects sections: the Windows links, and the
# ELF links whose kept callers are live, end in undefined symbols. Without
# the dead-symbol analysis nothing is dropped before the backends and every
# reference resolves; section GC then removes what nothing reaches. Only an
# archive written by a clang older than the LLVM it is linked with needs it.
if 0 < bitcode_producer_major(llvm_build / "lib" / "libLLVMSupport.a") < llvm_major(llvm_build):
# In a response file the linker expands itself, so the link stays in the
# seed's process. An argv that names -mllvm is linked out of process
# through kld, and past the command-line limit a seed may hand lld's
# MinGW driver --rsp-quoting, which it rejects. The option changes LLVM's
# global state in the seed, which runs nothing LLVM-backed after the link.
rsp = ROOT / "build" / "lto-compute-dead.rsp"
text = "-mllvm\n-compute-dead=false\n"
if not rsp.is_file() or rsp.read_text() != text:
rsp.parent.mkdir(parents=True, exist_ok=True)
rsp.write_text(text)
a += [f"--ld-flags=@{rsp}"]
# No mimalloc object here: the Kairo runtime (Lib/rt/mimalloc.c) already is mimalloc
# and replaces malloc on ELF, so a Kairo binary has it; a second copy is duplicate
# symbols. cross_llvm.py links one into the LLVM tools (clang, lld), which are not Kairo.
a += ["--target", target, *floor_args(floor)]
return a
def shared_libcxx_args(os_: str, native: bool) -> list:
"""Under --native the driver links the bundled libc++.a / libc++abi.a by path,
but libLLVM.so / libclang-cpp.so need the shared libc++.so.1 (the one the vendored
LLVM was linked against, which stage_tree.py bundles into lib/). Two copies in one
process throw std::bad_cast from ios_base::Init before main. Naming the shared
libraries first, as user libraries, resolves every libc++ symbol from them, so the
linker pulls no member out of the archives that follow."""
if os_ == "linux" and native:
return ["-l", "c++", "-l", "c++abi"]
return []
# --- platform glue (build.k platform_glue / windows_sdk_paths / host_sysroot_glue)
def windows_sdk_args() -> list:
"""Host-toolchain probing for the MSVC link (NOT LLVM linkage)."""
a = ["--ld-flags=/nodefaultlib:libcmt"]
sdk_root = None
try:
import winreg # Windows only
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\WOW6432Node\Microsoft\Windows Kits\Installed Roots") as k:
sdk_root = Path(winreg.QueryValueEx(k, "KitsRoot10")[0]) / "Lib"
except OSError:
pass
if sdk_root is None or not sdk_root.is_dir():
sdk_root = Path("C:/Program Files (x86)/Windows Kits/10/Lib")
sdks = sorted(p.name for p in sdk_root.iterdir() if p.is_dir() and p.name.startswith("10.")) \
if sdk_root.is_dir() else []
if not sdks:
die(f"no Windows SDK found in {sdk_root}; install the Windows 10/11 SDK")
base = sdk_root / sdks[-1]
a += [f"--ld-flags=/libpath:{base / 'ucrt' / 'x64'}", f"--ld-flags=/libpath:{base / 'um' / 'x64'}"]
vswhere = Path("C:/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe")
if vswhere.exists():
r = subprocess.run([str(vswhere), "-latest", "-products", "*", "-requires",
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
"-property", "installationPath"], capture_output=True, text=True)
vs = Path(r.stdout.strip()) if r.stdout.strip() else None
tools = vs / "VC" / "Tools" / "MSVC" if vs else None
if tools and tools.is_dir():
vers = sorted(p.name for p in tools.iterdir() if p.is_dir())
if vers:
a.append(f"--ld-flags=/libpath:{tools / vers[-1] / 'lib' / 'x64'}")
return a
def host_sysroot_args() -> list:
"""Opt-in: KAIRO_HOST_SYSROOT names an old-glibc sysroot (Scripts/host_sysroot.py)
so the shipped binaries need that glibc, not the build host's. Only valid if LLVM
was configured against the same sysroot (build_llvm.py reads the same variable)."""
if not os.environ.get("KAIRO_HOST_SYSROOT"):
return []
script = str(ROOT / "Scripts" / "host_sysroot.py")
run_or_die([sys.executable, script, "--check"])
cflags = run_or_die([sys.executable, script, "--cflags"]).split()
ldflags = run_or_die([sys.executable, script, "--ldflags"]).split()
# Stage 0 passed both straight to clang. In Stage 1 the compile side reaches
# C/C++ inputs and ffi headers through --cxx-flags; the link side is lld's.
return [f"--cxx-flags={f}" for f in cflags] + [f"--ld-flags={f}" for f in ldflags]
def platform_args(os_: str) -> list:
if os_ == "linux":
return ["--rpath", "$ORIGIN/../lib"] + host_sysroot_args()
if os_ == "macos":
return ["--rpath", "@loader_path/../lib"]
return windows_sdk_args()
# --- profile (build.k optimize) ---------------------------------------------
def profile_args(debug: bool, sanitize_ub: bool, os_: str = "linux") -> list:
if debug:
# Compiler/Spec/BuildSystem.md#compile-line. DEBUG for Kairo source (-D) and for C++ (--cxx-define).
# KAIRO_LLVM_DUMP_UNUSED: the merged codegen PCH drops `used` from clang's
# LLVM_DUMP_METHOD functions, so no TU IRGens them unasked (CodegenPCH.k).
a = ["--profile", "debug", "-O0", "-g", "--debug-macros",
"-D", "DEBUG", "--cxx-define", "DEBUG", "--cxx-define", "KAIRO_LLVM_DUMP_UNUSED"]
# LLVM crashes (null MCExpr fragment in DwarfDebug::endModule) emitting macro debug info
# for a Mach-O target, so a macOS host leaves --debug-macros out.
if os_ == "macos":
a.remove("--debug-macros")
if sanitize_ub:
a += ["-fsanitize-ub"]
return a
# -O3 as build.k; ICF is on by default above -O0 in Stage 1. --strip-debug: Kairo emits
# no -g here, but the sysroot's prebuilt archives (musl libc.a, libc++/libc++abi) carry
# DWARF, and without it every release binary shipped ~6 MB of their debug sections.
# Symbols stay, so backtraces still name functions.
return ["--profile", "release", "-O3", "--cxx-define", "NDEBUG", "--strip-debug"]
# --- hooks (build.k prebuild_script / postbuild_script) ------------------------
def run_or_die(argv: list, cwd: Path = ROOT, env=None) -> str:
r = subprocess.run(argv, cwd=str(cwd), env=env, text=True, stdout=subprocess.PIPE)
if r.returncode != 0:
die(f"command failed ({r.returncode}): {' '.join(map(str, argv))}")
return r.stdout
def run_streaming(argv: list, cwd: Path = ROOT, env=None) -> None:
"""Runs argv with the terminal as its stdout/stderr, so a long step (the LLVM build)
shows what it is doing as it does it; run_or_die captures stdout, which hid it."""
sys.stdout.flush()
r = subprocess.run(argv, cwd=str(cwd), env=env)
if r.returncode != 0:
die(f"command failed ({r.returncode}): {' '.join(map(str, argv))}")
def gen_registry(src: Path) -> Path:
"""gen_diag.py: Compiler/Diagnostic/Registry.k (declarations; only when the source tree
IS the repo) and build/registry/Compiler/Diagnostic/Registry.k (declarations + bodies),
both Stage 1, both rewritten only when their text changes. ~0.3 s."""
reg_k = REGISTRY_DIR / "Compiler" / "Diagnostic" / "Registry.k"
decl = (src / "Compiler" / "Diagnostic" / "Registry.k") if src == ROOT \
else (REGISTRY_DIR / "Unused" / "Registry.k")
run_or_die([sys.executable, str(ROOT / "Scripts" / "gen_diag.py"),
str(src / "Compiler" / "Diagnostic" / "TableGen"),
f"--output={decl}", f"--full-output={reg_k}"])
return reg_k
def postbuild(tree: Path, mode: str, triple: str, llvm_build: Path = None, target: str = None,
src: Path = None) -> None:
"""Stage clang, lld, the resource dir and Lib/ into the tree and make it
relocatable (stage_tree.py, every host). Idempotent. `llvm_build`: a cross
target's LLVM, whose clang / lld are the ones the tree ships."""
say(f"postbuild: Scripts/stage_tree.py {tree}")
env = dict(os.environ, KBLD_MODE=mode, KBLD_TRIPLE=triple, KBLD_ROOT=str(ROOT))
# The tree ships the Lib/ of the source it was built from: with --src, that
# tree's Lib/, never the checkout's (which may hold unrelated uncommitted work).
if src is not None:
env["KBLD_LIB_SRC"] = str(src / "Lib")
env["KBLD_TEMPLATES_SRC"] = str(src / "Extras" / "Templates")
if llvm_build:
env["KAIRO_LLVM_BUILD"] = str(llvm_build)
if target:
env["KAIRO_TREE_OS"] = {"linux": "Linux", "windows": "Windows", "macos": "Darwin",
"freebsd": "FreeBSD", "netbsd": "NetBSD"}[CROSS[target][0]]
run_or_die([sys.executable, str(ROOT / "Scripts" / "stage_tree.py"), str(tree)], env=env)
def selfhost_registry(kairo: Path, src: Path, out: Path, prog, extra: list = [], cache_root: Path = None) -> Path:
"""The diagnostic registry for a self-host tree, compiled by the compiler doing the
build. Its source, build/registry/Compiler/Diagnostic/Registry.k (gen_diag.py),
is the declarations plus the bodies as ONE module; its root goes first so it shadows the tree's
declarations-only Registry.k for this compile only. Rebuilt only when the source or
the compiler changed (the file is 65k lines). Later: back to a normal import after the
optimisation pass."""
reg_k = gen_registry(src)
obj_dir = (cache_root or (out / "obj")) / "registry"
obj_dir.mkdir(parents=True, exist_ok=True)
obj = obj_dir / "registry.o"
argv = [str(kairo), str(reg_k), "-c", "--emit-scope=inputs", "-w", "-o", str(obj),
"-I", str(REGISTRY_DIR / "Compiler"), "-I", str(src / "Compiler"), "-I", str(src / "Linker"),
"--cache-dir", str(cache_root / "tu" if cache_root else obj_dir / "cache"), *extra]
st = kairo.stat()
# Plus the modules it imports: an inline body among them (EvalHash's compute_hash)
# is compiled INTO registry.o, so an edit there must rebuild it.
deps = b""
# The module path of each import: `A::B::*;`, `A::B::name;` or `A::B::{` (gen_diag.py
# names what it uses, rules 5.1-5.2 of Extras/Formatter/README).
for m in re.findall(r"^import ([A-Za-z_][A-Za-z0-9_:]*)::(?:\*|\{|[A-Za-z_][A-Za-z0-9_]*;)", reg_k.read_text(), re.M):
f = src / "Compiler" / (m.replace("::", "/") + ".k")
deps += f.read_bytes() if f.exists() else m.encode()
key = hashlib.sha256(reg_k.read_bytes() + deps
+ repr((str(kairo), st.st_size, st.st_mtime_ns, argv)).encode()).hexdigest()
stamp = obj_dir / "registry.stamp"
if obj.exists() and stamp.exists() and stamp.read_text().strip() == key:
prog.log(f"registry: up to date ({obj})")
return obj
stamp.unlink(missing_ok=True)
rc, secs = prog.run("registry", argv, obj_dir / "registry.log", expect=None)
if rc != 0 or not obj.exists():
prog.fail(obj_dir / "registry.log")
die(f"the registry did not compile (rc {rc}); see {obj_dir / 'registry.log'}")
stamp.write_text(key)
return obj
def _llvm_identity(lib_dir: Path) -> str:
"""The LLVM a cached native object was compiled against, as the build sees it:
every LLVM / clang / lld library in lib_dir by name, size and mtime. A rebuild
of the fork (build_llvm.py, cross_llvm.py) rewrites them, and that is the only way
its headers or its clang change under a build."""
rows = []
if lib_dir.is_dir():
for f in sorted(lib_dir.iterdir()):
n = f.name
if n.startswith(("libLLVM", "libclang", "liblld", "LLVM", "clang", "lld")) and f.is_file():
st = f.stat()
rows.append(f"{n}:{st.st_size}:{st.st_mtime_ns}")
return "\n".join(rows)
def _claim_native(obj: Path, keep: Path):
"""obj, hard-linked (else copied) into keep, the build's own tree, or None when
obj is gone. The shared cache is pruned by whichever build stores next (another
worktree, another key), and that could delete the object this build picked
before its link read it: "object .native-objs/.../cc1as_main-*.o was never
written". The claimed name is this build's alone, and a link keeps the
bytes alive whatever the cache does afterwards."""
keep.mkdir(parents=True, exist_ok=True)
mine = keep / obj.name
tmp = keep / f"{obj.name}.{os.getpid()}.tmp"
try:
tmp.unlink(missing_ok=True)
try:
os.link(obj, tmp)
except FileNotFoundError:
raise
except OSError: # no hard links here (another filesystem)
shutil.copyfile(obj, tmp)
os.replace(tmp, mine)
except FileNotFoundError:
tmp.unlink(missing_ok=True)
return None
# Bounded by age, not count: the tools of one tree use different keys
# (kairo and kcc differ in VERSION) and may build at once, so another
# key's claim can be one a parallel link is about to read.
stem = obj.name.rsplit("-", 1)[0]
for f in keep.glob(f"{stem}-*.o"):
try:
if f.name != mine.name and time.time() - f.stat().st_mtime > 86400:
f.unlink(missing_ok=True)
except OSError:
pass
return mine
def native_object(kairo: Path, src: Path, args: list, key_args: list, llvm_lib: Path,
cache: Path, prog, keep: Path) -> Path:
"""src (the fork's cc1as_main.cpp) compiled once, then taken from cache.
It is one LLVM source file at -O3, ~2 s of every kairo/kcc link on the serial tail
after codegen (NativeCompile), and it changes only with the fork. Compiled by the
compiler doing the build, as `kairo -c` with the build's own flags (args), which
gives the object the in-build compile writes byte for byte. Keyed on the source,
the flags that can reach the object (key_args: the build's, minus the output
tree's path map, which differs between staging and release and names no file this
source includes) and the LLVM libraries (_llvm_identity), never on the compiler
binary: staging and release are different binaries with the same clang inside, and
keying on them would miss on every pipeline step. A miss compiles in place of the
build's own compile, so it costs what the build used to."""
# Plus how kairo turns those flags into the native cc1 line (FlagTranslator,
# ClangBackend, CompilerInstance::_native_words): an edit there must not keep
# linking an object compiled under the old translation. Staging and release
# build the same tree, so they still share the key.
xlate = b"".join((ROOT / "Compiler" / f).read_bytes() for f in
("Command/FlagTranslator.k", "Interop/Clang/ClangBackend.k", "Driver/CompilerInstance.k")
if (ROOT / "Compiler" / f).exists())
key = hashlib.sha256(src.read_bytes() + repr(key_args).encode() + _llvm_identity(llvm_lib).encode()
+ xlate).hexdigest()[:24]
cache.mkdir(parents=True, exist_ok=True)
obj = cache / f"{src.stem}-{key}.o"
if obj.exists():
try:
os.utime(obj) # recency, for the bound below
except OSError:
pass
mine = _claim_native(obj, keep)
if mine is not None:
prog.log(f"{src.name}: cached ({obj})")
return mine
# Pruned between the test and the claim: compile it, as on a miss.
# Per process: concurrent builds share this checkout and this cache.
tmp = cache / f"{src.stem}-{key}.{os.getpid()}.tmp.o"
argv = [str(kairo), str(src), "-c", "-o", str(tmp), *args]
rc, secs = prog.run(src.name, argv, cache / f"{src.stem}.log", expect=None)
if rc != 0 or not tmp.exists():
prog.fail(cache / f"{src.stem}.log")
die(f"{src.name} did not compile (rc {rc}); see {cache / (src.stem + '.log')}")
os.replace(tmp, obj)
# Bounded: the newest few keys per source stay (kairo and kcc differ in
# VERSION, so a pipeline uses two), older ones go.
olds = sorted((f for f in cache.glob(f"{src.stem}-*.o") if not f.name.endswith(".tmp.o")),
key=lambda f: f.stat().st_mtime_ns, reverse=True)
for old in olds[4:]:
old.unlink(missing_ok=True)
mine = _claim_native(obj, keep)
if mine is None:
# Another build's prune took it already: the compiled bytes are gone,
# so compile once more, into this build's own tree only.
tmp = keep / f"{src.stem}-{key}.{os.getpid()}.tmp.o"
keep.mkdir(parents=True, exist_ok=True)
argv = [str(kairo), str(src), "-c", "-o", str(tmp), *args]
rc, secs = prog.run(src.name, argv, cache / f"{src.stem}.log", expect=None)
if rc != 0 or not tmp.exists():
prog.fail(cache / f"{src.stem}.log")
die(f"{src.name} did not compile (rc {rc}); see {cache / (src.stem + '.log')}")
mine = keep / f"{src.stem}-{key}.o"
os.replace(tmp, mine)
return mine
# --- progress (a ninja-style pinned status line) -------------------------------
def tu_objects(obj_dir: Path):
"""The per-TU objects kairo writes under its --cache-dir, without its incremental
store (kairo-cache-v<N>/, Compiler/Spec/Incremental.md), which holds a copy of each."""
for f in obj_dir.rglob("*.o"):
if not any(p.startswith("kairo-cache-v") for p in f.relative_to(obj_dir).parts):
yield f
_PROGRESS_RE = re.compile(r"^@progress phase=(\w+) done=(\d+) total=(\d+)(?: reused=(\d+))?(?: ms=\d+)?(?: file=(.*))?$")
def parse_progress(line: str):
"""One `@progress` event from the compiler (Compiler/Spec/Driver.md#progress), as a
dict, or None for any other line (which belongs in the log)."""
m = _PROGRESS_RE.match(line.rstrip("\r\n"))
if not m:
return None
ev = {"phase": m.group(1), "done": int(m.group(2)), "total": int(m.group(3)),
"reused": int(m.group(4) or 0)}
if m.group(5):
ev["file"] = m.group(5) # only an event that names one replaces the last name
return ev
def progress_text(label: str, ev: dict) -> str:
text = f"{label}: {ev['phase']} {ev['done']}/{ev['total']}"
if ev.get("reused"):
text += f", {ev['reused']} reused"
if ev.get("file"):
text += " " + "/".join(ev["file"].split("/")[-3:])
return text
class Progress:
"""Log lines scroll above; one status line stays pinned at the bottom on a TTY:
[3/6] kairo: objects 214/327 65% [#############.......] 1m42s
The step count is build.py's own pipeline; the object count is the .o files the
compiler has written into its --cache-dir during this step, against the count the
previous build left there (or the number of .k files on a first build). Not a TTY:
plain lines, no redraws."""
def __init__(self, total: int):
self.total = total
self.step = 0
self.tty = sys.stdout.isatty() and os.environ.get("TERM") != "dumb"
self.started = time.monotonic()
def _clear(self):
if self.tty:
sys.stdout.write("\r\x1b[2K")
def log(self, msg: str):
self._clear()
print(f"[build] {msg}", flush=True)
def next(self, what: str):
self.step += 1
self.what = what
self.log(f"[{self.step}/{self.total}] {what}")
def _bar(self, text: str, frac=None):
if not self.tty:
return
cols = shutil.get_terminal_size((100, 20)).columns
el = int(time.monotonic() - self.t0)
tail = f" {el // 60}m{el % 60:02d}s"
head = f"[{self.step}/{self.total}] {text}"
if frac is not None:
w = max(10, min(30, cols - len(head) - len(tail) - 8))
fill = int(w * min(frac, 1.0))
head += f" {int(frac * 100):3d}% [{'#' * fill}{'.' * (w - fill)}]"
line = (head + tail)[:cols - 1]
sys.stdout.write("\r\x1b[2K\x1b[1m" + line + "\x1b[0m")
sys.stdout.flush()
def run(self, label: str, argv: list, log_path: Path, expect=None, obj_dir=None, binary=None):
"""Run argv with its output in log_path; animate the pinned line meanwhile.
A compiler that has --progress is run with --progress=lines and its `@progress`
events (Compiler/Spec/Driver.md#progress) drive the line; one that does not
keeps the old estimate from the .o files in its --cache-dir."""
self.t0 = time.monotonic()
log_path.parent.mkdir(parents=True, exist_ok=True)
wall0 = time.time()
events = kairo_has_flag(Path(argv[0]), "--progress") if Path(argv[0]).name.startswith("kairo") else False
state = {}
lock = threading.Lock()
with open(log_path, "w", encoding="utf-8") as lf:
if events and self.tty and _HAVE_PTY:
# Kairo draws its own bar: give it a terminal for stderr and pass its
# redraws through; everything else on stderr goes to the log.
rc = self._run_passthrough(argv, lf)
self._clear()
return rc, time.monotonic() - self.t0
if events:
p = subprocess.Popen([*argv, "--progress=lines"], cwd=str(ROOT), stdout=lf,
stderr=subprocess.PIPE)
def pump():
# Every other line goes to the log as it always did; the log is
# shared with stdout, so write under the lock and flush.
for raw in p.stderr:
line = raw.decode("utf-8", errors="replace")
ev = parse_progress(line)
with lock:
if ev is not None:
if ev["phase"] != state.get("phase"):
state.clear() # the last phase's file is not this one's
state.update(ev)
else:
lf.write(line)
lf.flush()
t = threading.Thread(target=pump, daemon=True)
t.start()
else:
p = subprocess.Popen(argv, cwd=str(ROOT), stdout=lf, stderr=subprocess.STDOUT)
while p.poll() is None:
time.sleep(0.25)
if events:
with lock:
ev = dict(state)
if ev:
self._bar(progress_text(label, ev), ev["done"] / ev["total"] if ev["total"] else None)
else:
self._bar(f"{label}")
elif obj_dir is not None and expect:
done = sum(1 for f in tu_objects(obj_dir) if f.stat().st_mtime >= wall0)
if binary is not None and binary.exists() and binary.stat().st_mtime >= wall0:
self._bar(f"{label}: linking", 1.0)
elif done == 0:
self._bar(f"{label}: parse + sema")
elif done >= expect:
self._bar(f"{label}: objects {done}/{expect}, linking", 1.0)
else:
self._bar(f"{label}: objects {done}/{expect}", done / expect)
else:
self._bar(f"{label}")
if events:
t.join()
self._clear()
secs = time.monotonic() - self.t0
return p.returncode, secs
def _run_passthrough(self, argv: list, lf) -> int:
"""Run a compiler with its stderr on a pty and --progress=always, so its own
pinned line (`\\r\\x1b[2K` + text, no newline) reaches the terminal unchanged.
Our pinned line stays off for the duration. A piece of stderr that ends in a
newline is not a redraw (the compiler erases its line before diagnostics):
it goes to the log, as does anything that is not preceded by an erase."""
sys.stdout.flush()
master, slave = pty.openpty()
try:
fcntl.ioctl(slave, termios.TIOCSWINSZ,
fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, b"\0" * 8))
except OSError:
pass
tty.setraw(slave) # no CRLF translation or echo: the bytes arrive as written
p = subprocess.Popen([*argv, "--progress=always"], cwd=str(ROOT), stdout=lf, stderr=slave)
os.close(slave)
erase = b"\r\x1b[2K"
def pump():
out = sys.stdout.buffer
while True:
try:
data = os.read(master, 65536)
except OSError:
break # EIO: every writer closed the slave
if not data:
break
head, *rest = data.split(erase)
if head:
lf.write(head.decode("utf-8", errors="replace"))
for piece in rest:
out.write(erase) # always: the compiler's own line is being replaced
if b"\n" in piece:
lf.write(piece.decode("utf-8", errors="replace")) # a diagnostic
else:
out.write(piece) # a redraw: a single write, never split
lf.flush()
out.flush()