[clang] [clang] Prefer StringRef::substr(0, N) to slice(0, N) (NFC) (PR #113784)

via cfe-commits cfe-commits at lists.llvm.org
Sat Oct 26 19:51:58 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-modules

@llvm/pr-subscribers-clang

Author: Kazu Hirata (kazutakahirata)

<details>
<summary>Changes</summary>

I'm planning to migrate StringRef to std::string_view
eventually. Since std::string_view does not have slice, this patch
migrates slice(0, N) to substr(0, N).


---
Full diff: https://github.com/llvm/llvm-project/pull/113784.diff


16 Files Affected:

- (modified) clang/lib/AST/DeclBase.cpp (+1-1) 
- (modified) clang/lib/Basic/Module.cpp (+1-1) 
- (modified) clang/lib/Driver/Driver.cpp (+1-1) 
- (modified) clang/lib/Driver/Job.cpp (+1-1) 
- (modified) clang/lib/Driver/ToolChain.cpp (+2-2) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+2-2) 
- (modified) clang/lib/Driver/ToolChains/Darwin.cpp (+2-2) 
- (modified) clang/lib/Driver/ToolChains/Gnu.cpp (+1-1) 
- (modified) clang/lib/Frontend/PrecompiledPreamble.cpp (+1-1) 
- (modified) clang/lib/Frontend/TextDiagnostic.cpp (+1-1) 
- (modified) clang/lib/InstallAPI/DirectoryScanner.cpp (+1-1) 
- (modified) clang/lib/Sema/SemaAvailability.cpp (+1-1) 
- (modified) clang/lib/Serialization/ASTWriter.cpp (+1-1) 
- (modified) clang/lib/Support/RISCVVIntrinsicUtils.cpp (+1-1) 
- (modified) clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp (+1-1) 
- (modified) clang/utils/TableGen/ClangDiagnosticsEmitter.cpp (+3-3) 


``````````diff
diff --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp
index 48b91dca1f6d91..d36cabd70d62db 100644
--- a/clang/lib/AST/DeclBase.cpp
+++ b/clang/lib/AST/DeclBase.cpp
@@ -631,7 +631,7 @@ static StringRef getRealizedPlatform(const AvailabilityAttr *A,
     return RealizedPlatform;
   size_t suffix = RealizedPlatform.rfind("_app_extension");
   if (suffix != StringRef::npos)
-    return RealizedPlatform.slice(0, suffix);
+    return RealizedPlatform.substr(0, suffix);
   return RealizedPlatform;
 }
 
