nova_vm 1.0.0

Nova Virtual Machine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
// 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/.

//! ## [7.4 Operations on Iterator Objects](https://tc39.es/ecma262/#sec-operations-on-iterator-objects)

use crate::{
    ecmascript::{
        Agent, ArgumentsList, BUILTIN_STRING_MEMORY, ExceptionType, Function, JsError, JsResult,
        Object, OrdinaryObject, PropertyKey, Value, call_function, get, get_method,
        get_object_method, is_callable, to_boolean, try_get_object_method,
        try_result_into_option_js,
    },
    engine::{
        Bindable, GcScope, NoGcScope, Scopable, ScopableCollection, ScopedCollection,
        VmIteratorRecord, bindable_handle,
    },
    heap::{
        CompactionLists, HeapMarkAndSweep, ObjectEntry, ObjectEntryPropertyDescriptor,
        WellKnownSymbols, WorkQueues,
    },
};

/// ### [7.4.1 Iterator Records](https://tc39.es/ecma262/#sec-iterator-records)
///
/// An Iterator Record is a Record value used to encapsulate an Iterator or
/// AsyncIterator along with the next method.
#[derive(Debug, Clone, Copy)]
pub(crate) struct IteratorRecord<'a> {
    pub(crate) iterator: Object<'a>,
    pub(crate) next_method: Function<'a>,
    // Note: The done field doesn't seem to be used anywhere.
    // pub(crate) done: bool,
}

bindable_handle!(IteratorRecord);

/// ### [7.4.2 GetIteratorDirect ( obj )](https://tc39.es/ecma262/#sec-getiteratordirect)
/// The abstract operation GetIteratorDirect takes argument obj (an Object) and returns
/// either a normal completion containing an Iterator Record or a throw completion.
///
/// Note: Different from the spec, this method returns None if the iterator
/// object's next method isn't callable.
pub(crate) fn get_iterator_direct<'gc>(
    agent: &mut Agent,
    obj: Object,
    mut gc: GcScope<'gc, '_>,
) -> JsResult<'gc, Option<IteratorRecord<'gc>>> {
    let obj = obj.bind(gc.nogc());

    let scoped_obj = obj.scope(agent, gc.nogc());
    // 1. Let nextMethod be ? Get(obj, "next").
    let next_method = get(
        agent,
        obj.unbind(),
        BUILTIN_STRING_MEMORY.next.into(),
        gc.reborrow(),
    )
    .unbind()?;
    let gc = gc.into_nogc();

    let Some(next_method) = is_callable(next_method, gc) else {
        return Ok(None);
    };

    // 2. Let iteratorRecord be the Iterator Record { [[Iterator]]: obj, [[NextMethod]]: nextMethod, [[Done]]: false }.
    let iterator_record = IteratorRecord {
        iterator: scoped_obj.get(agent).bind(gc),
        next_method,
    };

    // 3. Return iteratorRecord.
    Ok(Some(iterator_record))
}

pub(crate) struct MaybeInvalidIteratorRecord<'a> {
    pub(crate) iterator: Object<'a>,
    pub(crate) next_method: Option<Function<'a>>,
}

impl<'a> MaybeInvalidIteratorRecord<'a> {
    pub(crate) fn into_iterator_record(self) -> Option<IteratorRecord<'a>> {
        if let MaybeInvalidIteratorRecord {
            iterator,
            next_method: Some(next_method),
        } = self
        {
            Some(IteratorRecord {
                iterator,
                next_method,
            })
        } else {
            None
        }
    }

    pub(crate) fn into_vm_iterator_record(self) -> VmIteratorRecord<'a> {
        let MaybeInvalidIteratorRecord {
            iterator,
            next_method,
        } = self;
        if let Some(next_method) = next_method {
            VmIteratorRecord::GenericIterator(IteratorRecord {
                iterator,
                next_method,
            })
        } else {
            VmIteratorRecord::InvalidIterator { iterator }
        }
    }
}

bindable_handle!(MaybeInvalidIteratorRecord);

