llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

bugprone-unchecked-optional-access false-positive with absl::nullopt comparison

Open gburgessiv opened this issue 4 years ago • 5 comments

On clang-tidy at bdb859c9a75f0e574ac877c4ca277edcc6db4e46, I believe bugprone-unchecked-optional-access has a false-positive.

$ $clang_tidy '-checks=-*,bugprone-unchecked-optional-access' file_name.cpp -- clang++ -x c++ -std=c++17 file_name.cpp
file_name.cpp:19:52: warning: unchecked access to optional value [bugprone-unchecked-optional-access]
  return (optional_value != absl::nullopt) ? *optional_value : 0;

Creduce'd repro:

namespace absl {
namespace a {
enum au { av };
template <au> class aw {};
template <au> class ax {};
template <typename> struct ay { static constexpr au az = av; };
template <typename> struct b { static constexpr au az = av; };
} // namespace a
struct nullopt_t {
} nullopt;
template <typename am>
class optional : a::aw<a::ay<am>::az>, a::ax<a::b<am>::az> {
public:
  am operator*();
};
template <typename am> bool operator!=(am, nullopt_t);
} // namespace absl
int c(absl::optional<int> optional_value) {
  return (optional_value != absl::nullopt) ? *optional_value : 0;
}

Note that if the condition is changed to return optional_value ? *optional_value : 0; (and explicit operator bool() const; is added to the optional class above), the diagnostic is not issued.

cc @ymand

gburgessiv avatar Aug 19 '22 19:08 gburgessiv

@llvm/issue-subscribers-bug

llvmbot avatar Aug 19 '22 19:08 llvmbot

@llvm/issue-subscribers-clang-tidy

llvmbot avatar Aug 19 '22 19:08 llvmbot

Comparisons to std::nullopt are also not being taken into account.

https://godbolt.org/z/xKdqhTsaM

#include <optional>

void sinc(int);

void fun(std::optional<int> opt) {
    if (opt != std::nullopt) {
        sinc(*opt); // <source>:7:15: warning: unchecked access to optional value [bugprone-unchecked-optional-access]
    }
}

tiagomacarios avatar Sep 21 '22 14:09 tiagomacarios

Patch to add support for operator== and operator!=: https://reviews.llvm.org/D139360

ymand avatar Dec 05 '22 20:12 ymand

Fixed in commit 390029be8946cac807e8fc978b9cf3790e7456cc.

ymand avatar Mar 03 '23 17:03 ymand