Просмотр исходного кода

Refactor: Eliminate redundant `std::to_string` as arg of `cmStrCat`

Plus optimize some other string operations in the modified files.
Alex Turbov 8 месяцев назад
Родитель
Сommit
d34971f455

+ 8 - 8
Source/CTest/cmCTestRunTest.cxx

@@ -894,18 +894,17 @@ bool cmCTestRunTest::ForkProcess()
 
 void cmCTestRunTest::SetupResourcesEnvironment(std::vector<std::string>* log)
 {
-  std::string processCount = "CTEST_RESOURCE_GROUP_COUNT=";
-  processCount += std::to_string(this->AllocatedResources.size());
+  std::string processCount =
+    cmStrCat("CTEST_RESOURCE_GROUP_COUNT=", this->AllocatedResources.size());
   cmSystemTools::PutEnv(processCount);
   if (log) {
-    log->push_back(processCount);
+    log->emplace_back(std::move(processCount));
   }
 
   std::size_t i = 0;
   for (auto const& process : this->AllocatedResources) {
-    std::string prefix = "CTEST_RESOURCE_GROUP_";
-    prefix += std::to_string(i);
-    std::string resourceList = prefix + '=';
+    std::string prefix = cmStrCat("CTEST_RESOURCE_GROUP_", i);
+    std::string resourceList = cmStrCat(prefix, '=');
     prefix += '_';
     bool firstType = true;
     for (auto const& it : process) {
@@ -915,14 +914,15 @@ void cmCTestRunTest::SetupResourcesEnvironment(std::vector<std::string>* log)
       firstType = false;
       auto resourceType = it.first;
       resourceList += resourceType;
-      std::string var = prefix + cmSystemTools::UpperCase(resourceType) + '=';
+      std::string var =
+        cmStrCat(prefix, cmSystemTools::UpperCase(resourceType), '=');
       bool firstName = true;
       for (auto const& it2 : it.second) {
         if (!firstName) {
           var += ';';
         }
         firstName = false;
-        var += "id:" + it2.Id + ",slots:" + std::to_string(it2.Slots);
+        var += cmStrCat("id:", it2.Id, ",slots:", it2.Slots);
       }
       cmSystemTools::PutEnv(var);
       if (log) {

+ 3 - 3
Source/CTest/cmCTestTestHandler.cxx

@@ -2116,9 +2116,9 @@ void cmCTestTestHandler::CleanTestOutput(std::string& output, size_t length,
 
   // Truncation message.
   std::string const msg =
-    "\n[This part of the test output was removed since it "
-    "exceeds the threshold of " +
-    std::to_string(length) + " bytes.]\n";
+    cmStrCat("\n[This part of the test output was removed since it exceeds "
+             "the threshold of ",
+             length, " bytes.]\n");
 
   char const* const begin = output.c_str();
   char const* const end = begin + output.size();

+ 2 - 2
Source/cmCTest.cxx

@@ -3540,10 +3540,10 @@ void cmCTest::Log(LogType logType, std::string msg, bool suppress)
 std::string cmCTest::GetColorCode(Color color) const
 {
   if (this->Impl->OutputColorCode) {
-    return "\033[0;" + std::to_string(static_cast<int>(color)) + "m";
+    return cmStrCat("\033[0;", static_cast<int>(color), 'm');
   }
 
-  return "";
+  return {};
 }
 
 void cmCTest::SetTimeLimit(cmValue val)

+ 2 - 1
Source/cmDebuggerVariablesHelper.cxx

@@ -23,6 +23,7 @@
 #include "cmPropertyMap.h"
 #include "cmState.h"
 #include "cmStateSnapshot.h"
+#include "cmStringAlgorithms.h"
 #include "cmTarget.h"
 #include "cmTest.h"
 #include "cmValue.h"
@@ -100,7 +101,7 @@ std::shared_ptr<cmDebuggerVariables> cmDebuggerVariablesHelper::CreateIfAny(
         ret.reserve(items.size());
         int i = 0;
         for (std::string const& item : items) {
-          ret.emplace_back("[" + std::to_string(i++) + "]", item);
+          ret.emplace_back(cmStrCat('[', i++, ']'), item);
         }
         return ret;
       });

+ 11 - 17
Source/cmForEachCommand.cxx

@@ -12,7 +12,6 @@
 #include <cstdlib>
 #include <iterator>
 #include <map>
-#include <sstream>
 #include <stdexcept>
 #include <utility>
 
@@ -186,11 +185,11 @@ bool cmForEachFunctionBlocker::ReplayZipLists(
     // generate names as `var_name_N`,
     // where `N` is the count of lists to zip
     iterationVars.resize(values.size());
-    auto const iter_var_prefix = this->Args.front() + "_";
+    auto const iter_var_prefix = cmStrCat(this->Args.front(), '_');
     auto i = 0u;
     std::generate(
       iterationVars.begin(), iterationVars.end(),
-      [&]() -> std::string { return iter_var_prefix + std::to_string(i++); });
+      [&]() -> std::string { return cmStrCat(iter_var_prefix, i++); });
   }
   assert("Sanity check" && iterationVars.size() == values.size());
 
@@ -358,7 +357,7 @@ bool HandleInMode(std::vector<std::string> const& args,
 
     } else {
       makefile.IssueMessage(MessageType::FATAL_ERROR,
-                            cmStrCat("Unknown argument:\n", "  ", arg, "\n"));
+                            cmStrCat("Unknown argument:\n", "  ", arg, '\n'));
       return true;
     }
   }
@@ -367,11 +366,10 @@ bool HandleInMode(std::vector<std::string> const& args,
   // make sure the given lists count matches variables...
   if (doing == DoingZipLists && varsCount > 1u &&
       (2u * varsCount) != fb->Args.size()) {
-    makefile.IssueMessage(
-      MessageType::FATAL_ERROR,
-      cmStrCat("Expected ", std::to_string(varsCount),
-               " list variables, but given ",
-               std::to_string(fb->Args.size() - varsCount)));
+    makefile.IssueMessage(MessageType::FATAL_ERROR,
+                          cmStrCat("Expected ", varsCount,
+                                   " list variables, but given ",
+                                   fb->Args.size() - varsCount));
     return true;
   }
 
@@ -384,16 +382,12 @@ bool TryParseInteger(cmExecutionStatus& status, std::string const& str, int& i)
 {
   try {
     i = std::stoi(str);
-  } catch (std::invalid_argument&) {
-    std::ostringstream e;
-    e << "Invalid integer: '" << str << "'";
-    status.SetError(e.str());
+  } catch (std::invalid_argument const&) {
+    status.SetError(cmStrCat("Invalid integer: '", str, '\''));
     cmSystemTools::SetFatalErrorOccurred();
     return false;
-  } catch (std::out_of_range&) {
-    std::ostringstream e;
-    e << "Integer out of range: '" << str << "'";
-    status.SetError(e.str());
+  } catch (std::out_of_range const&) {
+    status.SetError(cmStrCat("Integer out of range: '", str, '\''));
     cmSystemTools::SetFatalErrorOccurred();
     return false;
   }

+ 1 - 1
Source/cmFunctionCommand.cxx

@@ -79,7 +79,7 @@ bool cmFunctionHelperCommand::operator()(
 
   // set the values for ARGV0 ARGV1 ...
   for (auto t = 0u; t < expandedArgs.size(); ++t) {
-    auto const value = cmStrCat(ARGV, std::to_string(t));
+    auto const value = cmStrCat(ARGV, t);
     makefile.AddDefinition(value, expandedArgs[t]);
     makefile.MarkVariableAsUsed(value);
   }

+ 1 - 1
Source/cmGeneratorExpressionNode.cxx

@@ -676,7 +676,7 @@ bool CheckGenExParameters(cmGeneratorExpressionContext* ctx,
         nbParameters = "four parameters";
         break;
       default:
-        nbParameters = cmStrCat(std::to_string(required), " parameters");
+        nbParameters = cmStrCat(required, " parameters");
     }
     reportError(ctx, cnt->GetOriginalExpression(),
                 cmStrCat("$<", genex, ':', option, "> expression requires ",

+ 1 - 1
Source/cmGlobalGenerator.cxx

@@ -3776,7 +3776,7 @@ std::string const& cmGlobalGenerator::GetRealPath(std::string const& dir)
 
 std::string cmGlobalGenerator::NewDeferId()
 {
-  return cmStrCat("__"_s, std::to_string(this->NextDeferId++));
+  return cmStrCat("__", this->NextDeferId++);
 }
 
 void cmGlobalGenerator::ProcessEvaluationFiles()

+ 2 - 8
Source/cmGlobalUnixMakefileGenerator3.cxx

@@ -556,7 +556,7 @@ cmGlobalUnixMakefileGenerator3::GenerateBuildCommand(
     if (jobs == cmake::DEFAULT_BUILD_PARALLEL_LEVEL) {
       makeCommand.Add("-j");
     } else {
-      makeCommand.Add("-j" + std::to_string(jobs));
+      makeCommand.Add(cmStrCat("-j", jobs));
     }
   }
 
@@ -690,13 +690,7 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2(
       cmLocalUnixMakefileGenerator3::EchoProgress progress;
       progress.Dir = cmStrCat(lg.GetBinaryDirectory(), "/CMakeFiles");
       {
-        std::ostringstream progressArg;
-        char const* sep = "";
-        for (unsigned long progFile : this->ProgressMap[gtarget.get()].Marks) {
-          progressArg << sep << progFile;
-          sep = ",";
-        }
-        progress.Arg = progressArg.str();
+        progress.Arg = cmJoin(this->ProgressMap[gtarget.get()].Marks, ",");
       }
 
       bool targetMessages = true;

+ 6 - 6
Source/cmGlobalVisualStudio10Generator.cxx

@@ -1025,11 +1025,11 @@ bool cmGlobalVisualStudio10Generator::FindVCTargetsPath(cmMakefile* mf)
       "Failed to run MSBuild command:\n"
       "  " << cmd[0] << "\n"
       "to get the value of VCTargetsPath:\n"
-      "  " << out << "\n"
+      "  " << out << '\n'
       ;
     /* clang-format on */
     if (ret != 0) {
-      e << "Exit code: " << ret << "\n";
+      e << "Exit code: " << ret << '\n';
     }
     mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
     cmSystemTools::SetFatalErrorOccurred();
@@ -1040,7 +1040,7 @@ bool cmGlobalVisualStudio10Generator::FindVCTargetsPath(cmMakefile* mf)
 
   {
     cmsys::ofstream fout(txt.c_str());
-    fout << this->VCTargetsPath << "\n";
+    fout << this->VCTargetsPath << '\n';
   }
   return true;
 }
@@ -1218,13 +1218,13 @@ cmGlobalVisualStudio10Generator::GenerateBuildCommand(
       if (jobs == cmake::DEFAULT_BUILD_PARALLEL_LEVEL) {
         makeCommand.Add("/m");
       } else {
-        makeCommand.Add(cmStrCat("/m:", std::to_string(jobs)));
+        makeCommand.Add(cmStrCat("/m:", jobs));
       }
     }
 
     // Respect the verbosity: 'n' normal will show build commands
     //                        'm' minimal only the build step's title
-    makeCommand.Add(cmStrCat("/v:", ((verbose) ? "n" : "m")));
+    makeCommand.Add(cmStrCat("/v:", ((verbose) ? 'n' : 'm')));
     makeCommand.Add(makeOptions.begin(), makeOptions.end());
     makeCommands.emplace_back(std::move(makeCommand));
   }
@@ -1462,7 +1462,7 @@ cmIDEFlagTable const* cmGlobalVisualStudio10Generator::LoadFlagTable(
     } else {
       mf->IssueMessage(MessageType::FATAL_ERROR,
                        cmStrCat("JSON flag table for ", table,
-                                " not found for toolset ", genericName, " ",
+                                " not found for toolset ", genericName, ' ',
                                 defaultName));
       return nullptr;
     }

+ 1 - 1
Source/cmList.cxx

@@ -626,7 +626,7 @@ ActionDescriptorSet::iterator TransformConfigure(
   auto descriptor = Descriptors.find(action);
   if (descriptor == Descriptors.end()) {
     throw transform_error(cmStrCat(" sub-command TRANSFORM, ",
-                                   std::to_string(static_cast<int>(action)),
+                                   static_cast<int>(action),
                                    " invalid action."));
   }
 

+ 2 - 5
Source/cmMacroCommand.cxx

@@ -2,7 +2,6 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMacroCommand.h"
 
-#include <cstdio>
 #include <utility>
 
 #include <cm/memory>
@@ -73,14 +72,12 @@ bool cmMacroHelperCommand::operator()(
   std::vector<std::string> variables;
   variables.reserve(this->Args.size() - 1);
   for (unsigned int j = 1; j < this->Args.size(); ++j) {
-    variables.push_back("${" + this->Args[j] + "}");
+    variables.emplace_back(cmStrCat("${", this->Args[j], '}'));
   }
   std::vector<std::string> argVs;
   argVs.reserve(expandedArgs.size());
-  char argvName[60];
   for (unsigned int j = 0; j < expandedArgs.size(); ++j) {
-    snprintf(argvName, sizeof(argvName), "${ARGV%u}", j);
-    argVs.emplace_back(argvName);
+    argVs.emplace_back(cmStrCat("${ARGV", j, '}'));
   }
   // Invoke all the functions that were collected in the block.
   // for each function

+ 2 - 4
Source/cmMakefile.cxx

@@ -437,8 +437,7 @@ public:
             }
             argsValue["functionArgs"] = args;
           }
-          argsValue["location"] =
-            cmStrCat(lfc.FilePath, ':', std::to_string(lfc.Line));
+          argsValue["location"] = cmStrCat(lfc.FilePath, ':', lfc.Line);
           return argsValue;
         });
 #endif
@@ -2722,8 +2721,7 @@ MessageType cmMakefile::ExpandVariablesInStringImpl(
         if (!openstack.empty() &&
             !(isalnum(inc) || inc == '_' || inc == '/' || inc == '.' ||
               inc == '+' || inc == '-')) {
-          errorstr += "Invalid character ('";
-          errorstr += inc;
+          errorstr += cmStrCat("Invalid character ('", inc);
           result.append(last, in - last);
           errorstr += cmStrCat("') in a variable name: '",
                                result.substr(openstack.back().loc), '\'');

+ 7 - 11
Source/cmMakefileTargetGenerator.cxx

@@ -2261,23 +2261,19 @@ void cmMakefileTargetGenerator::CreateObjectLists(
     char const* sep = "";
     for (unsigned int i = 0; i < object_strings.size(); ++i) {
       // Number the response files.
-      std::string responseFileName =
-        (responseMode == Link) ? "objects" : "deviceObjects";
-      responseFileName += std::to_string(i + 1);
-      responseFileName += ".rsp";
+      std::string responseFileName = cmStrCat(
+        (responseMode == Link) ? "objects" : "deviceObjects", i + 1, ".rsp");
 
       // Create this response file.
       std::string objects_rsp = this->CreateResponseFile(
         responseFileName, object_strings[i], makefile_depends, linkLanguage);
 
-      // Separate from previous response file references.
-      buildObjs += sep;
+      buildObjs +=
+        cmStrCat(sep, // Separate from previous response file references.
+                 responseFlag, // Reference the response file.
+                 this->LocalGenerator->ConvertToOutputFormat(
+                   objects_rsp, cmOutputConverter::SHELL));
       sep = " ";
-
-      // Reference the response file.
-      buildObjs += responseFlag;
-      buildObjs += this->LocalGenerator->ConvertToOutputFormat(
-        objects_rsp, cmOutputConverter::SHELL);
     }
   } else if (useLinkScript) {
     if (!useArchiveRules) {

+ 1 - 2
Source/cmQtAutoGenInitializer.cxx

@@ -2210,8 +2210,7 @@ static std::string FindMocExecutableFromMocTarget(cmMakefile const* makefile,
                                                   unsigned int qtMajorVersion)
 {
   std::string result;
-  std::string const mocTargetName =
-    "Qt" + std::to_string(qtMajorVersion) + "::moc";
+  std::string const mocTargetName = cmStrCat("Qt", qtMajorVersion, "::moc");
   cmTarget const* mocTarget = makefile->FindTargetToUse(mocTargetName);
   if (mocTarget) {
     result = mocTarget->GetSafeProperty("IMPORTED_LOCATION");

+ 48 - 59
Source/cmTryRunCommand.cxx

@@ -272,15 +272,9 @@ void TryRunCommandImpl::RunExecutable(std::string const& runArgs,
     this->Makefile->GetSafeDefinition("CMAKE_CROSSCOMPILING_EMULATOR");
   if (!emulator.empty()) {
     cmList emulatorWithArgs{ emulator };
-    finalCommand +=
-      cmSystemTools::ConvertToRunCommandPath(emulatorWithArgs[0]);
-    finalCommand += " ";
-    for (std::string const& arg : cmMakeRange(emulatorWithArgs).advance(1)) {
-      finalCommand += "\"";
-      finalCommand += arg;
-      finalCommand += "\"";
-      finalCommand += " ";
-    }
+    finalCommand += cmStrCat(
+      cmSystemTools::ConvertToRunCommandPath(emulatorWithArgs[0]), ' ',
+      cmWrap("\"", cmMakeRange(emulatorWithArgs).advance(1), "\"", " "), ' ');
   }
   finalCommand += cmSystemTools::ConvertToRunCommandPath(this->OutputFile);
   if (!runArgs.empty()) {
@@ -292,12 +286,7 @@ void TryRunCommandImpl::RunExecutable(std::string const& runArgs,
     workDir ? workDir->c_str() : nullptr, cmSystemTools::OUTPUT_NONE,
     cmDuration::zero());
   // set the run var
-  std::string retStr;
-  if (worked) {
-    retStr = std::to_string(retVal);
-  } else {
-    retStr = "FAILED_TO_RUN";
-  }
+  std::string retStr = worked ? std::to_string(retVal) : "FAILED_TO_RUN";
   if (this->NoCache) {
     this->Makefile->AddDefinition(this->RunResultVariable, retStr);
   } else {
@@ -454,58 +443,58 @@ void TryRunCommandImpl::DoNotRunExecutable(
                  "enter \"FAILED_TO_RUN\".\n");
       if (stdOut || stdErr) {
         if (stdOut) {
-          comment += internalRunOutputStdOutName;
-          comment +=
-            "\n   contains the text the executable "
-            "would have printed on stdout.\n"
-            "   If the executable would not have been able to run, set ";
-          comment += internalRunOutputStdOutName;
-          comment += " empty.\n"
-                     "   Otherwise check if the output is evaluated by the "
-                     "calling CMake code. If so,\n"
-                     "   check what the source file would have printed when "
-                     "called with the given arguments.\n";
+          comment += cmStrCat(
+            internalRunOutputStdOutName,
+            "\n   contains the text the executable would have printed on "
+            "stdout.\n"
+            "   If the executable would not have been able to run, set ",
+            internalRunOutputStdOutName,
+            " empty.\n"
+            "   Otherwise check if the output is evaluated by the "
+            "calling CMake code. If so,\n"
+            "   check what the source file would have printed when "
+            "called with the given arguments.\n");
         }
         if (stdErr) {
-          comment += internalRunOutputStdErrName;
-          comment +=
-            "\n   contains the text the executable "
-            "would have printed on stderr.\n"
-            "   If the executable would not have been able to run, set ";
-          comment += internalRunOutputStdErrName;
-          comment += " empty.\n"
-                     "   Otherwise check if the output is evaluated by the "
-                     "calling CMake code. If so,\n"
-                     "   check what the source file would have printed when "
-                     "called with the given arguments.\n";
+          comment += cmStrCat(
+            internalRunOutputStdErrName,
+            "\n   contains the text the executable would have printed on "
+            "stderr.\n"
+            "   If the executable would not have been able to run, set ",
+            internalRunOutputStdErrName,
+            " empty.\n"
+            "   Otherwise check if the output is evaluated by the "
+            "calling CMake code. If so,\n"
+            "   check what the source file would have printed when "
+            "called with the given arguments.\n");
         }
       } else if (out) {
-        comment += internalRunOutputName;
-        comment +=
-          "\n   contains the text the executable "
-          "would have printed on stdout and stderr.\n"
-          "   If the executable would not have been able to run, set ";
-        comment += internalRunOutputName;
-        comment += " empty.\n"
-                   "   Otherwise check if the output is evaluated by the "
-                   "calling CMake code. If so,\n"
-                   "   check what the source file would have printed when "
-                   "called with the given arguments.\n";
+        comment += cmStrCat(
+          internalRunOutputName,
+          "\n   contains the text the executable would have printed on stdout "
+          "and stderr.\n"
+          "   If the executable would not have been able to run, set ",
+          internalRunOutputName,
+          " empty.\n"
+          "   Otherwise check if the output is evaluated by the "
+          "calling CMake code. If so,\n"
+          "   check what the source file would have printed when "
+          "called with the given arguments.\n");
       }
 
-      comment += "The ";
-      comment += compileResultVariable;
-      comment += " variable holds the build result for this try_run().\n\n";
+      comment +=
+        cmStrCat("The ", compileResultVariable,
+                 " variable holds the build result for this try_run().\n\n");
       if (srcFile) {
-        comment += "Source file   : ";
-        comment += *srcFile + "\n";
+        comment += cmStrCat("Source file   : ", *srcFile, '\n');
       }
-      comment += "Executable    : ";
-      comment += copyDest + "\n";
-      comment += "Run arguments : ";
-      comment += runArgs;
-      comment += "\n";
-      comment += "   Called from: " + this->Makefile->FormatListFileStack();
+      comment += cmStrCat("Executable    : ", copyDest,
+                          "\n"
+                          "Run arguments : ",
+                          runArgs,
+                          "\n"
+                          "   Called from: ",
+                          this->Makefile->FormatListFileStack());
       cmsys::SystemTools::ReplaceString(comment, "\n", "\n# ");
       file << comment << "\n\n";
 

+ 4 - 5
Source/cmVSSetupHelper.cxx

@@ -433,15 +433,12 @@ bool cmVSSetupAPIHelper::EnumerateAndChooseVSInstance()
 
   std::string envVSCommonToolsDir;
   std::string envVSCommonToolsDirEnvName =
-    cmStrCat("VS", std::to_string(this->Version), "0COMNTOOLS");
+    cmStrCat("VS", this->Version, "0COMNTOOLS");
 
-  if (cmSystemTools::GetEnv(envVSCommonToolsDirEnvName.c_str(),
-                            envVSCommonToolsDir)) {
+  if (cmSystemTools::GetEnv(envVSCommonToolsDirEnvName, envVSCommonToolsDir)) {
     cmSystemTools::ConvertToUnixSlashes(envVSCommonToolsDir);
   }
 
-  std::string const wantVersion = cmStrCat(std::to_string(this->Version), '.');
-
   bool specifiedLocationNotSpecifiedVersion = false;
 
   SmartCOMPtr<ISetupInstance> instance;
@@ -455,6 +452,8 @@ bool cmVSSetupAPIHelper::EnumerateAndChooseVSInstance()
     return false;
   }
 
+  std::string const wantVersion = cmStrCat(this->Version, '.');
+
   std::vector<VSInstanceInfo> vecVSInstances;
   for (auto const& instanceInfo : vecVSInstancesAll) {
     // We are looking for a specific major version.

+ 1 - 2
Tests/RunCMake/CTestResourceAllocation/ctresalloc.cxx

@@ -122,8 +122,7 @@ static int doWrite(int argc, char const* const* argv)
           expectedResources.insert(it.ResourceType);
         }
 
-        std::string prefix = "CTEST_RESOURCE_GROUP_";
-        prefix += std::to_string(i);
+        std::string prefix = cmStrCat("CTEST_RESOURCE_GROUP_", i);
         char const* actualResourcesCStr = cmSystemTools::GetEnv(prefix);
         if (!actualResourcesCStr) {
           std::cout << prefix << " should be defined" << std::endl;