[clang-tidy] Fix bugprone-terminating-continue when continue appears inside a switch
authorNathan James <n.james93@hotmail.co.uk>
Sat, 20 Mar 2021 10:59:36 +0000 (10:59 +0000)
committerNathan James <n.james93@hotmail.co.uk>
Sat, 20 Mar 2021 10:59:37 +0000 (10:59 +0000)
Don't emit a warning if the `continue` appears in a switch context as changing it to `break` will break out of the switch rather than a do loop containing the switch.
Fixes https://llvm.org/PR49492.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D98338

clang-tools-extra/clang-tidy/bugprone/TerminatingContinueCheck.cpp
clang-tools-extra/test/clang-tidy/checkers/bugprone-terminating-continue.cpp

index 43402a2..65da4c3 100644 (file)
@@ -26,10 +26,11 @@ void TerminatingContinueCheck::registerMatchers(MatchFinder *Finder) {
              equalsBoundNode("closestLoop"));
 
   Finder->addMatcher(
-      continueStmt(hasAncestor(stmt(anyOf(forStmt(), whileStmt(),
-                                          cxxForRangeStmt(), doStmt()))
-                                   .bind("closestLoop")),
-                   hasAncestor(DoWithFalse))
+      continueStmt(
+          hasAncestor(stmt(anyOf(forStmt(), whileStmt(), cxxForRangeStmt(),
+                                 doStmt(), switchStmt()))
+                          .bind("closestLoop")),
+          hasAncestor(DoWithFalse))
           .bind("continue"),
       this);
 }
index 4bdcbc4..04fc4a8 100644 (file)
@@ -32,6 +32,15 @@ void f() {
     // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: 'continue' in loop with false condition is equivalent to 'break' [bugprone-terminating-continue]
     // CHECK-FIXES: if (x > 0) break;
   } while (false);
+
+  switch (2) {
+  case 2:
+    do {
+      continue; // LoopInSwitch
+      // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'continue' in loop with false condition is equivalent to 'break' [bugprone-terminating-continue]
+      // CHECK-FIXES: break; // LoopInSwitch
+    } while (0);
+  }
 }
 
 void g() {
@@ -62,4 +71,12 @@ void g() {
       if (n>2) continue;
     }
   } while (false);
+
+  do {
+    switch (2) {
+    case 1:
+    case 2:
+      continue;
+    }
+  } while (false);
 }