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
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
//! Boa's implementation of ECMAScript's global `Function` object and Native Functions.
//!
//! Objects wrap `Function`s and expose them via call/construct slots.
//!
//! The `Function` object is used for matching text with a pattern.
//!
//! More information:
//!  - [ECMAScript reference][spec]
//!  - [MDN documentation][mdn]
//!
//! [spec]: https://tc39.es/ecma262/#sec-function-objects
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function

use crate::{
    builtins::{BuiltInBuilder, BuiltInConstructor, BuiltInObject, IntrinsicObject},
    bytecompiler::FunctionCompiler,
    context::intrinsics::{Intrinsics, StandardConstructor, StandardConstructors},
    environments::{EnvironmentStack, PrivateEnvironment},
    error::JsNativeError,
    js_string,
    native_function::NativeFunction,
    object::{internal_methods::get_prototype_from_constructor, JsObject, Object, ObjectData},
    object::{JsFunction, PrivateElement, PrivateName},
    property::{Attribute, PropertyDescriptor, PropertyKey},
    realm::Realm,
    string::utf16,
    symbol::JsSymbol,
    value::IntegerOrInfinity,
    vm::{ActiveRunnable, CodeBlock},
    Context, JsArgs, JsResult, JsString, JsValue,
};
use boa_ast::{
    function::{FormalParameterList, FunctionBody},
    operations::{
        all_private_identifiers_valid, bound_names, contains, lexically_declared_names,
        ContainsSymbol,
    },
};
use boa_gc::{self, custom_trace, Finalize, Gc, Trace};
use boa_interner::Sym;
use boa_parser::{Parser, Source};
use boa_profiler::Profiler;
use std::{fmt, io::Read};
use thin_vec::ThinVec;

pub(crate) mod arguments;

#[cfg(test)]
mod tests;

/// Represents the `[[ThisMode]]` internal slot of function objects.
///
/// More information:
///  - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-ecmascript-function-objects
#[derive(Debug, Trace, Finalize, PartialEq, Eq, Clone)]
pub enum ThisMode {
    /// The `this` value refers to the `this` value of a lexically enclosing function.
    Lexical,

    /// The `this` value is used exactly as provided by an invocation of the function.
    Strict,

    /// The `this` value of `undefined` or `null` is interpreted as a reference to the global object,
    /// and any other `this` value is first passed to `ToObject`.
    Global,
}

impl ThisMode {
    /// Returns `true` if the this mode is `Lexical`.
    #[must_use]
    pub const fn is_lexical(&self) -> bool {
        matches!(self, Self::Lexical)
    }

    /// Returns `true` if the this mode is `Strict`.
    #[must_use]
    pub const fn is_strict(&self) -> bool {
        matches!(self, Self::Strict)
    }

    /// Returns `true` if the this mode is `Global`.
    #[must_use]
    pub const fn is_global(&self) -> bool {
        matches!(self, Self::Global)
    }
}

/// Represents the `[[ConstructorKind]]` internal slot of function objects.
///
/// More information:
///  - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-ecmascript-function-objects
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConstructorKind {
    /// The class constructor is not derived.
    Base,

    /// The class constructor is a derived class constructor.
    Derived,
}

impl ConstructorKind {
    /// Returns `true` if the constructor kind is `Base`.
    #[must_use]
    pub const fn is_base(&self) -> bool {
        matches!(self, Self::Base)
    }

    /// Returns `true` if the constructor kind is `Derived`.
    #[must_use]
    pub const fn is_derived(&self) -> bool {
        matches!(self, Self::Derived)
    }
}

/// Record containing the field definition of classes.
///
/// More information:
///  - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-classfielddefinition-record-specification-type
#[derive(Clone, Debug, Finalize)]
pub enum ClassFieldDefinition {
    /// A class field definition with a `string` or `symbol` as a name.
    Public(PropertyKey, JsFunction),

    /// A class field definition with a private name.
    Private(PrivateName, JsFunction),
}

unsafe impl Trace for ClassFieldDefinition {
    custom_trace! {this, {
        match this {
            Self::Public(_key, func) => {
                mark(func);
            }
            Self::Private(_, func) => {
                mark(func);
            }
        }
    }}
}

