1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 20:27:45 +00:00

LibJS: Add a special ThrowCompletionOr constructor for OptionalNone

Currently, if you have a fallible function with an Optional return type
and try to return OptionalNone like this:

    ThrowCompletionOr<Optional<SomeType>> { return OptionalNone {}; }

Then ThrowCompletionOr's m_value (whose type is an Optional<ValueType>)
will be set to empty, rather than containing an empty Optional. This is
due to the ThrowCompletionOr's WrappedValueType constructor.

This patch adds a constructor specifically for OptionalNone. If someone
attempts to construct a ThrowCompletionOr with OptionalNone, but the
ValueType is not an Optional, a compile error like the following will
occur:

    ThrowCompletionOr<String> foo() { return OptionalNone {}; }

    error: no matching constructor for initialization of 'AK::String'

Otherwise, it will fill ThrowCompletionOr's m_value with an empty
Optional.
This commit is contained in:
Timothy Flynn 2023-01-19 17:02:26 -05:00 committed by Linus Groh
parent d901a9989d
commit 5349972f41

View file

@ -277,6 +277,11 @@ public:
ThrowCompletionOr(ThrowCompletionOr&&) = default;
ThrowCompletionOr& operator=(ThrowCompletionOr&&) = default;
ThrowCompletionOr(OptionalNone value)
: m_value(ValueType { value })
{
}
// Allows implicit construction of ThrowCompletionOr<T> from a type U if T(U) is a supported constructor.
// Most commonly: Value from Object* or similar, so we can omit the curly braces from "return { TRY(...) };".
// Disabled for POD types to avoid weird conversion shenanigans.