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