#[derive(Finalize)]
pub(crate) enum FunctionKind {
    /// A rust function.
    Native {
        /// The rust function.
        function: NativeFunction,

        /// The kind of the function constructor if it is a constructor.
        constructor: Option<ConstructorKind>,
    },
    /// A bytecode function.
    Ordinary {
        /// The code block containing the compiled function.
        code: Gc<CodeBlock>,

        /// The `[[Environment]]` internal slot.
        environments: EnvironmentStack,

        /// The `[[ConstructorKind]]` internal slot.
        constructor_kind: ConstructorKind,

        /// The `[[HomeObject]]` internal slot.
        home_object: Option<JsObject>,

        /// The `[[Fields]]` internal slot.
        fields: ThinVec<ClassFieldDefinition>,

        /// The `[[PrivateMethods]]` internal slot.
        private_methods: ThinVec<(PrivateName, PrivateElement)>,

        /// The class object that this function is associated with.
        class_object: Option<JsObject>,

        /// The `[[ScriptOrModule]]` internal slot.
        script_or_module: Option<ActiveRunnable>,
    },

    /// A bytecode async function.
    Async {
        /// The code block containing the compiled function.
        code: Gc<CodeBlock>,

        /// The `[[Environment]]` internal slot.
        environments: EnvironmentStack,

        /// The `[[HomeObject]]` internal slot.
        home_object: Option<JsObject>,

        /// The class object that this function is associated with.
        class_object: Option<JsObject>,

        /// The `[[ScriptOrModule]]` internal slot.
        script_or_module: Option<ActiveRunnable>,
    },

    /// A bytecode generator function.
    Generator {
        /// The code block containing the compiled function.
        code: Gc<CodeBlock>,

        /// The `[[Environment]]` internal slot.
        environments: EnvironmentStack,

        /// The `[[HomeObject]]` internal slot.
        home_object: Option<JsObject>,

        /// The class object that this function is associated with.
        class_object: Option<JsObject>,

        /// The `[[ScriptOrModule]]` internal slot.
        script_or_module: Option<ActiveRunnable>,
    },

    /// A bytecode async generator function.
    AsyncGenerator {
        /// The code block containing the compiled function.
        code: Gc<CodeBlock>,

        /// The `[[Environment]]` internal slot.
        environments: EnvironmentStack,

        /// The `[[HomeObject]]` internal slot.
        home_object: Option<JsObject>,

        /// The class object that this function is associated with.
        class_object: Option<JsObject>,

        /// The `[[ScriptOrModule]]` internal slot.
        script_or_module: Option<ActiveRunnable>,
    },
}

impl fmt::Debug for FunctionKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Native {
                function,
                constructor,
            } => f
                .debug_struct("FunctionKind::Native")
                .field("function", &function)
                .field("constructor", &constructor)
                .finish(),
            Self::Ordinary { .. } => f
                .debug_struct("FunctionKind::Ordinary")
                .finish_non_exhaustive(),
            Self::Async { .. } => f
                .debug_struct("FunctionKind::Async")
                .finish_non_exhaustive(),
            Self::Generator { .. } => f
                .debug_struct("FunctionKind::Generator")
                .finish_non_exhaustive(),
            Self::AsyncGenerator { .. } => f
                .debug_struct("FunctionKind::AsyncGenerator")
                .finish_non_exhaustive(),
        }
    }
}

unsafe impl Trace for FunctionKind {
    custom_trace! {this, {
        match this {
            Self::Native { function, .. } => {mark(function)}
            Self::Ordinary {
                code,
                environments,
                home_object,
                fields,
                private_methods,
                class_object,
                script_or_module,
                ..
            } => {
                mark(code);
                mark(environments);
                mark(home_object);
                for elem in fields {
                    mark(elem);
                }
                for (_, elem) in private_methods {
                    mark(elem);
                }
                mark(class_object);
                mark(script_or_module);
            }
            Self::Async { code, environments, home_object, class_object, script_or_module }
            | Self::Generator { code, environments, home_object, class_object, script_or_module}
            | Self::AsyncGenerator { code, environments, home_object, class_object, script_or_module} => {
                mark(code);
                mark(environments);
                mark(home_object);
                mark(class_object);
                mark(script_or_module);
            }
        }
    }}
}

/// Boa representation of a Function Object.
///
/// `FunctionBody` is specific to this interpreter, it will either be Rust code or JavaScript code
/// (AST Node).
///
/// <https://tc39.es/ecma262/#sec-ecmascript-function-objects>
#[derive(Debug, Trace, Finalize)]
pub struct Function {
    kind: FunctionKind,
    realm: Realm,
}

impl Function {
    /// Returns the codeblock of the function, or `None` if the function is a [`NativeFunction`].
    pub fn codeblock(&self) -> Option<&CodeBlock> {
        match &self.kind {
            FunctionKind::Native { .. } => None,
            FunctionKind::Ordinary { code, .. }
            | FunctionKind::Async { code, .. }
            | FunctionKind::Generator { code, .. }
            | FunctionKind::AsyncGenerator { code, .. } => Some(code),
        }
    }

    /// Creates a new `Function`.
    pub(crate) fn new(kind: FunctionKind, realm: Realm) -> Self {
        Self { kind, realm }
    }

