clang-tools 19.0.0git
UseStdFormatCheck.cpp
Go to the documentation of this file.
1//===--- UseStdFormatCheck.cpp - clang-tidy -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "UseStdFormatCheck.h"
10#include "../utils/FormatStringConverter.h"
11#include "../utils/Matchers.h"
12#include "../utils/OptionsUtils.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
14#include "clang/Lex/Lexer.h"
15#include "clang/Tooling/FixIt.h"
16
17using namespace clang::ast_matchers;
18
19namespace clang::tidy::modernize {
20
21namespace {
22AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); }
23} // namespace
24
26 : ClangTidyCheck(Name, Context),
27 StrictMode(Options.getLocalOrGlobal("StrictMode", false)),
28 StrFormatLikeFunctions(utils::options::parseStringList(
29 Options.get("StrFormatLikeFunctions", ""))),
30 ReplacementFormatFunction(
31 Options.get("ReplacementFormatFunction", "std::format")),
32 IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
33 utils::IncludeSorter::IS_LLVM),
34 areDiagsSelfContained()),
35 MaybeHeaderToInclude(Options.get("FormatHeader")) {
36 if (StrFormatLikeFunctions.empty())
37 StrFormatLikeFunctions.push_back("absl::StrFormat");
38
39 if (!MaybeHeaderToInclude && ReplacementFormatFunction == "std::format")
40 MaybeHeaderToInclude = "<format>";
41}
42
43void UseStdFormatCheck::registerPPCallbacks(const SourceManager &SM,
44 Preprocessor *PP,
45 Preprocessor *ModuleExpanderPP) {
46 IncludeInserter.registerPreprocessor(PP);
47}
48
49void UseStdFormatCheck::registerMatchers(MatchFinder *Finder) {
50 auto CharPointerType =
51 hasType(pointerType(pointee(matchers::isSimpleChar())));
52 Finder->addMatcher(
53 callExpr(
54 argumentCountAtLeast(1), hasArgument(0, stringLiteral(isOrdinary())),
55 callee(functionDecl(
56 unless(cxxMethodDecl()), hasParameter(0, CharPointerType),
57 matchers::matchesAnyListedName(StrFormatLikeFunctions))
58 .bind("func_decl")))
59 .bind("strformat"),
60 this);
61}
62
65 Options.store(Opts, "StrictMode", StrictMode);
66 Options.store(Opts, "StrFormatLikeFunctions",
67 serializeStringList(StrFormatLikeFunctions));
68 Options.store(Opts, "ReplacementFormatFunction", ReplacementFormatFunction);
69 Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
70 if (MaybeHeaderToInclude)
71 Options.store(Opts, "FormatHeader", *MaybeHeaderToInclude);
72}
73
74void UseStdFormatCheck::check(const MatchFinder::MatchResult &Result) {
75 const unsigned FormatArgOffset = 0;
76 const auto *OldFunction = Result.Nodes.getNodeAs<FunctionDecl>("func_decl");
77 const auto *StrFormat = Result.Nodes.getNodeAs<CallExpr>("strformat");
78
80 ConverterConfig.StrictMode = StrictMode;
81 utils::FormatStringConverter Converter(Result.Context, StrFormat,
82 FormatArgOffset, ConverterConfig,
83 getLangOpts());
84 const Expr *StrFormatCall = StrFormat->getCallee();
85 if (!Converter.canApply()) {
86 diag(StrFormat->getBeginLoc(),
87 "unable to use '%0' instead of %1 because %2")
88 << StrFormatCall->getSourceRange() << ReplacementFormatFunction
89 << OldFunction->getIdentifier()
90 << Converter.conversionNotPossibleReason();
91 return;
92 }
93
94 DiagnosticBuilder Diag =
95 diag(StrFormatCall->getBeginLoc(), "use '%0' instead of %1")
96 << ReplacementFormatFunction << OldFunction->getIdentifier();
97 Diag << FixItHint::CreateReplacement(
98 CharSourceRange::getTokenRange(StrFormatCall->getSourceRange()),
99 ReplacementFormatFunction);
100 Converter.applyFixes(Diag, *Result.SourceManager);
101
102 if (MaybeHeaderToInclude)
103 Diag << IncludeInserter.createIncludeInsertion(
104 Result.Context->getSourceManager().getFileID(
105 StrFormatCall->getBeginLoc()),
106 *MaybeHeaderToInclude);
107}
108
109} // namespace clang::tidy::modernize
llvm::SmallString< 256U > Name
::clang::DynTypedNode Node
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
const LangOptions & getLangOpts() const
Returns the language options from the context.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
Override this to register PPCallbacks in the preprocessor.
UseStdFormatCheck(StringRef Name, ClangTidyContext *Context)
Convert a printf-style format string to a std::formatter-style one, and prepare any casts that are re...
void applyFixes(DiagnosticBuilder &Diag, SourceManager &SM)
Called by the check when it is ready to apply the fixes.
const std::string & conversionNotPossibleReason() const
void registerPreprocessor(Preprocessor *PP)
Registers this with the Preprocessor PP, must be called before this class is used.
std::optional< FixItHint > createIncludeInsertion(FileID FileID, llvm::StringRef Header)
Creates a Header inclusion directive fixit in the File FileID.
IncludeSorter::IncludeStyle getStyle() const
AST_MATCHER(Decl, declHasNoReturnAttr)
matches a Decl if it has a "no return" attribute of any kind
inline ::clang::ast_matchers::internal::Matcher< NamedDecl > matchesAnyListedName(llvm::ArrayRef< StringRef > NameList)
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap