[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

FĂ©lix-Antoine Constantin via cfe-commits cfe-commits at lists.llvm.org
Thu Jan 11 13:22:52 PST 2024


================
@@ -0,0 +1,27 @@
+// RUN: %check_clang_tidy %s readability-ConditionalToStdMinMax %t
+
+void foo() {
+  int value1,value2;
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use std::max instead of < [readability-ConditionalToStdMinMax]
+  if (value1 < value2)
+    value1 = value2; // CHECK-FIXES: value1 = std::max(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use std::min instead of < [readability-ConditionalToStdMinMax]
+  if (value1 < value2)
+    value2 = value1; // CHECK-FIXES: value2 = std::min(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use std::min instead of > [readability-ConditionalToStdMinMax]
+  if (value2 > value1)
+    value2 = value1; // CHECK-FIXES: value2 = std::min(value2, value1);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use std::max instead of > [readability-ConditionalToStdMinMax]
+  if (value2 > value1)
+    value1 = value2; // CHECK-FIXES: value1 = std::max(value2, value1);
+
+  // No suggestion needed here
+  if (value1 == value2)
+    value1 = value2;
+
+  
----------------
felix642 wrote:

What about classes ? 
We should add a test case that includes a comparison with a class member.

```
struct Foo
{
int  x;
};

void func()
{
    int bar;
    Foo foo;
    if(bar < foo.x)
        bar = foo.x;
}
```
I'm guessing that ideally we would also need to support this type of operation :
```
struct Foo
{
    int x;
    auto operator<=>(const Foo& rhs) const = default;
};

void func()
{
    Foo foo1;
    Foo foo2;
    if(foo2 < foo1)
        foo2 = foo1;
}
```

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


More information about the cfe-commits mailing list