    /// Push a private environment to the function.
    pub(crate) fn push_private_environment(&mut self, environment: Gc<PrivateEnvironment>) {
        if let FunctionKind::Ordinary { environments, .. } = &mut self.kind {
            environments.push_private(environment);
        }
    }

    /// Returns true if the function object is a derived constructor.
    pub(crate) const fn is_derived_constructor(&self) -> bool {
        if let FunctionKind::Ordinary {
            constructor_kind, ..
        } = self.kind
        {
            constructor_kind.is_derived()
        } else {
            false
        }
    }

    /// Does this function have the `[[ClassFieldInitializerName]]` internal slot set to non-empty value.
    pub(crate) fn in_class_field_initializer(&self) -> bool {
        if let FunctionKind::Ordinary { code, .. } = &self.kind {
            code.in_class_field_initializer()
        } else {
            false
        }
    }

    /// Returns a reference to the function `[[HomeObject]]` slot if present.
    pub(crate) const fn get_home_object(&self) -> Option<&JsObject> {
        match &self.kind {
            FunctionKind::Ordinary { home_object, .. }
            | FunctionKind::Async { home_object, .. }
            | FunctionKind::Generator { home_object, .. }
            | FunctionKind::AsyncGenerator { home_object, .. } => home_object.as_ref(),
            FunctionKind::Native { .. } => None,
        }
    }

    ///  Sets the `[[HomeObject]]` slot if present.
    pub(crate) fn set_home_object(&mut self, object: JsObject) {
        match &mut self.kind {
            FunctionKind::Ordinary { home_object, .. }
            | FunctionKind::Async { home_object, .. }
            | FunctionKind::Generator { home_object, .. }
            | FunctionKind::AsyncGenerator { home_object, .. } => *home_object = Some(object),
            FunctionKind::Native { .. } => {}
        }
    }

    /// Returns the values of the `[[Fields]]` internal slot.
    pub(crate) fn get_fields(&self) -> &[ClassFieldDefinition] {
        if let FunctionKind::Ordinary { fields, .. } = &self.kind {
            fields
        } else {
            &[]
        }
    }

    /// Pushes a value to the `[[Fields]]` internal slot if present.
    pub(crate) fn push_field(&mut self, key: PropertyKey, value: JsFunction) {
        if let FunctionKind::Ordinary { fields, .. } = &mut self.kind {
            fields.push(ClassFieldDefinition::Public(key, value));
        }
    }

    /// Pushes a private value to the `[[Fields]]` internal slot if present.
    pub(crate) fn push_field_private(&mut self, name: PrivateName, value: JsFunction) {
        if let FunctionKind::Ordinary { fields, .. } = &mut self.kind {
            fields.push(ClassFieldDefinition::Private(name, value));
        }
    }

    /// Returns the values of the `[[PrivateMethods]]` internal slot.
    pub(crate) fn get_private_methods(&self) -> &[(PrivateName, PrivateElement)] {
        if let FunctionKind::Ordinary {
            private_methods, ..
        } = &self.kind
        {
            private_methods
        } else {
            &[]
        }
    }

    /// Pushes a private method to the `[[PrivateMethods]]` internal slot if present.
    pub(crate) fn push_private_method(&mut self, name: PrivateName, method: PrivateElement) {
        if let FunctionKind::Ordinary {
            private_methods, ..
        } = &mut self.kind
        {
            private_methods.push((name, method));
        }
    }

    ///  Sets the class object.
    pub(crate) fn set_class_object(&mut self, object: JsObject) {
        match &mut self.kind {
            FunctionKind::Ordinary { class_object, .. }
            | FunctionKind::Async { class_object, .. }
            | FunctionKind::Generator { class_object, .. }
            | FunctionKind::AsyncGenerator { class_object, .. } => *class_object = Some(object),
            FunctionKind::Native { .. } => {}
        }
    }

    /// Gets the `Realm` from where this function originates.
    pub const fn realm(&self) -> &Realm {
        &self.realm
    }

    /// Gets a reference to the [`FunctionKind`] of the `Function`.
    pub(crate) const fn kind(&self) -> &FunctionKind {
        &self.kind
    }

    /// Gets a mutable reference to the [`FunctionKind`] of the `Function`.
    pub(crate) fn kind_mut(&mut self) -> &mut FunctionKind {
        &mut self.kind
    }
}

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

