-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathprepare.cppm
More file actions
3161 lines (2952 loc) · 152 KB
/
Copy pathprepare.cppm
File metadata and controls
3161 lines (2952 loc) · 152 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.libs.json;
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.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 {
// ── 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;
}
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& [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()));
}
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 manifest (root or dependency): 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. Conditional dependency maps are root-only and handled at the root
// call site; a dependency's conditional configs otherwise evaluate the same
// way (descriptor `target_cfg` must not be silently inert).
void merge_conditional_build(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;
m.buildConfig.cflags.insert(m.buildConfig.cflags.end(),
cc.cflags.begin(), cc.cflags.end());
m.buildConfig.cxxflags.insert(m.buildConfig.cxxflags.end(),
cc.cxxflags.begin(), cc.cxxflags.end());
m.buildConfig.ldflags.insert(m.buildConfig.ldflags.end(),
cc.ldflags.begin(), cc.ldflags.end());
for (auto const& s : cc.sources) {
m.buildConfig.sources.push_back(s);
m.modules.sources.push_back(s);
}
}
}
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 {
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
mcpp::project::merge_workspace_deps(*m, *wsManifest);
// 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
if (m->indices.empty() && !wsManifest->indices.empty()) {
m->indices = wsManifest->indices;
}
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) {
mcpp::project::merge_workspace_deps(*m, *wsm);
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
if (m->indices.empty() && !wsm->indices.empty()) {
m->indices = wsm->indices;
}
}
}
}
// 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);
std::println(stderr, "warning: {}", 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.
{
// 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).
std::string 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);
std::println(stderr, "warning: {}", 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";
// ── L1: merge platform-conditional [target.'cfg(...)'.build] flags ──────
// Evaluated now (target resolved) against the resolved target — the
// --target triple for a cross build, else the host. Matching predicates'
// flags append to buildConfig, mirroring the [profile] merge above.
if (!m->conditionalConfigs.empty()) {
auto cc_ctx = cfgpred::context_for(overrides.target_triple);
merge_conditional_build(*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());
}
}
// 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");
mcpp::fetcher::InstallProgressHandler progress;
auto payload = fetcher.resolve_xpkg_path(pkg.target(), /*autoInstall=*/true, &progress);
if (!payload) {
return std::unexpected(std::format(
"toolchain '{}': {}", *tcSpec, payload.error().message));
}
explicit_compiler = mcpp::toolchain::toolchain_frontend(payload->binDir, pkg);
if (!std::filesystem::exists(explicit_compiler)) {
return std::unexpected(std::format(
"toolchain payload '{}' has no known C++ frontend in {}",
pkg.target(), payload->binDir.string()));
}
// Same post-install fixup as `mcpp toolchain install` — this manifest
// [toolchain] path previously ran none, so a freshly auto-installed
// payload kept its stale install-time cfg / unpatched runtime libs.
mcpp::toolchain::ensure_post_install_fixup(**cfg, payload->root, pkg);
// Canonical rendering, whatever spelling the manifest/config used:
// "Resolved gcc@16.1.0 → x86_64-linux-musl → <frontend>".
mcpp::ui::info("Resolved",
std::format("{} → {}", spec->display(),
mcpp::ui::shorten_path(explicit_compiler,
mcpp::fetcher::make_path_ctx(&**get_cfg(), *root))));
} else if (tcSpec.has_value() && *tcSpec == "system") {
// Explicit user opt-in to system PATH compiler — kept as escape hatch.
} else if (auto* opt = std::getenv("MCPP_NO_AUTO_INSTALL"); opt && *opt && *opt != '0') {
// CI / offline / test opt-out: hard-error instead of silently
// pulling ~800 MB of toolchain. Preserves the original M5.5
// contract for environments that need it.
namespace pins = mcpp::toolchain::triple::pins;
if constexpr (mcpp::platform::is_macos || mcpp::platform::is_windows) {
return std::unexpected(std::format(
"no toolchain configured.\n"
" run one of:\n"
" mcpp toolchain install {}\n"
" mcpp toolchain default {}\n"
" or unset MCPP_NO_AUTO_INSTALL to let mcpp auto-install.",
pins::kSuggestLlvm, pins::kFirstRunMacWin));
} else {
return std::unexpected(std::format(
"no toolchain configured.\n"
" run one of:\n"
" mcpp toolchain install {}\n"
" mcpp toolchain default {}\n"
" or unset MCPP_NO_AUTO_INSTALL to let mcpp auto-install.",
pins::kSuggestGccMusl, pins::kFirstRunLinuxOther));
}
} else {
// First-run UX: no project-level [toolchain], no global default,
// and the user just ran `mcpp build` (or similar). Auto-install
// the platform's canonical default so the user gets a working
// binary out of the box without any config. We pin it as the
// global default so the next invocation is silent.
// Users can switch any time via `mcpp toolchain default <spec>`.
//
// macOS: LLVM/Clang — Apple doesn't ship GCC; upstream LLVM with
// bundled libc++ is the self-contained choice.
// Linux: glibc gcc — the platform-native ABI. A musl-static default
// cannot link the glibc world (X11/GL/system libs), so it
// breaks GUI/native packages out of the box. musl-static stays
// opt-in via `mcpp build --target x86_64-linux-musl` for users
// who explicitly want portable static binaries.
// Linux default is arch-aware:
// x86_64 → glibc gcc (native ABI; the glibc toolchain is published
// for x86_64). musl-static stays opt-in via --target.
// other arches (aarch64, ...) → musl-static gcc: it's what's
// published for them, is self-contained, and yields portable
// static binaries (ideal for aarch64 / Termux, no bionic dep).
// glibc-world linking (X11/GL) needs an explicit glibc
// toolchain, addable later for native-ABI aarch64 builds.
namespace pins = mcpp::toolchain::triple::pins;
std::string defaultSpec;
if constexpr (mcpp::platform::is_macos || mcpp::platform::is_windows) {
defaultSpec = std::string(pins::kFirstRunMacWin);
} else if (mcpp::platform::host_arch == std::string_view("x86_64")) {
defaultSpec = std::string(pins::kFirstRunLinuxX86_64);
} else {
defaultSpec = std::string(pins::kFirstRunLinuxOther);
}
auto defaultParsed = mcpp::toolchain::parse_toolchain_spec(defaultSpec);
// The legacy "-musl" spelling normalizes to (gcc, <host>-linux-musl),
// so the resolver finds the `<host_arch>-linux-musl-g++` frontend
// without any manual triple seeding.
bool muslDefault = defaultParsed->target.is_musl();
auto defaultPkg = mcpp::toolchain::to_xim_package(*defaultParsed);
if constexpr (mcpp::platform::is_macos || mcpp::platform::is_windows) {
mcpp::ui::info("First run",
std::format("no toolchain configured — installing {} (LLVM/Clang) as default",
defaultSpec));
} else {
mcpp::ui::info("First run",
std::format("no toolchain configured — installing {} ({}) as default",
defaultSpec, muslDefault ? "musl, static" : "glibc, native ABI"));
}
auto cfg = get_cfg();
if (!cfg) return std::unexpected(cfg.error());
mcpp::fetcher::Fetcher fetcher(**cfg);
mcpp::fetcher::InstallProgressHandler progress;
// The glibc default toolchain needs the sysroot payloads (C library +
// kernel headers). The musl default is self-contained, so skip them.
if (!mcpp::platform::is_macos && !mcpp::platform::is_windows && !muslDefault) {
for (auto dep : {"xim:glibc", "xim:linux-headers"}) {
(void)fetcher.resolve_xpkg_path(dep, /*autoInstall=*/true, &progress);
}
}
auto payload = fetcher.resolve_xpkg_path(defaultPkg.target(),
/*autoInstall=*/true, &progress);
if (!payload) {
return std::unexpected(std::format(
"auto-installing default toolchain {} failed: {}\n"
" you can install it manually with:\n"
" mcpp toolchain install {}",
defaultSpec, payload.error().message, defaultSpec));
}
explicit_compiler = mcpp::toolchain::toolchain_frontend(payload->binDir, defaultPkg);
if (!std::filesystem::exists(explicit_compiler)) {
return std::unexpected(std::format(
"default toolchain payload {} has no known C++ frontend in {}",
defaultPkg.target(), payload->binDir.string()));
}
// The freshly-installed toolchain needs the SAME post-install fixup
// (patchelf / specs / cfg wiring against the sandbox glibc) that
// `mcpp toolchain install` performs — without it a fresh sandbox
// gcc cannot find the C library (stdlib.h: No such file or
// directory) and a fresh llvm keeps its stale install-time cfg.
mcpp::toolchain::ensure_post_install_fixup(**cfg, payload->root, defaultPkg);
// Persist the default so we don't ask again next time.
if (auto wr = mcpp::config::write_default_toolchain(**cfg, defaultSpec); wr) {
(*cfg)->defaultToolchain = defaultSpec;
mcpp::ui::status("Default", std::format("set to {}", defaultSpec));
} // best-effort: a failed config write only loses the persistence,
// not the running build.
tcSpec = defaultSpec;
}
auto tc = mcpp::toolchain::detect(explicit_compiler);
if (!tc) return std::unexpected(tc.error().message);
// Native MSVC builds need the synthesized INCLUDE/LIB env — absent when
// detection found VC tools but no Windows SDK. Fail here with guidance
// instead of cl.exe's later "cannot open include file: 'corecrt.h'".
if (tc->compiler == mcpp::toolchain::CompilerId::MSVC
&& tc->envOverrides.empty()) {
return std::unexpected(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()));
}
// For musl-gcc the toolchain is fully self-contained
// (`<root>/x86_64-linux-musl/{include,lib}` is its own sysroot).
// musl-gcc's `-dumpmachine` reports `x86_64-linux-musl`.
bool isMuslTc = mcpp::toolchain::is_musl_target(*tc);
// A musl toolchain only really makes sense with static linkage —
// dynamic-musl binaries depend on a system /lib/ld-musl-x86_64.so.1
// that most distros don't ship. Default linkage to "static" when
// the resolved toolchain is musl, unless the user has already opted
// out via [build].linkage / [target.<triple>].linkage.
if (isMuslTc && m->buildConfig.linkage.empty()) {
m->buildConfig.linkage = "static";
}
// Sysroot comes from the toolchain payload itself (GCC -print-sysroot,
// Clang clang++.cfg). mcpp does not override it — the payload is
// self-describing. See docs: 2026-05-21-linux-sysroot-missing-kernel-headers.md
// ── L3: project-local `build.mcpp` imperative build program ─────────────
// Compiled with the (host) toolchain and run now — after target resolution
// + the L1 cfg-flag merge (buildConfig flags are final) and BEFORE the
// modgraph scan (so its `generated=` sources are picked up). Its stdout
// directives augment buildConfig; a declared-input cache re-runs it only
// when its source/inputs/env change. Leaf-only: it cannot gate the top-level
// dependency graph. Skipped under a cross --target (host program, host run).
// See .agents/docs/2026-06-30-l3-build-mcpp-implementation-design.md.
// Root [generated_files]: materialize before build.mcpp and the modgraph
// scan so synthesized sources are globbed like any on-disk file. (The
// per-dependency call sits in the dep resolution loop below; the root
// manifest needs its own.)
if (!m->buildConfig.generatedFiles.empty()) {
if (auto r = materialize_generated_files(*root, *m); !r) {