Skip to content
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

[Merged by Bors] - Implement Async Generators #2200

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
754 changes: 754 additions & 0 deletions boa_engine/src/builtins/async_generator/mod.rs

Large diffs are not rendered by default.

129 changes: 129 additions & 0 deletions boa_engine/src/builtins/async_generator_function/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
//! This module implements the `AsyncGeneratorFunction` object.
//!
//! More information:
//! - [ECMAScript reference][spec]
//!
//! [spec]: https://tc39.es/ecma262/#sec-asyncgeneratorfunction-objects

use crate::{
builtins::{
function::{BuiltInFunctionObject, ConstructorKind, Function},
BuiltIn,
},
object::ObjectData,
property::PropertyDescriptor,
symbol::WellKnownSymbols,
value::JsValue,
Context, JsResult,
};
use boa_profiler::Profiler;

/// The internal representation on a `AsyncGeneratorFunction` object.
#[derive(Debug, Clone, Copy)]
pub struct AsyncGeneratorFunction;

impl BuiltIn for AsyncGeneratorFunction {
const NAME: &'static str = "AsyncGeneratorFunction";

fn init(context: &mut Context) -> Option<JsValue> {
let _timer = Profiler::global().start_event(Self::NAME, "init");

let prototype = &context
.intrinsics()
.constructors()
.async_generator_function()
.prototype;
let constructor = &context
.intrinsics()
.constructors()
.async_generator_function()
.constructor;

constructor.set_prototype(Some(
context.intrinsics().constructors().function().constructor(),
));
let property = PropertyDescriptor::builder()
.value(1)
.writable(false)
.enumerable(false)
.configurable(true);
constructor.borrow_mut().insert("length", property);
let property = PropertyDescriptor::builder()
.value(Self::NAME)
.writable(false)
.enumerable(false)
.configurable(true);
constructor.borrow_mut().insert("name", property);
let property = PropertyDescriptor::builder()
.value(
context
.intrinsics()
.constructors()
.async_generator_function()
.prototype(),
)
.writable(false)
.enumerable(false)
.configurable(false);
constructor.borrow_mut().insert("prototype", property);
constructor.borrow_mut().data = ObjectData::function(Function::Native {
function: Self::constructor,
constructor: Some(ConstructorKind::Base),
});

prototype.set_prototype(Some(
context.intrinsics().constructors().function().prototype(),
));
let property = PropertyDescriptor::builder()
.value(
context
.intrinsics()
.constructors()
.async_generator_function()
.constructor(),
)
.writable(false)
.enumerable(false)
.configurable(true);
prototype.borrow_mut().insert("constructor", property);
let property = PropertyDescriptor::builder()
.value(
context
.intrinsics()
.constructors()
.async_generator()
.prototype(),
)
.writable(false)
.enumerable(false)
.configurable(true);
prototype.borrow_mut().insert("prototype", property);
let property = PropertyDescriptor::builder()
.value("AsyncGeneratorFunction")
.writable(false)
.enumerable(false)
.configurable(true);
prototype
.borrow_mut()
.insert(WellKnownSymbols::to_string_tag(), property);

None
}
}