impl IntrinsicObject for BuiltInFunctionObject {
    fn init(realm: &Realm) {
        let _timer = Profiler::global().start_event("function", "init");

        let has_instance = BuiltInBuilder::callable(realm, Self::has_instance)
            .name("[Symbol.hasInstance]")
            .length(1)
            .build();

        let throw_type_error = realm.intrinsics().objects().throw_type_error();

        BuiltInBuilder::from_standard_constructor::<Self>(realm)
            .method(Self::apply, "apply", 2)
            .method(Self::bind, "bind", 1)
            .method(Self::call, "call", 1)
            .method(Self::to_string, "toString", 0)
            .property(JsSymbol::has_instance(), has_instance, Attribute::default())
            .accessor(
                utf16!("caller"),
                Some(throw_type_error.clone()),
                Some(throw_type_error.clone()),
                Attribute::CONFIGURABLE,
            )
            .accessor(
                utf16!("arguments"),
                Some(throw_type_error.clone()),
                Some(throw_type_error),
                Attribute::CONFIGURABLE,
            )
            .build();

        let prototype = realm.intrinsics().constructors().function().prototype();

        BuiltInBuilder::callable_with_object(realm, prototype.clone(), Self::prototype)
            .name("")
            .length(0)
            .build();

        prototype.set_prototype(Some(realm.intrinsics().constructors().object().prototype()));
    }

    fn get(intrinsics: &Intrinsics) -> JsObject {
        Self::STANDARD_CONSTRUCTOR(intrinsics.constructors()).constructor()
    }
}

impl BuiltInObject for BuiltInFunctionObject {
    const NAME: &'static str = "Function";
}

impl BuiltInConstructor for BuiltInFunctionObject {
    const LENGTH: usize = 1;

    const STANDARD_CONSTRUCTOR: fn(&StandardConstructors) -> &StandardConstructor =
        StandardConstructors::function;

    /// `Function ( p1, p2, … , pn, body )`
    ///
    /// The apply() method invokes self with the first argument as the `this` value
    /// and the rest of the arguments provided as an array (or an array-like object).
    ///
    /// More information:
    ///  - [MDN documentation][mdn]
    ///  - [ECMAScript reference][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-function-p1-p2-pn-body
    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function
    fn constructor(
        new_target: &JsValue,
        args: &[JsValue],
        context: &mut Context<'_>,
    ) -> JsResult<JsValue> {
        let active_function = context
            .vm
            .active_function
            .clone()
            .unwrap_or_else(|| context.intrinsics().constructors().function().constructor());
        Self::create_dynamic_function(active_function, new_target, args, false, false, context)
            .map(Into::into)
    }
}

