From 661fc96fbb50805c31e3ac69492989e54135e926 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 22:42:03 +0000 Subject: [PATCH] feat(tidy): add fairmq-clangd for editor integration - Add the option BUILD_TIDY_CLANGD (default OFF). It builds fairmq-clangd from clangdMain plus the fairmq-* module. - clangd cannot load plugins, but creates its clang-tidy checks from the same registry. Thus the checks run on the AST that clangd builds anyway, and editors show their fixes as quick fixes. - Point clangd to the resource directory of the LLVM installation it was built with, unless --resource-dir is given. - Test each check over LSP with test/tidy/ClangdCheck.py: open the input, expect a diagnostic of the check and a quick fix for it. Co-Authored-By: Claude Opus 5.5 --- fairmq/tidy/CMakeLists.txt | 20 ++++++++ fairmq/tidy/runClangd.cxx | 54 ++++++++++++++++++++ test/tidy/CMakeLists.txt | 17 +++++++ test/tidy/ClangdCheck.py | 101 +++++++++++++++++++++++++++++++++++++ 4 files changed, 192 insertions(+) create mode 100644 fairmq/tidy/runClangd.cxx create mode 100644 test/tidy/ClangdCheck.py diff --git a/fairmq/tidy/CMakeLists.txt b/fairmq/tidy/CMakeLists.txt index 7459124e..266c221b 100644 --- a/fairmq/tidy/CMakeLists.txt +++ b/fairmq/tidy/CMakeLists.txt @@ -80,3 +80,23 @@ install(TARGETS ${target} LIBRARY DESTINATION ${PROJECT_INSTALL_LIBDIR} ) +# fairmq-clangd: the clangd language server plus the fairmq-* checks. +option(BUILD_TIDY_CLANGD "Build fairmq-clangd, the clangd language server with the fairmq-* checks." OFF) +if(BUILD_TIDY_CLANGD) + if(NOT TARGET clangdMain) + message(FATAL_ERROR "BUILD_TIDY_CLANGD=ON needs the clangd libraries " + "(clangdMain, clangDaemon) of the found Clang ${LLVM_PACKAGE_VERSION} " + "installation at ${Clang_DIR}.") + endif() + set(target fairmq-clangd) + add_executable(${target} runClangd.cxx) + add_executable("${PROJECT_NAME}::${target}" ALIAS ${target}) + target_compile_definitions(${target} PRIVATE + FAIRMQ_TIDY_CLANG_RESOURCE_DIR="${FAIRMQ_TIDY_CLANG_RESOURCE_DIR}" + ) + target_link_libraries(${target} PRIVATE fairmq-tidy-module clangdMain) + install(TARGETS ${target} + EXPORT ${PROJECT_EXPORT_SET} + RUNTIME DESTINATION ${PROJECT_INSTALL_BINDIR} + ) +endif() diff --git a/fairmq/tidy/runClangd.cxx b/fairmq/tidy/runClangd.cxx new file mode 100644 index 00000000..1acc4897 --- /dev/null +++ b/fairmq/tidy/runClangd.cxx @@ -0,0 +1,54 @@ +/******************************************************************************** + * Copyright (C) 2026 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH * + * * + * This software is distributed under the terms of the * + * GNU Lesser General Public Licence (LGPL) version 3, * + * copied verbatim in the file "LICENSE" * + ********************************************************************************/ + +// fairmq-clangd is the upstream clangd language server with the FairMQ module +// linked in. clangd cannot load clang-tidy plugins, but it creates its +// clang-tidy checks from the same registry as clang-tidy. Thus the fairmq-* +// checks run on the AST that clangd builds anyway, and their fixes show as +// quick fixes in the editor. +// +// Enable the checks in a .clangd file: +// +// Diagnostics: +// ClangTidy: +// Add: ["fairmq-*"] +// FastCheckFilter: Loose # clangd >= 18 skips checks of unknown cost + +#include +#include +#include + +namespace clang::clangd { +// Defined in the clangdMain library. The header ClangdMain.h is not installed. +int clangdMain(int argc, char* argv[]); +} // namespace clang::clangd + +extern volatile int FairMQTidyModuleAnchorSource; +[[maybe_unused]] static int const fairmqModuleAnchor = FairMQTidyModuleAnchorSource; + +int main(int argc, char* argv[]) +{ + // clangd looks for the Clang builtin headers relative to its executable. + // Point it to the LLVM installation it was built with, unless the user + // gives a resource directory. + std::vector args(argv, argv + argc); + bool userResourceDir = false; + for (std::string_view arg : args) { + if (arg.rfind("--resource-dir", 0) == 0 || arg.rfind("-resource-dir", 0) == 0) { + userResourceDir = true; + } + } + std::string resourceDirArg = "--resource-dir=" FAIRMQ_TIDY_CLANG_RESOURCE_DIR; + if (!userResourceDir && argc > 0) { + args.insert(args.begin() + 1, resourceDirArg.data()); + } + auto const count = static_cast(args.size()); + args.push_back(nullptr); // argv[argc] is a null pointer + + return clang::clangd::clangdMain(count, args.data()); +} diff --git a/test/tidy/CMakeLists.txt b/test/tidy/CMakeLists.txt index 746f328a..f9c1f9fa 100644 --- a/test/tidy/CMakeLists.txt +++ b/test/tidy/CMakeLists.txt @@ -39,6 +39,13 @@ if(NOT FAIRMQ_TIDY_CLANG_TIDY) "Skipping the fairmq-tidy plugin tests.") endif() +if(BUILD_TIDY_CLANGD) + find_package(Python3 COMPONENTS Interpreter) + if(NOT Python3_FOUND) + message(STATUS "Python 3 not found. Skipping the fairmq-clangd tests.") + endif() +endif() + file(GLOB inputs CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/fairmq-*.cxx") foreach(input IN LISTS inputs) get_filename_component(check "${input}" NAME_WE) @@ -67,4 +74,14 @@ foreach(input IN LISTS inputs) ) set_tests_properties("tidy.plugin.${check}" PROPERTIES TIMEOUT 120) endif() + + if(BUILD_TIDY_CLANGD AND Python3_FOUND) + add_test(NAME "tidy.clangd.${check}" + COMMAND Python3::Interpreter "${CMAKE_CURRENT_SOURCE_DIR}/ClangdCheck.py" + "$" "${check}" "${input}" + "${CMAKE_CURRENT_BINARY_DIR}/flags.txt" + "${CMAKE_CURRENT_BINARY_DIR}/clangd/${check}" + ) + set_tests_properties("tidy.clangd.${check}" PROPERTIES TIMEOUT 120) + endif() endforeach() diff --git a/test/tidy/ClangdCheck.py b/test/tidy/ClangdCheck.py new file mode 100644 index 00000000..34466a94 --- /dev/null +++ b/test/tidy/ClangdCheck.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +################################################################################ +# Copyright (C) 2026 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH # +# # +# This software is distributed under the terms of the # +# GNU Lesser General Public Licence (LGPL) version 3, # +# copied verbatim in the file "LICENSE" # +################################################################################ +"""Runs fairmq-clangd as a language server on one test input. + +The test passes if clangd publishes a diagnostic of the given check and offers +a quick fix for it, i.e. the fairmq-* checks work in an editor. + +Usage: ClangdCheck.py +""" + +import json +import pathlib +import shutil +import subprocess +import sys + + +def main(): + clangd, check, source, flags, workdir = sys.argv[1:6] + work = pathlib.Path(workdir) + shutil.rmtree(work, ignore_errors=True) + work.mkdir(parents=True) + src = work / pathlib.Path(source).name + shutil.copy(source, src) + args = [line for line in pathlib.Path(flags).read_text().splitlines() if line] + (work / "compile_commands.json").write_text(json.dumps( + [{"directory": str(work), "file": str(src), "arguments": ["clang++", *args, "-c", str(src)]}])) + (work / ".clangd").write_text( + "Diagnostics:\n ClangTidy:\n Add: [%s]\n FastCheckFilter: Loose\n" % check) + + proc = subprocess.Popen([clangd, "--log=error", f"--compile-commands-dir={work}"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE) + next_id = 0 + + def send(method, params, notification=False): + nonlocal next_id + msg = {"jsonrpc": "2.0", "method": method, "params": params} + if not notification: + next_id += 1 + msg["id"] = next_id + body = json.dumps(msg).encode() + proc.stdin.write(b"Content-Length: %d\r\n\r\n" % len(body) + body) + proc.stdin.flush() + return next_id + + def receive(predicate): + while True: + length = None + while True: + line = proc.stdout.readline() + if not line: + raise RuntimeError("clangd exited") + if line in (b"\r\n", b"\n"): + break + if line.lower().startswith(b"content-length:"): + length = int(line.split(b":")[1]) + msg = json.loads(proc.stdout.read(length)) + if predicate(msg): + return msg + + uri = src.as_uri() + try: + init = send("initialize", { + "processId": None, + "rootUri": work.as_uri(), + "capabilities": {"textDocument": {"codeAction": {"codeActionLiteralSupport": { + "codeActionKind": {"valueSet": ["quickfix"]}}}}}, + }) + receive(lambda m: m.get("id") == init) + send("initialized", {}, notification=True) + send("textDocument/didOpen", {"textDocument": { + "uri": uri, "languageId": "cpp", "version": 1, "text": src.read_text()}}, + notification=True) + diags = receive(lambda m: m.get("method") == "textDocument/publishDiagnostics" + and m["params"]["uri"] == uri)["params"]["diagnostics"] + found = [d for d in diags if d.get("code") == check] + if not found: + print(f"no {check} diagnostic, got:", json.dumps(diags, indent=1)) + return 1 + req = send("textDocument/codeAction", { + "textDocument": {"uri": uri}, "range": found[0]["range"], + "context": {"diagnostics": [found[0]]}}) + actions = receive(lambda m: m.get("id") == req)["result"] + if not any(a.get("kind") == "quickfix" and "edit" in a for a in actions): + print("no quick fix, got:", json.dumps(actions, indent=1)) + return 1 + print(f"{len(found)} {check} diagnostics, quick fix: {actions[0]['title']}") + send("shutdown", None) + return 0 + finally: + proc.kill() + + +if __name__ == "__main__": + sys.exit(main())