[clang-tidy][NFC] Don't qualify names unless strictly necessary (#185169)

We have a de-facto policy in clang-tidy to not qualify names unless
absolutely necessary. We're *mostly* consistent about that (especially
in new code), but a number of deviations have accumulated over the
years. We even have cases where the same name is sometimes qualified and
sometimes not *in the same file*. This makes it jarring to read the
code, and, I imagine, more confusing for newcomers to contribute to the
project (do I qualify X or not?). This PR tries to improve the situation
and regularize the codebase.
This commit is contained in:
Victor Chernyakin 2026-03-11 06:40:25 -07:00 committed by GitHub
parent 18cb220146
commit 6f23ba2555
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
170 changed files with 810 additions and 884 deletions

View File

@ -363,9 +363,8 @@ ClangTidyASTConsumerFactory::ClangTidyASTConsumerFactory(
}
#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
static void
setStaticAnalyzerCheckerOpts(const ClangTidyOptions &Opts,
clang::AnalyzerOptions &AnalyzerOptions) {
static void setStaticAnalyzerCheckerOpts(const ClangTidyOptions &Opts,
AnalyzerOptions &AnalyzerOptions) {
for (const auto &Opt : Opts.CheckOptions) {
StringRef OptName(Opt.getKey());
if (!OptName.consume_front(AnalyzerCheckNamePrefix))
@ -410,9 +409,9 @@ static CheckersList getAnalyzerCheckersAndPackages(ClangTidyContext &Context,
}
#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
std::unique_ptr<clang::ASTConsumer>
ClangTidyASTConsumerFactory::createASTConsumer(
clang::CompilerInstance &Compiler, StringRef File) {
std::unique_ptr<ASTConsumer>
ClangTidyASTConsumerFactory::createASTConsumer(CompilerInstance &Compiler,
StringRef File) {
// FIXME: Move this to a separate method, so that CreateASTConsumer doesn't
// modify Compiler.
SourceManager *SM = &Compiler.getSourceManager();
@ -517,10 +516,10 @@ ClangTidyOptions::OptionMap ClangTidyASTConsumerFactory::getCheckOptions() {
std::vector<std::string> getCheckNames(const ClangTidyOptions &Options,
bool AllowEnablingAnalyzerAlphaCheckers,
bool ExperimentalCustomChecks) {
clang::tidy::ClangTidyContext Context(
std::make_unique<DefaultOptionsProvider>(ClangTidyGlobalOptions(),
Options),
AllowEnablingAnalyzerAlphaCheckers, false, ExperimentalCustomChecks);
ClangTidyContext Context(std::make_unique<DefaultOptionsProvider>(
ClangTidyGlobalOptions(), Options),
AllowEnablingAnalyzerAlphaCheckers, false,
ExperimentalCustomChecks);
ClangTidyASTConsumerFactory Factory(Context);
return Factory.getCheckNames();
}
@ -543,10 +542,10 @@ ClangTidyOptions::OptionMap
getCheckOptions(const ClangTidyOptions &Options,
bool AllowEnablingAnalyzerAlphaCheckers,
bool ExperimentalCustomChecks) {
clang::tidy::ClangTidyContext Context(
std::make_unique<DefaultOptionsProvider>(ClangTidyGlobalOptions(),
Options),
AllowEnablingAnalyzerAlphaCheckers, false, ExperimentalCustomChecks);
ClangTidyContext Context(std::make_unique<DefaultOptionsProvider>(
ClangTidyGlobalOptions(), Options),
AllowEnablingAnalyzerAlphaCheckers, false,
ExperimentalCustomChecks);
ClangTidyDiagnosticConsumer DiagConsumer(Context);
auto DiagOpts = std::make_unique<DiagnosticOptions>();
DiagnosticsEngine DE(llvm::makeIntrusiveRefCnt<DiagnosticIDs>(), *DiagOpts,
@ -557,12 +556,11 @@ getCheckOptions(const ClangTidyOptions &Options,
}
std::vector<ClangTidyError>
runClangTidy(clang::tidy::ClangTidyContext &Context,
const CompilationDatabase &Compilations,
runClangTidy(ClangTidyContext &Context, const CompilationDatabase &Compilations,
ArrayRef<std::string> InputFiles,
llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
bool ApplyAnyFix, bool EnableCheckProfile,
llvm::StringRef StoreCheckProfile, bool Quiet) {
StringRef StoreCheckProfile, bool Quiet) {
ClangTool Tool(Compilations, InputFiles,
std::make_shared<PCHContainerOperations>(), BaseFS);
@ -686,7 +684,7 @@ void handleErrors(llvm::ArrayRef<ClangTidyError> Errors,
WarningsAsErrorsCount += Reporter.getWarningsAsErrorsCount();
}
void exportReplacements(const llvm::StringRef MainFilePath,
void exportReplacements(const StringRef MainFilePath,
const std::vector<ClangTidyError> &Errors,
raw_ostream &OS) {
TranslationUnitDiagnostics TUD;
@ -707,7 +705,7 @@ ChecksAndOptions getAllChecksAndOptions(bool AllowEnablingAnalyzerAlphaCheckers,
ChecksAndOptions Result;
ClangTidyOptions Opts;
Opts.Checks = "*";
clang::tidy::ClangTidyContext Context(
ClangTidyContext Context(
std::make_unique<DefaultOptionsProvider>(ClangTidyGlobalOptions(), Opts),
AllowEnablingAnalyzerAlphaCheckers, false, ExperimentalCustomChecks);
ClangTidyCheckFactories Factories;

View File

@ -38,8 +38,8 @@ public:
IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS = nullptr);
/// Returns an ASTConsumer that runs the specified clang-tidy checks.
std::unique_ptr<clang::ASTConsumer>
createASTConsumer(clang::CompilerInstance &Compiler, StringRef File);
std::unique_ptr<ASTConsumer> createASTConsumer(CompilerInstance &Compiler,
StringRef File);
/// Get the list of enabled checks.
std::vector<std::string> getCheckNames();
@ -91,13 +91,12 @@ void filterCheckOptions(ClangTidyOptions &Options,
/// the profile will not be output to stderr, but will instead be stored
/// as a JSON file in the specified directory.
std::vector<ClangTidyError>
runClangTidy(clang::tidy::ClangTidyContext &Context,
runClangTidy(ClangTidyContext &Context,
const tooling::CompilationDatabase &Compilations,
ArrayRef<std::string> InputFiles,
llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
bool ApplyAnyFix, bool EnableCheckProfile = false,
llvm::StringRef StoreCheckProfile = StringRef(),
bool Quiet = false);
StringRef StoreCheckProfile = {}, bool Quiet = false);
/// Controls what kind of fixes clang-tidy is allowed to apply.
enum FixBehaviour {

View File

@ -510,57 +510,57 @@ void ClangTidyDiagnosticConsumer::forwardDiagnostic(const Diagnostic &Info) {
for (unsigned Index = 0; Index < Info.getNumArgs(); ++Index) {
const DiagnosticsEngine::ArgumentKind Kind = Info.getArgKind(Index);
switch (Kind) {
case clang::DiagnosticsEngine::ak_std_string:
case DiagnosticsEngine::ak_std_string:
Builder << Info.getArgStdStr(Index);
break;
case clang::DiagnosticsEngine::ak_c_string:
case DiagnosticsEngine::ak_c_string:
Builder << Info.getArgCStr(Index);
break;
case clang::DiagnosticsEngine::ak_sint:
case DiagnosticsEngine::ak_sint:
Builder << Info.getArgSInt(Index);
break;
case clang::DiagnosticsEngine::ak_uint:
case DiagnosticsEngine::ak_uint:
Builder << Info.getArgUInt(Index);
break;
case clang::DiagnosticsEngine::ak_tokenkind:
case DiagnosticsEngine::ak_tokenkind:
Builder << static_cast<tok::TokenKind>(Info.getRawArg(Index));
break;
case clang::DiagnosticsEngine::ak_identifierinfo:
case DiagnosticsEngine::ak_identifierinfo:
Builder << Info.getArgIdentifier(Index);
break;
case clang::DiagnosticsEngine::ak_qual:
case DiagnosticsEngine::ak_qual:
Builder << Qualifiers::fromOpaqueValue(Info.getRawArg(Index));
break;
case clang::DiagnosticsEngine::ak_qualtype:
case DiagnosticsEngine::ak_qualtype:
Builder << QualType::getFromOpaquePtr(
reinterpret_cast<void *>(Info.getRawArg(Index)));
break;
case clang::DiagnosticsEngine::ak_declarationname:
case DiagnosticsEngine::ak_declarationname:
Builder << DeclarationName::getFromOpaqueInteger(Info.getRawArg(Index));
break;
case clang::DiagnosticsEngine::ak_nameddecl:
case DiagnosticsEngine::ak_nameddecl:
Builder << reinterpret_cast<const NamedDecl *>(Info.getRawArg(Index));
break;
case clang::DiagnosticsEngine::ak_nestednamespec:
case DiagnosticsEngine::ak_nestednamespec:
Builder << NestedNameSpecifier::getFromVoidPointer(
reinterpret_cast<void *>(Info.getRawArg(Index)));
break;
case clang::DiagnosticsEngine::ak_declcontext:
case DiagnosticsEngine::ak_declcontext:
Builder << reinterpret_cast<DeclContext *>(Info.getRawArg(Index));
break;
case clang::DiagnosticsEngine::ak_qualtype_pair:
case DiagnosticsEngine::ak_qualtype_pair:
assert(false); // This one is not passed around.
break;
case clang::DiagnosticsEngine::ak_attr:
case DiagnosticsEngine::ak_attr:
Builder << reinterpret_cast<Attr *>(Info.getRawArg(Index));
break;
case clang::DiagnosticsEngine::ak_attr_info:
case DiagnosticsEngine::ak_attr_info:
Builder << reinterpret_cast<AttributeCommonInfo *>(Info.getRawArg(Index));
break;
case clang::DiagnosticsEngine::ak_addrspace:
case DiagnosticsEngine::ak_addrspace:
Builder << static_cast<LangAS>(Info.getRawArg(Index));
break;
case clang::DiagnosticsEngine::ak_expr:
case DiagnosticsEngine::ak_expr:
Builder << reinterpret_cast<const Expr *>(Info.getRawArg(Index));
}
}

View File

@ -28,12 +28,12 @@ class ClangTidyContext;
class ClangTidyCheckFactories {
public:
using CheckFactory = std::function<std::unique_ptr<ClangTidyCheck>(
llvm::StringRef Name, ClangTidyContext *Context)>;
StringRef Name, ClangTidyContext *Context)>;
/// Registers check \p Factory with name \p Name.
///
/// For all checks that have default constructors, use \c registerCheck.
void registerCheckFactory(llvm::StringRef Name, CheckFactory Factory);
void registerCheckFactory(StringRef Name, CheckFactory Factory);
/// Registers the \c CheckType with the name \p Name.
///
@ -56,14 +56,14 @@ public:
/// }
/// };
/// \endcode
template <typename CheckType> void registerCheck(llvm::StringRef CheckName) {
template <typename CheckType> void registerCheck(StringRef CheckName) {
registerCheckFactory(CheckName,
[](llvm::StringRef Name, ClangTidyContext *Context) {
[](StringRef Name, ClangTidyContext *Context) {
return std::make_unique<CheckType>(Name, Context);
});
}
void eraseCheck(llvm::StringRef CheckName) { Factories.erase(CheckName); }
void eraseCheck(StringRef CheckName) { Factories.erase(CheckName); }
/// Create instances of checks that are enabled.
std::vector<std::unique_ptr<ClangTidyCheck>>

View File

@ -324,8 +324,7 @@ ClangTidyOptions ClangTidyOptions::merge(const ClangTidyOptions &Other,
return Result;
}
ClangTidyOptions
ClangTidyOptionsProvider::getOptions(llvm::StringRef FileName) {
ClangTidyOptions ClangTidyOptionsProvider::getOptions(StringRef FileName) {
ClangTidyOptions Result;
unsigned Priority = 0;
for (auto &Source : getRawOptions(FileName))
@ -334,7 +333,7 @@ ClangTidyOptionsProvider::getOptions(llvm::StringRef FileName) {
}
std::vector<OptionsSource>
DefaultOptionsProvider::getRawOptions(llvm::StringRef FileName) {
DefaultOptionsProvider::getRawOptions(StringRef FileName) {
std::vector<OptionsSource> Result;
Result.emplace_back(DefaultOptions, OptionsSourceTypeDefaultBinary);
return Result;
@ -350,14 +349,14 @@ ConfigOptionsProvider::ConfigOptionsProvider(
ConfigOptions(std::move(ConfigOptions)) {}
std::vector<OptionsSource>
ConfigOptionsProvider::getRawOptions(llvm::StringRef FileName) {
ConfigOptionsProvider::getRawOptions(StringRef FileName) {
std::vector<OptionsSource> RawOptions =
DefaultOptionsProvider::getRawOptions(FileName);
if (ConfigOptions.InheritParentConfig.value_or(false)) {
LLVM_DEBUG(llvm::dbgs()
<< "Getting options for file " << FileName << "...\n");
llvm::ErrorOr<llvm::SmallString<128>> AbsoluteFilePath =
llvm::ErrorOr<SmallString<128>> AbsoluteFilePath =
getNormalizedAbsolutePath(FileName);
if (AbsoluteFilePath)
addRawFileOptions(AbsoluteFilePath->str(), RawOptions);
@ -390,10 +389,10 @@ FileOptionsBaseProvider::FileOptionsBaseProvider(
OverrideOptions(std::move(OverrideOptions)),
ConfigHandlers(std::move(ConfigHandlers)) {}
llvm::ErrorOr<llvm::SmallString<128>>
FileOptionsBaseProvider::getNormalizedAbsolutePath(llvm::StringRef Path) {
llvm::ErrorOr<SmallString<128>>
FileOptionsBaseProvider::getNormalizedAbsolutePath(StringRef Path) {
assert(FS && "FS must be set.");
llvm::SmallString<128> NormalizedAbsolutePath = {Path};
SmallString<128> NormalizedAbsolutePath = {Path};
const std::error_code Err = FS->makeAbsolute(NormalizedAbsolutePath);
if (Err)
return Err;
@ -402,7 +401,7 @@ FileOptionsBaseProvider::getNormalizedAbsolutePath(llvm::StringRef Path) {
}
void FileOptionsBaseProvider::addRawFileOptions(
llvm::StringRef AbsolutePath, std::vector<OptionsSource> &CurOptions) {
StringRef AbsolutePath, std::vector<OptionsSource> &CurOptions) {
auto CurSize = CurOptions.size();
// Look for a suitable configuration file in all parent directories of the
// file. Start with the immediate parent directory and move up.
@ -465,7 +464,7 @@ FileOptionsProvider::getRawOptions(StringRef FileName) {
LLVM_DEBUG(llvm::dbgs() << "Getting options for file " << FileName
<< "...\n");
const llvm::ErrorOr<llvm::SmallString<128>> AbsoluteFilePath =
const llvm::ErrorOr<SmallString<128>> AbsoluteFilePath =
getNormalizedAbsolutePath(FileName);
if (!AbsoluteFilePath)
return {};

View File

@ -116,7 +116,7 @@ struct ClangTidyOptions {
struct ClangTidyValue {
ClangTidyValue() = default;
ClangTidyValue(const char *Value) : Value(Value) {}
ClangTidyValue(llvm::StringRef Value, unsigned Priority = 0)
ClangTidyValue(StringRef Value, unsigned Priority = 0)
: Value(Value), Priority(Priority) {}
std::string Value;
@ -138,9 +138,9 @@ struct ClangTidyOptions {
struct CustomCheckValue {
std::string Name;
std::string Query;
llvm::SmallVector<CustomCheckDiag> Diags;
SmallVector<CustomCheckDiag> Diags;
};
using CustomCheckValueList = llvm::SmallVector<CustomCheckValue>;
using CustomCheckValueList = SmallVector<CustomCheckValue>;
std::optional<CustomCheckValueList> CustomChecks;
using ArgList = std::vector<std::string>;
@ -193,12 +193,11 @@ public:
/// Returns an ordered vector of OptionsSources, in order of increasing
/// priority.
virtual std::vector<OptionsSource>
getRawOptions(llvm::StringRef FileName) = 0;
virtual std::vector<OptionsSource> getRawOptions(StringRef FileName) = 0;
/// Returns options applying to a specific translation unit with the
/// specified \p FileName.
ClangTidyOptions getOptions(llvm::StringRef FileName);
ClangTidyOptions getOptions(StringRef FileName);
};
/// Implementation of the \c ClangTidyOptionsProvider interface, which
@ -212,7 +211,7 @@ public:
const ClangTidyGlobalOptions &getGlobalOptions() override {
return GlobalOptions;
}
std::vector<OptionsSource> getRawOptions(llvm::StringRef FileName) override;
std::vector<OptionsSource> getRawOptions(StringRef FileName) override;
private:
ClangTidyGlobalOptions GlobalOptions;
@ -256,19 +255,19 @@ protected:
ClangTidyOptions OverrideOptions,
ConfigFileHandlers ConfigHandlers);
void addRawFileOptions(llvm::StringRef AbsolutePath,
void addRawFileOptions(StringRef AbsolutePath,
std::vector<OptionsSource> &CurOptions);
llvm::ErrorOr<llvm::SmallString<128>>
getNormalizedAbsolutePath(llvm::StringRef AbsolutePath);
llvm::ErrorOr<SmallString<128>>
getNormalizedAbsolutePath(StringRef AbsolutePath);
/// Try to read configuration files from \p Directory using registered
/// \c ConfigHandlers.
std::optional<OptionsSource> tryReadConfigFile(llvm::StringRef Directory);
std::optional<OptionsSource> tryReadConfigFile(StringRef Directory);
struct OptionsCache {
llvm::StringMap<size_t> Memorized;
llvm::SmallVector<OptionsSource, 4U> Storage;
SmallVector<OptionsSource, 4U> Storage;
} CachedOptions;
ClangTidyOptions OverrideOptions;
ConfigFileHandlers ConfigHandlers;
@ -283,7 +282,7 @@ public:
ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions,
ClangTidyOptions ConfigOptions, ClangTidyOptions OverrideOptions,
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = nullptr);
std::vector<OptionsSource> getRawOptions(llvm::StringRef FileName) override;
std::vector<OptionsSource> getRawOptions(StringRef FileName) override;
private:
ClangTidyOptions ConfigOptions;
@ -336,11 +335,11 @@ public:
ClangTidyOptions OverrideOptions,
ConfigFileHandlers ConfigHandlers);
std::vector<OptionsSource> getRawOptions(llvm::StringRef FileName) override;
std::vector<OptionsSource> getRawOptions(StringRef FileName) override;
};
/// Parses LineFilter from JSON and stores it to the \p Options.
std::error_code parseLineFilter(llvm::StringRef LineFilter,
std::error_code parseLineFilter(StringRef LineFilter,
ClangTidyGlobalOptions &Options);
/// Parses configuration from JSON and returns \c ClangTidyOptions or an

View File

@ -88,11 +88,11 @@ ExpandModularHeadersPPCallbacks::ExpandModularHeadersPPCallbacks(
HeaderInfo = std::make_unique<HeaderSearch>(HSOpts, Sources, Diags, LangOpts,
&Compiler.getTarget());
PP = std::make_unique<clang::Preprocessor>(Compiler.getPreprocessorOpts(),
Diags, LangOpts, Sources,
*HeaderInfo, ModuleLoader,
/*IILookup=*/nullptr,
/*OwnsHeaderSearch=*/false);
PP = std::make_unique<Preprocessor>(Compiler.getPreprocessorOpts(), Diags,
LangOpts, Sources, *HeaderInfo,
ModuleLoader,
/*IILookup=*/nullptr,
/*OwnsHeaderSearch=*/false);
PP->Initialize(Compiler.getTarget(), Compiler.getAuxTarget());
InitializePreprocessor(*PP, Compiler.getPreprocessorOpts(),
Compiler.getPCHContainerReader(),

View File

@ -22,7 +22,7 @@ static bool consumeNegativeIndicator(StringRef &GlobList) {
// Extracts the first glob from the comma-separated list of globs,
// removes it and the trailing comma from the GlobList and
// returns the extracted glob.
static llvm::StringRef extractNextGlob(StringRef &GlobList) {
static StringRef extractNextGlob(StringRef &GlobList) {
const StringRef UntrimmedGlob =
GlobList.substr(0, GlobList.find_first_of(",\n"));
const StringRef Glob = UntrimmedGlob.trim();
@ -31,7 +31,7 @@ static llvm::StringRef extractNextGlob(StringRef &GlobList) {
}
static llvm::Regex createRegexFromGlob(StringRef &Glob) {
llvm::SmallString<128> RegexText("^");
SmallString<128> RegexText("^");
const StringRef MetaChars("()^$|*+?.[]\\{}");
for (const char C : Glob) {
if (C == '*')

View File

@ -44,7 +44,7 @@ private:
struct GlobListItem {
bool IsPositive;
llvm::Regex Regex;
llvm::StringRef Text;
StringRef Text;
};
SmallVector<GlobListItem, 0> Items;

View File

@ -33,8 +33,8 @@ public:
~NoLintDirectiveHandler();
bool shouldSuppress(DiagnosticsEngine::Level DiagLevel,
const Diagnostic &Diag, llvm::StringRef DiagName,
llvm::SmallVectorImpl<tooling::Diagnostic> &NoLintErrors,
const Diagnostic &Diag, StringRef DiagName,
SmallVectorImpl<tooling::Diagnostic> &NoLintErrors,
bool AllowIO, bool EnableNoLintBlocks);
private:

View File

@ -29,19 +29,19 @@ void DurationAdditionCheck::registerMatchers(MatchFinder *Finder) {
}
void DurationAdditionCheck::check(const MatchFinder::MatchResult &Result) {
const auto *Binop = Result.Nodes.getNodeAs<clang::BinaryOperator>("binop");
const auto *Call = Result.Nodes.getNodeAs<clang::CallExpr>("call");
const auto *Binop = Result.Nodes.getNodeAs<BinaryOperator>("binop");
const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
// Don't try to replace things inside of macro definitions.
if (Binop->getExprLoc().isMacroID() || Binop->getExprLoc().isInvalid())
return;
std::optional<DurationScale> Scale = getScaleForTimeInverse(
Result.Nodes.getNodeAs<clang::FunctionDecl>("function_decl")->getName());
Result.Nodes.getNodeAs<FunctionDecl>("function_decl")->getName());
if (!Scale)
return;
const llvm::StringRef TimeFactory = getTimeInverseForScale(*Scale);
const StringRef TimeFactory = getTimeInverseForScale(*Scale);
FixItHint Hint;
if (Call == Binop->getLHS()->IgnoreParenImpCasts()) {

View File

@ -51,8 +51,7 @@ void DurationConversionCastCheck::check(
// Casting a double to an integer.
if (MatchedCast->getTypeAsWritten()->isIntegerType() &&
ConversionFuncName.contains("Double")) {
const llvm::StringRef NewFuncName =
getDurationInverseForScale(*Scale).second;
const StringRef NewFuncName = getDurationInverseForScale(*Scale).second;
diag(MatchedCast->getBeginLoc(),
"duration should be converted directly to an integer rather than "
@ -67,8 +66,7 @@ void DurationConversionCastCheck::check(
// Casting an integer to a double.
if (MatchedCast->getTypeAsWritten()->isRealFloatingType() &&
ConversionFuncName.contains("Int64")) {
const llvm::StringRef NewFuncName =
getDurationInverseForScale(*Scale).first;
const StringRef NewFuncName = getDurationInverseForScale(*Scale).first;
diag(MatchedCast->getBeginLoc(), "duration should be converted directly to "
"a floating-point number rather than "

View File

@ -20,9 +20,9 @@ namespace clang::tidy::abseil {
// Returns `true` if `Range` is inside a macro definition.
static bool insideMacroDefinition(const MatchFinder::MatchResult &Result,
SourceRange Range) {
return !clang::Lexer::makeFileCharRange(
clang::CharSourceRange::getCharRange(Range),
*Result.SourceManager, Result.Context->getLangOpts())
return !Lexer::makeFileCharRange(CharSourceRange::getCharRange(Range),
*Result.SourceManager,
Result.Context->getLangOpts())
.isValid();
}

View File

@ -20,8 +20,7 @@ namespace clang::tidy::abseil {
// Given the name of a duration factory function, return the appropriate
// `DurationScale` for that factory. If no factory can be found for
// `FactoryName`, return `std::nullopt`.
static std::optional<DurationScale>
getScaleForFactory(llvm::StringRef FactoryName) {
static std::optional<DurationScale> getScaleForFactory(StringRef FactoryName) {
return llvm::StringSwitch<std::optional<DurationScale>>(FactoryName)
.Case("Nanoseconds", DurationScale::Nanoseconds)
.Case("Microseconds", DurationScale::Microseconds)
@ -169,8 +168,8 @@ void DurationFactoryScaleCheck::check(const MatchFinder::MatchResult &Result) {
// cases where a user is multiplying by something such as 1e-3.
// First check the LHS
const auto *IntLit = llvm::dyn_cast<IntegerLiteral>(MultBinOp->getLHS());
const auto *FloatLit = llvm::dyn_cast<FloatingLiteral>(MultBinOp->getLHS());
const auto *IntLit = dyn_cast<IntegerLiteral>(MultBinOp->getLHS());
const auto *FloatLit = dyn_cast<FloatingLiteral>(MultBinOp->getLHS());
if (IntLit || FloatLit) {
NewScale = getNewScale(Scale, getValue(IntLit, FloatLit));
if (NewScale)
@ -179,8 +178,8 @@ void DurationFactoryScaleCheck::check(const MatchFinder::MatchResult &Result) {
// If we weren't able to scale based on the LHS, check the RHS
if (!NewScale) {
IntLit = llvm::dyn_cast<IntegerLiteral>(MultBinOp->getRHS());
FloatLit = llvm::dyn_cast<FloatingLiteral>(MultBinOp->getRHS());
IntLit = dyn_cast<IntegerLiteral>(MultBinOp->getRHS());
FloatLit = dyn_cast<FloatingLiteral>(MultBinOp->getRHS());
if (IntLit || FloatLit) {
NewScale = getNewScale(Scale, getValue(IntLit, FloatLit));
if (NewScale)
@ -191,7 +190,7 @@ void DurationFactoryScaleCheck::check(const MatchFinder::MatchResult &Result) {
Result.Nodes.getNodeAs<BinaryOperator>("div_binop")) {
// We next handle division.
// For division, we only check the RHS.
const auto *FloatLit = llvm::cast<FloatingLiteral>(DivBinOp->getRHS());
const auto *FloatLit = cast<FloatingLiteral>(DivBinOp->getRHS());
std::optional<DurationScale> NewScale =
getNewScale(Scale, 1.0 / FloatLit->getValueAsApproximateDouble());

View File

@ -30,10 +30,10 @@ truncateIfIntegral(const FloatingLiteral &FloatLiteral) {
return std::nullopt;
}
const std::pair<llvm::StringRef, llvm::StringRef> &
const std::pair<StringRef, StringRef> &
getDurationInverseForScale(DurationScale Scale) {
static constexpr std::array<std::pair<llvm::StringRef, llvm::StringRef>, 6>
InverseMap = {{
static constexpr std::array<std::pair<StringRef, StringRef>, 6> InverseMap = {
{
{"::absl::ToDoubleHours", "::absl::ToInt64Hours"},
{"::absl::ToDoubleMinutes", "::absl::ToInt64Minutes"},
{"::absl::ToDoubleSeconds", "::absl::ToInt64Seconds"},
@ -50,7 +50,7 @@ getDurationInverseForScale(DurationScale Scale) {
static std::optional<std::string>
rewriteInverseDurationCall(const MatchFinder::MatchResult &Result,
DurationScale Scale, const Expr &Node) {
const std::pair<llvm::StringRef, llvm::StringRef> &InverseFunctions =
const std::pair<StringRef, StringRef> &InverseFunctions =
getDurationInverseForScale(Scale);
if (const auto *MaybeCallArg = selectFirst<const Expr>(
"e",
@ -69,7 +69,7 @@ rewriteInverseDurationCall(const MatchFinder::MatchResult &Result,
static std::optional<std::string>
rewriteInverseTimeCall(const MatchFinder::MatchResult &Result,
DurationScale Scale, const Expr &Node) {
const llvm::StringRef InverseFunction = getTimeInverseForScale(Scale);
const StringRef InverseFunction = getTimeInverseForScale(Scale);
if (const auto *MaybeCallArg = selectFirst<const Expr>(
"e", match(callExpr(callee(functionDecl(hasName(InverseFunction))),
hasArgument(0, expr().bind("e"))),
@ -81,8 +81,8 @@ rewriteInverseTimeCall(const MatchFinder::MatchResult &Result,
}
/// Returns the factory function name for a given `Scale`.
llvm::StringRef getDurationFactoryForScale(DurationScale Scale) {
static constexpr std::array<llvm::StringRef, 6> FactoryMap = {
StringRef getDurationFactoryForScale(DurationScale Scale) {
static constexpr std::array<StringRef, 6> FactoryMap = {
"absl::Hours", "absl::Minutes", "absl::Seconds",
"absl::Milliseconds", "absl::Microseconds", "absl::Nanoseconds",
};
@ -90,8 +90,8 @@ llvm::StringRef getDurationFactoryForScale(DurationScale Scale) {
return FactoryMap[llvm::to_underlying(Scale)];
}
llvm::StringRef getTimeFactoryForScale(DurationScale Scale) {
static constexpr std::array<llvm::StringRef, 6> FactoryMap = {
StringRef getTimeFactoryForScale(DurationScale Scale) {
static constexpr std::array<StringRef, 6> FactoryMap = {
"absl::FromUnixHours", "absl::FromUnixMinutes", "absl::FromUnixSeconds",
"absl::FromUnixMillis", "absl::FromUnixMicros", "absl::FromUnixNanos",
};
@ -100,8 +100,8 @@ llvm::StringRef getTimeFactoryForScale(DurationScale Scale) {
}
/// Returns the Time factory function name for a given `Scale`.
llvm::StringRef getTimeInverseForScale(DurationScale Scale) {
static constexpr std::array<llvm::StringRef, 6> InverseMap = {
StringRef getTimeInverseForScale(DurationScale Scale) {
static constexpr std::array<StringRef, 6> InverseMap = {
"absl::ToUnixHours", "absl::ToUnixMinutes", "absl::ToUnixSeconds",
"absl::ToUnixMillis", "absl::ToUnixMicros", "absl::ToUnixNanos",
};
@ -115,14 +115,14 @@ bool isLiteralZero(const MatchFinder::MatchResult &Result, const Expr &Node) {
anyOf(integerLiteral(equals(0)), floatLiteral(equals(0.0)));
// Check to see if we're using a zero directly.
if (selectFirst<const clang::Expr>(
if (selectFirst<const Expr>(
"val", match(expr(ignoringImpCasts(ZeroMatcher)).bind("val"), Node,
*Result.Context)) != nullptr)
return true;
// Now check to see if we're using a functional cast with a scalar
// initializer expression, e.g. `int{0}`.
if (selectFirst<const clang::Expr>(
if (selectFirst<const Expr>(
"val", match(cxxFunctionalCastExpr(
hasDestinationType(
anyOf(isInteger(), realFloatingPointType())),
@ -158,7 +158,7 @@ stripFloatCast(const ast_matchers::MatchFinder::MatchResult &Result,
std::optional<std::string>
stripFloatLiteralFraction(const MatchFinder::MatchResult &Result,
const Expr &Node) {
if (const auto *LitFloat = llvm::dyn_cast<FloatingLiteral>(&Node))
if (const auto *LitFloat = dyn_cast<FloatingLiteral>(&Node))
// Attempt to simplify a `Duration` factory call with a literal argument.
if (std::optional<llvm::APSInt> IntValue = truncateIfIntegral(*LitFloat))
return toString(*IntValue, /*radix=*/10);
@ -181,7 +181,7 @@ std::string simplifyDurationFactoryArg(const MatchFinder::MatchResult &Result,
return tooling::fixit::getText(Node, *Result.Context).str();
}
std::optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name) {
std::optional<DurationScale> getScaleForDurationInverse(StringRef Name) {
static const llvm::StringMap<DurationScale> ScaleMap(
{{"ToDoubleHours", DurationScale::Hours},
{"ToInt64Hours", DurationScale::Hours},
@ -203,7 +203,7 @@ std::optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name) {
return ScaleIter->second;
}
std::optional<DurationScale> getScaleForTimeInverse(llvm::StringRef Name) {
std::optional<DurationScale> getScaleForTimeInverse(StringRef Name) {
static const llvm::StringMap<DurationScale> ScaleMap(
{{"ToUnixHours", DurationScale::Hours},
{"ToUnixMinutes", DurationScale::Minutes},

View File

@ -11,7 +11,7 @@
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include <cinttypes>
#include <cstdint>
#include <optional>
namespace clang::tidy::abseil {
@ -28,11 +28,11 @@ enum class DurationScale : std::uint8_t {
/// Given a `Scale`, return the appropriate factory function call for
/// constructing a `Duration` for that scale.
llvm::StringRef getDurationFactoryForScale(DurationScale Scale);
StringRef getDurationFactoryForScale(DurationScale Scale);
/// Given a 'Scale', return the appropriate factory function call for
/// constructing a `Time` for that scale.
llvm::StringRef getTimeFactoryForScale(DurationScale Scale);
StringRef getTimeFactoryForScale(DurationScale Scale);
// Determine if `Node` represents a literal floating point or integral zero.
bool isLiteralZero(const ast_matchers::MatchFinder::MatchResult &Result,
@ -63,20 +63,20 @@ simplifyDurationFactoryArg(const ast_matchers::MatchFinder::MatchResult &Result,
/// Given the name of an inverse Duration function (e.g., `ToDoubleSeconds`),
/// return its `DurationScale`, or `std::nullopt` if a match is not found.
std::optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name);
std::optional<DurationScale> getScaleForDurationInverse(StringRef Name);
/// Given the name of an inverse Time function (e.g., `ToUnixSeconds`),
/// return its `DurationScale`, or `std::nullopt` if a match is not found.
std::optional<DurationScale> getScaleForTimeInverse(llvm::StringRef Name);
std::optional<DurationScale> getScaleForTimeInverse(StringRef Name);
/// Given a `Scale` return the fully qualified inverse functions for it.
/// The first returned value is the inverse for `double`, and the second
/// returned value is the inverse for `int64`.
const std::pair<llvm::StringRef, llvm::StringRef> &
const std::pair<StringRef, StringRef> &
getDurationInverseForScale(DurationScale Scale);
/// Returns the Time inverse function name for a given `Scale`.
llvm::StringRef getTimeInverseForScale(DurationScale Scale);
StringRef getTimeInverseForScale(DurationScale Scale);
/// Assuming `Node` has type `double` or `int` representing a time interval of
/// `Scale`, return the expression to make it a suitable `Duration`.

View File

@ -28,7 +28,7 @@ makeCharacterLiteral(const StringLiteral *Literal, const ASTContext &Context) {
"Only single character string should be matched");
assert(Literal->getCharByteWidth() == 1 &&
"StrSplit doesn't support wide char");
std::string Result = clang::tooling::fixit::getText(*Literal, Context).str();
std::string Result = tooling::fixit::getText(*Literal, Context).str();
const bool IsRawStringLiteral = StringRef(Result).starts_with(R"(R")");
// Since raw string literal might contain unescaped non-printable characters,
// we normalize them using `StringLiteral::outputString`.

View File

@ -61,9 +61,9 @@ static void removeCallLeaveArgs(const CallExpr *Call,
Call->getRParenLoc(), Call->getEndLoc().getLocWithOffset(1))));
}
static const clang::CallExpr *
processArgument(const Expr *Arg, const MatchFinder::MatchResult &Result,
StrCatCheckResult *CheckResult) {
static const CallExpr *processArgument(const Expr *Arg,
const MatchFinder::MatchResult &Result,
StrCatCheckResult *CheckResult) {
const auto IsAlphanum = hasDeclaration(cxxMethodDecl(hasName("AlphaNum")));
static const auto *const Strcat = new auto(hasName("::absl::StrCat"));
const auto IsStrcat = cxxBindTemporaryExpr(
@ -89,17 +89,15 @@ static StrCatCheckResult processCall(const CallExpr *RootCall, bool IsAppend,
while (!CallsToProcess.empty()) {
++CheckResult.NumCalls;
const CallExpr *CallExpr = CallsToProcess.front();
const CallExpr *Call = CallsToProcess.front();
CallsToProcess.pop_front();
int StartArg = CallExpr == RootCall && IsAppend;
for (const auto *Arg : CallExpr->arguments()) {
int StartArg = Call == RootCall && IsAppend;
for (const auto *Arg : Call->arguments()) {
if (StartArg-- > 0)
continue;
if (const clang::CallExpr *Sub =
processArgument(Arg, Result, &CheckResult)) {
if (const CallExpr *Sub = processArgument(Arg, Result, &CheckResult))
CallsToProcess.push_back(Sub);
}
}
}
return CheckResult;

View File

@ -20,9 +20,9 @@ namespace clang::tidy::abseil {
// Returns `true` if `Range` is inside a macro definition.
static bool insideMacroDefinition(const MatchFinder::MatchResult &Result,
SourceRange Range) {
return !clang::Lexer::makeFileCharRange(
clang::CharSourceRange::getCharRange(Range),
*Result.SourceManager, Result.Context->getLangOpts())
return !Lexer::makeFileCharRange(CharSourceRange::getCharRange(Range),
*Result.SourceManager,
Result.Context->getLangOpts())
.isValid();
}
@ -85,7 +85,7 @@ static bool parensRequired(const MatchFinder::MatchResult &Result,
}
void TimeSubtractionCheck::emitDiagnostic(const Expr *Node,
llvm::StringRef Replacement) {
StringRef Replacement) {
diag(Node->getBeginLoc(), "perform subtraction in the time domain")
<< FixItHint::CreateReplacement(Node->getSourceRange(), Replacement);
}

View File

@ -29,7 +29,7 @@ public:
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
private:
void emitDiagnostic(const Expr *Node, llvm::StringRef Replacement);
void emitDiagnostic(const Expr *Node, StringRef Replacement);
};
} // namespace clang::tidy::abseil

View File

@ -48,7 +48,7 @@ void UncheckedStatusOrAccessCheck::check(
return;
UncheckedStatusOrAccessDiagnoser Diagnoser;
if (llvm::Expected<llvm::SmallVector<SourceLocation>> Locs =
if (llvm::Expected<SmallVector<SourceLocation>> Locs =
dataflow::diagnoseFunction<UncheckedStatusOrAccessModel,
SourceLocation>(*FuncDecl, *Result.Context,
Diagnoser))

View File

@ -113,7 +113,7 @@ void UpgradeDurationConversionsCheck::registerMatchers(MatchFinder *Finder) {
void UpgradeDurationConversionsCheck::check(
const MatchFinder::MatchResult &Result) {
const llvm::StringRef Message =
static constexpr StringRef Message =
"implicit conversion to 'int64_t' is deprecated in this context; use an "
"explicit cast instead";

View File

@ -52,7 +52,7 @@ void StructPackAlignCheck::check(const MatchFinder::MatchResult &Result) {
return;
// Get sizing info for the struct.
llvm::SmallVector<std::pair<unsigned int, unsigned int>, 10> FieldSizes;
SmallVector<std::pair<unsigned int, unsigned int>, 10> FieldSizes;
unsigned int TotalBitSize = 0;
for (const FieldDecl *StructField : Struct->fields()) {
// For each StructField, record how big it is (in bits).
@ -73,7 +73,7 @@ void StructPackAlignCheck::check(const MatchFinder::MatchResult &Result) {
const CharUnits CurrSize =
Result.Context->getASTRecordLayout(Struct).getSize();
const CharUnits MinByteSize =
CharUnits::fromQuantity(std::max<clang::CharUnits::QuantityType>(
CharUnits::fromQuantity(std::max<CharUnits::QuantityType>(
std::ceil(static_cast<float>(TotalBitSize) / CharSize), 1));
const CharUnits MaxAlign = CharUnits::fromQuantity(
std::ceil(static_cast<float>(Struct->getMaxAlignment()) / CharSize));

View File

@ -207,7 +207,7 @@ utils::UseRangesCheck::ReplacerMap UseRangesCheck::getReplacerMap() const {
const auto AddFrom =
[&Results](llvm::IntrusiveRefCntPtr<UseRangesCheck::Replacer> Replacer,
std::initializer_list<StringRef> Names, StringRef Prefix) {
llvm::SmallString<64> Buffer;
SmallString<64> Buffer;
for (const auto &Name : Names) {
Buffer.assign({"::", Prefix, (Prefix.empty() ? "" : "::"), Name});
Results.try_emplace(Buffer, Replacer);

View File

@ -273,7 +273,7 @@ void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx,
}
for (const auto &Comment : Comments) {
llvm::SmallVector<StringRef, 2> Matches;
SmallVector<StringRef, 2> Matches;
if (IdentRE.match(Comment.Text, &Matches) &&
!sameName(Matches[2], II->getName(), StrictMode)) {
{
@ -297,7 +297,7 @@ void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx,
// If the argument comments are missing for literals add them.
if (Comments.empty() && shouldAddComment(Args[I])) {
llvm::SmallString<32> ArgComment;
SmallString<32> ArgComment;
(llvm::Twine("/*") + II->getName() + "=*/").toStringRef(ArgComment);
const DiagnosticBuilder Diag =
diag(Args[I]->getBeginLoc(),

View File

@ -24,7 +24,7 @@ namespace clang::tidy::bugprone {
namespace {
AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
clang::ast_matchers::internal::Matcher<NamedDecl>,
ast_matchers::internal::Matcher<NamedDecl>,
IgnoredFunctionsMatcher) {
const Expr *E = &Node;

View File

@ -20,7 +20,7 @@ using namespace clang::ast_matchers;
namespace {
/// A branch in a switch may consist of several statements; while a branch in
/// an if/else if/else chain is one statement (which may be a CompoundStmt).
using SwitchBranch = llvm::SmallVector<const Stmt *, 2>;
using SwitchBranch = SmallVector<const Stmt *, 2>;
} // anonymous namespace
/// Determines if the bodies of two branches in a switch statements are Type I
@ -305,7 +305,7 @@ void BranchCloneCheck::check(const MatchFinder::MatchResult &Result) {
// This is the complicated case when we start an if/else if/else chain.
// To find all the duplicates, we collect all the branches into a vector.
llvm::SmallVector<const Stmt *, 4> Branches;
SmallVector<const Stmt *, 4> Branches;
const IfStmt *Cur = IS;
while (true) {
// Store the `then` branch.
@ -388,7 +388,7 @@ void BranchCloneCheck::check(const MatchFinder::MatchResult &Result) {
// (`case:` or `default:`) children of Body; that is, we ignore `case:` or
// `default:` labels embedded inside other statements and we do not follow
// the effects of `break` and other manipulation of the control-flow.
llvm::SmallVector<SwitchBranch, 4> Branches;
SmallVector<SwitchBranch, 4> Branches;
for (const Stmt *S : Body->body()) {
// If this is a `case` or `default`, we start a new, empty branch.
if (isa<SwitchCase>(S))

View File

@ -37,14 +37,14 @@ AST_MATCHER(CXXOperatorCallExpr,
}
struct ChainedComparisonData {
llvm::SmallString<256U> Name;
llvm::SmallVector<const Expr *, 32U> Operands;
SmallString<256U> Name;
SmallVector<const Expr *, 32U> Operands;
explicit ChainedComparisonData(const Expr *Op) { extract(Op); }
private:
void add(const Expr *Operand);
void add(llvm::StringRef Opcode);
void add(StringRef Opcode);
void extract(const Expr *Op);
void extract(const BinaryOperator *Op);
void extract(const CXXOperatorCallExpr *Op);
@ -60,7 +60,7 @@ void ChainedComparisonData::add(const Expr *Operand) {
Operands.push_back(Operand);
}
void ChainedComparisonData::add(llvm::StringRef Opcode) {
void ChainedComparisonData::add(StringRef Opcode) {
Name += ' ';
Name += Opcode;
}
@ -148,7 +148,7 @@ void ChainedComparisonCheck::check(const MatchFinder::MatchResult &Result) {
"chained comparison '%0' may generate unintended results, use "
"parentheses to specify order of evaluation or a logical operator to "
"separate comparison expressions")
<< llvm::StringRef(Data.Name).trim() << MatchedOperator->getSourceRange();
<< StringRef(Data.Name).trim() << MatchedOperator->getSourceRange();
for (std::size_t Index = 0U; Index < Data.Operands.size(); ++Index) {
diag(Data.Operands[Index]->getBeginLoc(), "operand 'v%0' is here",

View File

@ -65,7 +65,7 @@ void ComparePointerToMemberVirtualFunctionCheck::check(
return;
}
// compare with variable which type is pointer to member function.
llvm::SmallVector<SourceLocation, 12U> SameSignatureVirtualMethods{};
SmallVector<SourceLocation, 12U> SameSignatureVirtualMethods{};
const auto *MPT = cast<MemberPointerType>(DRE->getType().getCanonicalType());
const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
if (RD == nullptr)

View File

@ -43,14 +43,13 @@ namespace {
AST_MATCHER(CXXMethodDecl, nameCollidesWithMethodInBase) {
const CXXRecordDecl *DerivedClass = Node.getParent();
for (const auto &Base : DerivedClass->bases()) {
llvm::SmallVector<const CXXBaseSpecifier *, 8> Stack;
SmallVector<const CXXBaseSpecifier *, 8> Stack;
Stack.push_back(&Base);
while (!Stack.empty()) {
const CXXBaseSpecifier *CurrentBaseSpec = Stack.back();
Stack.pop_back();
if (CurrentBaseSpec->getAccessSpecifier() ==
clang::AccessSpecifier::AS_private)
if (CurrentBaseSpec->getAccessSpecifier() == AccessSpecifier::AS_private)
continue;
const CXXRecordDecl *CurrentRecord =
@ -66,8 +65,7 @@ AST_MATCHER(CXXMethodDecl, nameCollidesWithMethodInBase) {
for (const auto &BaseMethod : CurrentRecord->methods()) {
if (namesCollide(*BaseMethod, Node)) {
const ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
Builder->setBinding("base_method",
clang::DynTypedNode::create(*BaseMethod));
Builder->setBinding("base_method", DynTypedNode::create(*BaseMethod));
return true;
}
}

View File

@ -17,7 +17,7 @@ namespace clang::tidy::bugprone {
namespace {
AST_MATCHER(clang::VarDecl, hasConstantDeclaration) {
AST_MATCHER(VarDecl, hasConstantDeclaration) {
if (Node.isConstexpr() || Node.hasAttr<ConstInitAttr>())
return true;
if (const VarDecl *Def = Node.getDefinition();

View File

@ -1198,7 +1198,7 @@ public:
}
private:
llvm::SmallVector<PreparedConversion, 2> FlaggedConversions;
SmallVector<PreparedConversion, 2> FlaggedConversions;
const TheCheck &Check;
};
@ -1740,7 +1740,7 @@ public:
/// Implements the heuristic that marks two parameters related if different
/// ReturnStmts return them from the function.
class Returned {
llvm::SmallVector<const ParmVarDecl *, SmallDataStructureSize> ReturnedParams;
SmallVector<const ParmVarDecl *, SmallDataStructureSize> ReturnedParams;
public:
void setup(const FunctionDecl *FD) {

View File

@ -35,8 +35,7 @@ AST_MATCHER_P(CXXCatchStmt, hasCaughtType, Matcher<QualType>, InnerMatcher) {
return InnerMatcher.matches(Node.getCaughtType(), Finder, Builder);
}
AST_MATCHER_P(CompoundStmt, hasAnyTextFromList, std::vector<llvm::StringRef>,
List) {
AST_MATCHER_P(CompoundStmt, hasAnyTextFromList, std::vector<StringRef>, List) {
if (List.empty())
return false;

View File

@ -28,8 +28,8 @@ public:
std::optional<TraversalKind> getCheckTraversalKind() const override;
private:
std::vector<llvm::StringRef> IgnoreCatchWithKeywords;
std::vector<llvm::StringRef> AllowEmptyCatchForExceptions;
std::vector<StringRef> IgnoreCatchWithKeywords;
std::vector<StringRef> AllowEmptyCatchForExceptions;
};
} // namespace clang::tidy::bugprone

View File

@ -68,7 +68,7 @@ ExceptionEscapeCheck::ExceptionEscapeCheck(StringRef Name,
TreatFunctionsWithoutSpecificationAsThrowing(
Options.get("TreatFunctionsWithoutSpecificationAsThrowing",
TreatFunctionsWithoutSpecification::None)) {
llvm::SmallVector<StringRef, 8> FunctionsThatShouldNotThrowVec,
SmallVector<StringRef, 8> FunctionsThatShouldNotThrowVec,
IgnoredExceptionsVec, CheckedSwapFunctionsVec;
RawFunctionsThatShouldNotThrow.split(FunctionsThatShouldNotThrowVec, ",", -1,
false);

View File

@ -46,7 +46,7 @@ AST_MATCHER(QualType, isEnableIf) {
return false;
}
AST_MATCHER_P(TemplateTypeParmDecl, hasDefaultArgument,
clang::ast_matchers::internal::Matcher<QualType>, TypeMatcher) {
ast_matchers::internal::Matcher<QualType>, TypeMatcher) {
return Node.hasDefaultArgument() &&
TypeMatcher.matches(
Node.getDefaultArgument().getArgument().getAsType(), Finder,

View File

@ -44,7 +44,7 @@ void IncorrectEnableSharedFromThisCheck::check(
BaseSpec->getAccessSpecifierAsWritten() != AS_none;
const auto ReplacementRange = CharSourceRange(
SourceRange(BaseSpec->getBeginLoc()), HasWrittenAccessSpecifier);
const llvm::StringRef Replacement =
const StringRef Replacement =
HasWrittenAccessSpecifier ? "public" : "public ";
const FixItHint Hint =
IsEnableSharedFromThisDirectBase

View File

@ -299,13 +299,13 @@ static bool isFloatExactlyRepresentable(const ASTContext &Context,
return !Overflows && IsExact;
}
static llvm::SmallString<64> getValueAsString(const llvm::APSInt &Value,
uint64_t HexBits) {
llvm::SmallString<64> Str;
static SmallString<64> getValueAsString(const llvm::APSInt &Value,
uint64_t HexBits) {
SmallString<64> Str;
Value.toString(Str, 10);
if (HexBits > 0) {
Str.append(" (0x");
llvm::SmallString<32> HexValue;
SmallString<32> HexValue;
Value.toStringUnsigned(HexValue, 16);
for (size_t I = HexValue.size(); I < (HexBits / 4); ++I)
Str.append("0");
@ -550,7 +550,7 @@ void NarrowingConversionsCheck::handleBinaryOperator(const ASTContext &Context,
bool NarrowingConversionsCheck::handleConditionalOperator(
const ASTContext &Context, const Expr &Lhs, const Expr &Rhs) {
if (const auto *CO = llvm::dyn_cast<ConditionalOperator>(&Rhs)) {
if (const auto *CO = dyn_cast<ConditionalOperator>(&Rhs)) {
// We have an expression like so: `output = cond ? lhs : rhs`
// From the point of view of narrowing conversion we treat it as two
// expressions `output = lhs` and `output = rhs`.
@ -563,7 +563,7 @@ bool NarrowingConversionsCheck::handleConditionalOperator(
void NarrowingConversionsCheck::handleConditionalOperatorArgument(
const ASTContext &Context, const Expr &Lhs, const Expr *Arg) {
if (const auto *ICE = llvm::dyn_cast<ImplicitCastExpr>(Arg))
if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Arg))
if (!Arg->getIntegerConstantExpr(Context))
Arg = ICE->getSubExpr();

View File

@ -153,7 +153,7 @@ void OptionalValueConversionCheck::check(
<< FixItHint::CreateRemoval(
CharSourceRange::getTokenRange(Begin, CallExpr->getEndLoc()));
if (const auto *Member =
llvm::dyn_cast<MemberExpr>(CallExpr->getCallee()->IgnoreImplicit());
dyn_cast<MemberExpr>(CallExpr->getCallee()->IgnoreImplicit());
Member && Member->isArrow())
Diag << FixItHint::CreateInsertion(CallExpr->getBeginLoc(), "*");
return;

View File

@ -17,7 +17,7 @@ using namespace clang::ast_matchers;
namespace clang::tidy::bugprone {
using BasesVector = llvm::SmallVector<const CXXRecordDecl *, 5>;
using BasesVector = SmallVector<const CXXRecordDecl *, 5>;
static bool isParentOf(const CXXRecordDecl &Parent,
const CXXRecordDecl &ThisClass) {
@ -65,8 +65,7 @@ static std::string getNameAsString(const NamedDecl *Decl) {
// Returns E as written in the source code. Used to handle 'using' and
// 'typedef'ed names of grand-parent classes.
static std::string getExprAsString(const clang::Expr &E,
clang::ASTContext &AC) {
static std::string getExprAsString(const Expr &E, ASTContext &AC) {
std::string Text = tooling::fixit::getText(E, AC).str();
llvm::erase_if(Text, [](char C) {
return llvm::isSpace(static_cast<unsigned char>(C));

View File

@ -44,7 +44,7 @@ static const char BuiltinMemCmp[] = "::std::memcmp;"
"::std::strcmp;"
"::strcmp;"
"::strncmp;";
static constexpr llvm::StringRef ComparisonOperators[] = {
static constexpr StringRef ComparisonOperators[] = {
"operator==", "operator!=", "operator<",
"operator>", "operator<=", "operator>="};

View File

@ -37,9 +37,9 @@ static int getMessageSelectIndex(StringRef Tag) {
return 0;
}
llvm::SmallVector<llvm::Regex>
SmallVector<llvm::Regex>
ReservedIdentifierCheck::parseAllowedIdentifiers() const {
llvm::SmallVector<llvm::Regex> AllowedIdentifiers;
SmallVector<llvm::Regex> AllowedIdentifiers;
AllowedIdentifiers.reserve(AllowedIdentifiersRaw.size());
for (const auto &Identifier : AllowedIdentifiersRaw) {

View File

@ -31,7 +31,7 @@ namespace clang::tidy::bugprone {
class ReservedIdentifierCheck final : public RenamerClangTidyCheck {
const bool Invert;
const std::vector<StringRef> AllowedIdentifiersRaw;
const llvm::SmallVector<llvm::Regex> AllowedIdentifiers;
const SmallVector<llvm::Regex> AllowedIdentifiers;
public:
ReservedIdentifierCheck(StringRef Name, ClangTidyContext *Context);
@ -47,7 +47,7 @@ private:
const SourceManager &SM) const override;
DiagInfo getDiagInfo(const NamingCheckId &ID,
const NamingCheckFailure &Failure) const override;
llvm::SmallVector<llvm::Regex> parseAllowedIdentifiers() const;
SmallVector<llvm::Regex> parseAllowedIdentifiers() const;
};
} // namespace clang::tidy::bugprone

View File

@ -65,7 +65,7 @@ static bool hasSameParameterTypes(const FunctionDecl &FD, const FunctionDecl &O,
const ParmVarDecl *DPD = FD.getParamDecl(I);
const QualType OPT = O.getParamDecl(I)->getType();
if (DPD == &PD) {
if (!llvm::isa<RValueReferenceType>(OPT) ||
if (!isa<RValueReferenceType>(OPT) ||
!isSameTypeIgnoringConstRef(DPD->getType(), OPT))
return false;
} else {

View File

@ -532,7 +532,7 @@ bool SignalHandlerCheck::isStandardFunctionAsyncSafe(
}
void SignalHandlerCheck::reportHandlerChain(
const llvm::df_iterator<const clang::CallGraphNode *> &Itr,
const llvm::df_iterator<const CallGraphNode *> &Itr,
const DeclRefExpr *HandlerRef, bool SkipPathEnd) {
int CallLevel = Itr.getPathLength() - 2;
assert(CallLevel >= -1 && "Empty iterator?");

View File

@ -65,11 +65,10 @@ private:
/// registered as signal handler.
/// @param SkipPathEnd If true the last item of the call chain (farthest away
/// from the \c signal call) is omitted from note generation.
void
reportHandlerChain(const llvm::df_iterator<const clang::CallGraphNode *> &Itr,
const DeclRefExpr *HandlerRef, bool SkipPathEnd);
void reportHandlerChain(const llvm::df_iterator<const CallGraphNode *> &Itr,
const DeclRefExpr *HandlerRef, bool SkipPathEnd);
clang::CallGraph CG;
CallGraph CG;
AsyncSafeFunctionSetKind AsyncSafeFunctionSet;
llvm::StringSet<> ConformingFunctions;

View File

@ -32,8 +32,8 @@ void SignedCharMisuseCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
}
// Create a matcher for char -> integer cast.
BindableMatcher<clang::Stmt> SignedCharMisuseCheck::charCastExpression(
bool IsSigned, const Matcher<clang::QualType> &IntegerType,
BindableMatcher<Stmt> SignedCharMisuseCheck::charCastExpression(
bool IsSigned, const Matcher<QualType> &IntegerType,
const std::string &CastBindName) const {
// We can ignore typedefs which are some kind of integer types
// (e.g. typedef char sal_Int8). In this case, we don't need to

View File

@ -30,9 +30,9 @@ public:
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
private:
ast_matchers::internal::BindableMatcher<clang::Stmt> charCastExpression(
ast_matchers::internal::BindableMatcher<Stmt> charCastExpression(
bool IsSigned,
const ast_matchers::internal::Matcher<clang::QualType> &IntegerType,
const ast_matchers::internal::Matcher<QualType> &IntegerType,
const std::string &CastBindName) const;
const StringRef CharTypedefsToIgnoreList;

View File

@ -89,7 +89,7 @@ void SmartPtrArrayMismatchCheck::check(const MatchFinder::MatchResult &Result) {
if (VarOrField) {
auto TSTypeLoc = VarOrField->getTypeSourceInfo()
->getTypeLoc()
.getAsAdjusted<clang::TemplateSpecializationTypeLoc>();
.getAsAdjusted<TemplateSpecializationTypeLoc>();
assert(TSTypeLoc.getNumArgs() >= 1 &&
"Matched type should have at least 1 template argument.");

View File

@ -129,14 +129,13 @@ void StandaloneEmptyCheck::check(const MatchFinder::MatchResult &Result) {
auto Candidates = HeuristicResolver(Context).lookupDependentName(
MemberCall->getRecordDecl(), Name, [](const NamedDecl *ND) {
return isa<CXXMethodDecl>(ND) &&
llvm::cast<CXXMethodDecl>(ND)->getMinRequiredArguments() ==
0 &&
!llvm::cast<CXXMethodDecl>(ND)->isConst();
cast<CXXMethodDecl>(ND)->getMinRequiredArguments() == 0 &&
!cast<CXXMethodDecl>(ND)->isConst();
});
const bool HasClear = !Candidates.empty();
if (HasClear) {
const auto *Clear = llvm::cast<CXXMethodDecl>(Candidates.at(0));
const auto *Clear = cast<CXXMethodDecl>(Candidates.at(0));
const QualType RangeType =
MemberCall->getImplicitObjectArgument()->getType();
const bool QualifierIncompatible =
@ -179,15 +178,14 @@ void StandaloneEmptyCheck::check(const MatchFinder::MatchResult &Result) {
auto Candidates = HeuristicResolver(Context).lookupDependentName(
ArgRecordDecl, Name, [](const NamedDecl *ND) {
return isa<CXXMethodDecl>(ND) &&
llvm::cast<CXXMethodDecl>(ND)->getMinRequiredArguments() ==
0 &&
!llvm::cast<CXXMethodDecl>(ND)->isConst();
cast<CXXMethodDecl>(ND)->getMinRequiredArguments() == 0 &&
!cast<CXXMethodDecl>(ND)->isConst();
});
const bool HasClear = !Candidates.empty();
if (HasClear) {
const auto *Clear = llvm::cast<CXXMethodDecl>(Candidates.at(0));
const auto *Clear = cast<CXXMethodDecl>(Candidates.at(0));
const bool QualifierIncompatible =
(!Clear->isVolatile() && Arg->getType().isVolatileQualified()) ||
Arg->getType().isConstQualified();
@ -201,7 +199,7 @@ void StandaloneEmptyCheck::check(const MatchFinder::MatchResult &Result) {
SourceRange(NonMemberLoc, NonMemberEndLoc);
diag(NonMemberLoc,
"ignoring the result of '%0'; did you mean 'clear()'?")
<< llvm::dyn_cast<NamedDecl>(NonMemberCall->getCalleeDecl())
<< dyn_cast<NamedDecl>(NonMemberCall->getCalleeDecl())
->getQualifiedNameAsString()
<< FixItHint::CreateReplacement(ReplacementRange, ReplacementText);
return;
@ -209,7 +207,7 @@ void StandaloneEmptyCheck::check(const MatchFinder::MatchResult &Result) {
}
diag(NonMemberLoc, "ignoring the result of '%0'")
<< llvm::dyn_cast<NamedDecl>(NonMemberCall->getCalleeDecl())
<< dyn_cast<NamedDecl>(NonMemberCall->getCalleeDecl())
->getQualifiedNameAsString();
}
}

View File

@ -19,9 +19,9 @@ AST_POLYMORPHIC_MATCHER_P(
hasAnyTemplateArgumentIncludingPack,
AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
TemplateSpecializationType, FunctionDecl),
clang::ast_matchers::internal::Matcher<TemplateArgument>, InnerMatcher) {
ast_matchers::internal::Matcher<TemplateArgument>, InnerMatcher) {
const ArrayRef<TemplateArgument> Args =
clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
ast_matchers::internal::getTemplateSpecializationArgs(Node);
for (const auto &Arg : Args) {
if (Arg.getKind() != TemplateArgument::Pack)
continue;

View File

@ -27,8 +27,8 @@ AST_MATCHER_P(InitListExpr, initCountIs, unsigned, N) {
return Node.getNumInits() == N;
}
AST_MATCHER(clang::VarDecl, isDirectInitialization) {
return Node.getInitStyle() != clang::VarDecl::InitializationStyle::CInit;
AST_MATCHER(VarDecl, isDirectInitialization) {
return Node.getInitStyle() != VarDecl::InitializationStyle::CInit;
}
} // namespace
@ -59,7 +59,7 @@ static RewriteRuleWith<std::string> stringviewNullptrCheckImpl() {
// Matches `nullptr` and `(nullptr)` binding to a pointer
auto NullLiteral = implicitCastExpr(
hasCastKind(clang::CK_NullToPointer),
hasCastKind(CK_NullToPointer),
hasSourceExpression(ignoringParens(cxxNullPtrLiteralExpr())));
// Matches `{nullptr}` and `{(nullptr)}` binding to a pointer
@ -233,7 +233,7 @@ static RewriteRuleWith<std::string> stringviewNullptrCheckImpl() {
cxxOperatorCallExpr(
hasOverloadedOperatorName("=="),
hasOperands(ignoringImpCasts(BasicStringViewConstructingFromNullExpr),
traverse(clang::TK_IgnoreUnlessSpelledInSource,
traverse(TK_IgnoreUnlessSpelledInSource,
expr().bind("instance"))))
.bind("root"),
changeTo(node("root"), cat(access("instance", cat("empty")), "()")),
@ -244,7 +244,7 @@ static RewriteRuleWith<std::string> stringviewNullptrCheckImpl() {
cxxOperatorCallExpr(
hasOverloadedOperatorName("!="),
hasOperands(ignoringImpCasts(BasicStringViewConstructingFromNullExpr),
traverse(clang::TK_IgnoreUnlessSpelledInSource,
traverse(TK_IgnoreUnlessSpelledInSource,
expr().bind("instance"))))
.bind("root"),
changeTo(node("root"), cat("!", access("instance", cat("empty")), "()")),

View File

@ -29,8 +29,8 @@ public:
std::optional<TraversalKind> getCheckTraversalKind() const override;
private:
std::vector<llvm::StringRef> StringViewTypes;
std::vector<llvm::StringRef> AllowedCallees;
std::vector<StringRef> StringViewTypes;
std::vector<StringRef> AllowedCallees;
};
} // namespace clang::tidy::bugprone

View File

@ -43,7 +43,7 @@ AST_MATCHER_P2(RecordDecl, fieldCountOfKindIsOne,
// is used for matching.
//
// For precedence, see commit: 5b07de1a5faf4a22ae6fd982b877c5e7e3a76559
clang::ast_matchers::internal::BoundNodesTreeBuilder TempBuilder;
ast_matchers::internal::BoundNodesTreeBuilder TempBuilder;
const FieldDecl *FirstMatch = nullptr;
for (const FieldDecl *Field : Node.fields()) {
@ -55,7 +55,7 @@ AST_MATCHER_P2(RecordDecl, fieldCountOfKindIsOne,
}
if (FirstMatch) {
Builder->setBinding(BindName, clang::DynTypedNode::create(*FirstMatch));
Builder->setBinding(BindName, DynTypedNode::create(*FirstMatch));
return true;
}
return false;

View File

@ -53,9 +53,9 @@ void UncheckedOptionalAccessCheck::check(
UncheckedOptionalAccessDiagnoser Diagnoser(ModelOptions);
// FIXME: Allow user to set the (defaulted) SAT iterations max for
// `diagnoseFunction` with config options.
if (llvm::Expected<llvm::SmallVector<UncheckedOptionalAccessDiagnostic>>
Diags = dataflow::diagnoseFunction<UncheckedOptionalAccessModel,
UncheckedOptionalAccessDiagnostic>(
if (llvm::Expected<SmallVector<UncheckedOptionalAccessDiagnostic>> Diags =
dataflow::diagnoseFunction<UncheckedOptionalAccessModel,
UncheckedOptionalAccessDiagnostic>(
*FuncDecl, *Result.Context, Diagnoser))
for (const UncheckedOptionalAccessDiagnostic &Diag : *Diags) {
diag(Diag.Range.getBegin(), "unchecked access to optional value")

View File

@ -90,7 +90,7 @@ void UnintendedCharOstreamOutputCheck::check(
const QualType T = Value->getType();
const Type *UnqualifiedDesugaredType = T->getUnqualifiedDesugaredType();
const llvm::StringRef CastType = CastTypeName.value_or(
const StringRef CastType = CastTypeName.value_or(
UnqualifiedDesugaredType->isSpecificBuiltinType(BuiltinType::SChar)
? "int"
: "unsigned int");

View File

@ -227,7 +227,7 @@ void UnsafeFunctionsCheck::registerMatchers(MatchFinder *Finder) {
}
if (!CustomFunctions.empty()) {
std::vector<llvm::StringRef> FunctionNames;
std::vector<StringRef> FunctionNames;
FunctionNames.reserve(CustomFunctions.size());
for (const auto &Entry : CustomFunctions)

View File

@ -29,7 +29,7 @@ public:
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
private:
std::vector<llvm::StringRef> CheckedSwapFunctions;
std::vector<StringRef> CheckedSwapFunctions;
};
} // namespace clang::tidy::bugprone

View File

@ -44,7 +44,7 @@ AST_MATCHER(FunctionDecl, isAssignmentOverloadedOperator) {
}
} // namespace
UnusedReturnValueCheck::UnusedReturnValueCheck(llvm::StringRef Name,
UnusedReturnValueCheck::UnusedReturnValueCheck(StringRef Name,
ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
CheckedFunctions(utils::options::parseStringList(
@ -148,13 +148,13 @@ UnusedReturnValueCheck::UnusedReturnValueCheck(llvm::StringRef Name,
AllowCastToVoid(Options.get("AllowCastToVoid", false)) {}
UnusedReturnValueCheck::UnusedReturnValueCheck(
llvm::StringRef Name, ClangTidyContext *Context,
StringRef Name, ClangTidyContext *Context,
std::vector<StringRef> CheckedFunctions)
: UnusedReturnValueCheck(Name, Context, std::move(CheckedFunctions), {},
false) {}
UnusedReturnValueCheck::UnusedReturnValueCheck(
llvm::StringRef Name, ClangTidyContext *Context,
StringRef Name, ClangTidyContext *Context,
std::vector<StringRef> CheckedFunctions,
std::vector<StringRef> CheckedReturnTypes, bool AllowCastToVoid)
: ClangTidyCheck(Name, Context),

View File

@ -65,7 +65,7 @@ private:
const Expr *MovingCall,
const ValueDecl *MovedVariable);
void getUsesAndReinits(const CFGBlock *Block, const ValueDecl *MovedVariable,
llvm::SmallVectorImpl<const DeclRefExpr *> *Uses,
SmallVectorImpl<const DeclRefExpr *> *Uses,
llvm::SmallPtrSetImpl<const Stmt *> *Reinits);
void getDeclRefs(const CFGBlock *Block, const Decl *MovedVariable,
llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs);
@ -133,9 +133,9 @@ makeReinitMatcher(const ValueDecl *MovedVariable,
StandardResettableOwnerTypeMatcher)),
callee(cxxMethodDecl(hasName("reset")))),
// Methods that have the [[clang::reinitializes]] attribute.
cxxMemberCallExpr(on(DeclRefMatcher),
callee(cxxMethodDecl(
hasAttr(clang::attr::Reinitializes)))),
cxxMemberCallExpr(
on(DeclRefMatcher),
callee(cxxMethodDecl(hasAttr(attr::Reinitializes)))),
// Functions that are specified in ReinitializationFunctions
// option.
callExpr(
@ -243,7 +243,7 @@ UseAfterMoveFinder::findInternal(const CFGBlock *Block, const Expr *MovingCall,
Visited.insert(Block);
// Get all uses and reinits in the block.
llvm::SmallVector<const DeclRefExpr *, 1> Uses;
SmallVector<const DeclRefExpr *, 1> Uses;
llvm::SmallPtrSet<const Stmt *, 1> Reinits;
getUsesAndReinits(Block, MovedVariable, &Uses, &Reinits);
@ -251,7 +251,7 @@ UseAfterMoveFinder::findInternal(const CFGBlock *Block, const Expr *MovingCall,
// reinit.
// If `Reinit` is identical to `MovingCall`, we're looking at a move-to-self
// (e.g. `a = std::move(a)`). Count these as reinitializations.
llvm::SmallVector<const Stmt *, 1> ReinitsToDelete;
SmallVector<const Stmt *, 1> ReinitsToDelete;
for (const Stmt *Reinit : Reinits)
if (MovingCall && Reinit != MovingCall &&
Sequence->potentiallyAfter(MovingCall, Reinit))
@ -303,7 +303,7 @@ UseAfterMoveFinder::findInternal(const CFGBlock *Block, const Expr *MovingCall,
void UseAfterMoveFinder::getUsesAndReinits(
const CFGBlock *Block, const ValueDecl *MovedVariable,
llvm::SmallVectorImpl<const DeclRefExpr *> *Uses,
SmallVectorImpl<const DeclRefExpr *> *Uses,
llvm::SmallPtrSetImpl<const Stmt *> *Reinits) {
llvm::SmallPtrSet<const DeclRefExpr *, 1> DeclRefs;
llvm::SmallPtrSet<const DeclRefExpr *, 1> ReinitDeclRefs;
@ -550,7 +550,7 @@ void UseAfterMoveCheck::check(const MatchFinder::MatchResult &Result) {
return;
// Collect all code blocks that could use the arg after move.
llvm::SmallVector<Stmt *> CodeBlocks{};
SmallVector<Stmt *> CodeBlocks{};
if (ContainingCtor) {
CodeBlocks.push_back(ContainingCtor->getBody());
if (ContainingCtorInit) {

View File

@ -42,194 +42,191 @@
#include "../readability/EnumInitialValueCheck.h"
#include "../readability/UppercaseLiteralSuffixCheck.h"
namespace {
namespace clang::tidy {
// Checked functions for cert-err33-c.
// The following functions are deliberately excluded because they can be
// called with NULL argument and in this case the check is not applicable:
// `mblen, mbrlen, mbrtowc, mbtowc, wctomb, wctomb_s`.
// FIXME: The check can be improved to handle such cases.
const llvm::StringRef CertErr33CCheckedFunctions = "^::aligned_alloc$;"
"^::asctime_s$;"
"^::at_quick_exit$;"
"^::atexit$;"
"^::bsearch$;"
"^::bsearch_s$;"
"^::btowc$;"
"^::c16rtomb$;"
"^::c32rtomb$;"
"^::calloc$;"
"^::clock$;"
"^::cnd_broadcast$;"
"^::cnd_init$;"
"^::cnd_signal$;"
"^::cnd_timedwait$;"
"^::cnd_wait$;"
"^::ctime_s$;"
"^::fclose$;"
"^::fflush$;"
"^::fgetc$;"
"^::fgetpos$;"
"^::fgets$;"
"^::fgetwc$;"
"^::fopen$;"
"^::fopen_s$;"
"^::fprintf$;"
"^::fprintf_s$;"
"^::fputc$;"
"^::fputs$;"
"^::fputwc$;"
"^::fputws$;"
"^::fread$;"
"^::freopen$;"
"^::freopen_s$;"
"^::fscanf$;"
"^::fscanf_s$;"
"^::fseek$;"
"^::fsetpos$;"
"^::ftell$;"
"^::fwprintf$;"
"^::fwprintf_s$;"
"^::fwrite$;"
"^::fwscanf$;"
"^::fwscanf_s$;"
"^::getc$;"
"^::getchar$;"
"^::getenv$;"
"^::getenv_s$;"
"^::gets_s$;"
"^::getwc$;"
"^::getwchar$;"
"^::gmtime$;"
"^::gmtime_s$;"
"^::localtime$;"
"^::localtime_s$;"
"^::malloc$;"
"^::mbrtoc16$;"
"^::mbrtoc32$;"
"^::mbsrtowcs$;"
"^::mbsrtowcs_s$;"
"^::mbstowcs$;"
"^::mbstowcs_s$;"
"^::memchr$;"
"^::mktime$;"
"^::mtx_init$;"
"^::mtx_lock$;"
"^::mtx_timedlock$;"
"^::mtx_trylock$;"
"^::mtx_unlock$;"
"^::printf_s$;"
"^::putc$;"
"^::putwc$;"
"^::raise$;"
"^::realloc$;"
"^::remove$;"
"^::rename$;"
"^::scanf$;"
"^::scanf_s$;"
"^::setlocale$;"
"^::setvbuf$;"
"^::signal$;"
"^::snprintf$;"
"^::snprintf_s$;"
"^::sprintf$;"
"^::sprintf_s$;"
"^::sscanf$;"
"^::sscanf_s$;"
"^::strchr$;"
"^::strerror_s$;"
"^::strftime$;"
"^::strpbrk$;"
"^::strrchr$;"
"^::strstr$;"
"^::strtod$;"
"^::strtof$;"
"^::strtoimax$;"
"^::strtok$;"
"^::strtok_s$;"
"^::strtol$;"
"^::strtold$;"
"^::strtoll$;"
"^::strtoul$;"
"^::strtoull$;"
"^::strtoumax$;"
"^::strxfrm$;"
"^::swprintf$;"
"^::swprintf_s$;"
"^::swscanf$;"
"^::swscanf_s$;"
"^::thrd_create$;"
"^::thrd_detach$;"
"^::thrd_join$;"
"^::thrd_sleep$;"
"^::time$;"
"^::timespec_get$;"
"^::tmpfile$;"
"^::tmpfile_s$;"
"^::tmpnam$;"
"^::tmpnam_s$;"
"^::tss_create$;"
"^::tss_get$;"
"^::tss_set$;"
"^::ungetc$;"
"^::ungetwc$;"
"^::vfprintf$;"
"^::vfprintf_s$;"
"^::vfscanf$;"
"^::vfscanf_s$;"
"^::vfwprintf$;"
"^::vfwprintf_s$;"
"^::vfwscanf$;"
"^::vfwscanf_s$;"
"^::vprintf_s$;"
"^::vscanf$;"
"^::vscanf_s$;"
"^::vsnprintf$;"
"^::vsnprintf_s$;"
"^::vsprintf$;"
"^::vsprintf_s$;"
"^::vsscanf$;"
"^::vsscanf_s$;"
"^::vswprintf$;"
"^::vswprintf_s$;"
"^::vswscanf$;"
"^::vswscanf_s$;"
"^::vwprintf_s$;"
"^::vwscanf$;"
"^::vwscanf_s$;"
"^::wcrtomb$;"
"^::wcschr$;"
"^::wcsftime$;"
"^::wcspbrk$;"
"^::wcsrchr$;"
"^::wcsrtombs$;"
"^::wcsrtombs_s$;"
"^::wcsstr$;"
"^::wcstod$;"
"^::wcstof$;"
"^::wcstoimax$;"
"^::wcstok$;"
"^::wcstok_s$;"
"^::wcstol$;"
"^::wcstold$;"
"^::wcstoll$;"
"^::wcstombs$;"
"^::wcstombs_s$;"
"^::wcstoul$;"
"^::wcstoull$;"
"^::wcstoumax$;"
"^::wcsxfrm$;"
"^::wctob$;"
"^::wctrans$;"
"^::wctype$;"
"^::wmemchr$;"
"^::wprintf_s$;"
"^::wscanf$;"
"^::wscanf_s$;";
static constexpr StringRef CertErr33CCheckedFunctions = "^::aligned_alloc$;"
"^::asctime_s$;"
"^::at_quick_exit$;"
"^::atexit$;"
"^::bsearch$;"
"^::bsearch_s$;"
"^::btowc$;"
"^::c16rtomb$;"
"^::c32rtomb$;"
"^::calloc$;"
"^::clock$;"
"^::cnd_broadcast$;"
"^::cnd_init$;"
"^::cnd_signal$;"
"^::cnd_timedwait$;"
"^::cnd_wait$;"
"^::ctime_s$;"
"^::fclose$;"
"^::fflush$;"
"^::fgetc$;"
"^::fgetpos$;"
"^::fgets$;"
"^::fgetwc$;"
"^::fopen$;"
"^::fopen_s$;"
"^::fprintf$;"
"^::fprintf_s$;"
"^::fputc$;"
"^::fputs$;"
"^::fputwc$;"
"^::fputws$;"
"^::fread$;"
"^::freopen$;"
"^::freopen_s$;"
"^::fscanf$;"
"^::fscanf_s$;"
"^::fseek$;"
"^::fsetpos$;"
"^::ftell$;"
"^::fwprintf$;"
"^::fwprintf_s$;"
"^::fwrite$;"
"^::fwscanf$;"
"^::fwscanf_s$;"
"^::getc$;"
"^::getchar$;"
"^::getenv$;"
"^::getenv_s$;"
"^::gets_s$;"
"^::getwc$;"
"^::getwchar$;"
"^::gmtime$;"
"^::gmtime_s$;"
"^::localtime$;"
"^::localtime_s$;"
"^::malloc$;"
"^::mbrtoc16$;"
"^::mbrtoc32$;"
"^::mbsrtowcs$;"
"^::mbsrtowcs_s$;"
"^::mbstowcs$;"
"^::mbstowcs_s$;"
"^::memchr$;"
"^::mktime$;"
"^::mtx_init$;"
"^::mtx_lock$;"
"^::mtx_timedlock$;"
"^::mtx_trylock$;"
"^::mtx_unlock$;"
"^::printf_s$;"
"^::putc$;"
"^::putwc$;"
"^::raise$;"
"^::realloc$;"
"^::remove$;"
"^::rename$;"
"^::scanf$;"
"^::scanf_s$;"
"^::setlocale$;"
"^::setvbuf$;"
"^::signal$;"
"^::snprintf$;"
"^::snprintf_s$;"
"^::sprintf$;"
"^::sprintf_s$;"
"^::sscanf$;"
"^::sscanf_s$;"
"^::strchr$;"
"^::strerror_s$;"
"^::strftime$;"
"^::strpbrk$;"
"^::strrchr$;"
"^::strstr$;"
"^::strtod$;"
"^::strtof$;"
"^::strtoimax$;"
"^::strtok$;"
"^::strtok_s$;"
"^::strtol$;"
"^::strtold$;"
"^::strtoll$;"
"^::strtoul$;"
"^::strtoull$;"
"^::strtoumax$;"
"^::strxfrm$;"
"^::swprintf$;"
"^::swprintf_s$;"
"^::swscanf$;"
"^::swscanf_s$;"
"^::thrd_create$;"
"^::thrd_detach$;"
"^::thrd_join$;"
"^::thrd_sleep$;"
"^::time$;"
"^::timespec_get$;"
"^::tmpfile$;"
"^::tmpfile_s$;"
"^::tmpnam$;"
"^::tmpnam_s$;"
"^::tss_create$;"
"^::tss_get$;"
"^::tss_set$;"
"^::ungetc$;"
"^::ungetwc$;"
"^::vfprintf$;"
"^::vfprintf_s$;"
"^::vfscanf$;"
"^::vfscanf_s$;"
"^::vfwprintf$;"
"^::vfwprintf_s$;"
"^::vfwscanf$;"
"^::vfwscanf_s$;"
"^::vprintf_s$;"
"^::vscanf$;"
"^::vscanf_s$;"
"^::vsnprintf$;"
"^::vsnprintf_s$;"
"^::vsprintf$;"
"^::vsprintf_s$;"
"^::vsscanf$;"
"^::vsscanf_s$;"
"^::vswprintf$;"
"^::vswprintf_s$;"
"^::vswscanf$;"
"^::vswscanf_s$;"
"^::vwprintf_s$;"
"^::vwscanf$;"
"^::vwscanf_s$;"
"^::wcrtomb$;"
"^::wcschr$;"
"^::wcsftime$;"
"^::wcspbrk$;"
"^::wcsrchr$;"
"^::wcsrtombs$;"
"^::wcsrtombs_s$;"
"^::wcsstr$;"
"^::wcstod$;"
"^::wcstof$;"
"^::wcstoimax$;"
"^::wcstok$;"
"^::wcstok_s$;"
"^::wcstol$;"
"^::wcstold$;"
"^::wcstoll$;"
"^::wcstombs$;"
"^::wcstombs_s$;"
"^::wcstoul$;"
"^::wcstoull$;"
"^::wcstoumax$;"
"^::wcsxfrm$;"
"^::wctob$;"
"^::wctrans$;"
"^::wctype$;"
"^::wmemchr$;"
"^::wprintf_s$;"
"^::wscanf$;"
"^::wscanf_s$;";
} // namespace
namespace clang::tidy {
namespace cert {
namespace {

View File

@ -11,8 +11,10 @@
using namespace clang::ast_matchers;
namespace clang::tidy {
// Initial list was extracted from gcc documentation
static const clang::StringRef GlibcFunctions[] = {
static constexpr StringRef GlibcFunctions[] = {
"::argp_error",
"::argp_help",
"::argp_parse",
@ -171,7 +173,7 @@ static const clang::StringRef GlibcFunctions[] = {
"::wordexp",
};
static const clang::StringRef PosixFunctions[] = {
static constexpr StringRef PosixFunctions[] = {
"::asctime",
"::basename",
"::catgets",
@ -256,8 +258,6 @@ static const clang::StringRef PosixFunctions[] = {
"::wctomb",
};
namespace clang::tidy {
template <> struct OptionEnumMapping<concurrency::MtUnsafeCheck::FunctionSet> {
static llvm::ArrayRef<
std::pair<concurrency::MtUnsafeCheck::FunctionSet, StringRef>>
@ -273,7 +273,7 @@ template <> struct OptionEnumMapping<concurrency::MtUnsafeCheck::FunctionSet> {
namespace concurrency {
static ast_matchers::internal::Matcher<clang::NamedDecl>
static ast_matchers::internal::Matcher<NamedDecl>
hasAnyMtUnsafeNames(MtUnsafeCheck::FunctionSet Libc) {
switch (Libc) {
case MtUnsafeCheck::FunctionSet::Posix:

View File

@ -48,7 +48,7 @@ static std::string createReplacementText(const LambdaExpr *Lambda) {
std::string Replacement;
llvm::raw_string_ostream Stream(Replacement);
auto AppendName = [&](llvm::StringRef Name) {
auto AppendName = [&](StringRef Name) {
if (!Replacement.empty())
Stream << ", ";
if (Lambda->getCaptureDefault() == LCD_ByRef && Name != "this")

View File

@ -56,7 +56,7 @@ void NoSuspendWithLockCheck::check(const MatchFinder::MatchResult &Result) {
Options.AddTemporaryDtors = true;
const std::unique_ptr<CFG> TheCFG = CFG::buildCFG(
nullptr, const_cast<clang::CompoundStmt *>(Block), &Context, Options);
nullptr, const_cast<CompoundStmt *>(Block), &Context, Options);
if (!TheCFG)
return;

View File

@ -251,12 +251,12 @@ void PreferMemberInitializerCheck::check(
// comma.
InsertPrefix = ", ";
} else {
InsertPos = Lexer::getLocForEndOfToken(
Ctor->getTypeSourceInfo()
->getTypeLoc()
.getAs<clang::FunctionTypeLoc>()
.getLocalRangeEnd(),
0, *Result.SourceManager, getLangOpts());
InsertPos = Lexer::getLocForEndOfToken(Ctor->getTypeSourceInfo()
->getTypeLoc()
.getAs<FunctionTypeLoc>()
.getLocalRangeEnd(),
0, *Result.SourceManager,
getLangOpts());
// If this is first time in the loop, there are no initializers so
// `:` declares member initialization list. If this is a

View File

@ -16,7 +16,7 @@ using namespace clang::ast_matchers;
namespace clang::tidy::cppcoreguidelines {
static constexpr llvm::StringRef DefaultExclusionStr =
static constexpr StringRef DefaultExclusionStr =
"::std::map;::std::unordered_map;::std::flat_map";
ProBoundsAvoidUncheckedContainerAccessCheck::

View File

@ -35,11 +35,11 @@ public:
private:
// A list of class names that are excluded from the warning
std::vector<llvm::StringRef> ExcludedClasses;
std::vector<StringRef> ExcludedClasses;
// Setting which fix to suggest
FixModes FixMode;
llvm::StringRef FixFunction;
llvm::StringRef FixFunctionEmptyArgs;
StringRef FixFunction;
StringRef FixFunctionEmptyArgs;
};
} // namespace clang::tidy::cppcoreguidelines

View File

@ -76,7 +76,7 @@ void SpecialMemberFunctionsCheck::registerMatchers(MatchFinder *Finder) {
this);
}
static llvm::StringRef
static StringRef
toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K) {
switch (K) {
case SpecialMemberFunctionsCheck::SpecialMemberFunctionKind::Destructor:
@ -101,7 +101,7 @@ toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K) {
static std::string
join(ArrayRef<SpecialMemberFunctionsCheck::SpecialMemberFunctionKind> SMFS,
llvm::StringRef AndOr) {
StringRef AndOr) {
assert(!SMFS.empty() &&
"List of defined or undefined members should never be empty.");
std::string Buffer;
@ -126,7 +126,7 @@ void SpecialMemberFunctionsCheck::check(
std::string(MatchedDecl->getName()));
auto StoreMember = [this, &ID](SpecialMemberFunctionData Data) {
llvm::SmallVectorImpl<SpecialMemberFunctionData> &Members =
SmallVectorImpl<SpecialMemberFunctionData> &Members =
ClassWithSpecialMembers[ID];
if (!llvm::is_contained(Members, Data))
Members.push_back(std::move(Data));
@ -165,7 +165,7 @@ void SpecialMemberFunctionsCheck::onEndOfTranslationUnit() {
void SpecialMemberFunctionsCheck::checkForMissingMembers(
const ClassDefId &ID,
llvm::ArrayRef<SpecialMemberFunctionData> DefinedMembers) {
llvm::SmallVector<SpecialMemberFunctionKind, 5> MissingMembers;
SmallVector<SpecialMemberFunctionKind, 5> MissingMembers;
auto HasMember = [&](SpecialMemberFunctionKind Kind) {
return llvm::any_of(DefinedMembers, [Kind](const auto &Data) {
@ -234,7 +234,7 @@ void SpecialMemberFunctionsCheck::checkForMissingMembers(
}
if (!MissingMembers.empty()) {
llvm::SmallVector<SpecialMemberFunctionKind, 5> DefinedMemberKinds;
SmallVector<SpecialMemberFunctionKind, 5> DefinedMemberKinds;
for (const auto &Data : DefinedMembers)
if (!Data.IsImplicit)
DefinedMemberKinds.push_back(Data.FunctionKind);

View File

@ -56,8 +56,7 @@ public:
using ClassDefId = std::pair<SourceLocation, std::string>;
using ClassDefiningSpecialMembersMap =
llvm::DenseMap<ClassDefId,
llvm::SmallVector<SpecialMemberFunctionData, 5>>;
llvm::DenseMap<ClassDefId, SmallVector<SpecialMemberFunctionData, 5>>;
private:
void checkForMissingMembers(

View File

@ -15,17 +15,17 @@ namespace custom {
// will changed dynamically when switching to different source file.
static void registerCustomChecks(const ClangTidyOptions &Options,
ClangTidyCheckFactories &Factories) {
static llvm::SmallSet<llvm::SmallString<32>, 8> CustomCheckNames{};
static llvm::SmallSet<SmallString<32>, 8> CustomCheckNames{};
if (!Options.CustomChecks.has_value() || Options.CustomChecks->empty())
return;
for (const llvm::SmallString<32> &Name : CustomCheckNames)
for (const SmallString<32> &Name : CustomCheckNames)
Factories.eraseCheck(Name);
for (const ClangTidyOptions::CustomCheckValue &V :
Options.CustomChecks.value()) {
llvm::SmallString<32> Name = llvm::StringRef{"custom-" + V.Name};
SmallString<32> Name = StringRef{"custom-" + V.Name};
Factories.registerCheckFactory(
// add custom- prefix to avoid conflicts with builtin checks
Name, [&V](llvm::StringRef Name, ClangTidyContext *Context) {
Name, [&V](StringRef Name, ClangTidyContext *Context) {
return std::make_unique<custom::QueryCheck>(Name, V, Context);
});
CustomCheckNames.insert(std::move(Name));

View File

@ -31,27 +31,27 @@ parseQuery(const ClangTidyOptions::CustomCheckValue &V,
ClangTidyContext *Context) {
SmallVector<ast_matchers::dynamic::DynTypedMatcher> Matchers{};
clang::query::QuerySession QS({});
llvm::StringRef QueryStringRef{V.Query};
StringRef QueryStringRef{V.Query};
while (!QueryStringRef.empty()) {
const query::QueryRef Q = query::QueryParser::parse(QueryStringRef, QS);
switch (Q->Kind) {
case query::QK_Match: {
const auto &MatchQuery = llvm::cast<query::MatchQuery>(*Q);
const auto &MatchQuery = cast<query::MatchQuery>(*Q);
Matchers.push_back(MatchQuery.Matcher);
break;
}
case query::QK_Let: {
const auto &LetQuery = llvm::cast<query::LetQuery>(*Q);
const auto &LetQuery = cast<query::LetQuery>(*Q);
LetQuery.run(llvm::errs(), QS);
break;
}
case query::QK_NoOp: {
const auto &NoOpQuery = llvm::cast<query::NoOpQuery>(*Q);
const auto &NoOpQuery = cast<query::NoOpQuery>(*Q);
NoOpQuery.run(llvm::errs(), QS);
break;
}
case query::QK_Invalid: {
const auto &InvalidQuery = llvm::cast<query::InvalidQuery>(*Q);
const auto &InvalidQuery = cast<query::InvalidQuery>(*Q);
emitConfigurationDiag(Context, InvalidQuery.ErrStr, V.Name);
return {};
}
@ -99,7 +99,7 @@ parseQuery(const ClangTidyOptions::CustomCheckValue &V,
return Matchers;
}
QueryCheck::QueryCheck(llvm::StringRef Name,
QueryCheck::QueryCheck(StringRef Name,
const ClangTidyOptions::CustomCheckValue &V,
ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {
@ -107,11 +107,11 @@ QueryCheck::QueryCheck(llvm::StringRef Name,
auto DiagnosticIdIt =
Diags
.try_emplace(D.Level.value_or(DiagnosticIDs::Warning),
llvm::StringMap<llvm::SmallVector<std::string>>{})
llvm::StringMap<SmallVector<std::string>>{})
.first;
auto DiagMessageIt =
DiagnosticIdIt->getSecond()
.try_emplace(D.BindName, llvm::SmallVector<std::string>{})
.try_emplace(D.BindName, SmallVector<std::string>{})
.first;
DiagMessageIt->second.emplace_back(D.Message);
}

View File

@ -22,15 +22,14 @@ namespace clang::tidy::custom {
/// Not directly visible to users.
class QueryCheck : public ClangTidyCheck {
public:
QueryCheck(llvm::StringRef Name, const ClangTidyOptions::CustomCheckValue &V,
QueryCheck(StringRef Name, const ClangTidyOptions::CustomCheckValue &V,
ClangTidyContext *Context);
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
private:
llvm::SmallVector<ast_matchers::dynamic::DynTypedMatcher> Matchers;
using BindNameMapToDiagMessage =
llvm::StringMap<llvm::SmallVector<std::string>>;
SmallVector<ast_matchers::dynamic::DynTypedMatcher> Matchers;
using BindNameMapToDiagMessage = llvm::StringMap<SmallVector<std::string>>;
using DiagMaps =
llvm::DenseMap<DiagnosticIDs::Level, BindNameMapToDiagMessage>;
DiagMaps Diags;

View File

@ -75,7 +75,7 @@ static FixItHint generateFixItHint(const FunctionDecl *Decl) {
if (NewName != Name)
return FixItHint::CreateReplacement(
CharSourceRange::getTokenRange(SourceRange(Decl->getLocation())),
llvm::StringRef(NewName));
StringRef(NewName));
return {};
}

View File

@ -46,13 +46,12 @@ static FixItHint generateFixItHint(const VarDecl *Decl, bool IsConst) {
return {};
}
auto NewName = (IsConst ? "k" : "g") +
llvm::StringRef(std::string(1, FC)).upper() +
auto NewName = (IsConst ? "k" : "g") + StringRef(std::string(1, FC)).upper() +
Decl->getName().substr(1).str();
return FixItHint::CreateReplacement(
CharSourceRange::getTokenRange(SourceRange(Decl->getLocation())),
llvm::StringRef(NewName));
StringRef(NewName));
}
void GlobalVariableDeclarationCheck::registerMatchers(MatchFinder *Finder) {

View File

@ -41,8 +41,7 @@ public:
TodoCommentHandler(TodoCommentCheck &Check, std::optional<std::string> User)
: Check(Check), User(User ? *User : "unknown"),
TodoMatch(R"(^// *TODO *((\((.*)\))?:?( )?|: *(.*) *- *)?(.*)$)") {
const llvm::StringRef TodoStyleString =
Check.Options.get("Style", "Hyphen");
const StringRef TodoStyleString = Check.Options.get("Style", "Hyphen");
for (const auto &[Value, Name] :
OptionEnumMapping<StyleKind>::getEnumMapping()) {
if (Name == TodoStyleString) {

View File

@ -17,13 +17,12 @@ using namespace clang::ast_matchers;
namespace clang::tidy::google {
static const llvm::StringRef RenameCaseToSuiteMessage =
static constexpr StringRef RenameCaseToSuiteMessage =
"Google Test APIs named with 'case' are deprecated; use equivalent APIs "
"named with 'suite'";
static std::optional<llvm::StringRef>
getNewMacroName(llvm::StringRef MacroName) {
static const llvm::StringMap<llvm::StringRef> ReplacementMap = {
static std::optional<StringRef> getNewMacroName(StringRef MacroName) {
static const llvm::StringMap<StringRef> ReplacementMap = {
{"TYPED_TEST_CASE", "TYPED_TEST_SUITE"},
{"TYPED_TEST_CASE_P", "TYPED_TEST_SUITE_P"},
{"REGISTER_TYPED_TEST_CASE_P", "REGISTER_TYPED_TEST_SUITE_P"},
@ -62,7 +61,7 @@ public:
// We check if the newly defined macro is one of the target replacements.
// This ensures that the check creates warnings only if it is including a
// recent enough version of Google Test.
const llvm::StringRef FileName = PP->getSourceManager().getFilename(
const StringRef FileName = PP->getSourceManager().getFilename(
MD->getMacroInfo()->getDefinitionLoc());
ReplacementFound = FileName.ends_with("gtest/gtest-typed-test.h") &&
PP->getSpelling(MacroNameTok) == "TYPED_TEST_SUITE";
@ -87,18 +86,18 @@ public:
private:
enum class CheckAction { Warn, Rename };
void macroUsed(const clang::Token &MacroNameTok, const MacroDefinition &MD,
void macroUsed(const Token &MacroNameTok, const MacroDefinition &MD,
SourceLocation Loc, CheckAction Action) {
if (!ReplacementFound)
return;
const std::string Name = PP->getSpelling(MacroNameTok);
std::optional<llvm::StringRef> Replacement = getNewMacroName(Name);
std::optional<StringRef> Replacement = getNewMacroName(Name);
if (!Replacement)
return;
const llvm::StringRef FileName = PP->getSourceManager().getFilename(
const StringRef FileName = PP->getSourceManager().getFilename(
MD.getMacroInfo()->getDefinitionLoc());
if (!FileName.ends_with("gtest/gtest-typed-test.h"))
return;
@ -201,8 +200,8 @@ void UpgradeGoogletestCaseCheck::registerMatchers(MatchFinder *Finder) {
this);
}
static llvm::StringRef getNewMethodName(llvm::StringRef CurrentName) {
static const llvm::StringMap<llvm::StringRef> ReplacementMap = {
static StringRef getNewMethodName(StringRef CurrentName) {
static const llvm::StringMap<StringRef> ReplacementMap = {
{"SetUpTestCase", "SetUpTestSuite"},
{"TearDownTestCase", "TearDownTestSuite"},
{"test_case_name", "test_suite_name"},
@ -238,7 +237,7 @@ static bool isInTemplate(const NodeType &Node,
static bool
derivedTypeHasReplacementMethod(const MatchFinder::MatchResult &Result,
llvm::StringRef ReplacementMethod) {
StringRef ReplacementMethod) {
const auto *Class = Result.Nodes.getNodeAs<CXXRecordDecl>("class");
return !match(cxxRecordDecl(
unless(isExpansionInFileMatching(
@ -264,7 +263,7 @@ getAliasNameRange(const MatchFinder::MatchResult &Result) {
}
void UpgradeGoogletestCaseCheck::check(const MatchFinder::MatchResult &Result) {
llvm::StringRef ReplacementText;
StringRef ReplacementText;
CharSourceRange ReplacementRange;
if (const auto *Method = Result.Nodes.getNodeAs<CXXMethodDecl>("method")) {
ReplacementText = getNewMethodName(Method->getName());
@ -273,7 +272,7 @@ void UpgradeGoogletestCaseCheck::check(const MatchFinder::MatchResult &Result) {
bool IsInTemplate = false;
bool AddFix = true;
if (const auto *Call = Result.Nodes.getNodeAs<CXXMemberCallExpr>("call")) {
const auto *Callee = llvm::cast<MemberExpr>(Call->getCallee());
const auto *Callee = cast<MemberExpr>(Call->getCallee());
ReplacementRange = CharSourceRange::getTokenRange(Callee->getMemberLoc(),
Callee->getMemberLoc());
IsInInstantiation = isInInstantiation(*Call, Result);

View File

@ -50,14 +50,14 @@ static EditGenerator rewrite(RangeSelector Call, RangeSelector Builder) {
auto NextToken = [&](std::optional<Token> CurrentToken) {
if (!CurrentToken)
return CurrentToken;
if (CurrentToken->is(clang::tok::eof))
if (CurrentToken->is(tok::eof))
return std::optional<Token>();
return utils::lexer::findNextTokenSkippingComments(
CurrentToken->getLocation(), SM, LangOpts);
};
std::optional<Token> LessToken =
utils::lexer::findNextTokenSkippingComments(Begin, SM, LangOpts);
while (LessToken && LessToken->getKind() != clang::tok::less)
while (LessToken && LessToken->getKind() != tok::less)
LessToken = NextToken(LessToken);
if (!LessToken) {
return llvm::make_error<llvm::StringError>(llvm::errc::invalid_argument,
@ -66,7 +66,7 @@ static EditGenerator rewrite(RangeSelector Call, RangeSelector Builder) {
std::optional<Token> EndToken = NextToken(LessToken);
std::optional<Token> GreaterToken = NextToken(EndToken);
for (; GreaterToken && GreaterToken->getKind() != clang::tok::greater;
for (; GreaterToken && GreaterToken->getKind() != tok::greater;
GreaterToken = NextToken(GreaterToken)) {
EndToken = GreaterToken;
}
@ -76,7 +76,7 @@ static EditGenerator rewrite(RangeSelector Call, RangeSelector Builder) {
}
std::optional<Token> ArgStart = NextToken(GreaterToken);
if (!ArgStart || ArgStart->getKind() != clang::tok::l_paren) {
if (!ArgStart || ArgStart->getKind() != tok::l_paren) {
return llvm::make_error<llvm::StringError>(llvm::errc::invalid_argument,
"missing '(' token");
}
@ -85,7 +85,7 @@ static EditGenerator rewrite(RangeSelector Call, RangeSelector Builder) {
return llvm::make_error<llvm::StringError>(llvm::errc::invalid_argument,
"unexpected end of file");
}
const bool HasArgs = Arg->getKind() != clang::tok::r_paren;
const bool HasArgs = Arg->getKind() != tok::r_paren;
Expected<CharSourceRange> BuilderRange = Builder(Result);
if (!BuilderRange)
@ -93,7 +93,7 @@ static EditGenerator rewrite(RangeSelector Call, RangeSelector Builder) {
// Helper for concatting below.
auto GetText = [&](const CharSourceRange &Range) {
return clang::Lexer::getSourceText(Range, SM, LangOpts);
return Lexer::getSourceText(Range, SM, LangOpts);
};
Edit Replace;

View File

@ -64,7 +64,7 @@ void CalleeNamespaceCheck::check(const MatchFinder::MatchResult &Result) {
<< FuncDecl << RequiredNamespaceRefMacroName;
diag(FuncDecl->getLocation(), "resolves to this declaration",
clang::DiagnosticIDs::Note);
DiagnosticIDs::Note);
}
} // namespace clang::tidy::llvm_libc

View File

@ -78,8 +78,7 @@ void InlineFunctionDeclCheck::check(const MatchFinder::MatchResult &Result) {
// Check if decl starts with LIBC_INLINE
auto Loc = FullSourceLoc(Result.SourceManager->getFileLoc(SrcBegin),
*Result.SourceManager);
const llvm::StringRef SrcText =
Loc.getBufferData().drop_front(Loc.getFileOffset());
const StringRef SrcText = Loc.getBufferData().drop_front(Loc.getFileOffset());
if (SrcText.starts_with("LIBC_INLINE"))
return;

View File

@ -45,7 +45,7 @@ ConfusableIdentifierCheck::~ConfusableIdentifierCheck() = default;
// We're skipping 1. and 3. for the sake of simplicity, but this can lead to
// false positive.
static llvm::SmallString<64U> skeleton(StringRef Name) {
static SmallString<64U> skeleton(StringRef Name) {
using namespace llvm;
SmallString<64U> Skeleton;
Skeleton.reserve(1U + Name.size());
@ -102,7 +102,7 @@ struct Entry {
// that has no corresponding context, such as an alias template or variable
// template.
using DeclsWithinContextMap =
llvm::DenseMap<const Decl *, llvm::SmallVector<Entry, 1>>;
llvm::DenseMap<const Decl *, SmallVector<Entry, 1>>;
static bool addToContext(DeclsWithinContextMap &DeclsWithinContext,
const Decl *Context, Entry E) {
@ -189,7 +189,7 @@ void ConfusableIdentifierCheck::addDeclToCheck(const NamedDecl *ND,
}
void ConfusableIdentifierCheck::onEndOfTranslationUnit() {
llvm::StringMap<llvm::SmallVector<const IdentifierInfo *, 1>> SkeletonToNames;
llvm::StringMap<SmallVector<const IdentifierInfo *, 1>> SkeletonToNames;
// Compute the skeleton for each identifier.
for (auto &[Ident, Decls] : NameToDecls)
SkeletonToNames[skeleton(Ident->getName())].push_back(Ident);

View File

@ -33,9 +33,8 @@ public:
private:
void addDeclToCheck(const NamedDecl *ND, const Decl *Parent);
llvm::DenseMap<
const IdentifierInfo *,
llvm::SmallVector<std::pair<const NamedDecl *, const Decl *>, 1>>
llvm::DenseMap<const IdentifierInfo *,
SmallVector<std::pair<const NamedDecl *, const Decl *>, 1>>
NameToDecls;
};

View File

@ -37,7 +37,7 @@ int main(int argc, char *argv[]) {
return 2;
}
const llvm::StringRef From = Values[0].trim();
const StringRef From = Values[0].trim();
llvm::UTF32 CodePoint = 0;
From.getAsInteger(16, CodePoint);

View File

@ -25,7 +25,7 @@ namespace clang::tidy::misc {
/// https://clang.llvm.org/extra/clang-tidy/checks/misc/coroutine-hostile-raii.html
class CoroutineHostileRAIICheck : public ClangTidyCheck {
public:
CoroutineHostileRAIICheck(llvm::StringRef Name, ClangTidyContext *Context);
CoroutineHostileRAIICheck(StringRef Name, ClangTidyContext *Context);
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
return LangOpts.CPlusPlus20;

View File

@ -43,7 +43,7 @@ public:
void FileChanged(SourceLocation Loc, FileChangeReason Reason,
SrcMgr::CharacteristicKind FileType,
FileID PrevFID) override {
if (FileType != clang::SrcMgr::C_User)
if (FileType != SrcMgr::C_User)
return;
if (Reason != EnterFile && Reason != ExitFile)
@ -77,7 +77,7 @@ public:
OptionalFileEntryRef File, StringRef, StringRef,
const Module *, bool,
SrcMgr::CharacteristicKind FileType) override {
if (FileType != clang::SrcMgr::C_User)
if (FileType != SrcMgr::C_User)
return;
NextToEnter = Range.getBegin();

View File

@ -123,7 +123,7 @@ void IncludeCleanerCheck::check(const MatchFinder::MatchResult &Result) {
const FileEntry *MainFile = SM->getFileEntryForID(SM->getMainFileID());
llvm::DenseSet<const include_cleaner::Include *> Used;
std::vector<MissingIncludeInfo> Missing;
llvm::SmallVector<Decl *> MainFileDecls;
SmallVector<Decl *> MainFileDecls;
for (Decl *D : Result.Nodes.getNodeAs<TranslationUnitDecl>("top")->decls()) {
if (!SM->isWrittenInMainFile(SM->getExpansionLoc(D->getLocation())))
continue;
@ -200,7 +200,7 @@ void IncludeCleanerCheck::check(const MatchFinder::MatchResult &Result) {
Unused.push_back(&I);
}
const llvm::StringRef Code = SM->getBufferData(SM->getMainFileID());
const StringRef Code = SM->getBufferData(SM->getMainFileID());
auto FileStyle =
format::getStyle(format::DefaultFormatStyle, getCurrentMainFile(),
format::DefaultFallbackStyle, Code,
@ -227,14 +227,14 @@ void IncludeCleanerCheck::check(const MatchFinder::MatchResult &Result) {
for (const auto &Inc : Missing) {
const std::string Spelling = include_cleaner::spellHeader(
{Inc.Missing, PP->getHeaderSearchInfo(), MainFile});
const bool Angled = llvm::StringRef{Spelling}.starts_with("<");
const bool Angled = StringRef{Spelling}.starts_with("<");
// We might suggest insertion of an existing include in edge cases, e.g.,
// include is present in a PP-disabled region, or spelling of the header
// turns out to be the same as one of the unresolved includes in the
// main file.
if (auto Replacement = HeaderIncludes.insert(
llvm::StringRef{Spelling}.trim("\"<>"), Angled,
tooling::IncludeDirective::Include)) {
if (auto Replacement =
HeaderIncludes.insert(StringRef{Spelling}.trim("\"<>"), Angled,
tooling::IncludeDirective::Include)) {
const DiagnosticBuilder DB =
diag(SM->getSpellingLoc(Inc.SymRef.RefLocation),
"no header providing \"%0\" is directly included")

View File

@ -51,7 +51,7 @@ private:
const bool UnusedIncludes;
// Whether to report missing includes.
const bool MissingIncludes;
llvm::SmallVector<llvm::Regex> IgnoreHeadersRegex;
SmallVector<llvm::Regex> IgnoreHeadersRegex;
bool shouldIgnore(const include_cleaner::Header &H);
};

View File

@ -14,8 +14,7 @@
namespace clang::tidy::misc {
class NewDeleteOverloadsCheck : public ClangTidyCheck {
llvm::DenseMap<const CXXRecordDecl *,
llvm::SmallVector<const FunctionDecl *, 4>>
llvm::DenseMap<const CXXRecordDecl *, SmallVector<const FunctionDecl *, 4>>
Overloads;
public:

View File

@ -148,8 +148,7 @@ public:
constexpr unsigned SmallCallStackSize = 16;
constexpr unsigned SmallSCCSize = 32;
using CallStackTy =
llvm::SmallVector<CallGraphNode::CallRecord, SmallCallStackSize>;
using CallStackTy = SmallVector<CallGraphNode::CallRecord, SmallCallStackSize>;
} // namespace

View File

@ -35,7 +35,7 @@ private:
ChangeKind DetectVisibilityChange;
bool CheckDestructors;
bool CheckOperators;
std::vector<llvm::StringRef> IgnoredFunctions;
std::vector<StringRef> IgnoredFunctions;
};
} // namespace clang::tidy::misc

View File

@ -868,14 +868,14 @@ static bool areExprsMacroAndNonMacro(const Expr *&LhsExpr,
return LhsLoc.isMacroID() != RhsLoc.isMacroID();
}
static bool areStringsSameIgnoreSpaces(const llvm::StringRef Left,
const llvm::StringRef Right) {
static bool areStringsSameIgnoreSpaces(const StringRef Left,
const StringRef Right) {
if (Left == Right)
return true;
// Do running comparison ignoring spaces
llvm::StringRef L = Left.trim();
llvm::StringRef R = Right.trim();
StringRef L = Left.trim();
StringRef R = Right.trim();
while (!L.empty() && !R.empty()) {
L = L.ltrim();
R = R.ltrim();
@ -905,9 +905,9 @@ static bool areExprsSameMacroOrLiteral(const BinaryOperator *BinOp,
// Left is macro so right macro too
if (Rsr.getBegin().isMacroID()) {
// Both sides are macros so they are same macro or literal
const llvm::StringRef L = Lexer::getSourceText(
const StringRef L = Lexer::getSourceText(
CharSourceRange::getTokenRange(Lsr), SM, Context->getLangOpts());
const llvm::StringRef R = Lexer::getSourceText(
const StringRef R = Lexer::getSourceText(
CharSourceRange::getTokenRange(Rsr), SM, Context->getLangOpts());
return areStringsSameIgnoreSpaces(L, R);
}

View File

@ -51,8 +51,8 @@ bool ThrowByValueCatchByReferenceCheck::isFunctionParameter(
bool ThrowByValueCatchByReferenceCheck::isCatchVariable(
const DeclRefExpr *DeclRefExpr) {
auto *ValueDecl = DeclRefExpr->getDecl();
if (auto *VarDecl = dyn_cast<clang::VarDecl>(ValueDecl))
return VarDecl->isExceptionVariable();
if (auto *Var = dyn_cast<VarDecl>(ValueDecl))
return Var->isExceptionVariable();
return false;
}

View File

@ -20,13 +20,13 @@ namespace clang::tidy::misc {
namespace {
AST_MATCHER_P(DeducedTemplateSpecializationType, refsToTemplatedDecl,
clang::ast_matchers::internal::Matcher<NamedDecl>, DeclMatcher) {
ast_matchers::internal::Matcher<NamedDecl>, DeclMatcher) {
if (const auto *TD = Node.getTemplateName().getAsTemplateDecl())
return DeclMatcher.matches(*TD, Finder, Builder);
return false;
}
AST_MATCHER_P(Type, asTagDecl, clang::ast_matchers::internal::Matcher<TagDecl>,
AST_MATCHER_P(Type, asTagDecl, ast_matchers::internal::Matcher<TagDecl>,
DeclMatcher) {
if (const TagDecl *ND = Node.getAsTagDecl())
return DeclMatcher.matches(*ND, Finder, Builder);

View File

@ -24,7 +24,7 @@ AST_POLYMORPHIC_MATCHER_P(isInHeaderFile,
}
AST_MATCHER(FunctionDecl, isMemberFunction) {
return llvm::isa<CXXMethodDecl>(&Node);
return isa<CXXMethodDecl>(&Node);
}
AST_MATCHER(VarDecl, isStaticDataMember) { return Node.isStaticDataMember(); }
} // namespace
@ -52,8 +52,7 @@ void UseAnonymousNamespaceCheck::registerMatchers(MatchFinder *Finder) {
void UseAnonymousNamespaceCheck::check(const MatchFinder::MatchResult &Result) {
if (const auto *MatchedDecl = Result.Nodes.getNodeAs<NamedDecl>("x")) {
const StringRef Type =
llvm::isa<VarDecl>(MatchedDecl) ? "variable" : "function";
const StringRef Type = isa<VarDecl>(MatchedDecl) ? "variable" : "function";
diag(MatchedDecl->getLocation(),
"%0 %1 declared 'static', move to anonymous namespace instead")
<< Type << MatchedDecl;

View File

@ -391,7 +391,7 @@ static std::vector<const FunctionDecl *>
findCandidateCallOperators(const CXXRecordDecl *RecordDecl, size_t NumArgs) {
std::vector<const FunctionDecl *> Candidates;
for (const clang::CXXMethodDecl *Method : RecordDecl->methods()) {
for (const CXXMethodDecl *Method : RecordDecl->methods()) {
const OverloadedOperatorKind OOK = Method->getOverloadedOperator();
if (OOK != OverloadedOperatorKind::OO_Call)
@ -404,7 +404,7 @@ findCandidateCallOperators(const CXXRecordDecl *RecordDecl, size_t NumArgs) {
}
// Find templated operator(), if any.
for (const clang::Decl *D : RecordDecl->decls()) {
for (const Decl *D : RecordDecl->decls()) {
const auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
if (!FTD)
continue;

View File

@ -17,49 +17,44 @@ namespace clang::tidy::modernize {
template <typename TargetType, typename NodeType>
static const TargetType *getAs(const NodeType *Node) {
if constexpr (std::is_same_v<NodeType, clang::DynTypedNode>)
if constexpr (std::is_same_v<NodeType, DynTypedNode>)
return Node->template get<TargetType>();
else
return llvm::dyn_cast<TargetType>(Node);
return dyn_cast<TargetType>(Node);
}
namespace {
AST_MATCHER(clang::TypeLoc, hasValidBeginLoc) {
return Node.getBeginLoc().isValid();
}
AST_MATCHER(TypeLoc, hasValidBeginLoc) { return Node.getBeginLoc().isValid(); }
AST_MATCHER_P(clang::TypeLoc, hasType,
clang::ast_matchers::internal::Matcher<clang::Type>,
AST_MATCHER_P(TypeLoc, hasType, ast_matchers::internal::Matcher<Type>,
InnerMatcher) {
const clang::Type *TypeNode = Node.getTypePtr();
const Type *TypeNode = Node.getTypePtr();
return TypeNode != nullptr &&
InnerMatcher.matches(*TypeNode, Finder, Builder);
}
AST_MATCHER(clang::RecordDecl, isExternCContext) {
return Node.isExternCContext();
}
AST_MATCHER(RecordDecl, isExternCContext) { return Node.isExternCContext(); }
AST_MATCHER(clang::ParmVarDecl, isArgvOfMain) {
const clang::DeclContext *DC = Node.getDeclContext();
const auto *FD = llvm::dyn_cast<clang::FunctionDecl>(DC);
AST_MATCHER(ParmVarDecl, isArgvOfMain) {
const DeclContext *DC = Node.getDeclContext();
const auto *FD = dyn_cast<FunctionDecl>(DC);
return FD ? FD->isMain() : false;
}
AST_MATCHER(clang::TypeLoc, isWithinImplicitTemplateInstantiation) {
AST_MATCHER(TypeLoc, isWithinImplicitTemplateInstantiation) {
const auto IsImplicitTemplateInstantiation = [](const auto *Node) {
const auto IsImplicitInstantiation = [](const auto *Node) {
return (Node != nullptr) && (Node->getTemplateSpecializationKind() ==
TSK_ImplicitInstantiation);
};
return (IsImplicitInstantiation(getAs<clang::CXXRecordDecl>(Node)) ||
IsImplicitInstantiation(getAs<clang::FunctionDecl>(Node)) ||
IsImplicitInstantiation(getAs<clang::VarDecl>(Node)));
return (IsImplicitInstantiation(getAs<CXXRecordDecl>(Node)) ||
IsImplicitInstantiation(getAs<FunctionDecl>(Node)) ||
IsImplicitInstantiation(getAs<VarDecl>(Node)));
};
DynTypedNodeList ParentNodes = Finder->getASTContext().getParents(Node);
const clang::NamedDecl *ParentDecl = nullptr;
const NamedDecl *ParentDecl = nullptr;
while (!ParentNodes.empty()) {
const DynTypedNode &ParentNode = ParentNodes[0];
if (IsImplicitTemplateInstantiation(&ParentNode))
@ -68,14 +63,14 @@ AST_MATCHER(clang::TypeLoc, isWithinImplicitTemplateInstantiation) {
// in case of a `NamedDecl` as parent node, it is more efficient to proceed
// with the upward traversal via DeclContexts (see below) instead of via
// parent nodes
if ((ParentDecl = ParentNode.template get<clang::NamedDecl>()))
if ((ParentDecl = ParentNode.get<NamedDecl>()))
break;
ParentNodes = Finder->getASTContext().getParents(ParentNode);
}
if (ParentDecl != nullptr) {
const clang::DeclContext *DeclContext = ParentDecl->getDeclContext();
const DeclContext *DeclContext = ParentDecl->getDeclContext();
while (DeclContext != nullptr) {
if (IsImplicitTemplateInstantiation(DeclContext))
return true;
@ -141,7 +136,7 @@ void AvoidCArraysCheck::check(const MatchFinder::MatchResult &Result) {
Result.Nodes.getNodeAs<ParmVarDecl>("param_decl") != nullptr;
const bool IsVLA = ArrayTypeLoc.getTypePtr()->isVariableArrayType();
enum class RecommendType { Array, Vector, Span };
llvm::SmallVector<const char *> RecommendTypes{};
SmallVector<const char *> RecommendTypes{};
if (IsVLA) {
RecommendTypes.push_back("'std::vector'");
} else if (ArrayTypeLoc.getTypePtr()->isIncompleteArrayType() && IsInParam) {

View File

@ -58,7 +58,7 @@ static bool pointedUnqualifiedTypesAreEqual(QualType T1, QualType T2) {
return T1.getUnqualifiedType() == T2.getUnqualifiedType();
}
static clang::CharSourceRange getReplaceRange(const ExplicitCastExpr *Expr) {
static CharSourceRange getReplaceRange(const ExplicitCastExpr *Expr) {
if (const auto *CastExpr = dyn_cast<CStyleCastExpr>(Expr))
return CharSourceRange::getCharRange(
CastExpr->getLParenLoc(),
@ -254,7 +254,7 @@ void AvoidCStyleCastCheck::check(const MatchFinder::MatchResult &Result) {
}
[[fallthrough]];
case clang::CK_IntegralCast:
case CK_IntegralCast:
// Convert integral and no-op casts between builtin types and enums to
// static_cast. A cast from enum to integer may be unnecessary, but it's
// still retained.

View File

@ -15,9 +15,9 @@
namespace clang::tidy::modernize {
using NamespaceName = llvm::SmallString<40>;
using NamespaceName = SmallString<40>;
class NS : public llvm::SmallVector<const NamespaceDecl *, 6> {
class NS : public SmallVector<const NamespaceDecl *, 6> {
public:
std::optional<SourceRange>
getCleanedNamespaceFrontRange(const SourceManager &SM,
@ -43,7 +43,7 @@ public:
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
private:
using NamespaceContextVec = llvm::SmallVector<NS, 6>;
using NamespaceContextVec = SmallVector<NS, 6>;
void reportDiagnostic(const SourceManager &SM, const LangOptions &LangOpts);
NamespaceContextVec Namespaces;

View File

@ -1074,7 +1074,7 @@ void LoopConvertCheck::check(const MatchFinder::MatchResult &Result) {
Finder.aliasFromForInit(), Loop, Descriptor);
}
llvm::StringRef LoopConvertCheck::getReverseFunction() const {
StringRef LoopConvertCheck::getReverseFunction() const {
if (!ReverseFunction.empty())
return ReverseFunction;
if (UseReverseRanges)
@ -1082,7 +1082,7 @@ llvm::StringRef LoopConvertCheck::getReverseFunction() const {
return "";
}
llvm::StringRef LoopConvertCheck::getReverseHeader() const {
StringRef LoopConvertCheck::getReverseHeader() const {
if (!ReverseHeader.empty())
return ReverseHeader;
if (UseReverseRanges && ReverseFunction.empty())

View File

@ -15,8 +15,6 @@
#include "clang/Basic/SourceLocation.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include <algorithm>
#include <memory>
#include <string>
@ -32,29 +30,26 @@ enum LoopFixerKind {
};
/// A map used to walk the AST in reverse: maps child Stmt to parent Stmt.
using StmtParentMap = llvm::DenseMap<const clang::Stmt *, const clang::Stmt *>;
using StmtParentMap = llvm::DenseMap<const Stmt *, const Stmt *>;
/// A map used to walk the AST in reverse:
/// maps VarDecl to the to parent DeclStmt.
using DeclParentMap =
llvm::DenseMap<const clang::VarDecl *, const clang::DeclStmt *>;
using DeclParentMap = llvm::DenseMap<const VarDecl *, const DeclStmt *>;
/// A map used to track which variables have been removed by a refactoring pass.
/// It maps the parent ForStmt to the removed index variable's VarDecl.
using ReplacedVarsMap =
llvm::DenseMap<const clang::ForStmt *, const clang::VarDecl *>;
using ReplacedVarsMap = llvm::DenseMap<const ForStmt *, const VarDecl *>;
/// A map used to remember the variable names generated in a Stmt
using StmtGeneratedVarNameMap =
llvm::DenseMap<const clang::Stmt *, std::string>;
using StmtGeneratedVarNameMap = llvm::DenseMap<const Stmt *, std::string>;
/// A vector used to store the AST subtrees of an Expr.
using ComponentVector = llvm::SmallVector<const clang::Expr *, 16>;
using ComponentVector = SmallVector<const Expr *, 16>;
/// Class used build the reverse AST properties needed to detect
/// name conflicts and free variables.
class StmtAncestorASTVisitor
: public clang::RecursiveASTVisitor<StmtAncestorASTVisitor> {
: public RecursiveASTVisitor<StmtAncestorASTVisitor> {
public:
StmtAncestorASTVisitor() { StmtStack.push_back(nullptr); }
@ -72,50 +67,50 @@ public:
/// Accessor for DeclParents.
const DeclParentMap &getDeclToParentStmtMap() { return DeclParents; }
friend class clang::RecursiveASTVisitor<StmtAncestorASTVisitor>;
friend class RecursiveASTVisitor<StmtAncestorASTVisitor>;
private:
StmtParentMap StmtAncestors;
DeclParentMap DeclParents;
llvm::SmallVector<const clang::Stmt *, 16> StmtStack;
SmallVector<const Stmt *, 16> StmtStack;
bool TraverseStmt(clang::Stmt *Statement);
bool VisitDeclStmt(clang::DeclStmt *Statement);
bool TraverseStmt(Stmt *Statement);
bool VisitDeclStmt(DeclStmt *Statement);
};
/// Class used to find the variables and member expressions on which an
/// arbitrary expression depends.
class ComponentFinderASTVisitor
: public clang::RecursiveASTVisitor<ComponentFinderASTVisitor> {
: public RecursiveASTVisitor<ComponentFinderASTVisitor> {
public:
ComponentFinderASTVisitor() = default;
/// Find the components of an expression and place them in a ComponentVector.
void findExprComponents(const clang::Expr *SourceExpr) {
TraverseStmt(const_cast<clang::Expr *>(SourceExpr));
void findExprComponents(const Expr *SourceExpr) {
TraverseStmt(const_cast<Expr *>(SourceExpr));
}
/// Accessor for Components.
const ComponentVector &getComponents() { return Components; }
friend class clang::RecursiveASTVisitor<ComponentFinderASTVisitor>;
friend class RecursiveASTVisitor<ComponentFinderASTVisitor>;
private:
ComponentVector Components;
bool VisitDeclRefExpr(clang::DeclRefExpr *E);
bool VisitMemberExpr(clang::MemberExpr *Member);
bool VisitDeclRefExpr(DeclRefExpr *E);
bool VisitMemberExpr(MemberExpr *Member);
};
/// Class used to determine if an expression is dependent on a variable declared
/// inside of the loop where it would be used.
class DependencyFinderASTVisitor
: public clang::RecursiveASTVisitor<DependencyFinderASTVisitor> {
: public RecursiveASTVisitor<DependencyFinderASTVisitor> {
public:
DependencyFinderASTVisitor(const StmtParentMap *StmtParents,
const DeclParentMap *DeclParents,
const ReplacedVarsMap *ReplacedVars,
const clang::Stmt *ContainingStmt)
const Stmt *ContainingStmt)
: StmtParents(StmtParents), DeclParents(DeclParents),
ContainingStmt(ContainingStmt), ReplacedVars(ReplacedVars) {}
@ -149,31 +144,30 @@ public:
/// In order to avoid this, this class looks at the container expression
/// `arr[k]` and decides whether or not it contains a sub-expression declared
/// within the loop body.
bool dependsOnInsideVariable(const clang::Stmt *Body) {
bool dependsOnInsideVariable(const Stmt *Body) {
DependsOnInsideVariable = false;
TraverseStmt(const_cast<clang::Stmt *>(Body));
TraverseStmt(const_cast<Stmt *>(Body));
return DependsOnInsideVariable;
}
friend class clang::RecursiveASTVisitor<DependencyFinderASTVisitor>;
friend class RecursiveASTVisitor<DependencyFinderASTVisitor>;
private:
const StmtParentMap *StmtParents;
const DeclParentMap *DeclParents;
const clang::Stmt *ContainingStmt;
const Stmt *ContainingStmt;
const ReplacedVarsMap *ReplacedVars;
bool DependsOnInsideVariable;
bool VisitVarDecl(clang::VarDecl *V);
bool VisitDeclRefExpr(clang::DeclRefExpr *D);
bool VisitVarDecl(VarDecl *V);
bool VisitDeclRefExpr(DeclRefExpr *D);
};
/// Class used to determine if any declarations used in a Stmt would conflict
/// with a particular identifier. This search includes the names that don't
/// actually appear in the AST (i.e. created by a refactoring tool) by including
/// a map from Stmts to generated names associated with those stmts.
class DeclFinderASTVisitor
: public clang::RecursiveASTVisitor<DeclFinderASTVisitor> {
class DeclFinderASTVisitor : public RecursiveASTVisitor<DeclFinderASTVisitor> {
public:
DeclFinderASTVisitor(const StringRef &Name,
const StmtGeneratedVarNameMap *GeneratedDecls)
@ -182,13 +176,13 @@ public:
/// Attempts to find any usages of variables name Name in Body, returning
/// true when it is used in Body. This includes the generated loop variables
/// of ForStmts which have already been transformed.
bool findUsages(const clang::Stmt *Body) {
bool findUsages(const Stmt *Body) {
Found = false;
TraverseStmt(const_cast<clang::Stmt *>(Body));
TraverseStmt(const_cast<Stmt *>(Body));
return Found;
}
friend class clang::RecursiveASTVisitor<DeclFinderASTVisitor>;
friend class RecursiveASTVisitor<DeclFinderASTVisitor>;
private:
std::string Name;
@ -197,10 +191,10 @@ private:
const StmtGeneratedVarNameMap *GeneratedDecls;
bool Found = false;
bool VisitForStmt(clang::ForStmt *);
bool VisitNamedDecl(clang::NamedDecl *);
bool VisitDeclRefExpr(clang::DeclRefExpr *);
bool VisitTypeLoc(clang::TypeLoc);
bool VisitForStmt(ForStmt *);
bool VisitNamedDecl(NamedDecl *);
bool VisitDeclRefExpr(DeclRefExpr *);
bool VisitTypeLoc(TypeLoc);
};
/// The information needed to describe a valid convertible usage
@ -270,7 +264,7 @@ private:
};
// The main computational result of ForLoopIndexVisitor.
using UsageResult = llvm::SmallVector<Usage, 8>;
using UsageResult = SmallVector<Usage, 8>;
// General functions used by ForLoopIndexUseVisitor and LoopConvertCheck.
const Expr *digThroughConstructorsConversions(const Expr *E);
@ -385,7 +379,7 @@ private:
///
/// If any of these expressions are encountered outside of an acceptable usage
/// of the loop element, lower our confidence level.
llvm::SmallVector<std::pair<const Expr *, llvm::FoldingSetNodeID>, 16>
SmallVector<std::pair<const Expr *, llvm::FoldingSetNodeID>, 16>
DependentExprs;
/// The parent-in-waiting. Will become the real parent once we traverse down
@ -435,10 +429,9 @@ public:
};
VariableNamer(StmtGeneratedVarNameMap *GeneratedDecls,
const StmtParentMap *ReverseAST, const clang::Stmt *SourceStmt,
const clang::VarDecl *OldIndex,
const clang::ValueDecl *TheContainer,
const clang::ASTContext *Context, NamingStyle Style)
const StmtParentMap *ReverseAST, const Stmt *SourceStmt,
const VarDecl *OldIndex, const ValueDecl *TheContainer,
const ASTContext *Context, NamingStyle Style)
: GeneratedDecls(GeneratedDecls), ReverseAST(ReverseAST),
SourceStmt(SourceStmt), OldIndex(OldIndex), TheContainer(TheContainer),
Context(Context), Style(Style) {}
@ -453,15 +446,15 @@ public:
private:
StmtGeneratedVarNameMap *GeneratedDecls;
const StmtParentMap *ReverseAST;
const clang::Stmt *SourceStmt;
const clang::VarDecl *OldIndex;
const clang::ValueDecl *TheContainer;
const clang::ASTContext *Context;
const Stmt *SourceStmt;
const VarDecl *OldIndex;
const ValueDecl *TheContainer;
const ASTContext *Context;
const NamingStyle Style;
// Determine whether or not a declaration that would conflict with Symbol
// exists in an outer context or in any statement contained in SourceStmt.
bool declarationExists(llvm::StringRef Symbol);
bool declarationExists(StringRef Symbol);
};
} // namespace clang::tidy::modernize

View File

@ -12,8 +12,7 @@ using namespace clang::ast_matchers;
namespace clang::tidy::modernize {
MakeUniqueCheck::MakeUniqueCheck(StringRef Name,
clang::tidy::ClangTidyContext *Context)
MakeUniqueCheck::MakeUniqueCheck(StringRef Name, ClangTidyContext *Context)
: MakeSmartPtrCheck(Name, Context, "std::make_unique"),
RequireCPlusPlus14(Options.get("MakeSmartPtrFunction", "").empty()) {}

Some files were not shown because too many files have changed in this diff Show More