impl BuiltInFunctionObject {
    /// `CreateDynamicFunction ( constructor, newTarget, kind, args )`
    ///
    /// More information:
    ///  - [ECMAScript reference][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-createdynamicfunction
    pub(crate) fn create_dynamic_function(
        constructor: JsObject,
        new_target: &JsValue,
        args: &[JsValue],
        r#async: bool,
        generator: bool,
        context: &mut Context<'_>,
    ) -> JsResult<JsObject> {
        // 1. Let currentRealm be the current Realm Record.
        // 2. Perform ? HostEnsureCanCompileStrings(currentRealm).
        context
            .host_hooks()
            .ensure_can_compile_strings(context.realm().clone(), context)?;

        // 3. If newTarget is undefined, set newTarget to constructor.
        let new_target = if new_target.is_undefined() {
            constructor.into()
        } else {
            new_target.clone()
        };

        let default = if r#async && generator {
            // 7. Else,
            //     a. Assert: kind is asyncGenerator.
            //     b. Let prefix be "async function*".
            //     c. Let exprSym be the grammar symbol AsyncGeneratorExpression.
            //     d. Let bodySym be the grammar symbol AsyncGeneratorBody.
            //     e. Let parameterSym be the grammar symbol FormalParameters[+Yield, +Await].
            //     f. Let fallbackProto be "%AsyncGeneratorFunction.prototype%".
            StandardConstructors::async_generator_function
        } else if r#async {
            // 6. Else if kind is async, then
            //     a. Let prefix be "async function".
            //     b. Let exprSym be the grammar symbol AsyncFunctionExpression.
            //     c. Let bodySym be the grammar symbol AsyncFunctionBody.
            //     d. Let parameterSym be the grammar symbol FormalParameters[~Yield, +Await].
            //     e. Let fallbackProto be "%AsyncFunction.prototype%".
            StandardConstructors::async_function
        } else if generator {
            // 5. Else if kind is generator, then
            //     a. Let prefix be "function*".
            //     b. Let exprSym be the grammar symbol GeneratorExpression.
            //     c. Let bodySym be the grammar symbol GeneratorBody.
            //     d. Let parameterSym be the grammar symbol FormalParameters[+Yield, ~Await].
            //     e. Let fallbackProto be "%GeneratorFunction.prototype%".
            StandardConstructors::generator_function
        } else {
            // 4. If kind is normal, then
            //     a. Let prefix be "function".
            //     b. Let exprSym be the grammar symbol FunctionExpression.
            //     c. Let bodySym be the grammar symbol FunctionBody[~Yield, ~Await].
            //     d. Let parameterSym be the grammar symbol FormalParameters[~Yield, ~Await].
            //     e. Let fallbackProto be "%Function.prototype%".
            StandardConstructors::function
        };

        // 22. Let proto be ? GetPrototypeFromConstructor(newTarget, fallbackProto).
        let prototype = get_prototype_from_constructor(&new_target, default, context)?;

        if let Some((body_arg, args)) = args.split_last() {
            let parameters = if args.is_empty() {
                FormalParameterList::default()
            } else {
                let mut parameters = Vec::with_capacity(args.len());
                for arg in args {
                    parameters.push(arg.to_string(context)?);
                }
                let parameters = parameters.join(utf16!(","));

                // TODO: make parser generic to u32 iterators
                let parameters = String::from_utf16_lossy(&parameters);
                let mut parser = Parser::new(Source::from_bytes(&parameters));
                parser.set_identifier(context.next_parser_identifier());

                let parameters = match parser.parse_formal_parameters(
                    context.interner_mut(),
                    generator,
                    r#async,
                ) {
                    Ok(parameters) => parameters,
                    Err(e) => {
                        return Err(JsNativeError::syntax()
                            .with_message(format!("failed to parse function parameters: {e}"))
                            .into())
                    }
                };

                if generator && contains(&parameters, ContainsSymbol::YieldExpression) {
                    return Err(JsNativeError::syntax().with_message(
                            "yield expression is not allowed in formal parameter list of generator function",
                        ).into());
                }

                parameters
            };

            // It is a Syntax Error if FormalParameters Contains YieldExpression is true.
            if generator && r#async && contains(&parameters, ContainsSymbol::YieldExpression) {
                return Err(JsNativeError::syntax()
                    .with_message("yield expression not allowed in async generator parameters")
                    .into());
            }

            // It is a Syntax Error if FormalParameters Contains AwaitExpression is true.
            if generator && r#async && contains(&parameters, ContainsSymbol::AwaitExpression) {
                return Err(JsNativeError::syntax()
                    .with_message("await expression not allowed in async generator parameters")
                    .into());
            }

            // 11. Let bodyString be the string-concatenation of 0x000A (LINE FEED), ? ToString(bodyArg), and 0x000A (LINE FEED).
            let body_arg = body_arg.to_string(context)?.to_std_string_escaped();
            let body = b"\n".chain(body_arg.as_bytes()).chain(b"\n".as_slice());

            // TODO: make parser generic to u32 iterators
            let mut parser = Parser::new(Source::from_reader(body, None));
            parser.set_identifier(context.next_parser_identifier());

            let body = match parser.parse_function_body(context.interner_mut(), generator, r#async)
            {
                Ok(statement_list) => statement_list,
                Err(e) => {
                    return Err(JsNativeError::syntax()
                        .with_message(format!("failed to parse function body: {e}"))
                        .into())
                }
            };

            // Early Error: If BindingIdentifier is present and the source text matched by BindingIdentifier is strict mode code,
            // it is a Syntax Error if the StringValue of BindingIdentifier is "eval" or "arguments".
            if body.strict() {
                for name in bound_names(&parameters) {
                    if name == Sym::ARGUMENTS || name == Sym::EVAL {
                        return Err(JsNativeError::syntax()
                            .with_message(" Unexpected 'eval' or 'arguments' in strict mode")
                            .into());
                    }
                }
            }

            // Early Error: If the source code matching FormalParameters is strict mode code,
            // the Early Error rules for UniqueFormalParameters : FormalParameters are applied.
            if (body.strict()) && parameters.has_duplicates() {
                return Err(JsNativeError::syntax()
                    .with_message("Duplicate parameter name not allowed in this context")
                    .into());
            }

            // Early Error: It is a Syntax Error if FunctionBodyContainsUseStrict of GeneratorBody is true
            // and IsSimpleParameterList of FormalParameters is false.
            if body.strict() && !parameters.is_simple() {
                return Err(JsNativeError::syntax()
                    .with_message(
                        "Illegal 'use strict' directive in function with non-simple parameter list",
                    )
                    .into());
            }

            // It is a Syntax Error if FunctionBody Contains SuperProperty is true.
            if contains(&body, ContainsSymbol::SuperProperty) {
                return Err(JsNativeError::syntax()
                    .with_message("invalid `super` reference")
                    .into());
            }

            // It is a Syntax Error if FunctionBody Contains SuperCall is true.
            if contains(&body, ContainsSymbol::SuperCall) {
                return Err(JsNativeError::syntax()
                    .with_message("invalid `super` call")
                    .into());
            }

            // It is a Syntax Error if any element of the BoundNames of FormalParameters
            // also occurs in the LexicallyDeclaredNames of FunctionBody.
            // https://tc39.es/ecma262/#sec-function-definitions-static-semantics-early-errors
            {
                let lexically_declared_names = lexically_declared_names(&body);
                for name in bound_names(&parameters) {
                    if lexically_declared_names.contains(&name) {
                        return Err(JsNativeError::syntax()
                            .with_message(format!(
                                "Redeclaration of formal parameter `{}`",
                                context.interner().resolve_expect(name.sym())
                            ))
                            .into());
                    }
                }
            }

            if !all_private_identifiers_valid(&parameters, Vec::new()) {
                return Err(JsNativeError::syntax()
                    .with_message("invalid private identifier usage")
                    .into());
            }

            if !all_private_identifiers_valid(&body, Vec::new()) {
                return Err(JsNativeError::syntax()
                    .with_message("invalid private identifier usage")
                    .into());
            }

            let code = FunctionCompiler::new()
                .name(Sym::ANONYMOUS)
                .generator(generator)
                .r#async(r#async)
                .compile(
                    &parameters,
                    &body,
                    context.realm().environment().compile_env(),
                    context,
                );

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

            let function_object = if generator {
                crate::vm::create_generator_function_object(code, r#async, Some(prototype), context)
            } else {
                crate::vm::create_function_object(code, r#async, prototype, context)
            };

            context.vm.environments.extend(environments);

            Ok(function_object)
        } else if generator {
            let code = FunctionCompiler::new()
                .name(Sym::ANONYMOUS)
                .generator(true)
                .compile(
                    &FormalParameterList::default(),
                    &FunctionBody::default(),
                    context.realm().environment().compile_env(),
                    context,
                );

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

            Ok(function_object)
        } else {
            let code = FunctionCompiler::new().name(Sym::ANONYMOUS).compile(
                &FormalParameterList::default(),
                &FunctionBody::default(),
                context.realm().environment().compile_env(),
                context,
            );

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

            Ok(function_object)
        }
    }

    /// `Function.prototype.apply ( thisArg, argArray )`
    ///
    /// The apply() method invokes self with the first argument as the `this` value
    /// and the rest of the arguments provided as an array (or an array-like object).
    ///
    /// More information:
    ///  - [MDN documentation][mdn]
    ///  - [ECMAScript reference][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-function.prototype.apply
    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
    fn apply(this: &JsValue, args: &[JsValue], context: &mut Context<'_>) -> JsResult<JsValue> {
        // 1. Let func be the this value.
        // 2. If IsCallable(func) is false, throw a TypeError exception.
        let func = this.as_callable().ok_or_else(|| {
            JsNativeError::typ().with_message(format!("{} is not a function", this.display()))
        })?;

        let this_arg = args.get_or_undefined(0);
        let arg_array = args.get_or_undefined(1);
        // 3. If argArray is undefined or null, then
        if arg_array.is_null_or_undefined() {
            // a. Perform PrepareForTailCall().
            // TODO?: 3.a. PrepareForTailCall

            // b. Return ? Call(func, thisArg).
            return func.call(this_arg, &[], context);
        }

        // 4. Let argList be ? CreateListFromArrayLike(argArray).
        let arg_list = arg_array.create_list_from_array_like(&[], context)?;

        // 5. Perform PrepareForTailCall().
        // TODO?: 5. PrepareForTailCall

        // 6. Return ? Call(func, thisArg, argList).
        func.call(this_arg, &arg_list, context)
    }

    /// `Function.prototype.bind ( thisArg, ...args )`
    ///
    /// The bind() method creates a new function that, when called, has its
    /// this keyword set to the provided value, with a given sequence of arguments
    /// preceding any provided when the new function is called.
    ///
    /// More information:
    ///  - [MDN documentation][mdn]
    ///  - [ECMAScript reference][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-function.prototype.bind
    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind
    fn bind(this: &JsValue, args: &[JsValue], context: &mut Context<'_>) -> JsResult<JsValue> {
        // 1. Let Target be the this value.
        // 2. If IsCallable(Target) is false, throw a TypeError exception.
        let target = this.as_callable().ok_or_else(|| {
            JsNativeError::typ()
                .with_message("cannot bind `this` without a `[[Call]]` internal method")
        })?;

        let this_arg = args.get_or_undefined(0).clone();
        let bound_args = args.get(1..).unwrap_or(&[]).to_vec();
        let arg_count = bound_args.len() as i64;

        // 3. Let F be ? BoundFunctionCreate(Target, thisArg, args).
        let f = BoundFunction::create(target.clone(), this_arg, bound_args, context)?;

        // 4. Let L be 0.
        let mut l = JsValue::new(0);

        // 5. Let targetHasLength be ? HasOwnProperty(Target, "length").
        // 6. If targetHasLength is true, then
        if target.has_own_property(utf16!("length"), context)? {
            // a. Let targetLen be ? Get(Target, "length").
            let target_len = target.get(utf16!("length"), context)?;
            // b. If Type(targetLen) is Number, then
            if target_len.is_number() {
                // 1. Let targetLenAsInt be ! ToIntegerOrInfinity(targetLen).
                match target_len
                    .to_integer_or_infinity(context)
                    .expect("to_integer_or_infinity cannot fail for a number")
                {
                    // i. If targetLen is +∞𝔽, set L to +∞.
                    IntegerOrInfinity::PositiveInfinity => l = f64::INFINITY.into(),
                    // ii. Else if targetLen is -∞𝔽, set L to 0.
                    IntegerOrInfinity::NegativeInfinity => {}
                    // iii. Else,
                    IntegerOrInfinity::Integer(target_len) => {
                        // 2. Assert: targetLenAsInt is finite.
                        // 3. Let argCount be the number of elements in args.
                        // 4. Set L to max(targetLenAsInt - argCount, 0).
                        l = (target_len - arg_count).max(0).into();
                    }
                }
            }
        }

        // 7. Perform ! SetFunctionLength(F, L).
        f.define_property_or_throw(
            utf16!("length"),
            PropertyDescriptor::builder()
                .value(l)
                .writable(false)
                .enumerable(false)
                .configurable(true),
            context,
        )
        .expect("defining the `length` property for a new object should not fail");

        // 8. Let targetName be ? Get(Target, "name").
        let target_name = target.get(utf16!("name"), context)?;

        // 9. If Type(targetName) is not String, set targetName to the empty String.
        let target_name = target_name
            .as_string()
            .map_or_else(JsString::default, Clone::clone);

        // 10. Perform SetFunctionName(F, targetName, "bound").
        set_function_name(&f, &target_name.into(), Some(js_string!("bound")), context);

        // 11. Return F.
        Ok(f.into())
    }

    /// `Function.prototype.call ( thisArg, ...args )`
    ///
    /// The call() method calls a function with a given this value and arguments provided individually.
    ///
    /// More information:
    ///  - [MDN documentation][mdn]
    ///  - [ECMAScript reference][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-function.prototype.call
    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
    fn call(this: &JsValue, args: &[JsValue], context: &mut Context<'_>) -> JsResult<JsValue> {
        // 1. Let func be the this value.
        // 2. If IsCallable(func) is false, throw a TypeError exception.
        let func = this.as_callable().ok_or_else(|| {
            JsNativeError::typ().with_message(format!("{} is not a function", this.display()))
        })?;
        let this_arg = args.get_or_undefined(0);

        // 3. Perform PrepareForTailCall().
        // TODO?: 3. Perform PrepareForTailCall

        // 4. Return ? Call(func, thisArg, args).
        func.call(this_arg, args.get(1..).unwrap_or(&[]), context)
    }

    #[allow(clippy::wrong_self_convention)]
    fn to_string(this: &JsValue, _: &[JsValue], context: &mut Context<'_>) -> JsResult<JsValue> {
        let object = this.as_object().map(JsObject::borrow);
        let function = object
            .as_deref()
            .and_then(Object::as_function)
            .ok_or_else(|| JsNativeError::typ().with_message("Not a function"))?;

        let name = {
            // Is there a case here where if there is no name field on a value
            // name should default to None? Do all functions have names set?
            let value = this
                .as_object()
                .expect("checked that `this` was an object above")
                .get(utf16!("name"), &mut *context)?;
            if value.is_null_or_undefined() {
                None
            } else {
                Some(value.to_string(context)?)
            }
        };

        let name = name
            .filter(|n| !n.is_empty())
            .unwrap_or_else(|| "anonymous".into());

        match function.kind {
            FunctionKind::Native { .. } | FunctionKind::Ordinary { .. } => {
                Ok(js_string!(utf16!("[Function: "), &name, utf16!("]")).into())
            }
            FunctionKind::Async { .. } => {
                Ok(js_string!(utf16!("[AsyncFunction: "), &name, utf16!("]")).into())
            }
            FunctionKind::Generator { .. } => {
                Ok(js_string!(utf16!("[GeneratorFunction: "), &name, utf16!("]")).into())
            }
            FunctionKind::AsyncGenerator { .. } => {
                Ok(js_string!(utf16!("[AsyncGeneratorFunction: "), &name, utf16!("]")).into())
            }
        }
    }

    /// `Function.prototype [ @@hasInstance ] ( V )`
    ///
    /// More information:
    ///  - [ECMAScript reference][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-function.prototype-@@hasinstance
    fn has_instance(
        this: &JsValue,
        args: &[JsValue],
        context: &mut Context<'_>,
    ) -> JsResult<JsValue> {
        // 1. Let F be the this value.
        // 2. Return ? OrdinaryHasInstance(F, V).
        Ok(JsValue::ordinary_has_instance(this, args.get_or_undefined(0), context)?.into())
    }

    #[allow(clippy::unnecessary_wraps)]
    fn prototype(_: &JsValue, _: &[JsValue], _: &mut Context<'_>) -> JsResult<JsValue> {
        Ok(JsValue::undefined())
    }
}

