ps-boa-engine 1.1.1

Boa is a Javascript lexer, parser and compiler written in Rust. Currently, it has support for some of the language.
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
use std::{cell::RefCell, mem::MaybeUninit};

use boa_string::JsString;
use dynify::Dynify;

use super::args::Argument;
use super::{IndexOperand, RegisterOperand};
use crate::{
    Context, JsError, JsExpect, JsObject, JsResult, JsValue, NativeFunction,
    builtins::{Promise, math::Math, promise::PromiseCapability},
    error::JsNativeError,
    job::NativeAsyncJob,
    module::{ImportAttribute, ModuleKind, ModuleRequest, Referrer},
    object::{FunctionObjectBuilder, internal_methods::InternalMethodPropertyContext},
    property::PropertyKey,
    string::StaticJsStrings,
    vm::opcode::Operation,
};

/// `CallEval` implements the Opcode Operation for `Opcode::CallEval`
///
/// Operation:
///  - Call a function named "eval".
#[derive(Debug, Clone, Copy)]
pub(crate) struct CallEval;

impl CallEval {
    #[inline(always)]
    pub(super) fn operation(
        (argument_count, scope_index): (IndexOperand, IndexOperand),
        context: &mut Context,
    ) -> JsResult<()> {
        let func = context
            .vm
            .stack
            .calling_convention_get_function(argument_count.into());

        let Some(object) = func.as_object() else {
            return Err(JsNativeError::typ()
                .with_message("not a callable function")
                .into());
        };

        // Taken from `13.3.6.1 Runtime Semantics: Evaluation`
        //            `CallExpression : CoverCallExpressionAndAsyncArrowHead`
        //
        // <https://tc39.es/ecma262/#sec-function-calls-runtime-semantics-evaluation>
        //
        // 6. If ref is a Reference Record, IsPropertyReference(ref) is false, and ref.[[ReferencedName]] is "eval", then
        //     a. If SameValue(func, %eval%) is true, then
        let eval = context.intrinsics().objects().eval();
        if JsObject::equals(&object, &eval) {
            let arguments = context
                .vm
                .stack
                .calling_convention_pop_arguments(argument_count.into());
            let _func = context.vm.stack.pop();
            let _this = context.vm.stack.pop();
            if let Some(x) = arguments.first() {
                // i. Let argList be ? ArgumentListEvaluation of arguments.
                // ii. If argList has no elements, return undefined.
                // iii. Let evalArg be the first element of argList.
                // iv. If the source text matched by this CallExpression is strict mode code,
                //     let strictCaller be true. Otherwise let strictCaller be false.
                // v. Return ? PerformEval(evalArg, strictCaller, true).
                let strict = context.vm.frame().code_block.strict();
                let scope = context
                    .vm
                    .frame()
                    .code_block()
                    .constant_scope(scope_index.into());
                let result = crate::builtins::eval::Eval::perform_eval(
                    x,
                    true,
                    Some(scope),
                    strict,
                    context,
                )?;
                context.vm.stack.push(result);
            } else {
                // NOTE: This is a deviation from the spec, to optimize the case when we dont pass anything to `eval`.
                context.vm.stack.push(JsValue::undefined());
            }

            return Ok(());
        }

        object.__call__(argument_count.into()).resolve(context)?;
        Ok(())
    }
}

impl Operation for CallEval {
    const NAME: &'static str = "CallEval";
    const INSTRUCTION: &'static str = "INST - CallEval";
    const COST: u8 = 5;
}

/// `CallEvalSpread` implements the Opcode Operation for `Opcode::CallEvalSpread`
///
/// Operation:
///  - Call a function named "eval" where the arguments contain spreads.
#[derive(Debug, Clone, Copy)]
pub(crate) struct CallEvalSpread;

