Use StringRef::{starts,ends}_with (NFC)

This patch replaces uses of StringRef::{starts,ends}with with
StringRef::{starts,ends}_with for consistency with
std::{string,string_view}::{starts,ends}_with in C++20.

I'm planning to deprecate and eventually remove
StringRef::{starts,ends}with.
This commit is contained in:
Kazu Hirata 2023-12-14 07:53:20 -08:00
parent 66e0159db8
commit 732bccb8c1
14 changed files with 41 additions and 41 deletions

View File

@ -827,10 +827,10 @@ void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
// "IsVisibleInNewNs" matcher.
if (AliasQualifiedName != AliasName) {
// The alias is defined in some namespace.
assert(StringRef(AliasQualifiedName).endswith("::" + AliasName));
assert(StringRef(AliasQualifiedName).ends_with("::" + AliasName));
llvm::StringRef AliasNs =
StringRef(AliasQualifiedName).drop_back(AliasName.size() + 2);
if (!llvm::StringRef(OldNs).startswith(AliasNs))
if (!llvm::StringRef(OldNs).starts_with(AliasNs))
continue;
}
std::string NameWithAliasNamespace =
@ -862,7 +862,7 @@ void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext(
// If the new nested name in the new namespace is the same as it was in the
// old namespace, we don't create replacement unless there can be ambiguity.
if ((NestedName == ReplaceName && !Conflict) ||
(NestedName.startswith("::") && NestedName.drop_front(2) == ReplaceName))
(NestedName.starts_with("::") && NestedName.drop_front(2) == ReplaceName))
return;
// If the reference need to be fully-qualified, add a leading "::" unless
// NewNamespace is the global namespace.
@ -891,7 +891,7 @@ void ChangeNamespaceTool::fixTypeLoc(
// a typedef type, we need to use the typedef type instead.
auto IsInMovedNs = [&](const NamedDecl *D) {
if (!llvm::StringRef(D->getQualifiedNameAsString())
.startswith(OldNamespace + "::"))
.starts_with(OldNamespace + "::"))
return false;
auto ExpansionLoc = Result.SourceManager->getExpansionLoc(D->getBeginLoc());
if (ExpansionLoc.isInvalid())

View File

@ -28,7 +28,7 @@ std::string createQualifiedNameForReplacement(
const find_all_symbols::SymbolInfo &MatchedSymbol) {
// No need to add missing qualifiers if SymbolIdentifier has a global scope
// operator "::".
if (RawSymbolName.startswith("::"))
if (RawSymbolName.starts_with("::"))
return std::string(RawSymbolName);
std::string QualifiedName = MatchedSymbol.getQualifiedName();
@ -42,7 +42,7 @@ std::string createQualifiedNameForReplacement(
auto SymbolQualifiers = SplitQualifiers(RawSymbolName);
std::string StrippedQualifiers;
while (!SymbolQualifiers.empty() &&
!llvm::StringRef(QualifiedName).endswith(SymbolQualifiers.back())) {
!llvm::StringRef(QualifiedName).ends_with(SymbolQualifiers.back())) {
StrippedQualifiers =
"::" + SymbolQualifiers.back().str() + StrippedQualifiers;
SymbolQualifiers.pop_back();

View File

@ -82,7 +82,7 @@ SymbolIndexManager::search(llvm::StringRef Identifier,
Identifier.split(Names, "::");
bool IsFullyQualified = false;
if (Identifier.startswith("::")) {
if (Identifier.starts_with("::")) {
Names.erase(Names.begin()); // Drop first (empty) element.
IsFullyQualified = true;
}

View File

@ -24,7 +24,7 @@ std::string getIncludePath(const SourceManager &SM, SourceLocation Loc,
FilePath = SM.getFilename(Loc);
if (FilePath.empty())
return "";
if (!FilePath.endswith(".inc"))
if (!FilePath.ends_with(".inc"))
break;
FileID ID = SM.getFileID(Loc);
Loc = SM.getIncludeLoc(ID);

View File

@ -54,9 +54,9 @@ public:
// Parse the extra command line args.
// FIXME: This is very limited at the moment.
for (StringRef Arg : Args) {
if (Arg.startswith("-db="))
if (Arg.starts_with("-db="))
DB = Arg.substr(strlen("-db="));
else if (Arg.startswith("-input="))
else if (Arg.starts_with("-input="))
Input = Arg.substr(strlen("-input="));
}

View File

@ -126,7 +126,7 @@ analyze(llvm::ArrayRef<Decl *> ASTRoots,
// Since most private -> public mappings happen in a verbatim way, we
// check textually here. This might go wrong in presence of symlinks or
// header mappings. But that's not different than rest of the places.
if (MainFile->tryGetRealPathName().endswith(PHeader))
if (MainFile->tryGetRealPathName().ends_with(PHeader))
continue;
}
}

View File

@ -277,7 +277,7 @@ public:
int CommentLine = SM.getLineNumber(CommentFID, CommentOffset);
if (InMainFile) {
if (Pragma->startswith("keep")) {
if (Pragma->starts_with("keep")) {
KeepStack.push_back({CommentLine, false});
} else if (Pragma->starts_with("begin_keep")) {
KeepStack.push_back({CommentLine, true});
@ -300,9 +300,10 @@ public:
StringRef PublicHeader;
if (Pragma->consume_front(", include ")) {
// We always insert using the spelling from the pragma.
PublicHeader = save(Pragma->startswith("<") || Pragma->startswith("\"")
? (*Pragma)
: ("\"" + *Pragma + "\"").str());
PublicHeader =
save(Pragma->starts_with("<") || Pragma->starts_with("\"")
? (*Pragma)
: ("\"" + *Pragma + "\"").str());
}
Out->IWYUPublic.insert({CommentUID, PublicHeader});
return false;
@ -313,11 +314,11 @@ public:
}
auto Filename = FE->getName();
// Record export pragma.
if (Pragma->startswith("export")) {
if (Pragma->starts_with("export")) {
ExportStack.push_back({CommentLine, CommentFID, save(Filename), false});
} else if (Pragma->startswith("begin_exports")) {
} else if (Pragma->starts_with("begin_exports")) {
ExportStack.push_back({CommentLine, CommentFID, save(Filename), true});
} else if (Pragma->startswith("end_exports")) {
} else if (Pragma->starts_with("end_exports")) {
// FIXME: be robust on unmatching cases. We should only pop the stack if
// the begin_exports and end_exports is in the same file.
if (!ExportStack.empty()) {

View File

@ -302,7 +302,7 @@ void CoverageChecker::collectUmbrellaHeaderHeader(StringRef HeaderName) {
sys::fs::current_path(PathBuf);
// HeaderName will have an absolute path, so if it's the module map
// directory, we remove it, also skipping trailing separator.
if (HeaderName.startswith(PathBuf))
if (HeaderName.starts_with(PathBuf))
HeaderName = HeaderName.substr(PathBuf.size() + 1);
// Save header name.
ModuleMapHeadersSet.insert(ModularizeUtilities::getCanonicalPath(HeaderName));
@ -356,8 +356,8 @@ bool CoverageChecker::collectFileSystemHeaders(StringRef IncludePath) {
sys::path::append(Directory, IncludePath);
if (Directory.size() == 0)
Directory = ".";
if (IncludePath.startswith("/") || IncludePath.startswith("\\") ||
((IncludePath.size() >= 2) && (IncludePath[1] == ':'))) {
if (IncludePath.starts_with("/") || IncludePath.starts_with("\\") ||
((IncludePath.size() >= 2) && (IncludePath[1] == ':'))) {
llvm::errs() << "error: Include path \"" << IncludePath
<< "\" is not relative to the module map file.\n";
return false;

View File

@ -75,12 +75,11 @@ std::error_code ModularizeUtilities::loadAllHeaderListsAndDependencies() {
for (auto I = InputFilePaths.begin(), E = InputFilePaths.end(); I != E; ++I) {
llvm::StringRef InputPath = *I;
// If it's a module map.
if (InputPath.endswith(".modulemap")) {
if (InputPath.ends_with(".modulemap")) {
// Load the module map.
if (std::error_code EC = loadModuleMap(InputPath))
return EC;
}
else {
} else {
// Else we assume it's a header list and load it.
if (std::error_code EC = loadSingleHeaderListsAndDependencies(InputPath)) {
errs() << "modularize: error: Unable to get header list '" << InputPath
@ -276,7 +275,7 @@ std::error_code ModularizeUtilities::loadModuleMap(
StringRef DirName(Dir.getName());
if (llvm::sys::path::filename(DirName) == "Modules") {
DirName = llvm::sys::path::parent_path(DirName);
if (DirName.endswith(".framework")) {
if (DirName.ends_with(".framework")) {
auto FrameworkDirOrErr = FileMgr->getDirectoryRef(DirName);
if (!FrameworkDirOrErr) {
// This can happen if there's a race between the above check and the
@ -444,7 +443,7 @@ static std::string replaceDotDot(StringRef Path) {
llvm::sys::path::append(Buffer, *B);
++B;
}
if (Path.endswith("/") || Path.endswith("\\"))
if (Path.ends_with("/") || Path.ends_with("\\"))
Buffer.append(1, Path.back());
return Buffer.c_str();
}
@ -457,7 +456,7 @@ std::string ModularizeUtilities::getCanonicalPath(StringRef FilePath) {
std::string Tmp(replaceDotDot(FilePath));
std::replace(Tmp.begin(), Tmp.end(), '\\', '/');
StringRef Tmp2(Tmp);
if (Tmp2.startswith("./"))
if (Tmp2.starts_with("./"))
Tmp = std::string(Tmp2.substr(2));
return Tmp;
}

View File

@ -883,7 +883,7 @@ public:
// Handle entering a header source file.
void handleHeaderEntry(clang::Preprocessor &PP, llvm::StringRef HeaderPath) {
// Ignore <built-in> and <command-line> to reduce message clutter.
if (HeaderPath.startswith("<"))
if (HeaderPath.starts_with("<"))
return;
HeaderHandle H = addHeader(HeaderPath);
if (H != getCurrentHeaderHandle())
@ -896,7 +896,7 @@ public:
// Handle exiting a header source file.
void handleHeaderExit(llvm::StringRef HeaderPath) {
// Ignore <built-in> and <command-line> to reduce message clutter.
if (HeaderPath.startswith("<"))
if (HeaderPath.starts_with("<"))
return;
HeaderHandle H = findHeaderHandle(HeaderPath);
HeaderHandle TH;

View File

@ -28,9 +28,9 @@ static const char *CXXBNF =
// User-defined string literals look like `""suffix`.
bool isStringUserDefined(const Token &Tok) {
return !Tok.text().endswith("\"");
return !Tok.text().ends_with("\"");
}
bool isCharUserDefined(const Token &Tok) { return !Tok.text().endswith("'"); }
bool isCharUserDefined(const Token &Tok) { return !Tok.text().ends_with("'"); }
// Combinable flags describing numbers.
// Clang has just one numeric_token kind, the grammar has 4.

View File

@ -33,11 +33,11 @@ public:
assert(llvm::all_of(Specs,
[](const RuleSpec &R) {
if (R.Target.endswith(OptSuffix))
if (R.Target.ends_with(OptSuffix))
return false;
return llvm::all_of(
R.Sequence, [](const RuleSpec::Element &E) {
return !E.Symbol.endswith(OptSuffix);
return !E.Symbol.ends_with(OptSuffix);
});
}) &&
"Optional symbols should be eliminated!");
@ -225,7 +225,7 @@ private:
Chunk = Chunk.trim();
if (Chunk.empty())
continue; // skip empty
if (Chunk.startswith("[") && Chunk.endswith("]")) {
if (Chunk.starts_with("[") && Chunk.ends_with("]")) {
if (Out.Sequence.empty())
continue;
@ -241,7 +241,7 @@ private:
bool parseAttributes(
llvm::StringRef Content,
std::vector<std::pair<llvm::StringRef, llvm::StringRef>> &Out) {
assert(Content.startswith("[") && Content.endswith("]"));
assert(Content.starts_with("[") && Content.ends_with("]"));
auto KV = Content.drop_front().drop_back().split('=');
Out.push_back({KV.first, KV.second.trim()});
@ -299,7 +299,7 @@ private:
if (Elements.empty())
return CB();
auto Front = Elements.front();
if (!Front.Symbol.endswith(OptSuffix)) {
if (!Front.Symbol.ends_with(OptSuffix)) {
Result.push_back(std::move(Front));
eliminateOptionalTail(Elements.drop_front(1), Result, CB);
Result.pop_back();

View File

@ -66,7 +66,7 @@ protected:
"#define SOME_MACRO(x) using x\n";
std::vector<ClangTidyError> Errors;
std::vector<std::string> Args;
if (!StringRef(Filename).endswith(".cpp")) {
if (!StringRef(Filename).ends_with(".cpp")) {
Args.emplace_back("-xc++-header");
}
test::runCheckOnCode<readability::GlobalNamesInHeadersCheck>(

View File

@ -948,15 +948,15 @@ int64_t ARM::getImplicitAddend(const uint8_t *buf, RelType type) const {
}
static bool isArmMapSymbol(const Symbol *b) {
return b->getName() == "$a" || b->getName().startswith("$a.");
return b->getName() == "$a" || b->getName().starts_with("$a.");
}
static bool isThumbMapSymbol(const Symbol *s) {
return s->getName() == "$t" || s->getName().startswith("$t.");
return s->getName() == "$t" || s->getName().starts_with("$t.");
}
static bool isDataMapSymbol(const Symbol *b) {
return b->getName() == "$d" || b->getName().startswith("$d.");
return b->getName() == "$d" || b->getName().starts_with("$d.");
}
void elf::sortArmMappingSymbols() {
@ -1189,7 +1189,7 @@ void elf::processArmCmseSymbols() {
// Only symbols with external linkage end up in symtab, so no need to do
// linkage checks. Only check symbol type.
for (Symbol *acleSeSym : symtab.getSymbols()) {
if (!acleSeSym->getName().startswith(ACLESESYM_PREFIX))
if (!acleSeSym->getName().starts_with(ACLESESYM_PREFIX))
continue;
// If input object build attributes do not support CMSE, error and disable
// further scanning for <sym>, __acle_se_<sym> pairs.