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
//! A Rust API wrapper for Boa's promise Builtin ECMAScript Object

use std::{future::Future, pin::Pin, task};

use super::{JsArray, JsFunction};
use crate::{
    builtins::{
        promise::{PromiseState, ResolvingFunctions},
        Promise,
    },
    job::NativeJob,
    object::{JsObject, JsObjectType},
    value::TryFromJs,
    Context, JsArgs, JsError, JsNativeError, JsResult, JsValue, NativeFunction,
};
use boa_gc::{Finalize, Gc, GcRefCell, Trace};

/// An ECMAScript [promise] object.
///
/// Known as the concurrency primitive of ECMAScript, this is the main struct used to manipulate,
/// chain and inspect `Promises` from Rust code.
///
/// # Examples
///
/// ```
/// # use boa_engine::{
/// #     builtins::promise::PromiseState,
/// #     js_string,
/// #     object::{builtins::JsPromise, FunctionObjectBuilder},
/// #     property::Attribute,
/// #     Context, JsArgs, JsError, JsValue, NativeFunction,
/// # };
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let context = &mut Context::default();
///
/// context.register_global_property(
///     js_string!("finally"),
///     false,
///     Attribute::all(),
/// );
///
/// let promise = JsPromise::new(
///     |resolvers, context| {
///         let result = js_string!("hello world!").into();
///         resolvers.resolve.call(
///             &JsValue::undefined(),
///             &[result],
///             context,
///         )?;
///         Ok(JsValue::undefined())
///     },
///     context,
/// );
///
/// let promise = promise
///     .then(
///         Some(
///             NativeFunction::from_fn_ptr(|_, args, _| {
///                 Err(JsError::from_opaque(args.get_or_undefined(0).clone())
///                     .into())
///             })
///             .to_js_function(context.realm()),
///         ),
///         None,
///         context,
///     )
///     .catch(
///         NativeFunction::from_fn_ptr(|_, args, _| {
///             Ok(args.get_or_undefined(0).clone())
///         })
///         .to_js_function(context.realm()),
///         context,
///     )
///     .finally(
///         NativeFunction::from_fn_ptr(|_, _, context| {
///             context.global_object().clone().set(
///                 js_string!("finally"),
///                 JsValue::from(true),
///                 true,
///                 context,
///             )?;
///             Ok(JsValue::undefined())
///         })
///         .to_js_function(context.realm()),
///         context,
///     );
///
/// context.run_jobs();
///
/// assert_eq!(
///     promise.state(),
///     PromiseState::Fulfilled(js_string!("hello world!").into())
/// );
///
/// assert_eq!(
///     context
///         .global_object()
///         .clone()
///         .get(js_string!("finally"), context)?,
///     JsValue::from(true)
/// );
///
/// # Ok(())
/// # }
/// ```
///
/// [promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
#[derive(Debug, Clone, Trace, Finalize)]
pub struct JsPromise {
    inner: JsObject,
}