impl CallEvalSpread {
    #[inline(always)]
    pub(super) fn operation(index: IndexOperand, context: &mut Context) -> JsResult<()> {
        // Get the arguments that are stored as an array object on the stack.
        let arguments_array = context.vm.stack.pop();
        let arguments_array_object = arguments_array
            .as_object()
            .js_expect("arguments array in call spread function must be an object")?;
        let arguments = arguments_array_object
            .borrow()
            .properties()
            .to_dense_indexed_properties()
            .js_expect("arguments array in call spread function must be dense")?;

        let func = context.vm.stack.calling_convention_get_function(0);

        let Some(object) = func.as_object() else {
            return Err(JsNativeError::typ()
                .with_message("not a callable function")
                .into());
        };
        // Taken from `13.3.6.1 Runtime Semantics: Evaluation`
        //            `CallExpression : CoverCallExpressionAndAsyncArrowHead`
        //
        // <https://tc39.es/ecma262/#sec-function-calls-runtime-semantics-evaluation>
        //
        // 6. If ref is a Reference Record, IsPropertyReference(ref) is false, and ref.[[ReferencedName]] is "eval", then
        //     a. If SameValue(func, %eval%) is true, then
        let eval = context.intrinsics().objects().eval();
        if JsObject::equals(&object, &eval) {
            let _func = context.vm.stack.pop();
            let _this = context.vm.stack.pop();
            if let Some(x) = arguments.first() {
                // i. Let argList be ? ArgumentListEvaluation of arguments.
                // ii. If argList has no elements, return undefined.
                // iii. Let evalArg be the first element of argList.
                // iv. If the source text matched by this CallExpression is strict mode code,
                //     let strictCaller be true. Otherwise let strictCaller be false.
                // v. Return ? PerformEval(evalArg, strictCaller, true).
                let strict = context.vm.frame().code_block.strict();
                let scope = context.vm.frame().code_block().constant_scope(index.into());
                let result = crate::builtins::eval::Eval::perform_eval(
                    x,
                    true,
                    Some(scope),
                    strict,
                    context,
                )?;
                context.vm.stack.push(result);
            } else {
                // NOTE: This is a deviation from the spec, to optimize the case when we dont pass anything to `eval`.
                context.vm.stack.push(JsValue::undefined());
            }

            return Ok(());
        }

        let argument_count = arguments.len();
        context
            .vm
            .stack
            .calling_convention_push_arguments(&arguments);

        object.__call__(argument_count).resolve(context)?;
        Ok(())
    }
}

impl Operation for CallEvalSpread {
    const NAME: &'static str = "CallEvalSpread";
    const INSTRUCTION: &'static str = "INST - CallEvalSpread";
    const COST: u8 = 5;
}

/// `Call` implements the Opcode Operation for `Opcode::Call`
///
/// Operation:
///  - Call a function
#[derive(Debug, Clone, Copy)]
pub(crate) struct Call;

impl Call {
    #[inline(always)]
    pub(super) fn operation(argument_count: IndexOperand, context: &mut Context) -> JsResult<()> {
        let func = context
            .vm
            .stack
            .calling_convention_get_function(argument_count.into());

        let Some(object) = func.as_object() else {
            return Err(Self::handle_not_callable());
        };

        object.__call__(argument_count.into()).resolve(context)?;

        Ok(())
    }

    #[cold]
    #[inline(never)]
    fn handle_not_callable() -> JsError {
        JsNativeError::typ()
            .with_message("not a callable function")
            .into()
    }
}