/// Abstract operation `SetFunctionName`
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-setfunctionname
pub(crate) fn set_function_name(
    function: &JsObject,
    name: &PropertyKey,
    prefix: Option<JsString>,
    context: &mut Context<'_>,
) {
    // 1. Assert: F is an extensible object that does not have a "name" own property.
    // 2. If Type(name) is Symbol, then
    let mut name = match name {
        PropertyKey::Symbol(sym) => {
            // a. Let description be name's [[Description]] value.
            // b. If description is undefined, set name to the empty String.
            // c. Else, set name to the string-concatenation of "[", description, and "]".
            sym.description().map_or_else(
                || js_string!(),
                |desc| js_string!(utf16!("["), &desc, utf16!("]")),
            )
        }
        PropertyKey::String(string) => string.clone(),
        PropertyKey::Index(index) => js_string!(format!("{index}")),
    };

    // 3. Else if name is a Private Name, then
    // a. Set name to name.[[Description]].
    // todo: implement Private Names

    // 4. If F has an [[InitialName]] internal slot, then
    // a. Set F.[[InitialName]] to name.
    // todo: implement [[InitialName]] for builtins

    // 5. If prefix is present, then
    if let Some(prefix) = prefix {
        name = js_string!(&prefix, utf16!(" "), &name);
        // b. If F has an [[InitialName]] internal slot, then
        // i. Optionally, set F.[[InitialName]] to name.
        // todo: implement [[InitialName]] for builtins
    }

    // 6. Return ! DefinePropertyOrThrow(F, "name", PropertyDescriptor { [[Value]]: name,
    // [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }).
    function
        .define_property_or_throw(
            utf16!("name"),
            PropertyDescriptor::builder()
                .value(name)
                .writable(false)
                .enumerable(false)
                .configurable(true),
            context,
        )
        .expect("defining the `name` property must not fail per the spec");
}

