diff --git a/fairmq/tidy/CMakeLists.txt b/fairmq/tidy/CMakeLists.txt index 79f7546c..44a3a1f7 100644 --- a/fairmq/tidy/CMakeLists.txt +++ b/fairmq/tidy/CMakeLists.txt @@ -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--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 $ - $ ) +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} diff --git a/fairmq/tidy/ModernizeNonNamespacedTypes.h b/fairmq/tidy/ModernizeNonNamespacedTypes.h deleted file mode 100644 index 6796fec9..00000000 --- a/fairmq/tidy/ModernizeNonNamespacedTypes.h +++ /dev/null @@ -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 -#include -#include -#include -#include - -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("loc")); - auto const named_decl(m.Nodes.getNodeAs("decl")); - - if (auto const type_alias_decl = m.Nodes.getNodeAs("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 */ diff --git a/fairmq/tidy/Module.cxx b/fairmq/tidy/Module.cxx new file mode 100644 index 00000000..06f3462e --- /dev/null +++ b/fairmq/tidy/Module.cxx @@ -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 + +#include +#include + +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("fairmq-modernize-nonnamespaced-types"); + } +}; + +} // namespace fair::mq::tidy + +static clang::tidy::ClangTidyModuleRegistry::Add + 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; diff --git a/fairmq/tidy/NonNamespacedTypesCheck.cxx b/fairmq/tidy/NonNamespacedTypesCheck.cxx new file mode 100644 index 00000000..1e823bda --- /dev/null +++ b/fairmq/tidy/NonNamespacedTypesCheck.cxx @@ -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 + +#include +#include +#include + +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("alias"); + auto const* loc = result.Nodes.getNodeAs("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 diff --git a/fairmq/tidy/NonNamespacedTypesCheck.h b/fairmq/tidy/NonNamespacedTypesCheck.h new file mode 100644 index 00000000..f5a7c1c0 --- /dev/null +++ b/fairmq/tidy/NonNamespacedTypesCheck.h @@ -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 + +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 */ diff --git a/fairmq/tidy/Tool.h b/fairmq/tidy/Tool.h deleted file mode 100644 index 19f14020..00000000 --- a/fairmq/tidy/Tool.h +++ /dev/null @@ -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 -#include -#include -#include -#include -#include -#include - -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 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 */ diff --git a/fairmq/tidy/runTidy.cxx b/fairmq/tidy/runTidy.cxx new file mode 100644 index 00000000..a6169894 --- /dev/null +++ b/fairmq/tidy/runTidy.cxx @@ -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 + +#include +#include + +extern volatile int FairMQTidyModuleAnchorSource; +[[maybe_unused]] static int const fairmqModuleAnchor = FairMQTidyModuleAnchorSource; + +int main(int argc, char const** argv) +{ + std::vector 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. ) 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(args.size()), args.data()); +} diff --git a/fairmq/tidy/runTool.cpp b/fairmq/tidy/runTool.cpp deleted file mode 100644 index 2bb082b0..00000000 --- a/fairmq/tidy/runTool.cpp +++ /dev/null @@ -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 -#include -#include -#include -#include - -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()); -}