Skip to content

Truly independent web browser

LibJS: Step generators without calling %GeneratorPrototype%.next

Aliaksandr Kalenik75e953699eae
diff --git a/Libraries/LibJS/Rust/src/runtime/generator_object.rs b/Libraries/LibJS/Rust/src/runtime/generator_object.rs
index 52921e50306..d2c71fe8554 100644
--- a/Libraries/LibJS/Rust/src/runtime/generator_object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/generator_object.rs
@@ -26,8 +26,9 @@ use crate::runtime::ecmascript_function_object::EcmascriptFunctionObject;
use crate::runtime::error::ErrorKind;
use crate::runtime::error_types::ErrorType;
use crate::runtime::function_object::FunctionObject;
+use crate::runtime::iterator::{BuiltinIteratorNext, BuiltinIteratorStep};
use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;
-use crate::runtime::object::MayInterfereWithIndexedPropertyAccess;
+use crate::runtime::object::{MayInterfereWithIndexedPropertyAccess, ORDINARY_OBJECT_METHODS, ObjectMethods};
use crate::runtime::shared_function_instance_data::FunctionKind;
/// Variant<GC::Ref<ECMAScriptFunctionObject>, GC::Ref<NativeJavaScriptBackedFunction>>: the function whose body a
@@ -114,7 +115,12 @@ pub struct GeneratorObject {
execute: GeneratorExecuteFunction,
}
-define_cell!(GeneratorObject, Object, extends: [Object], finalize: finalize);
+pub static GENERATOR_OBJECT_METHODS: ObjectMethods = ObjectMethods {
+ as_builtin_iterator_if_next_is_not_redefined: GeneratorObject::as_builtin_iterator_if_next_is_not_redefined,
+ ..ORDINARY_OBJECT_METHODS
+};
+
+define_cell!(GeneratorObject, Object, extends: [Object], methods: GENERATOR_OBJECT_METHODS, finalize: finalize);
impl Deref for GeneratorObject {
type Target = Object;
@@ -206,6 +212,38 @@ impl GeneratorObject {
Gc::from_ref(self)
}
+ fn as_builtin_iterator_if_next_is_not_redefined(_: &Object, next_method: Value) -> Option<BuiltinIteratorNext> {
+ if next_method.is_function() {
+ let next_function = next_method.as_function();
+ if let Some(realm) = next_function.realm()
+ && next_function == realm.generator_prototype_next_function()
+ {
+ return Some(GeneratorObject::builtin_next);
+ }
+ }
+ None
+ }
+
+ fn builtin_next(object: &Object, vm: &Vm) -> ThrowCompletionOr<BuiltinIteratorStep> {
+ let generator_object = object
+ .as_gc()
+ .downcast::<GeneratorObject>()
+ .expect("the builtin step of a GeneratorObject steps a GeneratorObject");
+
+ // 27.5.1.2 Generator.prototype.next ( value ), https://tc39.es/ecma262/#sec-generator.prototype.next
+ // 1. Return ? GeneratorResume(this value, value, empty).
+ // NB: IteratorStep calls next without arguments, so value is undefined.
+ let iteration_result = generator_object.resume(vm, Value::UNDEFINED, None)?;
+
+ if iteration_result.done {
+ return Ok(BuiltinIteratorStep::Done);
+ }
+ if iteration_result.value_is_iterator_result {
+ return Ok(BuiltinIteratorStep::IteratorResult(iteration_result.value.as_object()));
+ }
+ Ok(BuiltinIteratorStep::Value(iteration_result.value))
+ }
+
/// [[GeneratorContext]]. It lives out of line until the generator is finalized, so the pointer stays valid for
/// as long as the generator does.
fn generator_context(&self) -> NonNull<ExecutionContext> {
diff --git a/Libraries/LibJS/Rust/src/runtime/intrinsics.rs b/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
index de680681bbc..a0e4c00aa39 100644
--- a/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
+++ b/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
@@ -262,6 +262,7 @@ define_intrinsics! {
// Namespace/constructor object functions
array_prototype_values_function: Cell<Option<Gc<FunctionObject>>>,
date_constructor_now_function: Cell<Option<Gc<FunctionObject>>>,
+ generator_prototype_next_function: Cell<Option<Gc<FunctionObject>>>,
json_parse_function: Cell<Option<Gc<FunctionObject>>>,
json_stringify_function: Cell<Option<Gc<FunctionObject>>>,
object_prototype_to_string_function: Cell<Option<Gc<FunctionObject>>>,
@@ -515,6 +516,7 @@ created_intrinsics! {
unescape_function: FunctionObject => "%unescape%",
array_prototype_values_function: FunctionObject => "%Array.prototype.values%",
date_constructor_now_function: FunctionObject => "%Date.now%",
+ generator_prototype_next_function: FunctionObject => "%GeneratorFunction.prototype.prototype.next%",
json_parse_function: FunctionObject => "%JSON.parse%",
json_stringify_function: FunctionObject => "%JSON.stringify%",
object_prototype_to_string_function: FunctionObject => "%Object.prototype.toString%",
@@ -1482,6 +1484,11 @@ impl Intrinsics {
.get_without_side_effects(vm, &names.now)
.as_function(),
));
+ self.generator_prototype_next_function.set(Some(
+ self.generator_prototype()
+ .get_without_side_effects(vm, &names.next)
+ .as_function(),
+ ));
assert!(self.array_prototype(vm).indexed_array_like_size() == 0);
assert!(self.object_prototype(vm).indexed_array_like_size() == 0);
diff --git a/Libraries/LibJS/Rust/src/runtime/realm.rs b/Libraries/LibJS/Rust/src/runtime/realm.rs
index 08de4afb151..85defae88fc 100644
--- a/Libraries/LibJS/Rust/src/runtime/realm.rs
+++ b/Libraries/LibJS/Rust/src/runtime/realm.rs
@@ -86,6 +86,7 @@ realm_intrinsic_accessors! {
throw_type_error_accessor: Accessor,
throw_type_error_function: FunctionObject,
array_prototype_values_function: FunctionObject,
+ generator_prototype_next_function: FunctionObject,
eval_function: FunctionObject,
array_iterator_prototype: Object,
}
diff --git a/Tests/LibJS/Runtime/iterators/generator-builtin-step.js b/Tests/LibJS/Runtime/iterators/generator-builtin-step.js
new file mode 100644
index 00000000000..38214df0591
--- /dev/null
+++ b/Tests/LibJS/Runtime/iterators/generator-builtin-step.js
@@ -0,0 +1,220 @@
+const GeneratorPrototype = Object.getPrototypeOf(function* () {}).prototype;
+
+function* threeValues() {
+ yield 1;
+ yield 2;
+ yield 3;
+}
+
+function withRecordingGeneratorReturn(callback) {
+ const originalReturn = GeneratorPrototype.return;
+ let returnCalls = 0;
+ GeneratorPrototype.return = function () {
+ ++returnCalls;
+ return originalReturn.apply(this, arguments);
+ };
+ try {
+ callback();
+ } finally {
+ GeneratorPrototype.return = originalReturn;
+ }
+ return returnCalls;
+}
+
+// An iterator for yield* whose results log every read of done and value. The fourth result is done.
+function makeLoggingIterator(log, throwingGetter) {
+ let count = 0;
+ return {
+ [Symbol.iterator]() {
+ return this;
+ },
+ next() {
+ const n = ++count;
+ let doneReads = 0;
+ return {
+ get done() {
+ log.push(`done ${n}`);
+ // NB: yield* reads done first, so the second read is the one of the consumer.
+ if (throwingGetter?.done === n && ++doneReads === 2) throw new Error("done getter");
+ return n > 3;
+ },
+ get value() {
+ log.push(`value ${n}`);
+ if (throwingGetter?.value === n) throw new Error("value getter");
+ return n;
+ },
+ };
+ },
+ return() {
+ log.push("return");
+ return {};
+ },
+ };
+}
+
+function* delegate(iterator) {
+ return yield* iterator;
+}
+
+test("an own next method of a generator is used", () => {
+ const generator = threeValues();
+ let nextCalls = 0;
+ generator.next = function () {
+ ++nextCalls;
+ return GeneratorPrototype.next.call(this);
+ };
+ expect([...generator]).toEqual([1, 2, 3]);
+ expect(nextCalls).toBe(4);
+});
+
+test("iterating a generator", () => {
+ const values = [];
+ for (const value of threeValues()) values.push(value);
+ expect(values).toEqual([1, 2, 3]);
+ expect([...threeValues()]).toEqual([1, 2, 3]);
+ expect(Array.from(threeValues())).toEqual([1, 2, 3]);
+ const [first, second, ...rest] = threeValues();
+ expect([first, second, rest]).toEqual([1, 2, [3]]);
+ expect(
+ threeValues()
+ .map(value => value * 2)
+ .toArray()
+ ).toEqual([2, 4, 6]);
+ expect(threeValues().drop(1).toArray()).toEqual([2, 3]);
+ expect(threeValues().take(2).toArray()).toEqual([1, 2]);
+});
+
+test("array destructuring closes a generator it does not exhaust", () => {
+ const log = [];
+ function* generator() {
+ try {
+ yield 1;
+ yield 2;
+ } finally {
+ log.push("finally");
+ }
+ }
+ const [first] = generator();
+ expect(first).toBe(1);
+ expect(log).toEqual(["finally"]);
+});
+
+test("the return value of a generator is not iterated", () => {
+ function* generator() {
+ yield 1;
+ return 2;
+ }
+ const values = [];
+ for (const value of generator()) values.push(value);
+ expect(values).toEqual([1]);
+ expect([...generator()]).toEqual([1]);
+ expect(Array.from(generator())).toEqual([1]);
+});
+
+test("a generator that throws is not closed", () => {
+ function* generator() {
+ yield 1;
+ throw new Error("generator body");
+ }
+ let rejection;
+ const returnCalls = withRecordingGeneratorReturn(() => {
+ expect(() => {
+ for (const value of generator());
+ }).toThrowWithMessage(Error, "generator body");
+ Promise.all(generator()).catch(error => {
+ rejection = error;
+ });
+ });
+ runQueuedPromiseJobs();
+ expect(rejection.message).toBe("generator body");
+ expect(returnCalls).toBe(0);
+});
+
+test("stepping a generator that is executing throws", () => {
+ let generator;
+ function* callsNext() {
+ yield 1;
+ generator.next();
+ }
+ generator = callsNext();
+ expect(() => {
+ for (const value of generator);
+ }).toThrowWithMessage(TypeError, "Generator is already executing");
+
+ function* iteratesItself() {
+ yield 1;
+ for (const value of generator);
+ }
+ generator = iteratesItself();
+ expect(() => {
+ for (const value of generator);
+ }).toThrowWithMessage(TypeError, "Generator is already executing");
+});
+
+test("yield* results are read as before", () => {
+ const expectedLog = [
+ "done 1",
+ "done 1",
+ "value 1",
+ "done 2",
+ "done 2",
+ "value 2",
+ "done 3",
+ "done 3",
+ "value 3",
+ "done 4",
+ "value 4",
+ ];
+
+ let log = [];
+ const values = [];
+ for (const value of delegate(makeLoggingIterator(log))) values.push(value);
+ expect(values).toEqual([1, 2, 3]);
+ expect(log).toEqual(expectedLog);
+
+ log = [];
+ expect([...delegate(makeLoggingIterator(log))]).toEqual([1, 2, 3]);
+ expect(log).toEqual(expectedLog);
+
+ log = [];
+ const [first] = delegate(makeLoggingIterator(log));
+ expect(first).toBe(1);
+ expect(log).toEqual(["done 1", "done 1", "value 1", "return"]);
+});
+
+test("yield* results skipped by IteratorStep do not have their value read", () => {
+ const log = [];
+ expect(delegate(makeLoggingIterator(log)).drop(2).toArray()).toEqual([3]);
+ expect(log).toEqual(["done 1", "done 1", "done 2", "done 2", "done 3", "done 3", "value 3", "done 4", "value 4"]);
+});
+
+test("a yield* result with a throwing getter marks the iteration as done", () => {
+ for (const getter of ["done", "value"]) {
+ const log = [];
+ let rejection;
+ const returnCalls = withRecordingGeneratorReturn(() => {
+ Promise.all(delegate(makeLoggingIterator(log, { [getter]: 2 }))).catch(error => {
+ rejection = error;
+ });
+ });
+ runQueuedPromiseJobs();
+ expect(rejection.message).toBe(`${getter} getter`);
+ expect(returnCalls).toBe(0);
+ expect(log.includes("return")).toBeFalse();
+ }
+});
+
+test("%GeneratorPrototype%.next rejects iterator helpers", () => {
+ const helper = [1, 2].values().map(value => value * 2);
+ expect(() => GeneratorPrototype.next.call(helper)).toThrowWithMessage(
+ TypeError,
+ "Generator brand 'Iterator Helper' does not match generator brand '<empty>'"
+ );
+ expect([...helper]).toEqual([2, 4]);
+
+ const helperWithGeneratorNext = [1, 2].values().map(value => value * 2);
+ helperWithGeneratorNext.next = GeneratorPrototype.next;
+ expect(() => {
+ for (const value of helperWithGeneratorNext);
+ }).toThrowWithMessage(TypeError, "Generator brand 'Iterator Helper' does not match generator brand '<empty>'");
+});
diff --git a/Tests/LibJS/Runtime/redefine-next-in-builtin-iterators.js b/Tests/LibJS/Runtime/redefine-next-in-builtin-iterators.js
index 1e0ecc78678..7683b59daf5 100644
--- a/Tests/LibJS/Runtime/redefine-next-in-builtin-iterators.js
+++ b/Tests/LibJS/Runtime/redefine-next-in-builtin-iterators.js
@@ -43,4 +43,22 @@ describe("redefine next() in built in iterators", () => {
}
expect(counter).toBe(4);
});
+
+ test("redefine next() in %GeneratorPrototype%", () => {
+ function* generator() {
+ yield 1;
+ yield 2;
+ yield 3;
+ }
+ let generatorPrototype = Object.getPrototypeOf(generator.prototype);
+ let originalNext = generatorPrototype.next;
+ let counter = 0;
+ generatorPrototype.next = function () {
+ counter++;
+ return originalNext.apply(this, arguments);
+ };
+ for (let v of generator()) {
+ }
+ expect(counter).toBe(4);
+ });
});