Skip to content

[clang-tidy]: bugprone-unchecked-optional-access false-positive if inside a loop we use checked optional value (might be a regression of Dataflow Analysis) #174250

@BaLiKfromUA

Description

@BaLiKfromUA

Way to reproduce

Smallest example which me and my colleague managed to make:

#include <optional>
#include <vector>

std::vector<std::optional<int>> getOptionals();

void test() {

  for (const auto &opt : getOptionals()) {
      if (opt.has_value()) {
        int x = opt.value(); // NO ERROR
      }
  }

  std::optional<int> opt; 
  if (opt.has_value()) {
    for (int i = 0; i < 10; ++i) {
        int x = opt.value(); // NO ERROR
    }
  }  

  for (const auto &opt : getOptionals()) {
      if (opt.has_value()) {
          for (int i = 0; i < 10; ++i) {
            int x = opt.value(); // ERROR
          }
      }
  }

  // Also happens when the loop is unbounded
  for (const auto &opt : getOptionals()) {
      if (opt.has_value()) {
          for (;;) {
            int x = opt.value(); // ERROR
          }
      }
  }
}

Compiler Explorer Link

Initial problem / User Impact

After fixing #168863 I found new false-positive like:

bsl::vector<bsl::optional<bsl::string>> getOptionals();

void test_with_ball_log_and_loop() {
    BALL_LOG_SET_CATEGORY(__func__);
  
    for (const auto& opt : getOptionals()) {
        if (opt.has_value()) {
            BALL_LOG_INFO << opt.value(); // ERROR?!
        }
    }
}

BALL_LOG is BDE tooling used for logging. Link

After some experiments, I found out that I can reproduce the same issue with std::optional<int> so it was somehow connected with BALL_LOG.

Compiler Explorer Link.

Removing/expanding macros and includes resulted in example from the beginning :)


So even though the initial example might be niche, the original issue is a pretty common pattern.

JFYI, I cannot reproduce it with clang-18 and clang-19 releases but I can reproduce it with clang-20 and clang-21. So maybe it's a regression??

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang-tidyclang:dataflowClang Dataflow Analysis framework - https://clang.llvm.org/docs/DataFlowAnalysisIntro.htmlfalse-positiveWarning fires when it should not

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions