diff --git a/docs/src/content/docs/guides/migrate-names.mdx b/docs/src/content/docs/guides/migrate-names.mdx index 98275273..8d7ea5ed 100644 --- a/docs/src/content/docs/guides/migrate-names.mdx +++ b/docs/src/content/docs/guides/migrate-names.mdx @@ -133,7 +133,7 @@ The table is in the order of the headers that declare the deprecated alias. The | `FairMQUnmanagedRegion` | [`fair::mq::UnmanagedRegion`](/api/fair/mq/UnmanagedRegion/) | `UnmanagedRegion.h` | yes | | `FairMQUnmanagedRegionPtr` | [`fair::mq::UnmanagedRegionPtr`](/api/fair/mq/#UnmanagedRegionPtr) | `UnmanagedRegion.h` | yes | | `FairMQRegionConfig` | [`fair::mq::RegionConfig`](/api/fair/mq/RegionConfig/) | `UnmanagedRegion.h` | yes | -| `FairMQDevicePtr` | `std::unique_ptr` as the return type of `getDevice()` | `runFairMQDevice.h` | no | +| `FairMQDevicePtr` | `std::unique_ptr` as the return type of `getDevice()` | `runFairMQDevice.h` | yes, with `fairmq-modernize-run-device` | All old names are global, except `fair::mq::FairMQMemoryResource`. All names in the table except `FairMQDevicePtr` have the attribute `[[deprecated]]`. @@ -185,7 +185,7 @@ The CMake package is `FairMQ`. Link your targets with `FairMQ::FairMQ`. The exec ## Automate the move with fairmq-tidy -`fairmq-tidy` finds the old headers, most old type names and `Device::fChannels`. With `--fix`, it replaces them in your files. See [Check code with fairmq-tidy](/guides/fairmq-tidy/) and the [list of checks](/tools/fairmq-tidy/#checks). +`fairmq-tidy` finds the old headers, most old type names, the deprecated functions and members, and a `getDevice()` for `runFairMQDevice.h`. With `--fix`, it replaces most of them in your files. See [Check code with fairmq-tidy](/guides/fairmq-tidy/) and the [list of checks](/tools/fairmq-tidy/#checks). ## Related pages diff --git a/docs/src/content/docs/tools/fairmq-tidy.mdx b/docs/src/content/docs/tools/fairmq-tidy.mdx index 69b844b6..16e3f70c 100644 --- a/docs/src/content/docs/tools/fairmq-tidy.mdx +++ b/docs/src/content/docs/tools/fairmq-tidy.mdx @@ -39,6 +39,7 @@ The `fairmq-*` checks are a clang-tidy module ([Module.cxx](/source/fairmq/tidy/ | `fairmq-modernize-nonnamespaced-types` | Uses of the deprecated global type aliases, for example `FairMQDevice` or `InputMsgCallback` | The namespaced type, for example `fair::mq::Device` | | `fairmq-modernize-parts-api` | Calls of `Parts::AtRef()` and of `Parts::AddPart(Message*)` | `At()` with `->` or `*`, and `MessagePtr(p)` | | `fairmq-modernize-progoptions-accessors` | Calls of the deprecated accessors `ProgOptions::GetValue()`, `GetStringValue()` and `SetValue()` | `GetProperty()`, `GetPropertyAsString()` and `SetProperty()` | +| `fairmq-modernize-run-device` | A `getDevice()` for `` that returns a raw pointer | ``, `std::unique_ptr` and `std::make_unique` | The checks report a name in a macro, but they do not fix it. Like all clang-tidy checks, they show findings in headers only if the header matches `--header-filter=`. @@ -117,6 +118,18 @@ The check does not fix a call on an object expression with side effects, for exa For a key that does not exist, the old accessors return a default-constructed value, and `GetProperty()` throws. The default `{}` keeps the old behavior. If you know that the key exists, remove the `{}`. The check fixes `SetValue()` only if the code does not use its result, because `SetProperty()` returns `void`. +### fairmq-modernize-run-device + +The check moves a device main file from `` to ``, see [Replace runFairMQDevice.h](/guides/migrate-names/#replace-runfairmqdeviceh): + +| Code | Fix | +| --- | --- | +| `#include ` | `#include ` | +| `FairMQDevicePtr getDevice(const fair::mq::ProgOptions& config)` | `std::unique_ptr getDevice(fair::mq::ProgOptions& config)` | +| `return new MyDevice(config);` | `return std::make_unique(config);` | + +The check changes all of these lines or none. If a `return` statement of `getDevice()` does not return a `new` expression, the check reports the function without a fix. + ## Build fairmq-tidy Set the CMake option `BUILD_TIDY_TOOL` (default `OFF`) when you configure FairMQ: diff --git a/fairmq/tidy/CMakeLists.txt b/fairmq/tidy/CMakeLists.txt index f3e7443e..e1ce0b91 100644 --- a/fairmq/tidy/CMakeLists.txt +++ b/fairmq/tidy/CMakeLists.txt @@ -45,6 +45,8 @@ add_library(fairmq-tidy-module OBJECT PartsApiCheck.h ProgOptionsAccessorsCheck.cxx ProgOptionsAccessorsCheck.h + RunDeviceCheck.cxx + RunDeviceCheck.h ) target_compile_features(fairmq-tidy-module PUBLIC cxx_std_17) target_include_directories(fairmq-tidy-module diff --git a/fairmq/tidy/Module.cxx b/fairmq/tidy/Module.cxx index 5175a568..0005eca3 100644 --- a/fairmq/tidy/Module.cxx +++ b/fairmq/tidy/Module.cxx @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -31,6 +32,7 @@ class Module : public clang::tidy::ClangTidyModule factories.registerCheck("fairmq-modernize-nonnamespaced-types"); factories.registerCheck("fairmq-modernize-parts-api"); factories.registerCheck("fairmq-modernize-progoptions-accessors"); + factories.registerCheck("fairmq-modernize-run-device"); } }; diff --git a/fairmq/tidy/RunDeviceCheck.cxx b/fairmq/tidy/RunDeviceCheck.cxx new file mode 100644 index 00000000..62a00500 --- /dev/null +++ b/fairmq/tidy/RunDeviceCheck.cxx @@ -0,0 +1,188 @@ +/******************************************************************************** + * 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 +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace fair::mq::tidy { + +using namespace clang; +using namespace clang::ast_matchers; + +namespace { + +class Callbacks : public PPCallbacks +{ + public: + Callbacks(std::optional& include, SourceManager const& sm) + : fInclude(include) + , fSM(sm) + {} + + void InclusionDirective(SourceLocation /*hashLoc*/, + Token const& /*includeTok*/, + StringRef fileName, + bool isAngled, + CharSourceRange fileNameRange, + OptionalFileEntryRef /*file*/, + StringRef /*searchPath*/, + StringRef /*relativePath*/, +#if LLVM_VERSION_MAJOR >= 19 + Module const* /*suggestedModule*/, + bool /*moduleImported*/, +#else + Module const* /*imported*/, +#endif + SrcMgr::CharacteristicKind /*fileType*/) override + { + if (fSM.isWrittenInMainFile(fileNameRange.getBegin()) + && (fileName == "runFairMQDevice.h" || fileName.ends_with("/runFairMQDevice.h"))) { + fInclude = RunDeviceCheck::Include{fileNameRange, isAngled}; + } + } + + private: + std::optional& fInclude; + SourceManager const& fSM; +}; + +/// Collects the return statements of a function body, but not those of nested +/// lambdas or local classes. +class ReturnCollector : public RecursiveASTVisitor +{ + public: + bool VisitReturnStmt(ReturnStmt* s) + { + fReturns.push_back(s); + return true; + } + bool TraverseLambdaExpr(LambdaExpr*) { return true; } + bool TraverseCXXRecordDecl(CXXRecordDecl*) { return true; } + + std::vector fReturns; +}; + +} // namespace + +void RunDeviceCheck::registerPPCallbacks(SourceManager const& sm, + Preprocessor* pp, + Preprocessor* /*moduleExpanderPP*/) +{ + fInclude.reset(); + pp->addPPCallbacks(std::make_unique(fInclude, sm)); +} + +void RunDeviceCheck::registerMatchers(MatchFinder* finder) +{ + auto const progOptions = cxxRecordDecl(hasName("::fair::mq::ProgOptions")); + finder->addMatcher( + functionDecl(hasName("::getDevice"), + isDefinition(), + isExpansionInMainFile(), + returns(hasCanonicalType(pointerType( + pointee(hasDeclaration(cxxRecordDecl(hasName("::fair::mq::Device"))))))), + parameterCountIs(1), + hasParameter(0, parmVarDecl(hasType(lValueReferenceType(pointee(qualType( + isConstQualified(), + hasCanonicalType(hasDeclaration(progOptions))))))) + .bind("param"))) + .bind("getDevice"), + this); +} + +void RunDeviceCheck::check(MatchFinder::MatchResult const& result) +{ + auto const* fn = result.Nodes.getNodeAs("getDevice"); + auto const* param = result.Nodes.getNodeAs("param"); + auto& sm = *result.SourceManager; + auto const& lo = getLangOpts(); + + auto diagnostic = diag(fn->getLocation(), + "'runFairMQDevice.h' and a raw 'fair::mq::Device*' from 'getDevice()' are " + "superseded; use 'fairmq/runDevice.h' and return a " + "'std::unique_ptr'"); + if (!fInclude) { + return; // the include is in another file: no consistent fix + } + + std::vector fixes; + auto const text = [&](CharSourceRange range) { return Lexer::getSourceText(range, sm, lo).str(); }; + auto const isMacro = [](SourceRange r) { return r.getBegin().isMacroID() || r.getEnd().isMacroID(); }; + + // #include -> #include + fixes.push_back(FixItHint::CreateReplacement( + fInclude->fileNameRange, fInclude->isAngled ? "" : "\"fairmq/runDevice.h\"")); + + // FairMQDevicePtr -> std::unique_ptr + auto const returnRange = fn->getReturnTypeSourceRange(); + if (returnRange.isInvalid() || isMacro(returnRange)) { + return; + } + fixes.push_back(FixItHint::CreateReplacement(returnRange, "std::unique_ptr")); + + // const fair::mq::ProgOptions& cfg -> fair::mq::ProgOptions& cfg + if (isMacro(param->getSourceRange())) { + return; + } + if (param->getName().empty()) { + fixes.push_back(FixItHint::CreateReplacement(param->getSourceRange(), "fair::mq::ProgOptions&")); + } else { + fixes.push_back(FixItHint::CreateReplacement( + CharSourceRange::getCharRange(param->getBeginLoc(), param->getLocation()), + "fair::mq::ProgOptions& ")); + } + + // return new T(args) -> return std::make_unique(args) + ReturnCollector collector; + collector.TraverseStmt(fn->getBody()); + for (auto const* ret : collector.fReturns) { + auto const* value = ret->getRetValue() ? ret->getRetValue()->IgnoreImpCasts() : nullptr; + if (!value || isa(value)) { + continue; // nullptr converts to std::unique_ptr + } + auto const* newExpr = dyn_cast(value); + if (!newExpr || newExpr->isArray() || newExpr->getNumPlacementArgs() > 0 + || isMacro(newExpr->getSourceRange())) { + return; + } + auto const typeRange = newExpr->getAllocatedTypeSourceInfo()->getTypeLoc().getSourceRange(); + auto const afterType = Lexer::getLocForEndOfToken(typeRange.getEnd(), 0, sm, lo); + auto const afterNew = Lexer::getLocForEndOfToken(newExpr->getEndLoc(), 0, sm, lo); + std::string init; // empty for `new T` + if (afterType != afterNew) { + init = text(CharSourceRange::getCharRange(afterType, afterNew)); + } + StringRef trimmed = StringRef(init).ltrim(); + if (trimmed.empty()) { + trimmed = "()"; + } else if (!trimmed.starts_with("(")) { + return; // new T{...}: braces mean something else in make_unique + } + fixes.push_back(FixItHint::CreateReplacement( + newExpr->getSourceRange(), + "std::make_unique<" + text(CharSourceRange::getTokenRange(typeRange)) + ">" + trimmed.str())); + } + + for (auto const& fix : fixes) { + diagnostic << fix; + } +} + +} // namespace fair::mq::tidy diff --git a/fairmq/tidy/RunDeviceCheck.h b/fairmq/tidy/RunDeviceCheck.h new file mode 100644 index 00000000..c8321fdf --- /dev/null +++ b/fairmq/tidy/RunDeviceCheck.h @@ -0,0 +1,55 @@ +/******************************************************************************** + * 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" * + ********************************************************************************/ + +#ifndef FAIR_MQ_TIDY_RUNDEVICECHECK_H +#define FAIR_MQ_TIDY_RUNDEVICECHECK_H + +#include + +#include + +namespace fair::mq::tidy { + +/// Migrates a device main file from `` to +/// ``: +/// +/// #include #include +/// FairMQDevicePtr -> std::unique_ptr +/// getDevice(const ProgOptions& cfg) getDevice(fair::mq::ProgOptions& cfg) +/// { return new MyDevice(cfg); } { return std::make_unique(cfg); } +/// +/// The check rewrites all of it in one fix, or nothing. It reports without a +/// fix if a return statement is not a plain `new` expression. +class RunDeviceCheck : public clang::tidy::ClangTidyCheck +{ + public: + using ClangTidyCheck::ClangTidyCheck; + + bool isLanguageVersionSupported(clang::LangOptions const& opts) const override + { + return opts.CPlusPlus17; + } + void registerPPCallbacks(clang::SourceManager const& sm, + clang::Preprocessor* pp, + clang::Preprocessor* moduleExpanderPP) override; + void registerMatchers(clang::ast_matchers::MatchFinder* finder) override; + void check(clang::ast_matchers::MatchFinder::MatchResult const& result) override; + + struct Include + { + clang::CharSourceRange fileNameRange; + bool isAngled; + }; + + private: + std::optional fInclude; // #include in the main file +}; + +} // namespace fair::mq::tidy + +#endif /* FAIR_MQ_TIDY_RUNDEVICECHECK_H */ diff --git a/test/tidy/fairmq-modernize-run-device.cxx b/test/tidy/fairmq-modernize-run-device.cxx new file mode 100644 index 00000000..a01fbe2c --- /dev/null +++ b/test/tidy/fairmq-modernize-run-device.cxx @@ -0,0 +1,33 @@ +// CHECK-FIXES: #include +#include + +#include + +struct Sampler : fair::mq::Device +{ + explicit Sampler(int rate) : fRate(rate) {} + int fRate; +}; + +struct Sink : fair::mq::Device +{}; + +void addCustomOptions(boost::program_options::options_description& options) +{ + options.add_options()("rate", boost::program_options::value()->default_value(1), "rate"); +} + +// CHECK-MESSAGES: :[[@LINE+1]]:17: warning: 'runFairMQDevice.h' and a raw 'fair::mq::Device*' from 'getDevice()' are superseded; use 'fairmq/runDevice.h' and return a 'std::unique_ptr' [fairmq-modernize-run-device] +FairMQDevicePtr getDevice(const fair::mq::ProgOptions& config) +// CHECK-FIXES: std::unique_ptr getDevice(fair::mq::ProgOptions& config) +{ + if (config.Count("sink")) { + return new Sink; + // CHECK-FIXES: return std::make_unique(); + } + if (config.Count("none")) { + return nullptr; + } + return new Sampler(config.GetProperty("rate")); + // CHECK-FIXES: return std::make_unique(config.GetProperty("rate")); +}