Scripts: Promise review fixes for rooting, slices, finally and the combinators

- A promise resolved with itself roots its TypeError before the queue
  reserves room, so a collection there no longer frees the reason.
- A sliced run whose last job ends a slice reports Done in that slice
  instead of Paused, and a pause asked for in a run's last step no longer
  pauses the next run.
- The job queue is replaced at run end, which frees its buffer.
- A reaction job runs a finally callback as its own call, so a slice can
  pause inside it; the callback no longer runs to its end within the
  unbroken-fuel allowance.
- all, allSettled and race read an array to its current length at each
  step, and a string input is flattened through the charged path and
  shared instead of copied.
- The test262 runner checks the expected exception of an async test with
  a runtime negative.
This commit is contained in:
dotCooCoo committed 2026-11-22 07:29:09 -08:00
1 parent c417aff8fb
commit 438f2a9ba8
3 files changed
+206 -11

No files matched your search

+89 -9
View File
@@ -32,6 +32,7 @@ use crate::LimitKind;
use crate::bytecode::Code;
use crate::heap::{BOUND_ARG_BYTES, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key};
use crate::interp::{Abrupt, ErrorType, Interp, JsResult};
use crate::string_builtins::flat_charged;
use crate::value::Value;
/// Where a promise was rejected: the code and the instruction.
@@ -142,6 +143,9 @@ enum Then {
Settle(ObjId),
/// An exception rejects through this resolving record.
Reject(ObjId),
/// The call was a `finally` callback that a reaction job runs in place of the Then Finally or
/// Catch Finally function: `derived` is settled as that function's result settles it.
Finally { derived: ObjId, value: Value, throws: bool },
}
/// The built-in functions a promise operation's functions call, with their record.
@@ -211,6 +215,10 @@ impl Promises {
roots.values.extend(self.completion.iter());
match &self.running {
Some(Then::Settle(o) | Then::Reject(o)) => roots.objects.push(*o),
Some(Then::Finally { derived, value, .. }) => {
roots.objects.push(*derived);
roots.values.push(value);
}
None => {}
}
for job in &self.queue {
@@ -233,6 +241,12 @@ impl Promises {
JOB_BYTES.saturating_mul(self.queue.len())
}
/// How many jobs are queued, and how many the queue's buffer has room for.
#[cfg(test)]
pub(crate) fn queue_size(&self) -> (usize, usize) {
(self.queue.len(), self.queue.capacity())
}
/// Drops the noted rejections whose promise has a handler now.
pub(crate) fn forget_handled(&mut self, heap: &crate::heap::Heap) {
self.rejected.retain(|p| matches!(heap.object(*p).map(|o| &o.class), Some(Class::Promise(d)) if !d.handled));
@@ -455,7 +469,7 @@ fn resolve_promise(interp: &mut Interp, p: ObjId, resolution: Value) -> JsResult
if o == p {
let e = error_value(interp, ErrorType::Type, "a promise cannot be resolved with itself");
let site = here(interp);
return settle(interp, p, false, e, site);
return reject_promise(interp, p, e, site);
}
let then = match interp.get_from(o, &key("then"), &resolution) {
Ok(t) => t,
@@ -584,10 +598,12 @@ impl Interp {
if self.frames.is_empty() {
let Some(job) = self.promises.queue.pop_front() else {
self.promises.draining = false;
// A pause asked for in the run's last step ends with the run.
self.pause.set(false);
return Ok(Some(self.promises.completion.take().unwrap_or(Value::Undefined)));
};
self.start_job(job)?;
if self.frames.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) {
if self.can_pause_between_jobs(pause_at) {
return Ok(None);
}
continue;
@@ -597,6 +613,7 @@ impl Interp {
Ok(Some(v)) if self.promises.running.is_none() => {
// The script's own code ended.
if self.promises.queue.is_empty() {
self.pause.set(false);
return Ok(Some(v));
}
self.promises.completion = Some(v);
@@ -606,12 +623,19 @@ impl Interp {
Err(Abrupt::Throw(v)) if self.promises.running.is_some() => self.finish_job(Err(v))?,
Err(e) => return Err(e),
}
if self.frames.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) {
if self.can_pause_between_jobs(pause_at) {
return Ok(None);
}
}
}
/// No code is running and jobs are still queued, and the slice has used its fuel or the host
/// asked for a pause. With the queue empty the run is done instead, and the next turn of the
/// loop ends it.
fn can_pause_between_jobs(&self, pause_at: u64) -> bool {
self.frames.is_empty() && !self.promises.queue.is_empty() && (self.fuel <= pause_at || self.pause.replace(false))
}
fn job_returned(&mut self, r: JsResult<Value>) -> JsResult<()> {
match r {
Ok(v) => self.finish_job(Ok(v)),
@@ -632,7 +656,14 @@ impl Interp {
return if reject { reject_promise(interp, derived, argument, site) } else { resolve_promise(interp, derived, argument) };
}
root(interp, &Value::Object(derived));
(handler, Value::Undefined, vec![argument], Then::Settle(derived))
match finally_callback(interp, &handler) {
// The callback runs as the job's own call, so a slice can pause inside it.
Some((on_finally, throws)) => {
interp.temp_roots.extend([handler, argument.clone()]);
(on_finally, Value::Undefined, Vec::new(), Then::Finally { derived, value: argument, throws })
}
None => (handler, Value::Undefined, vec![argument], Then::Settle(derived)),
}
}
Job::Thenable { promise, thenable, then } => {
interp.temp_roots.extend([Value::Object(promise), thenable.clone(), then.clone()]);
@@ -665,6 +696,18 @@ impl Interp {
root(interp, &Value::Object(rec));
reject_through(interp, rec, e, site)
}),
(Then::Finally { derived, value, throws }, Ok(result)) => scoped(self, |interp| {
interp.temp_roots.extend([Value::Object(derived), value.clone(), result.clone()]);
match after_finally(interp, result, value, throws) {
Ok(v) => resolve_promise(interp, derived, v),
Err(Abrupt::Throw(e)) => {
let site = caught(interp);
reject_promise(interp, derived, e, site)
}
Err(e) => Err(e),
}
}),
(Then::Finally { derived, .. }, Err(e)) => reject_promise(self, derived, e, site),
}
}
@@ -673,7 +716,8 @@ impl Interp {
pub(crate) fn end_jobs(&mut self, keep_rejections: bool) {
let queued = self.promises.queue_bytes();
self.heap.bytes = self.heap.bytes.saturating_sub(queued);
self.promises.queue.clear();
// A new queue frees the old one's buffer, which the heap estimate does not count.
self.promises.queue = VecDeque::new();
self.promises.running = None;
self.promises.completion = None;
self.promises.draining = false;
@@ -799,8 +843,15 @@ fn finally_step(interp: &mut Interp, args: &[Value], throws: bool) -> JsResult<V
let Record::Finally { on_finally } = record(interp, &rec_value)? else { return Err(Abrupt::Internal("not a finally record".into())) };
let on_finally = on_finally.clone();
let result = interp.call(&on_finally, &Value::Undefined, &[])?;
after_finally(interp, result, value, throws)
}
/// The steps of Then Finally and Catch Finally after the callback returned `result`: a promise
/// that passes `value` on, or throws it again when `throws`, once `result` settles.
fn after_finally(interp: &mut Interp, result: Value, value: Value, throws: bool) -> JsResult<Value> {
scoped(interp, |interp| {
root(interp, &value);
root(interp, &result);
let ctor = interp.promises.ctor.map_or(Value::Undefined, Value::Object);
let promise = promise_resolve(interp, &ctor, result)?;
root(interp, &promise);
@@ -812,6 +863,29 @@ fn finally_step(interp: &mut Interp, args: &[Value], throws: bool) -> JsResult<V
})
}
/// When `handler` is the Then Finally or Catch Finally function of a `finally` call, its callback,
/// and whether the function throws the value it gets again.
fn finally_callback(interp: &Interp, handler: &Value) -> Option<(Value, bool)> {
let Some(Class::Function(Func::Bound { target, args, .. })) = handler.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) else {
return None;
};
let natives = &interp.promises.natives;
let throws = if natives.get(Kind::ThenFinally as usize) == Some(target) {
false
} else if natives.get(Kind::CatchFinally as usize) == Some(target) {
true
} else {
return None;
};
match args.first().and_then(Value::as_object).and_then(|o| interp.heap.object(o)).map(|o| &o.class) {
Some(Class::PromiseRecord(rec)) => match &**rec {
Record::Finally { on_finally } => Some((on_finally.clone(), throws)),
_ => None,
},
_ => None,
}
}
fn then_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
finally_step(interp, args, false)
}
@@ -934,10 +1008,12 @@ fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsRe
})
}
/// Where the inputs of `Promise.all`, `allSettled` and `race` come from.
/// Where the inputs of `Promise.all`, `allSettled` and `race` come from. An array is read up to
/// its length at each step, as an array iterator reads it, and another object up to the `length`
/// it had at the start.
enum Inputs {
Indexed { object: ObjId, length: f64 },
CodePoints(Vec<u16>),
CodePoints(Rc<[u16]>),
}
impl Inputs {
@@ -949,7 +1025,7 @@ impl Inputs {
}
_ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))),
},
Value::String(s) => Ok(Inputs::CodePoints(s.flat().to_vec())),
Value::String(s) => Ok(Inputs::CodePoints(flat_charged(interp, s)?)),
_ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))),
}
}
@@ -958,7 +1034,11 @@ impl Inputs {
fn get(&self, interp: &mut Interp, index: &mut f64) -> JsResult<Option<Value>> {
match self {
Inputs::Indexed { object, length } => {
if *index >= *length {
let end = match interp.heap.object(*object).map(|o| &o.class) {
Some(Class::Array { length, .. }) => f64::from(*length),
_ => *length,
};
if *index >= end {
return Ok(None);
}
let v = super::get_at(interp, *object, *index)?;
+116 -1
View File
@@ -76,6 +76,26 @@ fn a_promise_resolved_with_itself_rejects_with_a_type_error() {
assert_eq!(log(src), "true");
}
#[test]
fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() {
let src = "var bad = 0; function check(e) { if (!(e instanceof TypeError)) bad++; }\n\
for (var i = 0; i < 200; i++) { var res; var p = new Promise(function (r) { res = r; }); p.then(null, check); res(p); }";
let mut finished = 0;
for spare in (40_000..240_000).step_by(641) {
let mut r = realm();
let live = r.collect_garbage();
r.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() });
match r.run(src) {
Ok(_) => finished += 1,
Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => continue,
Err(e) => panic!("{spare}: {e:?}"),
}
r.set_limits(Limits::default());
assert_eq!(r.run("bad"), Ok(JsValue::Number(0.0)), "{spare}");
}
assert!(finished > 0);
}
#[test]
fn catch_finally_and_the_combinators_settle_as_the_specification_says() {
let src = "Promise.reject(new Error('x')).catch(function (e) { log.push('caught ' + e.message); });\n\
@@ -104,6 +124,36 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() {
}
}
#[test]
fn the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_to_its_first_length() {
// `Promise.resolve` runs once for each input and appends to the input while it is read.
let src = "var resolve = Promise.resolve; var input;\n\
Promise.resolve = function (x) {\n\
if (input.length < 3) { input[input.length] = x + 1; if (!(input instanceof Array)) input.length++; }\n\
return resolve.call(this, x);\n\
};\n\
input = [1]; Promise.all(input).then(function (v) { log.push('array ' + v.join(',')); });\n\
input = { length: 1, 0: 1 }; Promise.all(input).then(function (v) { log.push('object ' + v.join(',')); });";
let out = log(src);
assert!(out.contains("array 1,2,3"), "{out}");
assert!(out.contains("object 1"), "{out}");
assert!(!out.contains("object 1,"), "{out}");
}
#[test]
fn a_string_a_combinator_reads_is_charged_to_the_heap_before_it_is_flattened() {
// A rope of 4 Mi code units is a few nodes until it is flattened to 8 MiB, more than the heap
// has room for. The combinator would stop at its first input.
let mut r = realm();
r.run("var s = 'ab'; for (var i = 0; i < 21; i++) s = s + s; var calls = 0; Promise.resolve = function () { calls++; throw 'stop'; };").unwrap();
let live = r.collect_garbage();
r.set_limits(Limits { heap_bytes: live + (1 << 20), ..Limits::default() });
let e = r.run("Promise.race(s)").unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}");
r.set_limits(Limits::default());
assert_eq!(r.run("calls").unwrap(), JsValue::Number(0.0));
}
#[test]
fn calling_promise_without_new_or_without_an_executor_is_a_type_error() {
let mut r = realm();
@@ -206,18 +256,83 @@ fn a_sliced_run_pauses_inside_the_jobs_and_ends_once_the_queue_is_empty() {
assert_eq!(r.run("t").unwrap(), JsValue::Number(12_497_500.0));
}
#[test]
fn a_sliced_run_whose_last_job_ends_a_slice_is_done_in_that_slice() {
let mut r = realm();
r.start("Promise.resolve().then(); Promise.reject(1).then(null, function () {}); 'done'").unwrap();
let v = loop {
match r.advance(1).unwrap() {
Progress::Paused => {
let interp = r.interp();
assert!(!interp.frames.is_empty() || interp.promises.queue_size().0 > 0, "paused with nothing left to run");
}
Progress::Done(v) => break v,
}
};
assert_eq!(v, JsValue::String("done".into()));
assert!(!r.is_running());
}
#[test]
fn a_pause_the_last_job_asks_for_does_not_pause_the_next_run() {
let mut r = realm();
let flag = r.pause_flag();
r.define_function("pauseNow", move |_| {
flag.set(true);
Ok(JsValue::Undefined)
});
r.start("Promise.resolve().then(pauseNow); 'first'").unwrap();
assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::String("first".into())));
r.start("var a = 1; var b = 2; a + b").unwrap();
assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::Number(3.0)));
}
#[test]
fn a_sliced_run_pauses_inside_a_finally_callback() {
let mut r = realm();
r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() });
r.set_unbroken_fuel(5_000);
r.start(
"var t = 0, kept, caught; function work() { for (var i = 0; i < 5000; i++) t += i; return Promise.resolve('ignored'); }\n\
Promise.resolve(1).finally(work).then(function (v) { kept = v; });\n\
Promise.reject(2).finally(work).then(null, function (e) { caught = e; });\n\
'done'",
)
.unwrap();
let mut paused_in_jobs = 0;
let v = loop {
match r.advance(500).unwrap() {
Progress::Paused => {
if r.interp().promises.draining {
paused_in_jobs += 1;
}
}
Progress::Done(v) => break v,
}
};
assert_eq!(v, JsValue::String("done".into()));
assert!(paused_in_jobs > 10, "{paused_in_jobs}");
assert_eq!(r.run("t + ' ' + kept + ' ' + caught").unwrap(), JsValue::String("24995000 1 2".into()));
}
#[test]
fn an_ended_sliced_run_drops_its_jobs() {
let mut r = realm();
r.start("var ran = 0; Promise.resolve().then(function () { for (;;) ran++; });").unwrap();
r.start(
"var ran = 0, after = false; Promise.resolve().then(function () { for (;;) ran++; }); Promise.resolve().then(function () { after = true; });",
)
.unwrap();
let mut slices = 0;
while r.advance(500).unwrap() == Progress::Paused && !r.interp().promises.draining {
slices += 1;
assert!(slices < 1000);
}
assert!(r.is_running());
assert_eq!(r.interp().promises.queue_size().0, 1);
r.end();
assert!(!r.is_running());
assert_eq!(r.interp().promises.queue_bytes(), 0);
assert_eq!(r.interp().promises.queue_size(), (0, 0));
assert_eq!(r.run("typeof ran").unwrap(), JsValue::String("number".into()));
assert_eq!(r.run("after").unwrap(), JsValue::Bool(false));
}
+1 -1
View File
@@ -734,7 +734,7 @@ fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool
Ok(JsValue::Undefined)
});
let result = realm.run(script);
if asynchronous && result.is_ok() {
if asynchronous && result.is_ok() && negative_type.is_none() {
let printed = printed.borrow();
return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") {
Ok(())