/// Binds a `Function Object` when `bind` is called.
#[derive(Debug, Trace, Finalize)]
pub struct BoundFunction {
    target_function: JsObject,
    this: JsValue,
    args: Vec<JsValue>,
}

impl BoundFunction {
    /// Abstract operation `BoundFunctionCreate`
    ///
    /// More information:
    ///  - [ECMAScript reference][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-boundfunctioncreate
    pub fn create(
        target_function: JsObject,
        this: JsValue,
        args: Vec<JsValue>,
        context: &mut Context<'_>,
    ) -> JsResult<JsObject> {
        // 1. Let proto be ? targetFunction.[[GetPrototypeOf]]().
        let proto = target_function.__get_prototype_of__(context)?;
        let is_constructor = target_function.is_constructor();

        // 2. Let internalSlotsList be the internal slots listed in Table 35, plus [[Prototype]] and [[Extensible]].
        // 3. Let obj be ! MakeBasicObject(internalSlotsList).
        // 4. Set obj.[[Prototype]] to proto.
        // 5. Set obj.[[Call]] as described in 10.4.1.1.
        // 6. If IsConstructor(targetFunction) is true, then
        // a. Set obj.[[Construct]] as described in 10.4.1.2.
        // 7. Set obj.[[BoundTargetFunction]] to targetFunction.
        // 8. Set obj.[[BoundThis]] to boundThis.
        // 9. Set obj.[[BoundArguments]] to boundArgs.
        // 10. Return obj.
        Ok(JsObject::from_proto_and_data_with_shared_shape(
            context.root_shape(),
            proto,
            ObjectData::bound_function(
                Self {
                    target_function,
                    this,
                    args,
                },
                is_constructor,
            ),
        ))
    }

    /// Get a reference to the bound function's this.
    pub const fn this(&self) -> &JsValue {
        &self.this
    }

    /// Get a reference to the bound function's target function.
    pub const fn target_function(&self) -> &JsObject {
        &self.target_function
    }

    /// Get a reference to the bound function's args.
    pub fn args(&self) -> &[JsValue] {
        self.args.as_slice()
    }
}