2021-09-05 07:32:15 -04:00
|
|
|
/*
|
2024-10-04 07:19:50 -04:00
|
|
|
* Copyright (c) 2021, Andreas Kling <andreas@ladybird.org>
|
2021-09-05 07:32:15 -04:00
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
2022-12-06 13:19:37 -05:00
|
|
|
#include <AK/Diagnostics.h>
|
2023-01-14 18:34:44 -05:00
|
|
|
#include <AK/StdLibExtras.h>
|
2022-12-06 13:19:37 -05:00
|
|
|
|
2024-11-30 10:29:25 -05:00
|
|
|
// This macro is redefined in `AK/Format.h` to give a nicer error message.
|
|
|
|
#define AK_HANDLE_UNEXPECTED_ERROR(result) VERIFY(!result.is_error());
|
|
|
|
|
2021-09-05 07:32:15 -04:00
|
|
|
// NOTE: This macro works with any result type that has the expected APIs.
|
2021-11-07 18:51:39 -05:00
|
|
|
// It's designed with AK::Result and AK::Error in mind.
|
2022-10-16 12:54:30 -04:00
|
|
|
//
|
|
|
|
// It depends on a non-standard C++ extension, specifically
|
|
|
|
// on statement expressions [1]. This is known to be implemented
|
|
|
|
// by at least clang and gcc.
|
|
|
|
// [1] https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
|
2023-01-13 15:48:09 -05:00
|
|
|
//
|
|
|
|
// If the static_assert below is triggered, it means you tried to return a reference
|
|
|
|
// from a fallible expression. This will not do what you want; the statement expression
|
|
|
|
// will create a copy regardless, so it is explicitly disallowed.
|
2021-09-05 07:32:15 -04:00
|
|
|
|
2024-11-17 05:21:20 -05:00
|
|
|
#define TRY(...) \
|
2023-01-14 18:34:44 -05:00
|
|
|
({ \
|
|
|
|
/* Ignore -Wshadow to allow nesting the macro. */ \
|
|
|
|
AK_IGNORE_DIAGNOSTIC("-Wshadow", \
|
2024-11-17 05:21:20 -05:00
|
|
|
auto&& _temporary_result = (__VA_ARGS__)); \
|
2023-01-14 18:34:44 -05:00
|
|
|
static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
|
|
|
|
"Do not return a reference from a fallible expression"); \
|
|
|
|
if (_temporary_result.is_error()) [[unlikely]] \
|
|
|
|
return _temporary_result.release_error(); \
|
|
|
|
_temporary_result.release_value(); \
|
2021-09-05 07:32:15 -04:00
|
|
|
})
|
2021-11-10 05:54:54 -05:00
|
|
|
|
2024-11-17 05:21:20 -05:00
|
|
|
#define MUST(...) \
|
2023-01-14 18:34:44 -05:00
|
|
|
({ \
|
|
|
|
/* Ignore -Wshadow to allow nesting the macro. */ \
|
|
|
|
AK_IGNORE_DIAGNOSTIC("-Wshadow", \
|
2024-11-17 05:21:20 -05:00
|
|
|
auto&& _temporary_result = (__VA_ARGS__)); \
|
2023-01-14 18:34:44 -05:00
|
|
|
static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
|
|
|
|
"Do not return a reference from a fallible expression"); \
|
2024-11-30 10:29:25 -05:00
|
|
|
AK_HANDLE_UNEXPECTED_ERROR(_temporary_result) \
|
2023-01-14 18:34:44 -05:00
|
|
|
_temporary_result.release_value(); \
|
2021-11-10 05:54:54 -05:00
|
|
|
})
|