[clang-tools-extra] [clang-tidy] Fix handling --driver-mode= (PR #66553)

Julian Schmidt via cfe-commits cfe-commits at lists.llvm.org
Wed Mar 6 14:50:32 PST 2024


================
@@ -550,9 +555,91 @@ static llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> createBaseFS() {
   return BaseFS;
 }
 
+static void recreateOptionsParserIfNeeded(
+    llvm::Expected<CommonOptionsParser> &OptionsParser,
+    llvm::ArrayRef<const char *> Args,
+    const ClangTidyOptions &EffectiveOptions) {
+
+  auto DoubleDashIt = std::find(Args.begin(), Args.end(), StringRef("--"));
+
+  // Exit if we don't have any compiler arguments
+  if (DoubleDashIt == Args.end() || Args.empty() ||
+      Args.back() == StringRef("--"))
+    return;
+
+  auto IsDriverMode = [](StringRef Argument) {
+    return Argument.startswith("--driver-mode=");
+  };
+
+  // Exit if --driver-mode= is explicitly passed in compiler arguments
+  if (Args.end() !=
+      std::find_if(std::next(DoubleDashIt), Args.end(), IsDriverMode))
+    return;
+
+  std::vector<std::string> CommandArguments(std::next(DoubleDashIt),
+                                            Args.end());
+
+  // Add clang-tool as program name if not added
+  if (CommandArguments.empty() ||
+      llvm::StringRef(CommandArguments.front()).startswith("-"))
+    CommandArguments.insert(CommandArguments.begin(), "clang-tool");
+
+  // Apply --extra-arg and --extra-arg-before to compiler arguments
+  CommandArguments =
+      OptionsParser->getArgumentsAdjuster()(CommandArguments, "");
+
+  // Apply ExtraArgsBefore from clang-tidy config to compiler arguments
+  if (EffectiveOptions.ExtraArgsBefore)
+    CommandArguments = tooling::getInsertArgumentAdjuster(
+        *EffectiveOptions.ExtraArgsBefore,
+        tooling::ArgumentInsertPosition::BEGIN)(CommandArguments, "");
+
+  // Apply ExtraArgs from clang-tidy config to compiler arguments
+  if (EffectiveOptions.ExtraArgs)
+    CommandArguments = tooling::getInsertArgumentAdjuster(
+        *EffectiveOptions.ExtraArgs,
+        tooling::ArgumentInsertPosition::END)(CommandArguments, "");
+
+  // Check if now we have --driver-mode=
+  auto DriverModeIt = std::find_if(CommandArguments.begin(),
+                                   CommandArguments.end(), IsDriverMode);
+  if (DriverModeIt == CommandArguments.end()) {
+    // Try to detect and add --driver-mode=
+    std::string ExeName = CommandArguments.front();
+    tooling::addTargetAndModeForProgramName(CommandArguments, ExeName);
+    DriverModeIt = std::find_if(CommandArguments.begin(),
+                                CommandArguments.end(), IsDriverMode);
+  }
+
+  // Exit if there is no --driver-mode= at this stage
+  if (DriverModeIt == CommandArguments.end())
+    return;
+
+  std::vector<const char *> NewArgs(Args.begin(), Args.end());
----------------
5chmidti wrote:

You can use `= Args.vec()` here

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


More information about the cfe-commits mailing list