refactor(tidy)!: rebuild fairmq-tidy on top of clang-tidy

- Implement the checks as a clang-tidy module (object library
  fairmq-tidy-module) instead of a standalone LibTooling program.
- Build fairmq-tidy from clangTidyMain plus the module. It gets all
  clang-tidy features: --fix, --export-fixes, .clang-tidy files, NOLINT,
  header filter, and the upstream checks on the same parse.
- Without a --checks option, add fairmq-* to the configured checks.
- Point the driver to the resource directory of the LLVM installation it
  was built with, so it finds the Clang builtin headers from any install
  location. The -I hint in fairmq_target_tidy() is no longer necessary.
- Add the include directories of LLVM and Clang. The old target compiled
  only where they are in /usr/include.
- Port fairmq-modernize-nonnamespaced-types. Match deprecated global
  aliases into fair::mq instead of the name prefix "FairMQ": this also
  finds e.g. InputMsgCallback and skips aliases that are not deprecated.
  Match only the TypedefTypeLoc, so each use is reported once.

BREAKING CHANGE: fairmq-tidy takes the options of clang-tidy and reads
.clang-tidy files. With no .clang-tidy file it now also runs the default
clang-tidy checks (clang-diagnostic-*, clang-analyzer-*).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Claude
2026-11-09 22:38:46 +00:00
parent 2fea52a071
commit cbcd0d3324
8 changed files with 223 additions and 199 deletions

View File

