// Copyright (c) 2024 Klemens D. Morgenstern // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_COBALT_EXPERIMENTAL_CONTEXT_HPP #define BOOST_COBALT_EXPERIMENTAL_CONTEXT_HPP #include #include #include #include #include #include #include #include namespace boost::cobalt::experimental { template struct context; namespace detail { template struct context_frame : frame, Promise> { boost::context::fiber caller, callee; void (*after_resume)(context_frame *, void *) = nullptr; void * after_resume_p; template requires std::constructible_from context_frame(Args && ... args) : frame(args...) {} template requires (!std::constructible_from && std::is_default_constructible_v) context_frame(Args && ...) {} void resume() { callee = std::move(callee).resume(); if (auto af = std::exchange(after_resume, nullptr)) af(this, after_resume_p); } void destroy() { auto c = std::exchange(callee, {}); this->~context_frame(); } template auto do_resume(void * ) { return +[](context_frame * this_, void * p) { auto aw_ = static_cast(p); auto h = std::coroutine_handle::from_address(this_) ; aw_->await_suspend(h); }; } template auto do_resume(bool * ) { return +[](context_frame * this_, void * p) { auto aw_ = static_cast(p); auto h = std::coroutine_handle::from_address(this_) ; if (!aw_->await_suspend(h)) h.resume(); }; } template auto do_resume(std::coroutine_handle * ) { return +[](context_frame * this_, void * p) { auto aw_ = static_cast(p); auto h = std::coroutine_handle::from_address(this_) ; aw_->await_suspend(h).resume(); }; } template auto do_await(Awaitable aw) { if (!aw.await_ready()) { after_resume_p = & aw; after_resume = do_resume( static_cast>()))*>(nullptr) ); caller = std::move(caller).resume(); } return aw.await_resume(); } template context get_context() { return context{this}; } }; template struct stack_allocator : boost::context::fixedsize_stack {}; template requires requires {Promise::operator new(std::size_t{});} struct stack_allocator { boost::context::stack_context allocate() { const auto size = Traits::default_size(); const auto p = Promise::operator new(size); boost::context::stack_context sctx; sctx.size = size; sctx.sp = static_cast< char * >( p) + sctx.size; return sctx; } void deallocate( boost::context::stack_context & sctx) noexcept { void * vp = static_cast< char * >( sctx.sp) - sctx.size; Promise::operator delete(vp, sctx.size); } }; template requires requires {Promise::operator new(std::size_t{}, std::decay_t()...);} struct stack_allocator { std::tuple args; boost::context::stack_context allocate() { const auto size = Traits::default_size(); const auto p = std::apply( [size](auto & ... args_) { return Promise::operator new(size, args_...); }, args); boost::context::stack_context sctx; sctx.size = size; sctx.sp = static_cast< char * >( p) + sctx.size; return sctx; } void deallocate( boost::context::stack_context & sctx) noexcept { void * vp = static_cast< char * >( sctx.sp) - sctx.size; Promise::operator delete(vp, sctx.size); } }; struct await_transform_base { struct dummy {}; void await_transform(dummy); }; template struct await_transform_impl : await_transform_base, T { }; template concept has_await_transform = ! requires (await_transform_impl & p) {p.await_transform(await_transform_base::dummy{});}; template void do_return(std::true_type /* is_void */, Promise& promise, Context ctx, Func && func, Args && ... args) { std::forward(func)(ctx, std::forward(args)...); promise.return_void(); } template void do_return(std::false_type /* is_void */, Promise& promise, Context ctx, Func && func, Args && ... args) { promise.return_value(std::forward(func)(ctx, std::forward(args)...)); } } template struct context { using return_type = Return; using promise_type = typename std::coroutine_traits::promise_type; promise_type & promise() {return frame_->promise;} const promise_type & promise() const {return frame_->promise;} template requires std::same_as::promise_type> constexpr operator context() const { return {frame_}; } template requires (detail::has_await_transform && requires (promise_type & pro, Awaitable && aw) { {pro.await_transform(std::forward(aw))} -> awaitable_type; }) auto await(Awaitable && aw) { return frame_->do_await(frame_->promise.await_transform(std::forward(aw))); } template requires (detail::has_await_transform && requires (promise_type & pro, Awaitable && aw) { {pro.await_transform(std::forward(aw).operator co_await())} -> awaitable_type; }) auto await(Awaitable && aw) { return frame_->do_await(frame_->promise.await_transform(std::forward(aw)).operator co_await()); } template requires (detail::has_await_transform && requires (promise_type & pro, Awaitable && aw) { {operator co_await(pro.await_transform(std::forward(aw)))} -> awaitable_type; }) auto await(Awaitable && aw) { return frame_->do_await(operator co_await(frame_->promise.await_transform(std::forward(aw)))); } template Awaitable> requires (!detail::has_await_transform ) auto await(Awaitable && aw) { return frame_->do_await(std::forward(aw)); } template requires (!detail::has_await_transform && requires (Awaitable && aw) {{operator co_await(std::forward(aw))} -> awaitable_type;}) auto await(Awaitable && aw) { return frame_->do_await(operator co_await(std::forward(aw))); } template requires (!detail::has_await_transform && requires (Awaitable && aw) {{std::forward(aw).operator co_await()} -> awaitable_type;}) auto await(Awaitable && aw) { return frame_->do_await(std::forward(aw).operator co_await()); } template requires requires (promise_type & pro, Yield && value) {{pro.yield_value(std::forward(value))} -> awaitable_type;} auto yield(Yield && value) { frame_->do_await(frame_->promise.yield_value(std::forward(value))); } private: context(detail::context_frame * frame) : frame_(frame) {} template friend struct context; //template friend struct detail::context_frame; detail::context_frame * frame_; }; template, Args...> Func, typename StackAlloc> auto make_context(Func && func, std::allocator_arg_t, StackAlloc && salloc, Args && ... args) { auto sctx_ = salloc.allocate(); using promise_type = typename std::coroutine_traits::promise_type; void * p = static_cast(sctx_.sp) - sizeof(detail::context_frame); auto sz = sctx_.size - sizeof(detail::context_frame); if (auto diff = reinterpret_cast(p) % alignof(detail::context_frame); diff != 0u) { p = static_cast(p) - diff; sz -= diff; } boost::context::preallocated psc{p, sz, sctx_}; auto f = new (p) detail::context_frame(args...); auto res = f->promise.get_return_object(); constexpr auto is_always_lazy = requires (promise_type & pro) {{pro.initial_suspend()} -> std::same_as;} && noexcept(f->promise.initial_suspend()); struct invoker { detail::context_frame * frame; mutable Func func; mutable std::tuple args; invoker(detail::context_frame * frame, Func && func, Args && ... args) : frame(frame), func(std::forward(func)), args(std::forward(args)...) { } boost::context::fiber operator()(boost::context::fiber && f) const { auto & promise = frame->promise; frame->caller = std::move(f); try { if (!is_always_lazy) frame->do_await(promise.initial_suspend()); std::apply( [&](auto && ... args_) { auto ctx = frame->template get_context(); using return_type = decltype(std::forward(func)(ctx, std::forward(args_)...)); detail::do_return(std::is_void{}, frame->promise, ctx, std::forward(func), std::forward(args_)...); }, std::move(args)); } catch (boost::context::detail::forced_unwind &) { throw; } catch (...) {promise.unhandled_exception();} static_assert(noexcept(promise.final_suspend())); frame->do_await(promise.final_suspend()); return std::move(frame->caller); } }; f->callee = boost::context::fiber{ std::allocator_arg, psc, std::forward(salloc), invoker(f, std::forward(func), std::forward(args)...)}; if constexpr (is_always_lazy) f->promise.initial_suspend(); else f->resume(); return res; } template, Args...> Func> auto make_context(Func && func, Args && ... args) { return make_context(std::forward(func), std::allocator_arg, boost::context::fixedsize_stack(), std::forward(args)...); } template auto make_context(Func && func, std::allocator_arg_t, StackAlloc && salloc, Args && ... args) { return make_context>::return_type>( std::forward(func), std::allocator_arg, std::forward(salloc), std::forward(args)... ); } template auto make_context(Func && func, Args && ... args) { return make_context>::return_type>( std::forward(func), std::forward(args)... ); } } #endif //BOOST_COBALT_EXPERIMENTAL_CONTEXT_HPP