AK: Allow Optional<T> to be used in constant expressions

This commit is contained in:
Jonne Ransijn 2025-04-11 15:55:43 +02:00 committed by Andrew Kaster
commit a059ab4677
Notes: github-actions[bot] 2025-04-23 03:21:35 +00:00
4 changed files with 233 additions and 86 deletions

View file

@ -46,7 +46,7 @@ template<typename>
class Optional; class Optional;
struct OptionalNone { struct OptionalNone {
explicit OptionalNone() = default; explicit constexpr OptionalNone() = default;
}; };
template<typename T, typename Self = Optional<T>> template<typename T, typename Self = Optional<T>>
@ -55,24 +55,24 @@ public:
using ValueType = T; using ValueType = T;
template<SameAs<OptionalNone> V> template<SameAs<OptionalNone> V>
Self& operator=(V) ALWAYS_INLINE constexpr Self& operator=(V)
{ {
static_cast<Self&>(*this).clear(); static_cast<Self&>(*this).clear();
return static_cast<Self&>(*this); return static_cast<Self&>(*this);
} }
[[nodiscard]] ALWAYS_INLINE T* ptr() & [[nodiscard]] ALWAYS_INLINE constexpr T* ptr() &
{ {
return static_cast<Self&>(*this).has_value() ? __builtin_launder(reinterpret_cast<T*>(&static_cast<Self&>(*this).value())) : nullptr; return static_cast<Self&>(*this).has_value() ? __builtin_launder(reinterpret_cast<T*>(&static_cast<Self&>(*this).value())) : nullptr;
} }
[[nodiscard]] ALWAYS_INLINE T const* ptr() const& [[nodiscard]] ALWAYS_INLINE constexpr T const* ptr() const&
{ {
return static_cast<Self const&>(*this).has_value() ? __builtin_launder(reinterpret_cast<T const*>(&static_cast<Self const&>(*this).value())) : nullptr; return static_cast<Self const&>(*this).has_value() ? __builtin_launder(reinterpret_cast<T const*>(&static_cast<Self const&>(*this).value())) : nullptr;
} }
template<typename O = T, typename Fallback = O> template<typename O = T, typename Fallback = O>
[[nodiscard]] ALWAYS_INLINE O value_or(Fallback const& fallback) const& [[nodiscard]] ALWAYS_INLINE constexpr O value_or(Fallback const& fallback) const&
{ {
if (static_cast<Self const&>(*this).has_value()) if (static_cast<Self const&>(*this).has_value())
return static_cast<Self const&>(*this).value(); return static_cast<Self const&>(*this).value();
@ -81,7 +81,7 @@ public:
template<typename O = T, typename Fallback = O> template<typename O = T, typename Fallback = O>
requires(!IsLvalueReference<O> && !IsRvalueReference<O>) requires(!IsLvalueReference<O> && !IsRvalueReference<O>)
[[nodiscard]] ALWAYS_INLINE O value_or(Fallback&& fallback) && [[nodiscard]] ALWAYS_INLINE constexpr O value_or(Fallback&& fallback) &&
{ {
if (static_cast<Self&>(*this).has_value()) if (static_cast<Self&>(*this).has_value())
return move(static_cast<Self&>(*this).value()); return move(static_cast<Self&>(*this).value());
@ -89,7 +89,7 @@ public:
} }
template<typename Callback, typename O = T> template<typename Callback, typename O = T>
[[nodiscard]] ALWAYS_INLINE O value_or_lazy_evaluated(Callback callback) const [[nodiscard]] ALWAYS_INLINE constexpr O value_or_lazy_evaluated(Callback callback) const
{ {
if (static_cast<Self const&>(*this).has_value()) if (static_cast<Self const&>(*this).has_value())
return static_cast<Self const&>(*this).value(); return static_cast<Self const&>(*this).value();
@ -97,7 +97,7 @@ public:
} }
template<typename Callback, typename O = T> template<typename Callback, typename O = T>
[[nodiscard]] ALWAYS_INLINE Optional<O> value_or_lazy_evaluated_optional(Callback callback) const [[nodiscard]] ALWAYS_INLINE constexpr Optional<O> value_or_lazy_evaluated_optional(Callback callback) const
{ {
if (static_cast<Self const&>(*this).has_value()) if (static_cast<Self const&>(*this).has_value())
return static_cast<Self const&>(*this).value(); return static_cast<Self const&>(*this).value();
@ -105,7 +105,7 @@ public:
} }
template<typename Callback, typename O = T> template<typename Callback, typename O = T>
[[nodiscard]] ALWAYS_INLINE ErrorOr<O> try_value_or_lazy_evaluated(Callback callback) const [[nodiscard]] ALWAYS_INLINE constexpr ErrorOr<O> try_value_or_lazy_evaluated(Callback callback) const
{ {
if (static_cast<Self const&>(*this).has_value()) if (static_cast<Self const&>(*this).has_value())
return static_cast<Self const&>(*this).value(); return static_cast<Self const&>(*this).value();
@ -113,21 +113,21 @@ public:
} }
template<typename Callback, typename O = T> template<typename Callback, typename O = T>
[[nodiscard]] ALWAYS_INLINE ErrorOr<Optional<O>> try_value_or_lazy_evaluated_optional(Callback callback) const [[nodiscard]] ALWAYS_INLINE constexpr ErrorOr<Optional<O>> try_value_or_lazy_evaluated_optional(Callback callback) const
{ {
if (static_cast<Self const&>(*this).has_value()) if (static_cast<Self const&>(*this).has_value())
return static_cast<Self const&>(*this).value(); return static_cast<Self const&>(*this).value();
return TRY(callback()); return TRY(callback());
} }
[[nodiscard]] ALWAYS_INLINE T const& operator*() const { return static_cast<Self const&>(*this).value(); } [[nodiscard]] ALWAYS_INLINE constexpr T const& operator*() const { return static_cast<Self const&>(*this).value(); }
[[nodiscard]] ALWAYS_INLINE T& operator*() { return static_cast<Self&>(*this).value(); } [[nodiscard]] ALWAYS_INLINE constexpr T& operator*() { return static_cast<Self&>(*this).value(); }
ALWAYS_INLINE T const* operator->() const { return &static_cast<Self const&>(*this).value(); } ALWAYS_INLINE constexpr T const* operator->() const { return &static_cast<Self const&>(*this).value(); }
ALWAYS_INLINE T* operator->() { return &static_cast<Self&>(*this).value(); } ALWAYS_INLINE constexpr T* operator->() { return &static_cast<Self&>(*this).value(); }
template<typename F, typename MappedType = decltype(declval<F>()(declval<T&>())), auto IsErrorOr = IsSpecializationOf<MappedType, ErrorOr>, typename OptionalType = Optional<ConditionallyResultType<IsErrorOr, MappedType>>> template<typename F, typename MappedType = decltype(declval<F>()(declval<T&>())), auto IsErrorOr = IsSpecializationOf<MappedType, ErrorOr>, typename OptionalType = Optional<ConditionallyResultType<IsErrorOr, MappedType>>>
ALWAYS_INLINE Conditional<IsErrorOr, ErrorOr<OptionalType>, OptionalType> map(F&& mapper) ALWAYS_INLINE constexpr Conditional<IsErrorOr, ErrorOr<OptionalType>, OptionalType> map(F&& mapper)
{ {
if constexpr (IsErrorOr) { if constexpr (IsErrorOr) {
if (static_cast<Self&>(*this).has_value()) if (static_cast<Self&>(*this).has_value())
@ -142,7 +142,7 @@ public:
} }
template<typename F, typename MappedType = decltype(declval<F>()(declval<T&>())), auto IsErrorOr = IsSpecializationOf<MappedType, ErrorOr>, typename OptionalType = Optional<ConditionallyResultType<IsErrorOr, MappedType>>> template<typename F, typename MappedType = decltype(declval<F>()(declval<T&>())), auto IsErrorOr = IsSpecializationOf<MappedType, ErrorOr>, typename OptionalType = Optional<ConditionallyResultType<IsErrorOr, MappedType>>>
ALWAYS_INLINE Conditional<IsErrorOr, ErrorOr<OptionalType>, OptionalType> map(F&& mapper) const ALWAYS_INLINE constexpr Conditional<IsErrorOr, ErrorOr<OptionalType>, OptionalType> map(F&& mapper) const
{ {
if constexpr (IsErrorOr) { if constexpr (IsErrorOr) {
if (static_cast<Self const&>(*this).has_value()) if (static_cast<Self const&>(*this).has_value())
@ -167,13 +167,19 @@ requires(!IsLvalueReference<T>) class [[nodiscard]] Optional<T> : public Optiona
public: public:
using ValueType = T; using ValueType = T;
ALWAYS_INLINE Optional() = default; ALWAYS_INLINE constexpr Optional()
{
construct_null_if_necessary();
}
template<SameAs<OptionalNone> V> template<SameAs<OptionalNone> V>
Optional(V) { } ALWAYS_INLINE constexpr Optional(V)
{
construct_null_if_necessary();
}
template<SameAs<OptionalNone> V> template<SameAs<OptionalNone> V>
Optional& operator=(V) ALWAYS_INLINE constexpr Optional& operator=(V)
{ {
clear(); clear();
return *this; return *this;
@ -183,78 +189,85 @@ public:
AK_MAKE_CONDITIONALLY_NONMOVABLE(Optional, <T>); AK_MAKE_CONDITIONALLY_NONMOVABLE(Optional, <T>);
AK_MAKE_CONDITIONALLY_DESTRUCTIBLE(Optional, <T>); AK_MAKE_CONDITIONALLY_DESTRUCTIBLE(Optional, <T>);
ALWAYS_INLINE Optional(Optional const& other) ALWAYS_INLINE constexpr Optional(Optional const& other)
requires(!IsTriviallyCopyConstructible<T>) requires(!IsTriviallyCopyConstructible<T>)
: m_has_value(other.m_has_value) : m_has_value(other.m_has_value)
{ {
if (other.has_value()) if (other.has_value())
new (&m_storage) T(other.value()); construct_at<RemoveConst<T>>(&m_storage, other.value());
else
construct_null_if_necessary();
} }
ALWAYS_INLINE Optional(Optional&& other) ALWAYS_INLINE constexpr Optional(Optional&& other)
requires(!IsTriviallyMoveConstructible<T>)
: m_has_value(other.m_has_value) : m_has_value(other.m_has_value)
{ {
if (other.has_value()) if (other.has_value())
new (&m_storage) T(other.release_value()); construct_at<RemoveConst<T>>(&m_storage, other.release_value());
else
construct_null_if_necessary();
} }
template<typename U> template<typename U>
requires(IsConstructible<T, U const&> && !IsSpecializationOf<T, Optional> && !IsSpecializationOf<U, Optional> && (!IsLvalueReference<U> || IsTriviallyCopyConstructible<U>)) ALWAYS_INLINE explicit Optional(Optional<U> const& other) requires(IsConstructible<T, U const&> && !IsSpecializationOf<T, Optional> && !IsSpecializationOf<U, Optional> && (!IsLvalueReference<U> || IsTriviallyCopyConstructible<U>)) ALWAYS_INLINE explicit constexpr Optional(Optional<U> const& other)
: m_has_value(other.has_value()) : m_has_value(other.has_value())
{ {
if (other.has_value()) if (other.has_value())
new (&m_storage) T(other.value()); construct_at<RemoveConst<T>>(&m_storage, other.value());
else
construct_null_if_necessary();
} }
template<typename U> template<typename U>
requires(IsConstructible<T, U &&> && !IsSpecializationOf<T, Optional> && !IsSpecializationOf<U, Optional> && (!IsLvalueReference<U> || IsTriviallyMoveConstructible<U>)) ALWAYS_INLINE explicit Optional(Optional<U>&& other) requires(IsConstructible<T, U &&> && !IsSpecializationOf<T, Optional> && !IsSpecializationOf<U, Optional> && (!IsLvalueReference<U> || IsTriviallyMoveConstructible<U>)) ALWAYS_INLINE explicit constexpr Optional(Optional<U>&& other)
: m_has_value(other.has_value()) : m_has_value(other.has_value())
{ {
if (other.has_value()) if (other.has_value())
new (&m_storage) T(other.release_value()); construct_at<RemoveConst<T>>(&m_storage, other.release_value());
else
construct_null_if_necessary();
} }
template<typename U = T> template<typename U = T>
requires(!IsSame<OptionalNone, RemoveCVReference<U>>) requires(!IsSame<OptionalNone, RemoveCVReference<U>>)
ALWAYS_INLINE explicit(!IsConvertible<U&&, T>) Optional(U&& value) ALWAYS_INLINE explicit(!IsConvertible<U&&, T>) constexpr Optional(U&& value)
requires(!IsSame<RemoveCVReference<U>, Optional<T>> && IsConstructible<T, U &&>) requires(!IsSame<RemoveCVReference<U>, Optional<T>> && IsConstructible<T, U &&>)
: m_has_value(true) : m_has_value(true)
{ {
new (&m_storage) T(forward<U>(value)); construct_at<RemoveConst<T>>(&m_storage, forward<U>(value));
} }
ALWAYS_INLINE Optional& operator=(Optional const& other) ALWAYS_INLINE constexpr Optional& operator=(Optional const& other)
requires(!IsTriviallyCopyConstructible<T> || !IsTriviallyDestructible<T>) requires(!IsTriviallyCopyConstructible<T> || !IsTriviallyDestructible<T>)
{ {
if (this != &other) { if (this != &other) {
clear(); clear();
m_has_value = other.m_has_value; m_has_value = other.m_has_value;
if (other.has_value()) { if (other.has_value())
new (&m_storage) T(other.value()); construct_at<RemoveConst<T>>(&m_storage, other.value());
}
} }
return *this; return *this;
} }
ALWAYS_INLINE Optional& operator=(Optional&& other) ALWAYS_INLINE constexpr Optional& operator=(Optional&& other)
{ {
if (this != &other) { if (this != &other) {
clear(); clear();
m_has_value = other.m_has_value; m_has_value = other.m_has_value;
if (other.has_value()) { if (other.has_value())
new (&m_storage) T(other.release_value()); construct_at<RemoveConst<T>>(&m_storage, other.release_value());
}
} }
return *this; return *this;
} }
ALWAYS_INLINE ~Optional() ALWAYS_INLINE constexpr ~Optional()
requires(!IsTriviallyDestructible<T> && IsDestructible<T>) requires(!IsTriviallyDestructible<T> && IsDestructible<T>)
{ {
clear(); clear();
} }
ALWAYS_INLINE void clear() ALWAYS_INLINE constexpr void clear()
{ {
if (m_has_value) { if (m_has_value) {
value().~T(); value().~T();
@ -263,41 +276,41 @@ public:
} }
template<typename... Parameters> template<typename... Parameters>
ALWAYS_INLINE void emplace(Parameters&&... parameters) ALWAYS_INLINE constexpr void emplace(Parameters&&... parameters)
{ {
clear(); clear();
m_has_value = true; m_has_value = true;
new (&m_storage) T(forward<Parameters>(parameters)...); construct_at<RemoveConst<T>>(&m_storage, forward<Parameters>(parameters)...);
} }
template<typename Callable> template<typename Callable>
ALWAYS_INLINE void lazy_emplace(Callable callable) ALWAYS_INLINE constexpr void lazy_emplace(Callable callable)
{ {
clear(); clear();
m_has_value = true; m_has_value = true;
new (&m_storage) T { callable() }; construct_at<RemoveConst<T>>(&m_storage, callable());
} }
[[nodiscard]] ALWAYS_INLINE bool has_value() const { return m_has_value; } [[nodiscard]] ALWAYS_INLINE constexpr bool has_value() const { return m_has_value; }
[[nodiscard]] ALWAYS_INLINE T& value() & [[nodiscard]] ALWAYS_INLINE constexpr T& value() &
{ {
VERIFY(m_has_value); VERIFY(m_has_value);
return *__builtin_launder(reinterpret_cast<T*>(&m_storage)); return m_storage;
} }
[[nodiscard]] ALWAYS_INLINE T const& value() const& [[nodiscard]] ALWAYS_INLINE constexpr T const& value() const&
{ {
VERIFY(m_has_value); VERIFY(m_has_value);
return *__builtin_launder(reinterpret_cast<T const*>(&m_storage)); return m_storage;
} }
[[nodiscard]] ALWAYS_INLINE T value() && [[nodiscard]] ALWAYS_INLINE constexpr T value() &&
{ {
return release_value(); return release_value();
} }
[[nodiscard]] ALWAYS_INLINE T release_value() [[nodiscard]] ALWAYS_INLINE constexpr T release_value()
{ {
VERIFY(m_has_value); VERIFY(m_has_value);
T released_value = move(value()); T released_value = move(value());
@ -307,7 +320,27 @@ public:
} }
private: private:
alignas(T) u8 m_storage[sizeof(T)]; ALWAYS_INLINE constexpr void construct_null_if_necessary(bool should_construct = is_constant_evaluated())
{
// OPTIMIZATION: Only construct the `m_null` member when we are constant-evaluating.
// Otherwise, this generates an unnecessary zero-fill.
#if defined(AK_COMPILER_GCC)
// NOTE: GCCs -Wuninitialized warning ends up checking this as well.
should_construct = true;
#endif
if (should_construct)
construct_at(&m_null);
}
union {
// FIXME: GCC seems to have an issue with uninitialized unions and non trivial types,
// which forces us to have an equally sized trivial null member in the union
// to pseudo-initialize the union.
struct {
u8 _[sizeof(T)];
} m_null;
RemoveConst<T> m_storage;
};
bool m_has_value { false }; bool m_has_value { false };
}; };
@ -325,46 +358,46 @@ requires(IsLvalueReference<T>) class [[nodiscard]] Optional<T> {
public: public:
using ValueType = T; using ValueType = T;
ALWAYS_INLINE Optional() = default; ALWAYS_INLINE constexpr Optional() = default;
template<SameAs<OptionalNone> V> template<SameAs<OptionalNone> V>
Optional(V) { } ALWAYS_INLINE constexpr Optional(V) { }
template<SameAs<OptionalNone> V> template<SameAs<OptionalNone> V>
Optional& operator=(V) ALWAYS_INLINE constexpr Optional& operator=(V)
{ {
clear(); clear();
return *this; return *this;
} }
template<typename U = T> template<typename U = T>
ALWAYS_INLINE Optional(U& value) ALWAYS_INLINE constexpr Optional(U& value)
requires(CanBePlacedInOptional<U&>) requires(CanBePlacedInOptional<U&>)
: m_pointer(&value) : m_pointer(&value)
{ {
} }
ALWAYS_INLINE Optional(RemoveReference<T>& value) ALWAYS_INLINE constexpr Optional(RemoveReference<T>& value)
: m_pointer(&value) : m_pointer(&value)
{ {
} }
template<typename U> template<typename U>
ALWAYS_INLINE Optional(Optional<U>& other) ALWAYS_INLINE constexpr Optional(Optional<U>& other)
requires(CanBePlacedInOptional<U>) requires(CanBePlacedInOptional<U>)
: m_pointer(other.ptr()) : m_pointer(other.ptr())
{ {
} }
template<typename U> template<typename U>
ALWAYS_INLINE Optional(Optional<U> const& other) ALWAYS_INLINE constexpr Optional(Optional<U> const& other)
requires(CanBePlacedInOptional<U const>) requires(CanBePlacedInOptional<U const>)
: m_pointer(other.ptr()) : m_pointer(other.ptr())
{ {
} }
template<typename U> template<typename U>
ALWAYS_INLINE Optional(Optional<U>&& other) ALWAYS_INLINE constexpr Optional(Optional<U>&& other)
requires(CanBePlacedInOptional<U>) requires(CanBePlacedInOptional<U>)
: m_pointer(other.ptr()) : m_pointer(other.ptr())
{ {
@ -372,7 +405,7 @@ public:
} }
template<typename U> template<typename U>
ALWAYS_INLINE Optional& operator=(Optional<U>& other) ALWAYS_INLINE constexpr Optional& operator=(Optional<U>& other)
requires(CanBePlacedInOptional<U>) requires(CanBePlacedInOptional<U>)
{ {
m_pointer = other.ptr(); m_pointer = other.ptr();
@ -380,7 +413,7 @@ public:
} }
template<typename U> template<typename U>
ALWAYS_INLINE Optional& operator=(Optional<U> const& other) ALWAYS_INLINE constexpr Optional& operator=(Optional<U> const& other)
requires(CanBePlacedInOptional<U const>) requires(CanBePlacedInOptional<U const>)
{ {
m_pointer = other.ptr(); m_pointer = other.ptr();
@ -388,7 +421,7 @@ public:
} }
template<typename U> template<typename U>
ALWAYS_INLINE Optional& operator=(Optional<U>&& other) ALWAYS_INLINE constexpr Optional& operator=(Optional<U>&& other)
requires(CanBePlacedInOptional<U> && IsLvalueReference<U>) requires(CanBePlacedInOptional<U> && IsLvalueReference<U>)
{ {
m_pointer = other.m_pointer; m_pointer = other.m_pointer;
@ -398,7 +431,7 @@ public:
template<typename U> template<typename U>
requires(!IsSame<OptionalNone, RemoveCVReference<U>>) requires(!IsSame<OptionalNone, RemoveCVReference<U>>)
ALWAYS_INLINE Optional& operator=(U& value) ALWAYS_INLINE constexpr Optional& operator=(U& value)
requires(CanBePlacedInOptional<U>) requires(CanBePlacedInOptional<U>)
{ {
m_pointer = &value; m_pointer = &value;
@ -412,12 +445,12 @@ public:
requires(CanBePlacedInOptional<U>) requires(CanBePlacedInOptional<U>)
= delete; = delete;
ALWAYS_INLINE void clear() ALWAYS_INLINE constexpr void clear()
{ {
m_pointer = nullptr; m_pointer = nullptr;
} }
[[nodiscard]] ALWAYS_INLINE bool has_value() const { return m_pointer != nullptr; } [[nodiscard]] ALWAYS_INLINE constexpr bool has_value() const { return m_pointer != nullptr; }
[[nodiscard]] ALWAYS_INLINE RemoveReference<T>* ptr() [[nodiscard]] ALWAYS_INLINE RemoveReference<T>* ptr()
{ {
@ -429,20 +462,20 @@ public:
return m_pointer; return m_pointer;
} }
[[nodiscard]] ALWAYS_INLINE T value() [[nodiscard]] ALWAYS_INLINE constexpr T value()
{ {
VERIFY(m_pointer); VERIFY(m_pointer);
return *m_pointer; return *m_pointer;
} }
[[nodiscard]] ALWAYS_INLINE AddConstToReferencedType<T> value() const [[nodiscard]] ALWAYS_INLINE constexpr AddConstToReferencedType<T> value() const
{ {
VERIFY(m_pointer); VERIFY(m_pointer);
return *m_pointer; return *m_pointer;
} }
template<typename U> template<typename U>
requires(IsBaseOf<RemoveCVReference<T>, U>) [[nodiscard]] ALWAYS_INLINE AddConstToReferencedType<T> value_or(U& fallback) const requires(IsBaseOf<RemoveCVReference<T>, U>) [[nodiscard]] ALWAYS_INLINE constexpr AddConstToReferencedType<T> value_or(U& fallback) const
{ {
if (m_pointer) if (m_pointer)
return value(); return value();
@ -450,26 +483,26 @@ public:
} }
// Note that this ends up copying the value. // Note that this ends up copying the value.
[[nodiscard]] ALWAYS_INLINE RemoveCVReference<T> value_or(RemoveCVReference<T> fallback) const [[nodiscard]] ALWAYS_INLINE constexpr RemoveCVReference<T> value_or(RemoveCVReference<T> fallback) const
{ {
if (m_pointer) if (m_pointer)
return value(); return value();
return fallback; return fallback;
} }
[[nodiscard]] ALWAYS_INLINE T release_value() [[nodiscard]] ALWAYS_INLINE constexpr T release_value()
{ {
return *exchange(m_pointer, nullptr); return *exchange(m_pointer, nullptr);
} }
ALWAYS_INLINE AddConstToReferencedType<T> operator*() const { return value(); } ALWAYS_INLINE constexpr AddConstToReferencedType<T> operator*() const { return value(); }
ALWAYS_INLINE T operator*() { return value(); } ALWAYS_INLINE constexpr T operator*() { return value(); }
ALWAYS_INLINE RawPtr<AddConst<RemoveReference<T>>> operator->() const { return &value(); } ALWAYS_INLINE RawPtr<AddConst<RemoveReference<T>>> operator->() const { return &value(); }
ALWAYS_INLINE RawPtr<RemoveReference<T>> operator->() { return &value(); } ALWAYS_INLINE RawPtr<RemoveReference<T>> operator->() { return &value(); }
// Conversion operators from Optional<T&> -> Optional<T>, implicit when T is trivially copyable. // Conversion operators from Optional<T&> -> Optional<T>, implicit when T is trivially copyable.
ALWAYS_INLINE operator Optional<RemoveCVReference<T>>() const ALWAYS_INLINE constexpr operator Optional<RemoveCVReference<T>>() const
requires(IsTriviallyCopyable<RemoveCVReference<T>>) requires(IsTriviallyCopyable<RemoveCVReference<T>>)
{ {
if (has_value()) if (has_value())
@ -478,7 +511,7 @@ public:
} }
// Conversion operators from Optional<T&> -> Optional<T>, explicit when T is not trivially copyable, since this is usually a mistake. // Conversion operators from Optional<T&> -> Optional<T>, explicit when T is not trivially copyable, since this is usually a mistake.
ALWAYS_INLINE explicit operator Optional<RemoveCVReference<T>>() const ALWAYS_INLINE explicit constexpr operator Optional<RemoveCVReference<T>>() const
requires(!IsTriviallyCopyable<RemoveCVReference<T>>) requires(!IsTriviallyCopyable<RemoveCVReference<T>>)
{ {
if (has_value()) if (has_value())
@ -492,7 +525,7 @@ public:
} }
template<typename Callback> template<typename Callback>
[[nodiscard]] ALWAYS_INLINE T value_or_lazy_evaluated(Callback callback) const [[nodiscard]] ALWAYS_INLINE constexpr T value_or_lazy_evaluated(Callback callback) const
{ {
if (m_pointer != nullptr) if (m_pointer != nullptr)
return value(); return value();
@ -500,7 +533,7 @@ public:
} }
template<typename Callback> template<typename Callback>
[[nodiscard]] ALWAYS_INLINE Optional<T> value_or_lazy_evaluated_optional(Callback callback) const [[nodiscard]] ALWAYS_INLINE constexpr Optional<T> value_or_lazy_evaluated_optional(Callback callback) const
{ {
if (m_pointer != nullptr) if (m_pointer != nullptr)
return value(); return value();
@ -508,7 +541,7 @@ public:
} }
template<typename Callback> template<typename Callback>
[[nodiscard]] ALWAYS_INLINE ErrorOr<T> try_value_or_lazy_evaluated(Callback callback) const [[nodiscard]] ALWAYS_INLINE constexpr ErrorOr<T> try_value_or_lazy_evaluated(Callback callback) const
{ {
if (m_pointer != nullptr) if (m_pointer != nullptr)
return value(); return value();
@ -516,7 +549,7 @@ public:
} }
template<typename Callback> template<typename Callback>
[[nodiscard]] ALWAYS_INLINE ErrorOr<Optional<T>> try_value_or_lazy_evaluated_optional(Callback callback) const [[nodiscard]] ALWAYS_INLINE constexpr ErrorOr<Optional<T>> try_value_or_lazy_evaluated_optional(Callback callback) const
{ {
if (m_pointer != nullptr) if (m_pointer != nullptr)
return value(); return value();
@ -524,7 +557,7 @@ public:
} }
template<typename F, typename MappedType = decltype(declval<F>()(declval<T&>())), auto IsErrorOr = IsSpecializationOf<MappedType, ErrorOr>, typename OptionalType = Optional<ConditionallyResultType<IsErrorOr, MappedType>>> template<typename F, typename MappedType = decltype(declval<F>()(declval<T&>())), auto IsErrorOr = IsSpecializationOf<MappedType, ErrorOr>, typename OptionalType = Optional<ConditionallyResultType<IsErrorOr, MappedType>>>
ALWAYS_INLINE Conditional<IsErrorOr, ErrorOr<OptionalType>, OptionalType> map(F&& mapper) ALWAYS_INLINE constexpr Conditional<IsErrorOr, ErrorOr<OptionalType>, OptionalType> map(F&& mapper)
{ {
if constexpr (IsErrorOr) { if constexpr (IsErrorOr) {
if (m_pointer != nullptr) if (m_pointer != nullptr)
@ -539,7 +572,7 @@ public:
} }
template<typename F, typename MappedType = decltype(declval<F>()(declval<T&>())), auto IsErrorOr = IsSpecializationOf<MappedType, ErrorOr>, typename OptionalType = Optional<ConditionallyResultType<IsErrorOr, MappedType>>> template<typename F, typename MappedType = decltype(declval<F>()(declval<T&>())), auto IsErrorOr = IsSpecializationOf<MappedType, ErrorOr>, typename OptionalType = Optional<ConditionallyResultType<IsErrorOr, MappedType>>>
ALWAYS_INLINE Conditional<IsErrorOr, ErrorOr<OptionalType>, OptionalType> map(F&& mapper) const ALWAYS_INLINE constexpr Conditional<IsErrorOr, ErrorOr<OptionalType>, OptionalType> map(F&& mapper) const
{ {
if constexpr (IsErrorOr) { if constexpr (IsErrorOr) {
if (m_pointer != nullptr) if (m_pointer != nullptr)
@ -558,20 +591,20 @@ private:
}; };
template<typename T1, typename T2> template<typename T1, typename T2>
ALWAYS_INLINE bool operator==(Optional<T1> const& first, Optional<T2> const& second) ALWAYS_INLINE constexpr bool operator==(Optional<T1> const& first, Optional<T2> const& second)
{ {
return first.has_value() == second.has_value() return first.has_value() == second.has_value()
&& (!first.has_value() || first.value() == second.value()); && (!first.has_value() || first.value() == second.value());
} }
template<typename T1, typename T2> template<typename T1, typename T2>
ALWAYS_INLINE bool operator==(Optional<T1> const& first, T2 const& second) ALWAYS_INLINE constexpr bool operator==(Optional<T1> const& first, T2 const& second)
{ {
return first.has_value() && first.value() == second; return first.has_value() && first.value() == second;
} }
template<typename T> template<typename T>
ALWAYS_INLINE bool operator==(Optional<T> const& first, OptionalNone) ALWAYS_INLINE constexpr bool operator==(Optional<T> const& first, OptionalNone)
{ {
return !first.has_value(); return !first.has_value();
} }

View file

@ -10,6 +10,7 @@
#include <AK/Platform.h> #include <AK/Platform.h>
#include <AK/StdLibExtraDetails.h> #include <AK/StdLibExtraDetails.h>
#include <memory>
#include <utility> #include <utility>
namespace AK { namespace AK {
@ -31,6 +32,7 @@ requires(AK::Detail::IsIntegral<T>)
template<typename... Args> template<typename... Args>
void compiletime_fail(Args...); void compiletime_fail(Args...);
using std::construct_at;
using std::forward; using std::forward;
using std::move; using std::move;
} }

View file

@ -130,6 +130,9 @@ bool assume(T const& expression, StringView expression_string, SourceLocation lo
return true; return true;
} }
template<typename T>
consteval void expect_consteval(T) { }
} }
#define EXPECT(...) \ #define EXPECT(...) \
@ -179,6 +182,8 @@ bool assume(T const& expression, StringView expression_string, SourceLocation lo
::Test::set_current_test_result(::Test::TestResult::Failed); \ ::Test::set_current_test_result(::Test::TestResult::Failed); \
} while (false) } while (false)
#define EXPECT_CONSTEVAL(...) ::Test::expect_consteval(__VA_ARGS__)
// To use, specify the lambda to execute in a sub process and verify it exits: // To use, specify the lambda to execute in a sub process and verify it exits:
// EXPECT_CRASH("This should fail", []{ // EXPECT_CRASH("This should fail", []{
// return Test::Crash::Failure::DidNotCrash; // return Test::Crash::Failure::DidNotCrash;

View file

@ -18,7 +18,7 @@ class NonCopyable {
AK_MAKE_DEFAULT_MOVABLE(NonCopyable); AK_MAKE_DEFAULT_MOVABLE(NonCopyable);
public: public:
NonCopyable() { } constexpr NonCopyable() { }
~NonCopyable() = default; ~NonCopyable() = default;
int x { 13 }; int x { 13 };
@ -29,7 +29,7 @@ class NonTriviallyCopyable {
AK_MAKE_DEFAULT_MOVABLE(NonTriviallyCopyable); AK_MAKE_DEFAULT_MOVABLE(NonTriviallyCopyable);
public: public:
NonTriviallyCopyable() = default; constexpr NonTriviallyCopyable() = default;
~NonTriviallyCopyable() = default; ~NonTriviallyCopyable() = default;
ByteString x { "13" }; ByteString x { "13" };
@ -40,7 +40,7 @@ class TriviallyCopyable {
AK_MAKE_DEFAULT_MOVABLE(TriviallyCopyable); AK_MAKE_DEFAULT_MOVABLE(TriviallyCopyable);
public: public:
TriviallyCopyable() = default; constexpr TriviallyCopyable() = default;
~TriviallyCopyable() = default; ~TriviallyCopyable() = default;
int x { 13 }; int x { 13 };
@ -144,6 +144,56 @@ TEST_CASE(comparison_with_numeric_types)
EXPECT_NE(opt1, -2); EXPECT_NE(opt1, -2);
} }
TEST_CASE(test_constexpr)
{
int i = 13;
NonCopyable dcm {};
EXPECT_CONSTEVAL(Optional<int> {});
EXPECT_CONSTEVAL(Optional<NonCopyable> {});
EXPECT_CONSTEVAL(Optional<int const> {});
EXPECT_CONSTEVAL(Optional<NonCopyable const> {});
EXPECT_CONSTEVAL(Optional<int&> {});
EXPECT_CONSTEVAL(Optional<NonCopyable&> {});
EXPECT_CONSTEVAL(Optional<int const&> {});
EXPECT_CONSTEVAL(Optional<NonCopyable const&> {});
EXPECT_CONSTEVAL(Optional<int> { 13 });
EXPECT_CONSTEVAL(Optional<NonCopyable> { NonCopyable {} });
EXPECT_CONSTEVAL(Optional<int const> { 13 });
EXPECT_CONSTEVAL(Optional<NonCopyable const> { NonCopyable {} });
EXPECT_CONSTEVAL(Optional<int&> { i });
EXPECT_CONSTEVAL(Optional<NonCopyable&> { dcm });
EXPECT_CONSTEVAL(Optional<int const&> { 13 });
EXPECT_CONSTEVAL(Optional<NonCopyable const&> { NonCopyable {} });
static_assert(!Optional<int> {}.has_value());
static_assert(!Optional<NonCopyable> {}.has_value());
static_assert(!Optional<int const> {}.has_value());
static_assert(!Optional<NonCopyable const> {}.has_value());
static_assert(!Optional<int&> {}.has_value());
static_assert(!Optional<NonCopyable&> {}.has_value());
static_assert(!Optional<int const&> {}.has_value());
static_assert(!Optional<NonCopyable const&> {}.has_value());
static_assert(Optional<int> { 13 }.has_value());
static_assert(Optional<NonCopyable> { NonCopyable {} }.has_value());
static_assert(Optional<int const> { 13 }.has_value());
static_assert(Optional<NonCopyable const> { NonCopyable {} }.has_value());
static_assert(Optional<int&> { i }.has_value());
static_assert(Optional<NonCopyable&> { dcm }.has_value());
static_assert(Optional<int const&> { 13 }.has_value());
static_assert(Optional<NonCopyable const&> { NonCopyable {} }.has_value());
static_assert(Optional<int> { 13 }.value() == 13);
static_assert(Optional<NonCopyable> { NonCopyable {} }.value().x == 13);
static_assert(Optional<int const> { 13 }.value() == 13);
static_assert(Optional<int const&> { 13 }.value() == 13);
static_assert(Optional<NonCopyable const&> { NonCopyable {} }.value().x == 13);
static_assert(!(Optional<int> { 1 } = {}).has_value(), "Assigning a `{}` should clear the Optional, even for scalar types^^");
}
TEST_CASE(test_copy_ctor_and_dtor_called) TEST_CASE(test_copy_ctor_and_dtor_called)
{ {
#ifdef AK_HAVE_CONDITIONALLY_TRIVIAL #ifdef AK_HAVE_CONDITIONALLY_TRIVIAL
@ -293,6 +343,63 @@ TEST_CASE(comparison_reference)
EXPECT_NE(opt1, opt3); EXPECT_NE(opt1, opt3);
} }
TEST_CASE(uninitialized_constructor)
{
static bool was_constructed = false;
struct Internal {
Internal() { was_constructed = true; }
};
struct ShouldNotBeDefaultConstructed {
bool m_default_constructed { true };
Internal m_internal;
ShouldNotBeDefaultConstructed() = default;
ShouldNotBeDefaultConstructed(bool)
: m_default_constructed(false)
{
}
};
static_assert(IsConstructible<ShouldNotBeDefaultConstructed>);
Optional<ShouldNotBeDefaultConstructed> opt;
EXPECT(!was_constructed);
EXPECT(!opt.has_value());
opt = ShouldNotBeDefaultConstructed { true };
EXPECT(was_constructed);
EXPECT(opt.has_value());
EXPECT(!opt.value().m_default_constructed);
}
consteval bool test_constexpr()
{
Optional<int> none;
if (none.has_value())
return false;
Optional<int> x;
x = 3;
if (!x.has_value())
return false;
if (x.value() != 3)
return false;
Optional<int> y;
y = x.release_value();
if (!y.has_value())
return false;
if (y.value() != 3)
return false;
if (x.has_value())
return false;
return true;
}
static_assert(test_constexpr());
template<typename To, typename From> template<typename To, typename From>
struct CheckAssignments; struct CheckAssignments;