impl JsPromise {
    /// Creates a new promise object from an executor function.
    ///
    /// It is equivalent to calling the [`Promise()`] constructor, which makes it share the same
    /// execution semantics as the constructor:
    /// - The executor function `executor` is called synchronously just after the promise is created.
    /// - The executor return value is ignored.
    /// - Any error thrown within the execution of `executor` will call the `reject` function
    /// of the newly created promise, unless either `resolve` or `reject` were already called
    /// beforehand.
    ///
    /// `executor` receives as an argument the [`ResolvingFunctions`] needed to settle the promise,
    /// which can be done by either calling the `resolve` function or the `reject` function.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #    object::builtins::JsPromise,
    /// #    builtins::promise::PromiseState,
    /// #    Context, JsValue, js_string
    /// # };
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let context = &mut Context::default();
    ///
    /// let promise = JsPromise::new(
    ///     |resolvers, context| {
    ///         let result = js_string!("hello world").into();
    ///         resolvers.resolve.call(
    ///             &JsValue::undefined(),
    ///             &[result],
    ///             context,
    ///         )?;
    ///         Ok(JsValue::undefined())
    ///     },
    ///     context,
    /// );
    ///
    /// context.run_jobs();
    ///
    /// assert_eq!(
    ///     promise.state(),
    ///     PromiseState::Fulfilled(js_string!("hello world").into())
    /// );
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`Promise()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise
    pub fn new<F>(executor: F, context: &mut Context) -> Self
    where
        F: FnOnce(&ResolvingFunctions, &mut Context) -> JsResult<JsValue>,
    {
        let promise = JsObject::from_proto_and_data_with_shared_shape(
            context.root_shape(),
            context.intrinsics().constructors().promise().prototype(),
            Promise::new(),
        );
        let resolvers = Promise::create_resolving_functions(&promise, context);

        if let Err(e) = executor(&resolvers, context) {
            let e = e.to_opaque(context);
            resolvers
                .reject
                .call(&JsValue::undefined(), &[e], context)
                .expect("default `reject` function cannot throw");
        }

        Self { inner: promise }
    }

    /// Creates a new pending promise and returns it and its associated `ResolvingFunctions`.
    ///
    /// This can be useful when you want to manually settle a promise from Rust code, instead of
    /// running an `executor` function that automatically settles the promise on creation
    /// (see [`JsPromise::new`]).
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #    object::builtins::JsPromise,
    /// #    builtins::promise::PromiseState,
    /// #    Context, JsValue
    /// # };
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let context = &mut Context::default();
    ///
    /// let (promise, resolvers) = JsPromise::new_pending(context);
    ///
    /// assert_eq!(promise.state(), PromiseState::Pending);
    ///
    /// resolvers
    ///     .reject
    ///     .call(&JsValue::undefined(), &[5.into()], context)?;
    ///
    /// assert_eq!(promise.state(), PromiseState::Rejected(5.into()));
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn new_pending(context: &mut Context) -> (Self, ResolvingFunctions) {
        let promise = JsObject::from_proto_and_data_with_shared_shape(
            context.root_shape(),
            context.intrinsics().constructors().promise().prototype(),
            Promise::new(),
        );
        let resolvers = Promise::create_resolving_functions(&promise, context);
        let promise =
            Self::from_object(promise).expect("this shouldn't fail with a newly created promise");

        (promise, resolvers)
    }

    /// Wraps an existing object with the `JsPromise` interface, returning `Err` if the object
    /// is not a valid promise.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #    object::builtins::JsPromise,
    /// #    builtins::promise::PromiseState,
    /// #    Context, JsObject, JsValue, Source
    /// # };
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let context = &mut Context::default();
    ///
    /// let promise = context.eval(Source::from_bytes(
    ///     "new Promise((resolve, reject) => resolve())",
    /// ))?;
    /// let promise = promise.as_object().cloned().unwrap();
    ///
    /// let promise = JsPromise::from_object(promise)?;
    ///
    /// assert_eq!(
    ///     promise.state(),
    ///     PromiseState::Fulfilled(JsValue::undefined())
    /// );
    ///
    /// assert!(JsPromise::from_object(JsObject::with_null_proto()).is_err());
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn from_object(object: JsObject) -> JsResult<Self> {
        if !object.is::<Promise>() {
            return Err(JsNativeError::typ()
                .with_message("`object` is not a Promise")
                .into());
        }
        Ok(Self { inner: object })
    }

    /// Creates a new `JsPromise` from a [`Future`]-like.
    ///
    /// If you want to convert a Rust async function into an ECMAScript async function, see
    /// [`NativeFunction::from_async_fn`][async_fn].
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #    object::builtins::JsPromise,
    /// #    builtins::promise::PromiseState,
    /// #    Context, JsResult, JsValue
    /// # };
    /// async fn f() -> JsResult<JsValue> {
    ///     Ok(JsValue::null())
    /// }
    /// let context = &mut Context::default();
    ///
    /// let promise = JsPromise::from_future(f(), context);
    ///
    /// context.run_jobs();
    ///
    /// assert_eq!(promise.state(), PromiseState::Fulfilled(JsValue::null()));
    /// ```
    ///
    /// [async_fn]: crate::native_function::NativeFunction::from_async_fn
    pub fn from_future<Fut>(future: Fut, context: &mut Context) -> Self
    where
        Fut: std::future::IntoFuture<Output = JsResult<JsValue>> + 'static,
    {
        let (promise, resolvers) = Self::new_pending(context);

        let future = async move {
            let result = future.await;

            NativeJob::new(move |context| match result {
                Ok(v) => resolvers.resolve.call(&JsValue::undefined(), &[v], context),
                Err(e) => {
                    let e = e.to_opaque(context);
                    resolvers.reject.call(&JsValue::undefined(), &[e], context)
                }
            })
        };

        context
            .job_queue()
            .enqueue_future_job(Box::pin(future), context);

        promise
    }