/// ### [7.4.3 GetIteratorFromMethod ( obj, method )](https://tc39.es/ecma262/#sec-getiteratorfrommethod)
///
/// The abstract operation GetIteratorFromMethod takes arguments obj (an
/// ECMAScript language value) and method (a function object) and returns
/// either a normal completion containing an Iterator Record or a throw
/// completion.
///
/// Note: Different from the spec, this method returns None if the iterator
/// object's next method isn't callable.
pub(crate) fn get_iterator_from_method<'a>(
    agent: &mut Agent,
    obj: Value,
    method: Function,
    mut gc: GcScope<'a, '_>,
) -> JsResult<'a, MaybeInvalidIteratorRecord<'a>> {
    let obj = obj.bind(gc.nogc());
    let method = method.bind(gc.nogc());
    // 1. Let iterator be ? Call(method, obj).
    let iterator = call_function(agent, method.unbind(), obj.unbind(), None, gc.reborrow())
        .unbind()?
        .bind(gc.nogc());

    // 2. If iterator is not an Object, throw a TypeError exception.
    let Ok(iterator) = Object::try_from(iterator) else {
        return Err(agent.throw_exception_with_static_message(
            ExceptionType::TypeError,
            "Iterator is not an object",
            gc.into_nogc(),
        ));
    };

    let scoped_iterator = iterator.scope(agent, gc.nogc());
    // 3. Let nextMethod be ? Get(iterator, "next").
    let next_method = get(
        agent,
        iterator.unbind(),
        BUILTIN_STRING_MEMORY.next.into(),
        gc.reborrow(),
    )
    .unbind()?;
    let gc = gc.into_nogc();
    // SAFETY: not shared.
    let iterator = unsafe { scoped_iterator.take(agent).bind(gc) };

    let next_method = is_callable(next_method, gc);

    // 4. Let iteratorRecord be the Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }.
    // 5. Return iteratorRecord.
    Ok(MaybeInvalidIteratorRecord {
        iterator,
        next_method,
        // done: false,
    })
}

/// ### [7.4.4 GetIterator ( obj, kind )](https://tc39.es/ecma262/#sec-getiterator)
///
/// The abstract operation GetIterator takes arguments obj (an ECMAScript
/// language value) and kind (sync or async) and returns either a normal
/// completion containing an Iterator Record or a throw completion.
pub(crate) fn get_iterator<'a>(
    agent: &mut Agent,
    obj: Value,
    is_async: bool,
    mut gc: GcScope<'a, '_>,
) -> JsResult<'a, MaybeInvalidIteratorRecord<'a>> {
    let obj = obj.bind(gc.nogc());
    let scoped_obj = obj.scope(agent, gc.nogc());
    // 1. If kind is async, then
    let method = if is_async {
        // a. Let method be ? GetMethod(obj, @@asyncIterator).
        let method = get_method(
            agent,
            obj.unbind(),
            PropertyKey::Symbol(WellKnownSymbols::AsyncIterator.into()),
            gc.reborrow(),
        )
        .unbind()?
        .bind(gc.nogc());

        // b. If method is undefined, then
        if method.is_none() {
            // i. Let syncMethod be ? GetMethod(obj, @@iterator).
            let Some(sync_method) = get_method(
                agent,
                scoped_obj.get(agent),
                PropertyKey::Symbol(WellKnownSymbols::Iterator.into()),
                gc.reborrow(),
            )
            .unbind()?
            .bind(gc.nogc()) else {
                // ii. If syncMethod is undefined, throw a TypeError exception.
                return Err(agent.throw_exception_with_static_message(
                    ExceptionType::TypeError,
                    "No iterator on object",
                    gc.into_nogc(),
                ));
            };

            // iii. Let syncIteratorRecord be ? GetIteratorFromMethod(obj, syncMethod).
            let _sync_iterator_record = get_iterator_from_method(
                agent,
                scoped_obj.get(agent),
                sync_method.unbind(),
                gc.reborrow(),
            )
            .unbind()?
            .bind(gc.nogc());

            // iv. Return CreateAsyncFromSyncIterator(syncIteratorRecord).
            todo!("Implement create_async_from_sync_iterator(sync_iterator_record)")
        } else {
            method
        }
    } else {
        // 2. Else,
        // a. Let method be ? GetMethod(obj, @@iterator).
        get_method(
            agent,
            obj.unbind(),
            PropertyKey::Symbol(WellKnownSymbols::Iterator.into()),
            gc.reborrow(),
        )
        .unbind()?
        .bind(gc.nogc())
    };

    // 3. If method is undefined, throw a TypeError exception.
    let Some(method) = method else {
        return Err(agent.throw_exception_with_static_message(
            ExceptionType::TypeError,
            "Iterator method cannot be undefined",
            gc.into_nogc(),
        ));
    };

    // 4. Return ? GetIteratorFromMethod(obj, method).
    get_iterator_from_method(agent, scoped_obj.get(agent), method.unbind(), gc)
}

