<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/126283>126283</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
[clang-tidy] `bugprone-unchecked-optional-access` false positive when analyzing optional field of object accessed via chain of getters
</td>
</tr>
<tr>
<th>Labels</th>
<td>
clang-tidy,
false-positive
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
BaLiKfromUA
</td>
</tr>
</table>
<pre>
### Problem
The next code snippet:
```cpp
#include <optional>
#include <string>
#include <iostream>
class A {
private:
std::optional<std::string> d_field;
public:
const std::optional<std::string>& field() const {
return d_field;
}
};
class B {
private:
A d_a;
public:
const A& a() const {
return d_a;
}
};
void foo(const B& data) {
if (data.a().field().has_value()) {
std::cout << data.a().field().value();
}
}
```
produces a false positive warning from clang-tidy:
```
clang-tidy (trunk) x86-64 clang 18.1.0 (Editor #1, Compiler #1)
-checks=bugprone-unchecked-optional-access
[<source>:27:22: warning: unchecked access to optional value [bugprone-unchecked-optional-access]](javascript:;)
27 | std::cout << data.a().field().value();
| ^
1 warning generated.
```
The next workaround could solve this issue:
```cpp
void bar(const B& data) {
const std::optional<std::string>& field = data.a().field();
if (field.has_value()) {
std::cout << field.value();
}
}
```
But it is easy to forget it, especially if such pattern is frequent in the codebase.
[Compiler explorer link](https://godbolt.org/z/P1bafhraa)
### Similar issues
I've checked existing open issues and one is similar-ish to mine -- https://github.com/llvm/llvm-project/issues/93194
Seems like it is fixed now and I cannot reproduce it on my side. I assume that the bug is connected to the _"chaining"_ of calls.
[Compiler explorer link](https://godbolt.org/z/hKoG9bM8a)
------
**I am happy to contribute the fix to this issue if someone could give me initial suggestions about a proper solution and possible places to look** :)
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJysVlFv2zgM_jXKC5HAkWs7echD0iyHYnfAgN09F7RE21plySfJWbtff5DlpN3a4oZhgtDGokV-JD-SRu9Va4h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