impl Operation for Call {
    const NAME: &'static str = "Call";
    const INSTRUCTION: &'static str = "INST - Call";
    const COST: u8 = 3;
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct CallSpread;

impl CallSpread {
    #[inline(always)]
    pub(super) fn operation((): (), context: &mut Context) -> JsResult<()> {
        // Get the arguments that are stored as an array object on the stack.
        let arguments_array = context.vm.stack.pop();
        let arguments_array_object = arguments_array
            .as_object()
            .js_expect("arguments array in call spread function must be an object")?;
        let arguments = arguments_array_object
            .borrow()
            .properties()
            .to_dense_indexed_properties()
            .js_expect("arguments array in call spread function must be dense")?;

        let argument_count = arguments.len();
        context
            .vm
            .stack
            .calling_convention_push_arguments(&arguments);

        let func = context
            .vm
            .stack
            .calling_convention_get_function(argument_count);

        let Some(object) = func.as_object() else {
            return Err(JsNativeError::typ()
                .with_message("not a callable function")
                .into());
        };

        object.__call__(argument_count).resolve(context)?;
        Ok(())
    }
}

impl Operation for CallSpread {
    const NAME: &'static str = "CallSpread";
    const INSTRUCTION: &'static str = "INST - CallSpread";
    const COST: u8 = 3;
}

/// Parses the import attributes from the options object.
fn parse_import_attributes(
    specifier: JsString,
    options: &JsValue,
    context: &mut Context,
) -> JsResult<ModuleRequest> {
    // Taken from `EvaluateImportCall`
    //
    // <https://tc39.es/ecma262/#sec-evaluate-import-call>

    // 1. Let attributes be a new empty List.
    let mut attributes = Vec::new();

    // 2. If options is not undefined, then
    if !options.is_undefined() {
        // a. If Type(options) is not Object, throw a TypeError exception.
        let Some(options_obj) = options.as_object() else {
            return Err(JsNativeError::typ()
                .with_message("import options must be an object or undefined")
                .into());
        };

        // b. Let attributesObj be ? Get(options, "with").
        let attributes_obj = options_obj.get(crate::js_str!("with"), context)?;

        // c. If attributesObj is not undefined, then
        if !attributes_obj.is_undefined() {
            // i. If Type(attributesObj) is not Object, throw a TypeError exception.
            let Some(attributes_obj) = attributes_obj.as_object() else {
                return Err(JsNativeError::typ()
                    .with_message("the 'with' option must be an object")
                    .into());
            };

            // ii. Let entries be ? EnumerableOwnProperties(attributesObj, "key+value").
            let entries = attributes_obj.enumerable_own_property_names(
                crate::property::PropertyNameKind::KeyAndValue,
                context,
            )?;

            // iii. For each entry in entries, do
            attributes.reserve(entries.len());
            for entry in entries {
                let entry = entry
                    .as_object()
                    .js_expect("entry from EnumerableOwnProperties must be an object")?;

                // 1. Let key be entry.[[Key]].
                let key = entry.get(0, context)?;
                let key_str = key
                    .as_string()
                    .js_expect("key from EnumerableOwnProperties must be a string")?
                    .clone();

                // 2. Let value be entry.[[Value]].
                let value = entry.get(1, context)?;

                // 3. If Type(value) is not String, throw a TypeError exception.
                let Some(value_str) = value.as_string() else {
                    return Err(JsNativeError::typ()
                        .with_message("import attribute value must be a string")
                        .into());
                };
                let value_str = value_str.clone();

                // 4. Append the Record { [[Key]]: key, [[Value]]: value } to attributes.
                attributes.push(ImportAttribute::new(key_str, value_str));
            }
        }
    }

    // 3. Return the Record { [[Specifier]]: specifier, [[Attributes]]: attributes }.
    Ok(ModuleRequest::new(specifier, attributes.into_boxed_slice()))
}

/// Loads the module of a dynamic import. This combines the operations:
/// - [`HostLoadImportedModule(referrer, specifierString, empty, promiseCapability).`][load]
/// - [`FinishLoadingImportedModule ( referrer, specifier, payload, result )`][finish]
/// - [`ContinueDynamicImport ( promiseCapability, moduleCompletion )`][continue]
///
/// [load]: https://tc39.es/ecma262/#sec-HostLoadImportedModule
/// [finish]: https://tc39.es/ecma262/#sec-FinishLoadingImportedModule
/// [continue]: https://tc39.es/ecma262/#sec-ContinueDynamicImport
async fn load_dyn_import(
    referrer: Referrer,
    request: ModuleRequest,
    cap: PromiseCapability,
    phase: u32,
    context: &RefCell<&mut Context>,
) -> JsResult<()> {
    let loader = context.borrow().module_loader();
    let fut = loader.load_imported_module(referrer.clone(), request.clone(), context);
    let mut stack = [MaybeUninit::<u8>::uninit(); 16];
    let mut heap = Vec::<MaybeUninit<u8>>::new();
    let completion = fut.init2(&mut stack, &mut heap).await;

    // `ContinueDynamicImport ( promiseCapability, moduleCompletion )`
    // https://tc39.es/ecma262/#sec-ContinueDynamicImport

    // `FinishLoadingImportedModule ( referrer, specifier, payload, result )`
    // https://tc39.es/ecma262/#sec-FinishLoadingImportedModule

    let module = match completion {
        // 1. If moduleCompletion is an abrupt completion, then
        Err(err) => {
            // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « moduleCompletion.[[Value]] »).
            let err = err.into_opaque(&mut context.borrow_mut())?;
            cap.reject()
                .call(&JsValue::undefined(), &[err], &mut context.borrow_mut())
                .expect("default `reject` function cannot throw");

            // b. Return unused.
            return Ok(());
        }
        Ok(m) => m,
    };

    // 1. If result is a normal completion, then
    match referrer {
        Referrer::Module(mod_ref) => {
            let ModuleKind::SourceText(src) = mod_ref.kind() else {
                panic!("referrer cannot be a synthetic module");
            };

            let mut loaded_modules = src.loaded_modules().borrow_mut();

            //     a. If referrer.[[LoadedModules]] contains a Record whose [[Specifier]] is specifier, then
            //     b. Else,
            //         i. Append the Record { [[Specifier]]: specifier, [[Module]]: result.[[Value]] } to referrer.[[LoadedModules]].
            let entry = loaded_modules
                .entry(request)
                .or_insert_with(|| module.clone());

            //         i. Assert: That Record's [[Module]] is result.[[Value]].
            debug_assert_eq!(&module, entry);

            // Same steps apply to referrers below
        }
        Referrer::Realm(realm) => {
            let mut loaded_modules = realm.loaded_modules().borrow_mut();
            let entry = loaded_modules
                .entry(request.specifier().clone())
                .or_insert_with(|| module.clone());
            debug_assert_eq!(&module, entry);
        }
        Referrer::Script(script) => {
            let mut loaded_modules = script.loaded_modules().borrow_mut();
            let entry = loaded_modules
                .entry(request.specifier().clone())
                .or_insert_with(|| module.clone());
            debug_assert_eq!(&module, entry);
        }
    }

    // When the `experimental` feature is disabled, reject any non-evaluation phase.
    #[cfg(not(feature = "experimental"))]
    if phase != 0 {
        let err = JsNativeError::syntax()
            .with_message("import.defer() and import.source() require the 'experimental' feature")
            .into();
        let err = JsError::into_opaque(err, &mut context.borrow_mut())?;
        cap.reject()
            .call(&JsValue::undefined(), &[err], &mut context.borrow_mut())
            .expect("default `reject` function cannot throw");
        return Ok(());
    }

    // TODO: For source phase (phase == 2), implement GetModuleSource()
    // 16.2.1.7.2 GetModuleSource ( )
    // Source Text Module Record provides a GetModuleSource implementation
    // that always returns an abrupt completion indicating that a source phase import is not available.
    // 1. Throw a SyntaxError exception.
    #[cfg(feature = "experimental")]
    if phase == 2 {
        let err = JsNativeError::syntax()
            .with_message("source phase import is not available for this module")
            .into();
        let err = JsError::into_opaque(err, &mut context.borrow_mut())?;
        cap.reject()
            .call(&JsValue::undefined(), &[err], &mut context.borrow_mut())
            .expect("default `reject` function cannot throw");
        return Ok(());
    }

    // 2. Let module be moduleCompletion.[[Value]].
    // 3. Let loadPromise be module.LoadRequestedModules().
    let load = module.load(&mut context.borrow_mut());

    // 4. Let rejectedClosure be a new Abstract Closure with parameters (reason) that captures promiseCapability and performs the following steps when called:
    // 5. Let onRejected be CreateBuiltinFunction(rejectedClosure, 1, "", « »).
    let on_rejected = FunctionObjectBuilder::new(
        context.borrow().realm(),
        NativeFunction::from_copy_closure_with_captures(
            |_, args, cap, context| {
                //     a. Perform ! Call(promiseCapability.[[Reject]], undefined, « reason »).
                cap.reject()
                    .call(&JsValue::undefined(), args, context)
                    .expect("default `reject` function cannot throw");

                //     b. Return unused.
                Ok(JsValue::undefined())
            },
            cap.clone(),
        ),
    )
    .build();

    // 6. Let linkAndEvaluateClosure be a new Abstract Closure with no parameters that captures module, promiseCapability, and onRejected and performs the following steps when called:
    // 7. Let linkAndEvaluate be CreateBuiltinFunction(linkAndEvaluateClosure, 0, "", « »).
    let link_evaluate = FunctionObjectBuilder::new(
        context.borrow().realm(),
        NativeFunction::from_copy_closure_with_captures(
            |_, _, (module, cap, on_rejected), context| {
                // a. Let link be Completion(module.Link()).
                // b. If link is an abrupt completion, then
                if let Err(e) = module.link(context) {
                    // i. Perform ! Call(promiseCapability.[[Reject]], undefined, « link.[[Value]] »).
                    let e = e.into_opaque(context)?;
                    cap.reject()
                        .call(&JsValue::undefined(), &[e], context)
                        .expect("default `reject` function cannot throw");
                    // ii. Return unused.
                    return Ok(JsValue::undefined());
                }

                // c. Let evaluatePromise be module.Evaluate().
                let evaluate = module.evaluate(context)?;

                // d. Let fulfilledClosure be a new Abstract Closure with no parameters that captures module and promiseCapability and performs the following steps when called:
                // e. Let onFulfilled be CreateBuiltinFunction(fulfilledClosure, 0, "", « »).
                let fulfill = FunctionObjectBuilder::new(
                    context.realm(),
                    NativeFunction::from_copy_closure_with_captures(
                        |_, _, (module, cap), context| {
                            // i. Let namespace be GetModuleNamespace(module).
                            let namespace = module.namespace(context);

                            // ii. Perform ! Call(promiseCapability.[[Resolve]], undefined, « namespace »).
                            cap.resolve()
                                .call(&JsValue::undefined(), &[namespace.into()], context)
                                .expect("default `resolve` function cannot throw");

                            // iii. Return unused.
                            Ok(JsValue::undefined())
                        },
                        (module.clone(), cap.clone()),
                    ),
                )
                .build();

                // f. Perform PerformPromiseThen(evaluatePromise, onFulfilled, onRejected).
                Promise::perform_promise_then(
                    &evaluate,
                    Some(fulfill),
                    Some(on_rejected.clone()),
                    None,
                    context,
                );

                // g. Return unused.
                Ok(JsValue::undefined())
            },
            (module.clone(), cap.clone(), on_rejected.clone()),
        ),
    )
    .build();

    // 8. Perform PerformPromiseThen(loadPromise, linkAndEvaluate, onRejected).
    Promise::perform_promise_then(
        &load,
        Some(link_evaluate),
        Some(on_rejected),
        None,
        &mut context.borrow_mut(),
    );

    // 9. Return unused.
    Ok(())
}

/// `ImportCall` implements the Opcode Operation for `Opcode::ImportCall`
///
/// Operation:
///  - Dynamically imports a module
#[derive(Debug, Clone, Copy)]
pub(crate) struct ImportCall;

impl ImportCall {
    #[inline(always)]
    pub(super) fn operation(
        (specifier_op, options_op, phase_op): (RegisterOperand, RegisterOperand, IndexOperand),
        context: &mut Context,
    ) -> JsResult<()> {
        // Import Calls
        // Runtime Semantics: Evaluation
        // https://tc39.es/ecma262/#sec-import-call-runtime-semantics-evaluation

        let phase: u32 = phase_op.into();

        // 1. Let referrer be GetActiveScriptOrModule().
        // 2. If referrer is null, set referrer to the current Realm Record.
        let referrer = context
            .get_active_script_or_module()
            .map_or_else(|| Referrer::Realm(context.realm().clone()), Into::into);

        // 3. Let argRef be ? Evaluation of AssignmentExpression.
        // 4. Let specifier be ? GetValue(argRef).
        let specifier = context.vm.get_register(specifier_op.into()).clone();

        // Get options if provided
        let options = context.vm.get_register(options_op.into()).clone();

        // 5. Let promiseCapability be ! NewPromiseCapability(%Promise%).
        let cap = PromiseCapability::new(
            &context.intrinsics().constructors().promise().constructor(),
            context,
        )
        .expect("operation cannot fail for the %Promise% intrinsic");
        let promise = cap.promise().clone();

        // 6. Let specifierString be Completion(ToString(specifier)).
        let specifier_str = match specifier.to_string(context) {
            Ok(s) => s,
            // 7. IfAbruptRejectPromise(specifierString, promiseCapability).
            Err(err) => {
                let err = err.into_opaque(context)?;
                cap.reject().call(&JsValue::undefined(), &[err], context)?;
                context.vm.set_register(specifier_op.into(), promise.into());
                return Ok(());
            }
        };

        let request = match parse_import_attributes(specifier_str, &options, context) {
            Ok(req) => req,
            Err(err) => {
                let err = err.into_opaque(context)?;
                cap.reject().call(&JsValue::undefined(), &[err], context)?;
                context.vm.set_register(specifier_op.into(), promise.into());
                return Ok(());
            }
        };

        // 8. Perform HostLoadImportedModule(referrer, specifierString, empty, promiseCapability).
        let job = NativeAsyncJob::with_realm(
            async move |context| {
                load_dyn_import(referrer, request, cap, phase, context).await?;
                Ok(JsValue::undefined())
            },
            context.realm().clone(),
        );
        context.enqueue_job(job.into());

        // 9. Return promiseCapability.[[Promise]].
        context.vm.set_register(specifier_op.into(), promise.into());

        Ok(())
    }
}

impl Operation for ImportCall {
    const NAME: &'static str = "ImportCall";
    const INSTRUCTION: &'static str = "INST - ImportCall";
    const COST: u8 = 15;
}

/// Operands of [`Opcode::PrepareMath`].
#[derive(Debug, Clone, Copy)]
pub(crate) struct PrepareMathOperands {
    pub(crate) callee: RegisterOperand,
    pub(crate) this: RegisterOperand,
    pub(crate) function: u8,
    pub(crate) binding_index: IndexOperand,
}

impl std::fmt::Display for PrepareMathOperands {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "callee:{}, this:{}, function:{}, binding_index:{}",
            self.callee, self.this, self.function, self.binding_index
        )
    }
}