impl AsyncGeneratorFunction {
/// `AsyncGeneratorFunction ( p1, p2, … , pn, body )`
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-asyncgeneratorfunction
pub(crate) fn constructor(
new_target: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
BuiltInFunctionObject::create_dynamic_function(new_target, args, true, true, context)
.map(Into::into)
}
}
83 changes: 51 additions & 32 deletions boa_engine/src/builtins/function/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use crate::{
builtins::{BuiltIn, JsArgs},
bytecompiler::{FunctionCompiler, FunctionKind},
context::intrinsics::StandardConstructors,
environments::DeclarativeEnvironmentStack,
object::{
Expand Down Expand Up @@ -246,6 +247,10 @@ pub enum Function {
code: Gc<crate::vm::CodeBlock>,
environments: DeclarativeEnvironmentStack,
},
AsyncGenerator {
code: Gc<crate::vm::CodeBlock>,
environments: DeclarativeEnvironmentStack,
},
}

unsafe impl Trace for Function {
Expand All @@ -267,7 +272,8 @@ unsafe impl Trace for Function {
mark(environments);
mark(promise_capability);
}
Self::Generator { code, environments } => {
Self::Generator { code, environments }
| Self::AsyncGenerator { code, environments } => {
mark(code);
mark(environments);
}
Expand All @@ -288,7 +294,7 @@ impl Function {
Self::Native { constructor, .. } | Self::Closure { constructor, .. } => {
constructor.is_some()
}
Self::Generator { .. } | Self::Async { .. } => false,
Self::Generator { .. } | Self::AsyncGenerator { .. } | Self::Async { .. } => false,
Self::Ordinary { code, .. } => !(code.this_mode == ThisMode::Lexical),
}
}
Expand Down Expand Up @@ -476,7 +482,9 @@ impl BuiltInFunctionObject {
generator: bool,
context: &mut Context,
) -> JsResult<JsObject> {
let default = if r#async {
let default = if r#async && generator {
StandardConstructors::async_generator_function
} else if r#async {
StandardConstructors::async_function
} else if generator {
StandardConstructors::generator_function
Expand Down Expand Up @@ -518,6 +526,20 @@ impl BuiltInFunctionObject {
parameters
};

// It is a Syntax Error if FormalParameters Contains YieldExpression is true.
if generator && r#async && parameters.contains_yield_expression() {
return context.throw_syntax_error(
"yield expression not allowed in async generator parameters",
);
}

// It is a Syntax Error if FormalParameters Contains AwaitExpression is true.
if generator && r#async && parameters.contains_await_expression() {
return context.throw_syntax_error(
"await expression not allowed in async generator parameters",
);
}

let body_arg = body_arg.to_string(context)?;

let body = match Parser::new(body_arg.as_bytes()).parse_function_body(
Expand Down Expand Up @@ -581,20 +603,17 @@ impl BuiltInFunctionObject {
}
}

let code = crate::bytecompiler::ByteCompiler::compile_function_code(
crate::bytecompiler::FunctionKind::Expression,
Some(Sym::ANONYMOUS),
&parameters,
&body,
generator,
false,
context,
)?;
let code = FunctionCompiler::new()
.name(Sym::ANONYMOUS)
.generator(generator)
.r#async(r#async)
.kind(FunctionKind::Expression)
.compile(&parameters, &body, context)?;

let environments = context.realm.environments.pop_to_global();

