quickjs-pure 0.17.38

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
//! `%AsyncFromSyncIteratorPrototype%` — the wrapper `for await` and `yield*` put around a
//! synchronous iterator.
//!
//! §27.1.4 `CreateAsyncFromSyncIterator` is not an optimisation: it changes what a script
//! observes. Every `next`/`return`/`throw` result's `value` goes through
//! `PromiseResolve(%Promise%, value)`, which reads `value.constructor` — so a poisoned
//! getter there has to reject the promise the caller is holding — and a rejection closes the
//! underlying synchronous iterator before the caller sees it. Handing the raw synchronous
//! iterator over (which is what the fallback in `GetIterator(obj, async)` used to do) skips
//! both, and every `AsyncFromSyncIteratorPrototype` case in the suite is about one of them.
//!
//! As with `Array.fromAsync`, the algorithm is written in JavaScript and compiled once at
//! install time. The state machine it needs — a promise capability that settles from a
//! `then` callback, a synchronous `IteratorClose` folded into a rejection — is exactly the
//! machinery the engine's own async functions run on, so writing it here instead of threading
//! it through Rust natives reuses that machinery rather than duplicating it.

use crate::interp::{Interp, JsResult, Signal};
use crate::value::Value;

/// The factory, as a function expression.
///
/// `createAsyncFromSyncIterator(syncIteratorRecord)` answers the wrapper object. The record is
/// `{ iterator, next }` — the pair `GetIterator` captured, so a `next` that is later replaced
/// on the iterator is not re-read (the spec's `[[SyncIteratorRecord]]` holds the method).
const SOURCE: &str = r#"
(function () {
  "use strict";

  var $Promise = Promise;
  var $Object = Object;
  var $TypeError = TypeError;

  // NewPromiseCapability(%Promise%): the spec's capability, built the same way so its
  // `resolve`/`reject` are ordinary resolving functions and the promise is a real one.
  var newCapability = function () {
    var capability = { __proto__: null };
    capability.promise = new $Promise(function (resolve, reject) {
      capability.resolve = resolve;
      capability.reject = reject;
    });
    return capability;
  };

  // IteratorClose for the synchronous iterator, on the rejection path: a failure here is the
  // one that happened first, so it wins over whatever `return` reported.
  var closeSync = function (record, error) {
    var returnMethod;
    try {
      returnMethod = record.iterator.return;
    } catch (thrown) {
      throw error;
    }
    if (returnMethod === undefined || returnMethod === null) {
      throw error;
    }
    var inner;
    try {
      inner = returnMethod.call(record.iterator);
    } catch (thrown) {
      throw error;
    }
    if ($Object(inner) !== inner) {
      throw error;
    }
    throw error;
  };

  // AsyncFromSyncIteratorContinuation. `closeOnRejection` is true for `next` and `throw`,
  // false for `return`.
  var continuation = function (result, capability, record, closeOnRejection) {
    var done, value;
    try {
      done = !!result.done;
      value = result.value;
    } catch (thrown) {
      capability.reject(thrown);
      return capability.promise;
    }
    var wrapper;
    try {
      // PromotionPromise: `PromiseResolve(%Promise%, value)` — the `constructor` read that
      // makes a poisoned wrapper reject here rather than at the caller's `await`.
      wrapper = $Promise.resolve(value);
    } catch (thrown) {
      if (!done && closeOnRejection) {
        try {
          closeSync(record, thrown);
        } catch (closing) {
          capability.reject(closing);
          return capability.promise;
        }
      }
      capability.reject(thrown);
      return capability.promise;
    }
    wrapper.then(function (settled) {
      capability.resolve({ __proto__: null, value: settled, done: done });
    }, function (reason) {
      if (!done && closeOnRejection) {
        try {
          closeSync(record, reason);
        } catch (closing) {
          capability.reject(closing);
          return;
        }
      }
      capability.reject(reason);
    });
    return capability.promise;
  };

  var step = function (record, method, argument, hasArgument, closeOnRejection) {
    var capability = newCapability();
    var result;
    try {
      result = hasArgument
        ? record.next.call(record.iterator, argument)
        : record.next.call(record.iterator);
    } catch (thrown) {
      capability.reject(thrown);
      return capability.promise;
    }
    if ($Object(result) !== result) {
      capability.reject(new $TypeError("iterator result is not an object"));
      return capability.promise;
    }
    return continuation(result, capability, record, closeOnRejection);
  };

  var wrapperProto = {
    __proto__: null,
    next: function (value) {
      var record = this === undefined || this === null ? undefined : this.__record;
      if (record === undefined) {
        return $Promise.reject(new $TypeError("%AsyncFromSyncIteratorPrototype% receiver is not an object"));
      }
      return step(record, record.next, value, arguments.length > 0, true);
    },
    return: function (value) {
      var record = this === undefined || this === null ? undefined : this.__record;
      if (record === undefined) {
        return $Promise.reject(new $TypeError("%AsyncFromSyncIteratorPrototype% receiver is not an object"));
      }
      // §27.1.4.2.2: `IteratorReturn` — `GetMethod(iterator, "return")`, and when the method
      // is absent the answer is `{ value, done: true }` without touching the iterator at all.
      var capability = newCapability();
      var returnMethod;
      try {
        returnMethod = record.iterator.return;
      } catch (thrown) {
        capability.reject(thrown);
        return capability.promise;
      }
      if (returnMethod === undefined || returnMethod === null) {
        capability.resolve({ __proto__: null, value: value, done: true });
        return capability.promise;
      }
      var result;
      try {
        // `IteratorReturn(iteratorRecord, value)` — and with no `value` given the method is
        // called with **no** arguments, which a `return() { arguments.length }` sees
        // (`return/absent-value-not-passed`).
        result = arguments.length > 0
          ? returnMethod.call(record.iterator, value)
          : returnMethod.call(record.iterator);
      } catch (thrown) {
        capability.reject(thrown);
        return capability.promise;
      }
      if ($Object(result) !== result) {
        capability.reject(new $TypeError("iterator result is not an object"));
        return capability.promise;
      }
      // `closeOnRejection` is false here: `return` already closed the iterator.
      return continuation(result, capability, record, false);
    },
    throw: function (value) {
      var record = this === undefined || this === null ? undefined : this.__record;
      if (record === undefined) {
        return $Promise.reject(new $TypeError("%AsyncFromSyncIteratorPrototype% receiver is not an object"));
      }
      var capability = newCapability();
      var throwMethod;
      try {
        throwMethod = record.iterator.throw;
      } catch (thrown) {
        capability.reject(thrown);
        return capability.promise;
      }
      if (throwMethod === undefined || throwMethod === null) {
        // Steps 7.b-7.d: `IteratorClose` with a *normal* completion, and its abrupt
        // completion is what gets rejected — a throwing `return` getter wins over the
        // fresh `TypeError` step 7.g would otherwise create
        // (`throw/throw-undefined-poisoned-return`).
        var completion;
        try {
          var returnMethod = record.iterator.return;
          if (returnMethod !== undefined && returnMethod !== null) {
            var inner = returnMethod.call(record.iterator);
            if ($Object(inner) !== inner) {
              completion = new $TypeError("iterator result is not an object");
            }
          }
        } catch (thrown) {
          completion = thrown;
        }
        if (completion !== undefined) {
          capability.reject(completion);
        } else {
          capability.reject(new $TypeError("iterator has no throw method"));
        }
        return capability.promise;
      }
      var result;
      try {
        result = throwMethod.call(record.iterator, value);
      } catch (thrown) {
        capability.reject(thrown);
        return capability.promise;
      }
      if ($Object(result) !== result) {
        capability.reject(new $TypeError("iterator result is not an object"));
        return capability.promise;
      }
      return continuation(result, capability, record, true);
    },
  };
  Object.defineProperty(wrapperProto, "__record", { value: undefined, writable: true });
  Object.defineProperty(wrapperProto, Symbol.toStringTag, { value: "Async-from-Sync Iterator" });

  return function createAsyncFromSyncIterator(iterator, next) {
    var wrapper = $Object.create(wrapperProto);
    Object.defineProperty(wrapper, "__record", {
      value: { __proto__: null, iterator: iterator, next: next },
    });
    return wrapper;
  };
})()
"#;