impl Argument for PrepareMathOperands {
    fn encode(self, bytes: &mut Vec<u8>) {
        self.callee.encode(bytes);
        self.this.encode(bytes);
        self.function.encode(bytes);
        self.binding_index.encode(bytes);
    }

    fn decode(bytes: &[u8], pos: usize) -> (Self, usize) {
        let (callee, pos) = RegisterOperand::decode(bytes, pos);
        let (this, pos) = RegisterOperand::decode(bytes, pos);
        let (function, pos) = u8::decode(bytes, pos);
        let (binding_index, pos) = IndexOperand::decode(bytes, pos);
        (
            Self {
                callee,
                this,
                function,
                binding_index,
            },
            pos,
        )
    }
}

/// Operands of [`Opcode::CallMath`].
///
/// `args` holds three registers. Only the first `argc` entries are live.
#[derive(Debug, Clone, Copy)]
pub(crate) struct CallMathOperands {
    pub(crate) dst: RegisterOperand,
    pub(crate) callee: RegisterOperand,
    pub(crate) this: RegisterOperand,
    pub(crate) function: u8,
    pub(crate) argc: u8,
    pub(crate) args: [RegisterOperand; 3],
}

impl std::fmt::Display for CallMathOperands {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "dst:{}, callee:{}, this:{}, function:{}, argc:{}",
            self.dst, self.callee, self.this, self.function, self.argc
        )?;
        for arg in self.args.iter().take(usize::from(self.argc)) {
            write!(f, ", arg:{arg}")?;
        }
        Ok(())
    }
}

