use crate::interp::{Interp, JsResult, Signal};
use crate::value::Value;
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;
};
})()
"#;
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)
}
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);
}