    /// Resolves a `JsValue` into a `JsPromise`.
    ///
    /// Equivalent to the [`Promise.resolve()`] static method.
    ///
    /// This function is mainly used to wrap a plain `JsValue` into a fulfilled promise, but it can
    /// also flatten nested layers of [thenables], which essentially converts them into native
    /// promises.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #    object::builtins::JsPromise,
    /// #    builtins::promise::PromiseState,
    /// #    Context, js_string
    /// # };
    /// let context = &mut Context::default();
    ///
    /// let promise = JsPromise::resolve(js_string!("resolved!"), context);
    ///
    /// assert_eq!(
    ///     promise.state(),
    ///     PromiseState::Fulfilled(js_string!("resolved!").into())
    /// );
    /// ```
    ///
    /// [`Promise.resolve()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve
    /// [thenables]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables
    pub fn resolve<V: Into<JsValue>>(value: V, context: &mut Context) -> Self {
        Promise::promise_resolve(
            &context.intrinsics().constructors().promise().constructor(),
            value.into(),
            context,
        )
        .and_then(Self::from_object)
        .expect("default resolving functions cannot throw and must return a promise")
    }

    /// Creates a `JsPromise` that is rejected with the reason `error`.
    ///
    /// Equivalent to the [`Promise.reject`] static method.
    ///
    /// `JsPromise::reject` is pretty similar to [`JsPromise::resolve`], with the difference that
    /// it always wraps `error` into a rejected promise, even if `error` is a promise or a [thenable].
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #    object::builtins::JsPromise,
    /// #    builtins::promise::PromiseState,
    /// #    Context, js_string, JsError
    /// # };
    /// let context = &mut Context::default();
    ///
    /// let promise = JsPromise::reject(
    ///     JsError::from_opaque(js_string!("oops!").into()),
    ///     context,
    /// );
    ///
    /// assert_eq!(
    ///     promise.state(),
    ///     PromiseState::Rejected(js_string!("oops!").into())
    /// );
    /// ```
    ///
    /// [`Promise.reject`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject
    /// [thenable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables
    pub fn reject<E: Into<JsError>>(error: E, context: &mut Context) -> Self {
        Promise::promise_reject(
            &context.intrinsics().constructors().promise().constructor(),
            &error.into(),
            context,
        )
        .and_then(Self::from_object)
        .expect("default resolving functions cannot throw and must return a promise")
    }

    /// Gets the current state of the promise.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #    object::builtins::JsPromise,
    /// #    builtins::promise::PromiseState,
    /// #    Context
    /// # };
    /// let context = &mut Context::default();
    ///
    /// let promise = JsPromise::new_pending(context).0;
    ///
    /// assert_eq!(promise.state(), PromiseState::Pending);
    /// ```
    #[inline]
    #[must_use]
    pub fn state(&self) -> PromiseState {
        self.inner
            .downcast_ref::<Promise>()
            .expect("objects cannot change type after creation")
            .state()
            .clone()
    }