/// ### [7.4.6 IteratorNext ( iteratorRecord [ , value ] )](https://tc39.es/ecma262/#sec-iteratornext)
///
/// The abstract operation IteratorNext takes argument iteratorRecord (an
/// Iterator Record) and optional argument value (an ECMAScript language value)
/// and returns either a normal completion containing an Object or a throw
/// completion.
pub(crate) fn iterator_next<'a>(
    agent: &mut Agent,
    iterator_record: IteratorRecord,
    // SAFETY: The value is immediately passed to Call and never used again:
    // We don't need to bind/unbind/worry about its lifetime.
    mut value: Option<Value<'static>>,
    mut gc: GcScope<'a, '_>,
) -> JsResult<'a, Object<'a>> {
    // 1. If value is not present, then
    // a. Let result be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]).
    // 2. Else,
    // a. Let result be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « value »).
    let result = call_function(
        agent,
        iterator_record.next_method,
        iterator_record.iterator.into(),
        value.as_mut().map(ArgumentsList::from_mut_value),
        gc.reborrow(),
    )
    .unbind()?;
    let gc = gc.into_nogc();
    let result = result.bind(gc);

    // 3. If result is not an Object, throw a TypeError exception.
    // 4. Return result.
    result
        .try_into()
        .or(Err(agent.throw_exception_with_static_message(
            ExceptionType::TypeError,
            "The iterator result was not an object",
            gc,
        )))
}

/// ### [7.4.7 IteratorComplete ( iterResult )](https://tc39.es/ecma262/#sec-iteratorcomplete)
///
/// The abstract operation IteratorComplete takes argument iterResult (an
/// Object) and returns either a normal completion containing a Boolean or a
/// throw completion.
pub(crate) fn iterator_complete<'a>(
    agent: &mut Agent,
    iter_result: Object,
    gc: GcScope<'a, '_>,
) -> JsResult<'a, bool> {
    // 1. Return ToBoolean(? Get(iterResult, "done")).
    let done = get(agent, iter_result, BUILTIN_STRING_MEMORY.done.into(), gc)?;
    Ok(to_boolean(agent, done))
}

/// ### [7.4.8 IteratorValue ( iterResult )](https://tc39.es/ecma262/#sec-iteratorvalue)
///
/// The abstract operation IteratorValue takes argument iterResult (an
/// Object) and returns either a normal completion containing an ECMAScript
/// language value or a throw completion.
pub(crate) fn iterator_value<'a>(
    agent: &mut Agent,
    iter_result: Object,
    gc: GcScope<'a, '_>,
) -> JsResult<'a, Value<'a>> {
    // 1. Return ? Get(iterResult, "value").
    get(agent, iter_result, BUILTIN_STRING_MEMORY.value.into(), gc)
}

/// ### [7.4.9 IteratorStep ( iteratorRecord )](https://tc39.es/ecma262/#sec-iteratorstep)
///
/// The abstract operation IteratorStep takes argument iteratorRecord (an
/// Iterator Record) and returns either a normal completion containing either
/// an Object or false, or a throw completion. It requests the next value from
/// iteratorRecord.\[\[Iterator\]\] by calling
/// iteratorRecord.\[\[NextMethod\]\] and returns either false indicating that
/// the iterator has reached its end or the IteratorResult object if a next
/// value is available.
///
/// > NOTE: Instead of returning the boolean value false we return an Option
/// > where the false state is None. That way we can pass the Object as is.
pub(crate) fn iterator_step<'a>(
    agent: &mut Agent,
    iterator_record: IteratorRecord,
    mut gc: GcScope<'a, '_>,
) -> JsResult<'a, Option<Object<'a>>> {
    // 1. Let result be ? IteratorNext(iteratorRecord).
    let result = iterator_next(agent, iterator_record, None, gc.reborrow())
        .unbind()?
        .bind(gc.nogc());
    let scoped_result = result.scope(agent, gc.nogc());

    // 2. Let done be ? IteratorComplete(result).
    let done = iterator_complete(agent, result.unbind(), gc.reborrow()).unbind()?;

    // 3. If done is true, return false.
    if done {
        return Ok(None);
    }

    // 4. Return result.
    // SAFETY: scoped_result is never shared.
    Ok(Some(unsafe {
        scoped_result.take(agent).bind(gc.into_nogc())
    }))
}

