Crafter.Build/interfaces/Crafter.Build-Lint.cppm

72 lines
3.8 KiB
Text
Raw Permalink Normal View History

2026-07-23 01:24:42 +02:00
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Crafter.Build:Lint;
import std;
import :Clang;
export namespace Crafter {
enum class LintMode {
// `lint`: diagnose only; transform output becomes would-reformat
// findings. Never writes. The default.
Report,
// `format --check`: dry run; record the files that would change.
Check,
// `format`: rewrite changed files in place.
Apply,
};
struct RunLintOptions {
// Rule-name globs ('*', '?'); empty = every registered rule.
std::vector<std::string> globs;
// Enumerate matching rule names without running them.
bool listOnly = false;
LintMode mode = LintMode::Report;
feat(lint): AST layer over libclang cursors Adds LintContext::Decls() — clang's view of the declarations written in the file — plus AddAstLintRule to register a rule that reads it. No rule uses it yet; the three that will are migrated separately. The declarations come back as a flat vector with parent indices rather than an opaque cursor handle: no lifetimes cross the project-DLL boundary, no callback hops back into project.so per node, and "is this at namespace scope or inside a function?" becomes an index lookup instead of a hand-rolled brace stack. Three things had to be solved for this to work at all on this codebase. libclang cannot see through `export`. A C++20 export declaration has no CXCursorKind, so `export namespace Crafter { … }` arrives as a childless CXCursor_UnexposedDecl and clang_visitChildren does not descend. Five of the eleven interfaces here are written that way — 677 lines, including Configuration and LintContext, yielding zero usable cursors. A plain `namespace` IS descended into, so the fix is to blank the keyword before parsing, byte-length preserving so every line and column still lands on the original file. `export module` is left alone or the unit stops being a module interface. Verified end-to-end against a fixture whose asserted line numbers match the unblanked file. PCMs are flag-locked, so each file has to parse with the flags that built it. CollectConfigSources now records which Configuration owns each source instead of flattening to a set, because three regimes coexist: the library, each test (carrying its own target, defines and -march), and project.cpp, which Build never touches and which therefore gets no command at all. libclang resolves its builtin headers relative to its own install path, which need not match the clang++ that wrote the PCMs. When it doesn't, every parse dies on "'stddef.h' file not found", so -resource-dir is passed explicitly from `clang++ -print-resource-dir`. Two flags on each declaration replace what would otherwise become more substring denylists: isExternC, and isForeignApi for a declaration that binds to an entity declared outside the project root — resolved through clang_getCursorReferenced and the same inside-the-root test the dependency walk already uses. Parameters and fields inherit it, so an exemption covers a whole signature rather than the one node that named the foreign entity. Failure is never silent. A fatal diagnostic leaves a fragment that is indistinguishable from a file declaring nothing, so it is reported as an error instead: the rule is skipped, a finding explains why, and summary.errors makes the run fail. --no-ast opts out deliberately and exits normally. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:30:41 +02:00
// Skip rules registered with AddAstLintRule instead of building the
// module PCMs they need. The escape hatch for a fresh clone where the
// token-based rules are wanted immediately; the run then exits normally
// rather than erroring, so it must be asked for explicitly.
bool noAst = false;
2026-07-23 01:24:42 +02:00
// Absolute path of the loaded project.cpp. It is linted too, and its
// parent directory is the project root that decides which dependency
// Configurations contribute rules/files (GitProject / cache-dir deps
feat: let a project file return several configurations A project.cpp described one configuration: CrafterBuildProject returns a Configuration by value, and anything else the project wanted built had to be among that one's dependencies. There it was built as part of that configuration's graph: under the check that a graph builds each module once, with its libraries handed up to whatever links that configuration, and with its tests and scripts out of reach of `test` and `run`. Jorijn asked for a project.cpp that can return several unrelated configurations which all get built, and suggested a separate entry point, so that no existing project file breaks. A project file now defines one of two functions. CrafterBuildProject is as it was. CrafterBuildConfigurations returns std::vector<Configuration*>: pointers to configurations the file keeps alive itself, or that GitProject and LocalProject gave it. The two have different names because the loader finds the entry point by its C symbol, which carries no return type, so one name with two return types would be called as whichever the loader guessed. They are pointers because a project file takes pointers between its configurations, for `dependencies` and for a test's, before it returns them, and a vector of values would move them. LoadConfigurations loads a project file with either entry point and returns the list. A CrafterBuildProject's Configuration comes back as a list of one, constructed by the call where the loader keeps it for the rest of the process; LoadProjectFromRoot, which did that for a sibling's, leaves it to LoadConfigurations, and the project cache holds the lists without owning a Configuration. The Configuration of the project crafter-build is pointed at is kept that long as well, where it was a local of Run(). LoadConfigurations throws for a file that defines both functions or neither, and for a CrafterBuildConfigurations that returns nothing, a null pointer or one configuration twice. It also throws for one that returns a configuration a project loaded through GitProject or LocalProject keeps to itself, which the loader now takes down when it loads that project's file: what the configurations the file returned led to through `dependencies` or through their tests, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps. Returned from here, such a configuration would count as this file's own to `test` and `run`, and only the configurations a project file returns are rebased onto its directory. LoadProject stays, for a caller that wants a CrafterBuildProject's Configuration by value, and throws for a file with the other entry point. GitProject and LocalProject keep, per spec and args, the list a sibling's file returned, and return the first one unless the spec's new `configuration` names another by Configuration::name. Every configuration of the list is rebased onto the sibling's directory, except one that another project's file had returned before, which was rebased onto that project's. Specs that differ only in the name they pick share one load. A name the sibling does not have throws, listing the names it has, and a name two of its configurations share throws too. A `#pragma crafter dependency` gets the first. BuildAll builds the returned configurations in one pass. Each is built by Build(), as a project's one configuration is, the first on the calling thread and each other one on a thread of its own, and its result then goes into the record of the pass under its PcmDir, where Build() looks for a dependency. One that another of them is built on is built before that other starts, which then finds it in the record: started beside it, the other would not find it there yet and would build it a second time. A configuration is not put into the record before it is built, because a dependency of its own that is built into the same directory would be handed its unfinished build and wait for it, while it waits for the dependency. All of them are built to the end, and the errors come back in the order given, each message once; an exception a build throws comes back as an error that names the configuration, where Run() printed the exception's own text for a project's one configuration. Refused before anything is built: two that would be built into one directory, which would be two builds writing the same files at once; several that are each built on something of another's directory, so that none could be built first; and one that is built on something of its own directory when another is built on that directory as well, since the record holds one result for a directory and the other could be given either. One shortcut is in it. A wasm executable that declares wasmVariants builds what it is built on once more per variant, and says which variant by rewriting those configurations in place, at the end of its Build(). A library that two returned configurations share would change under the one still building its baseline, so with such an executable anywhere in the graph BuildAll builds the configurations one after the other, on the calling thread. Keeping them side by side takes a variant driver that does not rewrite configurations other builds read, which this commit does not attempt. Run() works on the list. A build builds all of it. `test` runs the tests, and `run` offers the scripts, of the ones in it that the project file made itself. One that another project's file returned to GitProject or LocalProject, and that this file returns in turn, is built with the rest, but its tests and scripts stay that project's, so `run` still reaches only the scripts of the project crafter-build was pointed at. What the list itself rules out Run() refuses once the project file has loaded, before any of the list is built and before AGENTS.md is written: for a build, `-r`, `install` and `bundle` whatever BuildAll refuses a list for, and for `test`, which builds its tests with Build() and never comes to BuildAll, two returned configurations of one directory. BuildAll makes its refusals again for whoever calls it. A script is handed the configuration it is declared on. `lint` and `format` walk from every returned configuration and keep, as before, the configurations in the project's directory: the returned ones first, in the order the file returned them, then what they depend on, so that of two returned ones that register a rule under one name the earlier one's runs. `-r` runs the executable when exactly one of them is one, and `install` and `bundle` export the one that is packaged as a Flatpak; with more than one candidate each refuses and names them, `-r` once everything is built and `install` and `bundle` before anything is. AGENTS.md takes the notes that the dependencyNotes of each returned configuration the file made itself selects among what that one is built against, and the file's pragma tooling and a returned configuration of another project go by the widest of those settings. There, a configuration is another project's when GitProject or LocalProject loaded it from another project file than the one whose AGENTS.md is written, two files being one when they resolve to one path, so UpdateAgentsMd still reads the setting of a Configuration one of the two returned when it is given that Configuration's own project file. For that, RunTests, RunLint, RunScript and UpdateAgentsMd each gained an overload that takes the list, and the one that takes a single Configuration calls it with a list of one. SetParentProject gained one too, and ParentLib searches the graph of every configuration it was given. BuildAll, RunTests and RunScript count a configuration the list names twice once. The tests of several configurations share what one configuration's had to itself: AddTest names a test's sources, tests/<name>, and its build directory after the test and its compile state, not after the configuration that declares it. Two configurations that each declare a test of one name, compiled alike, would have RunTests build both in that one directory, each with the dependencies of its own declaration. RunTests fails both without building either, and each failure names the configurations. It compares tests of different configurations only, so a project of one configuration is treated as it was. The --help text names the second entry point, says what -r, install and bundle do with several configurations, and speaks of the project file's entry point as what gets the project args, where it named CrafterBuildProject. AGENTS.template.md says that a project.cpp returns one configuration or several, that Run() works on the list and what a new verb has to decide about it, which configurations have their path rebased, and that the scripts of a returned configuration of another project cannot be run. Two of its notes named LoadProject as what loads a project.cpp for crafter-build, which Run(), GitProject and LocalProject no longer call, and speak of the load now. Its rule for the link flags of a test that loads a project file names the ways a test loads one, where it named LoadProject, and its entry for `:Script` speaks of the `scripts` of the configurations the driver is given, where it named `cfg.scripts`. Its entry for `:Platform` names LoadConfigurations beside LoadProject. That entry also said that `:Platform` holds all OS-specific code, which it did not before this range either, :Agents, :Progress, :Lint and :Clang including POSIX headers of their own, and no longer says so. The bug-prover lens's section names BuildAll's threads and LoadConfigurations. Not in this commit: a way to say which executable -r runs or which app install and bundle export when there are several, and a keyword that lets a `#pragma crafter dependency` name a configuration.
2026-11-15 02:16:06 +01:00
// are foreign code and skipped). Empty => fall back to cfg.path, of
// several configurations the first one's.
2026-07-23 01:24:42 +02:00
std::filesystem::path projectFile;
};
struct LintSummary {
std::vector<LintFinding> findings; // sorted by (file, line); filled in every mode
// Apply: files rewritten on disk. Report/Check: files a transform
// would change. The `format` verb's exit code keys off this in Check
// mode; formatting files in Apply mode is success.
std::vector<std::filesystem::path> changedFiles;
std::size_t filesLinted = 0;
std::size_t rulesRun = 0; // rules remaining after glob filter
feat(lint): libclang-backed token layer Adds LintContext::Tokens() and friends, backed by clang_tokenize, as the substrate the rules will move onto. Nothing consumes it yet. libclang is dlopen'd rather than linked: -lclang would break the mingw and MSVC cross-builds at link time and would put a libclang.so.NN runtime dependency into the otherwise self-contained release tarballs. The clang-c header is used for its declarations only, and the function-pointer table is typed with decltype so the signatures cannot drift from the real API. Three properties this buys that the hand-rolled scanners could not have: - a raw string literal or block comment is ONE token, so the documented "raw string literals are not recognized" limitation goes away; - `//` inside a literal is not a comment, so LineHasComment() replaces the Line(n).contains("//") probes that false-positive on it; - tokens cover preprocessor branches that are inactive for the host, since clang_tokenize lexes rather than evaluates #if. Token rules therefore keep seeing every platform's code, which an AST could not offer. The parse backing the tokenizer is expected to fail on module units — no PCMs, no build flags — and that is fine, because lexing has no semantic prerequisites. Verified in the new tests. LintSummary::Clean() now counts `errors`. It previously ignored them, so an infrastructure failure that produced no findings reported clean and exited 0; a missing libclang would have been exactly that. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 02:54:38 +02:00
// Rule exceptions, write failures, and infrastructure failures such as
// libclang not loading. Counted in Clean() so a run that could not do
// its job never looks like a run that found nothing.
std::size_t errors = 0;
2026-07-23 01:24:42 +02:00
bool noRulesDefined = false; // project registered no rules at all
// Host-side only (like TestSummary::AllPassed), safe as in-class inline.
feat(lint): libclang-backed token layer Adds LintContext::Tokens() and friends, backed by clang_tokenize, as the substrate the rules will move onto. Nothing consumes it yet. libclang is dlopen'd rather than linked: -lclang would break the mingw and MSVC cross-builds at link time and would put a libclang.so.NN runtime dependency into the otherwise self-contained release tarballs. The clang-c header is used for its declarations only, and the function-pointer table is typed with decltype so the signatures cannot drift from the real API. Three properties this buys that the hand-rolled scanners could not have: - a raw string literal or block comment is ONE token, so the documented "raw string literals are not recognized" limitation goes away; - `//` inside a literal is not a comment, so LineHasComment() replaces the Line(n).contains("//") probes that false-positive on it; - tokens cover preprocessor branches that are inactive for the host, since clang_tokenize lexes rather than evaluates #if. Token rules therefore keep seeing every platform's code, which an AST could not offer. The parse backing the tokenizer is expected to fail on module units — no PCMs, no build flags — and that is fine, because lexing has no semantic prerequisites. Verified in the new tests. LintSummary::Clean() now counts `errors`. It previously ignored them, so an infrastructure failure that produced no findings reported clean and exited 0; a missing libclang would have been exactly that. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 02:54:38 +02:00
bool Clean() const { return findings.empty() && !noRulesDefined && errors == 0; }
2026-07-23 01:24:42 +02:00
};
// Run the project's lint rules over its own sources: module interfaces
// (+ partitions), implementations, cFiles, cuda, shaders, declared tests'
// sources, and project.cpp itself — for the root Configuration plus every
// transitive dependency whose path lies inside the project root. Rules
// run in registration order per file, each seeing the previous rule's
// transform output; a rule that throws is reverted and surfaced as a
// finding + error. Only Apply mode writes to disk, and only files whose
// final content differs from the original. Prints per-mode output:
// findings compiler-style (Report), would-change paths (Check), or
// formatted paths (Apply), plus a summary line.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
LintSummary RunLint(Configuration& projectCfg, const RunLintOptions& opts);
feat: let a project file return several configurations A project.cpp described one configuration: CrafterBuildProject returns a Configuration by value, and anything else the project wanted built had to be among that one's dependencies. There it was built as part of that configuration's graph: under the check that a graph builds each module once, with its libraries handed up to whatever links that configuration, and with its tests and scripts out of reach of `test` and `run`. Jorijn asked for a project.cpp that can return several unrelated configurations which all get built, and suggested a separate entry point, so that no existing project file breaks. A project file now defines one of two functions. CrafterBuildProject is as it was. CrafterBuildConfigurations returns std::vector<Configuration*>: pointers to configurations the file keeps alive itself, or that GitProject and LocalProject gave it. The two have different names because the loader finds the entry point by its C symbol, which carries no return type, so one name with two return types would be called as whichever the loader guessed. They are pointers because a project file takes pointers between its configurations, for `dependencies` and for a test's, before it returns them, and a vector of values would move them. LoadConfigurations loads a project file with either entry point and returns the list. A CrafterBuildProject's Configuration comes back as a list of one, constructed by the call where the loader keeps it for the rest of the process; LoadProjectFromRoot, which did that for a sibling's, leaves it to LoadConfigurations, and the project cache holds the lists without owning a Configuration. The Configuration of the project crafter-build is pointed at is kept that long as well, where it was a local of Run(). LoadConfigurations throws for a file that defines both functions or neither, and for a CrafterBuildConfigurations that returns nothing, a null pointer or one configuration twice. It also throws for one that returns a configuration a project loaded through GitProject or LocalProject keeps to itself, which the loader now takes down when it loads that project's file: what the configurations the file returned led to through `dependencies` or through their tests, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps. Returned from here, such a configuration would count as this file's own to `test` and `run`, and only the configurations a project file returns are rebased onto its directory. LoadProject stays, for a caller that wants a CrafterBuildProject's Configuration by value, and throws for a file with the other entry point. GitProject and LocalProject keep, per spec and args, the list a sibling's file returned, and return the first one unless the spec's new `configuration` names another by Configuration::name. Every configuration of the list is rebased onto the sibling's directory, except one that another project's file had returned before, which was rebased onto that project's. Specs that differ only in the name they pick share one load. A name the sibling does not have throws, listing the names it has, and a name two of its configurations share throws too. A `#pragma crafter dependency` gets the first. BuildAll builds the returned configurations in one pass. Each is built by Build(), as a project's one configuration is, the first on the calling thread and each other one on a thread of its own, and its result then goes into the record of the pass under its PcmDir, where Build() looks for a dependency. One that another of them is built on is built before that other starts, which then finds it in the record: started beside it, the other would not find it there yet and would build it a second time. A configuration is not put into the record before it is built, because a dependency of its own that is built into the same directory would be handed its unfinished build and wait for it, while it waits for the dependency. All of them are built to the end, and the errors come back in the order given, each message once; an exception a build throws comes back as an error that names the configuration, where Run() printed the exception's own text for a project's one configuration. Refused before anything is built: two that would be built into one directory, which would be two builds writing the same files at once; several that are each built on something of another's directory, so that none could be built first; and one that is built on something of its own directory when another is built on that directory as well, since the record holds one result for a directory and the other could be given either. One shortcut is in it. A wasm executable that declares wasmVariants builds what it is built on once more per variant, and says which variant by rewriting those configurations in place, at the end of its Build(). A library that two returned configurations share would change under the one still building its baseline, so with such an executable anywhere in the graph BuildAll builds the configurations one after the other, on the calling thread. Keeping them side by side takes a variant driver that does not rewrite configurations other builds read, which this commit does not attempt. Run() works on the list. A build builds all of it. `test` runs the tests, and `run` offers the scripts, of the ones in it that the project file made itself. One that another project's file returned to GitProject or LocalProject, and that this file returns in turn, is built with the rest, but its tests and scripts stay that project's, so `run` still reaches only the scripts of the project crafter-build was pointed at. What the list itself rules out Run() refuses once the project file has loaded, before any of the list is built and before AGENTS.md is written: for a build, `-r`, `install` and `bundle` whatever BuildAll refuses a list for, and for `test`, which builds its tests with Build() and never comes to BuildAll, two returned configurations of one directory. BuildAll makes its refusals again for whoever calls it. A script is handed the configuration it is declared on. `lint` and `format` walk from every returned configuration and keep, as before, the configurations in the project's directory: the returned ones first, in the order the file returned them, then what they depend on, so that of two returned ones that register a rule under one name the earlier one's runs. `-r` runs the executable when exactly one of them is one, and `install` and `bundle` export the one that is packaged as a Flatpak; with more than one candidate each refuses and names them, `-r` once everything is built and `install` and `bundle` before anything is. AGENTS.md takes the notes that the dependencyNotes of each returned configuration the file made itself selects among what that one is built against, and the file's pragma tooling and a returned configuration of another project go by the widest of those settings. There, a configuration is another project's when GitProject or LocalProject loaded it from another project file than the one whose AGENTS.md is written, two files being one when they resolve to one path, so UpdateAgentsMd still reads the setting of a Configuration one of the two returned when it is given that Configuration's own project file. For that, RunTests, RunLint, RunScript and UpdateAgentsMd each gained an overload that takes the list, and the one that takes a single Configuration calls it with a list of one. SetParentProject gained one too, and ParentLib searches the graph of every configuration it was given. BuildAll, RunTests and RunScript count a configuration the list names twice once. The tests of several configurations share what one configuration's had to itself: AddTest names a test's sources, tests/<name>, and its build directory after the test and its compile state, not after the configuration that declares it. Two configurations that each declare a test of one name, compiled alike, would have RunTests build both in that one directory, each with the dependencies of its own declaration. RunTests fails both without building either, and each failure names the configurations. It compares tests of different configurations only, so a project of one configuration is treated as it was. The --help text names the second entry point, says what -r, install and bundle do with several configurations, and speaks of the project file's entry point as what gets the project args, where it named CrafterBuildProject. AGENTS.template.md says that a project.cpp returns one configuration or several, that Run() works on the list and what a new verb has to decide about it, which configurations have their path rebased, and that the scripts of a returned configuration of another project cannot be run. Two of its notes named LoadProject as what loads a project.cpp for crafter-build, which Run(), GitProject and LocalProject no longer call, and speak of the load now. Its rule for the link flags of a test that loads a project file names the ways a test loads one, where it named LoadProject, and its entry for `:Script` speaks of the `scripts` of the configurations the driver is given, where it named `cfg.scripts`. Its entry for `:Platform` names LoadConfigurations beside LoadProject. That entry also said that `:Platform` holds all OS-specific code, which it did not before this range either, :Agents, :Progress, :Lint and :Clang including POSIX headers of their own, and no longer says so. The bug-prover lens's section names BuildAll's threads and LoadConfigurations. Not in this commit: a way to say which executable -r runs or which app install and bundle export when there are several, and a keyword that lets a `#pragma crafter dependency` name a configuration.
2026-11-15 02:16:06 +01:00
// The same for the several configurations a project file returns, as
// one run over all of them: each is a root, and the roots come before
// what any of them depends on, in the order given. A rule two of them
// register under one name runs once, as the first of them in that order
// registered it, and a source two of them reach is linted once.
LintSummary RunLint(std::span<Configuration* const> configurations, const RunLintOptions& opts);
2026-07-23 01:24:42 +02:00
}