    /// Schedules callback functions to run when the promise settles.
    ///
    /// Equivalent to the [`Promise.prototype.then`] method.
    ///
    /// The return value is a promise that is always pending on return, regardless of the current
    /// state of the original promise. Two handlers can be provided as callbacks to be executed when
    /// the original promise settles:
    ///
    /// - If the original promise is fulfilled, `on_fulfilled` is called with the fulfillment value
    /// of the original promise.
    /// - If the original promise is rejected, `on_rejected` is called with the rejection reason
    /// of the original promise.
    ///
    /// The return value of the handlers can be used to mutate the state of the created promise. If
    /// the callback:
    ///
    /// - returns a value: the created promise gets fulfilled with the returned value.
    /// - doesn't return: the created promise gets fulfilled with undefined.
    /// - throws: the created promise gets rejected with the thrown error as its value.
    /// - returns a fulfilled promise: the created promise gets fulfilled with that promise's value as its value.
    /// - returns a rejected promise: the created promise gets rejected with that promise's value as its value.
    /// - returns another pending promise: the created promise remains pending but becomes settled with that
    /// promise's value as its value immediately after that promise becomes settled.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #     builtins::promise::PromiseState,
    /// #     js_string,
    /// #     object::{builtins::JsPromise, FunctionObjectBuilder},
    /// #     Context, JsArgs, JsError, JsValue, NativeFunction,
    /// # };
    /// let context = &mut Context::default();
    ///
    /// let promise = JsPromise::new(
    ///     |resolvers, context| {
    ///         resolvers.resolve.call(
    ///             &JsValue::undefined(),
    ///             &[255.255.into()],
    ///             context,
    ///         )?;
    ///         Ok(JsValue::undefined())
    ///     },
    ///     context,
    /// )
    /// .then(
    ///     Some(
    ///         NativeFunction::from_fn_ptr(|_, args, context| {
    ///             args.get_or_undefined(0)
    ///                 .to_string(context)
    ///                 .map(JsValue::from)
    ///         })
    ///         .to_js_function(context.realm()),
    ///     ),
    ///     None,
    ///     context,
    /// );
    ///
    /// context.run_jobs();
    ///
    /// assert_eq!(
    ///     promise.state(),
    ///     PromiseState::Fulfilled(js_string!("255.255").into())
    /// );
    /// ```
    ///
    /// [`Promise.prototype.then`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
    #[inline]
    #[allow(clippy::return_self_not_must_use)] // Could just be used to add handlers on an existing promise
    pub fn then(
        &self,
        on_fulfilled: Option<JsFunction>,
        on_rejected: Option<JsFunction>,
        context: &mut Context,
    ) -> Self {
        Promise::inner_then(self, on_fulfilled, on_rejected, context)
            .and_then(Self::from_object)
            .expect("`inner_then` cannot fail for native `JsPromise`")
    }

    /// Schedules a callback to run when the promise is rejected.
    ///
    /// Equivalent to the [`Promise.prototype.catch`] method.
    ///
    /// This is essentially a shortcut for calling [`promise.then(None, Some(function))`][then], which
    /// only handles the error case and leaves the fulfilled case untouched.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #     js_string,
    /// #     builtins::promise::PromiseState,
    /// #     object::{builtins::JsPromise, FunctionObjectBuilder},
    /// #     Context, JsArgs, JsNativeError, JsValue, NativeFunction,
    /// # };
    /// let context = &mut Context::default();
    ///
    /// let promise = JsPromise::new(
    ///     |resolvers, context| {
    ///         let error = JsNativeError::typ().with_message("thrown");
    ///         let error = error.to_opaque(context);
    ///         resolvers.reject.call(
    ///             &JsValue::undefined(),
    ///             &[error.into()],
    ///             context,
    ///         )?;
    ///         Ok(JsValue::undefined())
    ///     },
    ///     context,
    /// )
    /// .catch(
    ///     NativeFunction::from_fn_ptr(|_, args, context| {
    ///         args.get_or_undefined(0)
    ///             .to_string(context)
    ///             .map(JsValue::from)
    ///     })
    ///     .to_js_function(context.realm()),
    ///     context,
    /// );
    ///
    /// context.run_jobs();
    ///
    /// assert_eq!(
    ///     promise.state(),
    ///     PromiseState::Fulfilled(js_string!("TypeError: thrown").into())
    /// );
    /// ```
    ///
    /// [`Promise.prototype.catch`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
    /// [then]: JsPromise::then
    #[inline]
    #[allow(clippy::return_self_not_must_use)] // Could just be used to add a handler on an existing promise
    pub fn catch(&self, on_rejected: JsFunction, context: &mut Context) -> Self {
        self.then(None, Some(on_rejected), context)
    }

