test(build): a source's declaration and imports, as its compile reads them

SourceScan builds copies of six fixtures and checks what the build read
in their sources, by the modules and units it gives each configuration,
and runs the program where what it does depends on that:

- text, three of the four inputs of #45: `import  Base;` and
  `import Spaced ;` are imports, and an import in a comment that spans
  lines or under #if 0 is none. A build with nothing changed then
  rewrites none of the scans, and one that cannot be read is taken
  again.
- quoted, the fourth: an implementation source whose string literal
  holds "export module std;" is a unit of no module, and the build
  succeeds.
- partition: a .cppm that declares an implementation partition
  (`module X:Impl;`) is the partition Impl of X, and the implementation
  unit that imports it has its edge to it.
- define: an #ifdef on a define that the test sets after listing the
  source decides whether the source imports a module.
- switch: an #if on a header of the library the app is built on decides
  it. The header is edited, and the source is scanned again; then the
  app is built on another library, whose header of that name says the
  other thing, so that only the command the scan was taken with has
  changed.
- missing: an #include of a header that is not there fails the build
  with a message naming the header, and nothing is compiled of the
  source.

On the engine of the range's base, with only this test added, every case
but missing fails. Each of the three inputs of the text case is read the
old way, and its first build fails outright whenever Spaced.cppm, whose
import of Base was missed, is compiled before Base's BMI is there; the
string literal makes the listing throw "Module std not found not found",
and the implementation partition the listing of the partition case, "No
module declaration found"; the import under the #ifdef counts without
the define, and the one under the #if after the edit and after the swap;
and there is no scan to look at. The missing case passes there too, the
compile reporting the header as the scan now does.
This commit is contained in:
Jorijn van der Graaf 2026-11-27 09:25:53 +01:00
commit 08a506d34b
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
23 changed files with 483 additions and 0 deletions

View file

@ -349,6 +349,7 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
cfg.AddTest("JobGroup").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("JobLimit").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("ImportCycle").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("SourceScan").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("BuildAll").Dependencies({ CrafterBuildLib.get() });
cfg.AddTest("Lint").Dependencies({ CrafterBuildLib.get() });
}

View file

@ -0,0 +1,8 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Extra;
export int ExtraValue() {
return 40;
}

View file

@ -0,0 +1,17 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Imports Extra when the build defines CRAFTER_TEST_EXTRA, which the test
// does after it lists this source.
#ifdef CRAFTER_TEST_EXTRA
import Extra;
#endif
// Exits with 40 when CRAFTER_TEST_EXTRA is defined, 2 when it is not.
int main() {
#ifdef CRAFTER_TEST_EXTRA
return ExtraValue();
#else
return 2;
#endif
}

View file

@ -0,0 +1,8 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include "not-there.h"
int main() {
return 0;
}

View file

