-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathprepare.cppm
More file actions
6017 lines (5704 loc) · 316 KB
/
Copy pathprepare.cppm
File metadata and controls
6017 lines (5704 loc) · 316 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.prepare — BuildContext + prepare_build: the build-orchestration
// core (workspace -> toolchain -> dependency resolution -> features ->
// modgraph -> fingerprint -> plan -> lockfile).
// Bodies moved verbatim from the CLI layer. Zero behavior change.
module;
#include <cstdio>
#include <cstdlib>
export module mcpp.build.prepare;
import std;
import mcpp.diag;
import mcpp.home;
import mcpp.platform.axis;
import mcpp.libs.json;
import mcpp.log;
import mcpp.manifest;
import mcpp.modgraph.graph;
import mcpp.modgraph.scanner;
import mcpp.modgraph.validate;
import mcpp.toolchain.clang;
import mcpp.toolchain.cppfly;
import mcpp.toolchain.detect;
import mcpp.toolchain.dialect;
import mcpp.toolchain.fingerprint;
import mcpp.toolchain.msvc;
import mcpp.toolchain.registry;
import mcpp.toolchain.stdmod;
import mcpp.toolchain.post_install;
import mcpp.toolchain.abi;
import mcpp.toolchain.triple;
import mcpp.build.plan;
import mcpp.build.cache_key;
import mcpp.build.build_program;
import mcpp.build.directives; // directive table: mark / fold_private_tail
import mcpp.build.tool_store; // #355 host tools: store layout + key + overrides
import mcpp.build.dep_graph; // queries over the resolved edge graph
import mcpp.build.provisions; // #359 build-time provisions: table + propagation
import mcpp.build.resources; // #365 Windows resources: synthesise / scan / find rc
import mcpp.build.backend; // BuildOptions for the tool sub-build
import mcpp.build.ninja; // make_ninja_backend — driving that sub-build
import mcpp.lockfile;
import mcpp.config;
import mcpp.xlings;
import mcpp.xlings.subos_info;
import mcpp.toolchain.post_install;
import mcpp.platform;
import mcpp.fetcher;
import mcpp.fetcher.progress;
import mcpp.pm.resolver;
import mcpp.pm.index_spec;
import mcpp.pm.index_contract;
import mcpp.pm.index_route;
import mcpp.pm.index_refresh;
import mcpp.pm.mangle;
import mcpp.pm.compat;
import mcpp.pm.dep_spec;
import mcpp.pm.lock_io;
import mcpp.version_req;
import mcpp.ui;
import mcpp.log;
import mcpp.fallback.install_integrity;
import mcpp.bmi_cache;
import mcpp.project;
namespace mcpp::build {
// mcpp#237: surface xpkg-descriptor mcpp-segment keys this mcpp did not
// recognise. The parser collects them into `xpkgUnknownKeys` and skips the
// value; without this a typo like `dependencies = {...}` (correct key: `deps`)
// dropped the dependency with no diagnostic. Called at the descriptor-adoption
// sites (a fetched dep with no mcpp.toml, synthesized from the index `mcpp={}`
// block) — the single place the descriptor becomes a build input. Warning (not
// hard error) keeps forward-compat: an older mcpp building a newer descriptor
// should not fail outright, only tell the user what it ignored.
inline void warn_unknown_xpkg_keys(const mcpp::manifest::Manifest& dm,
std::string_view depLabel) {
for (auto const& key : dm.xpkgUnknownKeys) {
auto suggestion = mcpp::manifest::closest_known_xpkg_key(key);
if (suggestion.empty())
mcpp::ui::warning(std::format(
"dependency '{}': unknown mcpp-segment key '{}' in its xpkg "
"descriptor — ignored (schema mismatch or typo)", depLabel, key));
else
mcpp::ui::warning(std::format(
"dependency '{}': unknown mcpp-segment key '{}' in its xpkg "
"descriptor — ignored; did you mean '{}'?", depLabel, key, suggestion));
}
}
// ── L1 platform-conditional config: cfg() predicate evaluation ──────────────
// Context = the RESOLVED target's coordinates. A `[target.'cfg(...)'.build]`
// predicate is evaluated against this (target triple for a cross build, host
// for a native build), so conditional flags follow what the binary will run on
// — not the build host. See the manifest design doc.
namespace cfgpred {
struct Ctx { std::string os, arch, family, env; };
// Derive the cfg context from the resolved --target triple, falling back to
// the host for a native build. Parsing goes through triple.cppm — the single
// triple parser — so the cfg vocabulary IS the canonical triple vocabulary
// (os: linux|macos|windows, arch: GNU spellings, env: gnu|musl|msvc), and
// alias spellings ("x86_64-w64-mingw32") evaluate identically to canonical.
inline Ctx context_for(std::string_view targetTriple) {
namespace triple = mcpp::toolchain::triple;
Ctx c;
auto t = targetTriple.empty()
? std::optional<triple::Triple>(triple::host_triple())
: triple::parse(targetTriple);
if (t) {
c.os = t->os;
c.arch = t->arch;
c.env = t->env;
c.family = t->family();
} else {
// Escape-hatch triple outside the language: only the leading arch
// segment is derivable; other dimensions stay empty (never match).
auto dash = targetTriple.find('-');
c.arch = std::string(dash == std::string_view::npos ? targetTriple
: targetTriple.substr(0, dash));
}
return c;
}
// Recursive-descent evaluator over the inside of `cfg(...)`:
// expr := all(list) | any(list) | not(expr) | key="value" | bareword
// key ∈ {os, arch, family, env} bareword ∈ {windows, unix, linux, macos}
struct Parser {
std::string_view s; std::size_t i = 0; const Ctx& c;
void ws() { while (i < s.size() && std::isspace((unsigned char)s[i])) ++i; }
bool eat(char ch) { ws(); if (i < s.size() && s[i] == ch) { ++i; return true; } return false; }
std::string ident() {
ws(); std::size_t b = i;
while (i < s.size() && (std::isalnum((unsigned char)s[i]) || s[i] == '_')) ++i;
return std::string(s.substr(b, i - b));
}
std::string str() {
ws(); if (i >= s.size() || s[i] != '"') return {};
++i; std::size_t b = i; while (i < s.size() && s[i] != '"') ++i;
auto v = std::string(s.substr(b, i - b)); if (i < s.size()) ++i; return v;
}
bool match_alias(const std::string& a) {
if (a == "windows") return c.os == "windows";
if (a == "linux") return c.os == "linux";
if (a == "macos") return c.os == "macos";
if (a == "unix") return c.family == "unix";
return false; // unknown bareword → no match
}
bool match_kv(const std::string& k, const std::string& v) {
if (k == "os") return c.os == v;
if (k == "arch") return c.arch == v;
if (k == "family") return c.family == v;
if (k == "env") return c.env == v;
return false;
}
bool expr() {
std::string id = ident();
if (id == "all" || id == "any") {
eat('(');
bool acc = (id == "all");
ws();
if (!(i < s.size() && s[i] == ')')) {
do { bool r = expr(); acc = (id == "all") ? (acc && r) : (acc || r); }
while (eat(','));
}
eat(')');
return acc;
}
if (id == "not") { eat('('); bool r = expr(); eat(')'); return !r; }
ws();
if (i < s.size() && s[i] == '=') { ++i; return match_kv(id, str()); }
return match_alias(id);
}
};
// Evaluate a `[target.<predicate>]` key. Returns the cfg() result, or — for a
// non-cfg key (a bare triple) — an exact match against the resolved triple.
inline bool matches(const std::string& predicate, const Ctx& c, std::string_view triple) {
std::string_view k = predicate;
if (k.starts_with("cfg(") && k.ends_with(")")) {
Parser p{ k.substr(4, k.size() - 5), 0, c };
return p.expr();
}
// Bare OS/family alias sugar: `[target.linux]` ≡ `[target.'cfg(linux)']`.
// These aliases are never valid triples (no dash), so there is no ambiguity
// with the exact-triple namespace. Evaluated as the cfg bareword.
if (predicate == "windows" || predicate == "linux" ||
predicate == "macos" || predicate == "unix") {
Parser p{ predicate, 0, c };
return p.expr();
}
// Bare-triple match, spelling-independent: a `[target.x86_64-w64-mingw32]`
// key matches a resolved `x86_64-windows-gnu` build (and vice versa) —
// both normalize through triple::parse. Unparseable keys (the explicit-
// section escape hatch) fall back to exact string comparison.
if (triple.empty()) return false;
if (auto p = mcpp::toolchain::triple::parse(predicate)) {
if (auto rt = mcpp::toolchain::triple::parse(triple))
return p->str() == rt->str();
}
return predicate == triple;
}
} // namespace cfgpred
export std::filesystem::path target_dir(const mcpp::toolchain::Toolchain& tc,
const mcpp::toolchain::Fingerprint& fp,
const std::filesystem::path& root)
{
// Canonical triple names the output directory (D1: `target/
// x86_64-windows-gnu/`, not the GNU spelling the compiler reports via
// -dumpmachine) — alias inputs land in the same directory. Triples
// outside the language keep their raw spelling.
auto triple = tc.targetTriple.empty() ? std::string{"unknown"} : tc.targetTriple;
if (auto t = mcpp::toolchain::triple::parse(triple)) triple = t->str();
return root / "target" / triple / fp.hex;
}
// Compose a stable canonical compile-flags string for fingerprinting.
// Exported so the "every build-variant knob is in here" invariant is machine-
// checkable: the profile knobs were absent for a long time precisely because
// nothing could assert on this string.
export std::string canonical_compile_flags(const mcpp::manifest::Manifest& m) {
std::string s;
s += "-std="; s += m.package.standard;
s += " -fmodules";
// macOS deployment target changes the effective compile triple
// (arm64-apple-macosxNN) — a std.pcm built for one target cannot be
// loaded by a TU compiled for another. Fold the resolved value
// (env override > [build] macos_deployment_target manifest default)
// into the fingerprint so switching targets rebuilds the BMI cache
// instead of dying with a module config mismatch.
//
// The built-in default floor (rustc-style) lives in the single
// resolver (platform::macos::deployment_target), so this rule, the
// flags and the std-module prebuild always agree — the 0.0.50-era
// attempt to inject a default here alone left the test build's
// std.pcm unstaged (import std failed wholesale on macos CI).
if constexpr (mcpp::platform::is_macos) {
auto dtv = mcpp::platform::macos::deployment_target(
m.buildConfig.macosDeploymentTarget);
if (!dtv.empty()) {
s += " macos_deployment_target=";
s += dtv;
}
}
if (!m.buildConfig.cStandard.empty()) {
s += " c_standard=";
s += m.buildConfig.cStandard;
}
for (auto const& flag : m.buildConfig.cflags) {
s += " cflag:";
s += flag;
}
for (auto const& flag : m.buildConfig.cxxflags) {
s += " cxxflag:";
s += flag;
}
// Explicit [build] dialect_cxxflags (auto-promoted ones are already in
// cxxflags above) — they change every BMI in the graph.
for (auto const& flag : m.buildConfig.dialectCxxflags) {
s += " dialect:";
s += flag;
}
for (auto const& flag : m.buildConfig.ldflags) {
s += " ldflag:";
s += flag;
}
// Per-glob flags (G4): full ordered serialization — glob + every list —
// so editing any entry (or reordering) re-fingerprints the output dir.
for (auto const& gf : m.buildConfig.globFlags) {
s += " globflags:"; s += gf.glob;
for (auto const& f : gf.cflags) { s += " gc:"; s += f; }
for (auto const& f : gf.cxxflags) { s += " gxx:"; s += f; }
for (auto const& f : gf.asmflags) { s += " gas:"; s += f; }
for (auto const& f : gf.defines) { s += " gd:"; s += f; }
}
// The resolved [profile] knobs. These are NOT in cflags/cxxflags: the
// profile block (see the profile resolution below) lands them in
// buildConfig.optLevel/debug/lto/strip and flags.cppm turns them into
// -O<n>/-g/-flto at command-construction time. Leaving them out made
// `--dev`, `--release` and `--profile dist` share ONE fingerprint, hence
// one target/<triple>/<fp>/ directory AND one global cache entry — so a
// release build could be served -O0 -g dependency objects. They are
// build-variant by definition; they belong here.
s += " opt="; s += m.buildConfig.optLevel;
s += " debug="; s += m.buildConfig.debug ? "1" : "0";
s += " lto="; s += m.buildConfig.lto ? "1" : "0";
s += " strip="; s += m.buildConfig.strip ? "1" : "0";
return s;
}
std::string canonical_package_build_metadata(
const std::vector<mcpp::modgraph::PackageRoot>& packages)
{
std::string s;
for (auto const& pkg : packages) {
s += "\npackage:";
s += pkg.manifest.package.namespace_;
s += "/";
s += pkg.manifest.package.name;
s += "@";
s += pkg.manifest.package.version;
if (!pkg.manifest.buildConfig.cStandard.empty()) {
s += " c_standard=";
s += pkg.manifest.buildConfig.cStandard;
}
for (auto const& flag : pkg.manifest.buildConfig.cflags) {
s += " cflag:";
s += flag;
}
for (auto const& flag : pkg.manifest.buildConfig.cxxflags) {
s += " cxxflag:";
s += flag;
}
for (auto const& flag : pkg.manifest.buildConfig.ldflags) {
s += " ldflag:";
s += flag;
}
// Per-glob flags — same full ordered serialization as the root-side
// block above. Until #253 dependency globFlags were unfingerprinted
// (held only by "descriptor frozen per version" + "feature toggles
// always change cflags via -DMCPP_FEATURE_*"); feature-folded entries
// make the vector build-variant, so fingerprint it directly.
// featureOrigin is diagnostic-only and deliberately NOT serialized
// (the active feature set is already in cflags above).
for (auto const& gf : pkg.manifest.buildConfig.globFlags) {
s += " globflags:"; s += gf.glob;
for (auto const& f : gf.cflags) { s += " gc:"; s += f; }
for (auto const& f : gf.cxxflags) { s += " gxx:"; s += f; }
for (auto const& f : gf.asmflags) { s += " gas:"; s += f; }
for (auto const& f : gf.defines) { s += " gd:"; s += f; }
}
if (pkg.usageResolved) {
for (auto const& dir : pkg.privateBuild.includeDirs) {
s += " private_include:";
s += dir.generic_string();
}
for (auto const& dir : pkg.publicUsage.includeDirs) {
s += " public_include:";
s += dir.generic_string();
}
for (auto const& dir : pkg.privateBuild.includeDirsAfter) {
s += " private_include_after:";
s += dir.generic_string();
}
for (auto const& dir : pkg.publicUsage.includeDirsAfter) {
s += " public_include_after:";
s += dir.generic_string();
}
}
for (auto const& [path, content] : pkg.manifest.buildConfig.generatedFiles) {
s += " genfile:";
s += path.generic_string();
s += "=";
s += content;
}
}
return s;
}
std::expected<void, std::string>
materialize_generated_files(const std::filesystem::path& root,
const mcpp::manifest::Manifest& manifest)
{
for (auto const& [relPath, content] : manifest.buildConfig.generatedFiles) {
if (relPath.empty()) {
return std::unexpected("generated_files contains an empty path");
}
if (relPath.is_absolute()) {
return std::unexpected(std::format(
"generated_files path '{}' must be relative", relPath.generic_string()));
}
auto const genericPath = relPath.generic_string();
for (std::size_t begin = 0; begin <= genericPath.size();) {
auto const end = genericPath.find('/', begin);
auto const part = genericPath.substr(begin, end == std::string::npos
? std::string::npos
: end - begin);
if (part == "..") {
return std::unexpected(std::format(
"generated_files path '{}' must not escape the package root",
relPath.generic_string()));
}
if (end == std::string::npos) {
break;
}
begin = end + 1;
}
auto out = root / relPath.lexically_normal();
std::error_code ec;
std::filesystem::create_directories(out.parent_path(), ec);
if (ec) {
return std::unexpected(std::format(
"cannot create directory for generated file '{}': {}",
out.string(), ec.message()));
}
// Skip the write when the on-disk content is already identical: ninja
// is mtime-driven, and an unconditional rewrite bumps the mtime every
// build, recompiling every TU that #includes the materialized file
// (via depfiles) — e.g. a frozen-snapshot config.h included by
// thousands of TUs. Change detection is already owned by the
// fingerprint (content is folded in above), so skipping only
// preserves the mtime — mirroring the build.mcpp cache design,
// which likewise avoids mtime churn on unchanged outputs.
{
std::ifstream is(out, std::ios::binary);
if (is) {
std::string existing((std::istreambuf_iterator<char>(is)),
std::istreambuf_iterator<char>());
if (is && existing == content) {
continue;
}
}
}
std::ofstream os(out, std::ios::binary);
if (!os) {
return std::unexpected(std::format(
"cannot write generated file '{}'", out.string()));
}
os << content;
if (!os) {
return std::unexpected(std::format(
"failed while writing generated file '{}'", out.string()));
}
}
return {};
}
// L1 cfg merge for ONE package's manifest (root or ANY dependency — path,
// git, or version/registry): append the matching conditional
// cflags/cxxflags/ldflags and sources (G1b) to its buildConfig. Sources also
// update the legacy modules.sources mirror — the scanner walks that.
//
// #229: this is the SINGLE funnel for cfg-conditional sources/flags — every
// package's manifest passes through exactly one call to this function,
// always immediately BEFORE that manifest is captured into `packages[]` via
// makePackageRoot()/propagateLinkFlags() (which snapshot buildConfig into
// privateBuild/linkUsage and into the root's propagated ldflags — merging
// any later than that point is silently lost for flags, though not for
// sources, which the modgraph scan re-reads live). Three call sites, one per
// loading branch, together cover every package exactly once: the root
// (before its own makePackageRoot), the path/git-dep branch, and
// loadVersionDep() (shared by the main per-dependency loop, the
// multi-version mangling secondary, and the SemVer-merge re-fetch — all three
// of ITS callers get the merge for free from the one call inside it).
// The dependency MAPS ride the same funnel (#359). They used to be merged by
// a hand-written loop at the root call site only, with a comment declaring a
// dependency's own conditional deps "out of scope". That was the #229 shape
// one level up: three call sites merged build inputs, ONE of them also merged
// deps, and nothing said why. A package's `[target.windows.dependencies]` is
// its own statement about itself and means the same thing whether the package
// is the root or someone's dependency.
void merge_conditional_config(mcpp::manifest::Manifest& m,
const cfgpred::Ctx& ctx,
std::string_view targetTriple)
{
for (auto const& cc : m.conditionalConfigs) {
if (!cfgpred::matches(cc.predicate, ctx, targetTriple)) continue;
// One append() for every field the axis may carry (#258). Matching
// sections land AFTER the base entries, so a conditional rule beats
// a broader unconditional one under GNU last-wins — which is what
// makes an off-OS REMOVAL expressible (`-U` after the base `-D`).
mcpp::manifest::append(m.buildConfig, cc.inputs);
// `modules.sources` is the scanner's own view and is not part of
// BuildInputs, so conditional sources are mirrored into it here.
for (auto const& s : cc.inputs.sources)
m.modules.sources.push_back(s);
// insert() keeps an existing unconditional entry: a conditional
// section adds a dependency, it never silently overrides one.
m.dependencies.insert(cc.dependencies.begin(), cc.dependencies.end());
m.devDependencies.insert(cc.devDependencies.begin(), cc.devDependencies.end());
m.buildDependencies.insert(cc.buildDependencies.begin(),
cc.buildDependencies.end());
// #359: `[target.<sel>.feature-deps.<feature>]`. The feature is
// registered by the parser regardless of the predicate; only what it
// pulls in is conditional.
for (auto const& [fname, deps] : cc.featureDeps) {
auto& dst = m.featureDeps[fname];
dst.insert(deps.begin(), deps.end());
}
}
}
// Desugar `[build].defines` into `-D<x>` on both C and C++ flag channels.
//
// ORDER (both halves are load-bearing): this must run AFTER
// merge_conditional_config — `defines` is a BuildInputs member, so a
// matching `[target.'cfg(...)'.build] defines` has been appended by then and
// folds in the same pass, landing after the unconditional entries so GNU
// last-wins gives the conditional rule precedence — and BEFORE the manifest is
// snapshotted into packages[] / fingerprinted, because that snapshot (not the
// manifest) is what the P1689 scan, the compile edges and compute_fingerprint
// actually read.
//
// Idempotent: clearing the vector after folding makes repeated calls harmless.
// Both `cflags` and `cxxflags` get the macro; assembly units pick it up for
// free via the -D/-U/-I subset the ninja backend filters out of packageCflags.
void fold_build_defines_into_flags(mcpp::manifest::BuildConfig& bc) {
for (auto const& d : bc.defines) {
bc.cflags.push_back("-D" + d);
bc.cxxflags.push_back("-D" + d);
}
bc.defines.clear();
}
// Feature-activation closure — THE single implementation (build.mcpp env
// contract, Stage 2a feature-deps, and the main feature pass all call this):
// seed = [features].default ∪ requested, expanded transitively over implies;
// the literal name "default" is never itself a feature.
//
// `seedDefault` is the funnel for consumer-side `default-features = false`
// (#242, Cargo parity): when false the dependency's own `[features].default`
// is NOT seeded, so only the explicitly `requested` features (and their
// transitive `implies`) activate. The root package always seeds its own
// default (seedDefault=true); a dependency passes its dep spec's
// `defaultFeatures` flag. `requested` is applied identically either way.
std::vector<std::string> feature_closure(const mcpp::manifest::Manifest& pm,
const std::vector<std::string>& requested,
bool seedDefault = true)
{
std::vector<std::string> act, q;
if (seedDefault)
if (auto it = pm.featuresMap.find("default"); it != pm.featuresMap.end())
q.insert(q.end(), it->second.begin(), it->second.end());
q.insert(q.end(), requested.begin(), requested.end());
std::set<std::string> seen;
while (!q.empty()) {
auto f = q.back(); q.pop_back();
if (f == "default" || !seen.insert(f).second) continue;
act.push_back(f);
if (auto it = pm.featuresMap.find(f); it != pm.featuresMap.end())
q.insert(q.end(), it->second.begin(), it->second.end());
}
return act;
}
// --features value → tokens (comma/space separated).
std::vector<std::string> parse_feature_request(std::string_view s) {
std::vector<std::string> out;
for (std::size_t p = 0; p < s.size();) {
auto c = s.find_first_of(", ", p);
auto tok = s.substr(p, c == std::string_view::npos ? std::string_view::npos : c - p);
if (!tok.empty()) out.emplace_back(tok);
if (c == std::string_view::npos) break;
p = c + 1;
}
return out;
}
bool is_std_module(std::string_view name) {
return name == "std" || name == "std.compat";
}
std::string trim_copy(std::string s) {
while (!s.empty() && std::isspace(static_cast<unsigned char>(s.front())))
s.erase(0, 1);
while (!s.empty() && std::isspace(static_cast<unsigned char>(s.back())))
s.pop_back();
return s;
}
bool source_file_imports_std(const std::filesystem::path& path) {
std::ifstream is(path);
if (!is) return false;
std::string line;
while (std::getline(is, line)) {
line = trim_copy(std::move(line));
std::size_t i = std::string::npos;
if (line.starts_with("import ")) {
i = 7;
} else if (line.starts_with("export import ")) {
i = 14;
}
if (i == std::string::npos) continue;
while (i < line.size() && std::isspace(static_cast<unsigned char>(line[i])))
++i;
std::string name;
while (i < line.size()
&& (std::isalnum(static_cast<unsigned char>(line[i]))
|| line[i] == '_' || line[i] == '.' || line[i] == ':')) {
name.push_back(line[i]);
++i;
}
if (is_std_module(name)) return true;
}
return false;
}
bool graph_or_targets_import_std(const mcpp::modgraph::Graph& graph,
const mcpp::manifest::Manifest& manifest,
const std::filesystem::path& projectRoot) {
for (auto& u : graph.units) {
for (auto& req : u.requires_) {
if (is_std_module(req.logicalName))
return true;
}
}
// Some target entry files can be added to the plan after the package scan.
// Check them here so std BMI setup matches what make_plan will compile.
for (auto& t : manifest.targets) {
if (!t.main.empty() && source_file_imports_std(projectRoot / t.main))
return true;
}
return false;
}
// How this invocation may use the global dependency cache.
//
// Global read + write (default)
// Local neither — every dependency is compiled inside this project's
// target/, which is what every build did before the cache worked
// Off neither, and this build's target/<triple>/<fp>/ directory is
// cleared first (a full cold rebuild). Sibling build dirs — other
// profiles, other targets — are left alone.
//
// `--no-cache` used to be the only switch and it meant "clear the build dir",
// which says nothing about a cache (and its help text claimed all of target/);
// it stays as a deprecated alias for Off.
// Where the resolved toolchain spec came from.
//
// This exists so mcpp can tell its own guesses apart from the user's
// instructions. When a resolved toolchain turns out to be unusable on this
// machine (the motivating case: a Windows default that targets the MSVC ABI
// on a box with no Visual Studio), mcpp may quietly revise a default it
// picked itself — but a spec the user wrote into mcpp.toml must produce an
// error instead. A project that needs the MSVC ABI to link vcpkg-built .lib
// files is worse off with a silent ABI swap than with a failed build.
//
// Deliberately derived from the two config layers that already exist rather
// than persisted: no new field, nothing to keep in sync on disk.
export enum class TcOrigin {
None, // nothing resolved yet
ManifestToolchain, // mcpp.toml [toolchain] — user explicit
TargetSection, // mcpp.toml [target.X].toolchain — user explicit
GlobalDefault, // config.toml [toolchain] default — mcpp's own default
TargetPin, // triple.cppm vocabulary convention
FirstRun, // chosen and persisted by this very invocation
};
export inline bool tc_origin_is_user_explicit(TcOrigin o) {
return o == TcOrigin::ManifestToolchain || o == TcOrigin::TargetSection;
}
// What to tell a user whose build targets the MSVC ABI on a machine that
// cannot serve it. Two shapes, because the two states need different fixes:
//
// • cl.exe was found but the Windows SDK was not — a half-installed VS.
// Point at the missing SDK component; switching toolchains would be an
// over-correction for someone who clearly wants MSVC.
// • nothing usable at all — the bare-Windows case. Lead with the MinGW-w64
// route, which needs no Visual Studio and is already a verified target,
// and keep the "install the C++ workload" option second.
export std::string msvc_unavailable_guidance(const mcpp::toolchain::Toolchain& tc) {
namespace pins = mcpp::toolchain::triple::pins;
const bool haveVcTools = tc.compiler == mcpp::toolchain::CompilerId::MSVC;
if (haveVcTools && mcpp::toolchain::msvc::find_msvc_tools_dir()) {
return std::format(
"msvc {} was detected at {}, but no Windows SDK was found —\n"
" cl.exe cannot compile without the UCRT/SDK headers.\n"
" Install the 'Windows 11 SDK' component via the Visual Studio\n"
" Installer (it is part of the Desktop development with C++\n"
" workload), then retry.",
tc.version, tc.binaryPath.string());
}
return std::format(
"this build targets the MSVC ABI, which needs Visual Studio /\n"
" Build Tools (MSVC STL + Windows SDK) — neither was found.\n"
"\n"
" No Visual Studio? Use the self-contained MinGW-w64 toolchain\n"
" (no Visual Studio required, `import std` works):\n"
" mcpp toolchain default {} --target {}\n"
"\n"
" Have Visual Studio? Install the 'Desktop development with C++'\n"
" workload — it provides the MSVC STL and the Windows SDK.",
pins::kSuggestGccMingw, pins::kFirstRunWinGnuTarget);
}
export enum class CacheMode { Global, Local, Off };
export std::optional<CacheMode> parse_cache_mode(std::string_view v) {
if (v == "global") return CacheMode::Global;
if (v == "local") return CacheMode::Local;
if (v == "off" || v == "none") return CacheMode::Off;
return std::nullopt;
}
export std::string_view cache_mode_name(CacheMode m) {
switch (m) {
case CacheMode::Local: return "local";
case CacheMode::Off: return "off";
default: return "global";
}
}
export struct BuildContext {
// --strict: degradations reported through mcpp::diag become errors.
// Carried on the context because the build's degradations are discovered
// during backend emission, i.e. after prepare_build has returned — the
// single place that settles the policy is run_build_plan (execute.cppm).
bool strict = false;
mcpp::manifest::Manifest manifest;
mcpp::toolchain::Toolchain tc;
mcpp::toolchain::Fingerprint fp;
std::filesystem::path projectRoot;
std::filesystem::path outputDir;
std::filesystem::path stdBmi;
std::filesystem::path stdObject;
mcpp::build::BuildPlan plan;
// Resolved profile name (resolve_profile_name). Carried so run_build_plan
// can record it in .build_cache — without it the fast path cannot tell
// whether a cached build.ninja was generated for the profile being asked
// for — and so `Finished <profile>` stops being a hardcoded "release".
std::string profile;
// Resolved global-cache mode. Read side is honored in prepare_build; write
// side in run_build_plan.
CacheMode cacheMode = CacheMode::Global;
// M3.2 BMI cache: deps that did NOT hit cache and therefore need
// populate_from(...) AFTER backend.build succeeds.
struct CacheTask {
mcpp::bmi_cache::CacheKey key;
mcpp::bmi_cache::DepArtifacts artifacts;
};
std::vector<CacheTask> depsToPopulate;
// Deps that DID hit the global cache, and how many compile units each one
// spared. run_build_plan reports the count so the "Cached" line cannot be
// true-looking and empty at the same time.
struct CachedDep {
std::string name;
std::string version;
std::size_t units = 0;
};
std::vector<CachedDep> cachedDeps;
// What the dependency walk actually RESOLVED, keyed by the root manifest's
// dependency map key. The "Compiling <dep> v<version>" banner used to read
// `manifest.dependencies[...].version` — the constraint as authored — so a
// caret dep announced itself as `v^1.92.8` (mcpp#363). The resolution result
// already existed inside prepare_build; the banner and mcpp.lock were simply
// reading the input instead of the output. Both now read this.
std::map<std::string, std::string> resolvedVersions;
};
// The ONE cache-mode resolver, for the same reason resolve_profile_name exists:
// execute.cppm's fast paths deliberately skip prepare_build, so they need to
// settle the mode from the same rule. Pure in (manifest, override, environment).
//
// `--cache` on the command line already bypasses the fast path, so the override
// argument is empty there; it is threaded anyway so there is exactly one place
// where precedence is written down.
//
// Precedence: --cache > MCPP_BUILD_CACHE > [build] cache > global. An
// unparseable value falls through to the next source rather than silently
// meaning "global" — see prepare_build, which also reports it.
export CacheMode resolve_cache_mode(const mcpp::manifest::Manifest& m,
std::string_view override_mode) {
if (auto v = parse_cache_mode(override_mode)) return *v;
if (const char* e = std::getenv("MCPP_BUILD_CACHE"); e && *e)
if (auto v = parse_cache_mode(e)) return *v;
if (auto v = parse_cache_mode(m.buildConfig.cacheMode)) return *v;
return CacheMode::Global;
}
// The ONE profile-name resolver. Shared with execute.cppm's fast paths:
// they deliberately skip prepare_build, so before this existed they had no
// idea which profile the request meant — and `.build_cache` keyed entries by
// target triple alone. Net effect: `mcpp build --release` followed by a bare
// `mcpp build` reported success in 0.00s and left the RELEASE artifacts in
// place. The rule is pure (manifest + one override string), so both sides can
// evaluate it without resolving a toolchain or scanning the module graph.
//
// Precedence: --profile/--release/--dev > [build].default-profile > "dev".
// The global default is "dev" (-O0 -g) per the dominant convention
// (Cargo/Meson/CMake/Zig/Bazel/MSBuild all default to debug).
export std::string resolve_profile_name(const mcpp::manifest::Manifest& m,
std::string_view override_name) {
if (!override_name.empty()) return std::string(override_name);
if (!m.buildConfig.defaultProfile.empty()) return m.buildConfig.defaultProfile;
return "dev";
}
// Command-level overrides (--target / --static).
// Empty defaults preserve pre-existing behaviour exactly.
export struct BuildOverrides {
// Where the package being built LIVES (its mcpp.toml). Empty = walk up from
// the process cwd, which is what every user-facing invocation does. Set by
// the tool-provisioning pass, which builds a package that lives in the
// registry rather than under the cwd.
std::filesystem::path project_root;
// Where mcpp WRITES. Empty = the project root, which is the historical
// (and for a normal build, correct) behaviour.
//
// The two are separate because a registry package root is shared across
// projects and may be read-only — build_program.cppm has said so in a
// comment since G2, and until now nothing could honour it for anything
// bigger than build.mcpp's own scratch dir. Splitting "source" from "work"
// is what lets mcpp build such a package at all.
//
// EVERYTHING derived from it moves together: target/, mcpp.lock,
// compile_commands.json, .mcpp/, and build.mcpp's artifact dir. Moving
// only some would be worse than moving none — a half-redirected build
// writes into the shared root anyway, just less visibly.
std::filesystem::path work_dir;
// #355 tool provisioning re-enters prepare_build for the tool package. A
// tool package's own build.mcpp may legitimately want another tool (gRPC's
// wants protoc), so the depth cannot be 1 — but an unbounded chain is a
// bug, and hanging is a worse diagnostic than a named cycle.
int tool_depth = 0;
// The request chain, for that diagnostic. "root → grpc:grpc_cpp_plugin → …"
std::string tool_chain;
// Use THIS manifest instead of reading `<project_root>/mcpp.toml`.
//
// Required for a `compat`-style registry package (Form B), which ships no
// mcpp.toml at all — its manifest is synthesized from the `.lua`
// descriptor during resolution. Without this the tool sub-build could only
// ever handle packages that carry their own manifest (Form A), which
// excludes most of the index, protobuf among them.
//
// Must be the PRISTINE manifest, before feature activation: the sub-build
// activates its own feature set, and starting from an already-activated
// copy would fold the same feature sources in twice.
// A shared_ptr rather than an optional<Manifest>: BuildOverrides is an
// EXPORTED struct, and embedding a large value type in the module
// interface made GCC fail to write the cluster at all
// ('failed to read compiled module cluster ...: Bad file data' when
// mcpp.build.execute imported it). A pointer keeps the exported layout
// trivial, and it also avoids copying the manifest per tool build.
std::shared_ptr<const mcpp::manifest::Manifest> preloaded_manifest;
std::string target_triple; // empty = host triple, fall through to [toolchain]
bool force_static = false; // --static (or implied by musl target)
std::string package_filter; // -p <name>: only build this workspace member
std::string profile; // --profile <name> (default "release")
std::string features; // --features a,b,c (root package activation)
bool strict = false; // --strict: schema warnings become errors
std::string capabilities; // --cap blas=openblas,lapack=mkl (provider pins)
std::string cache_mode; // --cache global|local|off ("" = unset)
};
// ── git dependency helpers ──────────────────────────────────────────────────
// Is this git remote reachable without a network round-trip?
//
// `--offline` means "never touch the network" (docs/05-mcpp-toml.md), and its
// standing promise is that anything already on disk still builds. A remote that
// names a local directory — or a file:// URL — is served by plain filesystem
// reads, so refusing it would break that promise without buying any isolation.
// The dependency-download gate further down draws the same line.
//
// Recognising a scheme (`https://`, `ssh://`, `git://`) or scp-like syntax
// (`git@host:path`) as remote first keeps a Windows drive letter (`C:\repo`,
// which contains a colon but no `@`) on the local side.
bool is_local_git_remote(std::string_view url) {
if (url.starts_with("file://")) return true;
if (url.contains("://")) return false;
if (url.contains('@') && url.contains(':')) return false;
std::error_code ec;
return std::filesystem::exists(std::filesystem::path(url), ec);
}
// The commit a cached clone is actually parked on, or "" if it cannot be read.
//
// Used to detect a clone that was interrupted between `git clone` and
// `git checkout` — the directory exists and looks like a repository, but sits
// on the wrong commit. Only meaningful when the expected revision is a sha,
// i.e. for branch deps after resolution.
//
// stderr is folded in so a git warning cannot leak to the user's terminal;
// the last line is taken so such a warning cannot corrupt the sha either.
std::string git_cache_head(const std::filesystem::path& gitRoot) {
auto r = mcpp::platform::process::capture(std::format(
"git -C {} rev-parse HEAD 2>&1",
mcpp::platform::shell::quote(gitRoot.string())));
if (r.exit_code != 0) return {};
std::string out = r.output;
while (!out.empty() && (out.back() == '\n' || out.back() == '\r'
|| out.back() == ' ' || out.back() == '\t'))
out.pop_back();
if (auto nl = out.find_last_of("\r\n"); nl != std::string::npos)
out.erase(0, nl + 1);
return out;
}
// `prepare_build` builds the BuildContext for any verb that compiles.
// includeDevDeps: when true, dev-dependencies are also fetched + scanned
// into the modgraph. mcpp test passes true; build/run pass false.
// extraTargets: additional Target entries (e.g. synthetic test targets)
// appended to the manifest before the modgraph runs.
// overrides: --target / --static.
namespace {
// A dependency that "cannot be found" while an index is unreadable is almost
// never missing — it is unreachable, and the two need different actions from
// the user (publish it vs upgrade mcpp). The floor error is printed when the
// index is first opened, which can be hundreds of lines earlier; the message
// that STOPS the build has to carry the cause, because that is the one a user
// reads. See mcpp::pm::unusable_index_hint.
std::string with_index_cause(std::string msg) {
if (auto hint = mcpp::pm::unusable_index_hint(); !hint.empty())
msg += "\n" + hint;
return msg;
}
// The runtime this build targets, in xlings's own spelling ("glibc@2.39").
//
// A degradation chain with every step explicit, and deliberately NO final
// "otherwise pick something". Payload resolution declines without an
// authority, because the guess it used to make is what let the compile side
// and the artifact's interpreter name different glibc versions -- invisibly,
// until the binary met a library built against the other one.
//
// 1. [xlings] subos -> that subos's subos_info.runtime
// 2. the active subos's subos_info.runtime
// 3. "" -- no authority, therefore no PayloadFirst
//
// `compilerBin` may be empty on the first call: the compiler has not been
// probed yet, and an inherited toolchain resolves its subos from its OWNER
// home. The caller re-resolves once it knows where the compiler is.
std::string resolve_runtime_binding(const mcpp::manifest::Manifest& m,
const std::filesystem::path& compilerBin) {
auto runtime_of = [](const std::filesystem::path& dir) -> std::string {
return mcpp::xlings::subos::read(dir).runtime;
};
// A declaration can only be honoured while the payload it names is still
// installed. Subos descriptions are written once and the payloads beneath
// them are replaced independently -- upgraded, garbage-collected -- so a
// subos can go on saying `glibc@2.39` on a machine that now has only 2.44.
//
// Taking that at face value is not conservative, it is worse than any
// substitution: the exact-match probe finds nothing, no loader reaches the
// link line, and the artifact ends up on the HOST loader -- outside the
// sandbox entirely. Measured on CI, three rounds running.
//
// So a declaration naming an absent payload is passed over rather than
// returned, and resolution carries on to something that can be honoured.
auto usable = [&](const std::string& binding) {
if (binding.empty()) return false;
if (compilerBin.empty()) return true; // cannot check yet; caller re-asks
if (mcpp::toolchain::probe_payload_paths(compilerBin, binding))
return true;
mcpp::log::verbose("probe", std::format(
"subos declares runtime {}, but that payload is not installed here "
"— looking for one that is", binding));
return false;
};
if (auto active = mcpp::xlings::paths::subos_dir_of(compilerBin)) {
// 1 — the project names a subos; it is a sibling of the active one.
if (!m.xlings.subos.empty()) {
auto named = active->parent_path() / m.xlings.subos;
if (auto r = runtime_of(named); usable(r)) return r;
}
// 2 — whatever is active.
if (auto r = runtime_of(*active); usable(r)) return r;
}
// 3 — COMPATIBILITY: the value this toolchain already has baked in.
//
// A subos created before xlings grew `subos_info` cannot answer, and that
// is the state of every machine installed before 2026.8.5.1 -- including
// mcpp's own sandbox, whose vendored xlings is never upgraded. Refusing
// there would break every existing user, so the toolchain's own baked
// value stands in.
//
// This is NOT the guess this design removed. The guess picked a version by
// directory order, unrelated to what the artifact would load. This reads
// the value the artifact WILL use -- gcc's specs, clang's cfg -- so the
// invariant that matters, compile side == run side, still holds. It is a
// migration path, and it goes away on its own: once the subos describes
// itself, step 1 or 2 answers first.
if (!compilerBin.empty()) {
if (auto r = mcpp::toolchain::baked_runtime_binding(compilerBin);
!r.empty()) {
mcpp::log::verbose("probe", std::format(
"subos does not describe itself; using the runtime this "
"toolchain was installed against ({}). `xlings self update` "
"and a fresh subos make this authoritative", r));
return r;
}
}
return {};
}
} // namespace
export std::expected<BuildContext, std::string>
prepare_build(bool print_fingerprint,
bool includeDevDeps = false,
std::vector<mcpp::manifest::Target> extraTargets = {},
BuildOverrides overrides = {}) {
auto root = overrides.project_root.empty()
? mcpp::project::find_manifest_root(std::filesystem::current_path())
: std::optional<std::filesystem::path>(overrides.project_root);