@@ -1,24 +1,61 @@
################################################################################
# Copyright (C) 2021 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH #
# Copyright (C) 2021-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" #
################################################################################
set(target fairmq-tidy)
add_executable(${target}
ModernizeNonNamespacedTypes.h
Tool.h
runTool.cpp
if(NOT TARGET clangTidy OR NOT TARGET clangTidyMain)
message(FATAL_ERROR "BUILD_TIDY_TOOL=ON needs the clang-tidy libraries "
"(clangTidy, clangTidyMain) of the found Clang ${LLVM_PACKAGE_VERSION} "
"installation at ${Clang_DIR}. Install the clang-tidy development package "
"(e.g. libclang-<version>-dev on Debian/Ubuntu).")
endif()
# The clang driver searches its builtin headers relative to the executable.
# Remember the resource directory of the LLVM installation that we build
# against, so that fairmq-tidy works from any install location.
foreach(candidate IN ITEMS "${LLVM_LIBRARY_DIR}/clang/${LLVM_VERSION_MAJOR}"
"${LLVM_LIBRARY_DIR}/clang/${LLVM_PACKAGE_VERSION}")
if(EXISTS "${candidate}/include/stddef.h")
set(FAIRMQ_TIDY_CLANG_RESOURCE_DIR "${candidate}"
CACHE PATH "Clang resource directory used by fairmq-tidy")
break()
endif()
endforeach()
if(NOT FAIRMQ_TIDY_CLANG_RESOURCE_DIR)
message(FATAL_ERROR "Cannot find the Clang resource directory below "
"${LLVM_LIBRARY_DIR}/clang. Set FAIRMQ_TIDY_CLANG_RESOURCE_DIR to the "
"output of `clang -print-resource-dir`.")
endif()
# The fairmq-* checks as a clang-tidy module.
add_library(fairmq-tidy-module OBJECT
Module.cxx
NonNamespacedTypesCheck.cxx
NonNamespacedTypesCheck.h
)
add_executable("${PROJECT_NAME}::${target}" ALIAS ${target})
target_compile_features(${target} PRIVATE cxx_std_17)
target_link_libraries(${target} PRIVATE clang-cpp LLVM)
target_include_directories(${target} PRIVATE
target_compile_features(fairmq-tidy-module PUBLIC cxx_std_17)
target_include_directories(fairmq-tidy-module
SYSTEM PUBLIC ${LLVM_INCLUDE_DIRS} ${CLANG_INCLUDE_DIRS}
)
target_include_directories(fairmq-tidy-module PUBLIC
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>
$<BUILD_INTERFACE:${PROJECT_BINARY_DIR}>
)
if(NOT LLVM_ENABLE_RTTI)
target_compile_options(fairmq-tidy-module PUBLIC -fno-rtti)
endif()
set_target_properties(fairmq-tidy-module PROPERTIES POSITION_INDEPENDENT_CODE ON)
# fairmq-tidy: the clang-tidy driver plus the fairmq-* checks.
set(target fairmq-tidy)
add_executable(${target} runTidy.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 clangTidyMain)
install(TARGETS ${target}
EXPORT ${PROJECT_EXPORT_SET}
RUNTIME DESTINATION ${PROJECT_INSTALL_BINDIR}

View File

@@ -1,73 +0,0 @@
/********************************************************************************
* Copyright (C) 2021 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" *
********************************************************************************/
#ifndef FAIR_MQ_TIDY_MODERNIZENONNAMESPACEDTYPES
#define FAIR_MQ_TIDY_MODERNIZENONNAMESPACEDTYPES
#include <clang/AST/AST.h>
#include <clang/ASTMatchers/ASTMatchFinder.h>
#include <clang/ASTMatchers/ASTMatchers.h>
#include <clang/Basic/Diagnostic.h>
#include <llvm/Support/Casting.h>
namespace fair::mq::tidy {
struct ModernizeNonNamespacedTypes
{
ModernizeNonNamespacedTypes() = delete;
ModernizeNonNamespacedTypes(clang::ast_matchers::MatchFinder& finder)
{
using namespace clang::ast_matchers;
// https://clang.llvm.org/docs/LibASTMatchersReference.html
finder.addMatcher(
typeLoc(loc(qualType(hasDeclaration(namedDecl(matchesName("::FairMQ")).bind("decl")))))
.bind("loc"),
&fCallback);
}
struct Callback : clang::ast_matchers::MatchFinder::MatchCallback
{
auto run(clang::ast_matchers::MatchFinder::MatchResult const& m) -> void final
{
using namespace clang;
auto const type_loc(m.Nodes.getNodeAs<TypeLoc>("loc"));
auto const named_decl(m.Nodes.getNodeAs<NamedDecl>("decl"));
if (auto const type_alias_decl = m.Nodes.getNodeAs<TypeAliasDecl>("decl")) {
auto const underlying_type(type_alias_decl->getUnderlyingType());
if (underlying_type.getAsString().rfind("fair::mq::", 0) == 0) {
auto& diag_engine(m.Context->getDiagnostics());
auto const location(type_loc->getBeginLoc());
if (location.isValid()) {
auto builder(diag_engine.Report(
location,
diag_engine.getCustomDiagID(
DiagnosticsEngine::Warning,
"Modernize non-namespaced type %0 with %1. [%2]")));
builder << named_decl;
builder << underlying_type;
builder << "fairmq-modernize-nonnamespaced-types";
builder.AddFixItHint(FixItHint::CreateReplacement(
type_loc->getSourceRange(), underlying_type.getAsString()));
}
}
}
}
};
private:
Callback fCallback;
};
} // namespace fair::mq::tidy
#endif /* FAIR_MQ_TIDY_MODERNIZENONNAMESPACEDTYPES */

35
fairmq/tidy/Module.cxx Normal file
View File

@@ -0,0 +1,35 @@
/********************************************************************************
* 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" *
********************************************************************************/
#include <fairmq/tidy/NonNamespacedTypesCheck.h>
#include <clang-tidy/ClangTidyModule.h>
#include <clang-tidy/ClangTidyModuleRegistry.h>
namespace fair::mq::tidy {
/// The `fairmq-*` checks as a clang-tidy module. Every front end links this
/// module: the `fairmq-tidy` executable and, later, the plugin and clangd.
class Module : public clang::tidy::ClangTidyModule
{
public:
void addCheckFactories(clang::tidy::ClangTidyCheckFactories& factories) override
{
factories.registerCheck<NonNamespacedTypesCheck>("fairmq-modernize-nonnamespaced-types");
}
};
} // namespace fair::mq::tidy
static clang::tidy::ClangTidyModuleRegistry::Add<fair::mq::tidy::Module>
fairmqModule("fairmq-module", "Adds the FairMQ checks.");
// A front end that links this module statically references this symbol, so
// the linker keeps the registration above.
// NOLINTNEXTLINE(misc-use-internal-linkage)
volatile int FairMQTidyModuleAnchorSource = 0;

View File

@@ -0,0 +1,54 @@
/********************************************************************************
* Copyright (C) 2021-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" *
********************************************************************************/
#include <fairmq/tidy/NonNamespacedTypesCheck.h>
#include <clang/AST/QualTypeNames.h>
#include <clang/ASTMatchers/ASTMatchFinder.h>
#include <clang/ASTMatchers/ASTMatchers.h>
namespace fair::mq::tidy {
using namespace clang;
using namespace clang::ast_matchers;
void NonNamespacedTypesCheck::registerMatchers(MatchFinder* finder)
{
// Match the TypedefTypeLoc only. Its ElaboratedTypeLoc wrapper would
// report the same spelling a second time.
finder->addMatcher(
typeLoc(loc(typedefType(hasDeclaration(
typedefNameDecl(hasDeclContext(translationUnitDecl()), hasAttr(attr::Deprecated))
.bind("alias")))))
.bind("loc"),
this);
}
void NonNamespacedTypesCheck::check(MatchFinder::MatchResult const& result)
{
auto const* alias = result.Nodes.getNodeAs<TypedefNameDecl>("alias");
auto const* loc = result.Nodes.getNodeAs<TypeLoc>("loc");
auto const begin = loc->getBeginLoc();
if (begin.isInvalid() || begin.isMacroID()) {
return;
}
PrintingPolicy policy(getLangOpts());
policy.SuppressScope = false;
policy.SuppressUnwrittenScope = true;
auto const replacement =
TypeName::getFullyQualifiedName(alias->getUnderlyingType(), *result.Context, policy);
if (!StringRef(replacement).starts_with("fair::mq::")) {
return;
}
diag(begin, "%0 is deprecated; use '%1'")
<< alias << replacement << FixItHint::CreateReplacement(loc->getSourceRange(), replacement);
}
} // namespace fair::mq::tidy

View File

@@ -0,0 +1,36 @@
/********************************************************************************
* Copyright (C) 2021-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" *
********************************************************************************/
#ifndef FAIR_MQ_TIDY_NONNAMESPACEDTYPESCHECK_H
#define FAIR_MQ_TIDY_NONNAMESPACEDTYPESCHECK_H
#include <clang-tidy/ClangTidyCheck.h>
namespace fair::mq::tidy {
/// Finds uses of the deprecated global type aliases (e.g. `FairMQDevice`) and
/// replaces them with the namespaced type they alias (e.g. `fair::mq::Device`).
///
/// A global alias qualifies if it is marked `[[deprecated]]` and its target
/// type lives in namespace `fair::mq`.
class NonNamespacedTypesCheck : public clang::tidy::ClangTidyCheck
{
public:
using ClangTidyCheck::ClangTidyCheck;
bool isLanguageVersionSupported(clang::LangOptions const& opts) const override
{
return opts.CPlusPlus17;
}
void registerMatchers(clang::ast_matchers::MatchFinder* finder) override;
void check(clang::ast_matchers::MatchFinder::MatchResult const& result) override;
};
} // namespace fair::mq::tidy
#endif /* FAIR_MQ_TIDY_NONNAMESPACEDTYPESCHECK_H */

View File

@@ -1,86 +0,0 @@
/********************************************************************************
* Copyright (C) 2021 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" *
********************************************************************************/
#ifndef FAIR_MQ_TIDY_TOOL
#define FAIR_MQ_TIDY_TOOL
#include <algorithm>
#include <clang/ASTMatchers/ASTMatchFinder.h>
#include <clang/Basic/FileManager.h>
#include <clang/Tooling/CompilationDatabase.h>
#include <clang/Tooling/Tooling.h>
#include <fairmq/tidy/ModernizeNonNamespacedTypes.h>
#include <string>
namespace fair::mq::tidy {
// Getting up to speed, read this:
// https://clang.llvm.org/docs/LibTooling.html
// https://clang.llvm.org/docs/IntroductionToTheClangAST.html
// Watch https://www.youtube.com/watch?v=VqCkCDFLSsc !!!
//
// optional, but helpful:
// https://static.linaro.org/connect/yvr18/presentations/yvr18-223.pdf
// https://steveire.wordpress.com/2018/11/20/composing-ast-matchers-in-clang-tidy/
// https://www.goldsborough.me/c++/clang/llvm/tools/2017/02/24/00-00-06-emitting_diagnostics_and_fixithints_in_clang_tools/
// https://steveire.com/CodeDive2018Presentation.pdf
//
// reference (no built-in search, however google will find things):
// https://clang.llvm.org/doxygen/
//
// Note: Implementing a standalone tool will impose double PP and parsing cost if one also
// runs clang-tidy. At the moment, one cannot extend clang-tidy with new checks without
// recompiling clang-tidy. In principle llvm-project/clang-extra-tools/clang-tidy
// has install rules, but Fedora is not packaging them which is likely due to their
// unstable state (lots of comments aka todo, fixme, refactor etc). Also, it seems
// focus has shifted towards implementing the
// https://microsoft.github.io/language-server-protocol/
// via https://clangd.llvm.org/ which includes clang-tidy, but also does not have
// an extension/plugin interface for third-party checks yet AFAICS.
struct Tool
{
static auto run(clang::tooling::CompilationDatabase const &compilations,
clang::ArrayRef<std::string> sources) -> int
{
using namespace clang;
// compose all checks in a single match finder
ast_matchers::MatchFinder finder;
ModernizeNonNamespacedTypes check1(finder);
// configure the clang tool
tooling::ClangTool tool(compilations, sources);
tool.appendArgumentsAdjuster(
[](tooling::CommandLineArguments const &_args, StringRef /*file*/) {
tooling::CommandLineArguments args(_args);
auto const no_std_arg_present =
std::find_if(cbegin(args),
cend(args),
[](std::string const &arg) {
return arg.find("-std=") != std::string::npos;
})
== std::cend(args);
if (no_std_arg_present) {
args.emplace(std::cbegin(args) + 1, "-std=c++17");
}
args.emplace_back("-Wno-everything");
return args;
});
// run checks on given files
return tool.run(clang::tooling::newFrontendActionFactory(&finder).get());
}
};
} // namespace fair::mq::tidy
#endif /* FAIR_MQ_TIDY_TOOL */

50
fairmq/tidy/runTidy.cxx Normal file
View File

@@ -0,0 +1,50 @@
/********************************************************************************
* Copyright (C) 2021-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-tidy is the upstream clang-tidy driver with the FairMQ module linked in.
// It accepts every clang-tidy option and runs the upstream checks and the
// fairmq-* checks on one parse of each file. Without a --checks option it adds
// the fairmq-* checks to the checks of the .clang-tidy configuration.
#include <clang-tidy/tool/ClangTidyMain.h>
#include <string_view>
#include <vector>
extern volatile int FairMQTidyModuleAnchorSource;
[[maybe_unused]] static int const fairmqModuleAnchor = FairMQTidyModuleAnchorSource;
int main(int argc, char const** argv)
{
std::vector<char const*> args(argv, argv + argc);
bool userResourceDir = false;
bool userChecks = false;
for (std::string_view arg : args) {
if (arg == "--") {
break; // the compiler command line follows
}
if (arg.find("-resource-dir") != std::string_view::npos) {
userResourceDir = true;
}
if (arg.rfind("--checks", 0) == 0 || arg.rfind("-checks", 0) == 0) {
userChecks = true;
}
}
// The driver looks for its builtin headers (e.g. <stddef.h>) relative to
// the executable. fairmq-tidy is not installed next to clang, so point it
// to the resource directory of the LLVM installation it was built with.
if (argc > 0 && !userResourceDir) {
args.insert(args.begin() + 1, "--extra-arg-before=-resource-dir=" FAIRMQ_TIDY_CLANG_RESOURCE_DIR);
}
// --checks appends to the Checks of the configuration.
if (argc > 0 && !userChecks) {
args.insert(args.begin() + 1, "--checks=fairmq-*");
}
return clang::tidy::clangTidyMain(static_cast<int>(args.size()), args.data());
}

View File

@@ -1,29 +0,0 @@
/********************************************************************************
* Copyright (C) 2021 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" *
********************************************************************************/
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Tooling.h>
#include <fairmq/tidy/Tool.h>
#include <llvm/ADT/STLExtras.h>
#include <llvm/Support/CommandLine.h>
static llvm::cl::OptionCategory ToolCategory("fairmq-tidy options");
static llvm::cl::extrahelp CommonHelp(clang::tooling::CommonOptionsParser::HelpMessage);
int main(int argc, const char** argv)
{
// TODO Replace command line parser with CLI11
auto parser(clang::tooling::CommonOptionsParser::create(
argc, argv, ToolCategory, llvm::cl::NumOccurrencesFlag::ZeroOrMore, ""));
if (!parser) {
llvm::errs() << parser.takeError();
return EXIT_FAILURE;
}
return fair::mq::tidy::Tool::run(parser->getCompilations(), parser->getSourcePathList());
}