summaryrefslogtreecommitdiff
path: root/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
blob: 18169deaa0681edc7f201e1756d9ff75b23836a4 (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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
//===--- ClangTidyCheck.cpp - clang-tidy ------------------------*- C++ -*-===//
//
// 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 "ClangTidyCheck.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/YAMLParser.h"
#include <optional>

namespace clang::tidy {

ClangTidyCheck::ClangTidyCheck(StringRef CheckName, ClangTidyContext *Context)
    : CheckName(CheckName), Context(Context),
      Options(CheckName, Context->getOptions().CheckOptions, Context) {
  assert(Context != nullptr);
  assert(!CheckName.empty());
}

DiagnosticBuilder ClangTidyCheck::diag(SourceLocation Loc, StringRef Message,
                                       DiagnosticIDs::Level Level) {
  return Context->diag(CheckName, Loc, Message, Level);
}

DiagnosticBuilder ClangTidyCheck::diag(StringRef Message,
                                       DiagnosticIDs::Level Level) {
  return Context->diag(CheckName, Message, Level);
}

DiagnosticBuilder
ClangTidyCheck::configurationDiag(StringRef Description,
                                  DiagnosticIDs::Level Level) const {
  return Context->configurationDiag(Description, Level);
}

void ClangTidyCheck::run(const ast_matchers::MatchFinder::MatchResult &Result) {
  // For historical reasons, checks don't implement the MatchFinder run()
  // callback directly. We keep the run()/check() distinction to avoid interface
  // churn, and to allow us to add cross-cutting logic in the future.
  check(Result);
}

ClangTidyCheck::OptionsView::OptionsView(
    StringRef CheckName, const ClangTidyOptions::OptionMap &CheckOptions,
    ClangTidyContext *Context)
    : NamePrefix((CheckName + ".").str()), CheckOptions(CheckOptions),
      Context(Context) {}

std::optional<StringRef>
ClangTidyCheck::OptionsView::get(StringRef LocalName) const {
  if (Context->getOptionsCollector())
    Context->getOptionsCollector()->insert((NamePrefix + LocalName).str());
  const auto &Iter = CheckOptions.find((NamePrefix + LocalName).str());
  if (Iter != CheckOptions.end())
    return StringRef(Iter->getValue().Value);
  return std::nullopt;
}

static ClangTidyOptions::OptionMap::const_iterator
findPriorityOption(const ClangTidyOptions::OptionMap &Options,
                   StringRef NamePrefix, StringRef LocalName,
                   llvm::StringSet<> *Collector) {
  if (Collector) {
    Collector->insert((NamePrefix + LocalName).str());
    Collector->insert(LocalName);
  }
  auto IterLocal = Options.find((NamePrefix + LocalName).str());
  auto IterGlobal = Options.find(LocalName);
  if (IterLocal == Options.end())
    return IterGlobal;
  if (IterGlobal == Options.end())
    return IterLocal;
  if (IterLocal->getValue().Priority >= IterGlobal->getValue().Priority)
    return IterLocal;
  return IterGlobal;
}

std::optional<StringRef>
ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const {
  auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName,
                                 Context->getOptionsCollector());
  if (Iter != CheckOptions.end())
    return StringRef(Iter->getValue().Value);
  return std::nullopt;
}

static std::optional<bool> getAsBool(StringRef Value,
                                     const llvm::Twine &LookupName) {

  if (std::optional<bool> Parsed = llvm::yaml::parseBool(Value))
    return *Parsed;
  // To maintain backwards compatability, we support parsing numbers as
  // booleans, even though its not supported in YAML.
  long long Number;
  if (!Value.getAsInteger(10, Number))
    return Number != 0;
  return std::nullopt;
}

template <>
std::optional<bool>
ClangTidyCheck::OptionsView::get<bool>(StringRef LocalName) const {
  if (std::optional<StringRef> ValueOr = get(LocalName)) {
    if (auto Result = getAsBool(*ValueOr, NamePrefix + LocalName))
      return Result;
    diagnoseBadBooleanOption(NamePrefix + LocalName, *ValueOr);
  }
  return std::nullopt;
}

template <>
std::optional<bool>
ClangTidyCheck::OptionsView::getLocalOrGlobal<bool>(StringRef LocalName) const {
  auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName,
                                 Context->getOptionsCollector());
  if (Iter != CheckOptions.end()) {
    if (auto Result = getAsBool(Iter->getValue().Value, Iter->getKey()))
      return Result;
    diagnoseBadBooleanOption(Iter->getKey(), Iter->getValue().Value);
  }
  return std::nullopt;
}

