| 1 |
//===----------------------------------------------------------------------===// |
| 2 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 3 |
// See https://llvm.org/LICENSE.txt for license information. |
| 4 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 5 |
// |
| 6 |
//===----------------------------------------------------------------------===// |
| 7 |
|
| 8 |
// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20 |
| 9 |
|
| 10 |
// constexpr bool has_value() const noexcept; |
| 11 |
|
| 12 |
#include <cassert> |
| 13 |
#include <concepts> |
| 14 |
#include <expected> |
| 15 |
#include <optional> |
| 16 |
#include <type_traits> |
| 17 |
#include <utility> |
| 18 |
|
| 19 |
#include "test_macros.h" |
| 20 |
#include "../../types.h" |
| 21 |
|
| 22 |
// Test noexcept |
| 23 |
template <class T> |
| 24 |
concept HasValueNoexcept = |
| 25 |
requires(T t) { |
| 26 |
{ t.has_value() } noexcept; |
| 27 |
}; |
| 28 |
|
| 29 |
struct Foo {}; |
| 30 |
static_assert(!HasValueNoexcept<Foo>); |
| 31 |
|
| 32 |
static_assert(HasValueNoexcept<std::expected<int, int>>); |
| 33 |
static_assert(HasValueNoexcept<const std::expected<int, int>>); |
| 34 |
|
| 35 |
constexpr bool test() { |
| 36 |
// has_value |
| 37 |
{ |
| 38 |
const std::expected<int, int> e(5); |
| 39 |
assert(e.has_value()); |
| 40 |
} |
| 41 |
|
| 42 |
// !has_value |
| 43 |
{ |
| 44 |
const std::expected<int, int> e(std::unexpect, 5); |
| 45 |
assert(!e.has_value()); |
| 46 |
} |
| 47 |
|
| 48 |
// The following tests check that the "has_value" flag is not overwritten |
| 49 |
// by the constructor of the value. This could happen because the flag is |
| 50 |
// stored in the tail padding of the value. |
| 51 |
// |
| 52 |
// The first test is a simplified version of the real code where this was |
| 53 |
// first observed. |
| 54 |
// |
| 55 |
// The other tests use a synthetic struct that clobbers its tail padding |
| 56 |
// on construction, making the issue easier to reproduce. |
| 57 |
// |
| 58 |
// See https://github.com/llvm/llvm-project/issues/68552 and the linked PR. |
| 59 |
{ |
| 60 |
auto f1 = []() -> std::expected<std::optional<int>, long> { return 0; }; |
| 61 |
|
| 62 |
auto f2 = [&f1]() -> std::expected<std::optional<int>, int> { |
| 63 |
return f1().transform_error([](auto) { return 0; }); |
| 64 |
}; |
| 65 |
|
| 66 |
auto e = f2(); |
| 67 |
assert(e.has_value()); |
| 68 |
} |
| 69 |
{ |
| 70 |
const std::expected<TailClobberer<0>, bool> e = {}; |
| 71 |
// clang-cl does not support [[no_unique_address]] yet. |
| 72 |
#if !(defined(TEST_COMPILER_CLANG) && defined(_MSC_VER)) |
| 73 |
LIBCPP_STATIC_ASSERT(sizeof(TailClobberer<0>) == sizeof(e)); |
| 74 |
#endif |
| 75 |
assert(e.has_value()); |
| 76 |
} |
| 77 |
|
| 78 |
return true; |
| 79 |
} |
| 80 |
|
| 81 |
int main(int, char**) { |
| 82 |
test(); |
| 83 |
static_assert(test()); |
| 84 |
return 0; |
| 85 |
} |