/// ### [7.4.10 IteratorStepValue ( iteratorRecord )](https://tc39.es/ecma262/#sec-iteratorstepvalue)
/// The abstract operation IteratorStepValue takes argument iteratorRecord
/// (an Iterator Record) and returns either a normal completion containing
/// either an ECMAScript language value or done, or a throw completion. It
/// requests the next value from iteratorRecord.[\[Iterator\]] by calling
/// iteratorRecord.[\[NextMethod\]] and returns either done indicating that the
/// iterator has reached its end or the value from the IteratorResult object if
/// a next value is available.
pub(crate) fn iterator_step_value<'a>(
    agent: &mut Agent,
    iterator_record: IteratorRecord,
    mut gc: GcScope<'a, '_>,
) -> JsResult<'a, Option<Value<'a>>> {
    // 1. Let result be Completion(IteratorNext(iteratorRecord)).
    let result = iterator_next(agent, iterator_record, None, gc.reborrow());

    // 2. If result is a throw completion, then
    let result = match result {
        Err(err) => {
            // a. Set iteratorRecord.[[Done]] to true.

            // b. Return ? result.
            return Err(err.unbind());
        }
        // 3. Set result to ! result.
        Ok(result) => result.unbind().bind(gc.nogc()),
    };
    let scoped_result = result.scope(agent, gc.nogc());

    // 4. Let done be Completion(IteratorComplete(result)).
    let done = iterator_complete(agent, result.unbind(), gc.reborrow())
        .unbind()
        .bind(gc.nogc());
    // SAFETY: scoped_result is never shared.
    let result = unsafe { scoped_result.take(agent) }.bind(gc.nogc());

    // 5. If done is a throw completion, then
    let done = match done {
        Err(err) => {
            // a. Set iteratorRecord.[[Done]] to true.
            // b. Return ? done.
            return Err(err.unbind());
        }
        // 6. Set done to ! done.
        Ok(done) => done,
    };

    // 7. If done is true, then
    if done {
        // a. Set iteratorRecord.[[Done]] to true.
        // b. Return done.
        return Ok(None);
    }

    // 8. Let value be Completion(Get(result, "value")).
    let value = get(
        agent,
        result.unbind(),
        BUILTIN_STRING_MEMORY.value.into(),
        gc,
    );

    // 9. If value is a throw completion, then
    // a. Set iteratorRecord.[[Done]] to true.
    // 10. Return ? value.
    value.map(Some)
}

