[clang-tools-extra] [clang-tidy] Add fix-its to `avoid-return-with-void-value` check (PR #81420)

Piotr Zegar via cfe-commits cfe-commits at lists.llvm.org
Tue Feb 20 08:14:21 PST 2024


================
@@ -40,12 +42,35 @@ void AvoidReturnWithVoidValueCheck::registerMatchers(MatchFinder *Finder) {
 void AvoidReturnWithVoidValueCheck::check(
     const MatchFinder::MatchResult &Result) {
   const auto *VoidReturn = Result.Nodes.getNodeAs<ReturnStmt>("void_return");
-  if (IgnoreMacros && VoidReturn->getBeginLoc().isMacroID())
+  if (IgnoreMacros && VoidReturn->getBeginLoc().isMacroID()) {
     return;
-  if (!StrictMode && !Result.Nodes.getNodeAs<CompoundStmt>("compound_parent"))
+  }
+  const auto *SurroundingBlock =
+      Result.Nodes.getNodeAs<CompoundStmt>("compound_parent");
+  if (!StrictMode && !SurroundingBlock) {
     return;
-  diag(VoidReturn->getBeginLoc(), "return statement within a void function "
-                                  "should not have a specified return value");
+  }
+  DiagnosticBuilder Diag = diag(VoidReturn->getBeginLoc(),
+                                "return statement within a void function "
+                                "should not have a specified return value");
+  std::optional<Token> SemicolonPos =
+      Lexer::findNextToken(VoidReturn->getRetValue()->getEndLoc(),
+                           *Result.SourceManager, getLangOpts());
+  if (!SemicolonPos) {
+    return;
+  }
+  const StringRef ReturnExpr =
+      Lexer::getSourceText(CharSourceRange::getTokenRange(
+                               VoidReturn->getRetValue()->getSourceRange()),
+                           *Result.SourceManager, getLangOpts());
+  std::string Replacement = (ReturnExpr + "; return;").str();
+  if (!SurroundingBlock) {
+    Replacement = "{" + Replacement + "}";
+  }
+  Diag << FixItHint::CreateReplacement(
----------------
PiotrZSL wrote:

instead of replacing just use [CreateRemoval](https://clang.llvm.org/doxygen/classclang_1_1FixItHint.html#a9e11ae1e22983fd4abea805755ecddbe) to remove begin, and [CreateInsertion](https://clang.llvm.org/doxygen/classclang_1_1FixItHint.html#afd481d826e9ddaa39fc82a698a810246) to insert `return;` and `{}` if needed.

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


More information about the cfe-commits mailing list