/// Compile [`SOURCE`] and answer the factory function.
pub fn build(interp: &mut Interp<'_>) -> JsResult<Value> {
    let value = interp.eval_builtin_source(SOURCE)?;
    let Value::Object(function) = &value else {
        return Err(Signal::Throw(interp.make_error(
            "InternalError",
            "async-from-sync source did not produce a function",
        )));
    };
    if !function.is_callable() {
        return Err(Signal::Throw(interp.make_error(
            "InternalError",
            "async-from-sync source is not callable",
        )));
    }
    Ok(value)
}

/// Install the factory under a hidden name so `GetIterator(obj, async)` can reach it.
///
/// A failure is fatal for the same reason `Array.fromAsync`'s is: the source is this crate's
/// own, so a syntax error is a bug here rather than a script's. A heap over its limit is the
/// host's setting talking, and is left as a missing wrapper rather than a panic.
pub fn install(interp: &mut Interp<'_>) {
    let factory = match build(interp) {
        Ok(value) => value,
        Err(Signal::Throw(reason)) => {
            if interp.heap.over_limit() {
                return;
            }
            let text = interp.describe_exception(&reason);
            panic!("async-from-sync source failed: {text}");
        }
        Err(_) => return,
    };
    interp.realm.async_from_sync = Some(factory);
}