Skip to content

Implement Promise.all #797

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 20 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

pub(crate) mod promise_all_record;
pub mod promise_capability_records;
pub(crate) mod promise_jobs;
pub(crate) mod promise_reaction_records;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use core::ops::{Index, IndexMut};

use crate::{
ecmascript::{
builtins::{
Array, promise::Promise,
promise_objects::promise_abstract_operations::promise_capability_records::PromiseCapability,
},
execution::Agent,
types::{IntoValue, Value},
},
engine::context::{Bindable, GcScope, NoGcScope},
heap::{
CompactionLists, CreateHeapData, Heap, HeapMarkAndSweep, WorkQueues, indexes::BaseIndex,
},
};

#[derive(Debug, Clone, Copy)]
pub struct PromiseAllRecord<'a> {
pub remaining_unresolved_promise_count: u32,
pub result_array: Array<'a>,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thought: Here it might be more appropriate to use the ElementsVector type, though that is not quite so easy with its API as the Array is.

Hmmm, ElementsVector should maybe be renamed to List...

pub promise: Promise<'a>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct PromiseAll<'a>(pub(crate) BaseIndex<'a, PromiseAllRecord<'a>>);

impl<'a> PromiseAllRecord<'a> {
pub(crate) fn on_promise_fufilled(
&mut self,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Aight, let's move this method to PromiseAllRecord; it doesn't really need to change all that much. Assuming we set up the get and get_mut method on PromiseAllRecord then something like this ought to do:

pub(crate) fn on_promise_fufilled(
        self,
        agent: &mut Agent,
        index: u32,
        value: Value<'a>,
        mut gc: GcScope<'a, '_>,
    ) {
        let promise_all = self.bind(gc.nogc());
        let value = value.bind(gc.nogc());
        let data = promise_all.get_mut(&mut agent.heap.promise_all_records); // splitting heap borrow
        let result_array = data.result_array.bind(gc.nogc()); // note: this copies the handle from the heap to stack; on stack we must always bind to make sure we don't use the handle after GC.
        let elements = result_array.as_mut_slice(...arrayheap...); // we want to split the heap borrow so we can get the elements slice as mutable at the same time as we get data as mutable. ArrayHeap is the thing you want to pass here here, IIRC.
        elements[index as usize] = Some(value.unbind());

        data.remaining_unresolved_promise_count -= 1;
        if data.remaining_unresolved_promise_count == 0 {
          let capability = ...;
          capability.resolve(agent, result_array.into_value().unbind(), gc);
        }
}

Now everything should be up-and-up from the GC perspective.

agent: &mut Agent,
index: u32,
value: Value<'a>,
mut gc: GcScope<'a, '_>,
) {
value.bind(gc.nogc());
let elements = self.result_array.as_mut_slice(agent);
elements[index as usize] = Some(value.unbind());

self.remaining_unresolved_promise_count -= 1;
if self.remaining_unresolved_promise_count == 0 {
eprintln!("Promise fulfilled: {:#?}", elements);
let capability = PromiseCapability::from_promise(self.promise.unbind(), true);
capability.resolve(agent, self.result_array.into_value().unbind(), gc);
}
}
}

impl PromiseAll<'_> {
pub(crate) const fn get_index(self) -> usize {
self.0.into_index()
}
}

impl Index<PromiseAll<'_>> for Agent {
type Output = PromiseAllRecord<'static>;

fn index(&self, index: PromiseAll) -> &Self::Output {
&self.heap.promise_all_records[index]
}
}

impl IndexMut<PromiseAll<'_>> for Agent {
fn index_mut(&mut self, index: PromiseAll) -> &mut Self::Output {
&mut self.heap.promise_all_records[index]
}
}

impl Index<PromiseAll<'_>> for Vec<Option<PromiseAllRecord<'static>>> {
type Output = PromiseAllRecord<'static>;

fn index(&self, index: PromiseAll) -> &Self::Output {
self.get(index.get_index())
.expect("PromiseAllRecord out of bounds")
.as_ref()
.expect("PromiseAllRecord slot empty")
}
}

impl IndexMut<PromiseAll<'_>> for Vec<Option<PromiseAllRecord<'static>>> {
fn index_mut(&mut self, index: PromiseAll) -> &mut Self::Output {
self.get_mut(index.get_index())
.expect("PromiseAllRecord out of bounds")
.as_mut()
.expect("PromiseAllRecord slot empty")
}
}

impl HeapMarkAndSweep for PromiseAllRecord<'static> {
fn mark_values(&self, queues: &mut WorkQueues) {
let Self {
remaining_unresolved_promise_count: _,
result_array,
promise,
} = self;
result_array.mark_values(queues);
promise.mark_values(queues);
}

fn sweep_values(&mut self, compactions: &CompactionLists) {
let Self {
remaining_unresolved_promise_count: _,
result_array,
promise,
} = self;
result_array.sweep_values(compactions);
promise.sweep_values(compactions);
}
}

unsafe impl Bindable for PromiseAllRecord<'_> {
type Of<'a> = PromiseAllRecord<'a>;

#[inline(always)]
fn unbind(self) -> Self::Of<'static> {
unsafe { core::mem::transmute::<Self, Self::Of<'static>>(self) }
}

#[inline(always)]
fn bind<'a>(self, _gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
unsafe { core::mem::transmute::<Self, Self::Of<'a>>(self) }
}
}

impl HeapMarkAndSweep for PromiseAll<'static> {
fn mark_values(&self, queues: &mut WorkQueues) {
queues.promise_all_records.push(*self);
}