/// ### [7.4.11 IteratorClose ( iteratorRecord, completion )](https://tc39.es/ecma262/#sec-iteratorclose)
///
/// The abstract operation IteratorClose takes arguments iteratorRecord (an
/// Iterator Record) and completion (a Completion Record) and returns a
/// Completion Record. It is used to notify an iterator that it should perform
/// any actions it would normally perform when it has reached its completed
/// state.
pub(crate) fn iterator_close_with_value<'a>(
    agent: &mut Agent,
    iterator: Object,
    completion: Value,
    mut gc: GcScope<'a, '_>,
) -> JsResult<'a, Value<'a>> {
    let mut iterator = iterator.bind(gc.nogc());
    let completion = completion.scope(agent, gc.nogc());
    // 1. Assert: iteratorRecord.[[Iterator]] is an Object.
    // 2. Let iterator be iteratorRecord.[[Iterator]].
    // 3. Let innerResult be Completion(GetMethod(iterator, "return")).
    let inner_result = if let Some(inner_result) = try_result_into_option_js(try_get_object_method(
        agent,
        iterator,
        BUILTIN_STRING_MEMORY.r#return.into(),
        gc.nogc(),
    )) {
        inner_result
    } else {
        let scoped_iterator = iterator.scope(agent, gc.nogc());
        let inner_result = get_object_method(
            agent,
            iterator.unbind(),
            BUILTIN_STRING_MEMORY.r#return.into(),
            gc.reborrow(),
        )
        .unbind()
        .bind(gc.nogc());
        // SAFETY: scoped_iterator is not shared.
        iterator = unsafe { scoped_iterator.take(agent) }.bind(gc.nogc());
        inner_result
    };
    // 4. If innerResult.[[Type]] is normal, then
    let inner_result = match inner_result {
        Ok(return_function) => {
            // a. Let return be innerResult.[[Value]].
            // b. If return is undefined, return ? completion.
            let Some(return_function) = return_function else {
                // SAFETY: completion is not shared.
                return Ok(unsafe { completion.take(agent) });
            };
            // c. Set innerResult to Completion(Call(return, iterator)).
            call_function(
                agent,
                return_function.unbind(),
                iterator.unbind().into(),
                None,
                gc.reborrow(),
            )
            .unbind()
            .bind(gc.nogc())
        }
        Err(inner_result) => Err(inner_result),
    };
    // SAFETY: completion is not shared.
    let completion = unsafe { completion.take(agent) }.bind(gc.nogc());

    // 5. If completion.[[Type]] is throw, return ? completion.
    // 6. If innerResult.[[Type]] is throw, return ? innerResult.
    let inner_result = inner_result.unbind()?.bind(gc.nogc());
    // 7. If innerResult.[[Value]] is not an Object, throw a TypeError exception.
    if !inner_result.is_object() {
        return Err(agent.throw_exception_with_static_message(
            ExceptionType::TypeError,
            "Invalid iterator 'return' method return value",
            gc.into_nogc(),
        ));
    }
    // 8. Return ? completion.
    Ok(completion.unbind())
}

/// ### [7.4.11 IteratorClose ( iteratorRecord, completion )](https://tc39.es/ecma262/#sec-iteratorclose)
///
/// The abstract operation IteratorClose takes arguments iteratorRecord (an
/// Iterator Record) and completion (a Completion Record) and returns a
/// Completion Record. It is used to notify an iterator that it should perform
/// any actions it would normally perform when it has reached its completed
/// state.
pub(crate) fn iterator_close_with_error<'a>(
    agent: &mut Agent,
    iterator: Object,
    completion: JsError,
    mut gc: GcScope<'a, '_>,
) -> JsError<'a> {
    let mut iterator = iterator.bind(gc.nogc());
    let completion = completion.scope(agent, gc.nogc());
    // 1. Assert: iteratorRecord.[[Iterator]] is an Object.
    // 2. Let iterator be iteratorRecord.[[Iterator]].
    // 3. Let innerResult be Completion(GetMethod(iterator, "return")).
    let inner_result = if let Some(inner_result) = try_result_into_option_js(try_get_object_method(
        agent,
        iterator,
        BUILTIN_STRING_MEMORY.r#return.into(),
        gc.nogc(),
    )) {
        inner_result
    } else {
        let scoped_iterator = iterator.scope(agent, gc.nogc());
        let inner_result = get_object_method(
            agent,
            iterator.unbind(),
            BUILTIN_STRING_MEMORY.r#return.into(),
            gc.reborrow(),
        )
        .unbind()
        .bind(gc.nogc());
        // SAFETY: scoped_iterator is not shared.
        iterator = unsafe { scoped_iterator.take(agent) }.bind(gc.nogc());
        inner_result
    };
    // 4. If innerResult.[[Type]] is normal, then
    if let Ok(Some(r#return)) = inner_result {
        // a. Let return be innerResult.[[Value]].
        // b. If return is undefined, return ? completion.
        // c. Set innerResult to Completion(Call(return, iterator)).
        let _ = call_function(
            agent,
            r#return.unbind(),
            iterator.unbind().into(),
            None,
            gc.reborrow(),
        );
    }
    // 5. If completion.[[Type]] is throw, return ? completion.
    // SAFETY: completion is not shared.
    unsafe { completion.take(agent) }
}

