| 1 |
//===--- TidyProvider.cpp - create options for running 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 "TidyProvider.h" |
| 10 |
#include "../clang-tidy/ClangTidyModuleRegistry.h" |
| 11 |
#include "Config.h" |
| 12 |
#include "support/FileCache.h" |
| 13 |
#include "support/Logger.h" |
| 14 |
#include "support/Path.h" |
| 15 |
#include "support/ThreadsafeFS.h" |
| 16 |
#include "llvm/ADT/STLExtras.h" |
| 17 |
#include "llvm/ADT/SmallString.h" |
| 18 |
#include "llvm/ADT/StringExtras.h" |
| 19 |
#include "llvm/ADT/StringSet.h" |
| 20 |
#include "llvm/Support/Allocator.h" |
| 21 |
#include "llvm/Support/Process.h" |
| 22 |
#include "llvm/Support/SourceMgr.h" |
| 23 |
#include <memory> |
| 24 |
#include <optional> |
| 25 |
|
| 26 |
namespace clang { |
| 27 |
namespace clangd { |
| 28 |
namespace { |
| 29 |
|
| 30 |
// Access to config from a .clang-tidy file, caching IO and parsing. |
| 31 |
class DotClangTidyCache : private FileCache { |
| 32 |
// We cache and expose shared_ptr to avoid copying the value on every lookup |
| 33 |
// when we're ultimately just going to pass it to mergeWith. |
| 34 |
mutable std::shared_ptr<const tidy::ClangTidyOptions> Value; |
| 35 |
|
| 36 |
public: |
| 37 |
DotClangTidyCache(PathRef Path) : FileCache(Path) {} |
| 38 |
|
| 39 |
std::shared_ptr<const tidy::ClangTidyOptions> |
| 40 |
get(const ThreadsafeFS &TFS, |
| 41 |
std::chrono::steady_clock::time_point FreshTime) const { |
| 42 |
std::shared_ptr<const tidy::ClangTidyOptions> Result; |
| 43 |
read( |
| 44 |
TFS, FreshTime, |
| 45 |
[this](std::optional<llvm::StringRef> Data) { |
| 46 |
Value.reset(); |
| 47 |
if (Data && !Data->empty()) { |
| 48 |
tidy::DiagCallback Diagnostics = [](const llvm::SMDiagnostic &D) { |
| 49 |
switch (D.getKind()) { |
| 50 |
case llvm::SourceMgr::DK_Error: |
| 51 |
elog("tidy-config error at {0}:{1}:{2}: {3}", D.getFilename(), |
| 52 |
D.getLineNo(), D.getColumnNo(), D.getMessage()); |
| 53 |
break; |
| 54 |
case llvm::SourceMgr::DK_Warning: |
| 55 |
log("tidy-config warning at {0}:{1}:{2}: {3}", D.getFilename(), |
| 56 |
D.getLineNo(), D.getColumnNo(), D.getMessage()); |
| 57 |
break; |
| 58 |
case llvm::SourceMgr::DK_Note: |
| 59 |
case llvm::SourceMgr::DK_Remark: |
| 60 |
vlog("tidy-config note at {0}:{1}:{2}: {3}", D.getFilename(), |
| 61 |
D.getLineNo(), D.getColumnNo(), D.getMessage()); |
| 62 |
break; |
| 63 |
} |
| 64 |
}; |
| 65 |
if (auto Parsed = tidy::parseConfigurationWithDiags( |
| 66 |
llvm::MemoryBufferRef(*Data, path()), Diagnostics)) |
| 67 |
Value = std::make_shared<const tidy::ClangTidyOptions>( |
| 68 |
std::move(*Parsed)); |
| 69 |
else |
| 70 |
elog("Error parsing clang-tidy configuration in {0}: {1}", path(), |
| 71 |
Parsed.getError().message()); |
| 72 |
} |
| 73 |
}, |
| 74 |
[&]() { Result = Value; }); |
| 75 |
return Result; |
| 76 |
} |
| 77 |
}; |
| 78 |
|
| 79 |
// Access to combined config from .clang-tidy files governing a source file. |
| 80 |
// Each config file is cached and the caches are shared for affected sources. |
| 81 |
// |
| 82 |
// FIXME: largely duplicates config::Provider::fromAncestorRelativeYAMLFiles. |
| 83 |
// Potentially useful for compile_commands.json too. Extract? |
| 84 |
class DotClangTidyTree { |
| 85 |
const ThreadsafeFS &FS; |
| 86 |
std::string RelPath; |
| 87 |
std::chrono::steady_clock::duration MaxStaleness; |
| 88 |
|
| 89 |
mutable std::mutex Mu; |
| 90 |
// Keys are the ancestor directory, not the actual config path within it. |
| 91 |
// We only insert into this map, so pointers to values are stable forever. |
| 92 |
// Mutex guards the map itself, not the values (which are threadsafe). |
| 93 |
mutable llvm::StringMap<DotClangTidyCache> Cache; |
| 94 |
|
| 95 |
public: |
| 96 |
DotClangTidyTree(const ThreadsafeFS &FS) |
| 97 |
: FS(FS), RelPath(".clang-tidy"), MaxStaleness(std::chrono::seconds(5)) {} |
| 98 |
|
| 99 |
void apply(tidy::ClangTidyOptions &Result, PathRef AbsPath) { |
| 100 |
namespace path = llvm::sys::path; |
| 101 |
assert(path::is_absolute(AbsPath)); |
| 102 |
|
| 103 |
// Compute absolute paths to all ancestors (substrings of P.Path). |
| 104 |
// Ensure cache entries for each ancestor exist in the map. |
| 105 |
llvm::SmallVector<DotClangTidyCache *> Caches; |
| 106 |
{ |
| 107 |
std::lock_guard<std::mutex> Lock(Mu); |
| 108 |
for (auto Ancestor = absoluteParent(AbsPath); !Ancestor.empty(); |
| 109 |
Ancestor = absoluteParent(Ancestor)) { |
| 110 |
auto It = Cache.find(Ancestor); |
| 111 |
// Assemble the actual config file path only if needed. |
| 112 |
if (It == Cache.end()) { |
| 113 |
llvm::SmallString<256> ConfigPath = Ancestor; |
| 114 |
path::append(ConfigPath, RelPath); |
| 115 |
It = Cache.try_emplace(Ancestor, ConfigPath.str()).first; |
| 116 |
} |
| 117 |
Caches.push_back(&It->second); |
| 118 |
} |
| 119 |
} |
| 120 |
// Finally query each individual file. |
| 121 |
// This will take a (per-file) lock for each file that actually exists. |
| 122 |
std::chrono::steady_clock::time_point FreshTime = |
| 123 |
std::chrono::steady_clock::now() - MaxStaleness; |
| 124 |
llvm::SmallVector<std::shared_ptr<const tidy::ClangTidyOptions>> |
| 125 |
OptionStack; |
| 126 |
for (const DotClangTidyCache *Cache : Caches) |
| 127 |
if (auto Config = Cache->get(FS, FreshTime)) { |
| 128 |
OptionStack.push_back(std::move(Config)); |
| 129 |
if (!OptionStack.back()->InheritParentConfig.value_or(false)) |
| 130 |
break; |
| 131 |
} |
| 132 |
unsigned Order = 1u; |
| 133 |
for (auto &Option : llvm::reverse(OptionStack)) |
| 134 |
Result.mergeWith(*Option, Order++); |
| 135 |
} |
| 136 |
}; |
| 137 |
|
| 138 |
} // namespace |
| 139 |
|
| 140 |
static void mergeCheckList(std::optional<std::string> &Checks, |
| 141 |
llvm::StringRef List) { |
| 142 |
if (List.empty()) |
| 143 |
return; |
| 144 |
if (!Checks || Checks->empty()) { |
| 145 |
Checks.emplace(List); |
| 146 |
return; |
| 147 |
} |
| 148 |
*Checks = llvm::join_items(",", *Checks, List); |
| 149 |
} |
| 150 |
|
| 151 |
TidyProviderRef provideEnvironment() { |
| 152 |
static const std::optional<std::string> User = [] { |
| 153 |
std::optional<std::string> Ret = llvm::sys::Process::GetEnv("USER"); |
| 154 |
#ifdef _WIN32 |
| 155 |
if (!Ret) |
| 156 |
return llvm::sys::Process::GetEnv("USERNAME"); |
| 157 |
#endif |
| 158 |
return Ret; |
| 159 |
}(); |
| 160 |
|
| 161 |
if (User) |
| 162 |
return |
| 163 |
[](tidy::ClangTidyOptions &Opts, llvm::StringRef) { Opts.User = User; }; |
| 164 |
// FIXME: Once function_ref and unique_function operator= operators handle |
| 165 |
// null values, this can return null. |
| 166 |
return [](tidy::ClangTidyOptions &, llvm::StringRef) {}; |
| 167 |
} |
| 168 |
|
| 169 |
TidyProviderRef provideDefaultChecks() { |
| 170 |
// These default checks are chosen for: |
| 171 |
// - low false-positive rate |
| 172 |
// - providing a lot of value |
| 173 |
// - being reasonably efficient |
| 174 |
static const std::string DefaultChecks = llvm::join_items( |
| 175 |
",", "readability-misleading-indentation", "readability-deleted-default", |
| 176 |
"bugprone-integer-division", "bugprone-sizeof-expression", |
| 177 |
"bugprone-suspicious-missing-comma", "bugprone-unused-raii", |
| 178 |
"bugprone-unused-return-value", "misc-unused-using-decls", |
| 179 |
"misc-unused-alias-decls", "misc-definitions-in-headers"); |
| 180 |
return [](tidy::ClangTidyOptions &Opts, llvm::StringRef) { |
| 181 |
if (!Opts.Checks || Opts.Checks->empty()) |
| 182 |
Opts.Checks = DefaultChecks; |
| 183 |
}; |
| 184 |
} |
| 185 |
|
| 186 |
TidyProvider addTidyChecks(llvm::StringRef Checks, |
| 187 |
llvm::StringRef WarningsAsErrors) { |
| 188 |
return [Checks = std::string(Checks), |
| 189 |
WarningsAsErrors = std::string(WarningsAsErrors)]( |
| 190 |
tidy::ClangTidyOptions &Opts, llvm::StringRef) { |
| 191 |
mergeCheckList(Opts.Checks, Checks); |
| 192 |
mergeCheckList(Opts.WarningsAsErrors, WarningsAsErrors); |
| 193 |
}; |
| 194 |
} |
| 195 |
|
| 196 |
TidyProvider disableUnusableChecks(llvm::ArrayRef<std::string> ExtraBadChecks) { |
| 197 |
constexpr llvm::StringLiteral Seperator(","); |
| 198 |
static const std::string BadChecks = |
| 199 |
llvm::join_items(Seperator, |
| 200 |
// We want this list to start with a seperator to |
| 201 |
// simplify appending in the lambda. So including an |
| 202 |
// empty string here will force that. |
| 203 |
"", |
| 204 |
// ----- False Positives ----- |
| 205 |
|
| 206 |
// Check relies on seeing ifndef/define/endif directives, |
| 207 |
// clangd doesn't replay those when using a preamble. |
| 208 |
"-llvm-header-guard", "-modernize-macro-to-enum", |
| 209 |
|
| 210 |
// ----- Crashing Checks ----- |
| 211 |
|
| 212 |
// Check can choke on invalid (intermediate) c++ |
| 213 |
// code, which is often the case when clangd |
| 214 |
// tries to build an AST. |
| 215 |
"-bugprone-use-after-move", |
| 216 |
// Alias for bugprone-use-after-move. |
| 217 |
"-hicpp-invalid-access-moved", |
| 218 |
|
| 219 |
// ----- Performance problems ----- |
| 220 |
|
| 221 |
// This check runs expensive analysis for each variable. |
| 222 |
// It has been observed to increase reparse time by 10x. |
| 223 |
"-misc-const-correctness"); |
| 224 |
|
| 225 |
size_t Size = BadChecks.size(); |
| 226 |
for (const std::string &Str : ExtraBadChecks) { |
| 227 |
if (Str.empty()) |
| 228 |
continue; |
| 229 |
Size += Seperator.size(); |
| 230 |
if (LLVM_LIKELY(Str.front() != '-')) |
| 231 |
++Size; |
| 232 |
Size += Str.size(); |
| 233 |
} |
| 234 |
std::string DisableGlob; |
| 235 |
DisableGlob.reserve(Size); |
| 236 |
DisableGlob += BadChecks; |
| 237 |
for (const std::string &Str : ExtraBadChecks) { |
| 238 |
if (Str.empty()) |
| 239 |
continue; |
| 240 |
DisableGlob += Seperator; |
| 241 |
if (LLVM_LIKELY(Str.front() != '-')) |
| 242 |
DisableGlob.push_back('-'); |
| 243 |
DisableGlob += Str; |
| 244 |
} |
| 245 |
|
| 246 |
return [DisableList(std::move(DisableGlob))](tidy::ClangTidyOptions &Opts, |
| 247 |
llvm::StringRef) { |
| 248 |
if (Opts.Checks && !Opts.Checks->empty()) |
| 249 |
Opts.Checks->append(DisableList); |
| 250 |
}; |
| 251 |
} |
| 252 |
|
| 253 |
TidyProviderRef provideClangdConfig() { |
| 254 |
return [](tidy::ClangTidyOptions &Opts, llvm::StringRef) { |
| 255 |
const auto &CurTidyConfig = Config::current().Diagnostics.ClangTidy; |
| 256 |
if (!CurTidyConfig.Checks.empty()) |
| 257 |
mergeCheckList(Opts.Checks, CurTidyConfig.Checks); |
| 258 |
|
| 259 |
for (const auto &CheckOption : CurTidyConfig.CheckOptions) |
| 260 |
Opts.CheckOptions.insert_or_assign(CheckOption.getKey(), |
| 261 |
tidy::ClangTidyOptions::ClangTidyValue( |
| 262 |
CheckOption.getValue(), 10000U)); |
| 263 |
}; |
| 264 |
} |
| 265 |
|
| 266 |
TidyProvider provideClangTidyFiles(ThreadsafeFS &TFS) { |
| 267 |
return [Tree = std::make_unique<DotClangTidyTree>(TFS)]( |
| 268 |
tidy::ClangTidyOptions &Opts, llvm::StringRef Filename) { |
| 269 |
Tree->apply(Opts, Filename); |
| 270 |
}; |
| 271 |
} |
| 272 |
|
| 273 |
TidyProvider combine(std::vector<TidyProvider> Providers) { |
| 274 |
// FIXME: Once function_ref and unique_function operator= operators handle |
| 275 |
// null values, we should filter out any Providers that are null. Right now we |
| 276 |
// have to ensure we dont pass any providers that are null. |
| 277 |
return [Providers(std::move(Providers))](tidy::ClangTidyOptions &Opts, |
| 278 |
llvm::StringRef Filename) { |
| 279 |
for (const auto &Provider : Providers) |
| 280 |
Provider(Opts, Filename); |
| 281 |
}; |
| 282 |
} |
| 283 |
|
| 284 |
tidy::ClangTidyOptions getTidyOptionsForFile(TidyProviderRef Provider, |
| 285 |
llvm::StringRef Filename) { |
| 286 |
tidy::ClangTidyOptions Opts = tidy::ClangTidyOptions::getDefaults(); |
| 287 |
Opts.Checks->clear(); |
| 288 |
if (Provider) |
| 289 |
Provider(Opts, Filename); |
| 290 |
return Opts; |
| 291 |
} |
| 292 |
|
| 293 |
bool isRegisteredTidyCheck(llvm::StringRef Check) { |
| 294 |
assert(!Check.empty()); |
| 295 |
assert(!Check.contains('*') && !Check.contains(',') && |
| 296 |
"isRegisteredCheck doesn't support globs"); |
| 297 |
assert(Check.ltrim().front() != '-'); |
| 298 |
|
| 299 |
static const llvm::StringSet<llvm::BumpPtrAllocator> AllChecks = [] { |
| 300 |
llvm::StringSet<llvm::BumpPtrAllocator> Result; |
| 301 |
tidy::ClangTidyCheckFactories Factories; |
| 302 |
for (tidy::ClangTidyModuleRegistry::entry E : |
| 303 |
tidy::ClangTidyModuleRegistry::entries()) |
| 304 |
E.instantiate()->addCheckFactories(Factories); |
| 305 |
for (const auto &Factory : Factories) |
| 306 |
Result.insert(Factory.getKey()); |
| 307 |
return Result; |
| 308 |
}(); |
| 309 |
|
| 310 |
return AllChecks.contains(Check); |
| 311 |
} |
| 312 |
} // namespace clangd |
| 313 |
} // namespace clang |