Skip to content

Commit f3dcc23

Browse files
[clang] Use StringRef::{starts,ends}_with (NFC) (#75149)
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.
1 parent eaa1152 commit f3dcc23

File tree

155 files changed

+547
-541
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

155 files changed

+547
-541
lines changed

clang/include/clang/Basic/Attr.td

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2878,7 +2878,7 @@ def Target : InheritableAttr {
28782878

28792879
for (auto &Feature : AttrFeatures) {
28802880
Feature = Feature.trim();
2881-
if (Feature.startswith("arch="))
2881+
if (Feature.starts_with("arch="))
28822882
return Feature.drop_front(sizeof("arch=") - 1);
28832883
}
28842884
return "";
@@ -2896,8 +2896,8 @@ def Target : InheritableAttr {
28962896
for (auto &Feature : AttrFeatures) {
28972897
Feature = Feature.trim();
28982898

2899-
if (!Feature.startswith("no-") && !Feature.startswith("arch=") &&
2900-
!Feature.startswith("fpmath=") && !Feature.startswith("tune="))
2899+
if (!Feature.starts_with("no-") && !Feature.starts_with("arch=") &&
2900+
!Feature.starts_with("fpmath=") && !Feature.starts_with("tune="))
29012901
Out.push_back(Feature);
29022902
}
29032903
}

clang/include/clang/Basic/IdentifierTable.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -511,7 +511,7 @@ class alignas(IdentifierInfoAlignment) IdentifierInfo {
511511
/// function(<#int x#>);
512512
/// \endcode
513513
bool isEditorPlaceholder() const {
514-
return getName().startswith("<#") && getName().endswith("#>");
514+
return getName().starts_with("<#") && getName().ends_with("#>");
515515
}
516516

517517
/// Determine whether \p this is a name reserved for the implementation (C99

clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -409,8 +409,8 @@ AnalyzerOptions::getRegisteredCheckers(bool IncludeExperimental) {
409409
};
410410
std::vector<StringRef> Checkers;
411411
for (StringRef CheckerName : StaticAnalyzerCheckerNames) {
412-
if (!CheckerName.startswith("debug.") &&
413-
(IncludeExperimental || !CheckerName.startswith("alpha.")))
412+
if (!CheckerName.starts_with("debug.") &&
413+
(IncludeExperimental || !CheckerName.starts_with("alpha.")))
414414
Checkers.push_back(CheckerName);
415415
}
416416
return Checkers;

clang/lib/APINotes/APINotesManager.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ static void checkPrivateAPINotesName(DiagnosticsEngine &Diags,
198198
StringRef RealFileName =
199199
llvm::sys::path::filename(File->tryGetRealPathName());
200200
StringRef RealStem = llvm::sys::path::stem(RealFileName);
201-
if (RealStem.endswith("_private"))
201+
if (RealStem.ends_with("_private"))
202202
return;
203203

204204
unsigned DiagID = diag::warn_apinotes_private_case;

clang/lib/APINotes/APINotesYAMLCompiler.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -745,7 +745,7 @@ class YAMLConverter {
745745
convertCommonEntity(M, MI, M.Selector);
746746

747747
// Check if the selector ends with ':' to determine if it takes arguments.
748-
bool takesArguments = M.Selector.endswith(":");
748+
bool takesArguments = M.Selector.ends_with(":");
749749

750750
// Split the selector into pieces.
751751
llvm::SmallVector<StringRef, 4> Args;

clang/lib/ARCMigrate/ARCMT.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ createInvocationForMigration(CompilerInvocation &origCI,
201201
for (std::vector<std::string>::iterator
202202
I = CInvok->getDiagnosticOpts().Warnings.begin(),
203203
E = CInvok->getDiagnosticOpts().Warnings.end(); I != E; ++I) {
204-
if (!StringRef(*I).startswith("error"))
204+
if (!StringRef(*I).starts_with("error"))
205205
WarnOpts.push_back(*I);
206206
}
207207
WarnOpts.push_back("error=arc-unsafe-retained-assign");

clang/lib/ARCMigrate/ObjCMT.cpp

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -562,7 +562,7 @@ static void rewriteToObjCProperty(const ObjCMethodDecl *Getter,
562562
static bool IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl *D) {
563563
if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D)) {
564564
StringRef Name = CatDecl->getName();
565-
return Name.endswith("Deprecated");
565+
return Name.ends_with("Deprecated");
566566
}
567567
return false;
568568
}
@@ -1176,12 +1176,12 @@ bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
11761176
if (!SetterMethod) {
11771177
// try a different naming convention for getter: isXxxxx
11781178
StringRef getterNameString = getterName->getName();
1179-
bool IsPrefix = getterNameString.startswith("is");
1179+
bool IsPrefix = getterNameString.starts_with("is");
11801180
// Note that we don't want to change an isXXX method of retainable object
11811181
// type to property (readonly or otherwise).
11821182
if (IsPrefix && GRT->isObjCRetainableType())
11831183
return false;
1184-
if (IsPrefix || getterNameString.startswith("get")) {
1184+
if (IsPrefix || getterNameString.starts_with("get")) {
11851185
LengthOfPrefix = (IsPrefix ? 2 : 3);
11861186
const char *CGetterName = getterNameString.data() + LengthOfPrefix;
11871187
// Make sure that first character after "is" or "get" prefix can
@@ -1320,11 +1320,11 @@ void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
13201320
if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) {
13211321
StringRef STRefMethodName(MethodName);
13221322
size_t len = 0;
1323-
if (STRefMethodName.startswith("standard"))
1323+
if (STRefMethodName.starts_with("standard"))
13241324
len = strlen("standard");
1325-
else if (STRefMethodName.startswith("shared"))
1325+
else if (STRefMethodName.starts_with("shared"))
13261326
len = strlen("shared");
1327-
else if (STRefMethodName.startswith("default"))
1327+
else if (STRefMethodName.starts_with("default"))
13281328
len = strlen("default");
13291329
else
13301330
return;
@@ -1341,7 +1341,7 @@ void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
13411341
StringRef LoweredMethodName(MethodName);
13421342
std::string StringLoweredMethodName = LoweredMethodName.lower();
13431343
LoweredMethodName = StringLoweredMethodName;
1344-
if (!LoweredMethodName.startswith(ClassNamePostfix))
1344+
if (!LoweredMethodName.starts_with(ClassNamePostfix))
13451345
return;
13461346
if (OIT_Family == OIT_ReturnsSelf)
13471347
ReplaceWithClasstype(*this, OM);

clang/lib/ARCMigrate/TransUnbridgedCasts.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ class UnbridgedCastRewriter : public RecursiveASTVisitor<UnbridgedCastRewriter>{
146146
ento::cocoa::isRefType(E->getSubExpr()->getType(), "CF",
147147
FD->getIdentifier()->getName())) {
148148
StringRef fname = FD->getIdentifier()->getName();
149-
if (fname.endswith("Retain") || fname.contains("Create") ||
149+
if (fname.ends_with("Retain") || fname.contains("Create") ||
150150
fname.contains("Copy")) {
151151
// Do not migrate to couple of bridge transfer casts which
152152
// cancel each other out. Leave it unchanged so error gets user

clang/lib/ARCMigrate/TransformActions.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,7 @@ bool TransformActionsImpl::canReplaceText(SourceLocation loc, StringRef text) {
431431
if (invalidTemp)
432432
return false;
433433

434-
return file.substr(locInfo.second).startswith(text);
434+
return file.substr(locInfo.second).starts_with(text);
435435
}
436436

437437
void TransformActionsImpl::commitInsert(SourceLocation loc, StringRef text) {

clang/lib/ARCMigrate/Transforms.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ bool trans::isPlusOne(const Expr *E) {
9595
ento::cocoa::isRefType(callE->getType(), "CF",
9696
FD->getIdentifier()->getName())) {
9797
StringRef fname = FD->getIdentifier()->getName();
98-
if (fname.endswith("Retain") || fname.contains("Create") ||
98+
if (fname.ends_with("Retain") || fname.contains("Create") ||
9999
fname.contains("Copy"))
100100
return true;
101101
}

clang/lib/AST/ASTContext.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8223,7 +8223,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
82238223
// Another legacy compatibility encoding. Some ObjC qualifier and type
82248224
// combinations need to be rearranged.
82258225
// Rewrite "in const" from "nr" to "rn"
8226-
if (StringRef(S).endswith("nr"))
8226+
if (StringRef(S).ends_with("nr"))
82278227
S.replace(S.end()-2, S.end(), "rn");
82288228
}
82298229

@@ -13519,7 +13519,7 @@ void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
1351913519
Target->getTargetOpts().FeaturesAsWritten.begin(),
1352013520
Target->getTargetOpts().FeaturesAsWritten.end());
1352113521
} else {
13522-
if (VersionStr.startswith("arch="))
13522+
if (VersionStr.starts_with("arch="))
1352313523
TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
1352413524
else if (VersionStr != "default")
1352513525
Features.push_back((StringRef{"+"} + VersionStr).str());

clang/lib/AST/DeclPrinter.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1728,7 +1728,7 @@ void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
17281728
std::string TypeStr = PDecl->getASTContext().getUnqualifiedObjCPointerType(T).
17291729
getAsString(Policy);
17301730
Out << ' ' << TypeStr;
1731-
if (!StringRef(TypeStr).endswith("*"))
1731+
if (!StringRef(TypeStr).ends_with("*"))
17321732
Out << ' ';
17331733
Out << *PDecl;
17341734
if (Policy.PolishForDeclaration)

clang/lib/AST/Mangle.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ void MangleContext::mangleName(GlobalDecl GD, raw_ostream &Out) {
147147

148148
// If the label isn't literal, or if this is an alias for an LLVM intrinsic,
149149
// do not add a "\01" prefix.
150-
if (!ALA->getIsLiteralLabel() || ALA->getLabel().startswith("llvm.")) {
150+
if (!ALA->getIsLiteralLabel() || ALA->getLabel().starts_with("llvm.")) {
151151
Out << ALA->getLabel();
152152
return;
153153
}

clang/lib/AST/MicrosoftMangle.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ struct msvc_hashing_ostream : public llvm::raw_svector_ostream {
6363
: llvm::raw_svector_ostream(Buffer), OS(OS) {}
6464
~msvc_hashing_ostream() override {
6565
StringRef MangledName = str();
66-
bool StartsWithEscape = MangledName.startswith("\01");
66+
bool StartsWithEscape = MangledName.starts_with("\01");
6767
if (StartsWithEscape)
6868
MangledName = MangledName.drop_front(1);
6969
if (MangledName.size() < 4096) {

clang/lib/AST/PrintfFormatString.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ static PrintfSpecifierResult ParsePrintfSpecifier(FormatStringHandler &H,
140140
// Set the privacy flag if the privacy annotation in the
141141
// comma-delimited segment is at least as strict as the privacy
142142
// annotations in previous comma-delimited segments.
143-
if (MatchedStr.startswith("mask")) {
143+
if (MatchedStr.starts_with("mask")) {
144144
StringRef MaskType = MatchedStr.substr(sizeof("mask.") - 1);
145145
unsigned Size = MaskType.size();
146146
if (Warn && (Size == 0 || Size > 8))

clang/lib/AST/RawCommentList.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,8 +141,8 @@ RawComment::RawComment(const SourceManager &SourceMgr, SourceRange SR,
141141
Kind = K.first;
142142
IsTrailingComment |= K.second;
143143

144-
IsAlmostTrailingComment = RawText.startswith("//<") ||
145-
RawText.startswith("/*<");
144+
IsAlmostTrailingComment =
145+
RawText.starts_with("//<") || RawText.starts_with("/*<");
146146
} else {
147147
Kind = RCK_Merged;
148148
IsTrailingComment =

clang/lib/AST/Stmt.cpp

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -811,11 +811,12 @@ std::string MSAsmStmt::generateAsmString(const ASTContext &C) const {
811811
StringRef Instruction = Pieces[I];
812812
// For vex/vex2/vex3/evex masm style prefix, convert it to att style
813813
// since we don't support masm style prefix in backend.
814-
if (Instruction.startswith("vex "))
814+
if (Instruction.starts_with("vex "))
815815
MSAsmString += '{' + Instruction.substr(0, 3).str() + '}' +
816816
Instruction.substr(3).str();
817-
else if (Instruction.startswith("vex2 ") ||
818-
Instruction.startswith("vex3 ") || Instruction.startswith("evex "))
817+
else if (Instruction.starts_with("vex2 ") ||
818+
Instruction.starts_with("vex3 ") ||
819+
Instruction.starts_with("evex "))
819820
MSAsmString += '{' + Instruction.substr(0, 4).str() + '}' +
820821
Instruction.substr(4).str();
821822
else

clang/lib/ASTMatchers/ASTMatchersInternal.cpp

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -480,11 +480,11 @@ HasNameMatcher::HasNameMatcher(std::vector<std::string> N)
480480

481481
static bool consumeNameSuffix(StringRef &FullName, StringRef Suffix) {
482482
StringRef Name = FullName;
483-
if (!Name.endswith(Suffix))
483+
if (!Name.ends_with(Suffix))
484484
return false;
485485
Name = Name.drop_back(Suffix.size());
486486
if (!Name.empty()) {
487-
if (!Name.endswith("::"))
487+
if (!Name.ends_with("::"))
488488
return false;
489489
Name = Name.drop_back(2);
490490
}
@@ -530,7 +530,7 @@ class PatternSet {
530530
PatternSet(ArrayRef<std::string> Names) {
531531
Patterns.reserve(Names.size());
532532
for (StringRef Name : Names)
533-
Patterns.push_back({Name, Name.startswith("::")});
533+
Patterns.push_back({Name, Name.starts_with("::")});
534534
}
535535

536536
/// Consumes the name suffix from each pattern in the set and removes the ones
@@ -652,11 +652,11 @@ bool HasNameMatcher::matchesNodeFullSlow(const NamedDecl &Node) const {
652652
const StringRef FullName = OS.str();
653653

654654
for (const StringRef Pattern : Names) {
655-
if (Pattern.startswith("::")) {
655+
if (Pattern.starts_with("::")) {
656656
if (FullName == Pattern)
657657
return true;
658-
} else if (FullName.endswith(Pattern) &&
659-
FullName.drop_back(Pattern.size()).endswith("::")) {
658+
} else if (FullName.ends_with(Pattern) &&
659+
FullName.drop_back(Pattern.size()).ends_with("::")) {
660660
return true;
661661
}
662662
}

clang/lib/ASTMatchers/Dynamic/Parser.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -187,10 +187,10 @@ class Parser::CodeTokenizer {
187187
break;
188188
++TokenLength;
189189
}
190-
if (TokenLength == 4 && Code.startswith("true")) {
190+
if (TokenLength == 4 && Code.starts_with("true")) {
191191
Result.Kind = TokenInfo::TK_Literal;
192192
Result.Value = true;
193-
} else if (TokenLength == 5 && Code.startswith("false")) {
193+
} else if (TokenLength == 5 && Code.starts_with("false")) {
194194
Result.Kind = TokenInfo::TK_Literal;
195195
Result.Value = false;
196196
} else {
@@ -737,7 +737,7 @@ bool Parser::parseMatcherExpressionImpl(const TokenInfo &NameToken,
737737
// Completions minus the prefix.
738738
void Parser::addCompletion(const TokenInfo &CompToken,
739739
const MatcherCompletion& Completion) {
740-
if (StringRef(Completion.TypedText).startswith(CompToken.Text) &&
740+
if (StringRef(Completion.TypedText).starts_with(CompToken.Text) &&
741741
Completion.Specificity > 0) {
742742
Completions.emplace_back(Completion.TypedText.substr(CompToken.Text.size()),
743743
Completion.MatcherDecl, Completion.Specificity);

clang/lib/Analysis/BodyFarm.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -726,8 +726,8 @@ Stmt *BodyFarm::getBody(const FunctionDecl *D) {
726726
FF = nullptr;
727727
break;
728728
}
729-
} else if (Name.startswith("OSAtomicCompareAndSwap") ||
730-
Name.startswith("objc_atomicCompareAndSwap")) {
729+
} else if (Name.starts_with("OSAtomicCompareAndSwap") ||
730+
Name.starts_with("objc_atomicCompareAndSwap")) {
731731
FF = create_OSAtomicCompareAndSwap;
732732
} else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
733733
FF = create_call_once;

clang/lib/Analysis/CallGraph.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ bool CallGraph::includeCalleeInGraph(const Decl *D) {
168168
return false;
169169

170170
IdentifierInfo *II = FD->getIdentifier();
171-
if (II && II->getName().startswith("__inline"))
171+
if (II && II->getName().starts_with("__inline"))
172172
return false;
173173
}
174174

clang/lib/Analysis/CalledOnceCheck.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -973,7 +973,7 @@ class CalledOnceChecker : public ConstStmtVisitor<CalledOnceChecker> {
973973
/// Return true if the given name has conventional suffixes.
974974
static bool hasConventionalSuffix(llvm::StringRef Name) {
975975
return llvm::any_of(CONVENTIONAL_SUFFIXES, [Name](llvm::StringRef Suffix) {
976-
return Name.endswith(Suffix);
976+
return Name.ends_with(Suffix);
977977
});
978978
}
979979

clang/lib/Analysis/CocoaConventions.cpp

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,10 @@ bool cocoa::isRefType(QualType RetTy, StringRef Prefix,
2626
// Recursively walk the typedef stack, allowing typedefs of reference types.
2727
while (const TypedefType *TD = RetTy->getAs<TypedefType>()) {
2828
StringRef TDName = TD->getDecl()->getIdentifier()->getName();
29-
if (TDName.startswith(Prefix) && TDName.endswith("Ref"))
29+
if (TDName.starts_with(Prefix) && TDName.ends_with("Ref"))
3030
return true;
3131
// XPC unfortunately uses CF-style function names, but aren't CF types.
32-
if (TDName.startswith("xpc_"))
32+
if (TDName.starts_with("xpc_"))
3333
return false;
3434
RetTy = TD->getDecl()->getUnderlyingType();
3535
}
@@ -43,7 +43,7 @@ bool cocoa::isRefType(QualType RetTy, StringRef Prefix,
4343
return false;
4444

4545
// Does the name start with the prefix?
46-
return Name.startswith(Prefix);
46+
return Name.starts_with(Prefix);
4747
}
4848

4949
/// Returns true when the passed-in type is a CF-style reference-counted
@@ -127,10 +127,9 @@ bool coreFoundation::followsCreateRule(const FunctionDecl *fn) {
127127
// Scan for *lowercase* 'reate' or 'opy', followed by no lowercase
128128
// character.
129129
StringRef suffix = functionName.substr(it - start);
130-
if (suffix.startswith("reate")) {
130+
if (suffix.starts_with("reate")) {
131131
it += 5;
132-
}
133-
else if (suffix.startswith("opy")) {
132+
} else if (suffix.starts_with("opy")) {
134133
it += 3;
135134
} else {
136135
// Keep scanning.

clang/lib/Analysis/FlowSensitive/Models/ChromiumCheckModel.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ bool isCheckLikeMethod(llvm::SmallDenseSet<const CXXMethodDecl *> &CheckDecls,
4343
return false;
4444

4545
for (const CXXMethodDecl *M : ParentClass->methods())
46-
if (M->getDeclName().isIdentifier() && M->getName().endswith("Check"))
46+
if (M->getDeclName().isIdentifier() && M->getName().ends_with("Check"))
4747
CheckDecls.insert(M);
4848
}
4949

0 commit comments

Comments
 (0)