|
| 1 | +// SPDX-FileCopyrightText: 2025 Mike Crowe |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +#include "ModernizeNlohmannJsonExplicitConversionsCheck.h" |
| 5 | +#include "clang/ASTMatchers/ASTMatchFinder.h" |
| 6 | +#include "clang/Lex/Lexer.h" |
| 7 | + |
| 8 | +using namespace clang::ast_matchers; |
| 9 | + |
| 10 | +namespace clang::tidy::modernize { |
| 11 | + |
| 12 | +void NlohmannJsonExplicitConversionsCheck::registerMatchers( |
| 13 | + MatchFinder *Finder) { |
| 14 | + auto Matcher = |
| 15 | + cxxMemberCallExpr( |
| 16 | + on(expr().bind("arg")), |
| 17 | + callee(cxxConversionDecl(ofClass(hasName("nlohmann::basic_json"))) |
| 18 | + .bind("conversionDecl"))) |
| 19 | + .bind("conversionCall"); |
| 20 | + Finder->addMatcher(Matcher, this); |
| 21 | +} |
| 22 | + |
| 23 | +void NlohmannJsonExplicitConversionsCheck::check( |
| 24 | + const MatchFinder::MatchResult &Result) { |
| 25 | + const auto *Decl = |
| 26 | + Result.Nodes.getNodeAs<CXXConversionDecl>("conversionDecl"); |
| 27 | + const auto *Call = |
| 28 | + Result.Nodes.getNodeAs<CXXMemberCallExpr>("conversionCall"); |
| 29 | + const auto *Arg = Result.Nodes.getNodeAs<Expr>("arg"); |
| 30 | + |
| 31 | + const QualType DestinationType = Decl->getConversionType(); |
| 32 | + std::string DestinationTypeStr = |
| 33 | + DestinationType.getAsString(Result.Context->getPrintingPolicy()); |
| 34 | + if (DestinationTypeStr == "std::basic_string<char>") |
| 35 | + DestinationTypeStr = "std::string"; |
| 36 | + |
| 37 | + const SourceRange ExprRange = Call->getSourceRange(); |
| 38 | + if (!ExprRange.isValid()) |
| 39 | + return; |
| 40 | + |
| 41 | + bool Deref = false; |
| 42 | + if (const auto *Op = llvm::dyn_cast<UnaryOperator>(Arg); |
| 43 | + Op && Op->getOpcode() == UO_Deref) |
| 44 | + Deref = true; |
| 45 | + else if (const auto *Op = llvm::dyn_cast<CXXOperatorCallExpr>(Arg); |
| 46 | + Op && Op->getOperator() == OO_Star) |
| 47 | + Deref = true; |
| 48 | + |
| 49 | + llvm::StringRef SourceText = clang::Lexer::getSourceText( |
| 50 | + clang::CharSourceRange::getTokenRange(ExprRange), *Result.SourceManager, |
| 51 | + Result.Context->getLangOpts()); |
| 52 | + |
| 53 | + if (Deref) |
| 54 | + SourceText.consume_front("*"); |
| 55 | + |
| 56 | + const std::string ReplacementText = |
| 57 | + (llvm::Twine(SourceText) + (Deref ? "->" : ".") + "get<" + |
| 58 | + DestinationTypeStr + ">()") |
| 59 | + .str(); |
| 60 | + diag(Call->getExprLoc(), |
| 61 | + "implicit nlohmann::json conversion to %0 should be explicit") |
| 62 | + << DestinationTypeStr |
| 63 | + << FixItHint::CreateReplacement(CharSourceRange::getTokenRange(ExprRange), |
| 64 | + ReplacementText); |
| 65 | +} |
| 66 | + |
| 67 | +} // namespace clang::tidy::modernize |
0 commit comments