    /// Schedules a callback to run when the promise is rejected.
    ///
    /// Equivalent to the [`Promise.prototype.finally()`] method.
    ///
    /// While this could be seen as a shortcut for calling [`promise.then(Some(function), Some(function))`][then],
    /// it has slightly different semantics than `then`:
    /// - `on_finally` doesn't receive any argument, unlike `on_fulfilled` and `on_rejected`.
    /// - `finally()` is transparent; a call like `Promise.resolve("first").finally(() => "second")`
    /// returns a promise fulfilled with the value `"first"`, which would return `"second"` if `finally`
    /// was a shortcut of `then`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #     object::{builtins::JsPromise, FunctionObjectBuilder},
    /// #     property::Attribute,
    /// #     Context, JsNativeError, JsValue, NativeFunction, js_string
    /// # };
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let context = &mut Context::default();
    ///
    /// context.register_global_property(
    ///     js_string!("finally"),
    ///     false,
    ///     Attribute::all(),
    /// )?;
    ///
    /// let promise = JsPromise::new(
    ///     |resolvers, context| {
    ///         let error = JsNativeError::typ().with_message("thrown");
    ///         let error = error.to_opaque(context);
    ///         resolvers.reject.call(
    ///             &JsValue::undefined(),
    ///             &[error.into()],
    ///             context,
    ///         )?;
    ///         Ok(JsValue::undefined())
    ///     },
    ///     context,
    /// )
    /// .finally(
    ///     NativeFunction::from_fn_ptr(|_, _, context| {
    ///         context.global_object().clone().set(
    ///             js_string!("finally"),
    ///             JsValue::from(true),
    ///             true,
    ///             context,
    ///         )?;
    ///         Ok(JsValue::undefined())
    ///     })
    ///     .to_js_function(context.realm()),
    ///     context,
    /// );
    ///
    /// context.run_jobs();
    ///
    /// assert_eq!(
    ///     context
    ///         .global_object()
    ///         .clone()
    ///         .get(js_string!("finally"), context)?,
    ///     JsValue::from(true)
    /// );
    ///
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`Promise.prototype.finally()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally
    /// [then]: JsPromise::then
    #[inline]
    #[allow(clippy::return_self_not_must_use)] // Could just be used to add a handler on an existing promise
    pub fn finally(&self, on_finally: JsFunction, context: &mut Context) -> Self {
        let (then, catch) = Promise::then_catch_finally_closures(
            context.intrinsics().constructors().promise().constructor(),
            on_finally,
            context,
        );
        Promise::inner_then(self, Some(then), Some(catch), context)
            .and_then(Self::from_object)
            .expect("`inner_then` cannot fail for native `JsPromise`")
    }

    /// Waits for a list of promises to settle with fulfilled values, rejecting the aggregate promise
    /// when any of the inner promises is rejected.
    ///
    /// Equivalent to the [`Promise.all`] static method.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #     js_string,
    /// #     object::builtins::{JsArray, JsPromise},
    /// #     Context, JsNativeError, JsValue,
    /// # };
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let context = &mut Context::default();
    ///
    /// let promise1 = JsPromise::all(
    ///     [
    ///         JsPromise::resolve(0, context),
    ///         JsPromise::resolve(2, context),
    ///         JsPromise::resolve(4, context),
    ///     ],
    ///     context,
    /// );
    ///
    /// let promise2 = JsPromise::all(
    ///     [
    ///         JsPromise::resolve(1, context),
    ///         JsPromise::reject(JsNativeError::typ(), context),
    ///         JsPromise::resolve(3, context),
    ///     ],
    ///     context,
    /// );
    ///
    /// context.run_jobs();
    ///
    /// let array = promise1
    ///     .state()
    ///     .as_fulfilled()
    ///     .and_then(JsValue::as_object)
    ///     .unwrap()
    ///     .clone();
    /// let array = JsArray::from_object(array)?;
    /// assert_eq!(array.at(0, context)?, 0.into());
    /// assert_eq!(array.at(1, context)?, 2.into());
    /// assert_eq!(array.at(2, context)?, 4.into());
    ///
    /// let error = promise2.state().as_rejected().unwrap().clone();
    /// assert_eq!(error.to_string(context)?, js_string!("TypeError"));
    ///
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`Promise.all`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
    pub fn all<I>(promises: I, context: &mut Context) -> Self
    where
        I: IntoIterator<Item = Self>,
    {
        let promises = JsArray::from_iter(promises.into_iter().map(JsValue::from), context);

        let c = &context
            .intrinsics()
            .constructors()
            .promise()
            .constructor()
            .into();

        let value = Promise::all(c, &[promises.into()], context)
            .expect("Promise.all cannot fail with the default `%Promise%` constructor");

        let object = value
            .as_object()
            .expect("`Promise.all` always returns an object on success");

        Self::from_object(object.clone())
        .expect("`Promise::all` with the  default `%Promise%` constructor always returns a native `JsPromise`")
    }

    /// Waits for a list of promises to settle, fulfilling with an array of the outcomes of every
    /// promise.
    ///
    /// Equivalent to the [`Promise.allSettled`] static method.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #     js_string,
    /// #     object::builtins::{JsArray, JsPromise},
    /// #     Context, JsNativeError, JsValue,
    /// # };
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let context = &mut Context::default();
    ///
    /// let promise = JsPromise::all_settled(
    ///     [
    ///         JsPromise::resolve(1, context),
    ///         JsPromise::reject(JsNativeError::typ(), context),
    ///         JsPromise::resolve(3, context),
    ///     ],
    ///     context,
    /// );
    ///
    /// context.run_jobs();
    ///
    /// let array = promise
    ///     .state()
    ///     .as_fulfilled()
    ///     .and_then(JsValue::as_object)
    ///     .unwrap()
    ///     .clone();
    /// let array = JsArray::from_object(array)?;
    ///
    /// let a = array.at(0, context)?.as_object().unwrap().clone();
    /// assert_eq!(
    ///     a.get(js_string!("status"), context)?,
    ///     js_string!("fulfilled").into()
    /// );
    /// assert_eq!(a.get(js_string!("value"), context)?, 1.into());
    ///
    /// let b = array.at(1, context)?.as_object().unwrap().clone();
    /// assert_eq!(
    ///     b.get(js_string!("status"), context)?,
    ///     js_string!("rejected").into()
    /// );
    /// assert_eq!(
    ///     b.get(js_string!("reason"), context)?.to_string(context)?,
    ///     js_string!("TypeError")
    /// );
    ///
    /// let c = array.at(2, context)?.as_object().unwrap().clone();
    /// assert_eq!(
    ///     c.get(js_string!("status"), context)?,
    ///     js_string!("fulfilled").into()
    /// );
    /// assert_eq!(c.get(js_string!("value"), context)?, 3.into());
    ///
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`Promise.allSettled`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled
    pub fn all_settled<I>(promises: I, context: &mut Context) -> Self
    where
        I: IntoIterator<Item = Self>,
    {
        let promises = JsArray::from_iter(promises.into_iter().map(JsValue::from), context);

        let c = &context
            .intrinsics()
            .constructors()
            .promise()
            .constructor()
            .into();

        let value = Promise::all_settled(c, &[promises.into()], context)
            .expect("`Promise.all_settled` cannot fail with the default `%Promise%` constructor");

        let object = value
            .as_object()
            .expect("`Promise.all_settled` always returns an object on success");

        Self::from_object(object.clone())
        .expect("`Promise::all_settled` with the  default `%Promise%` constructor always returns a native `JsPromise`")
    }

    /// Returns the first promise that fulfills from a list of promises.
    ///
    /// Equivalent to the [`Promise.any`] static method.
    ///
    /// If after settling all promises in `promises` there isn't a fulfilled promise, the returned
    /// promise will be rejected with an `AggregatorError` containing the rejection values of every
    /// promise; this includes the case where `promises` is an empty iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #     builtins::promise::PromiseState,
    /// #     js_string,
    /// #     object::builtins::JsPromise,
    /// #     Context, JsNativeError,
    /// # };
    /// let context = &mut Context::default();
    ///
    /// let promise = JsPromise::any(
    ///     [
    ///         JsPromise::reject(JsNativeError::syntax(), context),
    ///         JsPromise::reject(JsNativeError::typ(), context),
    ///         JsPromise::resolve(js_string!("fulfilled"), context),
    ///         JsPromise::reject(JsNativeError::range(), context),
    ///     ],
    ///     context,
    /// );
    ///
    /// context.run_jobs();
    ///
    /// assert_eq!(
    ///     promise.state(),
    ///     PromiseState::Fulfilled(js_string!("fulfilled").into())
    /// );
    /// ```
    ///
    /// [`Promise.any`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/any
    pub fn any<I>(promises: I, context: &mut Context) -> Self
    where
        I: IntoIterator<Item = Self>,
    {
        let promises = JsArray::from_iter(promises.into_iter().map(JsValue::from), context);

        let c = &context
            .intrinsics()
            .constructors()
            .promise()
            .constructor()
            .into();

        let value = Promise::any(c, &[promises.into()], context)
            .expect("`Promise.any` cannot fail with the default `%Promise%` constructor");

        let object = value
            .as_object()
            .expect("`Promise.any` always returns an object on success");

        Self::from_object(object.clone())
        .expect("`Promise::any` with the  default `%Promise%` constructor always returns a native `JsPromise`")
    }