let function_object = if generator {
crate::vm::create_generator_function_object(code, context)
crate::vm::create_generator_function_object(code, r#async, context)
} else {
crate::vm::create_function_object(code, r#async, Some(prototype), context)
};
Expand All @@ -603,31 +622,31 @@ impl BuiltInFunctionObject {

Ok(function_object)
} else if generator {
let code = crate::bytecompiler::ByteCompiler::compile_function_code(
crate::bytecompiler::FunctionKind::Expression,
Some(Sym::ANONYMOUS),
&FormalParameterList::empty(),
&StatementList::default(),
true,
false,
context,
)?;
let code = FunctionCompiler::new()
.name(Sym::ANONYMOUS)
.generator(true)
.kind(FunctionKind::Expression)
.compile(
&FormalParameterList::empty(),
&StatementList::default(),
context,
)?;

let environments = context.realm.environments.pop_to_global();
let function_object = crate::vm::create_generator_function_object(code, context);
let function_object =
crate::vm::create_generator_function_object(code, r#async, context);
context.realm.environments.extend(environments);

Ok(function_object)
} else {
let code = crate::bytecompiler::ByteCompiler::compile_function_code(
crate::bytecompiler::FunctionKind::Expression,
Some(Sym::ANONYMOUS),
&FormalParameterList::empty(),
&StatementList::default(),
false,
false,
context,
)?;
let code = FunctionCompiler::new()
.name(Sym::ANONYMOUS)
.kind(FunctionKind::Expression)
.compile(
&FormalParameterList::empty(),
&StatementList::default(),
context,
)?;

let environments = context.realm.environments.pop_to_global();
let function_object =
Expand Down
30 changes: 30 additions & 0 deletions boa_engine/src/builtins/iterable/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ use boa_profiler::Profiler;
pub struct IteratorPrototypes {
/// %IteratorPrototype%
iterator_prototype: JsObject,
/// %AsyncIteratorPrototype%
async_iterator_prototype: JsObject,
/// %MapIteratorPrototype%
array_iterator: JsObject,
/// %SetIteratorPrototype%
Expand All @@ -33,6 +35,7 @@ impl IteratorPrototypes {
let _timer = Profiler::global().start_event("IteratorPrototypes::init", "init");

let iterator_prototype = create_iterator_prototype(context);
let async_iterator_prototype = create_async_iterator_prototype(context);
Self {
array_iterator: ArrayIterator::create_prototype(iterator_prototype.clone(), context),
set_iterator: SetIterator::create_prototype(iterator_prototype.clone(), context),
Expand All @@ -44,6 +47,7 @@ impl IteratorPrototypes {
map_iterator: MapIterator::create_prototype(iterator_prototype.clone(), context),
for_in_iterator: ForInIterator::create_prototype(iterator_prototype.clone(), context),
iterator_prototype,
async_iterator_prototype,
}
}

Expand All @@ -57,6 +61,11 @@ impl IteratorPrototypes {
self.iterator_prototype.clone()
}

#[inline]
pub fn async_iterator_prototype(&self) -> JsObject {
self.async_iterator_prototype.clone()
}

#[inline]
pub fn set_iterator(&self) -> JsObject {
self.set_iterator.clone()
Expand Down Expand Up @@ -506,3 +515,24 @@ macro_rules! if_abrupt_close_iterator {

// Export macro to crate level
pub(crate) use if_abrupt_close_iterator;

/// Create the `%AsyncIteratorPrototype%` object
///
/// More information:
/// - [ECMA reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-asynciteratorprototype
#[inline]
fn create_async_iterator_prototype(context: &mut Context) -> JsObject {
let _timer = Profiler::global().start_event("AsyncIteratorPrototype", "init");

let symbol_iterator = WellKnownSymbols::async_iterator();
let iterator_prototype = ObjectInitializer::new(context)
.function(
|v, _, _| Ok(v.clone()),
(symbol_iterator, "[Symbol.asyncIterator]"),
0,
)
.build();
iterator_prototype
}
11 changes: 8 additions & 3 deletions boa_engine/src/builtins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
pub mod array;
pub mod array_buffer;
pub mod async_function;
pub mod async_generator;
pub mod async_generator_function;
pub mod bigint;
pub mod boolean;
pub mod dataview;
Expand Down Expand Up @@ -77,8 +79,9 @@ pub(crate) use self::{

use crate::{
builtins::{
array_buffer::ArrayBuffer, generator::Generator, generator_function::GeneratorFunction,
typed_array::TypedArray,
array_buffer::ArrayBuffer, async_generator::AsyncGenerator,
async_generator_function::AsyncGeneratorFunction, generator::Generator,
generator_function::GeneratorFunction, typed_array::TypedArray,
},
property::{Attribute, PropertyDescriptor},
Context, JsValue,
Expand Down Expand Up @@ -188,7 +191,9 @@ pub fn init(context: &mut Context) {
Generator,
GeneratorFunction,
Promise,
AsyncFunction
AsyncFunction,
AsyncGenerator,
AsyncGeneratorFunction
};

#[cfg(feature = "intl")]
Expand Down
6 changes: 4 additions & 2 deletions boa_engine/src/builtins/promise/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,22 @@ macro_rules! if_abrupt_reject_promise {
Err(value) => {
// a. Perform ? Call(capability.[[Reject]], undefined, « value.[[Value]] »).
$context.call(
&$capability.reject.clone().into(),
&$capability.reject().clone().into(),
&JsValue::undefined(),
&[value],
)?;

// b. Return capability.[[Promise]].
return Ok($capability.promise.clone().into());
return Ok($capability.promise().clone().into());
}
// 2. Else if value is a Completion Record, set value to value.[[Value]].
Ok(value) => value,
};
};
}

pub(crate) use if_abrupt_reject_promise;
raskad marked this conversation as resolved.
Show resolved Hide resolved

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PromiseState {
Pending,
Expand Down