Crafter.Build/implementations/Crafter.Build-Shader.cpp
Jorijn van der Graaf 651720e494 feat(lint): const-local and constexpr-constant rules
Two rules the AST makes possible, plus the mutation analysis behind them.

const-local reports a local that is never written. It is restricted to SCALARS
— integers, bools, enums, floating types — and that restriction is what makes
the answer exact rather than a guess: a scalar has no member functions, so the
only ways to write one are assignment, ++/--, having its address taken, or
binding to a non-const reference. All four are now tracked in the walk:

  - assignment and compound assignment visit their LEFT operand in a write
    context, the right one normally;
  - ++/-- and & write their operand;
  - a call argument is checked against the callee's parameter type, so passing
    to `const int&` or by value is a read while `int&` is a write;
  - initialising a non-const reference writes what it binds to.

For a class type a non-const method call could mutate it, and deciding that is
the whole-program analysis clang-tidy does, so those are simply out of scope
rather than guessed at.

constexpr-constant promotes a const constant whose initialiser is made only of
literals and operators, so `const int A = 1 << 4;` qualifies and
`const int B = Compute();` does not.

On this repository const-local found 103 candidates, which was too many to be
useful, and the reason was informative: most were range-for bindings and
pointer locals. `for (T* const x : …)` and `T* const p` are not spellings
anybody writes, and the useful constness for a pointer is on the pointee, which
this rule cannot advise on. Excluding both leaves 36, all plain bool or enum
locals worth fixing — isWasm, isPe, exists, writes, isC and so on. Those 36 are
fixed in this commit; the compiler verified every one.

Both rules are report-only. The analysis is exact, but adding const is a
judgement about intent as much as mechanics, and a wrong suggestion should cost
a glance rather than a build. const-local also deliberately does not become a
transform: inserting `const` before a shared type would apply it to every
declarator in a multi-declarator statement, including any that IS written.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-31 00:50:48 +02:00

126 lines
5.6 KiB
C++

// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include "SPIRV/GlslangToSpv.h"
#include "glslang/Public/ShaderLang.h"
#include "glslang/Public/ResourceLimits.h"
#include "../lib/DirStackFileIncluder.h"
module Crafter.Build:Shader_impl;
import :Shader;
import std;
namespace fs = std::filesystem;
namespace {
EShLanguage ToEShLanguage(Crafter::ShaderType t) {
switch (t) {
case Crafter::ShaderType::Vertex: return EShLangVertex;
case Crafter::ShaderType::TessControl: return EShLangTessControl;
case Crafter::ShaderType::TessEvaluation: return EShLangTessEvaluation;
case Crafter::ShaderType::Geometry: return EShLangGeometry;
case Crafter::ShaderType::Fragment: return EShLangFragment;
case Crafter::ShaderType::Compute: return EShLangCompute;
case Crafter::ShaderType::RayGen: return EShLangRayGen;
case Crafter::ShaderType::Intersect: return EShLangIntersect;
case Crafter::ShaderType::AnyHit: return EShLangAnyHit;
case Crafter::ShaderType::ClosestHit: return EShLangClosestHit;
case Crafter::ShaderType::Miss: return EShLangMiss;
case Crafter::ShaderType::Callable: return EShLangCallable;
case Crafter::ShaderType::Task: return EShLangTask;
case Crafter::ShaderType::Mesh: return EShLangMesh;
}
return EShLangVertex;
}
}
namespace Crafter {
Shader::Shader(fs::path&& path, std::string&& entrypoint, ShaderType type) : path(std::move(path)), entrypoint(std::move(entrypoint)), type(type) {
}
bool Shader::Check(const fs::path& outputDir) const {
fs::path spv = outputDir / path.filename().replace_extension("spv");
return fs::exists(spv) && fs::last_write_time(path) < fs::last_write_time(spv);
}
std::string Shader::Compile(const fs::path& outputDir, std::span<const fs::path> includeDirs) const {
EShLanguage glslangType = ToEShLanguage(type);
glslang::InitializeProcess();
// Every error path returns a non-empty string; the caller treats
// empty as success (see Crafter.Build-Clang.cpp BuildOnce shader
// worker). Prefixing with the source path is what tells the user
// which shader actually failed when several compile in parallel.
auto fail = [&](std::string_view stage, std::string log) {
glslang::FinalizeProcess();
std::string out = path.string();
out += ": ";
out += stage;
if (!log.empty()) {
out += '\n';
out += log;
}
return out;
};
const EShMessages messages = static_cast<EShMessages>(EShMsgDefault | EShMsgVulkanRules | EShMsgSpvRules);
std::ifstream fileStream(path, std::ios::in | std::ios::binary);
if (!fileStream) {
return fail("failed to open shader source", {});
}
std::ostringstream contents;
contents << fileStream.rdbuf();
std::string src = contents.str();
std::string pathStr = path.string();
const char* fileNameList[1] = { pathStr.c_str() };
const char* shaderSource = src.data();
const std::int32_t shaderSourceLen = static_cast<std::int32_t>(src.size());
glslang::TShader shader(glslangType);
shader.setStringsWithLengthsAndNames(&shaderSource, &shaderSourceLen, fileNameList, 1);
shader.setEntryPoint(entrypoint.c_str());
shader.setSourceEntryPoint(entrypoint.c_str());
shader.setEnvTarget(glslang::EShTargetSpv, glslang::EShTargetSpv_1_4);
DirStackFileIncluder includeDir;
includeDir.pushExternalLocalDirectory(path.parent_path().generic_string());
for (const fs::path& dir : includeDirs) {
includeDir.pushExternalLocalDirectory(dir.generic_string());
}
if (!shader.parse(GetDefaultResources(), 100, false, messages, includeDir)) {
return fail("GLSL parse failed", std::string(shader.getInfoLog()) + shader.getInfoDebugLog());
}
glslang::TProgram program;
program.addShader(&shader);
if (!program.link(messages)) {
return fail("GLSL link failed", std::string(program.getInfoLog()) + program.getInfoDebugLog());
}
glslang::TIntermediate* intermediate = program.getIntermediate(glslangType);
if (!intermediate) {
// Defensive: parse+link succeeded above, so this should be
// unreachable. If glslang ever changes that contract we'd
// rather surface a clear error than dereference null (the
// pre-fix bug that masqueraded as a silent SIGSEGV).
return fail("glslang produced no intermediate code", {});
}
spv::SpvBuildLogger logger;
std::vector<std::uint32_t> spirv;
glslang::GlslangToSpv(*intermediate, spirv, &logger);
std::string spvLog = logger.getAllMessages();
fs::path filename = path.filename().replace_extension("spv");
std::ofstream file(outputDir/filename, std::ios::binary);
if (!file) {
return fail("failed to open SPIR-V output", (outputDir/filename).string());
}
file.write(reinterpret_cast<const char*>(spirv.data()), spirv.size() * sizeof(std::uint32_t));
if (!spvLog.empty()) {
return fail("SPIR-V codegen reported issues", std::move(spvLog));
}
glslang::FinalizeProcess();
return {};
}
}