llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.35k stars 11.7k forks source link

New false positive in clang-tidy 18 bugprone-unchecked-optional access #93194

Open woutervdstoel opened 4 months ago

woutervdstoel commented 4 months ago

I'm trying to upgrade to clang-tidy-18 and found a regression with the changed bugprone-unchecked-optional-access check.

I managed to distill the following minimal reproducer:

#include <iostream>
#include <optional>

std::optional<int> get_optional()
{
  return 5;
}

int main()
{
  for (int j = 0; j < 1; j++)
  {
  }
  auto i = get_optional();
  // perform the check
  if (!i.has_value())
  {
    return 0;
  }
  for (int j = 0; j < 1; ++j)
  {
    // test.cpp:24:19: error: unchecked access to optional value [bugprone-unchecked-optional-access,-warnings-as-errors]
    // 24 |     std::cout << *i << std::endl;
    std::cout << *i << std::endl;
  }
  return 0;
}

The reuse of the loop indexing variable name seems to be the root cause.

woutervdstoel commented 4 months ago

This issue seems to be fixed in current main (used clang-tidy from godbolt).