-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathninja_backend.cppm
More file actions
737 lines (658 loc) · 28.1 KB
/
Copy pathninja_backend.cppm
File metadata and controls
737 lines (658 loc) · 28.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
// 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.compile_commands;
import mcpp.dyndep;
import mcpp.toolchain.detect;
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;
}
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";
}
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)
bool has_scanner = mcpp::toolchain::is_gcc(plan.toolchain)
|| !plan.scanDepsPath.empty();
bool dyndep = dyndep_mode_enabled() && has_scanner;
auto traits = mcpp::toolchain::bmi_traits(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;
for (auto& cu : plan.compileUnits) {
if (is_c_source(cu.source)) {
need_c_rule = true;
break;
}
}
append(std::format("cxx = {}\n", escape_ninja_path(flags.cxxBinary)));
append(std::format("cxxflags = {}\n", flags.cxx));
if (need_c_rule) {
append(std::format("cc = {}\n", escape_ninja_path(flags.ccBinary)));
append(std::format("cflags = {}\n", flags.cc));
}
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");
}
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 {} --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.
std::string module_output_flag = traits.needsExplicitModuleOutput
? " -fmodule-output=$bmi_out" : "";
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{} -c $in -o $out\n", module_output_flag));
} 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{} -c $in -o $out && "
"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));
}
append(" description = MOD $out\n");
if (dyndep)
append(" restat = 1\n");
append("\n");
append("rule cxx_object\n");
append(" command = $cxx $local_includes $cxxflags $unit_cxxflags -c $in -o $out\n");
append(" description = OBJ $out\n");
if (dyndep)
append(" restat = 1\n");
append("\n");
if (need_c_rule) {
append("rule c_object\n");
append(" command = $cc $local_includes $cflags $unit_cflags -c $in -o $out\n");
append(" description = CC $out\n");
if (dyndep)
append(" restat = 1\n");
append("\n");
}
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(" command = $ar rcs $out $in\n");
append(" description = AR $out\n\n");
append("rule cxx_shared\n");
append(" command = $cxx -shared $in -o $out $ldflags $unit_ldflags\n");
append(" description = SHARED $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 (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.o";
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("pcm.cache") / "std.compat.pcm";
auto compat_o_dst = std::filesystem::path("obj") / "std.compat.o";
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";
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_c_source(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;
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));
}
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 (rule != "c_object") {
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_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 files don't `import` modules; skip BMI implicit inputs.
if (rule != "c_object") {
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_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);
}
std::string out_line = std::format("build {} : {}{}{}\n",
escape_ninja_path(lu.output), rule, ins,
implicit.empty() ? std::string{} : " |" + implicit);
if (auto flags = join_flags(lu.linkFlags); !flags.empty())
out_line += " unit_ldflags =" + flags + "\n";
append(std::move(out_line));
}
append("\n");
if (!plan.linkUnits.empty()) {
std::string defaults;
for (auto& lu : plan.linkUnits) {
defaults += " " + escape_ninja_path(lu.output);
}
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;
}
// 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;
}
std::string ninjaProgram;
if (!ninjaBin.empty()) {
if constexpr (mcpp::platform::is_windows)
ninjaProgram = ninjaBin.string();
else
ninjaProgram = mcpp::platform::shell::quote(ninjaBin.string());
} else {
ninjaProgram = "ninja";
}
// Record ninja binary for P0 fast-path cache.
BuildResult r;
r.ninjaProgram = ninjaProgram;
if (auto runtimeEnv = runtime_env_for_dirs(plan.toolchain.compilerRuntimeDirs)) {
r.runtimeEnvKey = runtimeEnv->first;
r.runtimeEnvValue = runtimeEnv->second;
} else {
r.runtimeEnvKey = "-";
}
std::string cmd = ninjaProgram;
if (!opts.verbose)
cmd += " --quiet";
cmd += std::format(" -C {}", mcpp::xlings::shq(plan.outputDir.string()));
if (opts.verbose)
cmd += " -v";
if (opts.parallelJobs)
cmd += std::format(" -j{}", opts.parallelJobs);
cmd += " 2>&1";
std::string out;
std::optional<mcpp::platform::env::ScopedEnv> scopedEnv;
if (r.runtimeEnvKey != "-" && !r.runtimeEnvValue.empty())
scopedEnv.emplace(r.runtimeEnvKey, r.runtimeEnvValue);
bool ok = run(cmd, out, /*capture=*/true);
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);
}
} 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>();
}
} // namespace mcpp::build