fn sweep_values(&mut self, compactions: &CompactionLists) {
compactions.promise_all_records.shift_index(&mut self.0);
}
}

unsafe impl Bindable for PromiseAll<'_> {
type Of<'a> = PromiseAll<'a>;

#[inline(always)]
fn unbind(self) -> Self::Of<'static> {
unsafe { core::mem::transmute::<Self, Self::Of<'static>>(self) }
}

#[inline(always)]
fn bind<'a>(self, _gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
unsafe { core::mem::transmute::<Self, Self::Of<'a>>(self) }
}
}

impl<'a> CreateHeapData<PromiseAllRecord<'a>, PromiseAll<'a>> for Heap {
fn create(&mut self, data: PromiseAllRecord<'a>) -> PromiseAll<'a> {
self.promise_all_records.push(Some(data.unbind()));
self.alloc_counter += core::mem::size_of::<Option<PromiseAllRecord<'static>>>();
PromiseAll(BaseIndex::last(&self.promise_all_records))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ impl PromiseReactionJob {
let Self { reaction, argument } = self;
let reaction = reaction.take(agent).bind(gc.nogc());
let argument = argument.take(agent).bind(gc.nogc());
// The following are substeps of point 1 in NewPromiseReactionJob.

let (handler_result, promise_capability) = match agent[reaction].handler {
PromiseReactionHandler::Empty => {
let capability = agent[reaction].capability.clone().unwrap().bind(gc.nogc());
Expand Down Expand Up @@ -288,6 +288,42 @@ impl PromiseReactionJob {
}
}
}
PromiseReactionHandler::PromiseAll { promise_all, index } => {
let capability = agent[reaction].capability.clone().unwrap().bind(gc.nogc());
match agent[reaction].reaction_type {
PromiseReactionType::Fulfill => {
// Take out the record to drop the vec borrow before we use `agent`/`gc`
let rec = {
let slot = agent
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: You don't want to do this; what you want to do instead is to implement the on_promise_fulfilled method on the PromiseAll "index" directly, and not on the "heap data record".

I assume you currently get an error about calling on_promise_fulfilled since rec_bound is bound to the GC lifetime and the call requires exclusive access to that; this is absolutely correct, as what is concretely happening here is that by taking rec out of the heap and onto the stack, you're bringing the Promise and Array indexes/handles onto the stack, where the GC cannot see them (our GC does not do stack scanning).

If GC triggers during on_promise_fulfilled, that will cause data to move on the heap and handles to need to be shifted to adjust. But now because the Promise and Array handles are on the stack where the GC cannot see them, they will not be adjusted. This leads to them pointing to either beyond the end of the heap vector (leading to a crash), or to some other Promise/Array (leading to very odd bugs).

To deal with this, we implement on_promise_fulfilled on the PromiseAll handle; I'll write more in the method implementation about what sort of things need to change there, if anything.

.heap
.promise_all_records
.get_mut(promise_all.get_index())
.expect("PromiseAllRecord out of bounds");
slot.take().expect("PromiseAllRecord slot empty")
};

// Bind to current scope and mutate
let mut rec_bound = rec.unbind().bind(gc.nogc());
rec_bound.on_promise_fufilled(
agent,
index,
argument.clone().unbind(),
gc.reborrow(),
);

// Write back with 'static lifetime
agent
.heap
.promise_all_records
.get_mut(promise_all.get_index())
.unwrap()
.replace(rec_bound.unbind());

(Ok(argument), capability)
}
PromiseReactionType::Reject => (Err(JsError::new(argument)), capability),
}
}
};

// f. If promiseCapability is undefined, then
Expand Down Expand Up @@ -348,7 +384,8 @@ pub(crate) fn new_promise_reaction_job(
| PromiseReactionHandler::AsyncFromSyncIteratorClose(_)
| PromiseReactionHandler::AsyncModule(_)
| PromiseReactionHandler::DynamicImport { .. }
| PromiseReactionHandler::DynamicImportEvaluate { .. } => None,
| PromiseReactionHandler::DynamicImportEvaluate { .. }
| PromiseReactionHandler::PromiseAll { .. } => None,
};

// 4. Return the Record { [[Job]]: job, [[Realm]]: handlerRealm }.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::{
async_generator_objects::AsyncGenerator,
control_abstraction_objects::async_function_objects::await_reaction::AwaitReaction,
promise::Promise,
promise_objects::promise_abstract_operations::promise_all_record::PromiseAll,
},
execution::Agent,
scripts_and_modules::module::module_semantics::{
Expand Down Expand Up @@ -68,6 +69,10 @@ pub(crate) enum PromiseReactionHandler<'a> {
promise: Promise<'a>,
module: AbstractModule<'a>,
},
PromiseAll {
index: u32,
promise_all: PromiseAll<'a>,
},
Empty,
}

Expand All @@ -85,6 +90,10 @@ impl HeapMarkAndSweep for PromiseReactionHandler<'static> {
promise.mark_values(queues);
module.mark_values(queues);
}
Self::PromiseAll {
index: _,
promise_all,
} => promise_all.mark_values(queues),
Self::Empty => {}
}
}
Expand All @@ -104,6 +113,12 @@ impl HeapMarkAndSweep for PromiseReactionHandler<'static> {
promise.sweep_values(compactions);
module.sweep_values(compactions);
}
Self::PromiseAll {
index: _,
promise_all,
} => {
promise_all.sweep_values(compactions);
}
Self::Empty => {}
}
}
Expand Down
Loading
Loading