    /// Returns the first promise that settles from a list of promises.
    ///
    /// Equivalent to the [`Promise.race`] static method.
    ///
    /// If the provided iterator is empty, the returned promise will remain on the pending state
    /// forever.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #     builtins::promise::PromiseState,
    /// #     js_string,
    /// #     object::builtins::JsPromise,
    /// #     Context, JsValue,
    /// # };
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let context = &mut Context::default();
    ///
    /// let (a, resolvers_a) = JsPromise::new_pending(context);
    /// let (b, resolvers_b) = JsPromise::new_pending(context);
    /// let (c, resolvers_c) = JsPromise::new_pending(context);
    ///
    /// let promise = JsPromise::race([a, b, c], context);
    ///
    /// resolvers_b
    ///     .reject
    ///     .call(&JsValue::undefined(), &[], context)?;
    /// resolvers_a
    ///     .resolve
    ///     .call(&JsValue::undefined(), &[5.into()], context)?;
    /// resolvers_c.reject.call(
    ///     &JsValue::undefined(),
    ///     &[js_string!("c error").into()],
    ///     context,
    /// )?;
    ///
    /// context.run_jobs();
    ///
    /// assert_eq!(
    ///     promise.state(),
    ///     PromiseState::Rejected(JsValue::undefined())
    /// );
    ///
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`Promise.race`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race
    pub fn race<I>(promises: I, context: &mut Context) -> Self
    where
        I: IntoIterator<Item = Self>,
    {
        let promises = JsArray::from_iter(promises.into_iter().map(JsValue::from), context);

        let c = &context
            .intrinsics()
            .constructors()
            .promise()
            .constructor()
            .into();

        let value = Promise::race(c, &[promises.into()], context)
            .expect("`Promise.race` cannot fail with the default `%Promise%` constructor");

        let object = value
            .as_object()
            .expect("`Promise.race` always returns an object on success");

        Self::from_object(object.clone())
        .expect("`Promise::race` with the  default `%Promise%` constructor always returns a native `JsPromise`")
    }

