aboutsummaryrefslogtreecommitdiff
path: root/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
blob: 5cabc6df21da9236fb9fee40c04040ab7d2ba8f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
//===--- UseStdFormatCheck.cpp - clang-tidy -------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "UseStdFormatCheck.h"
#include "../utils/FormatStringConverter.h"
#include "../utils/Matchers.h"
#include "../utils/OptionsUtils.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang::tidy::modernize {

namespace {
AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); }
} // namespace

UseStdFormatCheck::UseStdFormatCheck(StringRef Name, ClangTidyContext *Context)
    : ClangTidyCheck(Name, Context),
      StrictMode(Options.getLocalOrGlobal("StrictMode", false)),
      StrFormatLikeFunctions(utils::options::parseStringList(
          Options.get("StrFormatLikeFunctions", ""))),
      ReplacementFormatFunction(
          Options.get("ReplacementFormatFunction", "std::format")),
      IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
                                               utils::IncludeSorter::IS_LLVM),
                      areDiagsSelfContained()),
      MaybeHeaderToInclude(Options.get("FormatHeader")) {
  if (StrFormatLikeFunctions.empty())
    StrFormatLikeFunctions.emplace_back("absl::StrFormat");

  if (!MaybeHeaderToInclude && ReplacementFormatFunction == "std::format")
    MaybeHeaderToInclude = "<format>";
}

void UseStdFormatCheck::registerPPCallbacks(const SourceManager &SM,
                                            Preprocessor *PP,
                                            Preprocessor *ModuleExpanderPP) {
  IncludeInserter.registerPreprocessor(PP);
  this->PP = PP;
}

void UseStdFormatCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(
      callExpr(argumentCountAtLeast(1),
               hasArgument(0, stringLiteral(isOrdinary())),
               callee(functionDecl(matchers::matchesAnyListedName(
                                       StrFormatLikeFunctions))
                          .bind("func_decl")))
          .bind("strformat"),
      this);
}

void UseStdFormatCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
  using utils::options::serializeStringList;
  Options.store(Opts, "StrictMode", StrictMode);
  Options.store(Opts, "StrFormatLikeFunctions",
                serializeStringList(StrFormatLikeFunctions));
  Options.store(Opts, "ReplacementFormatFunction", ReplacementFormatFunction);
  Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
  if (MaybeHeaderToInclude)
    Options.store(Opts, "FormatHeader", *MaybeHeaderToInclude);
}

void UseStdFormatCheck::check(const MatchFinder::MatchResult &Result) {
  const unsigned FormatArgOffset = 0;
  const auto *OldFunction = Result.Nodes.getNodeAs<FunctionDecl>("func_decl");
  const auto *StrFormat = Result.Nodes.getNodeAs<CallExpr>("strformat");

  utils::FormatStringConverter::Configuration ConverterConfig;
  ConverterConfig.StrictMode = StrictMode;
  utils::FormatStringConverter Converter(
      Result.Context, StrFormat, FormatArgOffset, ConverterConfig,
      getLangOpts(), *Result.SourceManager, *PP);
  const Expr *StrFormatCall = StrFormat->getCallee();
  if (!Converter.canApply()) {
    diag(StrFormat->getBeginLoc(),
         "unable to use '%0' instead of %1 because %2")
        << StrFormatCall->getSourceRange() << ReplacementFormatFunction
        << OldFunction->getIdentifier()
        << Converter.conversionNotPossibleReason();
    return;
  }

  DiagnosticBuilder Diag =
      diag(StrFormatCall->getBeginLoc(), "use '%0' instead of %1")
      << ReplacementFormatFunction << OldFunction->getIdentifier();
  Diag << FixItHint::CreateReplacement(
      CharSourceRange::getTokenRange(StrFormatCall->getExprLoc(),
                                     StrFormatCall->getEndLoc()),
      ReplacementFormatFunction);
  Converter.applyFixes(Diag, *Result.SourceManager);

  if (MaybeHeaderToInclude)
    Diag << IncludeInserter.createIncludeInsertion(
        Result.Context->getSourceManager().getFileID(
            StrFormatCall->getBeginLoc()),
        *MaybeHeaderToInclude);
}

} // namespace clang::tidy::modernize