diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index d960fac60b..52c0e229ae 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -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) -> 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 JsResult { 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 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 { 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), + 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> { 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)?; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 96e93764ff..8e03f2a136 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -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)); } diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 9f5223ea36..0c23a80e9b 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -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(())