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