ladybird/AK/Try.h
Andreas Kling cc4b3cbacc
Some checks are pending
CI / Lagom (false, FUZZ, ubuntu-24.04, Linux, Clang) (push) Waiting to run
CI / Lagom (false, NO_FUZZ, macos-14, macOS, Clang) (push) Waiting to run
CI / Lagom (false, NO_FUZZ, ubuntu-24.04, Linux, GNU) (push) Waiting to run
CI / Lagom (true, NO_FUZZ, ubuntu-24.04, Linux, Clang) (push) Waiting to run
Package the js repl as a binary artifact / build-and-package (macos-14, macOS, macOS-universal2) (push) Waiting to run
Package the js repl as a binary artifact / build-and-package (ubuntu-24.04, Linux, Linux-x86_64) (push) Waiting to run
Run test262 and test-wasm / run_and_update_results (push) Waiting to run
Lint Code / lint (push) Waiting to run
Push notes / build (push) Waiting to run
Meta: Update my e-mail address everywhere
2024-10-04 13:19:50 +02:00

45 lines
2.7 KiB
C

/*
* Copyright (c) 2021, Andreas Kling <andreas@ladybird.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Diagnostics.h>
#include <AK/StdLibExtras.h>
// NOTE: This macro works with any result type that has the expected APIs.
// It's designed with AK::Result and AK::Error in mind.
//
// 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
//
// 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.
#define TRY(expression) \
({ \
/* Ignore -Wshadow to allow nesting the macro. */ \
AK_IGNORE_DIAGNOSTIC("-Wshadow", \
auto&& _temporary_result = (expression)); \
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(); \
})
#define MUST(expression) \
({ \
/* Ignore -Wshadow to allow nesting the macro. */ \
AK_IGNORE_DIAGNOSTIC("-Wshadow", \
auto&& _temporary_result = (expression)); \
static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
"Do not return a reference from a fallible expression"); \
VERIFY(!_temporary_result.is_error()); \
_temporary_result.release_value(); \
})