Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix coroutine continuation cleanup #181

Merged
merged 4 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 41 additions & 10 deletions support-lib/cpp/Future.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

#pragma once

#include "expected.hpp"

#include <atomic>
#include <functional>
#include <memory>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I find I have to change the feature detection to the following to make it work in c++17 + -fcoroutine-ts

#if defined(__cpp_coroutines) && __has_include(<experimental/coroutine>)
    #include <experimental/coroutine>
    namespace djinni::detail {
        template <typename Promise = void> using CoroutineHandle = std::experimental::coroutine_handle<Promise>;
        using SuspendNever = std::experimental::suspend_never;
    }
    #define DJINNI_FUTURE_HAS_COROUTINE_SUPPORT 1
#elif defined(__cpp_impl_coroutine) && __has_include(<coroutine>)
    #include <coroutine>
    namespace djinni::detail {
        template <typename Promise = void> using CoroutineHandle = std::coroutine_handle<Promise>;
        using SuspendNever = std::suspend_never;
    }
    #define DJINNI_FUTURE_HAS_COROUTINE_SUPPORT 1
#endif

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like with these settings the <coroutine> header is available but not functional. Your suggestion fixes that nicely, but I found another issue: with clang 16 and -std=c++20 -stdlib=libc++, it chooses the experimental implementation even though the proper one is available.

I've done some experiments:

  • __cpp_coroutines is available for both C++20 and C++17 + -fcoroutines-ts until clang 17 when the macro and -fcoroutines-ts were completely removed
  • __cpp_impl_coroutine and __cpp_lib_coroutine are only available in proper C++20 mode when we have <coroutine>

I've just pushed another suggestion based on these findings. Here's what I used to test it with a few compilers/settings: https://godbolt.org/z/rj737E5eq

Caveat: I've tested only with clang. For iOS and Android that seems to be the relevant compiler.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks! this works really well.

Expand Down Expand Up @@ -364,34 +366,63 @@ class Future {
return true;
}

template<typename ConcretePromise>
struct PromiseTypeBase {
Promise<T> _promise;
std::optional<djinni::expected<T, std::exception_ptr>> _result{};

struct FinalAwaiter {
constexpr bool await_ready() const noexcept {
return false;
}
bool await_suspend(std::coroutine_handle<ConcretePromise> finished) const noexcept {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use the alias detail::CoroutineHandle for now

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done 👍

auto& promise_type = finished.promise();
if (*promise_type._result) {
if constexpr (std::is_void_v<T>) {
promise_type._promise.setValue();
} else {
promise_type._promise.setValue(std::move(**promise_type._result));
}
} else {
promise_type._promise.setException(std::move(promise_type._result->error()));
}
return false;
}
constexpr void await_resume() const noexcept {}
};

detail::SuspendNever initial_suspend() { return {}; }
detail::SuspendNever final_suspend() noexcept { return {}; }
constexpr detail::SuspendNever initial_suspend() const noexcept { return {}; }
FinalAwaiter final_suspend() const noexcept { return {}; }

Future<T> get_return_object() noexcept {
return _promise.getFuture();
}
void unhandled_exception() {
_promise.setException(std::current_exception());
_result.emplace(djinni::unexpect, std::current_exception());
}
};
template <typename U>
struct PromiseType: PromiseTypeBase{
template <typename V>

struct PromiseType: PromiseTypeBase<PromiseType>{
template <typename V, typename = std::enable_if_t<std::is_convertible_v<V, T>>>
void return_value(V&& value) {
this->_promise.setValue(std::forward<V>(value));
this->_result.emplace(std::forward<V>(value));
}
void return_value(T&& value) {
this->_result.emplace(std::move(value));
}
void return_value(const T& value) {
this->_result.emplace(value);
}
};
using promise_type = PromiseType<T>;
using promise_type = PromiseType;
#endif
};

#if defined(DJINNI_FUTURE_HAS_COROUTINE_SUPPORT)
template<> template<> struct Future<void>::PromiseType<void>:PromiseTypeBase {
template<>
struct Future<void>::PromiseType : PromiseTypeBase<PromiseType> {
void return_void() {
this->_promise.setValue();
_result.emplace();
}
};
#endif
Expand Down
2 changes: 2 additions & 0 deletions support-lib/cpp/expected.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ namespace djinni {

using ::std::expected;
using ::std::unexpected;
inline constexpr ::std::unexpect_t unexpect{};

}

Expand All @@ -28,6 +29,7 @@ namespace djinni {

using ::tl::unexpected;
using ::tl::expected;
inline constexpr ::tl::unexpect_t unexpect{};

}

Expand Down
70 changes: 70 additions & 0 deletions test-suite/handwritten-src/objc/tests/DBCppFutureTests.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#import <Foundation/Foundation.h>
#import <XCTest/XCTest.h>

#include <Future.hpp>

#ifdef DJINNI_FUTURE_HAS_COROUTINE_SUPPORT

namespace {

template<typename Functor>
struct OnCleanup {
OnCleanup(Functor&& functor)
:functor{std::move(functor)}
{}
~OnCleanup() {
functor();
}
Functor functor;
};

djinni::Future<void> inner_coroutine(std::vector<int>& cleanup_ids, int id, djinni::Future<void> suspendOn) {
OnCleanup cleanup{
[&] {
cleanup_ids.push_back(id);
}
};

co_await suspendOn;
co_return; // do not remove!
}

djinni::Future<void> outer_coroutine(std::vector<int>& cleanup_ids, int id, djinni::Future<void> suspendOn) {
OnCleanup cleanup{
[&] {
cleanup_ids.push_back(id);
}
};

co_await inner_coroutine(cleanup_ids, id + 1, std::move(suspendOn));
co_return; // do not remove!
}

}

#endif

@interface DBCppFutureTests : XCTestCase
@end

@implementation DBCppFutureTests

#ifdef DJINNI_FUTURE_HAS_COROUTINE_SUPPORT
- (void) testFutureCoroutines_cleanupOrder {
std::vector<int> cleanupIds{};

djinni::Promise<void> djinniPromise{};

auto coroutineFuture = outer_coroutine(cleanupIds, 0, djinniPromise.getFuture());
XCTAssertFalse(coroutineFuture.isReady());

djinniPromise.setValue();
XCTAssertTrue(coroutineFuture.isReady());

XCTAssertEqual(cleanupIds.size(), 2);
XCTAssertEqual(cleanupIds[0], 1); // the inner coroutine should be cleaned up first
XCTAssertEqual(cleanupIds[1], 0); // ... then the outer
}
#endif

@end
Loading