impl Argument for CallMathOperands {
    fn encode(self, bytes: &mut Vec<u8>) {
        self.dst.encode(bytes);
        self.callee.encode(bytes);
        self.this.encode(bytes);
        self.function.encode(bytes);
        self.argc.encode(bytes);
        self.args[0].encode(bytes);
        self.args[1].encode(bytes);
        self.args[2].encode(bytes);
    }

    fn decode(bytes: &[u8], pos: usize) -> (Self, usize) {
        let (dst, pos) = RegisterOperand::decode(bytes, pos);
        let (callee, pos) = RegisterOperand::decode(bytes, pos);
        let (this, pos) = RegisterOperand::decode(bytes, pos);
        let (function, pos) = u8::decode(bytes, pos);
        let (count, pos) = u8::decode(bytes, pos);
        let (arg0, pos) = RegisterOperand::decode(bytes, pos);
        let (arg1, pos) = RegisterOperand::decode(bytes, pos);
        let (arg2, pos) = RegisterOperand::decode(bytes, pos);
        (
            Self {
                dst,
                callee,
                this,
                function,
                argc: count,
                args: [arg0, arg1, arg2],
            },
            pos,
        )
    }
}

/// `PrepareMath` implements the Opcode Operation for `Opcode::PrepareMath`.
///
/// Operation:
///  - Runs where the generic call reads `Math.<name>`, before the arguments. When the
///    realm's `Math` is pristine, stores `undefined` in `this`: the callee is the
///    intrinsic and `CallMath` calls it directly. Otherwise gets the `Math` binding
///    into `this` and its property into `callee`.
#[derive(Debug, Clone, Copy)]
pub(crate) struct PrepareMath;

