Chris@63: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
Chris@63: // Licensed under the MIT License:
Chris@63: //
Chris@63: // Permission is hereby granted, free of charge, to any person obtaining a copy
Chris@63: // of this software and associated documentation files (the "Software"), to deal
Chris@63: // in the Software without restriction, including without limitation the rights
Chris@63: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
Chris@63: // copies of the Software, and to permit persons to whom the Software is
Chris@63: // furnished to do so, subject to the following conditions:
Chris@63: //
Chris@63: // The above copyright notice and this permission notice shall be included in
Chris@63: // all copies or substantial portions of the Software.
Chris@63: //
Chris@63: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
Chris@63: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
Chris@63: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Chris@63: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
Chris@63: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
Chris@63: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
Chris@63: // THE SOFTWARE.
Chris@63: 
Chris@63: // This file contains extended inline implementation details that are required along with async.h.
Chris@63: // We move this all into a separate file to make async.h more readable.
Chris@63: //
Chris@63: // Non-inline declarations here are defined in async.c++.
Chris@63: 
Chris@63: #ifndef KJ_ASYNC_H_
Chris@63: #error "Do not include this directly; include kj/async.h."
Chris@63: #include "async.h"  // help IDE parse this file
Chris@63: #endif
Chris@63: 
Chris@63: #ifndef KJ_ASYNC_INL_H_
Chris@63: #define KJ_ASYNC_INL_H_
Chris@63: 
Chris@63: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS
Chris@63: #pragma GCC system_header
Chris@63: #endif
Chris@63: 
Chris@63: namespace kj {
Chris@63: namespace _ {  // private
Chris@63: 
Chris@63: template <typename T>
Chris@63: class ExceptionOr;
Chris@63: 
Chris@63: class ExceptionOrValue {
Chris@63: public:
Chris@63:   ExceptionOrValue(bool, Exception&& exception): exception(kj::mv(exception)) {}
Chris@63:   KJ_DISALLOW_COPY(ExceptionOrValue);
Chris@63: 
Chris@63:   void addException(Exception&& exception) {
Chris@63:     if (this->exception == nullptr) {
Chris@63:       this->exception = kj::mv(exception);
Chris@63:     }
Chris@63:   }
Chris@63: 
Chris@63:   template <typename T>
Chris@63:   ExceptionOr<T>& as() { return *static_cast<ExceptionOr<T>*>(this); }
Chris@63:   template <typename T>
Chris@63:   const ExceptionOr<T>& as() const { return *static_cast<const ExceptionOr<T>*>(this); }
Chris@63: 
Chris@63:   Maybe<Exception> exception;
Chris@63: 
Chris@63: protected:
Chris@63:   // Allow subclasses to have move constructor / assignment.
Chris@63:   ExceptionOrValue() = default;
Chris@63:   ExceptionOrValue(ExceptionOrValue&& other) = default;
Chris@63:   ExceptionOrValue& operator=(ExceptionOrValue&& other) = default;
Chris@63: };
Chris@63: 
Chris@63: template <typename T>
Chris@63: class ExceptionOr: public ExceptionOrValue {
Chris@63: public:
Chris@63:   ExceptionOr() = default;
Chris@63:   ExceptionOr(T&& value): value(kj::mv(value)) {}
Chris@63:   ExceptionOr(bool, Exception&& exception): ExceptionOrValue(false, kj::mv(exception)) {}
Chris@63:   ExceptionOr(ExceptionOr&&) = default;
Chris@63:   ExceptionOr& operator=(ExceptionOr&&) = default;
Chris@63: 
Chris@63:   Maybe<T> value;
Chris@63: };
Chris@63: 
Chris@63: class Event {
Chris@63:   // An event waiting to be executed.  Not for direct use by applications -- promises use this
Chris@63:   // internally.
Chris@63: 
Chris@63: public:
Chris@63:   Event();
Chris@63:   ~Event() noexcept(false);
Chris@63:   KJ_DISALLOW_COPY(Event);
Chris@63: 
Chris@63:   void armDepthFirst();
Chris@63:   // Enqueue this event so that `fire()` will be called from the event loop soon.
Chris@63:   //
Chris@63:   // Events scheduled in this way are executed in depth-first order:  if an event callback arms
Chris@63:   // more events, those events are placed at the front of the queue (in the order in which they
Chris@63:   // were armed), so that they run immediately after the first event's callback returns.
Chris@63:   //
Chris@63:   // Depth-first event scheduling is appropriate for events that represent simple continuations
Chris@63:   // of a previous event that should be globbed together for performance.  Depth-first scheduling
Chris@63:   // can lead to starvation, so any long-running task must occasionally yield with
Chris@63:   // `armBreadthFirst()`.  (Promise::then() uses depth-first whereas evalLater() uses
Chris@63:   // breadth-first.)
Chris@63:   //
Chris@63:   // To use breadth-first scheduling instead, use `armBreadthFirst()`.
Chris@63: 
Chris@63:   void armBreadthFirst();
Chris@63:   // Like `armDepthFirst()` except that the event is placed at the end of the queue.
Chris@63: 
Chris@63:   kj::String trace();
Chris@63:   // Dump debug info about this event.
Chris@63: 
Chris@63:   virtual _::PromiseNode* getInnerForTrace();
Chris@63:   // If this event wraps a PromiseNode, get that node.  Used for debug tracing.
Chris@63:   // Default implementation returns nullptr.
Chris@63: 
Chris@63: protected:
Chris@63:   virtual Maybe<Own<Event>> fire() = 0;
Chris@63:   // Fire the event.  Possibly returns a pointer to itself, which will be discarded by the
Chris@63:   // caller.  This is the only way that an event can delete itself as a result of firing, as
Chris@63:   // doing so from within fire() will throw an exception.
Chris@63: 
Chris@63: private:
Chris@63:   friend class kj::EventLoop;
Chris@63:   EventLoop& loop;
Chris@63:   Event* next;
Chris@63:   Event** prev;
Chris@63:   bool firing = false;
Chris@63: };
Chris@63: 
Chris@63: class PromiseNode {
Chris@63:   // A Promise<T> contains a chain of PromiseNodes tracking the pending transformations.
Chris@63:   //
Chris@63:   // To reduce generated code bloat, PromiseNode is not a template.  Instead, it makes very hacky
Chris@63:   // use of pointers to ExceptionOrValue which actually point to ExceptionOr<T>, but are only
Chris@63:   // so down-cast in the few places that really need to be templated.  Luckily this is all
Chris@63:   // internal implementation details.
Chris@63: 
Chris@63: public:
Chris@63:   virtual void onReady(Event& event) noexcept = 0;
Chris@63:   // Arms the given event when ready.
Chris@63: 
Chris@63:   virtual void setSelfPointer(Own<PromiseNode>* selfPtr) noexcept;
Chris@63:   // Tells the node that `selfPtr` is the pointer that owns this node, and will continue to own
Chris@63:   // this node until it is destroyed or setSelfPointer() is called again.  ChainPromiseNode uses
Chris@63:   // this to shorten redundant chains.  The default implementation does nothing; only
Chris@63:   // ChainPromiseNode should implement this.
Chris@63: 
Chris@63:   virtual void get(ExceptionOrValue& output) noexcept = 0;
Chris@63:   // Get the result.  `output` points to an ExceptionOr<T> into which the result will be written.
Chris@63:   // Can only be called once, and only after the node is ready.  Must be called directly from the
Chris@63:   // event loop, with no application code on the stack.
Chris@63: 
Chris@63:   virtual PromiseNode* getInnerForTrace();
Chris@63:   // If this node wraps some other PromiseNode, get the wrapped node.  Used for debug tracing.
Chris@63:   // Default implementation returns nullptr.
Chris@63: 
Chris@63: protected:
Chris@63:   class OnReadyEvent {
Chris@63:     // Helper class for implementing onReady().
Chris@63: 
Chris@63:   public:
Chris@63:     void init(Event& newEvent);
Chris@63:     // Returns true if arm() was already called.
Chris@63: 
Chris@63:     void arm();
Chris@63:     // Arms the event if init() has already been called and makes future calls to init() return
Chris@63:     // true.
Chris@63: 
Chris@63:   private:
Chris@63:     Event* event = nullptr;
Chris@63:   };
Chris@63: };
Chris@63: 
Chris@63: // -------------------------------------------------------------------
Chris@63: 
Chris@63: class ImmediatePromiseNodeBase: public PromiseNode {
Chris@63: public:
Chris@63:   ImmediatePromiseNodeBase();
Chris@63:   ~ImmediatePromiseNodeBase() noexcept(false);
Chris@63: 
Chris@63:   void onReady(Event& event) noexcept override;
Chris@63: };
Chris@63: 
Chris@63: template <typename T>
Chris@63: class ImmediatePromiseNode final: public ImmediatePromiseNodeBase {
Chris@63:   // A promise that has already been resolved to an immediate value or exception.
Chris@63: 
Chris@63: public:
Chris@63:   ImmediatePromiseNode(ExceptionOr<T>&& result): result(kj::mv(result)) {}
Chris@63: 
Chris@63:   void get(ExceptionOrValue& output) noexcept override {
Chris@63:     output.as<T>() = kj::mv(result);
Chris@63:   }
Chris@63: 
Chris@63: private:
Chris@63:   ExceptionOr<T> result;
Chris@63: };
Chris@63: 
Chris@63: class ImmediateBrokenPromiseNode final: public ImmediatePromiseNodeBase {
Chris@63: public:
Chris@63:   ImmediateBrokenPromiseNode(Exception&& exception);
Chris@63: 
Chris@63:   void get(ExceptionOrValue& output) noexcept override;
Chris@63: 
Chris@63: private:
Chris@63:   Exception exception;
Chris@63: };
Chris@63: 
Chris@63: // -------------------------------------------------------------------
Chris@63: 
Chris@63: class AttachmentPromiseNodeBase: public PromiseNode {
Chris@63: public:
Chris@63:   AttachmentPromiseNodeBase(Own<PromiseNode>&& dependency);
Chris@63: 
Chris@63:   void onReady(Event& event) noexcept override;
Chris@63:   void get(ExceptionOrValue& output) noexcept override;
Chris@63:   PromiseNode* getInnerForTrace() override;
Chris@63: 
Chris@63: private:
Chris@63:   Own<PromiseNode> dependency;
Chris@63: 
Chris@63:   void dropDependency();
Chris@63: 
Chris@63:   template <typename>
Chris@63:   friend class AttachmentPromiseNode;
Chris@63: };
Chris@63: 
Chris@63: template <typename Attachment>
Chris@63: class AttachmentPromiseNode final: public AttachmentPromiseNodeBase {
Chris@63:   // A PromiseNode that holds on to some object (usually, an Own<T>, but could be any movable
Chris@63:   // object) until the promise resolves.
Chris@63: 
Chris@63: public:
Chris@63:   AttachmentPromiseNode(Own<PromiseNode>&& dependency, Attachment&& attachment)
Chris@63:       : AttachmentPromiseNodeBase(kj::mv(dependency)),
Chris@63:         attachment(kj::mv<Attachment>(attachment)) {}
Chris@63: 
Chris@63:   ~AttachmentPromiseNode() noexcept(false) {
Chris@63:     // We need to make sure the dependency is deleted before we delete the attachment because the
Chris@63:     // dependency may be using the attachment.
Chris@63:     dropDependency();
Chris@63:   }
Chris@63: 
Chris@63: private:
Chris@63:   Attachment attachment;
Chris@63: };
Chris@63: 
Chris@63: // -------------------------------------------------------------------
Chris@63: 
Chris@63: class PtmfHelper {
Chris@63:   // This class is a private helper for GetFunctorStartAddress. The class represents the internal
Chris@63:   // representation of a pointer-to-member-function.
Chris@63: 
Chris@63:   template <typename... ParamTypes>
Chris@63:   friend struct GetFunctorStartAddress;
Chris@63: 
Chris@63: #if __GNUG__
Chris@63: 
Chris@63:   void* ptr;
Chris@63:   ptrdiff_t adj;
Chris@63:   // Layout of a pointer-to-member-function used by GCC and compatible compilers.
Chris@63: 
Chris@63:   void* apply(void* obj) {
Chris@63: #if defined(__arm__) || defined(__mips__) || defined(__aarch64__)
Chris@63:     if (adj & 1) {
Chris@63:       ptrdiff_t voff = (ptrdiff_t)ptr;
Chris@63: #else
Chris@63:     ptrdiff_t voff = (ptrdiff_t)ptr;
Chris@63:     if (voff & 1) {
Chris@63:       voff &= ~1;
Chris@63: #endif
Chris@63:       return *(void**)(*(char**)obj + voff);
Chris@63:     } else {
Chris@63:       return ptr;
Chris@63:     }
Chris@63:   }
Chris@63: 
Chris@63: #define BODY \
Chris@63:     PtmfHelper result; \
Chris@63:     static_assert(sizeof(p) == sizeof(result), "unknown ptmf layout"); \
Chris@63:     memcpy(&result, &p, sizeof(result)); \
Chris@63:     return result
Chris@63: 
Chris@63: #else  // __GNUG__
Chris@63: 
Chris@63:   void* apply(void* obj) { return nullptr; }
Chris@63:   // TODO(port):  PTMF instruction address extraction
Chris@63: 
Chris@63: #define BODY return PtmfHelper{}
Chris@63: 
Chris@63: #endif  // __GNUG__, else
Chris@63: 
Chris@63:   template <typename R, typename C, typename... P, typename F>
Chris@63:   static PtmfHelper from(F p) { BODY; }
Chris@63:   // Create a PtmfHelper from some arbitrary pointer-to-member-function which is not
Chris@63:   // overloaded nor a template. In this case the compiler is able to deduce the full function
Chris@63:   // signature directly given the name since there is only one function with that name.
Chris@63: 
Chris@63:   template <typename R, typename C, typename... P>
Chris@63:   static PtmfHelper from(R (C::*p)(NoInfer<P>...)) { BODY; }
Chris@63:   template <typename R, typename C, typename... P>
Chris@63:   static PtmfHelper from(R (C::*p)(NoInfer<P>...) const) { BODY; }
Chris@63:   // Create a PtmfHelper from some poniter-to-member-function which is a template. In this case
Chris@63:   // the function must match exactly the containing type C, return type R, and parameter types P...
Chris@63:   // GetFunctorStartAddress normally specifies exactly the correct C and R, but can only make a
Chris@63:   // guess at P. Luckily, if the function parameters are template parameters then it's not
Chris@63:   // necessary to be precise about P.
Chris@63: #undef BODY
Chris@63: };
Chris@63: 
Chris@63: template <typename... ParamTypes>
Chris@63: struct GetFunctorStartAddress {
Chris@63:   // Given a functor (any object defining operator()), return the start address of the function,
Chris@63:   // suitable for passing to addr2line to obtain a source file/line for debugging purposes.
Chris@63:   //
Chris@63:   // This turns out to be incredibly hard to implement in the presence of overloaded or templated
Chris@63:   // functors. Therefore, we impose these specific restrictions, specific to our use case:
Chris@63:   // - Overloading is not allowed, but templating is. (Generally we only intend to support lambdas
Chris@63:   //   anyway.)
Chris@63:   // - The template parameters to GetFunctorStartAddress specify a hint as to the expected
Chris@63:   //   parameter types. If the functor is templated, its parameters must match exactly these types.
Chris@63:   //   (If it's not templated, ParamTypes are ignored.)
Chris@63: 
Chris@63:   template <typename Func>
Chris@63:   static void* apply(Func&& func) {
Chris@63:     typedef decltype(func(instance<ParamTypes>()...)) ReturnType;
Chris@63:     return PtmfHelper::from<ReturnType, Decay<Func>, ParamTypes...>(
Chris@63:         &Decay<Func>::operator()).apply(&func);
Chris@63:   }
Chris@63: };
Chris@63: 
Chris@63: template <>
Chris@63: struct GetFunctorStartAddress<Void&&>: public GetFunctorStartAddress<> {};
Chris@63: // Hack for TransformPromiseNode use case: an input type of `Void` indicates that the function
Chris@63: // actually has no parameters.
Chris@63: 
Chris@63: class TransformPromiseNodeBase: public PromiseNode {
Chris@63: public:
Chris@63:   TransformPromiseNodeBase(Own<PromiseNode>&& dependency, void* continuationTracePtr);
Chris@63: 
Chris@63:   void onReady(Event& event) noexcept override;
Chris@63:   void get(ExceptionOrValue& output) noexcept override;
Chris@63:   PromiseNode* getInnerForTrace() override;
Chris@63: 
Chris@63: private:
Chris@63:   Own<PromiseNode> dependency;
Chris@63:   void* continuationTracePtr;
Chris@63: 
Chris@63:   void dropDependency();
Chris@63:   void getDepResult(ExceptionOrValue& output);
Chris@63: 
Chris@63:   virtual void getImpl(ExceptionOrValue& output) = 0;
Chris@63: 
Chris@63:   template <typename, typename, typename, typename>
Chris@63:   friend class TransformPromiseNode;
Chris@63: };
Chris@63: 
Chris@63: template <typename T, typename DepT, typename Func, typename ErrorFunc>
Chris@63: class TransformPromiseNode final: public TransformPromiseNodeBase {
Chris@63:   // A PromiseNode that transforms the result of another PromiseNode through an application-provided
Chris@63:   // function (implements `then()`).
Chris@63: 
Chris@63: public:
Chris@63:   TransformPromiseNode(Own<PromiseNode>&& dependency, Func&& func, ErrorFunc&& errorHandler)
Chris@63:       : TransformPromiseNodeBase(kj::mv(dependency),
Chris@63:             GetFunctorStartAddress<DepT&&>::apply(func)),
Chris@63:         func(kj::fwd<Func>(func)), errorHandler(kj::fwd<ErrorFunc>(errorHandler)) {}
Chris@63: 
Chris@63:   ~TransformPromiseNode() noexcept(false) {
Chris@63:     // We need to make sure the dependency is deleted before we delete the continuations because it
Chris@63:     // is a common pattern for the continuations to hold ownership of objects that might be in-use
Chris@63:     // by the dependency.
Chris@63:     dropDependency();
Chris@63:   }
Chris@63: 
Chris@63: private:
Chris@63:   Func func;
Chris@63:   ErrorFunc errorHandler;
Chris@63: 
Chris@63:   void getImpl(ExceptionOrValue& output) override {
Chris@63:     ExceptionOr<DepT> depResult;
Chris@63:     getDepResult(depResult);
Chris@63:     KJ_IF_MAYBE(depException, depResult.exception) {
Chris@63:       output.as<T>() = handle(
Chris@63:           MaybeVoidCaller<Exception, FixVoid<ReturnType<ErrorFunc, Exception>>>::apply(
Chris@63:               errorHandler, kj::mv(*depException)));
Chris@63:     } else KJ_IF_MAYBE(depValue, depResult.value) {
Chris@63:       output.as<T>() = handle(MaybeVoidCaller<DepT, T>::apply(func, kj::mv(*depValue)));
Chris@63:     }
Chris@63:   }
Chris@63: 
Chris@63:   ExceptionOr<T> handle(T&& value) {
Chris@63:     return kj::mv(value);
Chris@63:   }
Chris@63:   ExceptionOr<T> handle(PropagateException::Bottom&& value) {
Chris@63:     return ExceptionOr<T>(false, value.asException());
Chris@63:   }
Chris@63: };
Chris@63: 
Chris@63: // -------------------------------------------------------------------
Chris@63: 
Chris@63: class ForkHubBase;
Chris@63: 
Chris@63: class ForkBranchBase: public PromiseNode {
Chris@63: public:
Chris@63:   ForkBranchBase(Own<ForkHubBase>&& hub);
Chris@63:   ~ForkBranchBase() noexcept(false);
Chris@63: 
Chris@63:   void hubReady() noexcept;
Chris@63:   // Called by the hub to indicate that it is ready.
Chris@63: 
Chris@63:   // implements PromiseNode ------------------------------------------
Chris@63:   void onReady(Event& event) noexcept override;
Chris@63:   PromiseNode* getInnerForTrace() override;
Chris@63: 
Chris@63: protected:
Chris@63:   inline ExceptionOrValue& getHubResultRef();
Chris@63: 
Chris@63:   void releaseHub(ExceptionOrValue& output);
Chris@63:   // Release the hub.  If an exception is thrown, add it to `output`.
Chris@63: 
Chris@63: private:
Chris@63:   OnReadyEvent onReadyEvent;
Chris@63: 
Chris@63:   Own<ForkHubBase> hub;
Chris@63:   ForkBranchBase* next = nullptr;
Chris@63:   ForkBranchBase** prevPtr = nullptr;
Chris@63: 
Chris@63:   friend class ForkHubBase;
Chris@63: };
Chris@63: 
Chris@63: template <typename T> T copyOrAddRef(T& t) { return t; }
Chris@63: template <typename T> Own<T> copyOrAddRef(Own<T>& t) { return t->addRef(); }
Chris@63: 
Chris@63: template <typename T>
Chris@63: class ForkBranch final: public ForkBranchBase {
Chris@63:   // A PromiseNode that implements one branch of a fork -- i.e. one of the branches that receives
Chris@63:   // a const reference.
Chris@63: 
Chris@63: public:
Chris@63:   ForkBranch(Own<ForkHubBase>&& hub): ForkBranchBase(kj::mv(hub)) {}
Chris@63: 
Chris@63:   void get(ExceptionOrValue& output) noexcept override {
Chris@63:     ExceptionOr<T>& hubResult = getHubResultRef().template as<T>();
Chris@63:     KJ_IF_MAYBE(value, hubResult.value) {
Chris@63:       output.as<T>().value = copyOrAddRef(*value);
Chris@63:     } else {
Chris@63:       output.as<T>().value = nullptr;
Chris@63:     }
Chris@63:     output.exception = hubResult.exception;
Chris@63:     releaseHub(output);
Chris@63:   }
Chris@63: };
Chris@63: 
Chris@63: template <typename T, size_t index>
Chris@63: class SplitBranch final: public ForkBranchBase {
Chris@63:   // A PromiseNode that implements one branch of a fork -- i.e. one of the branches that receives
Chris@63:   // a const reference.
Chris@63: 
Chris@63: public:
Chris@63:   SplitBranch(Own<ForkHubBase>&& hub): ForkBranchBase(kj::mv(hub)) {}
Chris@63: 
Chris@63:   typedef kj::Decay<decltype(kj::get<index>(kj::instance<T>()))> Element;
Chris@63: 
Chris@63:   void get(ExceptionOrValue& output) noexcept override {
Chris@63:     ExceptionOr<T>& hubResult = getHubResultRef().template as<T>();
Chris@63:     KJ_IF_MAYBE(value, hubResult.value) {
Chris@63:       output.as<Element>().value = kj::mv(kj::get<index>(*value));
Chris@63:     } else {
Chris@63:       output.as<Element>().value = nullptr;
Chris@63:     }
Chris@63:     output.exception = hubResult.exception;
Chris@63:     releaseHub(output);
Chris@63:   }
Chris@63: };
Chris@63: 
Chris@63: // -------------------------------------------------------------------
Chris@63: 
Chris@63: class ForkHubBase: public Refcounted, protected Event {
Chris@63: public:
Chris@63:   ForkHubBase(Own<PromiseNode>&& inner, ExceptionOrValue& resultRef);
Chris@63: 
Chris@63:   inline ExceptionOrValue& getResultRef() { return resultRef; }
Chris@63: 
Chris@63: private:
Chris@63:   Own<PromiseNode> inner;
Chris@63:   ExceptionOrValue& resultRef;
Chris@63: 
Chris@63:   ForkBranchBase* headBranch = nullptr;
Chris@63:   ForkBranchBase** tailBranch = &headBranch;
Chris@63:   // Tail becomes null once the inner promise is ready and all branches have been notified.
Chris@63: 
Chris@63:   Maybe<Own<Event>> fire() override;
Chris@63:   _::PromiseNode* getInnerForTrace() override;
Chris@63: 
Chris@63:   friend class ForkBranchBase;
Chris@63: };
Chris@63: 
Chris@63: template <typename T>
Chris@63: class ForkHub final: public ForkHubBase {
Chris@63:   // A PromiseNode that implements the hub of a fork.  The first call to Promise::fork() replaces
Chris@63:   // the promise's outer node with a ForkHub, and subsequent calls add branches to that hub (if
Chris@63:   // possible).
Chris@63: 
Chris@63: public:
Chris@63:   ForkHub(Own<PromiseNode>&& inner): ForkHubBase(kj::mv(inner), result) {}
Chris@63: 
Chris@63:   Promise<_::UnfixVoid<T>> addBranch() {
Chris@63:     return Promise<_::UnfixVoid<T>>(false, kj::heap<ForkBranch<T>>(addRef(*this)));
Chris@63:   }
Chris@63: 
Chris@63:   _::SplitTuplePromise<T> split() {
Chris@63:     return splitImpl(MakeIndexes<tupleSize<T>()>());
Chris@63:   }
Chris@63: 
Chris@63: private:
Chris@63:   ExceptionOr<T> result;
Chris@63: 
Chris@63:   template <size_t... indexes>
Chris@63:   _::SplitTuplePromise<T> splitImpl(Indexes<indexes...>) {
Chris@63:     return kj::tuple(addSplit<indexes>()...);
Chris@63:   }
Chris@63: 
Chris@63:   template <size_t index>
Chris@63:   Promise<JoinPromises<typename SplitBranch<T, index>::Element>> addSplit() {
Chris@63:     return Promise<JoinPromises<typename SplitBranch<T, index>::Element>>(
Chris@63:         false, maybeChain(kj::heap<SplitBranch<T, index>>(addRef(*this)),
Chris@63:                           implicitCast<typename SplitBranch<T, index>::Element*>(nullptr)));
Chris@63:   }
Chris@63: };
Chris@63: 
Chris@63: inline ExceptionOrValue& ForkBranchBase::getHubResultRef() {
Chris@63:   return hub->getResultRef();
Chris@63: }
Chris@63: 
Chris@63: // -------------------------------------------------------------------
Chris@63: 
Chris@63: class ChainPromiseNode final: public PromiseNode, public Event {
Chris@63:   // Promise node which reduces Promise<Promise<T>> to Promise<T>.
Chris@63:   //
Chris@63:   // `Event` is only a public base class because otherwise we can't cast Own<ChainPromiseNode> to
Chris@63:   // Own<Event>.  Ugh, templates and private...
Chris@63: 
Chris@63: public:
Chris@63:   explicit ChainPromiseNode(Own<PromiseNode> inner);
Chris@63:   ~ChainPromiseNode() noexcept(false);
Chris@63: 
Chris@63:   void onReady(Event& event) noexcept override;
Chris@63:   void setSelfPointer(Own<PromiseNode>* selfPtr) noexcept override;
Chris@63:   void get(ExceptionOrValue& output) noexcept override;
Chris@63:   PromiseNode* getInnerForTrace() override;
Chris@63: 
Chris@63: private:
Chris@63:   enum State {
Chris@63:     STEP1,
Chris@63:     STEP2
Chris@63:   };
Chris@63: 
Chris@63:   State state;
Chris@63: 
Chris@63:   Own<PromiseNode> inner;
Chris@63:   // In STEP1, a PromiseNode for a Promise<T>.
Chris@63:   // In STEP2, a PromiseNode for a T.
Chris@63: 
Chris@63:   Event* onReadyEvent = nullptr;
Chris@63:   Own<PromiseNode>* selfPtr = nullptr;
Chris@63: 
Chris@63:   Maybe<Own<Event>> fire() override;
Chris@63: };
Chris@63: 
Chris@63: template <typename T>
Chris@63: Own<PromiseNode> maybeChain(Own<PromiseNode>&& node, Promise<T>*) {
Chris@63:   return heap<ChainPromiseNode>(kj::mv(node));
Chris@63: }
Chris@63: 
Chris@63: template <typename T>
Chris@63: Own<PromiseNode>&& maybeChain(Own<PromiseNode>&& node, T*) {
Chris@63:   return kj::mv(node);
Chris@63: }
Chris@63: 
Chris@63: // -------------------------------------------------------------------
Chris@63: 
Chris@63: class ExclusiveJoinPromiseNode final: public PromiseNode {
Chris@63: public:
Chris@63:   ExclusiveJoinPromiseNode(Own<PromiseNode> left, Own<PromiseNode> right);
Chris@63:   ~ExclusiveJoinPromiseNode() noexcept(false);
Chris@63: 
Chris@63:   void onReady(Event& event) noexcept override;
Chris@63:   void get(ExceptionOrValue& output) noexcept override;
Chris@63:   PromiseNode* getInnerForTrace() override;
Chris@63: 
Chris@63: private:
Chris@63:   class Branch: public Event {
Chris@63:   public:
Chris@63:     Branch(ExclusiveJoinPromiseNode& joinNode, Own<PromiseNode> dependency);
Chris@63:     ~Branch() noexcept(false);
Chris@63: 
Chris@63:     bool get(ExceptionOrValue& output);
Chris@63:     // Returns true if this is the side that finished.
Chris@63: 
Chris@63:     Maybe<Own<Event>> fire() override;
Chris@63:     _::PromiseNode* getInnerForTrace() override;
Chris@63: 
Chris@63:   private:
Chris@63:     ExclusiveJoinPromiseNode& joinNode;
Chris@63:     Own<PromiseNode> dependency;
Chris@63:   };
Chris@63: 
Chris@63:   Branch left;
Chris@63:   Branch right;
Chris@63:   OnReadyEvent onReadyEvent;
Chris@63: };
Chris@63: 
Chris@63: // -------------------------------------------------------------------
Chris@63: 
Chris@63: class ArrayJoinPromiseNodeBase: public PromiseNode {
Chris@63: public:
Chris@63:   ArrayJoinPromiseNodeBase(Array<Own<PromiseNode>> promises,
Chris@63:                            ExceptionOrValue* resultParts, size_t partSize);
Chris@63:   ~ArrayJoinPromiseNodeBase() noexcept(false);
Chris@63: 
Chris@63:   void onReady(Event& event) noexcept override final;
Chris@63:   void get(ExceptionOrValue& output) noexcept override final;
Chris@63:   PromiseNode* getInnerForTrace() override final;
Chris@63: 
Chris@63: protected:
Chris@63:   virtual void getNoError(ExceptionOrValue& output) noexcept = 0;
Chris@63:   // Called to compile the result only in the case where there were no errors.
Chris@63: 
Chris@63: private:
Chris@63:   uint countLeft;
Chris@63:   OnReadyEvent onReadyEvent;
Chris@63: 
Chris@63:   class Branch final: public Event {
Chris@63:   public:
Chris@63:     Branch(ArrayJoinPromiseNodeBase& joinNode, Own<PromiseNode> dependency,
Chris@63:            ExceptionOrValue& output);
Chris@63:     ~Branch() noexcept(false);
Chris@63: 
Chris@63:     Maybe<Own<Event>> fire() override;
Chris@63:     _::PromiseNode* getInnerForTrace() override;
Chris@63: 
Chris@63:     Maybe<Exception> getPart();
Chris@63:     // Calls dependency->get(output).  If there was an exception, return it.
Chris@63: 
Chris@63:   private:
Chris@63:     ArrayJoinPromiseNodeBase& joinNode;
Chris@63:     Own<PromiseNode> dependency;
Chris@63:     ExceptionOrValue& output;
Chris@63:   };
Chris@63: 
Chris@63:   Array<Branch> branches;
Chris@63: };
Chris@63: 
Chris@63: template <typename T>
Chris@63: class ArrayJoinPromiseNode final: public ArrayJoinPromiseNodeBase {
Chris@63: public:
Chris@63:   ArrayJoinPromiseNode(Array<Own<PromiseNode>> promises,
Chris@63:                        Array<ExceptionOr<T>> resultParts)
Chris@63:       : ArrayJoinPromiseNodeBase(kj::mv(promises), resultParts.begin(), sizeof(ExceptionOr<T>)),
Chris@63:         resultParts(kj::mv(resultParts)) {}
Chris@63: 
Chris@63: protected:
Chris@63:   void getNoError(ExceptionOrValue& output) noexcept override {
Chris@63:     auto builder = heapArrayBuilder<T>(resultParts.size());
Chris@63:     for (auto& part: resultParts) {
Chris@63:       KJ_IASSERT(part.value != nullptr,
Chris@63:                  "Bug in KJ promise framework:  Promise result had neither value no exception.");
Chris@63:       builder.add(kj::mv(*_::readMaybe(part.value)));
Chris@63:     }
Chris@63:     output.as<Array<T>>() = builder.finish();
Chris@63:   }
Chris@63: 
Chris@63: private:
Chris@63:   Array<ExceptionOr<T>> resultParts;
Chris@63: };
Chris@63: 
Chris@63: template <>
Chris@63: class ArrayJoinPromiseNode<void> final: public ArrayJoinPromiseNodeBase {
Chris@63: public:
Chris@63:   ArrayJoinPromiseNode(Array<Own<PromiseNode>> promises,
Chris@63:                        Array<ExceptionOr<_::Void>> resultParts);
Chris@63:   ~ArrayJoinPromiseNode();
Chris@63: 
Chris@63: protected:
Chris@63:   void getNoError(ExceptionOrValue& output) noexcept override;
Chris@63: 
Chris@63: private:
Chris@63:   Array<ExceptionOr<_::Void>> resultParts;
Chris@63: };
Chris@63: 
Chris@63: // -------------------------------------------------------------------
Chris@63: 
Chris@63: class EagerPromiseNodeBase: public PromiseNode, protected Event {
Chris@63:   // A PromiseNode that eagerly evaluates its dependency even if its dependent does not eagerly
Chris@63:   // evaluate it.
Chris@63: 
Chris@63: public:
Chris@63:   EagerPromiseNodeBase(Own<PromiseNode>&& dependency, ExceptionOrValue& resultRef);
Chris@63: 
Chris@63:   void onReady(Event& event) noexcept override;
Chris@63:   PromiseNode* getInnerForTrace() override;
Chris@63: 
Chris@63: private:
Chris@63:   Own<PromiseNode> dependency;
Chris@63:   OnReadyEvent onReadyEvent;
Chris@63: 
Chris@63:   ExceptionOrValue& resultRef;
Chris@63: 
Chris@63:   Maybe<Own<Event>> fire() override;
Chris@63: };
Chris@63: 
Chris@63: template <typename T>
Chris@63: class EagerPromiseNode final: public EagerPromiseNodeBase {
Chris@63: public:
Chris@63:   EagerPromiseNode(Own<PromiseNode>&& dependency)
Chris@63:       : EagerPromiseNodeBase(kj::mv(dependency), result) {}
Chris@63: 
Chris@63:   void get(ExceptionOrValue& output) noexcept override {
Chris@63:     output.as<T>() = kj::mv(result);
Chris@63:   }
Chris@63: 
Chris@63: private:
Chris@63:   ExceptionOr<T> result;
Chris@63: };
Chris@63: 
Chris@63: template <typename T>
Chris@63: Own<PromiseNode> spark(Own<PromiseNode>&& node) {
Chris@63:   // Forces evaluation of the given node to begin as soon as possible, even if no one is waiting
Chris@63:   // on it.
Chris@63:   return heap<EagerPromiseNode<T>>(kj::mv(node));
Chris@63: }
Chris@63: 
Chris@63: // -------------------------------------------------------------------
Chris@63: 
Chris@63: class AdapterPromiseNodeBase: public PromiseNode {
Chris@63: public:
Chris@63:   void onReady(Event& event) noexcept override;
Chris@63: 
Chris@63: protected:
Chris@63:   inline void setReady() {
Chris@63:     onReadyEvent.arm();
Chris@63:   }
Chris@63: 
Chris@63: private:
Chris@63:   OnReadyEvent onReadyEvent;
Chris@63: };
Chris@63: 
Chris@63: template <typename T, typename Adapter>
Chris@63: class AdapterPromiseNode final: public AdapterPromiseNodeBase,
Chris@63:                                 private PromiseFulfiller<UnfixVoid<T>> {
Chris@63:   // A PromiseNode that wraps a PromiseAdapter.
Chris@63: 
Chris@63: public:
Chris@63:   template <typename... Params>
Chris@63:   AdapterPromiseNode(Params&&... params)
Chris@63:       : adapter(static_cast<PromiseFulfiller<UnfixVoid<T>>&>(*this), kj::fwd<Params>(params)...) {}
Chris@63: 
Chris@63:   void get(ExceptionOrValue& output) noexcept override {
Chris@63:     KJ_IREQUIRE(!isWaiting());
Chris@63:     output.as<T>() = kj::mv(result);
Chris@63:   }
Chris@63: 
Chris@63: private:
Chris@63:   ExceptionOr<T> result;
Chris@63:   bool waiting = true;
Chris@63:   Adapter adapter;
Chris@63: 
Chris@63:   void fulfill(T&& value) override {
Chris@63:     if (waiting) {
Chris@63:       waiting = false;
Chris@63:       result = ExceptionOr<T>(kj::mv(value));
Chris@63:       setReady();
Chris@63:     }
Chris@63:   }
Chris@63: 
Chris@63:   void reject(Exception&& exception) override {
Chris@63:     if (waiting) {
Chris@63:       waiting = false;
Chris@63:       result = ExceptionOr<T>(false, kj::mv(exception));
Chris@63:       setReady();
Chris@63:     }
Chris@63:   }
Chris@63: 
Chris@63:   bool isWaiting() override {
Chris@63:     return waiting;
Chris@63:   }
Chris@63: };
Chris@63: 
Chris@63: }  // namespace _ (private)
Chris@63: 
Chris@63: // =======================================================================================
Chris@63: 
Chris@63: template <typename T>
Chris@63: Promise<T>::Promise(_::FixVoid<T> value)
Chris@63:     : PromiseBase(heap<_::ImmediatePromiseNode<_::FixVoid<T>>>(kj::mv(value))) {}
Chris@63: 
Chris@63: template <typename T>
Chris@63: Promise<T>::Promise(kj::Exception&& exception)
Chris@63:     : PromiseBase(heap<_::ImmediateBrokenPromiseNode>(kj::mv(exception))) {}
Chris@63: 
Chris@63: template <typename T>
Chris@63: template <typename Func, typename ErrorFunc>
Chris@63: PromiseForResult<Func, T> Promise<T>::then(Func&& func, ErrorFunc&& errorHandler) {
Chris@63:   typedef _::FixVoid<_::ReturnType<Func, T>> ResultT;
Chris@63: 
Chris@63:   Own<_::PromiseNode> intermediate =
Chris@63:       heap<_::TransformPromiseNode<ResultT, _::FixVoid<T>, Func, ErrorFunc>>(
Chris@63:           kj::mv(node), kj::fwd<Func>(func), kj::fwd<ErrorFunc>(errorHandler));
Chris@63:   return PromiseForResult<Func, T>(false,
Chris@63:       _::maybeChain(kj::mv(intermediate), implicitCast<ResultT*>(nullptr)));
Chris@63: }
Chris@63: 
Chris@63: namespace _ {  // private
Chris@63: 
Chris@63: template <typename T>
Chris@63: struct IdentityFunc {
Chris@63:   inline T operator()(T&& value) const {
Chris@63:     return kj::mv(value);
Chris@63:   }
Chris@63: };
Chris@63: template <typename T>
Chris@63: struct IdentityFunc<Promise<T>> {
Chris@63:   inline Promise<T> operator()(T&& value) const {
Chris@63:     return kj::mv(value);
Chris@63:   }
Chris@63: };
Chris@63: template <>
Chris@63: struct IdentityFunc<void> {
Chris@63:   inline void operator()() const {}
Chris@63: };
Chris@63: template <>
Chris@63: struct IdentityFunc<Promise<void>> {
Chris@63:   Promise<void> operator()() const;
Chris@63:   // This can't be inline because it will make the translation unit depend on kj-async. Awkwardly,
Chris@63:   // Cap'n Proto relies on being able to include this header without creating such a link-time
Chris@63:   // dependency.
Chris@63: };
Chris@63: 
Chris@63: }  // namespace _ (private)
Chris@63: 
Chris@63: template <typename T>
Chris@63: template <typename ErrorFunc>
Chris@63: Promise<T> Promise<T>::catch_(ErrorFunc&& errorHandler) {
Chris@63:   // then()'s ErrorFunc can only return a Promise if Func also returns a Promise. In this case,
Chris@63:   // Func is being filled in automatically. We want to make sure ErrorFunc can return a Promise,
Chris@63:   // but we don't want the extra overhead of promise chaining if ErrorFunc doesn't actually
Chris@63:   // return a promise. So we make our Func return match ErrorFunc.
Chris@63:   return then(_::IdentityFunc<decltype(errorHandler(instance<Exception&&>()))>(),
Chris@63:               kj::fwd<ErrorFunc>(errorHandler));
Chris@63: }
Chris@63: 
Chris@63: template <typename T>
Chris@63: T Promise<T>::wait(WaitScope& waitScope) {
Chris@63:   _::ExceptionOr<_::FixVoid<T>> result;
Chris@63: 
Chris@63:   waitImpl(kj::mv(node), result, waitScope);
Chris@63: 
Chris@63:   KJ_IF_MAYBE(value, result.value) {
Chris@63:     KJ_IF_MAYBE(exception, result.exception) {
Chris@63:       throwRecoverableException(kj::mv(*exception));
Chris@63:     }
Chris@63:     return _::returnMaybeVoid(kj::mv(*value));
Chris@63:   } else KJ_IF_MAYBE(exception, result.exception) {
Chris@63:     throwFatalException(kj::mv(*exception));
Chris@63:   } else {
Chris@63:     // Result contained neither a value nor an exception?
Chris@63:     KJ_UNREACHABLE;
Chris@63:   }
Chris@63: }
Chris@63: 
Chris@63: template <>
Chris@63: inline void Promise<void>::wait(WaitScope& waitScope) {
Chris@63:   // Override <void> case to use throwRecoverableException().
Chris@63: 
Chris@63:   _::ExceptionOr<_::Void> result;
Chris@63: 
Chris@63:   waitImpl(kj::mv(node), result, waitScope);
Chris@63: 
Chris@63:   if (result.value != nullptr) {
Chris@63:     KJ_IF_MAYBE(exception, result.exception) {
Chris@63:       throwRecoverableException(kj::mv(*exception));
Chris@63:     }
Chris@63:   } else KJ_IF_MAYBE(exception, result.exception) {
Chris@63:     throwRecoverableException(kj::mv(*exception));
Chris@63:   } else {
Chris@63:     // Result contained neither a value nor an exception?
Chris@63:     KJ_UNREACHABLE;
Chris@63:   }
Chris@63: }
Chris@63: 
Chris@63: template <typename T>
Chris@63: ForkedPromise<T> Promise<T>::fork() {
Chris@63:   return ForkedPromise<T>(false, refcounted<_::ForkHub<_::FixVoid<T>>>(kj::mv(node)));
Chris@63: }
Chris@63: 
Chris@63: template <typename T>
Chris@63: Promise<T> ForkedPromise<T>::addBranch() {
Chris@63:   return hub->addBranch();
Chris@63: }
Chris@63: 
Chris@63: template <typename T>
Chris@63: _::SplitTuplePromise<T> Promise<T>::split() {
Chris@63:   return refcounted<_::ForkHub<_::FixVoid<T>>>(kj::mv(node))->split();
Chris@63: }
Chris@63: 
Chris@63: template <typename T>
Chris@63: Promise<T> Promise<T>::exclusiveJoin(Promise<T>&& other) {
Chris@63:   return Promise(false, heap<_::ExclusiveJoinPromiseNode>(kj::mv(node), kj::mv(other.node)));
Chris@63: }
Chris@63: 
Chris@63: template <typename T>
Chris@63: template <typename... Attachments>
Chris@63: Promise<T> Promise<T>::attach(Attachments&&... attachments) {
Chris@63:   return Promise(false, kj::heap<_::AttachmentPromiseNode<Tuple<Attachments...>>>(
Chris@63:       kj::mv(node), kj::tuple(kj::fwd<Attachments>(attachments)...)));
Chris@63: }
Chris@63: 
Chris@63: template <typename T>
Chris@63: template <typename ErrorFunc>
Chris@63: Promise<T> Promise<T>::eagerlyEvaluate(ErrorFunc&& errorHandler) {
Chris@63:   // See catch_() for commentary.
Chris@63:   return Promise(false, _::spark<_::FixVoid<T>>(then(
Chris@63:       _::IdentityFunc<decltype(errorHandler(instance<Exception&&>()))>(),
Chris@63:       kj::fwd<ErrorFunc>(errorHandler)).node));
Chris@63: }
Chris@63: 
Chris@63: template <typename T>
Chris@63: Promise<T> Promise<T>::eagerlyEvaluate(decltype(nullptr)) {
Chris@63:   return Promise(false, _::spark<_::FixVoid<T>>(kj::mv(node)));
Chris@63: }
Chris@63: 
Chris@63: template <typename T>
Chris@63: kj::String Promise<T>::trace() {
Chris@63:   return PromiseBase::trace();
Chris@63: }
Chris@63: 
Chris@63: template <typename Func>
Chris@63: inline PromiseForResult<Func, void> evalLater(Func&& func) {
Chris@63:   return _::yield().then(kj::fwd<Func>(func), _::PropagateException());
Chris@63: }
Chris@63: 
Chris@63: template <typename Func>
Chris@63: inline PromiseForResult<Func, void> evalNow(Func&& func) {
Chris@63:   PromiseForResult<Func, void> result = nullptr;
Chris@63:   KJ_IF_MAYBE(e, kj::runCatchingExceptions([&]() {
Chris@63:     result = func();
Chris@63:   })) {
Chris@63:     result = kj::mv(*e);
Chris@63:   }
Chris@63:   return result;
Chris@63: }
Chris@63: 
Chris@63: template <typename T>
Chris@63: template <typename ErrorFunc>
Chris@63: void Promise<T>::detach(ErrorFunc&& errorHandler) {
Chris@63:   return _::detach(then([](T&&) {}, kj::fwd<ErrorFunc>(errorHandler)));
Chris@63: }
Chris@63: 
Chris@63: template <>
Chris@63: template <typename ErrorFunc>
Chris@63: void Promise<void>::detach(ErrorFunc&& errorHandler) {
Chris@63:   return _::detach(then([]() {}, kj::fwd<ErrorFunc>(errorHandler)));
Chris@63: }
Chris@63: 
Chris@63: template <typename T>
Chris@63: Promise<Array<T>> joinPromises(Array<Promise<T>>&& promises) {
Chris@63:   return Promise<Array<T>>(false, kj::heap<_::ArrayJoinPromiseNode<T>>(
Chris@63:       KJ_MAP(p, promises) { return kj::mv(p.node); },
Chris@63:       heapArray<_::ExceptionOr<T>>(promises.size())));
Chris@63: }
Chris@63: 
Chris@63: // =======================================================================================
Chris@63: 
Chris@63: namespace _ {  // private
Chris@63: 
Chris@63: template <typename T>
Chris@63: class WeakFulfiller final: public PromiseFulfiller<T>, private kj::Disposer {
Chris@63:   // A wrapper around PromiseFulfiller which can be detached.
Chris@63:   //
Chris@63:   // There are a couple non-trivialities here:
Chris@63:   // - If the WeakFulfiller is discarded, we want the promise it fulfills to be implicitly
Chris@63:   //   rejected.
Chris@63:   // - We cannot destroy the WeakFulfiller until the application has discarded it *and* it has been
Chris@63:   //   detached from the underlying fulfiller, because otherwise the later detach() call will go
Chris@63:   //   to a dangling pointer.  Essentially, WeakFulfiller is reference counted, although the
Chris@63:   //   refcount never goes over 2 and we manually implement the refcounting because we need to do
Chris@63:   //   other special things when each side detaches anyway.  To this end, WeakFulfiller is its own
Chris@63:   //   Disposer -- dispose() is called when the application discards its owned pointer to the
Chris@63:   //   fulfiller and detach() is called when the promise is destroyed.
Chris@63: 
Chris@63: public:
Chris@63:   KJ_DISALLOW_COPY(WeakFulfiller);
Chris@63: 
Chris@63:   static kj::Own<WeakFulfiller> make() {
Chris@63:     WeakFulfiller* ptr = new WeakFulfiller;
Chris@63:     return Own<WeakFulfiller>(ptr, *ptr);
Chris@63:   }
Chris@63: 
Chris@63:   void fulfill(FixVoid<T>&& value) override {
Chris@63:     if (inner != nullptr) {
Chris@63:       inner->fulfill(kj::mv(value));
Chris@63:     }
Chris@63:   }
Chris@63: 
Chris@63:   void reject(Exception&& exception) override {
Chris@63:     if (inner != nullptr) {
Chris@63:       inner->reject(kj::mv(exception));
Chris@63:     }
Chris@63:   }
Chris@63: 
Chris@63:   bool isWaiting() override {
Chris@63:     return inner != nullptr && inner->isWaiting();
Chris@63:   }
Chris@63: 
Chris@63:   void attach(PromiseFulfiller<T>& newInner) {
Chris@63:     inner = &newInner;
Chris@63:   }
Chris@63: 
Chris@63:   void detach(PromiseFulfiller<T>& from) {
Chris@63:     if (inner == nullptr) {
Chris@63:       // Already disposed.
Chris@63:       delete this;
Chris@63:     } else {
Chris@63:       KJ_IREQUIRE(inner == &from);
Chris@63:       inner = nullptr;
Chris@63:     }
Chris@63:   }
Chris@63: 
Chris@63: private:
Chris@63:   mutable PromiseFulfiller<T>* inner;
Chris@63: 
Chris@63:   WeakFulfiller(): inner(nullptr) {}
Chris@63: 
Chris@63:   void disposeImpl(void* pointer) const override {
Chris@63:     // TODO(perf): Factor some of this out so it isn't regenerated for every fulfiller type?
Chris@63: 
Chris@63:     if (inner == nullptr) {
Chris@63:       // Already detached.
Chris@63:       delete this;
Chris@63:     } else {
Chris@63:       if (inner->isWaiting()) {
Chris@63:         inner->reject(kj::Exception(kj::Exception::Type::FAILED, __FILE__, __LINE__,
Chris@63:             kj::heapString("PromiseFulfiller was destroyed without fulfilling the promise.")));
Chris@63:       }
Chris@63:       inner = nullptr;
Chris@63:     }
Chris@63:   }
Chris@63: };
Chris@63: 
Chris@63: template <typename T>
Chris@63: class PromiseAndFulfillerAdapter {
Chris@63: public:
Chris@63:   PromiseAndFulfillerAdapter(PromiseFulfiller<T>& fulfiller,
Chris@63:                              WeakFulfiller<T>& wrapper)
Chris@63:       : fulfiller(fulfiller), wrapper(wrapper) {
Chris@63:     wrapper.attach(fulfiller);
Chris@63:   }
Chris@63: 
Chris@63:   ~PromiseAndFulfillerAdapter() noexcept(false) {
Chris@63:     wrapper.detach(fulfiller);
Chris@63:   }
Chris@63: 
Chris@63: private:
Chris@63:   PromiseFulfiller<T>& fulfiller;
Chris@63:   WeakFulfiller<T>& wrapper;
Chris@63: };
Chris@63: 
Chris@63: }  // namespace _ (private)
Chris@63: 
Chris@63: template <typename T>
Chris@63: template <typename Func>
Chris@63: bool PromiseFulfiller<T>::rejectIfThrows(Func&& func) {
Chris@63:   KJ_IF_MAYBE(exception, kj::runCatchingExceptions(kj::mv(func))) {
Chris@63:     reject(kj::mv(*exception));
Chris@63:     return false;
Chris@63:   } else {
Chris@63:     return true;
Chris@63:   }
Chris@63: }
Chris@63: 
Chris@63: template <typename Func>
Chris@63: bool PromiseFulfiller<void>::rejectIfThrows(Func&& func) {
Chris@63:   KJ_IF_MAYBE(exception, kj::runCatchingExceptions(kj::mv(func))) {
Chris@63:     reject(kj::mv(*exception));
Chris@63:     return false;
Chris@63:   } else {
Chris@63:     return true;
Chris@63:   }
Chris@63: }
Chris@63: 
Chris@63: template <typename T, typename Adapter, typename... Params>
Chris@63: Promise<T> newAdaptedPromise(Params&&... adapterConstructorParams) {
Chris@63:   return Promise<T>(false, heap<_::AdapterPromiseNode<_::FixVoid<T>, Adapter>>(
Chris@63:       kj::fwd<Params>(adapterConstructorParams)...));
Chris@63: }
Chris@63: 
Chris@63: template <typename T>
Chris@63: PromiseFulfillerPair<T> newPromiseAndFulfiller() {
Chris@63:   auto wrapper = _::WeakFulfiller<T>::make();
Chris@63: 
Chris@63:   Own<_::PromiseNode> intermediate(
Chris@63:       heap<_::AdapterPromiseNode<_::FixVoid<T>, _::PromiseAndFulfillerAdapter<T>>>(*wrapper));
Chris@63:   Promise<_::JoinPromises<T>> promise(false,
Chris@63:       _::maybeChain(kj::mv(intermediate), implicitCast<T*>(nullptr)));
Chris@63: 
Chris@63:   return PromiseFulfillerPair<T> { kj::mv(promise), kj::mv(wrapper) };
Chris@63: }
Chris@63: 
Chris@63: }  // namespace kj
Chris@63: 
Chris@63: #endif  // KJ_ASYNC_INL_H_