https://github.com/BaLiKfromUA updated https://github.com/llvm/llvm-project/pull/242868
>From 8625c5f542556db71124afe95d7d8a1102bebce7 Mon Sep 17 00:00:00 2001 From: BaLiKfromUA <[email protected]> Date: Sun, 15 Nov 2026 20:37:59 +0000 Subject: [PATCH 1/6] Implementation that passes simple optional-like tests Add mock and basic tests to start with --- .../Models/UncheckedExpectedAccessModel.h | 67 ++++ .../FlowSensitive/Models/CMakeLists.txt | 1 + .../Models/UncheckedExpectedAccessModel.cpp | 160 ++++++++ .../Analysis/FlowSensitive/CMakeLists.txt | 1 + .../Analysis/FlowSensitive/MockHeaders.cpp | 120 ++++++ .../UncheckedExpectedAccessModelTest.cpp | 341 ++++++++++++++++++ 6 files changed, 690 insertions(+) create mode 100644 clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h create mode 100644 clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp create mode 100644 clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp diff --git a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h new file mode 100644 index 00000000000000..1e9390ee190c3e --- /dev/null +++ b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h @@ -0,0 +1,67 @@ +//===-- UncheckedExpectedAccessModel.h --------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines a dataflow analysis that detects unsafe accesses to the +// values of `std::expected` objects. +// +//===----------------------------------------------------------------------===// + +#ifndef CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_UNCHECKEDEXPECTEDACCESSMODEL_H +#define CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_UNCHECKEDEXPECTEDACCESSMODEL_H + +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/Analysis/CFG.h" +#include "clang/Analysis/FlowSensitive/CFGMatchSwitch.h" +#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h" +#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h" +#include "clang/Analysis/FlowSensitive/NoopLattice.h" +#include "clang/Basic/SourceLocation.h" +#include "llvm/ADT/SmallVector.h" + +namespace clang { +namespace dataflow { + +/// Dataflow analysis that models whether `std::expected` objects hold values. +class UncheckedExpectedAccessModel + : public DataflowAnalysis<UncheckedExpectedAccessModel, NoopLattice> { +public: + UncheckedExpectedAccessModel(ASTContext &Ctx, Environment &Env); + + /// Returns a matcher for calls to member functions of `std::expected`. + static ast_matchers::StatementMatcher callToExpectedClass(); + + static NoopLattice initialElement() { return {}; } + + void transfer(const CFGElement &Elt, NoopLattice &L, Environment &Env); + +private: + CFGMatchSwitch<TransferState<NoopLattice>> TransferMatchSwitch; +}; + +/// Reports the locations of accesses to `std::expected` values that are not +/// provably preceded by a check that the object holds a value. +class UncheckedExpectedAccessDiagnoser { +public: + UncheckedExpectedAccessDiagnoser(); + + llvm::SmallVector<SourceLocation> + operator()(const CFGElement &Elt, ASTContext &Ctx, + const TransferStateForDiagnostics<NoopLattice> &State) { + return DiagnoseMatchSwitch(Elt, Ctx, State.Env); + } + +private: + CFGMatchSwitch<const Environment, llvm::SmallVector<SourceLocation>> + DiagnoseMatchSwitch; +}; + +} // namespace dataflow +} // namespace clang + +#endif // CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_UNCHECKEDEXPECTEDACCESSMODEL_H diff --git a/clang/lib/Analysis/FlowSensitive/Models/CMakeLists.txt b/clang/lib/Analysis/FlowSensitive/Models/CMakeLists.txt index 62c9473842779d..41ab2c6fa786c5 100644 --- a/clang/lib/Analysis/FlowSensitive/Models/CMakeLists.txt +++ b/clang/lib/Analysis/FlowSensitive/Models/CMakeLists.txt @@ -1,5 +1,6 @@ add_clang_library(clangAnalysisFlowSensitiveModels ChromiumCheckModel.cpp + UncheckedExpectedAccessModel.cpp UncheckedOptionalAccessModel.cpp UncheckedStatusOrAccessModel.cpp GtestModelHelpers.cpp diff --git a/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp new file mode 100644 index 00000000000000..9bbb2f6e5b394d --- /dev/null +++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp @@ -0,0 +1,160 @@ +//===-- UncheckedExpectedAccessModel.cpp ------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines a dataflow analysis that detects unsafe accesses to the +// values of `std::expected` objects. +// +//===----------------------------------------------------------------------===// + +#include "clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h" +#include "clang/AST/DeclCXX.h" +#include "clang/AST/ExprCXX.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/Analysis/FlowSensitive/StorageLocation.h" +#include "clang/Analysis/FlowSensitive/Value.h" + +namespace clang { +namespace dataflow { + +static bool isExpectedClass(const CXXRecordDecl &RD) { + return RD.getDeclName().isIdentifier() && RD.getName() == "expected" && + RD.getDeclContext()->isStdNamespace(); +} + +// Classes derived from `std::expected` are deliberately not supported. +static bool isExpectedType(QualType Ty) { + const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); + return RD != nullptr && isExpectedClass(*RD); +} + +namespace { + +using namespace ::clang::ast_matchers; + +using LatticeTransferState = TransferState<NoopLattice>; + +AST_MATCHER(CXXRecordDecl, expectedClass) { return isExpectedClass(Node); } + +auto expectedMemberCall(ast_matchers::internal::Matcher<NamedDecl> Name) { + return cxxMemberCallExpr( + callee(cxxMethodDecl(Name, ofClass(expectedClass())))); +} + +auto expectedOperatorCall(ArrayRef<StringRef> Names) { + return cxxOperatorCallExpr(hasAnyOverloadedOperatorName(Names), + callee(cxxMethodDecl(ofClass(expectedClass())))); +} + +StorageLocation &locForHasValue(const RecordStorageLocation &ExpectedLoc) { + return ExpectedLoc.getSyntheticField("has_value"); +} + +/// Returns the symbolic value that represents the "has_value" property of the +/// expected at `ExpectedLoc`. Returns null if `ExpectedLoc` is null or is not +/// the location of a `std::expected` object (e.g. of a derived class object). +BoolValue *getHasValue(Environment &Env, RecordStorageLocation *ExpectedLoc) { + if (ExpectedLoc == nullptr || !isExpectedType(ExpectedLoc->getType())) + return nullptr; + StorageLocation &HasValueLoc = locForHasValue(*ExpectedLoc); + auto *HasValueVal = Env.get<BoolValue>(HasValueLoc); + if (HasValueVal == nullptr) { + HasValueVal = &Env.makeAtomicBoolValue(); + Env.setValue(HasValueLoc, *HasValueVal); + } + return HasValueVal; +} + +void transferHasValueCall(const CXXMemberCallExpr *E, + const MatchFinder::MatchResult &, + LatticeTransferState &State) { + if (BoolValue *HasValueVal = + getHasValue(State.Env, getImplicitObjectLocation(*E, State.Env))) + State.Env.setValue(*E, *HasValueVal); +} + +// FIXME: Model the constructors, assignments, `emplace` and `swap`. +auto buildTransferMatchSwitch() { + return CFGMatchSwitchBuilder<LatticeTransferState>() + // expected::has_value, expected::operator bool + .CaseOfCFGStmt<CXXMemberCallExpr>( + expectedMemberCall(hasAnyName("has_value", "operator bool")), + transferHasValueCall) + .Build(); +} + +llvm::SmallVector<SourceLocation> +diagnoseAccess(SourceLocation AccessLoc, + const RecordStorageLocation *ExpectedLoc, + const Environment &Env) { + if (ExpectedLoc != nullptr) { + // Accesses through classes derived from `std::expected` are not modeled. + if (!isExpectedType(ExpectedLoc->getType())) + return {}; + if (auto *HasValueVal = Env.get<BoolValue>(locForHasValue(*ExpectedLoc))) + if (Env.proves(HasValueVal->formula())) + return {}; + } + + return {AccessLoc}; +} + +auto buildDiagnoseMatchSwitch() { + return CFGMatchSwitchBuilder<const Environment, + llvm::SmallVector<SourceLocation>>() + // expected::value + .CaseOfCFGStmt<CXXMemberCallExpr>( + expectedMemberCall(hasName("value")), + [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &, + const Environment &Env) { + return diagnoseAccess(E->getExprLoc(), + getImplicitObjectLocation(*E, Env), Env); + }) + // expected::operator*, expected::operator-> + .CaseOfCFGStmt<CXXOperatorCallExpr>( + expectedOperatorCall({"*", "->"}), + [](const CXXOperatorCallExpr *E, const MatchFinder::MatchResult &, + const Environment &Env) { + // `getExprLoc` of `operator->` is the start of the object + // expression, so point at the operator token instead. + return diagnoseAccess(E->getOperatorLoc(), + Env.get<RecordStorageLocation>(*E->getArg(0)), + Env); + }) + .Build(); +} + +} // namespace + +ast_matchers::StatementMatcher +UncheckedExpectedAccessModel::callToExpectedClass() { + return callExpr(callee(cxxMethodDecl(ofClass(expectedClass())))); +} + +UncheckedExpectedAccessModel::UncheckedExpectedAccessModel(ASTContext &Ctx, + Environment &Env) + : DataflowAnalysis<UncheckedExpectedAccessModel, NoopLattice>(Ctx), + TransferMatchSwitch(buildTransferMatchSwitch()) { + Env.getDataflowAnalysisContext().setSyntheticFieldCallback( + [&Ctx](QualType Ty) -> llvm::StringMap<QualType> { + if (!isExpectedType(Ty)) + return {}; + return {{"has_value", Ctx.BoolTy}}; + }); +} + +void UncheckedExpectedAccessModel::transfer(const CFGElement &Elt, + NoopLattice &L, Environment &Env) { + LatticeTransferState State(L, Env); + TransferMatchSwitch(Elt, getASTContext(), State); +} + +UncheckedExpectedAccessDiagnoser::UncheckedExpectedAccessDiagnoser() + : DiagnoseMatchSwitch(buildDiagnoseMatchSwitch()) {} + +} // namespace dataflow +} // namespace clang diff --git a/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt b/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt index 1d932ec6e8a963..8dae4d0c3282b2 100644 --- a/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt +++ b/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt @@ -24,6 +24,7 @@ add_clang_unittest(ClangAnalysisFlowSensitiveTests TransferBranchTest.cpp TransferTest.cpp TypeErasedDataflowAnalysisTest.cpp + UncheckedExpectedAccessModelTest.cpp UncheckedOptionalAccessModelTest.cpp UncheckedStatusOrAccessModelTest.cpp UncheckedStatusOrAccessModelTestFixture.cpp diff --git a/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp b/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp index 3601d3efbcf1bf..68b58169cbdf75 100644 --- a/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp +++ b/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp @@ -820,6 +820,125 @@ constexpr bool operator!=(const T &value, const optional<U> &opt); } // namespace std )"; +static constexpr char StdExpectedHeader[] = R"( +#ifndef STD_EXPECTED_H +#define STD_EXPECTED_H + +namespace std { + +template <class E> class unexpected { +public: + unexpected(const unexpected &) = default; + unexpected(unexpected &&) = default; + + template <class Err = E> explicit unexpected(Err &&e); + + const E &error() const & noexcept; + E &error() & noexcept; + const E &&error() const && noexcept; + E &&error() && noexcept; +}; + +template <class E> unexpected(E) -> unexpected<E>; + +struct unexpect_t { + explicit unexpect_t() = default; +}; + +inline constexpr unexpect_t unexpect{}; + +template <class T, class E> class expected { +public: + using value_type = T; + using error_type = E; + using unexpected_type = unexpected<E>; + + expected(); + expected(const expected &); + expected(expected &&) noexcept; + + template <class U = T> expected(U &&v); + + template <class G> expected(const unexpected<G> &e); + template <class G> expected(unexpected<G> &&e); + + template <class... Args> + explicit expected(unexpect_t, Args &&...args); + + expected &operator=(const expected &); + expected &operator=(expected &&) noexcept; + + const T *operator->() const noexcept; + T *operator->() noexcept; + + const T &operator*() const & noexcept; + T &operator*() & noexcept; + const T &&operator*() const && noexcept; + T &&operator*() && noexcept; + + explicit operator bool() const noexcept; + bool has_value() const noexcept; + + const T &value() const &; + T &value() &; + const T &&value() const &&; + T &&value() &&; + + const E &error() const & noexcept; + E &error() & noexcept; + const E &&error() const && noexcept; + E &&error() && noexcept; + + template <class U> T value_or(U &&v) const &; + template <class U> T value_or(U &&v) &&; + + template <class... Args> T &emplace(Args &&...args) noexcept; + + void swap(expected &rhs) noexcept; +}; + +template <class E> class expected<void, E> { +public: + using value_type = void; + using error_type = E; + using unexpected_type = unexpected<E>; + + expected() noexcept; + expected(const expected &); + expected(expected &&) noexcept; + + template <class G> expected(const unexpected<G> &e); + template <class G> expected(unexpected<G> &&e); + + template <class... Args> + explicit expected(unexpect_t, Args &&...args); + + expected &operator=(const expected &); + expected &operator=(expected &&) noexcept; + + explicit operator bool() const noexcept; + bool has_value() const noexcept; + + void operator*() const noexcept; + + void value() const &; + void value() &&; + + const E &error() const & noexcept; + E &error() & noexcept; + const E &&error() const && noexcept; + E &&error() && noexcept; + + void emplace() noexcept; + + void swap(expected &rhs) noexcept; +}; + +} // namespace std + +#endif // STD_EXPECTED_H +)"; + static constexpr char AbslOptionalHeader[] = R"( #include "absl_type_traits.h" #include "std_initializer_list.h" @@ -2503,6 +2622,7 @@ std::vector<std::pair<std::string, std::string>> getMockHeaders() { Headers.emplace_back("std_type_traits.h", StdTypeTraitsHeader); Headers.emplace_back("std_utility.h", StdUtilityHeader); Headers.emplace_back("std_optional.h", StdOptionalHeader); + Headers.emplace_back("std_expected.h", StdExpectedHeader); Headers.emplace_back("std_coroutine.h", StdCoroutineHeader); Headers.emplace_back("absl_type_traits.h", AbslTypeTraitsHeader); Headers.emplace_back("absl_optional.h", AbslOptionalHeader); diff --git a/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp b/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp new file mode 100644 index 00000000000000..1abd1d4edbb519 --- /dev/null +++ b/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp @@ -0,0 +1,341 @@ +//===- UncheckedExpectedAccessModelTest.cpp -------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h" +#include "MockHeaders.h" +#include "TestingSupport.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Frontend/TextDiagnostic.h" +#include "clang/Tooling/Tooling.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/DenseSet.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/Support/Error.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include <string> +#include <utility> +#include <vector> + +using namespace clang; +using namespace dataflow; +using namespace test; + +using ::testing::ContainerEq; + +/// Replaces all occurrences of `Pattern` in `S` with `Replacement`. +static void ReplaceAllOccurrences(std::string &S, const std::string &Pattern, + const std::string &Replacement) { + size_t Pos = 0; + while (true) { + Pos = S.find(Pattern, Pos); + if (Pos == std::string::npos) + break; + S.replace(Pos, Pattern.size(), Replacement); + } +} + +struct ExpectedTypeIdentifier { + std::string NamespaceName; +}; + +static raw_ostream &operator<<(raw_ostream &OS, + const ExpectedTypeIdentifier &TypeId) { + OS << TypeId.NamespaceName << "::expected"; + return OS; +} + +class UncheckedExpectedAccessTest + : public ::testing::TestWithParam<ExpectedTypeIdentifier> { +protected: + // Check that after running the analysis on SourceCode, it produces the + // expected diagnostics according to [[unsafe]] annotations. + // - No annotations => no diagnostics. + // - Given "// [[unsafe]]" annotations on a line, we expect a diagnostic on + // that line. + void ExpectDiagnosticsFor(std::string SourceCode) { + // Run in C++17 and C++20 mode to cover differences in the AST between modes + // (e.g. C++20 can contain `CXXRewrittenBinaryOperator`). + for (const char *CxxMode : {"-std=c++17", "-std=c++20"}) + ExpectDiagnosticsFor(SourceCode, CxxMode); + } + + void ExpectDiagnosticsFor(std::string SourceCode, const char *CxxMode) { + ReplaceAllOccurrences(SourceCode, "$ns", GetParam().NamespaceName); + + auto Headers = getMockHeaders(); + Headers.emplace_back("unchecked_expected_access_test.h", R"( + #include "std_expected.h" + #include "std_utility.h" + + template <typename T> + T Make(); + )"); + std::vector<SourceLocation> Diagnostics; + llvm::Error Error = checkDataflow<UncheckedExpectedAccessModel>( + AnalysisInputs<UncheckedExpectedAccessModel>( + SourceCode, ast_matchers::hasName("target"), + [](ASTContext &Ctx, Environment &Env) { + return UncheckedExpectedAccessModel(Ctx, Env); + }) + .withDiagnosisCallbacks( + {/*Before=*/[&Diagnostics, + Diagnoser = UncheckedExpectedAccessDiagnoser()]( + ASTContext &Ctx, const CFGElement &Elt, + const TransferStateForDiagnostics<NoopLattice> + &State) mutable { + auto EltDiagnostics = Diagnoser(Elt, Ctx, State); + llvm::move(EltDiagnostics, std::back_inserter(Diagnostics)); + }, + /*After=*/nullptr}) + .withASTBuildArgs( + {"-fsyntax-only", CxxMode, "-Wno-undefined-inline"}) + .withASTBuildVirtualMappedFiles( + tooling::FileContentMappings(Headers.begin(), Headers.end())), + /*VerifyResults=*/[&Diagnostics]( + const llvm::DenseMap<unsigned, std::string> + &Annotations, + const AnalysisOutputs &AO) { + llvm::DenseSet<unsigned> AnnotationLines; + for (const auto &[Line, _] : Annotations) + AnnotationLines.insert(Line); + auto &SrcMgr = AO.ASTCtx.getSourceManager(); + llvm::DenseSet<unsigned> DiagnosticLines; + for (SourceLocation Loc : Diagnostics) { + unsigned Line = SrcMgr.getPresumedLineNumber(Loc); + DiagnosticLines.insert(Line); + if (!AnnotationLines.contains(Line)) { + DiagnosticOptions DiagOpts; + TextDiagnostic TD(llvm::errs(), AO.ASTCtx.getLangOpts(), + DiagOpts); + TD.emitDiagnostic(FullSourceLoc(Loc, SrcMgr), + DiagnosticsEngine::Error, + "unexpected diagnostic", {}, {}); + } + } + + EXPECT_THAT(DiagnosticLines, ContainerEq(AnnotationLines)); + }); + if (Error) + FAIL() << llvm::toString(std::move(Error)); + } +}; + +INSTANTIATE_TEST_SUITE_P( + UncheckedExpectedUseTestInst, UncheckedExpectedAccessTest, + ::testing::Values(ExpectedTypeIdentifier{"std"}), + [](const ::testing::TestParamInfo<ExpectedTypeIdentifier> &Info) { + return Info.param.NamespaceName; + }); + +TEST_P(UncheckedExpectedAccessTest, EmptyFunctionBody) { + ExpectDiagnosticsFor(R"( + void target() { + (void)0; + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, UnwrapUsingValueNoCheck) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + e.value(); // [[unsafe]] + } + )"); + + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target(const $ns::expected<int, int> &e) { + e.value(); // [[unsafe]] + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, UnwrapUsingOperatorStarNoCheck) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + *e; // [[unsafe]] + } + )"); + + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target(const $ns::expected<int, int> &e) { + *e; // [[unsafe]] + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, UnwrapUsingOperatorArrowNoCheck) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + struct Foo { + void foo() const {} + }; + + void target($ns::expected<Foo, int> e) { + e->foo(); // [[unsafe]] + } + )"); + + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + struct Foo { + void foo() const {} + }; + + void target(const $ns::expected<Foo, int> &e) { + e->foo(); // [[unsafe]] + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, UnwrapFunctionCallResultNoCheck) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target() { + auto e = Make<$ns::expected<int, int>>(); + e.value(); // [[unsafe]] + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, UnwrapVoidUsingValueNoCheck) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<void, int> e) { + e.value(); // [[unsafe]] + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, UnwrapInElseBranch) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + if (e.has_value()) { + } else { + e.value(); // [[unsafe]] + } + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, UnwrapInNegatedCheck) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + if (!e) { + *e; // [[unsafe]] + } + } + )"); + + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + int target($ns::expected<int, int> e) { + return !e ? *e : 0; // [[unsafe]] + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, HasValueCheck) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + struct Foo { + void foo() const {} + }; + + void target($ns::expected<Foo, int> e) { + if (e.has_value()) { + e.value(); + *e; + e->foo(); + } + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, OperatorBoolCheck) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + if (e) { + e.value(); + *e; + } + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, CheckedAfterEarlyReturn) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + if (!e) + return; + e.value(); + } + )"); + + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + int target($ns::expected<int, int> e) { + if (!e.has_value()) + return 0; + return *e; + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, CheckedInTernary) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + int target($ns::expected<int, int> e) { + return e ? *e : 0; + } + )"); + + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + int target($ns::expected<int, int> e) { + return e.has_value() ? e.value() : 0; + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, ValueOrIsNotAnAccess) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + e.value_or(0); + } + )"); +} >From 3e1355d974b3b2ce2c9ef0a96a24fbea14c1f2b9 Mon Sep 17 00:00:00 2001 From: BaLiKfromUA <[email protected]> Date: Sun, 15 Nov 2026 20:38:54 +0000 Subject: [PATCH 2/6] Add basic of `.error()` Add basic tests for `.error()` access --- .../Models/UncheckedExpectedAccessModel.h | 26 ++- .../Models/UncheckedExpectedAccessModel.cpp | 39 +++- .../Analysis/FlowSensitive/MockHeaders.cpp | 6 + .../UncheckedExpectedAccessModelTest.cpp | 201 +++++++++++++++++- 4 files changed, 251 insertions(+), 21 deletions(-) diff --git a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h index 1e9390ee190c3e..b6d6b0e5e118a6 100644 --- a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h +++ b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h @@ -44,20 +44,38 @@ class UncheckedExpectedAccessModel CFGMatchSwitch<TransferState<NoopLattice>> TransferMatchSwitch; }; -/// Reports the locations of accesses to `std::expected` values that are not -/// provably preceded by a check that the object holds a value. +/// The part of a `std::expected` object that is accessed. +/// +/// The values are used as `%select` indices in diagnostics, so they must not +/// be reordered. +enum class UncheckedExpectedAccessKind : int { + /// `value()`, `operator*` or `operator->`, which require a value. + Value = 0, + /// `error()`, which requires an error. + Error = 1, +}; + +/// Diagnostic information for an unchecked `std::expected` access. +struct UncheckedExpectedAccessDiagnostic { + SourceLocation Loc; + UncheckedExpectedAccessKind Kind; +}; + +/// Reports accesses to the value (or error) of `std::expected` objects that are +/// not provably preceded by a check that the object holds a value (or error). class UncheckedExpectedAccessDiagnoser { public: UncheckedExpectedAccessDiagnoser(); - llvm::SmallVector<SourceLocation> + llvm::SmallVector<UncheckedExpectedAccessDiagnostic> operator()(const CFGElement &Elt, ASTContext &Ctx, const TransferStateForDiagnostics<NoopLattice> &State) { return DiagnoseMatchSwitch(Elt, Ctx, State.Env); } private: - CFGMatchSwitch<const Environment, llvm::SmallVector<SourceLocation>> + CFGMatchSwitch<const Environment, + llvm::SmallVector<UncheckedExpectedAccessDiagnostic>> DiagnoseMatchSwitch; }; diff --git a/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp index 9bbb2f6e5b394d..f9376bafd98d0b 100644 --- a/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp +++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp @@ -15,6 +15,8 @@ #include "clang/AST/DeclCXX.h" #include "clang/AST/ExprCXX.h" #include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/Analysis/FlowSensitive/Arena.h" +#include "clang/Analysis/FlowSensitive/Formula.h" #include "clang/Analysis/FlowSensitive/StorageLocation.h" #include "clang/Analysis/FlowSensitive/Value.h" @@ -87,31 +89,39 @@ auto buildTransferMatchSwitch() { .Build(); } -llvm::SmallVector<SourceLocation> -diagnoseAccess(SourceLocation AccessLoc, +llvm::SmallVector<UncheckedExpectedAccessDiagnostic> +diagnoseAccess(SourceLocation AccessLoc, UncheckedExpectedAccessKind Kind, const RecordStorageLocation *ExpectedLoc, const Environment &Env) { if (ExpectedLoc != nullptr) { // Accesses through classes derived from `std::expected` are not modeled. if (!isExpectedType(ExpectedLoc->getType())) return {}; - if (auto *HasValueVal = Env.get<BoolValue>(locForHasValue(*ExpectedLoc))) - if (Env.proves(HasValueVal->formula())) + if (auto *HasValueVal = Env.get<BoolValue>(locForHasValue(*ExpectedLoc))) { + // The value may only be accessed if the expected holds a value, and the + // error only if it does not. + const Formula &Safe = Kind == UncheckedExpectedAccessKind::Value + ? HasValueVal->formula() + : Env.arena().makeNot(HasValueVal->formula()); + if (Env.proves(Safe)) return {}; + } } - return {AccessLoc}; + return {{AccessLoc, Kind}}; } auto buildDiagnoseMatchSwitch() { - return CFGMatchSwitchBuilder<const Environment, - llvm::SmallVector<SourceLocation>>() + return CFGMatchSwitchBuilder< + const Environment, + llvm::SmallVector<UncheckedExpectedAccessDiagnostic>>() // expected::value .CaseOfCFGStmt<CXXMemberCallExpr>( expectedMemberCall(hasName("value")), [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &, const Environment &Env) { return diagnoseAccess(E->getExprLoc(), + UncheckedExpectedAccessKind::Value, getImplicitObjectLocation(*E, Env), Env); }) // expected::operator*, expected::operator-> @@ -121,9 +131,18 @@ auto buildDiagnoseMatchSwitch() { const Environment &Env) { // `getExprLoc` of `operator->` is the start of the object // expression, so point at the operator token instead. - return diagnoseAccess(E->getOperatorLoc(), - Env.get<RecordStorageLocation>(*E->getArg(0)), - Env); + return diagnoseAccess( + E->getOperatorLoc(), UncheckedExpectedAccessKind::Value, + Env.get<RecordStorageLocation>(*E->getArg(0)), Env); + }) + // expected::error + .CaseOfCFGStmt<CXXMemberCallExpr>( + expectedMemberCall(hasName("error")), + [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &, + const Environment &Env) { + return diagnoseAccess(E->getExprLoc(), + UncheckedExpectedAccessKind::Error, + getImplicitObjectLocation(*E, Env), Env); }) .Build(); } diff --git a/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp b/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp index 68b58169cbdf75..97d77d3dbcac23 100644 --- a/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp +++ b/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp @@ -892,6 +892,9 @@ template <class T, class E> class expected { template <class U> T value_or(U &&v) const &; template <class U> T value_or(U &&v) &&; + template <class G> E error_or(G &&e) const &; + template <class G> E error_or(G &&e) &&; + template <class... Args> T &emplace(Args &&...args) noexcept; void swap(expected &rhs) noexcept; @@ -929,6 +932,9 @@ template <class E> class expected<void, E> { const E &&error() const && noexcept; E &&error() && noexcept; + template <class G> E error_or(G &&e) const &; + template <class G> E error_or(G &&e) &&; + void emplace() noexcept; void swap(expected &rhs) noexcept; diff --git a/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp b/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp index 1abd1d4edbb519..409f0e918731ed 100644 --- a/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp @@ -58,8 +58,10 @@ class UncheckedExpectedAccessTest // Check that after running the analysis on SourceCode, it produces the // expected diagnostics according to [[unsafe]] annotations. // - No annotations => no diagnostics. - // - Given "// [[unsafe]]" annotations on a line, we expect a diagnostic on - // that line. + // - Given "// [[unsafe]]" annotations on a line, we expect a diagnostic for + // an unchecked value access on that line. + // - Given "// [[unsafe:error]]" annotations on a line, we expect a diagnostic + // for an unchecked error access on that line. void ExpectDiagnosticsFor(std::string SourceCode) { // Run in C++17 and C++20 mode to cover differences in the AST between modes // (e.g. C++20 can contain `CXXRewrittenBinaryOperator`). @@ -78,7 +80,7 @@ class UncheckedExpectedAccessTest template <typename T> T Make(); )"); - std::vector<SourceLocation> Diagnostics; + std::vector<UncheckedExpectedAccessDiagnostic> Diagnostics; llvm::Error Error = checkDataflow<UncheckedExpectedAccessModel>( AnalysisInputs<UncheckedExpectedAccessModel>( SourceCode, ast_matchers::hasName("target"), @@ -108,16 +110,23 @@ class UncheckedExpectedAccessTest AnnotationLines.insert(Line); auto &SrcMgr = AO.ASTCtx.getSourceManager(); llvm::DenseSet<unsigned> DiagnosticLines; - for (SourceLocation Loc : Diagnostics) { - unsigned Line = SrcMgr.getPresumedLineNumber(Loc); + for (const UncheckedExpectedAccessDiagnostic &Diag : Diagnostics) { + unsigned Line = SrcMgr.getPresumedLineNumber(Diag.Loc); DiagnosticLines.insert(Line); - if (!AnnotationLines.contains(Line)) { + auto It = Annotations.find(Line); + if (It == Annotations.end()) { DiagnosticOptions DiagOpts; TextDiagnostic TD(llvm::errs(), AO.ASTCtx.getLangOpts(), DiagOpts); - TD.emitDiagnostic(FullSourceLoc(Loc, SrcMgr), + TD.emitDiagnostic(FullSourceLoc(Diag.Loc, SrcMgr), DiagnosticsEngine::Error, "unexpected diagnostic", {}, {}); + } else { + UncheckedExpectedAccessKind ExpectedKind = + It->second == "unsafe:error" + ? UncheckedExpectedAccessKind::Error + : UncheckedExpectedAccessKind::Value; + EXPECT_EQ(Diag.Kind, ExpectedKind) << "on line " << Line; } } @@ -339,3 +348,181 @@ TEST_P(UncheckedExpectedAccessTest, ValueOrIsNotAnAccess) { } )"); } + +TEST_P(UncheckedExpectedAccessTest, UnwrapErrorNoCheck) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + e.error(); // [[unsafe:error]] + } + )"); + + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target(const $ns::expected<int, int> &e) { + e.error(); // [[unsafe:error]] + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, UnwrapErrorOfFunctionCallResultNoCheck) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target() { + auto e = Make<$ns::expected<int, int>>(); + e.error(); // [[unsafe:error]] + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, UnwrapVoidErrorNoCheck) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<void, int> e) { + e.error(); // [[unsafe:error]] + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, UnwrapErrorWhenHoldingValue) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + if (e) { + e.error(); // [[unsafe:error]] + } + } + )"); + + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + if (e.has_value()) { + e.error(); // [[unsafe:error]] + } + } + )"); + + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + if (!e) + return; + e.error(); // [[unsafe:error]] + } + )"); + + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + int target($ns::expected<int, int> e) { + return e ? e.error() : 0; // [[unsafe:error]] + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, ErrorCheck) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + if (!e) { + e.error(); + } + } + )"); + + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + if (!e.has_value()) { + e.error(); + } + } + )"); + + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + if (e) { + } else { + e.error(); + } + } + )"); + + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<void, int> e) { + if (!e) + e.error(); + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, ErrorCheckedAfterEarlyReturn) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + int target($ns::expected<int, int> e) { + if (e) + return 0; + return e.error(); + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, ErrorCheckedInTernary) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + int target($ns::expected<int, int> e) { + return e ? 0 : e.error(); + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, ValueAndErrorChecked) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + if (e) { + *e; + } else { + e.error(); + } + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, ErrorOrIsNotAnAccess) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target($ns::expected<int, int> e) { + e.error_or(0); + } + )"); +} + +TEST_P(UncheckedExpectedAccessTest, UnexpectedErrorIsNotAnAccess) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target() { + $ns::unexpected<int> u(1); + u.error(); + } + )"); +} >From ab28ab5440504e0f111ff158c6ccf41cf599f47e Mon Sep 17 00:00:00 2001 From: BaLiKfromUA <[email protected]> Date: Sun, 15 Nov 2026 20:41:43 +0000 Subject: [PATCH 3/6] Basic support of `tl::expected` Need it for battle-testing on real codebase --- .../Models/UncheckedExpectedAccessModel.h | 21 ++- .../Models/UncheckedExpectedAccessModel.cpp | 27 +++- .../Analysis/FlowSensitive/MockHeaders.cpp | 145 ++++++++++++++++++ .../UncheckedExpectedAccessModelTest.cpp | 50 +++++- 4 files changed, 231 insertions(+), 12 deletions(-) diff --git a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h index b6d6b0e5e118a6..2928bc172fc24c 100644 --- a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h +++ b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h @@ -7,7 +7,7 @@ //===----------------------------------------------------------------------===// // // This file defines a dataflow analysis that detects unsafe accesses to the -// values of `std::expected` objects. +// values of `std::expected` and `tl::expected` objects. // //===----------------------------------------------------------------------===// @@ -23,17 +23,22 @@ #include "clang/Analysis/FlowSensitive/NoopLattice.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringRef.h" namespace clang { namespace dataflow { -/// Dataflow analysis that models whether `std::expected` objects hold values. +/// Dataflow analysis that models whether expected objects hold values. +/// +/// Supported types are `std::expected` and `tl::expected` +/// (https://github.com/TartanLlama/expected). class UncheckedExpectedAccessModel : public DataflowAnalysis<UncheckedExpectedAccessModel, NoopLattice> { public: UncheckedExpectedAccessModel(ASTContext &Ctx, Environment &Env); - /// Returns a matcher for calls to member functions of `std::expected`. + /// Returns a matcher for calls to member functions of a supported expected + /// type. static ast_matchers::StatementMatcher callToExpectedClass(); static NoopLattice initialElement() { return {}; } @@ -44,7 +49,7 @@ class UncheckedExpectedAccessModel CFGMatchSwitch<TransferState<NoopLattice>> TransferMatchSwitch; }; -/// The part of a `std::expected` object that is accessed. +/// The part of an expected object that is accessed. /// /// The values are used as `%select` indices in diagnostics, so they must not /// be reordered. @@ -55,14 +60,16 @@ enum class UncheckedExpectedAccessKind : int { Error = 1, }; -/// Diagnostic information for an unchecked `std::expected` access. +/// Diagnostic information for an unchecked expected access. struct UncheckedExpectedAccessDiagnostic { SourceLocation Loc; UncheckedExpectedAccessKind Kind; + /// The accessed type, either "std::expected" or "tl::expected". + llvm::StringRef TypeName; }; -/// Reports accesses to the value (or error) of `std::expected` objects that are -/// not provably preceded by a check that the object holds a value (or error). +/// Reports accesses to the value (or error) of expected objects that are not +/// provably preceded by a check that the object holds a value (or error). class UncheckedExpectedAccessDiagnoser { public: UncheckedExpectedAccessDiagnoser(); diff --git a/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp index f9376bafd98d0b..f742fb25e21513 100644 --- a/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp +++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp @@ -23,9 +23,25 @@ namespace clang { namespace dataflow { +/// Returns true if `DC` is `std` or the top-level `tl` namespace, which holds +/// `tl::expected` (https://github.com/TartanLlama/expected). +static bool isSupportedNamespace(const DeclContext &DC) { + if (DC.isStdNamespace()) + return true; + const auto *NS = dyn_cast<NamespaceDecl>(&DC); + return NS != nullptr && NS->getDeclName().isIdentifier() && + NS->getName() == "tl" && NS->getParent()->isTranslationUnit(); +} + static bool isExpectedClass(const CXXRecordDecl &RD) { return RD.getDeclName().isIdentifier() && RD.getName() == "expected" && - RD.getDeclContext()->isStdNamespace(); + isSupportedNamespace(*RD.getDeclContext()); +} + +/// Returns the name of the expected class `RD` to show in diagnostics. +static llvm::StringRef getExpectedTypeName(const CXXRecordDecl &RD) { + return RD.getDeclContext()->isStdNamespace() ? "std::expected" + : "tl::expected"; } // Classes derived from `std::expected` are deliberately not supported. @@ -89,12 +105,14 @@ auto buildTransferMatchSwitch() { .Build(); } +/// `ExpectedClass` is the class of the called accessor. llvm::SmallVector<UncheckedExpectedAccessDiagnostic> diagnoseAccess(SourceLocation AccessLoc, UncheckedExpectedAccessKind Kind, + const CXXRecordDecl &ExpectedClass, const RecordStorageLocation *ExpectedLoc, const Environment &Env) { if (ExpectedLoc != nullptr) { - // Accesses through classes derived from `std::expected` are not modeled. + // Accesses through classes derived from an expected are not modeled. if (!isExpectedType(ExpectedLoc->getType())) return {}; if (auto *HasValueVal = Env.get<BoolValue>(locForHasValue(*ExpectedLoc))) { @@ -108,7 +126,7 @@ diagnoseAccess(SourceLocation AccessLoc, UncheckedExpectedAccessKind Kind, } } - return {{AccessLoc, Kind}}; + return {{AccessLoc, Kind, getExpectedTypeName(ExpectedClass)}}; } auto buildDiagnoseMatchSwitch() { @@ -122,6 +140,7 @@ auto buildDiagnoseMatchSwitch() { const Environment &Env) { return diagnoseAccess(E->getExprLoc(), UncheckedExpectedAccessKind::Value, + *E->getMethodDecl()->getParent(), getImplicitObjectLocation(*E, Env), Env); }) // expected::operator*, expected::operator-> @@ -133,6 +152,7 @@ auto buildDiagnoseMatchSwitch() { // expression, so point at the operator token instead. return diagnoseAccess( E->getOperatorLoc(), UncheckedExpectedAccessKind::Value, + *cast<CXXMethodDecl>(E->getCalleeDecl())->getParent(), Env.get<RecordStorageLocation>(*E->getArg(0)), Env); }) // expected::error @@ -142,6 +162,7 @@ auto buildDiagnoseMatchSwitch() { const Environment &Env) { return diagnoseAccess(E->getExprLoc(), UncheckedExpectedAccessKind::Error, + *E->getMethodDecl()->getParent(), getImplicitObjectLocation(*E, Env), Env); }) .Build(); diff --git a/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp b/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp index 97d77d3dbcac23..f325b913ae2c7f 100644 --- a/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp +++ b/clang/unittests/Analysis/FlowSensitive/MockHeaders.cpp @@ -945,6 +945,150 @@ template <class E> class expected<void, E> { #endif // STD_EXPECTED_H )"; +static constexpr char TlExpectedHeader[] = R"( +#ifndef TL_EXPECTED_H +#define TL_EXPECTED_H + +// Mock of `tl::expected` from https://github.com/TartanLlama/expected. +// +// Unlike `std::expected`, it has no `void` specialization. + +#include "std_type_traits.h" + +namespace tl { + +template <class T, class E> class expected; + +struct in_place_t { + explicit in_place_t() = default; +}; +static constexpr in_place_t in_place{}; + +template <class E> class unexpected { +public: + unexpected() = delete; + explicit unexpected(const E &e); + explicit unexpected(E &&e); + + const E &value() const &; + E &value() &; + E &&value() &&; + const E &&value() const &&; +}; + +template <class E> unexpected(E) -> unexpected<E>; + +template <class E> +unexpected<typename std::decay<E>::type> make_unexpected(E &&e); + +struct unexpect_t { + unexpect_t() = default; +}; +static constexpr unexpect_t unexpect{}; + +namespace detail { + +template <class> constexpr bool is_unexpected = false; +template <class E> constexpr bool is_unexpected<unexpected<E>> = true; + +} // namespace detail + +template <class T, class E> class expected { +public: + typedef T value_type; + typedef E error_type; + typedef unexpected<E> unexpected_type; + + constexpr expected() = default; + constexpr expected(const expected &rhs) = default; + constexpr expected(expected &&rhs) = default; + expected &operator=(const expected &rhs) = default; + expected &operator=(expected &&rhs) = default; + + template <class... Args> expected(in_place_t, Args &&...args); + + template <class G> expected(const unexpected<G> &e); + template <class G> expected(unexpected<G> &&e); + + 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> + expected(const expected<U, G> &rhs); + template <class U, class G, + std::enable_if_t<__is_constructible(T, U &&) && + __is_constructible(E, G &&)> * = nullptr> + expected(expected<U, G> &&rhs); + + template < + class U = T, + std::enable_if_t< + __is_constructible(T, U &&) && + !std::is_same<typename std::decay<U>::type, in_place_t>::value && + !std::is_same<typename std::decay<U>::type, unexpect_t>::value && + !std::is_same<typename std::decay<U>::type, expected>::value && + !detail::is_unexpected<typename std::decay<U>::type>> * = nullptr> + expected(U &&v); + + // `G` delays forming `T &`, which is ill-formed for `void`. + template < + class U = T, class G = T, + std::enable_if_t< + __is_constructible(T, U &&) && __is_assignable(G &, U &&) && + !std::is_same<typename std::decay<U>::type, expected>::value && + !detail::is_unexpected<typename std::decay<U>::type>> * = nullptr> + expected &operator=(U &&v); + + template <class G> expected &operator=(const unexpected<G> &rhs); + template <class G> expected &operator=(unexpected<G> &&rhs); + + template <class... Args> void emplace(Args &&...args); + + void swap(expected &rhs); + + const T *operator->() const; + T *operator->(); + + template <class U = T, + std::enable_if_t<!std::is_void<U>::value> * = nullptr> + const U &operator*() const &; + template <class U = T, + std::enable_if_t<!std::is_void<U>::value> * = nullptr> + U &operator*() &; + template <class U = T, + std::enable_if_t<!std::is_void<U>::value> * = nullptr> + U &&operator*() &&; + + bool has_value() const noexcept; + explicit operator bool() const noexcept; + + template <class U = T, + std::enable_if_t<!std::is_void<U>::value> * = nullptr> + const U &value() const &; + template <class U = T, + std::enable_if_t<!std::is_void<U>::value> * = nullptr> + U &value() &; + template <class U = T, + std::enable_if_t<!std::is_void<U>::value> * = nullptr> + U &&value() &&; + + const E &error() const &; + E &error() &; + E &&error() &&; + + template <class U> T value_or(U &&v) const &; + template <class U> T value_or(U &&v) &&; +}; + +template <class T, class E> +void swap(expected<T, E> &lhs, expected<T, E> &rhs); + +} // namespace tl + +#endif // TL_EXPECTED_H +)"; + static constexpr char AbslOptionalHeader[] = R"( #include "absl_type_traits.h" #include "std_initializer_list.h" @@ -2629,6 +2773,7 @@ std::vector<std::pair<std::string, std::string>> getMockHeaders() { Headers.emplace_back("std_utility.h", StdUtilityHeader); Headers.emplace_back("std_optional.h", StdOptionalHeader); Headers.emplace_back("std_expected.h", StdExpectedHeader); + Headers.emplace_back("tl_expected.h", TlExpectedHeader); Headers.emplace_back("std_coroutine.h", StdCoroutineHeader); Headers.emplace_back("absl_type_traits.h", AbslTypeTraitsHeader); Headers.emplace_back("absl_optional.h", AbslOptionalHeader); diff --git a/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp b/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp index 409f0e918731ed..96b3c093e5212b 100644 --- a/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp @@ -76,6 +76,7 @@ class UncheckedExpectedAccessTest Headers.emplace_back("unchecked_expected_access_test.h", R"( #include "std_expected.h" #include "std_utility.h" + #include "tl_expected.h" template <typename T> T Make(); @@ -101,7 +102,8 @@ class UncheckedExpectedAccessTest {"-fsyntax-only", CxxMode, "-Wno-undefined-inline"}) .withASTBuildVirtualMappedFiles( tooling::FileContentMappings(Headers.begin(), Headers.end())), - /*VerifyResults=*/[&Diagnostics]( + /*VerifyResults=*/[&Diagnostics, + TypeName = GetParam().NamespaceName + "::expected"]( const llvm::DenseMap<unsigned, std::string> &Annotations, const AnalysisOutputs &AO) { @@ -127,6 +129,7 @@ class UncheckedExpectedAccessTest ? UncheckedExpectedAccessKind::Error : UncheckedExpectedAccessKind::Value; EXPECT_EQ(Diag.Kind, ExpectedKind) << "on line " << Line; + EXPECT_EQ(Diag.TypeName, TypeName) << "on line " << Line; } } @@ -139,11 +142,33 @@ class UncheckedExpectedAccessTest INSTANTIATE_TEST_SUITE_P( UncheckedExpectedUseTestInst, UncheckedExpectedAccessTest, - ::testing::Values(ExpectedTypeIdentifier{"std"}), + ::testing::Values(ExpectedTypeIdentifier{"std"}, + ExpectedTypeIdentifier{"tl"}), [](const ::testing::TestParamInfo<ExpectedTypeIdentifier> &Info) { return Info.param.NamespaceName; }); +// Verifies that similarly-named types are ignored. +TEST_P(UncheckedExpectedAccessTest, NonTrackedExpectedType) { + ExpectDiagnosticsFor( + R"( + namespace other { + namespace $ns { + template <typename T, typename E> + struct expected { + T value(); + E error(); + }; + } + + void target($ns::expected<int, int> e) { + e.value(); + e.error(); + } + } + )"); +} + TEST_P(UncheckedExpectedAccessTest, EmptyFunctionBody) { ExpectDiagnosticsFor(R"( void target() { @@ -226,6 +251,10 @@ TEST_P(UncheckedExpectedAccessTest, UnwrapFunctionCallResultNoCheck) { } TEST_P(UncheckedExpectedAccessTest, UnwrapVoidUsingValueNoCheck) { + // `tl::expected<void, E>` has no `value()`. + if (GetParam().NamespaceName != "std") + GTEST_SKIP(); + ExpectDiagnosticsFor(R"( #include "unchecked_expected_access_test.h" @@ -507,6 +536,10 @@ TEST_P(UncheckedExpectedAccessTest, ValueAndErrorChecked) { } TEST_P(UncheckedExpectedAccessTest, ErrorOrIsNotAnAccess) { + // `tl::expected` has no `error_or()`. + if (GetParam().NamespaceName != "std") + GTEST_SKIP(); + ExpectDiagnosticsFor(R"( #include "unchecked_expected_access_test.h" @@ -517,6 +550,19 @@ TEST_P(UncheckedExpectedAccessTest, ErrorOrIsNotAnAccess) { } TEST_P(UncheckedExpectedAccessTest, UnexpectedErrorIsNotAnAccess) { + // `tl::unexpected` names its accessor `value()`. + if (GetParam().NamespaceName == "tl") { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + void target() { + $ns::unexpected<int> u(1); + u.value(); + } + )"); + return; + } + ExpectDiagnosticsFor(R"( #include "unchecked_expected_access_test.h" >From f431c2daa9488a011e74d33cfff7bf9a65fbcf9b Mon Sep 17 00:00:00 2001 From: BaLiKfromUA <[email protected]> Date: Mon, 16 Nov 2026 17:22:32 +0000 Subject: [PATCH 4/6] More test coverage and minor clean up --- .../Models/UncheckedExpectedAccessModel.cpp | 8 +++++--- .../UncheckedExpectedAccessModelTest.cpp | 20 ++++++++++++++++--- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp index f742fb25e21513..6d44442ae04fff 100644 --- a/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp +++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp @@ -7,7 +7,7 @@ //===----------------------------------------------------------------------===// // // This file defines a dataflow analysis that detects unsafe accesses to the -// values of `std::expected` objects. +// values of `std::expected` and `tl::expected` objects. // //===----------------------------------------------------------------------===// @@ -44,7 +44,8 @@ static llvm::StringRef getExpectedTypeName(const CXXRecordDecl &RD) { : "tl::expected"; } -// Classes derived from `std::expected` are deliberately not supported. +// Classes derived from `std::expected` or `tl::expected` are deliberately not +// supported. static bool isExpectedType(QualType Ty) { const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); return RD != nullptr && isExpectedClass(*RD); @@ -74,7 +75,8 @@ StorageLocation &locForHasValue(const RecordStorageLocation &ExpectedLoc) { /// Returns the symbolic value that represents the "has_value" property of the /// expected at `ExpectedLoc`. Returns null if `ExpectedLoc` is null or is not -/// the location of a `std::expected` object (e.g. of a derived class object). +/// the location of a `std::expected` or `tl::expected` object (e.g. of a +/// derived class object). BoolValue *getHasValue(Environment &Env, RecordStorageLocation *ExpectedLoc) { if (ExpectedLoc == nullptr || !isExpectedType(ExpectedLoc->getType())) return nullptr; diff --git a/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp b/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp index 96b3c093e5212b..69bd344f02723e 100644 --- a/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/UncheckedExpectedAccessModelTest.cpp @@ -63,9 +63,8 @@ class UncheckedExpectedAccessTest // - Given "// [[unsafe:error]]" annotations on a line, we expect a diagnostic // for an unchecked error access on that line. void ExpectDiagnosticsFor(std::string SourceCode) { - // Run in C++17 and C++20 mode to cover differences in the AST between modes - // (e.g. C++20 can contain `CXXRewrittenBinaryOperator`). - for (const char *CxxMode : {"-std=c++17", "-std=c++20"}) + // `tl::expected` is usable since C++17, and `std::expected` since C++23. + for (const char *CxxMode : {"-std=c++17", "-std=c++20", "-std=c++23"}) ExpectDiagnosticsFor(SourceCode, CxxMode); } @@ -169,6 +168,21 @@ TEST_P(UncheckedExpectedAccessTest, NonTrackedExpectedType) { )"); } +// Classes derived from an expected are deliberately not analyzed. +TEST_P(UncheckedExpectedAccessTest, DerivedClassIsNotAnalyzed) { + ExpectDiagnosticsFor(R"( + #include "unchecked_expected_access_test.h" + + struct Derived : $ns::expected<int, int> {}; + + void target(Derived d) { + d.value(); + *d; + d.error(); + } + )"); +} + TEST_P(UncheckedExpectedAccessTest, EmptyFunctionBody) { ExpectDiagnosticsFor(R"( void target() { >From 7e4674ec8ae5c66cf5ce1734f4f928b7a649020c Mon Sep 17 00:00:00 2001 From: BaLiKfromUA <[email protected]> Date: Thu, 19 Nov 2026 08:53:54 +0000 Subject: [PATCH 5/6] Comments about model code/comments --- .../FlowSensitive/Models/UncheckedExpectedAccessModel.h | 2 +- .../FlowSensitive/Models/UncheckedExpectedAccessModel.cpp | 7 ++----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h index 2928bc172fc24c..0de0d4358de279 100644 --- a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h +++ b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.h @@ -64,7 +64,7 @@ enum class UncheckedExpectedAccessKind : int { struct UncheckedExpectedAccessDiagnostic { SourceLocation Loc; UncheckedExpectedAccessKind Kind; - /// The accessed type, either "std::expected" or "tl::expected". + /// The accessed type, e.g. "std::expected". llvm::StringRef TypeName; }; diff --git a/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp index 6d44442ae04fff..7664741533627a 100644 --- a/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp +++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp @@ -44,7 +44,7 @@ static llvm::StringRef getExpectedTypeName(const CXXRecordDecl &RD) { : "tl::expected"; } -// Classes derived from `std::expected` or `tl::expected` are deliberately not +// Classes derived from the expected class are deliberately not // supported. static bool isExpectedType(QualType Ty) { const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); @@ -75,7 +75,7 @@ StorageLocation &locForHasValue(const RecordStorageLocation &ExpectedLoc) { /// Returns the symbolic value that represents the "has_value" property of the /// expected at `ExpectedLoc`. Returns null if `ExpectedLoc` is null or is not -/// the location of a `std::expected` or `tl::expected` object (e.g. of a +/// the location of a supported expected object (e.g. of a /// derived class object). BoolValue *getHasValue(Environment &Env, RecordStorageLocation *ExpectedLoc) { if (ExpectedLoc == nullptr || !isExpectedType(ExpectedLoc->getType())) @@ -114,9 +114,6 @@ diagnoseAccess(SourceLocation AccessLoc, UncheckedExpectedAccessKind Kind, const RecordStorageLocation *ExpectedLoc, const Environment &Env) { if (ExpectedLoc != nullptr) { - // Accesses through classes derived from an expected are not modeled. - if (!isExpectedType(ExpectedLoc->getType())) - return {}; if (auto *HasValueVal = Env.get<BoolValue>(locForHasValue(*ExpectedLoc))) { // The value may only be accessed if the expected holds a value, and the // error only if it does not. >From be84187858b55edcf92aa0ff127976b42be7fb5a Mon Sep 17 00:00:00 2001 From: BaLiKfromUA <[email protected]> Date: Thu, 19 Nov 2026 09:17:21 +0000 Subject: [PATCH 6/6] Put check back with more helpfull comment --- .../FlowSensitive/Models/UncheckedExpectedAccessModel.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp index 7664741533627a..1841ebfcaa9a45 100644 --- a/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp +++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedExpectedAccessModel.cpp @@ -114,6 +114,10 @@ diagnoseAccess(SourceLocation AccessLoc, UncheckedExpectedAccessKind Kind, const RecordStorageLocation *ExpectedLoc, const Environment &Env) { if (ExpectedLoc != nullptr) { + // The matchers only check the class of the called accessor, but the object + // may be of a derived class, whose location has no "has_value" field. + if (!isExpectedType(ExpectedLoc->getType())) + return {}; if (auto *HasValueVal = Env.get<BoolValue>(locForHasValue(*ExpectedLoc))) { // The value may only be accessed if the expected holds a value, and the // error only if it does not. _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