macro_rules! if_abrupt_close_iterator {
    ($agent:ident, $value:ident, $iterator_record:ident, $gc:ident) => {
        // 1. Assert: value is a Completion Record.
        // 2. If value is an abrupt completion, return ? IteratorClose(iteratorRecord, value).
        if let Err(err) = $value {
            return Err(
                crate::ecmascript::abstract_operations::iterator_close_with_error(
                    $agent,
                    $iterator_record.iterator.unbind(),
                    err.unbind(),
                    $gc,
                ),
            );
        } else if let Ok(value) = $value {
            value.unbind().bind($gc.nogc())
        } else {
            unreachable!();
        }
    };
}

pub(crate) use if_abrupt_close_iterator;

/// ### [7.4.14 CreateIterResultObject ( value, done )](https://tc39.es/ecma262/#sec-createiterresultobject)
///
/// The abstract operation CreateIterResultObject takes arguments value (an
/// ECMAScript language value) and done (a Boolean) and returns an Object that
/// conforms to the IteratorResult interface. It creates an object that
/// conforms to the IteratorResult interface.
pub(crate) fn create_iter_result_object<'a>(
    agent: &mut Agent,
    value: Value<'a>,
    done: bool,
    gc: NoGcScope<'a, '_>,
) -> JsResult<'a, OrdinaryObject<'a>> {
    // 1. Let obj be OrdinaryObjectCreate(%Object.prototype%).
    // 2. Perform ! CreateDataPropertyOrThrow(obj, "value", value).
    // 3. Perform ! CreateDataPropertyOrThrow(obj, "done", done).
    // 4. Return obj.
    OrdinaryObject::create_object(
        agent,
        Some(
            agent
                .current_realm_record()
                .intrinsics()
                .object_prototype()
                .into(),
        ),
        &[
            ObjectEntry {
                key: PropertyKey::from(BUILTIN_STRING_MEMORY.value),
                value: ObjectEntryPropertyDescriptor::Data {
                    value,
                    writable: true,
                    enumerable: true,
                    configurable: true,
                },
            },
            ObjectEntry {
                key: PropertyKey::from(BUILTIN_STRING_MEMORY.done),
                value: ObjectEntryPropertyDescriptor::Data {
                    value: done.into(),
                    writable: true,
                    enumerable: true,
                    configurable: true,
                },
            },
        ],
    )
    .map_err(|err| agent.throw_allocation_exception(err, gc))
}

/// ### [7.4.16 IteratorToList ( iteratorRecord )](https://tc39.es/ecma262/#sec-iteratortolist)
///
/// The abstract operation IteratorToList takes argument iteratorRecord (an
/// Iterator Record) and returns either a normal completion containing a List
/// of ECMAScript language values or a throw completion.
pub(crate) fn iterator_to_list<'a, 'b>(
    agent: &mut Agent,
    iterator_record: IteratorRecord,
    mut gc: GcScope<'a, 'b>,
) -> JsResult<'a, ScopedCollection<'b, Vec<Value<'static>>>> {
    // 1. Let values be a new empty List.
    let mut values = Vec::<Value>::new().scope(agent, gc.nogc());

    // 2. Let next be true.
    // 3. Repeat, while next is not false,
    // a. Set next to ? IteratorStep(iteratorRecord).
    // b. If next is not false, then
    while let Some(next) = iterator_step(agent, iterator_record, gc.reborrow())
        .unbind()?
        .bind(gc.nogc())
    {
        // i. Let nextValue be ? IteratorValue(next).
        let next_value = iterator_value(agent, next.unbind(), gc.reborrow())
            .unbind()?
            .bind(gc.nogc());
        // ii. Append nextValue to values.
        values.push(agent, next_value);
    }

    // 4. Return values.
    Ok(values)
}

impl HeapMarkAndSweep for IteratorRecord<'static> {
    fn mark_values(&self, queues: &mut WorkQueues) {
        let Self {
            iterator,
            next_method,
            // done: _,
        } = self;
        iterator.mark_values(queues);
        next_method.mark_values(queues);
    }

    fn sweep_values(&mut self, compactions: &CompactionLists) {
        let Self {
            iterator,
            next_method,
            // done: _,
        } = self;
        iterator.sweep_values(compactions);
        next_method.sweep_values(compactions);
    }
}