[clang] [FlowSensitive][Expected] Model constructors, assignments and `emplace` in `UncheckedExpectedAccessModel` [PR 3/N] (PR #246771)
via cfe-commits
cfe-commits at lists.llvm.org
Sun Nov 29 14:50:45 PST 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang
Author: Valentyn Yukhymenko (BaLiKfromUA)
<details>
<summary>Changes</summary>
This is the third part of a split of #<!-- -->233219 (`bugprone-unchecked-expected-access`). It adds modeling of the calls that set
whether an expected holds a value:
- **`emplace`**: every overload leaves the expected holding a value.
- **Constructors**:
- `expected(unexpect_t, ...)`, `expected(const unexpected<G> &)` and `expected(unexpected<G> &&)`
construct an expected that holds an error.
- The converting constructors from `expected<U, G>` copy whether the source holds a value.
- All other constructors (default, from a value, `in_place_t`) construct an expected that holds a value.
- Copy and move constructors are left to the Dataflow framework, which copies the "has_value" property of the source.
- **Assignments**:
- `operator=(const unexpected<G> &)` and `operator=(unexpected<G> &&)` leave the expected holding an error.
- Other non-copy, non-move assignments (from a value) leave it holding a value.
- Copy and move assignments, and converting assignments from another `expected` that go through them, are
left to the framework.
### Examples of diagnostics:
```cpp
void f(std::expected<int, int> a, std::expected<long, int> b, bool cond) {
std::expected<int, int> e;
*e; // ok: default-constructed with a value
e = std::unexpected(1);
*e; // diagnosed: unchecked value access
e.error(); // ok
if (b) {
std::expected<int, int> c(b);
*c; // ok: `c` holds a value because `b` does
}
if (cond)
a.emplace(1);
*a; // diagnosed: `a` holds a value on only one path
}
```
### AI usage
I used AI to split my big end-to-end PR (https://github.com/llvm/llvm-project/pull/233219) as well as port clang-tidy style tests to clang model unit tests.
As noted in the PR above, the constructor and assignment support, both the implementation and the tests, was written with heavy AI assistance.
Assisted-by: Claude Opus 5.5
---
Patch is 33.80 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/246771.diff
3 Files Affected:
- (modified) clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp (+142-1)
- (modified) clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp (+89-9)
- (modified) clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp (+791)
``````````diff
diff --git a/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp
index f0d5f3764f028a..75ce8a344310e2 100644
--- a/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp
@@ -120,6 +120,65 @@ auto expectedUnexpectedEqualityCall() {
return expectedComparisonCall(hasUnexpectedType());
}
+// Copy and move constructors are handled by the framework.
+auto expectedConstructor() {
+ return cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
+ ofClass(expectedClass()),
+ unless(anyOf(isCopyConstructor(), isMoveConstructor())))));
+}
+
+// `expected(unexpect_t, ...)`, `expected(const unexpected<G> &)` and
+// `expected(unexpected<G> &&)`.
+auto expectedErrorConstructor() {
+ return cxxConstructExpr(
+ expectedConstructor(),
+ hasArgument(0, anyOf(hasType(namedDecl(hasAnyName("std::unexpect_t",
+ "tl::unexpect_t"))),
+ hasUnexpectedType())));
+}
+
+// `expected(const expected<U, G> &)` and `expected(expected<U, G> &&)`,
+// matched by declaration since `expected(U &&)` may also take an `expected`.
+AST_MATCHER(CXXConstructorDecl, expectedConvertingConstructorDecl) {
+ const FunctionTemplateDecl *Template = Node.getPrimaryTemplate();
+ if (Template == nullptr)
+ return false;
+ const FunctionDecl *Pattern = Template->getTemplatedDecl();
+ if (Pattern->getNumParams() != 1)
+ return false;
+ const auto *ParamType = Pattern->getParamDecl(0)
+ ->getType()
+ .getNonReferenceType()
+ ->getAs<TemplateSpecializationType>();
+ if (ParamType == nullptr)
+ return false;
+ const auto *ParamTemplate = dyn_cast_or_null<ClassTemplateDecl>(
+ ParamType->getTemplateName().getAsTemplateDecl());
+ return ParamTemplate != nullptr &&
+ isExpectedClass(*ParamTemplate->getTemplatedDecl());
+}
+
+auto expectedConvertingConstructor() {
+ return cxxConstructExpr(
+ expectedConstructor(),
+ hasDeclaration(cxxConstructorDecl(expectedConvertingConstructorDecl())));
+}
+
+// Copy and move assignments are handled by the framework.
+auto expectedAssignment() {
+ return cxxOperatorCallExpr(
+ hasOverloadedOperatorName("="), argumentCountIs(2),
+ callee(cxxMethodDecl(ofClass(expectedClass()),
+ unless(anyOf(isCopyAssignmentOperator(),
+ isMoveAssignmentOperator())))));
+}
+
+// `operator=(const unexpected<G> &)` and `operator=(unexpected<G> &&)`.
+auto expectedErrorAssignment() {
+ return cxxOperatorCallExpr(expectedAssignment(),
+ hasArgument(1, hasUnexpectedType()));
+}
+
/// Ensures that `E` is mapped to a `BoolValue` and returns its formula.
const Formula &forceBoolValue(Environment &Env, const Expr &E) {
auto *Value = Env.get<BoolValue>(E);
@@ -170,6 +229,15 @@ BoolValue *getHasValue(Environment &Env, RecordStorageLocation *ExpectedLoc) {
return HasValueVal;
}
+/// Sets `HasValueVal` as the symbolic value that represents the "has_value"
+/// property of the expected at `ExpectedLoc`.
+void setHasValue(RecordStorageLocation *ExpectedLoc, BoolValue &HasValueVal,
+ Environment &Env) {
+ if (ExpectedLoc == nullptr || !isExpectedType(ExpectedLoc->getType()))
+ return;
+ Env.setValue(locForHasValue(*ExpectedLoc), HasValueVal);
+}
+
void transferHasValueCall(const CXXMemberCallExpr *E,
const MatchFinder::MatchResult &,
LatticeTransferState &State) {
@@ -178,6 +246,13 @@ void transferHasValueCall(const CXXMemberCallExpr *E,
State.Env.setValue(*E, *HasValueVal);
}
+void transferEmplaceCall(const CXXMemberCallExpr *E,
+ const MatchFinder::MatchResult &,
+ LatticeTransferState &State) {
+ setHasValue(getImplicitObjectLocation(*E, State.Env),
+ State.Env.getBoolLiteralValue(true), State.Env);
+}
+
void transferExpectedEqualityCall(const CXXOperatorCallExpr *E,
const MatchFinder::MatchResult &,
LatticeTransferState &State) {
@@ -233,13 +308,64 @@ void transferExpectedUnexpectedEqualityCall(const CXXOperatorCallExpr *E,
A.makeNot(HasValueVal->formula())));
}
-// FIXME: Model the constructors, assignments, `emplace` and `swap`.
+void constructExpected(const CXXConstructExpr &E, BoolValue &HasValueVal,
+ Environment &Env) {
+ setHasValue(&Env.getResultObjectLocation(E), HasValueVal, Env);
+}
+
+void transferValueConstructor(const CXXConstructExpr *E,
+ const MatchFinder::MatchResult &,
+ LatticeTransferState &State) {
+ constructExpected(*E, State.Env.getBoolLiteralValue(true), State.Env);
+}
+
+void transferErrorConstructor(const CXXConstructExpr *E,
+ const MatchFinder::MatchResult &,
+ LatticeTransferState &State) {
+ constructExpected(*E, State.Env.getBoolLiteralValue(false), State.Env);
+}
+
+void transferConvertingConstructor(const CXXConstructExpr *E,
+ const MatchFinder::MatchResult &,
+ LatticeTransferState &State) {
+ // The new expected holds a value if and only if the source does.
+ if (BoolValue *HasValueVal = getHasValue(
+ State.Env, State.Env.get<RecordStorageLocation>(*E->getArg(0))))
+ constructExpected(*E, *HasValueVal, State.Env);
+}
+
+void assignExpected(const CXXOperatorCallExpr &E, BoolValue &HasValueVal,
+ Environment &Env) {
+ auto *Loc = Env.get<RecordStorageLocation>(*E.getArg(0));
+ if (Loc == nullptr)
+ return;
+ setHasValue(Loc, HasValueVal, Env);
+ // Assign a storage location for the whole expression.
+ Env.setStorageLocation(E, *Loc);
+}
+
+void transferValueAssignment(const CXXOperatorCallExpr *E,
+ const MatchFinder::MatchResult &,
+ LatticeTransferState &State) {
+ assignExpected(*E, State.Env.getBoolLiteralValue(true), State.Env);
+}
+
+void transferErrorAssignment(const CXXOperatorCallExpr *E,
+ const MatchFinder::MatchResult &,
+ LatticeTransferState &State) {
+ assignExpected(*E, State.Env.getBoolLiteralValue(false), State.Env);
+}
+
+// FIXME: Model `swap`.
auto buildTransferMatchSwitch() {
return CFGMatchSwitchBuilder<LatticeTransferState>()
// expected::has_value, expected::operator bool
.CaseOfCFGStmt<CXXMemberCallExpr>(
expectedMemberCall(hasAnyName("has_value", "operator bool")),
transferHasValueCall)
+ // expected::emplace
+ .CaseOfCFGStmt<CXXMemberCallExpr>(expectedMemberCall(hasName("emplace")),
+ transferEmplaceCall)
// operator==, operator!= between two expecteds
.CaseOfCFGStmt<CXXOperatorCallExpr>(expectedEqualityCall(),
transferExpectedEqualityCall)
@@ -250,6 +376,21 @@ auto buildTransferMatchSwitch() {
.CaseOfCFGStmt<CXXOperatorCallExpr>(
expectedUnexpectedEqualityCall(),
transferExpectedUnexpectedEqualityCall)
+ // expected::expected (unexpect_t, unexpected)
+ .CaseOfCFGStmt<CXXConstructExpr>(expectedErrorConstructor(),
+ transferErrorConstructor)
+ // expected::expected (converting)
+ .CaseOfCFGStmt<CXXConstructExpr>(expectedConvertingConstructor(),
+ transferConvertingConstructor)
+ // expected::expected (value, default, in place)
+ .CaseOfCFGStmt<CXXConstructExpr>(expectedConstructor(),
+ transferValueConstructor)
+ // expected::operator= (unexpected)
+ .CaseOfCFGStmt<CXXOperatorCallExpr>(expectedErrorAssignment(),
+ transferErrorAssignment)
+ // expected::operator= (value)
+ .CaseOfCFGStmt<CXXOperatorCallExpr>(expectedAssignment(),
+ transferValueAssignment)
.Build();
}
diff --git a/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp b/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp
index 9e157efa964f91..f0f76918e4f777 100644
--- a/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp
@@ -824,6 +824,12 @@ static constexpr char StdExpectedHeader[] = R"(
#ifndef STD_EXPECTED_H
#define STD_EXPECTED_H
+// For `std::in_place_t` and `std::in_place`.
+#include "std_type_traits.h"
+
+// Uses C++20 features, but is also included by the `tl` tests in C++17 mode.
+#if __cplusplus >= 202002L
+
namespace std {
template <class E> class unexpected {
@@ -853,6 +859,33 @@ template <class> constexpr bool __is_expected = false;
template <class T, class E>
constexpr bool __is_expected<expected<T, E>> = true;
+template <class> constexpr bool __is_unexpected = false;
+template <class E> constexpr bool __is_unexpected<unexpected<E>> = true;
+
+// `__remove_cvref` is a clang builtin, so the helper has a different name.
+// clang-format off
+template <class T> struct __remove_cvref_impl { using type = T; };
+template <class T> struct __remove_cvref_impl<const T> { using type = T; };
+template <class T> struct __remove_cvref_impl<T &> { using type = T; };
+template <class T> struct __remove_cvref_impl<const T &> { using type = T; };
+template <class T> struct __remove_cvref_impl<T &&> { using type = T; };
+template <class T> struct __remove_cvref_impl<const T &&> { using type = T; };
+// clang-format on
+
+template <class T>
+using __remove_cvref_t = typename __remove_cvref_impl<T>::type;
+
+// Whether `T` can be constructed from `expected<U, G>`, in which case the
+// converting constructors from `expected<U, G>` are disabled. As in the
+// standard, `bool` is an exception.
+template <class T, class U, class G>
+constexpr bool __cons_from_expected =
+ !__is_same(__remove_cvref_t<T>, bool) &&
+ (__is_constructible(T, expected<U, G> &) ||
+ __is_constructible(T, expected<U, G>) ||
+ __is_constructible(T, const expected<U, G> &) ||
+ __is_constructible(T, const expected<U, G>));
+
template <class T, class E> class expected {
public:
using value_type = T;
@@ -863,17 +896,46 @@ template <class T, class E> class expected {
expected(const expected &);
expected(expected &&) noexcept;
- template <class U = T> expected(U &&v);
+ template <class U, class G>
+ requires(__is_constructible(T, const U &) &&
+ __is_constructible(E, const G &) &&
+ !__cons_from_expected<T, U, G>)
+ expected(const expected<U, G> &x);
+ template <class U, class G>
+ requires(__is_constructible(T, U) && __is_constructible(E, G) &&
+ !__cons_from_expected<T, U, G>)
+ expected(expected<U, G> &&x);
+
+ template <class U = T>
+ requires(!__is_same(__remove_cvref_t<U>, expected) &&
+ !__is_same(__remove_cvref_t<U>, in_place_t) &&
+ !__is_same(__remove_cvref_t<U>, unexpect_t) &&
+ !__is_unexpected<__remove_cvref_t<U>> &&
+ __is_constructible(T, U) &&
+ (!__is_same(__remove_cvref_t<T>, bool) ||
+ !__is_expected<__remove_cvref_t<U>>))
+ expected(U &&v);
template <class G> expected(const unexpected<G> &e);
template <class G> expected(unexpected<G> &&e);
+ template <class... Args> explicit expected(in_place_t, Args &&...args);
+
template <class... Args>
explicit expected(unexpect_t, Args &&...args);
expected &operator=(const expected &);
expected &operator=(expected &&) noexcept;
+ template <class U = T>
+ requires(!__is_same(__remove_cvref_t<U>, expected) &&
+ !__is_unexpected<__remove_cvref_t<U>> &&
+ __is_constructible(T, U) && __is_assignable(T &, U))
+ expected &operator=(U &&v);
+
+ template <class G> expected &operator=(const unexpected<G> &e);
+ template <class G> expected &operator=(unexpected<G> &&e);
+
const T *operator->() const noexcept;
T *operator->() noexcept;
@@ -907,7 +969,6 @@ template <class T, class E> class expected {
// The comparisons rely on C++20 rewritten candidates for `!=` and for
// reversed operands.
-#if __cplusplus >= 202002L
template <class T2, class E2>
friend bool operator==(const expected &x, const expected<T2, E2> &y);
@@ -917,7 +978,6 @@ template <class T, class E> class expected {
template <class E2>
friend bool operator==(const expected &x, const unexpected<E2> &e);
-#endif
};
template <class E> class expected<void, E> {
@@ -930,15 +990,23 @@ template <class E> class expected<void, E> {
expected(const expected &);
expected(expected &&) noexcept;
+ template <class U, class G> expected(const expected<U, G> &x);
+ template <class U, class G> expected(expected<U, G> &&x);
+
template <class G> expected(const unexpected<G> &e);
template <class G> expected(unexpected<G> &&e);
+ explicit expected(in_place_t) noexcept;
+
template <class... Args>
explicit expected(unexpect_t, Args &&...args);
expected &operator=(const expected &);
expected &operator=(expected &&) noexcept;
+ template <class G> expected &operator=(const unexpected<G> &e);
+ template <class G> expected &operator=(unexpected<G> &&e);
+
explicit operator bool() const noexcept;
bool has_value() const noexcept;
@@ -959,17 +1027,17 @@ template <class E> class expected<void, E> {
void swap(expected &rhs) noexcept;
-#if __cplusplus >= 202002L
template <class T2, class E2>
friend bool operator==(const expected &x, const expected<T2, E2> &y);
template <class E2>
friend bool operator==(const expected &x, const unexpected<E2> &e);
-#endif
};
} // namespace std
+#endif // __cplusplus >= 202002L
+
#endif // STD_EXPECTED_H
)";
@@ -1021,6 +1089,15 @@ namespace detail {
template <class> constexpr bool is_unexpected = false;
template <class E> constexpr bool is_unexpected<unexpected<E>> = true;
+// Whether `T` can be constructed from `expected<U, G>`, in which case the
+// converting constructors from `expected<U, G>` are disabled.
+template <class T, class U, class G>
+constexpr bool is_constructible_from_expected =
+ __is_constructible(T, expected<U, G> &) ||
+ __is_constructible(T, expected<U, G> &&) ||
+ __is_constructible(T, const expected<U, G> &) ||
+ __is_constructible(T, const expected<U, G> &&);
+
} // namespace detail
template <class T, class E> class expected {
@@ -1043,12 +1120,15 @@ template <class T, class E> class expected {
template <class... Args> explicit expected(unexpect_t, Args &&...args);
template <class U, class G,
- std::enable_if_t<__is_constructible(T, const U &) &&
- __is_constructible(E, const G &)> * = nullptr>
+ std::enable_if_t<
+ __is_constructible(T, const U &) &&
+ __is_constructible(E, const G &) &&
+ !detail::is_constructible_from_expected<T, U, G>> * = nullptr>
expected(const expected<U, G> &rhs);
template <class U, class G,
- std::enable_if_t<__is_constructible(T, U &&) &&
- __is_constructible(E, G &&)> * = nullptr>
+ std::enable_if_t<
+ __is_constructible(T, U &&) && __is_constructible(E, G &&) &&
+ !detail::is_constructible_from_expected<T, U, G>> * = nullptr>
expected(expected<U, G> &&rhs);
template <
diff --git a/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp b/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp
index 550209c73e9206..f8fe7e7a1ad21c 100644
--- a/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp
@@ -951,4 +951,795 @@ TEST_P(UncheckedExpectedAccessTest, EqualToUnexpectedUncheckedVoidValue) {
)");
}
+TEST_P(UncheckedExpectedAccessTest, Emplace) {
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ void target($ns::expected<int, int> e) {
+ e.emplace(1);
+ e.value();
+ *e;
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ struct Foo {
+ void foo() const {}
+ };
+
+ void target($ns::expected<Foo, int> e) {
+ e.emplace();
+ e->foo();
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ int target($ns::expected<int, int> e) {
+ if (!e)
+ e.emplace(0);
+ return *e;
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ int target($ns::expected<int, int> *p) {
+ p->emplace(1);
+ return **p;
+ }
+ )");
+}
+
+TEST_P(UncheckedExpectedAccessTest, EmplaceVoid) {
+ // `tl::expected<void, E>` has no `value()`.
+ if (GetParam().NamespaceName != "std")
+ GTEST_SKIP();
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ void target($ns::expected<void, int> e) {
+ e.emplace();
+ e.value();
+ }
+ )");
+}
+
+TEST_P(UncheckedExpectedAccessTest, EmplaceUnchecked) {
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ void target($ns::expected<int, int> e) {
+ e.emplace(1);
+ e.error(); // [[unsafe:error]]
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ int target($ns::expected<int, int> a, $ns::expected<int, int> b) {
+ a.emplace(1);
+ return *b; // [[unsafe]]
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ int target($ns::expected<int, int> e, bool cond) {
+ if (cond)
+ e.emplace(1);
+ return *e; // [[unsafe]]
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ void target($ns::expected<void, int> e) {
+ e.emplace();
+ e.error(); // [[unsafe:error]]
+ }
+ )");
+}
+
+TEST_P(UncheckedExpectedAccessTest, Construct) {
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ int target() {
+ $ns::expected<int, int> e;
+ return *e;
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ int target() {
+ $ns::expected<int, int> e{};
+ return e.value();
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ int target() {
+ $ns::expected<int, int> e(5);
+ return *e;
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ int target() {
+ $ns::expected<int, int> e = 5;
+ return *e;
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ struct Foo {
+ void foo() const {}
+ };
+
+ void target() {
+ $ns::expected<Foo, int> e($ns::in_place);
+ e->foo();
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ int target() {
+ return $ns::expected<int, int>(5).value();
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ int target() {
+ $ns::expected<int, int> e($ns::unexpected(1));
+ return e.error();
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ int target() {
+ const $ns::unexpected<int> u(1);
+ $ns::expected<int, int> e(u);
+ return e.error();
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ int target() {
+ $ns::expected<int, int> e = $ns::unexpected(1);
+ return e.error();
+ }
+ )");
+
+ ExpectDiagnosticsFor(R"(
+ #include "unchecked_expected_access_test.h"
+
+ int target() {
+ $ns::expected<int, int> e($ns::unexpect, 1);
+ return...
[truncated]
``````````
</details>
https://github.com/llvm/llvm-project/pull/246771
More information about the cfe-commits
mailing list