[clang-tidy] Improvement for bugprone-unchecked-optional-access
- Dominant language
- LLVM
- Stars
- 40.5k
- Forks
- 18.7k
- PR merge metrics
- PR metrics pending
Description
Consider following snippet
```c++
std::optional> aTestData = foo();
CPPUNIT_ASSERT( aTestData.has_value() );
CPPUNIT_ASSERT( aTestData->empty() );
```
Currently bugprone-unchecked-optional-access warns for `aTestData->empty()`, even if the code is executed only if `aTestData.has_value()`; thus there is no unchecked access.
`CPPUNIT_ASSERT` comes from the test suite CppUnit, but the same holds for other test suites; for example catch2:
```c++
std::optional> aTestData = foo();
REQUIRE( aTestData.has_value() );
REQUIRE( aTestData->empty() );
```
This makes it currently very hard to use optional in a test suite with bugprone-unchecked-optional-access enabled.
Since support for gtest is there in clang (see https://github.com/llvm/llvm-project/pull/186363), it would be nice for clang-tidy to support both cppunit and catch out-of-the-box, and eventually add support for defining own macros.
Another issue is given by following pattern
```c++
// avoid creating potentially expensive empty container to query if empty/size
template
bool optionalEmpty( const OC& v ){ return v ? v->empty() : true; }
template
std::size_t optionalSize( const OC& v ) { return v ? v->size() : 0u; }
std::optional data = bar();
if ( not optionalEmpty( data ) ) {
data->at(0);
}
if ( optionalSize( data ) == 5 ) {
data->at(2);
}
```
If `optionalEmpty( data )` returns `false`, then `std::optional` is engaged.
If `optionalSize( data )` returns `5`, then `std::optional` is engaged.
But in both cases, clang-tidy does not recognize it.
On godbolt: https://godbolt.org/z/TEfY4TTaG
Related: https://github.com/catchorg/Catch2/issues/3170
Contributor guide
Assessment
This issue has not been assessed yet.