void ClangTidyCheck::OptionsView::store(ClangTidyOptions::OptionMap &Options,
                                        StringRef LocalName,
                                        StringRef Value) const {
  Options[(NamePrefix + LocalName).str()] = Value;
}

void ClangTidyCheck::OptionsView::storeInt(ClangTidyOptions::OptionMap &Options,
                                           StringRef LocalName,
                                           int64_t Value) const {
  store(Options, LocalName, llvm::itostr(Value));
}

template <>
void ClangTidyCheck::OptionsView::store<bool>(
    ClangTidyOptions::OptionMap &Options, StringRef LocalName,
    bool Value) const {
  store(Options, LocalName, Value ? StringRef("true") : StringRef("false"));
}

std::optional<int64_t> ClangTidyCheck::OptionsView::getEnumInt(
    StringRef LocalName, ArrayRef<NameAndValue> Mapping, bool CheckGlobal,
    bool IgnoreCase) const {
  if (!CheckGlobal && Context->getOptionsCollector())
    Context->getOptionsCollector()->insert((NamePrefix + LocalName).str());
  auto Iter = CheckGlobal
                  ? findPriorityOption(CheckOptions, NamePrefix, LocalName,
                                       Context->getOptionsCollector())
                  : CheckOptions.find((NamePrefix + LocalName).str());
  if (Iter == CheckOptions.end())
    return std::nullopt;

  StringRef Value = Iter->getValue().Value;
  StringRef Closest;
  unsigned EditDistance = 3;
  for (const auto &NameAndEnum : Mapping) {
    if (IgnoreCase) {
      if (Value.equals_insensitive(NameAndEnum.second))
        return NameAndEnum.first;
    } else if (Value.equals(NameAndEnum.second)) {
      return NameAndEnum.first;
    } else if (Value.equals_insensitive(NameAndEnum.second)) {
      Closest = NameAndEnum.second;
      EditDistance = 0;
      continue;
    }
    unsigned Distance =
        Value.edit_distance(NameAndEnum.second, true, EditDistance);
    if (Distance < EditDistance) {
      EditDistance = Distance;
      Closest = NameAndEnum.second;
    }
  }
  if (EditDistance < 3)
    diagnoseBadEnumOption(Iter->getKey(), Iter->getValue().Value, Closest);
  else
    diagnoseBadEnumOption(Iter->getKey(), Iter->getValue().Value);
  return std::nullopt;
}

static constexpr llvm::StringLiteral ConfigWarning(
    "invalid configuration value '%0' for option '%1'%select{|; expected a "
    "bool|; expected an integer|; did you mean '%3'?}2");

void ClangTidyCheck::OptionsView::diagnoseBadBooleanOption(
    const Twine &Lookup, StringRef Unparsed) const {
  SmallString<64> Buffer;
  Context->configurationDiag(ConfigWarning)
      << Unparsed << Lookup.toStringRef(Buffer) << 1;
}

void ClangTidyCheck::OptionsView::diagnoseBadIntegerOption(
    const Twine &Lookup, StringRef Unparsed) const {
  SmallString<64> Buffer;
  Context->configurationDiag(ConfigWarning)
      << Unparsed << Lookup.toStringRef(Buffer) << 2;
}

void ClangTidyCheck::OptionsView::diagnoseBadEnumOption(
    const Twine &Lookup, StringRef Unparsed, StringRef Suggestion) const {
  SmallString<64> Buffer;
  auto Diag = Context->configurationDiag(ConfigWarning)
              << Unparsed << Lookup.toStringRef(Buffer);
  if (Suggestion.empty())
    Diag << 0;
  else
    Diag << 3 << Suggestion;
}

StringRef ClangTidyCheck::OptionsView::get(StringRef LocalName,
                                           StringRef Default) const {
  return get(LocalName).value_or(Default);
}

StringRef
ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName,
                                              StringRef Default) const {
  return getLocalOrGlobal(LocalName).value_or(Default);
}
} // namespace clang::tidy