@ -0,0 +1,10 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// An implementation partition, listed as an interface unit of the
// configuration, as a partition another unit of the module imports has to be.
module X:Impl;
int G() {
return 7;
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module X;
import :Impl;
int F() {
return G();
}

View file

@ -0,0 +1,6 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module X;
export int F();

View file

@ -0,0 +1,8 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import X;
int main() {
return F() == 7 ? 0 : 1;
}

View file

@ -0,0 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// No unit of any module: what reads as a module declaration below is the
// text of a string literal.
int QuotedLength() {
constexpr char text[] = "export module std;";
return static_cast<int>(sizeof(text)) - 1;
}

View file

@ -0,0 +1,8 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
int QuotedLength();
int main() {
return QuotedLength() == 18 ? 0 : 1;
}

View file

@ -0,0 +1,8 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Extra;
export int ExtraValue() {
return 40;
}

View file

@ -0,0 +1,19 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// WITH_EXTRA comes from the switch.h of the library the app is built on:
// found through its directory, which is on the include path of what is
// built on it.
#include <switch.h>
#if WITH_EXTRA
import Extra;
#endif
// Exits with 40 when WITH_EXTRA is 1, 2 when it is 0.
int main() {
#if WITH_EXTRA
return ExtraValue();
#else
return 2;
#endif
}

View file

@ -0,0 +1,8 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Off;
export int OffValue() {
return 0;
}

View file

@ -0,0 +1,5 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#pragma once
#define WITH_EXTRA 0

View file

@ -0,0 +1,8 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module On;
export int OnValue() {
return 1;
}

View file

@ -0,0 +1,6 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Copied over switch.h by the test, mid-run.
#pragma once
#define WITH_EXTRA 0

View file

@ -0,0 +1,5 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#pragma once
#define WITH_EXTRA 1

View file

@ -0,0 +1,8 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Base;
export int BaseValue() {
return 1;
}

View file

@ -0,0 +1,11 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Commented;
/*
import Spaced;
*/
export int CommentedValue() {
return 3;
}

View file

@ -0,0 +1,11 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Disabled;
#if 0
import Spaced;
#endif
export int DisabledValue() {
return 4;
}

View file

@ -0,0 +1,10 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Spaced;
// Two spaces after `import`, as a formatter that lines up columns writes it.
import Base;
export int SpacedValue() {
return BaseValue() + 1;
}

View file

@ -0,0 +1,12 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// A space before the semicolon.
import Spaced ;
import Commented;
import Disabled;
// Exits 0 when each module gives what it should.
int main() {
return SpacedValue() + CommentedValue() + DisabledValue() == 9 ? 0 : 1;
}

288
tests/SourceScan/main.cpp Normal file
View file

@ -0,0 +1,288 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// A build reads what a source declares and imports as the compiler reads
// it: clang-scan-deps preprocesses the source with the command it is
// compiled with. The build used to search the text with regular
// expressions after deleting the comments that fit on one line (issue #45),
// so it took a module declaration in a string literal for a real one,
// followed an import in a comment that spans lines or under `#if 0`, missed
// `import X;` and `import X ;`, and read every #if as true. A source that
// held "export module std;" in a string became a unit of a module std and
// stopped the build; an import it missed was an edge missing, so a unit
// could be compiled before the BMI it imports, or kept when that changed.
//
// Each case builds a copy of a fixture and checks what the build read, by
// the modules and units it gave the configuration, and runs the program
// where what it does depends on that:
// text an import in a comment that spans lines, under #if 0, after
// two spaces and before a space, three of the issue's four
// inputs; a build with nothing changed; a kept scan that cannot
// be read
// quoted a module declaration in a string literal, the fourth
// partition
// a .cppm that declares an implementation partition, which
// the build refused as declaring no module
// define an #ifdef on a define set after the source is listed
// switch an #if on a header of a dependency: the header edited, and the
// dependency swapped for another
// missing an #include of a header that is not there
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
const fs::path Scratch = fs::temp_directory_path() / "crafter-build-source-scan";
// A copy of the fixture `name`, made anew: the switch case edits it.
fs::path Stage(std::string_view name) {
const fs::path staged = Scratch / name;
fs::remove_all(staged);
fs::create_directories(Scratch);
fs::copy(fs::current_path() / "tests" / "SourceScan" / "fixture" / name, staged, fs::copy_options::recursive);
return staged;
}
Configuration Make(const fs::path& dir, std::string_view name, ConfigurationType type, std::vector<fs::path> interfaces, std::vector<fs::path> implementations) {
Configuration cfg;
cfg.path = dir;
cfg.name = std::string(name);
cfg.outputName = std::string(name);
cfg.target = HostTarget();
cfg.type = type;
cfg.GetInterfacesAndImplementations(interfaces, implementations);
return cfg;
}
// Build()'s error, in a pass of its own.
std::string BuildError(Configuration& cfg) {
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
return Build(cfg, depResults, depMutex).result;
}
// The exit code of the program `cfg` built.
std::int32_t Run(const Configuration& cfg) {
const auto run = RunCommandWithTimeout(ShellQuote(ExpectedOutput(cfg).string()), std::chrono::seconds(30));
return run.crashed || run.timedOut ? -1 : run.exitCode;
}
const Module* Named(const Configuration& cfg, std::string_view name) {
for (const std::unique_ptr<Module>& module : cfg.interfaces) {
if (module->name == name) return module.get();
}
return nullptr;
}
// The names of the modules a unit's import edges lead to, local and
// external alike, in order.
template <typename Unit>
std::vector<std::string> Imports(const Unit& unit) {
std::vector<std::string> names;
for (const Module* imported : unit.moduleDependencies) names.push_back(imported->name);
for (const auto& [imported, bmi] : unit.externalModuleDependencies) names.push_back(imported->name);
return names;
}
std::string Listed(const std::vector<std::string>& names) {
return names.empty() ? "nothing" : std::format("{}", names);
}
// The implementation unit of `cfg` whose source is `source`.
const Implementation* UnitOf(const Configuration& cfg, const fs::path& source) {
fs::path stem = source;
stem.replace_extension();
for (const Implementation& unit : cfg.implementations) {
if (unit.path == stem) return &unit;
}
return nullptr;
}
// When the scan the build keeps of `source` was written.
std::optional<fs::file_time_type> ScanTime(const Configuration& cfg, const fs::path& source) {
std::error_code ec;
const fs::file_time_type written = fs::last_write_time(cfg.BuildDir() / "scans" / std::format("{}.json", source.string()), ec);
if (ec) return std::nullopt;
return written;
}
// Copies `from` over `to` and dates it now: copy_file keeps the time of
// `from`, which would leave the edit older than what was built before.
void Replace(const fs::path& from, const fs::path& to) {
fs::copy_file(from, to, fs::copy_options::overwrite_existing);
fs::last_write_time(to, fs::file_time_type::clock::now());
}
void TextCase() {
const fs::path dir = Stage("text");
Configuration cfg = Make(dir, "scan-text", ConfigurationType::Executable, { "Base", "Spaced", "Commented", "Disabled" }, { "main" });
const std::string error = BuildError(cfg);
Check(error.empty(), std::format("text: the build succeeds: {}", error));
if (!error.empty()) return;
Check(Run(cfg) == 0, "text: the program gets what each module gives");
const Module* spaced = Named(cfg, "Spaced");
const Module* commented = Named(cfg, "Commented");
const Module* disabled = Named(cfg, "Disabled");
Check(spaced != nullptr && commented != nullptr && disabled != nullptr && Named(cfg, "Base") != nullptr, "text: the four interface units are four modules");
if (spaced == nullptr || commented == nullptr || disabled == nullptr) return;
Check(Imports(*spaced) == std::vector<std::string>{ "Base" }, std::format("text: `import Base;` is an import of Base, got {}", Listed(Imports(*spaced))));
Check(Imports(*commented).empty(), std::format("text: an import in a comment that spans lines is none, got {}", Listed(Imports(*commented))));
Check(Imports(*disabled).empty(), std::format("text: an import under #if 0 is none, got {}", Listed(Imports(*disabled))));
const Implementation* main = UnitOf(cfg, dir / "main.cpp");
Check(main != nullptr && Imports(*main) == std::vector<std::string>{ "Spaced", "Commented", "Disabled" }, std::format("text: `import Spaced ;` is an import of Spaced, beside the two others, got {}", main == nullptr ? "no unit" : Listed(Imports(*main))));
// Built again with nothing changed: every scan is read as it was
// kept, and none is taken again.
const std::vector<fs::path> sources = { "Base.cppm", "Spaced.cppm", "Commented.cppm", "Disabled.cppm", "main.cpp" };
std::vector<std::optional<fs::file_time_type>> before;
for (const fs::path& source : sources) before.push_back(ScanTime(cfg, source));
Check(std::ranges::none_of(before, [](const std::optional<fs::file_time_type>& t) { return !t; }), "text: every source has its scan in the build directory");
const std::string again = BuildError(cfg);
Check(again.empty(), std::format("text: the build with nothing changed succeeds: {}", again));
for (std::size_t i = 0; i < sources.size(); ++i) {
Check(ScanTime(cfg, sources[i]) == before[i], std::format("text: {} is not scanned again when nothing changed", sources[i].string()));
}
// The build made the modules anew, from the scans it kept.
const Module* kept = Named(cfg, "Spaced");
Check(kept != nullptr && Imports(*kept) == std::vector<std::string>{ "Base" }, "text: the kept scan gives the import of Base again");
// A kept scan that cannot be read is taken again.
std::ofstream(cfg.BuildDir() / "scans" / "Spaced.cppm.json", std::ios::binary | std::ios::trunc) << "not what a build writes";
const std::string unreadable = BuildError(cfg);
Check(unreadable.empty(), std::format("text: a scan that cannot be read is taken again, and the build succeeds: {}", unreadable));
if (const Module* rescanned = Named(cfg, "Spaced")) Check(Imports(*rescanned) == std::vector<std::string>{ "Base" }, "text: the scan taken again gives the import of Base");
}
void QuotedCase() {
const fs::path dir = Stage("quoted");
Configuration cfg = Make(dir, "scan-quoted", ConfigurationType::Executable, {}, { "Quoted", "main" });
const std::string error = BuildError(cfg);
Check(error.empty(), std::format("quoted: a module declaration in a string literal is none, and the build succeeds: {}", error));
if (!error.empty()) return;
Check(cfg.interfaces.empty(), "quoted: the configuration has no module");
const Implementation* quoted = UnitOf(cfg, dir / "Quoted.cpp");
Check(quoted != nullptr && Imports(*quoted).empty(), "quoted: Quoted.cpp imports nothing, a module std least of all");
Check(Run(cfg) == 0, "quoted: the program holds the string");
}
void PartitionCase() {
const fs::path dir = Stage("partition");
Configuration cfg = Make(dir, "scan-partition", ConfigurationType::Executable, { "X", "X-Impl" }, { "X", "main" });
const std::string error = BuildError(cfg);
Check(error.empty(), std::format("partition: an implementation partition listed as an interface unit builds: {}", error));
if (!error.empty()) return;
const Module* x = Named(cfg, "X");
Check(x != nullptr && x->partitions.size() == 1 && x->partitions[0]->name == "Impl", "partition: it is the partition Impl of module X");
const Implementation* unit = UnitOf(cfg, dir / "X.cpp");
Check(unit != nullptr && unit->partitionDependencies.size() == 1 && unit->partitionDependencies[0]->name == "Impl", "partition: X.cpp, which imports :Impl, has its edge to it");
Check(Run(cfg) == 0, "partition: the program gets G() through F()");
}
void DefineCase() {
const fs::path dir = Stage("define");
for (const bool defined : { false, true }) {
Configuration cfg = Make(dir, "scan-define", ConfigurationType::Executable, { "Extra" }, { "main" });
// After the source is listed: the build reads it with the
// command the configuration has by then.
if (defined) cfg.defines.push_back({ "CRAFTER_TEST_EXTRA", "" });
const std::string label = defined ? "with CRAFTER_TEST_EXTRA" : "without CRAFTER_TEST_EXTRA";
const std::string error = BuildError(cfg);
Check(error.empty(), std::format("define, {}: the build succeeds: {}", label, error));
if (!error.empty()) continue;
const Implementation* main = UnitOf(cfg, dir / "main.cpp");
const std::vector<std::string> expected = defined ? std::vector<std::string>{ "Extra" } : std::vector<std::string>{};
Check(main != nullptr && Imports(*main) == expected, std::format("define, {}: main.cpp imports {}, got {}", label, Listed(expected), main == nullptr ? "no unit" : Listed(Imports(*main))));
Check(Run(cfg) == (defined ? 40 : 2), std::format("define, {}: the program is built as the define says", label));
}
}
void SwitchCase() {
const fs::path dir = Stage("switch");
Configuration on = Make(dir / "on", "scan-on", ConfigurationType::LibraryStatic, { "On" }, {});
Configuration off = Make(dir / "off", "scan-off", ConfigurationType::LibraryStatic, { "Off" }, {});
Configuration app = Make(dir / "app", "scan-switch", ConfigurationType::Executable, { "Extra" }, { "main" });
app.dependencies = { &on };
const fs::path source = dir / "app" / "main.cpp";
const auto imports = [&] {
const Implementation* main = UnitOf(app, source);
return main == nullptr ? std::vector<std::string>{ "no unit" } : Imports(*main);
};
std::string error = BuildError(app);
Check(error.empty(), std::format("switch, on: the build succeeds: {}", error));
if (!error.empty()) return;
Check(imports() == std::vector<std::string>{ "Extra" }, std::format("switch, on: WITH_EXTRA 1 imports Extra, got {}", Listed(imports())));
Check(Run(app) == 40, "switch, on: the program imports Extra");
// The header is edited: the scan that read it is taken again.
Replace(dir / "on" / "switch-off.h.in", dir / "on" / "switch.h");
const std::optional<fs::file_time_type> scannedOn = ScanTime(app, "main.cpp");
error = BuildError(app);
Check(error.empty(), std::format("switch, header edited: the build succeeds: {}", error));
if (!error.empty()) return;
Check(ScanTime(app, "main.cpp") != scannedOn, "switch, header edited: main.cpp is scanned again");
Check(imports().empty(), std::format("switch, header edited: WITH_EXTRA 0 imports nothing, got {}", Listed(imports())));
Check(Run(app) == 2, "switch, header edited: the program is compiled again without Extra");
// Back to 1, then built on the other library, whose switch.h has 0.
// Nothing the scan read has changed, but the command it read them
// with has: its include path names the other library. Checked by
// what the build read alone: this is about the scan.
Replace(fs::current_path() / "tests" / "SourceScan" / "fixture" / "switch" / "on" / "switch.h", dir / "on" / "switch.h");
error = BuildError(app);
Check(error.empty() && imports() == std::vector<std::string>{ "Extra" }, std::format("switch, header back to 1: main.cpp imports Extra again, got {} ({})", Listed(imports()), error));
app.dependencies = { &off };
const std::optional<fs::file_time_type> scannedWithOn = ScanTime(app, "main.cpp");
error = BuildError(app);
Check(error.empty(), std::format("switch, off: the build succeeds: {}", error));
if (!error.empty()) return;
Check(ScanTime(app, "main.cpp") != scannedWithOn, "switch, off: main.cpp is scanned again for the command that changed");
Check(imports().empty(), std::format("switch, off: the other library's WITH_EXTRA 0 imports nothing, got {}", Listed(imports())));
}
void MissingCase() {
const fs::path dir = Stage("missing");
Configuration cfg = Make(dir, "scan-missing", ConfigurationType::Executable, {}, { "main" });
const std::string error = BuildError(cfg);
Check(error.contains("not-there.h"), std::format("missing: the build fails naming the header it cannot find, got: {}", error));
Check(!fs::exists(ObjectPath(cfg, dir / "main.cpp")), "missing: nothing is compiled of a source that cannot be read");
}
// Runs one case: an exception it lets out fails that case, and the
// others still run.
void RunCase(std::string_view name, const std::function<void()>& run) {
try {
run();
} catch (const std::exception& e) {
Check(false, std::format("{}: threw {}", name, e.what()));
}
}
}
int main() {
RunCase("text", TextCase);
RunCase("quoted", QuotedCase);
RunCase("partition", PartitionCase);
RunCase("define", DefineCase);
RunCase("switch", SwitchCase);
RunCase("missing", MissingCase);
std::error_code ec;
fs::remove_all(Scratch, ec);
if (Failures > 0) {
std::println(std::cerr, "{} assertions failed", Failures);
return 1;
}
return 0;
}