TLA Line data Source code
1 : //
2 : // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3 : // Copyright (c) 2026 Michael Vandeberg
4 : //
5 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
6 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 : //
8 : // Official repository: https://github.com/cppalliance/capy
9 : //
10 :
11 : #ifndef BOOST_CAPY_EX_CONTEXT_AWAITABLE_PROMISE_BASE_HPP
12 : #define BOOST_CAPY_EX_CONTEXT_AWAITABLE_PROMISE_BASE_HPP
13 :
14 : #include <boost/capy/detail/config.hpp>
15 : #include <boost/capy/ex/abandon.hpp>
16 : #include <boost/capy/ex/await_context.hpp>
17 : #include <boost/capy/detail/context_awaiter.hpp>
18 : #include <boost/capy/ex/frame_alloc_mixin.hpp>
19 : #include <boost/capy/ex/frame_allocator.hpp>
20 : #include <boost/capy/ex/this_coro.hpp>
21 :
22 : #include <coroutine>
23 : #include <memory_resource>
24 : #include <stop_token>
25 : #include <type_traits>
26 :
27 : namespace boost {
28 : namespace capy {
29 :
30 : /** Give a promise frame allocation and environment propagation to I/O awaitables.
31 :
32 : Inherit from this class to enable these capabilities in your coroutine:
33 :
34 : 1. **Frame allocation**: the mixin provides `operator new/delete` that
35 : use the current frame allocator (see
36 : @ref get_current_frame_allocator).
37 :
38 : 2. **Environment storage** — The mixin stores a pointer to the `await_context`
39 : containing the executor, stop token, and allocator for this coroutine.
40 :
41 : 3. **Environment access** — Coroutine code can retrieve the environment
42 : via `co_await this_coro::environment`, or individual fields via
43 : `co_await this_coro::executor`, `co_await this_coro::stop_token`,
44 : and `co_await this_coro::frame_allocator`.
45 :
46 : 4. **Environment propagation** — Each @ref ContextAwaitable the
47 : coroutine awaits receives that environment.
48 :
49 : @par Basic Usage
50 :
51 : For coroutines that need to access their execution environment:
52 :
53 : @par !example example_1
54 :
55 :
56 : @par Custom Awaitable Transformation
57 :
58 : If your promise needs to transform awaitables (e.g., for affinity or
59 : logging), override `transform_awaitable` instead of `await_transform`.
60 : Hand @ref ContextAwaitable types on to the base's
61 : `transform_awaitable` so they still receive the environment:
62 :
63 : @par !example example_2
64 :
65 :
66 : The mixin's `await_transform` intercepts @ref this_coro::environment_tag
67 : and the fine-grained tag types (@ref this_coro::executor_tag,
68 : @ref this_coro::stop_token_tag, @ref this_coro::frame_allocator_tag),
69 : then delegates all other awaitables to your `transform_awaitable`.
70 :
71 : @par Making Your Coroutine a ContextAwaitable
72 :
73 : The mixin handles the "inside the coroutine" part—accessing the
74 : environment. To receive the environment when your coroutine is awaited
75 : (satisfying @ref ContextAwaitable), implement the `await_suspend` overload
76 : on your coroutine return type:
77 :
78 : @par !example example_3
79 :
80 :
81 : @par Ownership
82 : The object that awaits a coroutine, such as the parent's `task`,
83 : owns its frame. A chain is therefore destroyed from its top down,
84 : each frame freeing the one it awaits. The suspended coroutine at the
85 : bottom is held by whoever will resume it: an operation, queue or
86 : primitive. A holder that will never resume it calls @ref abandon,
87 : which unwinds the chain's segment from its owner (see
88 : @ref chain_owner) rather than destroying the bottom frame.
89 : Destroying a frame that is still awaited, other than in that
90 : unwind, calls `std::terminate`.
91 :
92 : @par Thread Safety
93 : The environment is stored before the coroutine's body runs, from
94 : `await_suspend` or the promise's constructor, and read during
95 : `co_await this_coro::environment`. These occur on the same logical
96 : thread of execution, so no synchronization is required.
97 :
98 : @note A chain waiting on a primitive stored in its own frames owns
99 : itself through that primitive. Only a stop request or a signal on
100 : the primitive frees it.
101 :
102 : @note A mutex must outlive every coroutine holding or handed its
103 : lock.
104 :
105 : @note A cross-thread `wake()` racing the teardown of an armed
106 : waker's frame on its executor thread is a precondition violation.
107 :
108 : @tparam Derived The derived promise type (CRTP pattern).
109 :
110 : @see @ref this_coro::environment, @ref this_coro::executor,
111 : @ref this_coro::stop_token, @ref this_coro::frame_allocator
112 : @see @ref await_context
113 : @see @ref ContextAwaitable
114 : */
115 : template<typename Derived>
116 : class context_awaitable_promise_base
117 : : public frame_alloc_mixin
118 : {
119 : await_context const* env_ = nullptr;
120 : mutable std::coroutine_handle<> cont_{std::noop_coroutine()};
121 :
122 : public:
123 : /** Store the continuation to resume on completion.
124 :
125 : Call this from your coroutine type's `await_suspend` overload
126 : to set up the completion path. Your `final_suspend` awaiter
127 : should return `continuation()` by symmetric transfer.
128 :
129 : @param cont The continuation to resume on completion.
130 : */
131 HIT 108201 : void set_continuation(std::coroutine_handle<> cont) noexcept
132 : {
133 108201 : cont_ = cont;
134 108201 : }
135 :
136 : /** Return and consume the stored continuation handle.
137 :
138 : Resets the stored handle to `std::noop_coroutine()`, so a second
139 : call returns a no-op handle.
140 :
141 : @return The continuation for symmetric transfer.
142 : */
143 5607 : std::coroutine_handle<> continuation() const noexcept
144 : {
145 5607 : return std::exchange(cont_, std::noop_coroutine());
146 : }
147 :
148 : /** Store a pointer to the execution environment.
149 :
150 : Call this before the coroutine's body runs. The environment then
151 : reaches `co_await this_coro::environment` and each awaited
152 : @ref ContextAwaitable. Call it from your coroutine type's
153 : `await_suspend` overload when it receives the environment from
154 : the awaiting coroutine. Call it from the promise's constructor
155 : when the promise holds its own. The pointed-to `await_context`
156 : must outlive this coroutine.
157 :
158 : @param env The environment to store.
159 : */
160 108288 : void set_environment(await_context const* env) noexcept
161 : {
162 108288 : env_ = env;
163 108288 : }
164 :
165 : /** Return the stored execution environment.
166 :
167 : @pre @ref set_environment has been called with a non-null
168 : pointer.
169 :
170 : @return The environment.
171 : */
172 222917 : await_context const* environment() const noexcept
173 : {
174 222917 : BOOST_CAPY_ASSERT(env_);
175 222917 : return env_;
176 : }
177 :
178 : /** Transform an awaitable before co_await.
179 :
180 : The default wraps a @ref ContextAwaitable so that it receives
181 : this coroutine's environment when the coroutine suspends on it.
182 : The wrapper also reinstalls the frame allocator when the
183 : coroutine resumes. The awaitable is moved or copied into the
184 : wrapper, so an lvalue is awaited as a copy. A move-only
185 : awaitable must be passed as an rvalue. The wrapper also works
186 : around compilers that miscompile
187 : symmetric transfer, so a promise relying on the default need
188 : not. Any other awaitable passes through unchanged. Override
189 : this in your derived promise type to customize how awaitables
190 : are transformed; an override that still awaits
191 : @ref ContextAwaitable types passes them to this function.
192 :
193 : @pre @ref set_environment has been called, if `A` satisfies
194 : @ref ContextAwaitable. A promise that receives its environment
195 : when awaited calls it from its `await_suspend`, before the body
196 : runs. A promise that holds its own environment calls it from
197 : its constructor.
198 :
199 : @note An exception from a wrapped awaitable's `await_ready` or
200 : `await_suspend` calls `std::terminate`.
201 :
202 : @param a The awaitable expression from `co_await a`.
203 :
204 : @return The transformed awaitable.
205 : */
206 : template<typename A>
207 4 : decltype(auto) transform_awaitable(A&& a)
208 : {
209 : if constexpr (ContextAwaitable<std::decay_t<A>>)
210 : return detail::context_awaiter<
211 : std::decay_t<A>, context_awaitable_promise_base>{
212 3 : std::forward<A>(a), this};
213 : else
214 1 : return std::forward<A>(a);
215 : }
216 :
217 : /** Intercept co_await expressions.
218 :
219 : This function handles @ref this_coro::environment_tag and
220 : the fine-grained tags (@ref this_coro::executor_tag,
221 : @ref this_coro::stop_token_tag, @ref this_coro::frame_allocator_tag)
222 : specially, returning an awaiter that yields the stored value.
223 : All other awaitables are delegated to @ref transform_awaitable.
224 :
225 : @pre @ref set_environment has been called with a non-null
226 : pointer, if `T` is one of the tag types.
227 :
228 : @param t The awaited expression.
229 :
230 : @return An awaiter for the expression.
231 : */
232 : template<typename T>
233 108405 : auto await_transform(T&& t)
234 : {
235 : using Tag = std::decay_t<T>;
236 :
237 : if constexpr (std::is_same_v<Tag, this_coro::environment_tag>)
238 : {
239 24 : BOOST_CAPY_ASSERT(env_);
240 : struct awaiter
241 : {
242 : await_context const* env_;
243 22 : bool await_ready() const noexcept { return true; }
244 2 : void await_suspend(std::coroutine_handle<>) const noexcept { }
245 21 : await_context const* await_resume() const noexcept { return env_; }
246 : };
247 24 : return awaiter{env_};
248 : }
249 : else if constexpr (std::is_same_v<Tag, this_coro::executor_tag>)
250 : {
251 4 : BOOST_CAPY_ASSERT(env_);
252 : struct awaiter
253 : {
254 : executor_ref executor_;
255 3 : bool await_ready() const noexcept { return true; }
256 : void await_suspend(std::coroutine_handle<>) const noexcept { } // LCOV_EXCL_LINE await_ready() always true, never suspends
257 3 : executor_ref await_resume() const noexcept { return executor_; }
258 : };
259 4 : return awaiter{env_->executor};
260 : }
261 : else if constexpr (std::is_same_v<Tag, this_coro::stop_token_tag>)
262 : {
263 26 : BOOST_CAPY_ASSERT(env_);
264 : struct awaiter
265 : {
266 : std::stop_token token_;
267 25 : bool await_ready() const noexcept { return true; }
268 : void await_suspend(std::coroutine_handle<>) const noexcept { } // LCOV_EXCL_LINE await_ready() always true, never suspends
269 25 : std::stop_token await_resume() const noexcept { return token_; }
270 : };
271 26 : return awaiter{env_->stop_token};
272 : }
273 : else if constexpr (std::is_same_v<Tag, this_coro::frame_allocator_tag>)
274 : {
275 8 : BOOST_CAPY_ASSERT(env_);
276 : struct awaiter
277 : {
278 : std::pmr::memory_resource* frame_allocator_;
279 6 : bool await_ready() const noexcept { return true; }
280 : void await_suspend(std::coroutine_handle<>) const noexcept { } // LCOV_EXCL_LINE await_ready() always true, never suspends
281 7 : std::pmr::memory_resource* await_resume() const noexcept { return frame_allocator_; }
282 : };
283 8 : return awaiter{env_->frame_allocator};
284 : }
285 : else
286 : {
287 2532 : return static_cast<Derived*>(this)->transform_awaitable(
288 108343 : std::forward<T>(t));
289 : }
290 : }
291 : };
292 :
293 : } // namespace capy
294 : } // namespace boost
295 :
296 : #endif
|