-
Notifications
You must be signed in to change notification settings - Fork 13.3k
/
Copy pathTidyProvider.cpp
335 lines (302 loc) · 12 KB
/
TidyProvider.cpp
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
//===--- TidyProvider.cpp - create options for running 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 "TidyProvider.h"
#include "../clang-tidy/ClangTidyModuleRegistry.h"
#include "../clang-tidy/ClangTidyOptions.h"
#include "Config.h"
#include "support/FileCache.h"
#include "support/Logger.h"
#include "support/Path.h"
#include "support/ThreadsafeFS.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/SourceMgr.h"
#include <memory>
#include <optional>
namespace clang {
namespace clangd {
namespace {
// Access to config from a .clang-tidy file, caching IO and parsing.
class DotClangTidyCache : private FileCache {
// We cache and expose shared_ptr to avoid copying the value on every lookup
// when we're ultimately just going to pass it to mergeWith.
mutable std::shared_ptr<const tidy::ClangTidyOptions> Value;
public:
DotClangTidyCache(PathRef Path) : FileCache(Path) {}
std::shared_ptr<const tidy::ClangTidyOptions>
get(const ThreadsafeFS &TFS,
std::chrono::steady_clock::time_point FreshTime) const {
std::shared_ptr<const tidy::ClangTidyOptions> Result;
read(
TFS, FreshTime,
[this](std::optional<llvm::StringRef> Data) {
Value.reset();
if (Data && !Data->empty()) {
auto Diagnostics = [](const llvm::SMDiagnostic &D) {
switch (D.getKind()) {
case llvm::SourceMgr::DK_Error:
elog("tidy-config error at {0}:{1}:{2}: {3}", D.getFilename(),
D.getLineNo(), D.getColumnNo(), D.getMessage());
break;
case llvm::SourceMgr::DK_Warning:
log("tidy-config warning at {0}:{1}:{2}: {3}", D.getFilename(),
D.getLineNo(), D.getColumnNo(), D.getMessage());
break;
case llvm::SourceMgr::DK_Note:
case llvm::SourceMgr::DK_Remark:
vlog("tidy-config note at {0}:{1}:{2}: {3}", D.getFilename(),
D.getLineNo(), D.getColumnNo(), D.getMessage());
break;
}
};
if (auto Parsed = tidy::parseConfigurationWithDiags(
llvm::MemoryBufferRef(*Data, path()), Diagnostics))
Value = std::make_shared<const tidy::ClangTidyOptions>(
std::move(*Parsed));
else
elog("Error parsing clang-tidy configuration in {0}: {1}", path(),
Parsed.getError().message());
}
},
[&]() { Result = Value; });
return Result;
}
};
// Access to combined config from .clang-tidy files governing a source file.
// Each config file is cached and the caches are shared for affected sources.
//
// FIXME: largely duplicates config::Provider::fromAncestorRelativeYAMLFiles.
// Potentially useful for compile_commands.json too. Extract?
class DotClangTidyTree {
const ThreadsafeFS &FS;
std::string RelPath;
std::chrono::steady_clock::duration MaxStaleness;
mutable std::mutex Mu;
// Keys are the ancestor directory, not the actual config path within it.
// We only insert into this map, so pointers to values are stable forever.
// Mutex guards the map itself, not the values (which are threadsafe).
mutable llvm::StringMap<DotClangTidyCache> Cache;
public:
DotClangTidyTree(const ThreadsafeFS &FS)
: FS(FS), RelPath(".clang-tidy"), MaxStaleness(std::chrono::seconds(5)) {}
void apply(tidy::ClangTidyOptions &Result, PathRef AbsPath) {
namespace path = llvm::sys::path;
assert(path::is_absolute(AbsPath));
// Compute absolute paths to all ancestors (substrings of P.Path).
// Ensure cache entries for each ancestor exist in the map.
llvm::SmallVector<DotClangTidyCache *> Caches;
{
std::lock_guard<std::mutex> Lock(Mu);
for (auto Ancestor = absoluteParent(AbsPath); !Ancestor.empty();
Ancestor = absoluteParent(Ancestor)) {
auto It = Cache.find(Ancestor);
// Assemble the actual config file path only if needed.
if (It == Cache.end()) {
llvm::SmallString<256> ConfigPath = Ancestor;
path::append(ConfigPath, RelPath);
It = Cache.try_emplace(Ancestor, ConfigPath.str()).first;
}
Caches.push_back(&It->second);
}
}
// Finally query each individual file.
// This will take a (per-file) lock for each file that actually exists.
std::chrono::steady_clock::time_point FreshTime =
std::chrono::steady_clock::now() - MaxStaleness;
llvm::SmallVector<std::shared_ptr<const tidy::ClangTidyOptions>>
OptionStack;
for (const DotClangTidyCache *Cache : Caches)
if (auto Config = Cache->get(FS, FreshTime)) {
OptionStack.push_back(std::move(Config));
if (!OptionStack.back()->InheritParentConfig.value_or(false))
break;
}
unsigned Order = 1u;
for (auto &Option : llvm::reverse(OptionStack))
Result.mergeWith(*Option, Order++);
}
};
} // namespace
static void mergeCheckList(std::optional<std::string> &Checks,
llvm::StringRef List) {
if (List.empty())
return;
if (!Checks || Checks->empty()) {
Checks.emplace(List);
return;
}
*Checks = llvm::join_items(",", *Checks, List);
}
TidyProvider provideEnvironment() {
static const std::optional<std::string> User = [] {
std::optional<std::string> Ret = llvm::sys::Process::GetEnv("USER");
#ifdef _WIN32
if (!Ret)
return llvm::sys::Process::GetEnv("USERNAME");
#endif
return Ret;
}();
if (User)
return
[](tidy::ClangTidyOptions &Opts, llvm::StringRef) { Opts.User = User; };
// FIXME: Once function_ref and unique_function operator= operators handle
// null values, this can return null.
return [](tidy::ClangTidyOptions &, llvm::StringRef) {};
}
TidyProvider provideDefaultChecks() {
// These default checks are chosen for:
// - low false-positive rate
// - providing a lot of value
// - being reasonably efficient
static const std::string DefaultChecks = llvm::join_items(
",", "readability-misleading-indentation", "readability-deleted-default",
"bugprone-integer-division", "bugprone-sizeof-expression",
"bugprone-suspicious-missing-comma", "bugprone-unused-raii",
"bugprone-unused-return-value", "misc-unused-using-decls",
"misc-unused-alias-decls", "misc-definitions-in-headers");
return [](tidy::ClangTidyOptions &Opts, llvm::StringRef) {
if (!Opts.Checks || Opts.Checks->empty())
Opts.Checks = DefaultChecks;
};
}
TidyProvider addTidyChecks(llvm::StringRef Checks,
llvm::StringRef WarningsAsErrors) {
return [Checks = std::string(Checks),
WarningsAsErrors = std::string(WarningsAsErrors)](
tidy::ClangTidyOptions &Opts, llvm::StringRef) {
mergeCheckList(Opts.Checks, Checks);
mergeCheckList(Opts.WarningsAsErrors, WarningsAsErrors);
};
}
TidyProvider disableUnusableChecks(llvm::ArrayRef<std::string> ExtraBadChecks) {
constexpr llvm::StringLiteral Separator(",");
static const std::string BadChecks = llvm::join_items(
Separator,
// We want this list to start with a separator to
// simplify appending in the lambda. So including an
// empty string here will force that.
"",
// include-cleaner is directly integrated in IncludeCleaner.cpp
"-misc-include-cleaner",
// ----- False Positives -----
// Check relies on seeing ifndef/define/endif directives,
// clangd doesn't replay those when using a preamble.
"-llvm-header-guard", "-modernize-macro-to-enum",
"-cppcoreguidelines-macro-to-enum",
// ----- Crashing Checks -----
// Check can choke on invalid (intermediate) c++
// code, which is often the case when clangd
// tries to build an AST.
"-bugprone-use-after-move",
// Alias for bugprone-use-after-move.
"-hicpp-invalid-access-moved",
// Checks use dataflow analysis, which might hang/crash unexpectedly on
// incomplete code.
"-bugprone-unchecked-optional-access",
"-bugprone-null-check-after-dereference");
size_t Size = BadChecks.size();
for (const std::string &Str : ExtraBadChecks) {
if (Str.empty())
continue;
Size += Separator.size();
if (LLVM_LIKELY(Str.front() != '-'))
++Size;
Size += Str.size();
}
std::string DisableGlob;
DisableGlob.reserve(Size);
DisableGlob += BadChecks;
for (const std::string &Str : ExtraBadChecks) {
if (Str.empty())
continue;
DisableGlob += Separator;
if (LLVM_LIKELY(Str.front() != '-'))
DisableGlob.push_back('-');
DisableGlob += Str;
}
return [DisableList(std::move(DisableGlob))](tidy::ClangTidyOptions &Opts,
llvm::StringRef) {
if (Opts.Checks && !Opts.Checks->empty())
Opts.Checks->append(DisableList);
};
}
TidyProvider provideClangdConfig() {
return [](tidy::ClangTidyOptions &Opts, llvm::StringRef) {
const auto &CurTidyConfig = Config::current().Diagnostics.ClangTidy;
if (!CurTidyConfig.Checks.empty())
mergeCheckList(Opts.Checks, CurTidyConfig.Checks);
for (const auto &CheckOption : CurTidyConfig.CheckOptions)
Opts.CheckOptions.insert_or_assign(CheckOption.getKey(),
tidy::ClangTidyOptions::ClangTidyValue(
CheckOption.getValue(), 10000U));
};
}
TidyProvider provideClangTidyFiles(ThreadsafeFS &TFS) {
return [Tree = std::make_unique<DotClangTidyTree>(TFS)](
tidy::ClangTidyOptions &Opts, llvm::StringRef Filename) {
Tree->apply(Opts, Filename);
};
}
TidyProvider combine(std::vector<TidyProvider> Providers) {
// FIXME: Once function_ref and unique_function operator= operators handle
// null values, we should filter out any Providers that are null. Right now we
// have to ensure we dont pass any providers that are null.
return [Providers(std::move(Providers))](tidy::ClangTidyOptions &Opts,
llvm::StringRef Filename) {
for (const auto &Provider : Providers)
Provider(Opts, Filename);
};
}
tidy::ClangTidyOptions getTidyOptionsForFile(TidyProviderRef Provider,
llvm::StringRef Filename) {
// getDefaults instantiates all check factories, which are registered at link
// time. So cache the results once.
static const auto *DefaultOpts = [] {
auto *Opts = new tidy::ClangTidyOptions;
*Opts = tidy::ClangTidyOptions::getDefaults();
Opts->Checks->clear();
return Opts;
}();
auto Opts = *DefaultOpts;
if (Provider)
Provider(Opts, Filename);
return Opts;
}
bool isRegisteredTidyCheck(llvm::StringRef Check) {
assert(!Check.empty());
assert(!Check.contains('*') && !Check.contains(',') &&
"isRegisteredCheck doesn't support globs");
assert(Check.ltrim().front() != '-');
static const llvm::StringSet<llvm::BumpPtrAllocator> AllChecks = [] {
llvm::StringSet<llvm::BumpPtrAllocator> Result;
tidy::ClangTidyCheckFactories Factories;
for (tidy::ClangTidyModuleRegistry::entry E :
tidy::ClangTidyModuleRegistry::entries())
E.instantiate()->addCheckFactories(Factories);
for (const auto &Factory : Factories)
Result.insert(Factory.getKey());
return Result;
}();
return AllChecks.contains(Check);
}
std::optional<bool> isFastTidyCheck(llvm::StringRef Check) {
static auto &Fast = *new llvm::StringMap<bool>{
#define FAST(CHECK, TIME) {#CHECK,true},
#define SLOW(CHECK, TIME) {#CHECK,false},
#include "TidyFastChecks.inc"
};
if (auto It = Fast.find(Check); It != Fast.end())
return It->second;
return std::nullopt;
}
} // namespace clangd
} // namespace clang