impl Operation for PrepareMath {
    const NAME: &'static str = "PrepareMath";
    const INSTRUCTION: &'static str = "INST - PrepareMath";
    const COST: u8 = 2;
}

impl PrepareMath {
    #[inline(always)]
    pub(super) fn operation(operands: PrepareMathOperands, context: &mut Context) -> JsResult<()> {
        if context.realm().math_pristine() && context.global_binding_is_static() {
            context
                .vm
                .set_register(operands.this.into(), JsValue::undefined());
            return Ok(());
        }
        prepare_math_slow(operands, context)
    }
}

#[cold]
#[inline(never)]
fn prepare_math_slow(operands: PrepareMathOperands, context: &mut Context) -> JsResult<()> {
    let base = load_math_binding(operands.binding_index, context)?;
    let object = base.base_class(context)?;
    let key = PropertyKey::from(Math::pure_name(operands.function));
    let callee = object.__get__(
        &key,
        base.clone(),
        &mut InternalMethodPropertyContext::new(context),
    )?;
    // `base_class` threw for null and undefined, so `this` is never `undefined` here.
    context.vm.set_register(operands.this.into(), base);
    context.vm.set_register(operands.callee.into(), callee);
    Ok(())
}

/// `CallMath` implements the Opcode Operation for `Opcode::CallMath`.
///
/// Operation:
///  - Calls the intrinsic pure `Math` function when `PrepareMath` found `Math`
///    pristine, otherwise calls `callee` with `this`.
#[derive(Debug, Clone, Copy)]
pub(crate) struct CallMath;

