-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathninja_backend.cppm
More file actions
1002 lines (909 loc) · 41.1 KB
/
Copy pathninja_backend.cppm
File metadata and controls
1002 lines (909 loc) · 41.1 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
// mcpp.build.ninja — Ninja-backed implementation of Backend.
//
// Layout produced under plan.outputDir = target/<triple>/<fp>/:
// build.ninja
// gcm.cache/std.gcm (symlink/copy of plan.stdBmiPath)
// gcm.cache/<module>.gcm (created by GCC during compile)
// obj/<unit>.o
// obj/std.o (symlink/copy of plan.stdObjectPath)
// bin/<target>
//
// All compile commands are run with cwd = plan.outputDir, so GCC's implicit
// gcm.cache/ lookup finds both std and our package modules.
module;
#include <cstdio>
#include <cstdlib>
export module mcpp.build.ninja;
import std;
import mcpp.build.backend;
import mcpp.build.plan;
import mcpp.build.flags;
import mcpp.build.hermetic;
import mcpp.build.compile_commands;
import mcpp.dyndep;
import mcpp.toolchain.detect;
import mcpp.toolchain.dialect;
import mcpp.toolchain.provider;
import mcpp.toolchain.registry;
import mcpp.xlings;
import mcpp.platform;
export namespace mcpp::build {
class NinjaBackend final : public Backend {
public:
std::string_view name() const override {
return "ninja";
}
std::expected<BuildResult, BuildError> build(const BuildPlan& plan,
const BuildOptions& opts) override;
};
// Factory for this backend implementation.
std::unique_ptr<Backend> make_ninja_backend();
// Helper exposed for testing / debugging
std::string emit_ninja_string(const BuildPlan& plan);
std::string filter_ninja_output(std::string_view output,
std::span<const std::string> commandPrefixes);
} // namespace mcpp::build
namespace mcpp::build {
namespace {
std::string escape_ninja_path(const std::filesystem::path& p) {
// Ninja escapes: $ → $$, : → $:, space → $ (with leading space).
// For simplicity we wrap in case-by-case.
std::string s = p.string();
std::string out;
for (char c : s) {
if (c == '$')
out += "$$";
else if (c == ':')
out += "$:";
else if (c == ' ')
out += "$ ";
else
out.push_back(c);
}
return out;
}
std::string escape_flag_path(const std::filesystem::path& p) {
auto s = p.string();
std::string out;
out.reserve(s.size());
for (char c : s) {
if (c == ' ' || c == '$' || c == ':')
out.push_back('$');
out.push_back(c);
}
return out;
}
std::string local_include_flags(const CompileUnit& cu) {
std::string flags;
for (auto const& inc : cu.localIncludeDirs) {
flags += " -I";
flags += escape_flag_path(inc);
}
return flags;
}
std::string join_flags(const std::vector<std::string>& flags) {
std::string out;
for (auto const& flag : flags) {
out += ' ';
out += flag;
}
return out;
}
std::string shared_soname_flag(const LinkUnit& lu) {
if (lu.kind != LinkUnit::SharedLibrary || lu.soname.empty()) return "";
#if defined(__APPLE__)
return "-Wl,-install_name,@rpath/" + lu.soname;
#elif defined(__linux__)
return "-Wl,-soname," + lu.soname;
#else
return "";
#endif
}
void write_file(const std::filesystem::path& p, std::string_view content) {
std::filesystem::create_directories(p.parent_path());
std::ofstream os(p);
os << content;
}
bool run(const std::string& cmd, std::string& output_capture, bool capture_output = true) {
output_capture.clear();
if (capture_output) {
auto r = mcpp::platform::process::capture(cmd);
output_capture = r.output;
return r.exit_code == 0;
}
return mcpp::platform::process::run_passthrough(cmd) == 0;
}
bool dyndep_mode_enabled() {
// M4 #7: dyndep is now the default. Set MCPP_NINJA_DYNDEP=0 to opt
// OUT and fall back to the static-deps emission path.
const char* v = std::getenv("MCPP_NINJA_DYNDEP");
if (!v)
return true;
std::string_view sv(v);
return !(sv == "0" || sv == "off" || sv == "false");
}
std::filesystem::path mcpp_exe_path() {
return mcpp::platform::fs::self_exe_path();
}
bool is_c_source(const std::filesystem::path& src) {
auto ext = src.extension();
return ext == ".c" || ext == ".m";
}
bool is_gas_source(const std::filesystem::path& src) {
auto ext = src.extension();
return ext == ".S" || ext == ".s";
}
bool is_nasm_source(const std::filesystem::path& src) {
return src.extension() == ".asm";
}
// TUs the P1689 module scan must skip: C-family and assembly units cannot
// contain `import`/`module` declarations, and feeding them to the scanner
// would route them through the C++ frontend.
bool is_scan_exempt(const std::filesystem::path& src) {
return is_c_source(src) || is_gas_source(src) || is_nasm_source(src);
}
// Per-unit flags an assembler can take: the -D/-U/-I subset of the unit's C
// flags (feature defines land there). NASM shares the GNU -D/-U/-I spelling
// (and ≥2.14 inserts a missing -I path separator itself), so one filter
// serves both asm rules. Explicit per-glob asmflags (G4) append after the
// filtered subset — author-directed flags win.
std::vector<std::string> asm_unit_flags(const CompileUnit& cu) {
std::vector<std::string> out;
for (auto& f : cu.packageCflags) {
if (f.starts_with("-D") || f.starts_with("-U") || f.starts_with("-I"))
out.push_back(f);
}
out.insert(out.end(), cu.packageAsmflags.begin(), cu.packageAsmflags.end());
return out;
}
std::string ltrim_copy(std::string_view s) {
while (!s.empty() && std::isspace(static_cast<unsigned char>(s.front())))
s.remove_prefix(1);
return std::string(s);
}
bool is_ninja_progress_line(std::string_view line) {
if (line.size() < 5 || line.front() != '[') return false;
std::size_t i = 1;
if (i >= line.size() || !std::isdigit(static_cast<unsigned char>(line[i])))
return false;
while (i < line.size() && std::isdigit(static_cast<unsigned char>(line[i]))) ++i;
if (i >= line.size() || line[i] != '/') return false;
++i;
if (i >= line.size() || !std::isdigit(static_cast<unsigned char>(line[i])))
return false;
while (i < line.size() && std::isdigit(static_cast<unsigned char>(line[i]))) ++i;
return i < line.size() && line[i] == ']';
}
bool starts_with_any(std::string_view line,
std::span<const std::string> prefixes) {
for (auto& prefix : prefixes) {
if (!prefix.empty() && line.starts_with(prefix))
return true;
}
return false;
}
bool contains_any(std::string_view line,
std::span<const std::string> needles) {
for (auto& needle : needles) {
if (!needle.empty() && line.find(needle) != std::string_view::npos)
return true;
}
return false;
}
std::vector<std::string> command_prefixes(const CompileFlags& flags,
const BuildPlan& plan) {
std::vector<std::string> prefixes;
auto add = [&](const std::filesystem::path& p) {
if (p.empty()) return;
auto s = p.string();
if (std::find(prefixes.begin(), prefixes.end(), s) == prefixes.end())
prefixes.push_back(std::move(s));
};
add(flags.cxxBinary);
add(flags.ccBinary);
add(flags.arBinary);
add(plan.scanDepsPath);
return prefixes;
}
bool is_command_line(std::string_view trimmed,
std::span<const std::string> commandPrefixes) {
if (starts_with_any(trimmed, commandPrefixes)) return true;
if (trimmed.starts_with("env ")
&& (trimmed.find("LD_LIBRARY_PATH=") != std::string_view::npos
|| trimmed.find("DYLD_LIBRARY_PATH=") != std::string_view::npos
|| contains_any(trimmed, commandPrefixes))) {
return true;
}
if ((trimmed.starts_with("cmd /c ") || trimmed.starts_with("if [ "))
&& contains_any(trimmed, commandPrefixes)) {
return true;
}
return false;
}
std::optional<std::pair<std::string, std::string>>
runtime_env_for_dirs(const std::vector<std::filesystem::path>& dirs) {
auto key = mcpp::platform::env::runtime_library_path_key();
auto value = mcpp::platform::env::prepend_path_list(key, dirs);
if (key.empty() || value.empty()) return std::nullopt;
return std::pair{std::move(key), std::move(value)};
}
} // namespace
std::string filter_ninja_output(std::string_view output,
std::span<const std::string> commandPrefixes) {
std::string filtered;
std::string line;
std::istringstream in{std::string(output)};
while (std::getline(in, line)) {
if (!line.empty() && line.back() == '\r')
line.pop_back();
auto trimmed = ltrim_copy(line);
if (trimmed.starts_with("ninja: Entering directory")
|| trimmed.starts_with("ninja: build stopped")
|| trimmed.starts_with("FAILED:")
|| is_ninja_progress_line(trimmed)
|| is_command_line(trimmed, commandPrefixes)) {
continue;
}
filtered += line;
filtered.push_back('\n');
}
return filtered;
}
std::string emit_ninja_string(const BuildPlan& plan) {
// dyndep requires P1689 scanning capability:
// GCC: built-in -fdeps-format=p1689r5
// Clang: external clang-scan-deps tool (same P1689 output format)
// (MSVC /scanDependencies is the future third driver — scanner design §3a)
auto caps = mcpp::toolchain::capabilities_for(plan.toolchain);
bool has_scanner = caps.has_builtin_p1689_scan || !plan.scanDepsPath.empty();
bool dyndep = dyndep_mode_enabled() && has_scanner;
auto traits = mcpp::toolchain::bmi_traits(plan.toolchain);
const auto& dial = mcpp::toolchain::dialect_for(plan.toolchain);
std::string out;
auto append = [&](std::string s) { out += std::move(s); };
append("# Auto-generated by mcpp v0.0.1. Do not edit by hand.\n");
append("ninja_required_version = 1.11\n\n");
// All compile/link flags are computed once via flags.cppm.
auto flags = compute_flags(plan);
bool need_c_rule = false, need_asm_rule = false, need_nasm_rule = false;
for (auto& cu : plan.compileUnits) {
if (is_c_source(cu.source)) need_c_rule = true;
else if (is_gas_source(cu.source)) need_asm_rule = true;
else if (is_nasm_source(cu.source)) need_nasm_rule = true;
}
append(std::format("cxx = {}\n", escape_ninja_path(flags.cxxBinary)));
append(std::format("cxxflags = {}\n", flags.cxx));
if (need_c_rule || need_asm_rule) { // asm_object drives the C compiler too
append(std::format("cc = {}\n", escape_ninja_path(flags.ccBinary)));
}
if (need_c_rule) {
append(std::format("cflags = {}\n", flags.cc));
}
if (need_asm_rule) {
append(std::format("asmflags ={}\n", flags.as));
}
if (need_nasm_rule) {
append(std::format("nasm = {}\n", escape_ninja_path(plan.nasmPath)));
append(std::format("nasmfmt = {}\n", plan.nasmFormat));
append(std::format("nasmflags ={}\n", flags.nasm));
}
append(std::format("ldflags ={}\n", flags.ld));
// `ar` for cxx_archive.
if (!flags.arBinary.empty()) {
append(std::format("ar = {}\n", escape_ninja_path(flags.arBinary)));
} else {
append("ar = ar\n");
}
// Separate linker (link.exe) for the msvc dialect.
const bool separateLinker =
dial.linkStyle == mcpp::toolchain::CommandDialect::LinkStyle::SeparateLinker;
if (separateLinker) {
append(std::format("ld = {}\n",
flags.ldBinary.empty() ? std::string("link.exe")
: escape_ninja_path(flags.ldBinary)));
}
if (dyndep) {
append(std::format("mcpp = {}\n", escape_ninja_path(mcpp_exe_path())));
if (!plan.scanDepsPath.empty()) {
append(std::format("scan_deps = {}\n", escape_ninja_path(plan.scanDepsPath)));
}
}
append("\n");
append("rule cp_bmi\n");
if constexpr (mcpp::platform::is_windows) {
// Use PowerShell Copy-Item which handles both forward and back slashes.
// cmd.exe `copy` breaks on forward-slash paths from ninja.
append(" command = powershell -NoProfile -Command \"Copy-Item -Force '$in' -Destination '$out'\"\n");
} else {
append(" command = mkdir -p $$(dirname $out) && cp -f $in $out\n");
}
append(" description = STAGE $out\n\n");
// P1: per-file dyndep rule. Converts one .ddi → .dd independently.
append(std::format(
"rule cxx_dyndep\n"
" command = $mcpp dyndep --single --bmi-dir {} --bmi-ext {} $expect --output $out $in\n"
" description = DYNDEP $out\n"
" restat = 1\n\n",
traits.bmiDir, traits.bmiExt));
// P2: cxx_module preserves BMI timestamps when interface is unchanged.
// GCC always updates the .gcm timestamp even if content is identical.
// We backup the BMI before compilation, compile, then restore the old
// file if content is byte-identical. Combined with restat = 1 in the
// dyndep file, this prevents cascading rebuilds when only the module
// implementation changed (not the interface).
//
// $bmi_out is set per build edge to the BMI path (gcm.cache/<module>.gcm).
// If $bmi_out is empty (no module provided), we just compile normally.
// Runtime library paths for private toolchain executables are scoped onto
// the ninja subprocess instead of being emitted into each visible rule.
// Command spellings come from the toolchain's CommandDialect (gnu vs
// msvc); the rule *structure* is shared across compilers.
std::string module_output_flag = traits.needsExplicitModuleOutput
? std::string(traits.moduleOutputPrefix) + "$bmi_out" : "";
// msvc: /showIncludes feeds ninja's deps=msvc header tracking; the
// stable-English prefix is guaranteed by VSLANG=1033 in envOverrides.
const bool msvcDeps = dial.ninjaDepsMode == std::string_view("msvc");
const std::string compile_tail = std::format(
"{}{} $in {}$out",
msvcDeps ? "/showIncludes " : "", dial.compileOnly, dial.outputObjPrefix);
auto append_deps = [&] {
if (msvcDeps) append(" deps = msvc\n");
};
// cl.exe needs /TP (our module interfaces are .cppm, unknown to cl) and
// /interface to treat the TU as a module interface unit.
const std::string module_src_flags = msvcDeps ? " /interface /TP" : "";
append("rule cxx_module\n");
if constexpr (mcpp::platform::is_windows) {
// Windows: skip BMI restat optimization (requires POSIX shell).
append(std::format(" command = "
"$cxx $local_includes $cxxflags $unit_cxxflags{}{} {}\n",
module_output_flag, module_src_flags, compile_tail));
append_deps();
} else {
append(std::format(" command = "
"if [ -n \"$bmi_out\" ] && [ -f \"$bmi_out\" ]; then "
"cp -p \"$bmi_out\" \"$bmi_out.bak\"; "
"fi && "
"$cxx $local_includes $cxxflags $unit_cxxflags{} {} && "
"if [ -n \"$bmi_out\" ] && [ -f \"$bmi_out.bak\" ] && "
"cmp -s \"$bmi_out\" \"$bmi_out.bak\"; then "
"mv \"$bmi_out.bak\" \"$bmi_out\"; "
"else "
"rm -f \"$bmi_out.bak\"; "
"fi\n", module_output_flag, compile_tail));
}
append(" description = MOD $out\n");
if (dyndep)
append(" restat = 1\n");
append("\n");
append("rule cxx_object\n");
append(std::format(
" command = $cxx $local_includes $cxxflags $unit_cxxflags {}\n",
compile_tail));
append(" description = OBJ $out\n");
append_deps();
if (dyndep)
append(" restat = 1\n");
append("\n");
if (need_c_rule) {
append("rule c_object\n");
append(std::format(
" command = $cc $local_includes $cflags $unit_cflags {}\n",
compile_tail));
append(" description = CC $out\n");
append_deps();
if (dyndep)
append(" restat = 1\n");
append("\n");
}
if (need_asm_rule) {
// GAS assembly (.S/.s) through the C driver: it preprocesses .S (cpp)
// and assembles both, dispatching by extension. $asmflags is the
// asm-safe flag subset (no -std / no -O — see flags.cppm).
append("rule asm_object\n");
append(std::format(
" command = $cc $local_includes $asmflags $unit_asmflags {}\n",
compile_tail));
append(" description = AS $out\n\n");
}
if (need_nasm_rule) {
// NASM (.asm): its own fixed flag spelling — deliberately outside
// CommandDialect. -MD/-MQ feed ninja's header tracking for %include.
append("rule nasm_object\n");
append(" command = $nasm -f $nasmfmt $local_includes $nasmflags "
"$unit_asmflags -MD $out.d -MQ $out -o $out $in\n");
append(" deps = gcc\n");
append(" depfile = $out.d\n");
append(" description = NASM $out\n\n");
}
// Link/archive/shared: driver-style (g++/clang++ are the linker) vs the
// msvc dialect's separate link.exe/lib.exe. The msvc commands go through
// response files — object lists exceed cmd.exe's 8191-char limit fast.
if (separateLinker) {
append("rule cxx_link\n");
append(" command = $ld /nologo /OUT:$out @$out.rsp $ldflags $unit_ldflags\n");
append(" rspfile = $out.rsp\n");
append(" rspfile_content = $in\n");
append(" description = LINK $out\n\n");
append("rule cxx_archive\n");
append(" command = $ar /nologo /OUT:$out @$out.rsp\n");
append(" rspfile = $out.rsp\n");
append(" rspfile_content = $in\n");
append(" description = AR $out\n\n");
append("rule cxx_shared\n");
append(" command = $ld /nologo /DLL /OUT:$out /IMPLIB:$out.lib "
"@$out.rsp $ldflags $unit_ldflags\n");
append(" rspfile = $out.rsp\n");
append(" rspfile_content = $in\n");
append(" description = SHARED $out\n\n");
} else {
append("rule cxx_link\n");
append(" command = $cxx $in -o $out $ldflags $unit_ldflags\n");
append(" description = LINK $out\n\n");
append("rule cxx_archive\n");
append(std::format(" command = {}\n", dial.archiveCmd));
append(" description = AR $out\n\n");
append("rule cxx_shared\n");
append(" command = $cxx -shared $in -o $out $ldflags $soname_flag $unit_ldflags\n");
append(" description = SHARED $out\n\n");
}
append("rule runtime_alias\n");
if constexpr (mcpp::platform::is_windows) {
append(" command = powershell -NoProfile -Command \"Copy-Item -Force '$in' -Destination '$out'\"\n");
} else {
append(" command = mkdir -p $$(dirname $out) && rm -f $out && ln -s $$(basename $in) $out\n");
}
append(" description = ALIAS $out\n\n");
if (dyndep) {
// Scan rule: produce P1689 .ddi for one TU.
// GCC: built-in -fdeps-format=p1689r5 flags during preprocessing.
// Clang: external clang-scan-deps tool with -format=p1689.
append("rule cxx_scan\n");
if (msvcDeps) {
// MSVC: compiler-integrated P1689 via /scanDependencies (scan
// only — no codegen); /TP because our module units are .cppm.
append(" command = $cxx $local_includes $cxxflags $unit_cxxflags "
"/scanDependencies $out /TP /c $in /Fo:$compile_target\n");
} else if (plan.scanDepsPath.empty()) {
// GCC path: compiler-integrated P1689 scanning.
append(" command = $cxx $local_includes $cxxflags -fmodules "
"$unit_cxxflags "
"-fdeps-format=p1689r5 "
"-fdeps-file=$out -fdeps-target=$compile_target "
"-M -MM -MF $out.dep -E $in -o $compile_target\n");
} else {
// Clang path: clang-scan-deps produces P1689 JSON to stdout.
if constexpr (mcpp::platform::is_windows) {
// Wrap in cmd /c for shell redirection (ninja on Windows uses
// CreateProcess which doesn't interpret > as redirect).
append(" command = cmd /c \"$scan_deps -format=p1689 -- "
"$cxx $local_includes $cxxflags $unit_cxxflags -c $in -o $compile_target > $out\"\n");
} else {
append(" command = $scan_deps -format=p1689 -- "
"$cxx $local_includes $cxxflags $unit_cxxflags -c $in -o $compile_target > $out\n");
}
}
append(" description = SCAN $out\n\n");
// Aggregate .ddi files into a Ninja dyndep file.
append(std::format(
"rule cxx_collect\n"
" command = $mcpp dyndep --bmi-dir {} --bmi-ext {} --output $out $in\n"
" description = COLLECT $out\n"
" restat = 1\n\n",
traits.bmiDir, traits.bmiExt));
}
// Stage prebuilt std artifacts into the compiler-specific BMI cache.
auto std_bmi_dst = mcpp::toolchain::staged_std_bmi_path(plan.toolchain, {});
auto std_o_dst = std::filesystem::path("obj")
/ std::format("std{}", dial.objExt);
bool has_std_artifacts = !plan.stdBmiPath.empty() && !plan.stdObjectPath.empty();
if (has_std_artifacts) {
append(std::format("build {} : cp_bmi {}\n", escape_ninja_path(std_bmi_dst),
escape_ninja_path(plan.stdBmiPath)));
append(std::format("build {} : cp_bmi {}\n\n", escape_ninja_path(std_o_dst),
escape_ninja_path(plan.stdObjectPath)));
}
bool has_std_compat = !plan.stdCompatBmiPath.empty() && !plan.stdCompatObjectPath.empty();
auto compat_bmi_dst = std::filesystem::path(traits.bmiDir)
/ std::format("std.compat{}", traits.bmiExt);
auto compat_o_dst = std::filesystem::path("obj")
/ std::format("std.compat{}", dial.objExt);
if (has_std_compat) {
// std.compat.pcm depends on std.pcm — ensure std.pcm is staged first
// so clang can resolve the transitive dependency when loading std.compat.pcm.
append(std::format("build {} : cp_bmi {} | {}\n", escape_ninja_path(compat_bmi_dst),
escape_ninja_path(plan.stdCompatBmiPath),
escape_ninja_path(std_bmi_dst)));
append(std::format("build {} : cp_bmi {}\n\n", escape_ninja_path(compat_o_dst),
escape_ninja_path(plan.stdCompatObjectPath)));
}
auto bmi_path = [&traits](std::string_view name) {
std::string s(traits.bmiDir);
s += '/';
for (char c : name)
s.push_back(c == ':' ? '-' : c);
s += traits.bmiExt;
return s;
};
auto pick_rule = [](const std::filesystem::path& src) -> std::string {
auto ext = src.extension();
if (ext == ".cppm")
return "cxx_module";
if (ext == ".c" || ext == ".m")
return "c_object";
if (ext == ".S" || ext == ".s")
return "asm_object";
if (ext == ".asm")
return "nasm_object";
return "cxx_object";
};
if (dyndep) {
// ── Phase 1: scan edges (one .ddi per TU). ──────────────────────
// .ddi is placed beside the object so multi-version mangling can
// namespace by package without producing two `build` rules with
// the same `.ddi` output (plan.cppm switches `cu.object` from
// `obj/<file>.o` to `obj/<pkg>/<file>.o` whenever a basename
// collides across packages — `.ddi` follows that placement).
// Skip .c files: they have no `import`s and don't need P1689 scan;
// running them through cxx_scan would route them through g++ /
// -fmodules which is exactly what C support is here to avoid.
std::vector<std::string> ddi_paths;
ddi_paths.reserve(plan.compileUnits.size());
for (auto& cu : plan.compileUnits) {
if (is_scan_exempt(cu.source))
continue;
auto ddi = (cu.object.parent_path() / cu.source.filename()).string() + ".ddi";
ddi_paths.push_back(ddi);
append(std::format("build {} : cxx_scan {}\n", escape_ninja_path(ddi),
escape_ninja_path(cu.source)));
append(std::format(" compile_target = {}\n", escape_ninja_path(cu.object)));
if (auto includes = local_include_flags(cu); !includes.empty())
append(std::format(" local_includes ={}\n", includes));
if (auto flags = join_flags(cu.packageCxxflags); !flags.empty())
append(std::format(" unit_cxxflags ={}\n", flags));
}
append("\n");
// ── Phase 2: per-file dyndep (P1 optimization). ────────────────
// Each .ddi → .dd independently, so modifying one source file only
// invalidates that file's .dd and its compile edge, not all edges.
// Map ddi path → dd path for Phase 3 reference.
std::map<std::string, std::string> ddi_to_dd;
// Plan-vs-ddi reconciliation (design 2026-07-08 scanner doc §3d):
// scan_overrides units ALWAYS carry their planned (provides, imports)
// on the dyndep edge — the compiler's own P1689 scan audits the
// author's assertion, per TU, failing the edge on divergence.
// MCPP_VERIFY_MODGRAPH=1 (read at generation time) extends the
// check to every module unit.
const bool verifyAll = [] {
const char* v = std::getenv("MCPP_VERIFY_MODGRAPH");
return v && std::string_view(v) == "1";
}();
std::map<std::string, std::string> ddi_expect;
for (auto& cu : plan.compileUnits) {
if (is_scan_exempt(cu.source)) continue;
if (!cu.scanOverridden && !verifyAll) continue;
auto ddi = (cu.object.parent_path() / cu.source.filename()).string() + ".ddi";
std::string exp;
if (cu.providesModule)
exp += std::format("--expect-provides {}", *cu.providesModule);
if (!cu.imports.empty()) {
std::string csv;
for (auto& m : cu.imports) {
if (!csv.empty()) csv += ",";
csv += m;
}
if (!exp.empty()) exp += " ";
exp += std::format("--expect-imports {}", csv);
}
if (exp.empty()) exp = "--expect-none";
ddi_expect[ddi] = std::move(exp);
}
for (auto& ddi : ddi_paths) {
auto dd = ddi + ".dd"; // e.g. obj/cli.cppm.ddi.dd
ddi_to_dd[ddi] = dd;
append(std::format("build {} : cxx_dyndep {}\n", dd, ddi));
if (auto it = ddi_expect.find(ddi); it != ddi_expect.end())
append(std::format(" expect = {}\n", it->second));
}
append("\n");
// ── Phase 3: compile edges with per-file dyndep. ────────────────
// Each compile edge references its OWN .dd file instead of a global one.
// P2: module compile edges get a $bmi_out variable for BMI preservation.
for (auto& cu : plan.compileUnits) {
std::string rule = pick_rule(cu.source);
std::string out_line = "build " + escape_ninja_path(cu.object);
if (cu.providesModule) {
out_line += " | " + bmi_path(*cu.providesModule);
}
out_line += std::format(" : {} {}", rule, escape_ninja_path(cu.source));
if (!is_scan_exempt(cu.source)) {
auto ddi = (cu.object.parent_path() / cu.source.filename()).string() + ".ddi";
auto it = ddi_to_dd.find(ddi);
if (it != ddi_to_dd.end()) {
out_line += " | " + it->second;
out_line += "\n dyndep = " + it->second;
// P2: set bmi_out for the copy_if_different logic in cxx_module.
if (cu.providesModule) {
out_line += "\n bmi_out = " + bmi_path(*cu.providesModule);
}
out_line += "\n";
} else {
out_line += "\n";
}
} else {
out_line += "\n";
}
if (auto includes = local_include_flags(cu); !includes.empty())
out_line += " local_includes =" + includes + "\n";
if (is_gas_source(cu.source) || is_nasm_source(cu.source)) {
if (auto flags = join_flags(asm_unit_flags(cu)); !flags.empty())
out_line += " unit_asmflags =" + flags + "\n";
} else if (is_c_source(cu.source)) {
if (auto flags = join_flags(cu.packageCflags); !flags.empty())
out_line += " unit_cflags =" + flags + "\n";
} else {
if (auto flags = join_flags(cu.packageCxxflags); !flags.empty())
out_line += " unit_cxxflags =" + flags + "\n";
}
append(std::move(out_line));
}
append("\n");
} else {
// ── Static-deps mode (M3.2 and earlier). ────────────────────────
for (auto& cu : plan.compileUnits) {
std::string rule = pick_rule(cu.source);
std::string implicit;
// C/asm files don't `import` modules; skip BMI implicit inputs.
if (!is_scan_exempt(cu.source)) {
for (auto& imp : cu.imports) {
if (imp == "std") {
if (has_std_artifacts)
implicit += " " + escape_ninja_path(std_bmi_dst);
continue;
}
if (imp == "std.compat") {
if (has_std_compat)
implicit += " " + escape_ninja_path(compat_bmi_dst);
else if (has_std_artifacts)
implicit += " " + escape_ninja_path(std_bmi_dst);
continue;
}
implicit += " " + bmi_path(imp);
}
}
std::string out_line = "build " + escape_ninja_path(cu.object);
if (cu.providesModule) {
// Use implicit output (|) so $out only contains the .o file.
// GCC writes BMI implicitly; Clang uses -fmodule-output=$bmi_out.
out_line += " | " + bmi_path(*cu.providesModule);
}
out_line += std::format(" : {} {}", rule, escape_ninja_path(cu.source));
if (!implicit.empty())
out_line += " |" + implicit;
out_line += "\n";
if (auto includes = local_include_flags(cu); !includes.empty())
out_line += " local_includes =" + includes + "\n";
if (is_gas_source(cu.source) || is_nasm_source(cu.source)) {
if (auto flags = join_flags(asm_unit_flags(cu)); !flags.empty())
out_line += " unit_asmflags =" + flags + "\n";
} else if (is_c_source(cu.source)) {
if (auto flags = join_flags(cu.packageCflags); !flags.empty())
out_line += " unit_cflags =" + flags + "\n";
} else {
if (auto flags = join_flags(cu.packageCxxflags); !flags.empty())
out_line += " unit_cxxflags =" + flags + "\n";
}
// Clang needs $bmi_out to emit -fmodule-output=$bmi_out
if (cu.providesModule) {
out_line += " bmi_out = " + bmi_path(*cu.providesModule) + "\n";
}
append(std::move(out_line));
}
append("\n");
}
// Link units
for (auto& lu : plan.linkUnits) {
std::string ins;
for (auto& o : lu.objects) {
ins += " " + escape_ninja_path(o);
}
std::string rule;
switch (lu.kind) {
case LinkUnit::Binary:
case LinkUnit::TestBinary:
if (has_std_artifacts)
ins += " " + escape_ninja_path(std_o_dst);
if (has_std_compat)
ins += " " + escape_ninja_path(compat_o_dst);
rule = "cxx_link";
break;
case LinkUnit::StaticLibrary:
rule = "cxx_archive";
break;
case LinkUnit::SharedLibrary:
if (has_std_artifacts)
ins += " " + escape_ninja_path(std_o_dst);
if (has_std_compat)
ins += " " + escape_ninja_path(compat_o_dst);
rule = "cxx_shared";
break;
}
std::string implicit;
for (auto& input : lu.implicitInputs) {
implicit += " " + escape_ninja_path(input);
}
// Windows runtime-DLL deployment: an executable takes an implicit
// dependency on each staged dep DLL (bin/<dll>), so ninja copies them
// beside the .exe before the build is considered done. Empty on RPATH
// platforms (no *.dll deps), so other targets are unaffected.
if (lu.kind == LinkUnit::Binary || lu.kind == LinkUnit::TestBinary) {
for (auto const& d : plan.runtimeDeployFiles)
implicit += " " + escape_ninja_path(d.dest);
}
std::string out_line = std::format("build {} : {}{}{}\n",
escape_ninja_path(lu.output), rule, ins,
implicit.empty() ? std::string{} : " |" + implicit);
if (auto flag = shared_soname_flag(lu); !flag.empty())
out_line += " soname_flag = " + flag + "\n";
{
// Per-unit C++ stdlib link (macOS; empty elsewhere): test
// binaries run on the build host and use the system -lc++,
// distributable targets get the static LLVM libc++. See
// CompileFlags::ldStdlibDefault/ldStdlibTest.
std::string unit = join_flags(lu.linkFlags);
unit += (lu.kind == mcpp::build::LinkUnit::TestBinary)
? flags.ldStdlibTest : flags.ldStdlibDefault;
if (!unit.empty())
out_line += " unit_ldflags =" + unit + "\n";
}
append(std::move(out_line));
for (auto const& alias : lu.runtimeAliases) {
append(std::format("build {} : runtime_alias {}\n",
escape_ninja_path(alias),
escape_ninja_path(lu.output)));
}
}
append("\n");
// Windows runtime-DLL deployment: one copy edge per staged dep DLL. Emitted
// once (deduped by dest in BuildPlan), reusing the generic cp_bmi copy rule.
// Inert on RPATH platforms where runtimeDeployFiles is empty.
for (auto const& d : plan.runtimeDeployFiles) {
append(std::format("build {} : cp_bmi {}\n",
escape_ninja_path(d.dest),
escape_ninja_path(d.source)));
}
if (!plan.runtimeDeployFiles.empty())
append("\n");
if (!plan.linkUnits.empty()) {
std::string defaults;
for (auto& lu : plan.linkUnits) {
defaults += " " + escape_ninja_path(lu.output);
for (auto const& alias : lu.runtimeAliases) {
defaults += " " + escape_ninja_path(alias);
}
}
for (auto const& d : plan.runtimeDeployFiles) {
defaults += " " + escape_ninja_path(d.dest);
}
append("default" + defaults + "\n");
}
return out;
}
std::expected<BuildResult, BuildError> NinjaBackend::build(const BuildPlan& plan,
const BuildOptions& opts) {
auto t0 = std::chrono::steady_clock::now();
std::error_code ec;
std::filesystem::create_directories(plan.outputDir, ec);
if (ec)
return std::unexpected(BuildError{std::format("cannot create output dir '{}': {}",
plan.outputDir.string(), ec.message()),
plan.outputDir});
auto ninja_path = plan.outputDir / "build.ninja";
write_file(ninja_path, emit_ninja_string(plan));
// compile_commands.json — via the dedicated module.
auto flags = compute_flags(plan);
write_compile_commands(plan, flags);
if (opts.dryRun) {
BuildResult r;
r.exitCode = 0;
r.elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - t0);
return r;
}
// Hermetic link check: assert the sandbox toolchain resolves its CRT
// objects + dynamic linker inside the sandbox BEFORE running the build —
// catches both the bare-CRT link failure (#195) and silent host-library
// contamination, cached per flag-set.
if (auto h = verify_hermetic_link(plan.toolchain, flags.ld, plan.outputDir,
plan.manifest.buildConfig.allowHostLibs); !h) {
return std::unexpected(BuildError{h.error(), {}});
}
// When the toolchain comes from mcpp's private sandbox, use the
// sandbox-local ninja absolute path (skip the system xlings ninja
// shim which requires per-tool version pin activation).
//
// The compiler's internal `as`/`ld` lookup is handled via the
// -B<binutils-bin> flag we emit into cxxflags/ldflags (see
// emit_ninja_string). No PATH injection needed here.
std::filesystem::path ninjaBin;
auto ninja_name = std::string("ninja") + std::string(mcpp::platform::exe_suffix);
if (auto nb = mcpp::xlings::paths::find_sibling_binary(
plan.toolchain.binaryPath, "ninja", ninja_name)) {
ninjaBin = *nb;
}
// Raw program path (no shell quoting): recorded in the fast-path cache and
// exec'd directly via capture_exec/execvp, which take argv (not a shell
// string). Shell-using call sites must quote it locally.
std::string ninjaProgram = ninjaBin.empty() ? std::string("ninja")
: ninjaBin.string();
// Record ninja binary for P0 fast-path cache.
BuildResult r;
r.ninjaProgram = ninjaProgram;
if (!plan.toolchain.envOverrides.empty()) {
// Toolchain-declared env (MSVC INCLUDE/LIB/PATH/VSLANG). Encode all
// pairs (plus any runtime-dirs pair) into the fast-path cache's
// single env slot: "@env" key + \x1f-separated k=v records — the
// fast path must re-create this exact environment for ninja.
r.runtimeEnvKey = "@env";
std::string joined;
auto add = [&](const std::string& k, const std::string& v) {
if (!joined.empty()) joined += '\x1f';
joined += k; joined += '='; joined += v;
};
if (auto runtimeEnv = runtime_env_for_dirs(plan.toolchain.compilerRuntimeDirs))
add(runtimeEnv->first, runtimeEnv->second);
for (auto& ev : plan.toolchain.envOverrides) add(ev.key, ev.value);
r.runtimeEnvValue = std::move(joined);
} else if (auto runtimeEnv = runtime_env_for_dirs(plan.toolchain.compilerRuntimeDirs)) {
r.runtimeEnvKey = runtimeEnv->first;
r.runtimeEnvValue = runtimeEnv->second;
} else {
r.runtimeEnvKey = "-";
}
// Direct exec (no /bin/sh): argv, not a shell string. capture_exec merges
// stderr into the captured output (replacing the old `2>&1`), and applies
// the runtime env to the child ONLY — so a bundled-glibc LD_LIBRARY_PATH
// can never poison the host shell (the newer-glibc `sh:` crash class).
std::vector<std::string> nargv{ninjaProgram};
if (!opts.verbose)
nargv.push_back("--quiet");
nargv.push_back("-C");
nargv.push_back(plan.outputDir.string());
if (opts.verbose)
nargv.push_back("-v");
if (opts.parallelJobs)
nargv.push_back(std::format("-j{}", opts.parallelJobs));
// Real env pairs for THIS run (the "@env" cache encoding above is only
// for the fast path's later re-creation of the same environment).
std::vector<std::pair<std::string, std::string>> nenv;
if (auto runtimeEnv = runtime_env_for_dirs(plan.toolchain.compilerRuntimeDirs))
nenv.emplace_back(runtimeEnv->first, runtimeEnv->second);
for (auto& ev : plan.toolchain.envOverrides)
nenv.emplace_back(ev.key, ev.value);
auto cap = mcpp::platform::process::capture_exec(nargv, nenv);
std::string out = cap.output;
bool ok = (cap.exit_code == 0);
r.exitCode = ok ? 0 : 1;
r.elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - t0);
if (ok) {
if (opts.verbose && !out.empty())
std::fputs(out.c_str(), stdout);
for (auto& lu : plan.linkUnits) {
r.producedArtifacts.push_back(plan.outputDir / lu.output);
for (auto const& alias : lu.runtimeAliases) {
r.producedArtifacts.push_back(plan.outputDir / alias);
}
}
} else {
auto prefixes = command_prefixes(flags, plan);
auto diagnostics = opts.verbose ? out : filter_ninja_output(out, prefixes);
return std::unexpected(BuildError{"build failed", plan.outputDir / "build.ninja",
std::move(diagnostics)});
}
return r;
}
std::unique_ptr<Backend> make_ninja_backend() {
return std::make_unique<NinjaBackend>();
}