diff --git a/clang/lib/Basic/Module.cpp b/clang/lib/Basic/Module.cpp
index a7a3f6b37efef1..f74d9908261aa3 100644
--- a/clang/lib/Basic/Module.cpp
+++ b/clang/lib/Basic/Module.cpp
@@ -74,7 +74,7 @@ static bool isPlatformEnvironment(const TargetInfo &Target, StringRef Feature) {
     auto Pos = LHS.find('-');
     if (Pos == StringRef::npos)
       return false;
-    SmallString<128> NewLHS = LHS.slice(0, Pos);
+    SmallString<128> NewLHS = LHS.substr(0, Pos);
     NewLHS += LHS.slice(Pos+1, LHS.size());
     return NewLHS == RHS;
   };
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 9878a9dad78d40..a92031e3787270 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -6875,7 +6875,7 @@ static void applyOneOverrideOption(raw_ostream &OS,
              Edit.slice(2, Edit.size() - 1).contains('/')) {
     StringRef MatchPattern = Edit.substr(2).split('/').first;
     StringRef ReplPattern = Edit.substr(2).split('/').second;
-    ReplPattern = ReplPattern.slice(0, ReplPattern.size() - 1);
+    ReplPattern = ReplPattern.substr(0, ReplPattern.size() - 1);
 
     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
       // Ignore end-of-line response file markers
diff --git a/clang/lib/Driver/Job.cpp b/clang/lib/Driver/Job.cpp
index fe2f7242b04a51..01af5306e4f31b 100644
--- a/clang/lib/Driver/Job.cpp
+++ b/clang/lib/Driver/Job.cpp
@@ -189,7 +189,7 @@ rewriteIncludes(const llvm::ArrayRef<const char *> &Args, size_t Idx,
            "Expecting -I or -F");
     StringRef Inc = FlagRef.slice(2, StringRef::npos);
     if (getAbsPath(Inc, NewInc)) {
-      SmallString<128> NewArg(FlagRef.slice(0, 2));
+      SmallString<128> NewArg(FlagRef.substr(0, 2));
       NewArg += NewInc;
       IncFlags.push_back(std::move(NewArg));
     }
diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 4df31770950858..4efeecca2475bc 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -441,7 +441,7 @@ static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
   if (!DS) {
     // Try again after stripping trailing -component.
     // clang++-tot -> clang++
-    ProgName = ProgName.slice(0, ProgName.rfind('-'));
+    ProgName = ProgName.substr(0, ProgName.rfind('-'));
     DS = FindDriverSuffix(ProgName, Pos);
   }
   return DS;
@@ -464,7 +464,7 @@ ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
 
   // Infer target from the prefix.
   StringRef Prefix(ProgName);
-  Prefix = Prefix.slice(0, LastComponent);
+  Prefix = Prefix.substr(0, LastComponent);
   std::string IgnoredError;
   bool IsRegistered =
       llvm::TargetRegistry::lookupTarget(std::string(Prefix), IgnoredError);
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp
index 04b3832327a99c..b39c8b03aed709 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -183,7 +183,7 @@ static void ParseMRecip(const Driver &D, const ArgList &Args,
     size_t RefStepLoc;
     if (!getRefinementStep(Val, D, *A, RefStepLoc))
       return;
-    StringRef ValBase = Val.slice(0, RefStepLoc);
+    StringRef ValBase = Val.substr(0, RefStepLoc);
     if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
       OutStrings.push_back(Args.MakeArgString(Out + Val));
       return;
@@ -220,7 +220,7 @@ static void ParseMRecip(const Driver &D, const ArgList &Args,
     if (!getRefinementStep(Val, D, *A, RefStep))
       return;
 
-    StringRef ValBase = Val.slice(0, RefStep);
+    StringRef ValBase = Val.substr(0, RefStep);
     llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
     if (OptionIter == OptionStrings.end()) {
       // Try again specifying float suffix.
diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp b/clang/lib/Driver/ToolChains/Darwin.cpp
index 87380869f6fdab..f06bfc5cadb0ae 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1401,7 +1401,7 @@ StringRef Darwin::getSDKName(StringRef isysroot) {
   for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
     StringRef SDK = *IT;
     if (SDK.ends_with(".sdk"))
-        return SDK.slice(0, SDK.size() - 4);
+      return SDK.substr(0, SDK.size() - 4);
   }
   return "";
 }
@@ -2454,7 +2454,7 @@ void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
     StringRef SDK = getSDKName(A->getValue());
     if (SDK.size() > 0) {
       size_t StartVer = SDK.find_first_of("0123456789");
-      StringRef SDKName = SDK.slice(0, StartVer);
+      StringRef SDKName = SDK.substr(0, StartVer);
       if (!SDKName.starts_with(getPlatformFamily()) &&
           !dropSDKNamePrefix(SDKName).starts_with(getPlatformFamily()))
         getDriver().Diag(diag::warn_incompatible_sysroot)
diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp b/clang/lib/Driver/ToolChains/Gnu.cpp
index 8397f1121ec2ce..8a03713cd971b4 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2154,7 +2154,7 @@ Generic_GCC::GCCVersion Generic_GCC::GCCVersion::Parse(StringRef VersionText) {
     // string into GoodVersion.PatchSuffix.
 
     if (size_t EndNumber = Segment.find_first_not_of("0123456789")) {
-      StringRef NumberStr = Segment.slice(0, EndNumber);
+      StringRef NumberStr = Segment.substr(0, EndNumber);
       if (NumberStr.getAsInteger(10, Number) || Number < 0)
         return false;
       OutStr = NumberStr;
diff --git a/clang/lib/Frontend/PrecompiledPreamble.cpp b/clang/lib/Frontend/PrecompiledPreamble.cpp
index cab5838fceb24d..1ad792aa94baf6 100644
--- a/clang/lib/Frontend/PrecompiledPreamble.cpp
+++ b/clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -499,7 +499,7 @@ llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
   // Remap the main source file to the preamble buffer.
   StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
   auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
-      MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
+      MainFileBuffer->getBuffer().substr(0, Bounds.Size), MainFilePath);
   if (PreprocessorOpts.RetainRemappedFileBuffers) {
     // MainFileBuffer will be deleted by unique_ptr after leaving the method.
     PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
diff --git a/clang/lib/Frontend/TextDiagnostic.cpp b/clang/lib/Frontend/TextDiagnostic.cpp
index 4119ce6048d45d..bdc7a657e794fe 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -55,7 +55,7 @@ static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
                                       bool &Normal, bool Bold) {
   while (true) {
     size_t Pos = Str.find(ToggleHighlight);
-    OS << Str.slice(0, Pos);
+    OS << Str.substr(0, Pos);
     if (Pos == StringRef::npos)
       break;
 
diff --git a/clang/lib/InstallAPI/DirectoryScanner.cpp b/clang/lib/InstallAPI/DirectoryScanner.cpp
index 03a8208c7364e9..bb285335d3eabd 100644
--- a/clang/lib/InstallAPI/DirectoryScanner.cpp
+++ b/clang/lib/InstallAPI/DirectoryScanner.cpp
@@ -65,7 +65,7 @@ llvm::Error DirectoryScanner::scanForUnwrappedLibraries(StringRef Directory) {
 
 static bool isFramework(StringRef Path) {
   while (Path.back() == '/')
-    Path = Path.slice(0, Path.size() - 1);
+    Path = Path.substr(0, Path.size() - 1);
 
   return llvm::StringSwitch<bool>(llvm::sys::path::extension(Path))
       .Case(".framework", true)
diff --git a/clang/lib/Sema/SemaAvailability.cpp b/clang/lib/Sema/SemaAvailability.cpp
index 076d3489fa9438..8e710111a2244b 100644
--- a/clang/lib/Sema/SemaAvailability.cpp
+++ b/clang/lib/Sema/SemaAvailability.cpp
@@ -63,7 +63,7 @@ static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
       if (Context.getLangOpts().AppExt) {
         size_t suffix = RealizedPlatform.rfind("_app_extension");
         if (suffix != StringRef::npos)
-          RealizedPlatform = RealizedPlatform.slice(0, suffix);
+          RealizedPlatform = RealizedPlatform.substr(0, suffix);
       }
 
       StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
diff --git a/clang/lib/Serialization/ASTWriter.cpp b/clang/lib/Serialization/ASTWriter.cpp
index c09a41f4d1403c..13355eafbc19fe 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -1188,7 +1188,7 @@ ASTWriter::createSignature() const {
 
   // Add the remaining bytes:
   //  1. Before the unhashed control block.
-  Hasher.update(AllBytes.slice(0, UnhashedControlBlockRange.first));
+  Hasher.update(AllBytes.substr(0, UnhashedControlBlockRange.first));
   //  2. Between the unhashed control block and the AST block.
   Hasher.update(
       AllBytes.slice(UnhashedControlBlockRange.second, ASTBlockRange.first));
diff --git a/clang/lib/Support/RISCVVIntrinsicUtils.cpp b/clang/lib/Support/RISCVVIntrinsicUtils.cpp
index 091e35f47fe8ef..8297e255fe3116 100644
--- a/clang/lib/Support/RISCVVIntrinsicUtils.cpp
+++ b/clang/lib/Support/RISCVVIntrinsicUtils.cpp
@@ -1187,7 +1187,7 @@ SmallVector<PrototypeDescriptor> parsePrototypes(StringRef Prototypes) {
     Idx = Prototypes.find_first_of(Primaries, Idx);
     assert(Idx != StringRef::npos);
     auto PD = PrototypeDescriptor::parsePrototypeDescriptor(
-        Prototypes.slice(0, Idx + 1));
+        Prototypes.substr(0, Idx + 1));
     if (!PD)
       llvm_unreachable("Error during parsing prototype.");
     PrototypeDescriptors.push_back(*PD);
diff --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
index d77187bfb1f2b8..8b45b650fb6369 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -222,7 +222,7 @@ static std::optional<StringRef> getSimpleMacroName(StringRef Macro) {
   std::size_t I = 0;
 
   auto FinishName = [&]() -> std::optional<StringRef> {
-    StringRef SimpleName = Name.slice(0, I);
+    StringRef SimpleName = Name.substr(0, I);
     if (SimpleName.empty())
       return std::nullopt;
     return SimpleName;
diff --git a/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp b/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
index 34e2e8f47ae71a..e0e491e121605b 100644
--- a/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
+++ b/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
@@ -1030,7 +1030,7 @@ Piece *DiagnosticTextBuilder::DiagText::parseDiagText(StringRef &Text,
         (Text[End + 1] == '%' || Text[End + 1] == '|' || Text[End + 1] == '$'));
 
     if (End) {
-      Parsed.push_back(New<TextPiece>(Text.slice(0, End), "diagtext"));
+      Parsed.push_back(New<TextPiece>(Text.substr(0, End), "diagtext"));
       Text = Text.slice(End, StringRef::npos);
       if (Text.empty())
         break;
@@ -1044,7 +1044,7 @@ Piece *DiagnosticTextBuilder::DiagText::parseDiagText(StringRef &Text,
 
     // Extract the (optional) modifier.
     size_t ModLength = Text.find_first_of("0123456789{");
-    StringRef Modifier = Text.slice(0, ModLength);
+    StringRef Modifier = Text.substr(0, ModLength);
     Text = Text.slice(ModLength, StringRef::npos);
     ModifierType ModType = StringSwitch<ModifierType>{Modifier}
                                .Case("select", MT_Select)
@@ -1091,7 +1091,7 @@ Piece *DiagnosticTextBuilder::DiagText::parseDiagText(StringRef &Text,
         ++End;
         assert(!Text.empty());
         Plural->OptionPrefixes.push_back(
-            New<TextPiece>(Text.slice(0, End), "diagtext"));
+            New<TextPiece>(Text.substr(0, End), "diagtext"));
         Text = Text.slice(End, StringRef::npos);
         Plural->Options.push_back(
             parseDiagText(Text, StopAt::PipeOrCloseBrace));

``````````

</details>


https://github.com/llvm/llvm-project/pull/113784


More information about the cfe-commits mailing list