    /// Creates a `JsFuture` from this `JsPromise`.
    ///
    /// The returned `JsFuture` implements [`Future`], which means it can be `await`ed within Rust's
    /// async contexts (async functions and async blocks).
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use boa_engine::{
    /// #     builtins::promise::PromiseState,
    /// #     object::builtins::JsPromise,
    /// #     Context, JsValue, JsError
    /// # };
    /// # use futures_lite::future;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let context = &mut Context::default();
    ///
    /// let (promise, resolvers) = JsPromise::new_pending(context);
    /// let promise_future = promise.into_js_future(context);
    ///
    /// let future1 = async move { promise_future.await };
    ///
    /// let future2 = async move {
    ///     resolvers
    ///         .resolve
    ///         .call(&JsValue::undefined(), &[10.into()], context)?;
    ///     context.run_jobs();
    ///     Ok::<(), JsError>(())
    /// };
    ///
    /// let (result1, result2) = future::block_on(future::zip(future1, future2));
    ///
    /// assert_eq!(result1, Ok(JsValue::from(10)));
    /// assert_eq!(result2, Ok(()));
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub fn into_js_future(self, context: &mut Context) -> JsFuture {
        // Mostly based from:
        // https://docs.rs/wasm-bindgen-futures/0.4.37/src/wasm_bindgen_futures/lib.rs.html#109-168

        fn finish(state: &GcRefCell<Inner>, val: JsResult<JsValue>) {
            let task = {
                let mut state = state.borrow_mut();

                // The engine ensures both `resolve` and `reject` are called only once,
                // and only one of them.
                debug_assert!(state.result.is_none());

                // Store the received value into the state shared by the resolving functions
                // and the `JsFuture` itself. This will be accessed when the executor polls
                // the `JsFuture` again.
                state.result = Some(val);
                state.task.take()
            };

            // `task` could be `None` if the `JsPromise` was already fulfilled before polling
            // the `JsFuture`.
            if let Some(task) = task {
                task.wake();
            }
        }

        let state = Gc::new(GcRefCell::new(Inner {
            result: None,
            task: None,
        }));

        let resolve = {
            let state = state.clone();

            NativeFunction::from_copy_closure_with_captures(
                move |_, args, state, _| {
                    finish(state, Ok(args.get_or_undefined(0).clone()));
                    Ok(JsValue::undefined())
                },
                state,
            )
        };

        let reject = {
            let state = state.clone();

            NativeFunction::from_copy_closure_with_captures(
                move |_, args, state, _| {
                    let err = JsError::from_opaque(args.get_or_undefined(0).clone());
                    finish(state, Err(err));
                    Ok(JsValue::undefined())
                },
                state,
            )
        };

        drop(self.then(
            Some(resolve.to_js_function(context.realm())),
            Some(reject.to_js_function(context.realm())),
            context,
        ));

        JsFuture { inner: state }
    }
}

impl From<JsPromise> for JsObject {
    #[inline]
    fn from(o: JsPromise) -> Self {
        o.inner.clone()
    }
}

impl From<JsPromise> for JsValue {
    #[inline]
    fn from(o: JsPromise) -> Self {
        o.inner.clone().into()
    }
}

impl std::ops::Deref for JsPromise {
    type Target = JsObject;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl JsObjectType for JsPromise {}

impl TryFromJs for JsPromise {
    fn try_from_js(value: &JsValue, _context: &mut Context) -> JsResult<Self> {
        match value {
            JsValue::Object(o) => Self::from_object(o.clone()),
            _ => Err(JsNativeError::typ()
                .with_message("value is not a Promise object")
                .into()),
        }
    }
}

/// A Rust's `Future` that becomes ready when a `JsPromise` fulfills.
///
/// This type allows `await`ing `JsPromise`s inside Rust's async contexts, which makes interfacing
/// between promises and futures a bit easier.
///
/// The only way to construct an instance of `JsFuture` is by calling [`JsPromise::into_js_future`].
pub struct JsFuture {
    inner: Gc<GcRefCell<Inner>>,
}

impl std::fmt::Debug for JsFuture {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JsFuture").finish_non_exhaustive()
    }
}

#[derive(Trace, Finalize)]
struct Inner {
    result: Option<JsResult<JsValue>>,
    #[unsafe_ignore_trace]
    task: Option<task::Waker>,
}

// Taken from:
// https://docs.rs/wasm-bindgen-futures/0.4.37/src/wasm_bindgen_futures/lib.rs.html#171-187
impl Future for JsFuture {
    type Output = JsResult<JsValue>;

    fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
        let mut inner = self.inner.borrow_mut();

        if let Some(result) = inner.result.take() {
            return task::Poll::Ready(result);
        }

        inner.task = Some(cx.waker().clone());
        task::Poll::Pending
    }
}