impl Operation for CallMath {
    const NAME: &'static str = "CallMath";
    const INSTRUCTION: &'static str = "INST - CallMath";
    const COST: u8 = 15;
}

impl CallMath {
    #[inline(always)]
    pub(super) fn operation(operands: CallMathOperands, context: &mut Context) -> JsResult<()> {
        let live = usize::from(operands.argc);
        assert!(live <= 3, "CallMath argument count");

        // Pristine `Math` and Number arguments: compute without building a call.
        if context.vm.get_register(operands.this.into()).is_undefined() {
            let mut numbers = [0f64; 3];
            let all_numbers =
                numbers
                    .iter_mut()
                    .zip(operands.args)
                    .take(live)
                    .all(|(slot, reg)| {
                        context
                            .vm
                            .get_register(reg.into())
                            .as_number()
                            .map(|number| *slot = number)
                            .is_some()
                    });
            if all_numbers
                && let Some(value) = Math::call_pure_numbers(operands.function, &numbers[..live])
            {
                context
                    .vm
                    .set_register(operands.dst.into(), JsValue::from(value));
                return Ok(());
            }
        }

        let mut stored = [
            JsValue::undefined(),
            JsValue::undefined(),
            JsValue::undefined(),
        ];
        for (slot, reg) in stored.iter_mut().zip(operands.args).take(live) {
            *slot = context.vm.get_register(reg.into()).clone();
        }
        let args = &stored[..live];

        // The callee is the intrinsic, which ignores `this` and converts its own
        // arguments, so calling it here is the call the generic sequence makes.
        let value = if context.vm.get_register(operands.this.into()).is_undefined() {
            Math::call_pure(operands.function, args, context)?
        } else {
            call_math_slow(operands, args, context)?
        };
        context.vm.set_register(operands.dst.into(), value);
        Ok(())
    }
}

