-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathprepare.cppm
More file actions
3981 lines (3750 loc) · 201 KB
/
Copy pathprepare.cppm
File metadata and controls
3981 lines (3750 loc) · 201 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.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.build_program;
import mcpp.lockfile;
import mcpp.config;
import mcpp.xlings;
import mcpp.platform;
import mcpp.fetcher;
import mcpp.fetcher.progress;
import mcpp.pm.resolver;
import mcpp.pm.index_spec;
import mcpp.pm.index_route;
import mcpp.pm.mangle;
import mcpp.pm.compat;
import mcpp.pm.dep_spec;
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.
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; }
}
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).
// (Conditional *dependencies* are a separate, root-only concern: they must be
// merged into the dependency map BEFORE resolution even starts, so a
// dependency's own conditional deps are out of scope — see the root cfg
// block that merges `cc.dependencies` etc.)
void merge_conditional_build_inputs(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);
}
}
// 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_build_inputs — `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;
}
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;
// 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;
// Names of deps that DID hit cache (for ui status output).
std::vector<std::string> cachedDepLabels; // "mcpplibs.cmdline v0.0.1"
};
// Command-level overrides (--target / --static).
// Empty defaults preserve pre-existing behaviour exactly.
export struct BuildOverrides {
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)
};
// `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.
export std::expected<BuildContext, std::string>
prepare_build(bool print_fingerprint,
bool includeDevDeps = false,
std::vector<mcpp::manifest::Target> extraTargets = {},
BuildOverrides overrides = {}) {
auto root = mcpp::project::find_manifest_root(std::filesystem::current_path());
if (!root) {
return std::unexpected("no mcpp.toml found in current directory or any parent");
}
auto m = mcpp::manifest::load(*root / "mcpp.toml");
if (!m) return std::unexpected(m.error().format());
// ─── Workspace handling ────────────────────────────────────────────
// If the manifest has [workspace] and is a virtual workspace (no [package]),
// or if -p filter is set, switch to the target member's manifest.
std::optional<mcpp::manifest::Manifest> wsManifest; // keep workspace manifest alive
if (m->workspace.present) {
std::string targetMember;
if (!overrides.package_filter.empty()) {
// -p <name>: find matching member by directory basename or path
for (auto& mp : m->workspace.members) {
auto basename = std::filesystem::path(mp).filename().string();
if (basename == overrides.package_filter || mp == overrides.package_filter) {
targetMember = mp;
break;
}
}
if (targetMember.empty()) {
return std::unexpected(std::format(
"workspace member '{}' not found in [workspace].members",
overrides.package_filter));
}
} else if (m->package.name.empty()) {
// Virtual workspace: find a member with a binary target, or use last member.
for (auto& mp : m->workspace.members) {
auto memberDir = *root / mp;
auto mm = mcpp::manifest::load(memberDir / "mcpp.toml");
if (!mm) continue;
for (auto& t : mm->targets) {
if (t.kind == mcpp::manifest::Target::Binary) {
targetMember = mp;
break;
}
}
if (!targetMember.empty()) break;
}
if (targetMember.empty() && !m->workspace.members.empty()) {
targetMember = m->workspace.members.back();
}
}
// else: rooted workspace with [package] — build root normally.
if (!targetMember.empty()) {
auto memberDir = *root / targetMember;
if (!std::filesystem::exists(memberDir / "mcpp.toml")) {
return std::unexpected(std::format(
"workspace member '{}' has no mcpp.toml", targetMember));
}
wsManifest = std::move(*m); // preserve workspace manifest
m = mcpp::manifest::load(memberDir / "mcpp.toml");
if (!m) return std::unexpected(std::format(
"workspace member '{}': {}", targetMember, m.error().format()));
// Merge workspace dependency versions/paths. `*root` is still the
// WORKSPACE root here (the `root = memberDir` reassignment below
// hasn't happened yet), so it anchors any relative `path` in
// `[workspace.dependencies]` (#224).
mcpp::project::merge_workspace_deps(*m, *wsManifest, *root);
// Inherit workspace toolchain if member doesn't define one
if (m->toolchain.byPlatform.empty()) {
m->toolchain = wsManifest->toolchain;
}
// Inherit workspace target overrides
for (auto& [triple, entry] : wsManifest->targetOverrides) {
if (!m->targetOverrides.contains(triple)) {
m->targetOverrides[triple] = entry;
}
}
// Inherit workspace indices if member doesn't define any. `*root`
// is still the workspace root here, which is what a relative
// `[indices].path` was written against (#224).
mcpp::project::inherit_workspace_indices(*m, *wsManifest, *root);
mcpp::ui::status("Workspace", std::format("building member '{}'", targetMember));
root = memberDir;
}
} else {
// Not at workspace root — check if we're inside a workspace
auto wsRoot = mcpp::project::find_workspace_root(*root);
if (!wsRoot.empty()) {
auto wsm = mcpp::manifest::load(wsRoot / "mcpp.toml");
if (wsm && wsm->workspace.present) {
// #224: anchor relative `path`/`[indices].path` to the
// workspace root, not this member's own directory.
mcpp::project::merge_workspace_deps(*m, *wsm, wsRoot);
if (m->toolchain.byPlatform.empty()) {
m->toolchain = wsm->toolchain;
}
for (auto& [triple, entry] : wsm->targetOverrides) {
if (!m->targetOverrides.contains(triple)) {
m->targetOverrides[triple] = entry;
}
}
// Inherit workspace indices if member doesn't define any
mcpp::project::inherit_workspace_indices(*m, *wsm, wsRoot);
}
}
}
// Inject synthetic targets (e.g. test binaries from `mcpp test`).
for (auto& t : extraTargets) m->targets.push_back(t);
// Surface non-fatal manifest schema warnings (e.g. unsupported [targets.*]
// keys). Under --strict they become errors — same policy as the
// feature/platform schema checks below.
for (auto const& w : m->schemaWarnings) {
if (overrides.strict) return std::unexpected(w);
mcpp::diag::warning("manifest/schema", w);
}
// ─── Toolchain resolution (docs/21) ────────────────────────────────
// Priority chain:
// 1. mcpp.toml [toolchain].<platform> → resolve_xpkg_path → abs path
// 2. $CXX env var
// 3. PATH g++ (with warning)
std::filesystem::path explicit_compiler;
std::optional<mcpp::config::GlobalConfig> cfg_opt;
bool bootstrap_checked = false;
auto get_cfg = [&](bool requireBootstrap = true) -> std::expected<mcpp::config::GlobalConfig*, std::string> {
if (!cfg_opt) {
auto c = mcpp::config::load_or_init(/*quiet=*/false,
mcpp::fetcher::make_bootstrap_progress_callback());
if (!c) return std::unexpected(c.error().message);
cfg_opt = std::move(*c);
}
// Commands that need bootstrap tools (build, run, toolchain install)
// pass requireBootstrap=true to get an early, clear error.
if (requireBootstrap && !bootstrap_checked) {
bootstrap_checked = true;
auto problem = mcpp::config::check_base_init(*cfg_opt);
if (!problem.empty()) {
return std::unexpected(std::format(
"{}\n hint: run `mcpp self init --force` to reset and re-initialize",
problem));
}
}
return &*cfg_opt;
};
constexpr std::string_view kCurrentPlatform = mcpp::platform::name;
// M5.5: toolchain resolution priority:
// 0. --target X / --static, looked up in [target.<triple>]
// 1. project mcpp.toml [toolchain].<platform> or .default
// 2. global ~/.mcpp/config.toml [toolchain].default
// 3. hard error (no system fallback)
// Resolve the build profile, overlaid by any [profile.<name>] from the
// manifest → buildConfig. `effectiveProfile` outlives the block: the
// build.mcpp env contract exposes it as MCPP_PROFILE.
std::string effectiveProfile;
{
auto& pname = effectiveProfile;
// Precedence: --profile / --release / --dev flag (overrides.profile) >
// [build].default-profile (project default) > "dev" (global default).
// The global default is "dev" (-O0 -g) to follow the dominant convention
// (Cargo/Meson/CMake/Zig/Bazel/MSBuild all default to debug); release is
// opt-in via --release / --profile release. A project that wants its
// plain `mcpp build` optimized sets [build].default-profile = "release"
// (mcpp's own mcpp.toml does this, so the released binary stays -O2).
pname = !overrides.profile.empty() ? overrides.profile
: !m->buildConfig.defaultProfile.empty() ? m->buildConfig.defaultProfile
: "dev";
mcpp::manifest::Profile pr;
if (pname == "dev" || pname == "debug") { pr.optLevel = "0"; pr.debug = true; }
else if (pname == "dist") { pr.optLevel = "3"; pr.strip = true; }
// (built-in dist intentionally leaves lto off: several packaged gcc
// payloads ship without the LTO plugin; enable via [profile.dist].)
else { pr.optLevel = "2"; } // release
if (auto it = m->profiles.find(pname); it != m->profiles.end()) pr = it->second;
m->buildConfig.optLevel = pr.optLevel;
m->buildConfig.debug = pr.debug;
m->buildConfig.lto = pr.lto;
m->buildConfig.strip = pr.strip;
m->buildConfig.cflags.insert(m->buildConfig.cflags.end(),
pr.cflags.begin(), pr.cflags.end());
m->buildConfig.cxxflags.insert(m->buildConfig.cxxflags.end(),
pr.cxxflags.begin(), pr.cxxflags.end());
m->buildConfig.ldflags.insert(m->buildConfig.ldflags.end(),
pr.ldflags.begin(), pr.ldflags.end());
}
// [package] platforms — fixed vocabulary owned by mcpp (it owns the
// target/triple system). Unknown values: warning, or error under --strict.
for (auto& pf : m->package.platforms) {
if (pf != "linux" && pf != "macos" && pf != "windows") {
auto msg = std::format(
"[package] platforms contains unknown platform '{}' "
"(expected: linux | macos | windows)", pf);
if (overrides.strict) return std::unexpected(msg);
mcpp::diag::warning("manifest/platforms", msg);
}
}
auto tcSpec = m->toolchain.for_platform(kCurrentPlatform);
if (!tcSpec.has_value()) {
auto cfg = get_cfg();
if (cfg && !(*cfg)->defaultToolchain.empty()) {
tcSpec = (*cfg)->defaultToolchain;
}
}
// ─── --target / --static overrides ──────────────────────────────────
// Target-axis default resolution when no --target flag was passed:
// [build] target (project default, ≙ cargo build.target) >
// [toolchain] default_target (global config) > host.
if (overrides.target_triple.empty() && !m->buildConfig.target.empty())
overrides.target_triple = m->buildConfig.target;
if (overrides.target_triple.empty()) {
if (auto cfg = get_cfg(); cfg && !(*cfg)->defaultTarget.empty())
overrides.target_triple = (*cfg)->defaultTarget;
}
// Normalize the triple (alias spellings → canonical), validate against
// the known-target vocabulary, then apply the manifest [target.<triple>]
// override and the vocabulary-table convention (pin + default linkage).
if (!overrides.target_triple.empty()) {
namespace triple = mcpp::toolchain::triple;
auto parsed = triple::parse(overrides.target_triple);
// [target.X] lookup is spelling-independent: a section keyed
// `x86_64-w64-mingw32` matches `--target x86_64-windows-gnu` and
// vice versa. Unparseable keys/inputs compare exactly (escape hatch).
auto it = m->targetOverrides.find(overrides.target_triple);
if (it == m->targetOverrides.end() && parsed) {
for (auto o = m->targetOverrides.begin();
o != m->targetOverrides.end(); ++o) {
if (auto k = triple::parse(o->first);
k && k->str() == parsed->str()) { it = o; break; }
}
}
bool hasExplicitSection = it != m->targetOverrides.end();
bool hasToolchainOverride = hasExplicitSection
&& !it->second.toolchain.empty();
const triple::TargetInfo* known =
parsed ? triple::find_known_target(*parsed) : nullptr;
// Validation: a typo must never silently fall through to the host
// toolchain (the worst failure mode — you think you cross-compiled).
// An explicit [target.X] section is the escape hatch for custom
// triples outside the vocabulary.
if (!known && !hasExplicitSection) {
auto sug = triple::did_you_mean(overrides.target_triple);
return std::unexpected(std::format(
"unknown target '{}'{}\n"
" known targets: `mcpp toolchain list`; a custom triple needs an\n"
" explicit [target.{}] section in mcpp.toml",
overrides.target_triple,
sug ? std::format(" — did you mean '{}'?", *sug) : "",
overrides.target_triple));
}
if (known && known->tier == "planned" && !hasToolchainOverride) {
return std::unexpected(std::format(
"target '{}' is registered but not yet supported (planned) — "
"no toolchain is published for it yet.\n"
" An explicit [target.{}] toolchain override can opt in early.",
parsed->str(), parsed->str()));
}
// Canonical from here on: cfg evaluation, spec attachment and the
// target/ output directory all see one spelling.
if (parsed) overrides.target_triple = parsed->str();
if (hasExplicitSection) {
if (!it->second.toolchain.empty()) tcSpec = it->second.toolchain;
if (!it->second.linkage.empty()) m->buildConfig.linkage = it->second.linkage;
}
// Convention from the vocabulary table (triple.cppm): the target's
// pinned toolchain (host-awareness — native musl-gcc vs triple-named
// cross, winlibs mingw vs Linux-hosted cross — lives in the payload
// mapping, not here) and its default linkage. GCC 16 pin rationale:
// GCC 15 drops module template instantiations at link (remediation
// doc A2; packages shipped 2026-07-08/09, GitHub+GitCode).
if (known && !hasToolchainOverride && !known->pin.empty())
tcSpec = std::string(known->pin);
if (known && known->defaultStatic && m->buildConfig.linkage.empty())
m->buildConfig.linkage = "static";
}
if (overrides.force_static) m->buildConfig.linkage = "static";
// #254: everything compiled INTO this build is resolved for the TARGET —
// an xpkg descriptor's per-OS sections (sources, flags, deps) and its xpm
// asset/version table all describe code that will run on the target, not
// on the machine building it. Previously a compile-time host constant,
// which is invisible natively (host == target) and picks the wrong leg
// under --target.
//
// Computed HERE, not earlier: `overrides.target_triple` is only complete
// above — it is filled from `[build] target` and the config default, then
// canonicalized. Reading it before that point would silently fall back to
// the host for any project that sets its target in the manifest rather
// than on the command line.
const auto targetPlatform = mcpp::platform::TargetPlatform::for_os(
cfgpred::context_for(overrides.target_triple).os);
// ── L1: merge conditional [target.'cfg(...)'.build] sources/flags AND
// root-only [target.'cfg(...)'.dependencies] ─────────────────────────────
// Evaluated now (target resolved) against the resolved target — the
// --target triple for a cross build, else the host.
//
// #229: merge_conditional_build_inputs MUST run here — before
// `packages[0] = makePackageRoot(*root, *m)` snapshots `m->buildConfig`
// into `packages[0].privateBuild`/`.manifest` — because that snapshot,
// not `*m`, is what the modgraph scan and per-TU compile-flag assembly
// actually read afterward. Every dependency (path/git/version alike) gets
// the SAME treatment, at the mirror-image point in its own load path
// (right before ITS `makePackageRoot`/`propagateLinkFlags`) — see the
// dependency-manifest-acquisition block below. That makes this the root
// package's half of the one funnel, not a special case: every package is
// merged exactly once, immediately before it is captured into `packages[]`.
if (!m->conditionalConfigs.empty()) {
auto cc_ctx = cfgpred::context_for(overrides.target_triple);
merge_conditional_build_inputs(*m, cc_ctx, overrides.target_triple);
for (auto const& cc : m->conditionalConfigs) {
if (!cfgpred::matches(cc.predicate, cc_ctx, overrides.target_triple))
continue;
// Conditional dependencies (Phase 1b): merge into the manifest maps
// before dependency resolution so they resolve like any dep. insert()
// keeps an existing unconditional entry (no silent override).
// Root-only — a dependency's own conditional deps are out of scope.
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());
}
}
// `[build].defines` must reach the scanner (P1689) and the compile edge,
// and must participate in the fingerprint. Fold before dependency
// resolution / fingerprinting.
fold_build_defines_into_flags(m->buildConfig);
// msvc@system: a *system* toolchain — located on the machine, never
// resolved through xim packages. mcpp does not install MSVC.
bool tcSpecIsMsvc = false;
if (tcSpec.has_value()) {
if (auto s = mcpp::toolchain::parse_toolchain_spec(*tcSpec);
s && mcpp::toolchain::is_system_toolchain(*s))
tcSpecIsMsvc = true;
}
if (tcSpecIsMsvc) {
if (!mcpp::platform::is_windows) {
return std::unexpected(std::format(
"toolchain '{}' is only available on Windows hosts", *tcSpec));
}
auto inst = mcpp::toolchain::msvc::detect_installation();
if (!inst) {
return std::unexpected(mcpp::toolchain::msvc::install_guidance());
}
explicit_compiler = inst->clPath;
mcpp::ui::info("Resolved", std::format(
"msvc@system → msvc {} ({})",
inst->display_version(), inst->clPath.string()));
} else if (tcSpec.has_value() && *tcSpec != "system") {
auto spec = mcpp::toolchain::parse_toolchain_spec(*tcSpec);
if (!spec || spec->version.empty()) {
return std::unexpected(std::format(
"[toolchain].{} = '{}' is invalid; expected '<pkg>@<version>'",
kCurrentPlatform, *tcSpec));
}
// A `--target <triple>` build carries the (already canonical) triple
// into the spec's target axis: the payload mapping then resolves the
// right package/frontend (e.g. aarch64-linux-musl-g++ for a cross
// musl build, never the host g++). Escape-hatch triples outside the
// language don't parse and leave the spec on the host target.
if (!overrides.target_triple.empty()) {
if (auto t = mcpp::toolchain::triple::parse(overrides.target_triple))
spec->target = *t;
}
auto pkg = mcpp::toolchain::to_xim_package(*spec);
auto cfg = get_cfg();
if (!cfg) return std::unexpected(cfg.error());
mcpp::fetcher::Fetcher fetcher(**cfg);
mcpp::ui::info("Resolving", "toolchain");