-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathprepare.cppm
More file actions
6869 lines (6533 loc) · 366 KB
/
Copy pathprepare.cppm
File metadata and controls
6869 lines (6533 loc) · 366 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;
// The cfg() predicate evaluator and the fingerprint canonicalisers moved out —
// see mcpp.build.prepare_inputs. Re-exported so every existing caller of
// `target_dir` / `canonical_compile_flags` keeps working: a split whose only
// visible effect is that other files stop compiling is not an improvement.
export import mcpp.build.prepare_inputs;
import std;
import mcpp.diag;
import mcpp.home;
import mcpp.platform.axis;
import mcpp.libs.json;
import mcpp.log;
import mcpp.manifest;
import mcpp.source_kind;
import mcpp.modgraph.glob;
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.freestanding.target; // the target sysroot layout (libdir)
import mcpp.toolchain.post_install;
import mcpp.toolchain.abi;
import mcpp.toolchain.triple;
import mcpp.build.plan;
import mcpp.build.schedule.policy;
import mcpp.build.flags; // compute_flags — the per-role contracts (#418)
import mcpp.build.distribution; // dist::Role / dist::Contract to_string
import mcpp.platform.capacity; // the host fallback handed to schedule::decide
import mcpp.build.graph_shape; // #407: the graph says which mode wrote it
import mcpp.build.runtime_validation; // declared artifact -> identity verdict
import mcpp.build.cache_key;
import mcpp.pack.abi_tag; // the tag a prebuilt dependency is checked against
import mcpp.pack.prebuilt; // …and the check itself
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.platform.xlings;
import mcpp.platform.xlings.subos_info;
import mcpp.platform.xlings.runtime_selection;
import mcpp.platform.runtime_binding;
import mcpp.platform.runtime_search;
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.dependency_selector;
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));
}
}
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.
// The resolved triple travels INSIDE `ctx` (cfgpred::Ctx::triple). It used to
// be a third parameter here too, which is how a bare-triple predicate came to
// disagree with a cfg() one about the same native build — see the note on Ctx.
void merge_conditional_config(mcpp::manifest::Manifest& m,
const cfgpred::Ctx& ctx)
{
// A DISTRIBUTION package may carry a leg's link line twice: as `ldflags`
// (GNU spelling, which is all an older mcpp reads) and as the neutral
// `[target.<pred>.runtime]` pair, which mcpp renders per dialect. Applying
// both would put `-L` on a native `cl.exe` command line, which is exactly
// what the neutral form exists to avoid — so where the neutral form is
// present it REPLACES the ldflags rather than adding to them.
//
// Scoped to distribution packages on purpose: a hand-written manifest that
// states both may well mean both (`ldflags` also carries things like
// `-Wl,--as-needed`), and silently dropping half of it would be its own
// silent failure.
const bool generatedPackage = mcpp::pack::is_distribution_package(m);
for (auto const& cc : m.conditionalConfigs) {
if (!cfgpred::matches(cc.predicate, ctx)) continue;
const bool neutralWins = generatedPackage
&& (!cc.linkLibraryDirs.empty() || !cc.libraries.empty());
// 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`).
if (neutralWins) {
// ⚠️ Drop the LIBRARY REFERENCES, not the whole ldflags list.
//
// Clearing it outright was a measured regression: a PE/MinGW shared
// leg's ldflags also carry `-Wl,-Bdynamic`, without which `-static`
// leaves ld in static-only mode and it refuses the import library
// with `have you installed the static version of the mathkit
// library?`. e2e 257 caught it.
//
// The neutral form replaces exactly what it can express — a library
// and where to find it. Anything else in that block says something
// it cannot say, and must survive.
auto inputs = cc.inputs;
std::erase_if(inputs.ldflags, [](std::string_view f) {
return f.starts_with("-L") || f.starts_with("-l")
|| f.starts_with("/LIBPATH:");
});
mcpp::manifest::append(m.buildConfig, inputs);
} else {
mcpp::manifest::append(m.buildConfig, cc.inputs);
}
// The neutral half goes where `render_link_intent_flags` will find it.
for (auto const& d : cc.linkLibraryDirs)
m.runtimeConfig.linkIntent.linkLibraryDirs.push_back(d);
for (auto const& l : cc.libraries)
m.runtimeConfig.linkIntent.libraries.push_back(l);
// `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;
mcpp::xlings::runtime::RuntimeSelection runtimeSelection;
mcpp::platform::runtime::RuntimeBinding runtimeBinding;
std::filesystem::path projectRoot;
std::filesystem::path outputDir;
std::filesystem::path stdBmi;
std::filesystem::path stdObject;
mcpp::build::BuildPlan plan;
// The scanned module graph. Only `mcpp pack` reads it — see the note at
// the assignment for why the plan cannot answer its question.
mcpp::modgraph::Graph graph;
// 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 > `fallback`.
// The global default is "dev" (-O0 -g) per the dominant convention
// (Cargo/Meson/CMake/Zig/Bazel/MSBuild all default to debug).
//
// `fallback` exists for ONE caller: `mcpp pack`, where the artifact leaves this
// machine and an unoptimized build with the publisher's absolute source paths
// in it is never what was meant. It changes the LAST step only, so a manifest
// that states `[build] default-profile` still decides — packaging an artifact
// with different flags than `mcpp build` produces would be its own surprise.
// Adding a parameter here rather than a second resolver keeps the precedence
// rule in one function, which is why this function exists at all.
export std::string resolve_profile_name(const mcpp::manifest::Manifest& m,
std::string_view override_name,
std::string_view fallback = "dev") {
if (!override_name.empty()) return std::string(override_name);
if (!m.buildConfig.defaultProfile.empty()) return m.buildConfig.defaultProfile;
return fallback.empty() ? std::string("dev") : std::string(fallback);
}
// 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;
// Nested source/tool builds inherit the consumer root's local development
// OS. A dependency's own [xlings].subos is never consulted or propagated.
std::shared_ptr<const mcpp::xlings::runtime::RuntimeSelection>
inherited_runtime_selection;
std::shared_ptr<const mcpp::platform::runtime::RuntimeBinding>
inherited_runtime_binding;
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")
// What `resolve_profile_name` falls back to when neither the command line
// nor `[build] default-profile` says. Empty = "dev", which is every
// interactive command. `mcpp pack` sets "release": see resolve_profile_name.
std::string profile_fallback;
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.
// Spelling-independent `[target.<triple>]` lookup.
//
// A section keyed `x86_64-w64-mingw32` matches a resolved `x86_64-windows-gnu`,
// and unparseable keys compare exactly (the escape hatch for custom triples).
// Factored out of the toolchain-override path because the sysroot override must
// use the SAME matching: two lookups that disagreed about spelling would give a
// section that applies to `toolchain` and not to `sysroot`, which is a defect
// nobody would think to look for.
const mcpp::manifest::TargetEntry*
find_target_entry(const mcpp::manifest::Manifest& m,
const mcpp::toolchain::triple::Triple& t)
{
if (auto it = m.targetOverrides.find(t.str()); it != m.targetOverrides.end())
return &it->second;
for (auto const& [key, entry] : m.targetOverrides) {
if (auto k = mcpp::toolchain::triple::parse(key); k && k->str() == t.str())
return &entry;
}
return nullptr;
}
// The project's `[target.<triple>].sysroot`, or nullptr when it declared none.
const std::string*
sysroot_override(const mcpp::manifest::Manifest& m,
const mcpp::toolchain::triple::Triple& t)
{
auto* e = find_target_entry(m, t);
return (e && e->sysrootDeclared) ? &e->sysroot : nullptr;
}
// The target-facing answers a `build.mcpp` may ask the engine for.
//
// ONE function because there are TWO call sites — the root project and each
// dependency — and four values derived independently in two places is the
// shape this codebase keeps paying for. A board package that got the right
// answer as a root project and a stale one as a dependency would fail only in
// the consuming build, which is the harder direction to debug.
void fill_target_build_env(mcpp::build::BuildProgramEnv& e,
const mcpp::toolchain::Toolchain* tc)
{
e.toolchainDir = (tc && !tc->binaryPath.empty())
? tc->binaryPath.parent_path().parent_path().string() : std::string{};
e.targetSysroot = tc ? tc->targetSysrootRoot.string() : std::string{};
e.targetLibc = tc ? tc->targetSysrootPkg : std::string{};
if (!tc) return;
// The C LIBRARY's sub-directory for this ISA profile, from the freestanding
// table — the same single read point the compile flags use.
//
// ⚠️ Gated on there being a C library at all, and the gate is the point: the
// value is a multilib convention, so on the zero-libc tier there is nothing
// for it to be a convention OF. Emitting `rv64gc/lp64d` there would hand a
// kernel a path into a directory that does not exist, and the name of the
// accessor would be a lie. All three libc-facing answers are empty together.
if (!e.targetSysroot.empty())
if (auto spec = mcpp::freestanding::resolve(tc->targetTriple))
e.targetLibcProfile = std::string(spec->libdir);
// Which builtins library the RESOLVED toolchain ships. Freestanding only:
// on a hosted target the driver links them without being asked, and
// handing a package a name it must not use would invite it to.
if (auto t = mcpp::toolchain::triple::parse(tc->targetTriple);
t && t->is_freestanding()) {
e.targetBuiltinsLib = mcpp::toolchain::is_clang(*tc)
? "clang_rt.builtins-" + t->arch
: std::string("gcc");
}
}
std::string with_index_cause(std::string msg) {
if (auto hint = mcpp::pm::unusable_index_hint(); !hint.empty())
msg += "\n" + hint;
return msg;
}
} // 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);
if (!root) {
return std::unexpected("no mcpp.toml found in current directory or any parent");
}
// NOTE: `workRoot` is deliberately NOT derived here. `root` is not final
// yet — the workspace block below reassigns it to the selected member
// (`root = memberDir`), and anchoring the write root to the pre-switch
// value puts a member's target/, mcpp.lock and .mcpp/ at the WORKSPACE
// root. See the derivation right after that block.
// A registry package in `compat` form (Form B) ships NO mcpp.toml — its
// manifest is synthesized from the `.lua` descriptor by the resolver. So a
// nested build of such a package cannot re-read one off disk, and the
// caller hands over the manifest it already synthesized instead.
//
// Passing it in rather than re-deriving it is also the more correct of the
// two: re-deriving could produce a DIFFERENT manifest than the one the
// parent resolved against (the L1 cfg merge and feature-activated deps
// have already been folded in by then).
auto m = overrides.preloaded_manifest
? std::expected<mcpp::manifest::Manifest, mcpp::manifest::ManifestError>(
*overrides.preloaded_manifest)
: mcpp::manifest::load(*root / "mcpp.toml");
if (!m) return std::unexpected(m.error().format());
// A DISTRIBUTION package is not a source tree, and building "in" one is a
// failure that looks like a success: `interface/` holds declarations whose
// definitions are in the prebuilt archive, so the build compiles the
// declarations, produces a near-empty library, links nothing, and reports
// Finished. The archive it was supposed to carry never enters the picture.
//
// Only the ROOT is refused. As a dependency this is exactly what the
// package is for — the consumer compiles the interface and links the
// artifact, which is the whole design.
if (!overrides.preloaded_manifest && mcpp::pack::is_distribution_package(*m)) {
return std::unexpected(std::format(
"'{}' is a distribution package produced by `mcpp pack`, not a source tree.\n"
" Its sources are interface declarations; the definitions are in the\n"
" prebuilt artifacts beside them, so building here would produce an\n"
" empty library and say it succeeded.\n"
" Use it: add it to a project as a dependency —\n"
" [dependencies]\n"
" {} = {{ path = \"{}\" }}",
root->string(), m->package.name, root->string()));
}
// ─── 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
std::filesystem::path runtimeWorkspaceRoot;
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));
}
runtimeWorkspaceRoot = *root;
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) {
runtimeWorkspaceRoot = wsRoot;
wsManifest = std::move(*wsm);
// #224: anchor relative `path`/`[indices].path` to the
// workspace root, not this member's own directory.
mcpp::project::merge_workspace_deps(*m, *wsManifest, wsRoot);
if (m->toolchain.byPlatform.empty()) {
m->toolchain = wsManifest->toolchain;
}
for (auto& [triple, entry] : wsManifest->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, *wsManifest, wsRoot);
}
}
}
mcpp::xlings::runtime::RuntimeSelection runtimeSelection;
if (overrides.inherited_runtime_selection) {
runtimeSelection = *overrides.inherited_runtime_selection;
} else {
std::optional<std::reference_wrapper<const mcpp::manifest::Manifest>> wsRef;
if (wsManifest) wsRef = std::cref(*wsManifest);
auto selected = mcpp::xlings::runtime::select_runtime(
*m, wsRef, *root, runtimeWorkspaceRoot);
if (!selected) return std::unexpected(selected.error());
runtimeSelection = std::move(*selected);
}
// Where mcpp WRITES — derived here because `root` is only final now: the
// workspace block above may have moved it to the selected member. Defaults
// to the project root, so every existing invocation is byte-for-byte
// unchanged; the tool-provisioning pass points it at the tool store
// instead (BuildOverrides::work_dir).
const std::filesystem::path workRoot =
overrides.work_dir.empty() ? *root : overrides.work_dir;
{
std::error_code wdEc;
std::filesystem::create_directories(workRoot, wdEc);
}
if (m->package.sourceProvenance.empty()) {
m->package.sourceProvenance =
"path+" + root->lexically_normal().generic_string();
}
// A `compat`-form (Form B) package's sources live under a wrap directory
// inside the version dir, which is why its descriptor writes globs like
// `*/src/foo.cc` — the `*` stands for the tarball's top-level folder,
// whose name the descriptor cannot know. `[build] sources` has always
// expanded those; `targets.<x>.main` did NOT, so a bin target in such a
// package handed ninja a literal `*` and died with
// `missing and no known rule to make it`.
//
// Nothing could reach that path before #355 (a dependency's bin targets
// were never built), which is why it went unnoticed. Resolve it here, once
// the manifest is final and before anything reads `t.main`.
for (auto& t : m->targets) {
if (t.main.empty() || t.main.find('*') == std::string::npos) continue;
auto hits = mcpp::modgraph::expand_glob(*root, t.main);
if (hits.size() == 1) {
t.main = std::filesystem::relative(hits.front(), *root).generic_string();
} else {
return std::unexpected(std::format(
"target '{}': `main = \"{}\"` matched {} files; it must name "