#[cold]
#[inline(never)]
fn call_math_slow(
    operands: CallMathOperands,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let this = context.vm.get_register(operands.this.into()).clone();
    let callee = context.vm.get_register(operands.callee.into()).clone();
    let Some(function) = callee.as_callable() else {
        return Err(JsNativeError::typ()
            .with_message("not a callable function")
            .into());
    };
    function.call(&this, args, context)
}

fn load_math_binding(index: IndexOperand, context: &mut Context) -> JsResult<JsValue> {
    let slot = usize::from(index);
    let is_global = context.vm.frame().code_block.bindings[slot].is_global();
    if is_global && context.global_binding_is_static() {
        return get_global_math(context);
    }

    let mut locator = context.vm.frame().code_block.bindings[slot].clone();
    context.find_runtime_binding(&mut locator)?;
    if locator.is_global() {
        return get_global_math(context);
    }

    context.get_binding(&locator)?.ok_or_else(|| {
        let name = locator.name().to_std_string_escaped();
        JsNativeError::reference()
            .with_message(format!("{name} is not defined"))
            .into()
    })
}

fn get_global_math(context: &mut Context) -> JsResult<JsValue> {
    let object = context.global_object();
    let key = PropertyKey::from(StaticJsStrings::MATH);
    let property_context = &mut InternalMethodPropertyContext::new(context);
    match object.__try_get__(&key, object.clone().into(), property_context)? {
        Some(result) => Ok(result),
        None => Err(JsNativeError::reference()
            .with_message(format!("{key} is not defined"))
            .into()),
    }
}