-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathquickjspp.hpp
2232 lines (1964 loc) · 71.9 KB
/
quickjspp.hpp
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
#pragma once
#include "quickjs/quickjs.h"
#include <vector>
#include <string_view>
#include <string>
#include <cassert>
#include <memory>
#include <cstddef>
#include <algorithm>
#include <tuple>
#include <functional>
#include <stdexcept>
#include <variant>
#include <optional>
#include <type_traits>
#include <unordered_map>
#include <fstream>
#include <ios>
#include <sstream>
#include <filesystem>
#if defined(__cpp_rtti)
#define QJSPP_TYPENAME(...) (typeid(__VA_ARGS__).name())
#else
#define QJSPP_TYPENAME(...) #__VA_ARGS__
#endif
namespace qjs {
class Context;
class Value;
/** Exception type.
* Indicates that exception has occured in JS context.
*/
class exception {
JSContext * ctx;
public:
exception(JSContext * ctx) : ctx(ctx) {}
Context & context() const;
/// Clears and returns the occurred exception.
Value get();
};
/** std::shared_ptr, for compatibility with quickjspp v2. */
template <class T> using shared_ptr = std::shared_ptr<T>;
/** std::make_shared, for compatibility with quickjspp v2. */
template <class T, typename... Args>
shared_ptr<T> make_shared(JSContext *, Args&&... args)
{
return std::make_shared<T>(std::forward<Args>(args)...);
}
/** Javascript conversion traits.
* Describes how to convert type R to/from JSValue. Second template argument can be used for SFINAE/enable_if type filters.
*/
template <typename R, typename /*_SFINAE*/ = void>
struct js_traits
{
/** Create an object of C++ type R given JSValue v and JSContext.
* This function is intentionally not implemented. User should implement this function for their own type.
* @param v This value is passed as JSValueConst so it should be freed by the caller.
* @throws exception in case of conversion error
*/
static R unwrap(JSContext * ctx, JSValueConst v) = delete;
/** Create JSValue from an object of type R and JSContext.
* This function is intentionally not implemented. User should implement this function for their own type.
* @return Returns JSValue which should be freed by the caller or JS_EXCEPTION in case of error.
*/
static JSValue wrap(JSContext * ctx, R value) = delete;
};
/** Conversion traits for JSValue (identity).
*/
template <>
struct js_traits<JSValue>
{
static JSValue unwrap(JSContext * ctx, JSValueConst v) noexcept
{
return JS_DupValue(ctx, v);
}
static JSValue wrap(JSContext * ctx, JSValue&& v) noexcept
{
return v;
}
};
/** Conversion traits for integers.
* Intentionally doesn't define traits for uint64_t since it can be typedefed to JSValue. (@see JS_NAN_BOXING)
*/
template <typename Int>
struct js_traits<Int, std::enable_if_t<std::is_integral_v<Int> && sizeof(Int) <= sizeof(int64_t) && !std::is_same_v<Int, uint64_t>>>
{
/// @throws exception
static Int unwrap(JSContext * ctx, JSValueConst v)
{
if constexpr (sizeof(Int) > sizeof(int32_t))
{
int64_t r;
if(JS_ToInt64(ctx, &r, v))
throw exception{ctx};
return static_cast<Int>(r);
}
else
{
int32_t r;
if(JS_ToInt32(ctx, &r, v))
throw exception{ctx};
return static_cast<Int>(r);
}
}
static JSValue wrap(JSContext * ctx, Int i) noexcept
{
if constexpr (std::is_same_v<Int, uint32_t> || sizeof(Int) > sizeof(int32_t))
return JS_NewInt64(ctx, static_cast<Int>(i));
else
return JS_NewInt32(ctx, static_cast<Int>(i));
}
};
/** Conversion traits for boolean.
*/
template <>
struct js_traits<bool>
{
static bool unwrap(JSContext * ctx, JSValueConst v) noexcept
{
// TODO: is this behaviour correct?
return JS_ToBool(ctx, v) > 0;
}
static JSValue wrap(JSContext * ctx, bool i) noexcept
{
return JS_NewBool(ctx, i);
}
};
/** Conversion trait for void.
*/
template <>
struct js_traits<void>
{
/// @throws exception if jsvalue is neither undefined nor null
static void unwrap(JSContext * ctx, JSValueConst value)
{
if(JS_IsException(value))
throw exception{ctx};
}
};
/** Conversion traits for float64/double.
*/
template <>
struct js_traits<double>
{
/// @throws exception
static double unwrap(JSContext * ctx, JSValueConst v)
{
double r;
if(JS_ToFloat64(ctx, &r, v))
throw exception{ctx};
return r;
}
static JSValue wrap(JSContext * ctx, double i) noexcept
{
return JS_NewFloat64(ctx, i);
}
};
namespace detail {
/** Fake std::string_view which frees the string on destruction.
*/
class js_string : public std::string_view
{
using Base = std::string_view;
JSContext * ctx = nullptr;
friend struct js_traits<std::string_view>;
js_string(JSContext * ctx, const char * ptr, std::size_t len) : Base(ptr, len), ctx(ctx) {}
public:
template <typename... Args>
js_string(Args&& ... args) : Base(std::forward<Args>(args)...), ctx(nullptr) {}
js_string(const js_string& other) = delete;
operator const char *() const
{
return this->data();
}
~js_string()
{
if(ctx)
JS_FreeCString(ctx, this->data());
}
};
} // namespace detail
/** Conversion traits from std::string_view and to detail::js_string. */
template <>
struct js_traits<std::string_view>
{
static detail::js_string unwrap(JSContext * ctx, JSValueConst v)
{
size_t plen;
const char * ptr = JS_ToCStringLen(ctx, &plen, v);
if(!ptr)
throw exception{ctx};
return detail::js_string{ctx, ptr, plen};
}
static JSValue wrap(JSContext * ctx, std::string_view str) noexcept
{
return JS_NewStringLen(ctx, str.data(), str.size());
}
};
/** Conversion traits for std::string */
template <> // slower
struct js_traits<std::string>
{
static std::string unwrap(JSContext * ctx, JSValueConst v)
{
auto str_view = js_traits<std::string_view>::unwrap(ctx, v);
return std::string{str_view.data(), str_view.size()};
}
static JSValue wrap(JSContext * ctx, const std::string& str) noexcept
{
return JS_NewStringLen(ctx, str.data(), str.size());
}
};
/** Conversion from const char * */
template <>
struct js_traits<const char *>
{
static JSValue wrap(JSContext * ctx, const char * str) noexcept
{
return JS_NewString(ctx, str);
}
static detail::js_string unwrap(JSContext * ctx, JSValueConst v)
{
return js_traits<std::string_view>::unwrap(ctx, v);
}
};
/** Conversion from const std::variant */
template <typename ... Ts>
struct js_traits<std::variant<Ts...>>
{
static JSValue wrap(JSContext * ctx, std::variant<Ts...> value) noexcept
{
return std::visit([ctx](auto&& value) {
using T = std::decay_t<decltype(value)>;
return js_traits<T>::wrap(ctx, value);
}, std::move(value));
}
/* Useful type traits */
template <typename T> struct is_shared_ptr : std::false_type {};
template <typename T> struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
template <typename T> struct is_string
{
static constexpr bool value = std::is_same_v<T, const char *> || std::is_same_v<std::decay_t<T>, std::string> ||
std::is_same_v<std::decay_t<T>, std::string_view>;
};
template <typename T> struct is_boolean { static constexpr bool value = std::is_same_v<std::decay_t<T>, bool>; };
template <typename T> struct is_double { static constexpr bool value = std::is_same_v<std::decay_t<T>, double>; };
template <typename T> struct is_vector : std::false_type {};
template <typename T> struct is_vector<std::vector<T>> : std::true_type {};
template <typename T> struct is_pair : std::false_type {};
template <typename U, typename V> struct is_pair<std::pair<U, V>> : std::true_type {};
template <typename T> struct is_variant : std::false_type {};
template <typename ... Us> struct is_variant<std::variant<Us...>> : std::true_type {};
/** Attempt to match common types (integral, floating-point, string, etc.) */
template <template <typename R> typename Trait, typename U, typename ... Us>
static std::optional<std::variant<Ts...>> unwrapImpl(JSContext * ctx, JSValueConst v)
{
if constexpr (Trait<U>::value)
{
return js_traits<U>::unwrap(ctx, v);
}
if constexpr ((sizeof ... (Us)) > 0)
{
return unwrapImpl<Trait, Us...>(ctx, v);
}
return std::nullopt;
}
/** Attempt to match class ID with type */
template <typename U, typename ... Us>
static std::optional<std::variant<Ts...>> unwrapObj(JSContext * ctx, JSValueConst v, JSClassID class_id)
{
if constexpr (is_shared_ptr<U>::value)
{
if(class_id == js_traits<U>::QJSClassId)
{
return js_traits<U>::unwrap(ctx, v);
}
}
// try to unwrap embedded variant (variant<variant<...>>), might be slow
if constexpr (is_variant<U>::value)
{
if(auto opt = js_traits<std::optional<U>>::unwrap(ctx, v))
return *opt;
}
if constexpr (is_vector<U>::value)
{
if(JS_IsArray(ctx, v) == 1)
{
auto firstElement = JS_GetPropertyUint32(ctx, v, 0);
bool ok = isCompatible<std::decay_t<typename U::value_type>>(ctx, firstElement);
JS_FreeValue(ctx, firstElement);
if(ok)
{
return U{js_traits<U>::unwrap(ctx, v)};
}
}
}
if constexpr (is_pair<U>::value)
{
if(JS_IsArray(ctx, v) == 1)
{
// todo: check length?
auto firstElement = JS_GetPropertyUint32(ctx, v, 0);
auto secondElement = JS_GetPropertyUint32(ctx, v, 1);
bool ok = isCompatible<std::decay_t<typename U::first_type>>(ctx, firstElement)
&& isCompatible<std::decay_t<typename U::second_type>>(ctx, secondElement);
JS_FreeValue(ctx, firstElement);
JS_FreeValue(ctx, secondElement);
if(ok)
{
return U{js_traits<U>::unwrap(ctx, v)};
}
}
}
if constexpr ((sizeof ... (Us)) > 0)
{
return unwrapObj<Us...>(ctx, v, class_id);
}
return std::nullopt;
}
/** Attempt to cast to types satisfying traits, ordered in terms of priority */
template <template <typename T> typename Trait, template <typename T> typename ... Traits>
static std::variant<Ts...> unwrapPriority(JSContext * ctx, JSValueConst v)
{
if(auto result = unwrapImpl<Trait, Ts...>(ctx, v))
{
return *result;
}
if constexpr ((sizeof ... (Traits)) > 0)
{
return unwrapPriority<Traits...>(ctx, v);
}
JS_ThrowTypeError(ctx, "Expected type %s", QJSPP_TYPENAME(std::variant<Ts...>));
throw exception{ctx};
}
template <typename T>
static bool isCompatible(JSContext * ctx, JSValueConst v) noexcept
{
//const char * type_name = typeid(T).name();
switch(JS_VALUE_GET_TAG(v))
{
case JS_TAG_STRING:
return is_string<T>::value;
case JS_TAG_FUNCTION_BYTECODE:
return std::is_function<T>::value;
case JS_TAG_OBJECT:
if(JS_IsArray(ctx, v) == 1)
return is_vector<T>::value || is_pair<T>::value;
if constexpr (is_shared_ptr<T>::value)
{
if(JS_GetClassID(v) == js_traits<T>::QJSClassId)
return true;
}
return false;
case JS_TAG_INT:
[[fallthrough]];
case JS_TAG_BIG_INT:
return std::is_integral_v<T> || std::is_floating_point_v<T>;
case JS_TAG_BOOL:
return is_boolean<T>::value || std::is_integral_v<T> || std::is_floating_point_v<T>;
case JS_TAG_BIG_DECIMAL:
[[fallthrough]];
case JS_TAG_BIG_FLOAT:
[[fallthrough]];
case JS_TAG_FLOAT64:
default: // >JS_TAG_FLOAT64 (JS_NAN_BOXING)
return is_double<T>::value || std::is_floating_point_v<T>;
case JS_TAG_SYMBOL:
[[fallthrough]];
case JS_TAG_MODULE:
[[fallthrough]];
case JS_TAG_NULL:
[[fallthrough]];
case JS_TAG_UNDEFINED:
[[fallthrough]];
case JS_TAG_UNINITIALIZED:
[[fallthrough]];
case JS_TAG_CATCH_OFFSET:
[[fallthrough]];
case JS_TAG_EXCEPTION:
break;
}
return false;
}
static std::variant<Ts...> unwrap(JSContext * ctx, JSValueConst v)
{
const auto tag = JS_VALUE_GET_TAG(v);
switch(tag)
{
case JS_TAG_STRING:
return unwrapPriority<is_string>(ctx, v);
case JS_TAG_FUNCTION_BYTECODE:
return unwrapPriority<std::is_function>(ctx, v);
case JS_TAG_OBJECT:
if(auto result = unwrapObj<Ts...>(ctx, v, JS_GetClassID(v)))
{
return *result;
}
JS_ThrowTypeError(ctx, "Expected type %s, got object with classid %d",
QJSPP_TYPENAME(std::variant<Ts...>), JS_GetClassID(v));
break;
case JS_TAG_INT:
[[fallthrough]];
case JS_TAG_BIG_INT:
return unwrapPriority<std::is_integral, std::is_floating_point>(ctx, v);
case JS_TAG_BOOL:
return unwrapPriority<is_boolean, std::is_integral, std::is_floating_point>(ctx, v);
case JS_TAG_SYMBOL:
[[fallthrough]];
case JS_TAG_MODULE:
[[fallthrough]];
case JS_TAG_NULL:
[[fallthrough]];
case JS_TAG_UNDEFINED:
[[fallthrough]];
case JS_TAG_UNINITIALIZED:
[[fallthrough]];
case JS_TAG_CATCH_OFFSET:
JS_ThrowTypeError(ctx, "Expected type %s, got tag %d", QJSPP_TYPENAME(std::variant<Ts...>), tag);
[[fallthrough]];
case JS_TAG_EXCEPTION:
break;
case JS_TAG_BIG_DECIMAL:
[[fallthrough]];
case JS_TAG_BIG_FLOAT:
[[fallthrough]];
case JS_TAG_FLOAT64:
[[fallthrough]];
default: // more than JS_TAG_FLOAT64 (nan boxing)
return unwrapPriority<is_double, std::is_floating_point>(ctx, v);
}
throw exception{ctx};
}
};
template <typename T>
struct rest : std::vector<T>
{
using std::vector<T>::vector;
using std::vector<T>::operator=;
};
namespace detail {
/** Helper function to convert and then free JSValue. */
template <typename T>
T unwrap_free(JSContext * ctx, JSValue val)
{
if constexpr(std::is_same_v<T, void>)
{
JS_FreeValue(ctx, val);
return js_traits<T>::unwrap(ctx, val);
}
else
{
try
{
T result = js_traits<std::decay_t<T>>::unwrap(ctx, val);
JS_FreeValue(ctx, val);
return result;
}
catch(...)
{
JS_FreeValue(ctx, val);
throw;
}
}
}
template <typename T, size_t I, size_t NArgs>
struct unwrap_arg_impl {
static auto unwrap(JSContext * ctx, int argc, JSValueConst * argv)
{
if (size_t(argc) <= I) {
JS_ThrowTypeError(ctx, "Expected at least %lu arguments but received %d",
(unsigned long)NArgs, argc);
throw exception{ctx};
}
return js_traits<std::decay_t<T>>::unwrap(ctx, argv[I]);
}
};
template <typename T, size_t I, size_t NArgs>
struct unwrap_arg_impl<rest<T>, I, NArgs> {
static rest<T> unwrap(JSContext * ctx, int argc, JSValueConst * argv) {
static_assert(I == NArgs - 1, "The `rest` argument must be the last function argument.");
rest<T> result;
result.reserve(argc - I);
for (size_t i = I; i < size_t(argc); ++i)
result.push_back(js_traits<T>::unwrap(ctx, argv[i]));
return result;
}
};
template <class Tuple, std::size_t... I>
Tuple unwrap_args_impl(JSContext * ctx, int argc, JSValueConst * argv, std::index_sequence<I...>)
{
return Tuple{unwrap_arg_impl<std::tuple_element_t<I, Tuple>, I, sizeof...(I)>::unwrap(ctx, argc, argv)...};
}
/** Helper function to convert an array of JSValues to a tuple.
* @tparam Args C++ types of the argv array
*/
template <typename... Args>
std::tuple<std::decay_t<Args>...> unwrap_args(JSContext * ctx, int argc, JSValueConst * argv)
{
return unwrap_args_impl<std::tuple<std::decay_t<Args>...>>(ctx, argc, argv, std::make_index_sequence<sizeof...(Args)>());
}
/** Helper function to call f with an array of JSValues.
* @tparam R return type of f
* @tparam Args argument types of f
* @tparam Callable type of f (inferred)
* @param ctx JSContext
* @param f callable object
* @param argv array of JSValue's
* @return converted return value of f or JS_NULL if f returns void
*/
template <typename R, typename... Args, typename Callable>
JSValue wrap_call(JSContext * ctx, Callable&& f, int argc, JSValueConst * argv) noexcept
{
try
{
if constexpr(std::is_same_v<R, void>)
{
std::apply(std::forward<Callable>(f), unwrap_args<Args...>(ctx, argc, argv));
return JS_NULL;
}
else
{
return js_traits<std::decay_t<R>>::wrap(ctx,
std::apply(std::forward<Callable>(f),
unwrap_args<Args...>(ctx, argc, argv)));
}
}
catch(exception)
{
return JS_EXCEPTION;
}
catch (std::exception const & err)
{
JS_ThrowInternalError(ctx, "%s", err.what());
return JS_EXCEPTION;
}
catch (...)
{
JS_ThrowInternalError(ctx, "Unknown error");
return JS_EXCEPTION;
}
}
/** Same as wrap_call, but pass this_value as first argument.
* @tparam FirstArg type of this_value
*/
template <typename R, typename FirstArg, typename... Args, typename Callable>
JSValue wrap_this_call(JSContext * ctx, Callable&& f, JSValueConst this_value, int argc, JSValueConst * argv) noexcept
{
try
{
if constexpr(std::is_same_v<R, void>)
{
std::apply(std::forward<Callable>(f), std::tuple_cat(unwrap_args<FirstArg>(ctx, 1, &this_value),
unwrap_args<Args...>(ctx, argc, argv)));
return JS_NULL;
}
else
{
return js_traits<std::decay_t<R>>::wrap(ctx,
std::apply(std::forward<Callable>(f),
std::tuple_cat(
unwrap_args<FirstArg>(ctx, 1, &this_value),
unwrap_args<Args...>(ctx, argc, argv))));
}
}
catch(exception)
{
return JS_EXCEPTION;
}
catch (std::exception const & err)
{
JS_ThrowInternalError(ctx, "%s", err.what());
return JS_EXCEPTION;
}
catch (...)
{
JS_ThrowInternalError(ctx, "Unknown error");
return JS_EXCEPTION;
}
}
template <class Tuple, std::size_t... I>
void wrap_args_impl(JSContext * ctx, JSValue * argv, Tuple tuple, std::index_sequence<I...>)
{
((argv[I] = js_traits<std::decay_t<std::tuple_element_t<I, Tuple>>>::wrap(ctx, std::get<I>(tuple))), ...);
}
/** Converts C++ args to JSValue array.
* @tparam Args argument types
* @param argv array of size at least sizeof...(Args)
*/
template <typename... Args>
void wrap_args(JSContext * ctx, JSValue * argv, Args&& ... args)
{
wrap_args_impl(ctx, argv, std::make_tuple(std::forward<Args>(args)...),
std::make_index_sequence<sizeof...(Args)>());
}
// Helper trait to obtain `T` in `T::*` expressions
template<typename T> struct class_from_member_pointer { using type = void; };
template<typename T, typename U> struct class_from_member_pointer<T U::*> { using type = U; };
template<typename T> using class_from_member_pointer_t = typename class_from_member_pointer<T>::type;
} // namespace detail
/** A wrapper type for free and class member functions.
* Pointer to function F is a template argument.
* @tparam F either a pointer to free function or a pointer to class member function
* @tparam PassThis if true and F is a pointer to free function, passes Javascript "this" value as first argument:
*/
template <auto F, bool PassThis = false /* pass this as the first argument */>
struct fwrapper
{
/// "name" property of the JS function object (not defined if nullptr)
const char * name = nullptr;
};
/** Conversion to JSValue for free function in fwrapper. */
template <typename R, typename... Args, R (* F)(Args...), bool PassThis>
struct js_traits<fwrapper<F, PassThis>>
{
static JSValue wrap(JSContext * ctx, fwrapper<F, PassThis> fw) noexcept
{
return JS_NewCFunction(ctx, [](JSContext * ctx, JSValueConst this_value, int argc,
JSValueConst * argv) noexcept -> JSValue {
if constexpr(PassThis)
return detail::wrap_this_call<R, Args...>(ctx, F, this_value, argc, argv);
else
return detail::wrap_call<R, Args...>(ctx, F, argc, argv);
}, fw.name, sizeof...(Args));
}
};
/** Conversion to JSValue for class member function in fwrapper. PassThis is ignored and treated as true */
template <typename R, class T, typename... Args, R (T::*F)(Args...), bool PassThis/*=ignored*/>
struct js_traits<fwrapper<F, PassThis>>
{
static JSValue wrap(JSContext * ctx, fwrapper<F, PassThis> fw) noexcept
{
return JS_NewCFunction(ctx, [](JSContext * ctx, JSValueConst this_value, int argc,
JSValueConst * argv) noexcept -> JSValue {
return detail::wrap_this_call<R, std::shared_ptr<T>, Args...>(ctx, F, this_value, argc, argv);
}, fw.name, sizeof...(Args));
}
};
/** Conversion to JSValue for const class member function in fwrapper. PassThis is ignored and treated as true */
template <typename R, class T, typename... Args, R (T::*F)(Args...) const, bool PassThis/*=ignored*/>
struct js_traits<fwrapper<F, PassThis>>
{
static JSValue wrap(JSContext * ctx, fwrapper<F, PassThis> fw) noexcept
{
return JS_NewCFunction(ctx, [](JSContext * ctx, JSValueConst this_value, int argc,
JSValueConst * argv) noexcept -> JSValue {
return detail::wrap_this_call<R, std::shared_ptr<T>, Args...>(ctx, F, this_value, argc, argv);
}, fw.name, sizeof...(Args));
}
};
/** A wrapper type for constructor of type T with arguments Args.
* Compilation fails if no such constructor is defined.
* @tparam Args constructor arguments
*/
template <class T, typename... Args>
struct ctor_wrapper
{
static_assert(std::is_constructible<T, Args...>::value, "no such constructor!");
/// "name" property of JS constructor object
const char * name = nullptr;
};
namespace detail {
/// equivalent to JS_GetPropertyStr(ctx, this_value, "prototype");
inline JSValue GetPropertyPrototype(JSContext * ctx, JSValueConst this_value)
{
// constant atom: doesn't need to be freed and doesn't change with context
static const JSAtom JS_ATOM_prototype = JS_NewAtom(ctx, "prototype");
return JS_GetProperty(ctx, this_value, JS_ATOM_prototype);
}
} // namespace detail
/** Conversion to JSValue for ctor_wrapper. */
template <class T, typename... Args>
struct js_traits<ctor_wrapper<T, Args...>>
{
static JSValue wrap(JSContext * ctx, ctor_wrapper<T, Args...> cw) noexcept
{
return JS_NewCFunction2(ctx, [](JSContext * ctx, JSValueConst this_value, int argc,
JSValueConst * argv) noexcept -> JSValue {
if(js_traits<std::shared_ptr<T>>::QJSClassId == 0) // not registered
{
#if defined(__cpp_rtti)
// automatically register class on first use (no prototype)
js_traits<std::shared_ptr<T>>::register_class(ctx, typeid(T).name());
#else
JS_ThrowTypeError(ctx, "quickjspp ctor_wrapper<T>::wrap: Class is not registered");
return JS_EXCEPTION;
#endif
}
auto proto = detail::GetPropertyPrototype(ctx, this_value);
if(JS_IsException(proto))
return proto;
auto jsobj = JS_NewObjectProtoClass(ctx, proto, js_traits<std::shared_ptr<T>>::QJSClassId);
JS_FreeValue(ctx, proto);
if(JS_IsException(jsobj))
return jsobj;
try
{
std::shared_ptr<T> ptr = std::apply(std::make_shared<T, Args...>, detail::unwrap_args<Args...>(ctx, argc, argv));
JS_SetOpaque(jsobj, new std::shared_ptr<T>(std::move(ptr)));
return jsobj;
}
catch (exception)
{
JS_FreeValue(ctx, jsobj);
return JS_EXCEPTION;
}
catch (std::exception const & err)
{
JS_FreeValue(ctx, jsobj);
JS_ThrowInternalError(ctx, "%s", err.what());
return JS_EXCEPTION;
}
catch (...)
{
JS_FreeValue(ctx, jsobj);
JS_ThrowInternalError(ctx, "Unknown error");
return JS_EXCEPTION;
}
// return detail::wrap_call<std::shared_ptr<T>, Args...>(ctx, std::make_shared<T, Args...>, argv);
}, cw.name, sizeof...(Args), JS_CFUNC_constructor, 0);
}
};
/** Conversions for std::shared_ptr<T>. Empty shared_ptr corresponds to JS_NULL.
* T should be registered to a context before conversions.
* @tparam T class type
*/
template <class T>
struct js_traits<std::shared_ptr<T>>
{
/// Registered class id in QuickJS.
inline static JSClassID QJSClassId = 0;
/// Signature of the function to obtain the std::shared_ptr from the JSValue.
using ptr_cast_fcn_t = std::function<std::shared_ptr<T>(JSContext*, JSValueConst)>;
/// Used by registerDerivedClass to register new derived classes with this class' base type.
inline static std::function<void(JSClassID, ptr_cast_fcn_t)> registerWithBase;
/// Mapping between derived class' JSClassID and function to obtain the std::shared_ptr from the JSValue.
inline static std::unordered_map<JSClassID, ptr_cast_fcn_t> ptrCastFcnMap;
/** Register a class as a derived class.
*
* @tparam D type of the derived class
* @param derived_class_id class id of the derived class
* @param ptr_cast_fcn function to obtain a std::shared_ptr from the JSValue
*/
template<typename D>
static void registerDerivedClass(JSClassID derived_class_id, ptr_cast_fcn_t ptr_cast_fcn) {
static_assert(std::is_base_of<T,D>::value && !std::is_same<T,D>::value, "Type is not a derived class");
using derived_ptr_cast_fcn_t = typename js_traits<std::shared_ptr<D>>::ptr_cast_fcn_t;
// Register how to obtain the std::shared_ptr from the derived class.
ptrCastFcnMap[derived_class_id] = ptr_cast_fcn;
// Propagate the registration to our base class (if any).
if (registerWithBase) registerWithBase(derived_class_id, ptr_cast_fcn);
// Instrument the derived class so that it can propagate new derived classes to us.
auto old_registerWithBase = js_traits<std::shared_ptr<D>>::registerWithBase;
js_traits<std::shared_ptr<D>>::registerWithBase =
[old_registerWithBase = std::move(old_registerWithBase)]
(JSClassID derived_class_id, derived_ptr_cast_fcn_t derived_ptr_cast_fcn){
if (old_registerWithBase) old_registerWithBase(derived_class_id, derived_ptr_cast_fcn);
registerDerivedClass<D>(derived_class_id, [derived_cast_fcn = std::move(derived_ptr_cast_fcn)](JSContext * ctx, JSValueConst v) {
return std::shared_ptr<T>(derived_cast_fcn(ctx, v));
});
};
}
template <typename B>
static
std::enable_if_t<std::is_same_v<B, T> || std::is_same_v<B, void>>
ensureCanCastToBase() { }
template <typename B>
static
std::enable_if_t<!std::is_same_v<B, T> && !std::is_same_v<B, void>>
ensureCanCastToBase() {
static_assert(std::is_base_of_v<B, T>, "Type is not a derived class");
if(js_traits<std::shared_ptr<T>>::QJSClassId == 0)
JS_NewClassID(&js_traits<std::shared_ptr<T>>::QJSClassId);
js_traits<std::shared_ptr<B>>::template registerDerivedClass<T>(QJSClassId, unwrap);
}
template <auto M>
static void ensureCanCastToBase() {
ensureCanCastToBase<detail::class_from_member_pointer_t<decltype(M)>>();
}
/** Stores offsets to qjs::Value members of T.
* These values should be marked by class_registrar::mark for QuickJS garbage collector
* so that the cycle removal algorithm can find the other objects referenced by this object.
*/
static inline std::vector<Value T::*> markOffsets;
/** Register class in QuickJS context.
*
* @param ctx context
* @param name class name
* @param proto class prototype or JS_NULL
* @param call QJS call function. see quickjs doc
* @param exotic pointer to QJS exotic methods(static lifetime) which allow custom property handling. see quickjs doc
* @throws exception
*/
static void register_class(JSContext * ctx, const char * name, JSValue proto = JS_NULL,
JSClassCall * call = nullptr, JSClassExoticMethods * exotic = nullptr)
{
if(QJSClassId == 0)
{
JS_NewClassID(&QJSClassId);
}
auto rt = JS_GetRuntime(ctx);
if(!JS_IsRegisteredClass(rt, QJSClassId))
{
JSClassGCMark * marker = nullptr;
if(!markOffsets.empty())
{
marker = [](JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) {
auto pptr = static_cast<std::shared_ptr<T> *>(JS_GetOpaque(val, QJSClassId));
assert(pptr);
const T * ptr = pptr->get();
assert(ptr);
for(Value T::* member : markOffsets)
{
JS_MarkValue(rt, (*ptr.*member).v, mark_func);
}
};
}
JSClassDef def{
name,
// destructor (finalizer)
[](JSRuntime * rt, JSValue obj) noexcept {
auto pptr = static_cast<std::shared_ptr<T> *>(JS_GetOpaque(obj, QJSClassId));
delete pptr;
},
// mark
marker,
// call
call,
// exotic
exotic
};
int e = JS_NewClass(rt, QJSClassId, &def);
if(e < 0)
{
JS_ThrowInternalError(ctx, "Can't register class %s", name);
throw exception{ctx};
}
}
JS_SetClassProto(ctx, QJSClassId, proto);
}
/** Create a JSValue from std::shared_ptr<T>.
* Creates an object with class if #QJSClassId and sets its opaque pointer to a new copy of #ptr.
*/
static JSValue wrap(JSContext * ctx, std::shared_ptr<T> ptr)
{
if(!ptr)
return JS_NULL;
if(QJSClassId == 0) // not registered
{
#if defined(__cpp_rtti)
// automatically register class on first use (no prototype)
register_class(ctx, typeid(T).name());
#else
JS_ThrowTypeError(ctx, "quickjspp std::shared_ptr<T>::wrap: Class is not registered");
return JS_EXCEPTION;
#endif
}
auto jsobj = JS_NewObjectClass(ctx, QJSClassId);
if(JS_IsException(jsobj))
return jsobj;
auto pptr = new std::shared_ptr<T>(std::move(ptr));
JS_SetOpaque(jsobj, pptr);
return jsobj;
}
/// @throws exception if #v doesn't have the correct class id
static std::shared_ptr<T> unwrap(JSContext * ctx, JSValueConst v)
{
std::shared_ptr<T> ptr = nullptr;
if (JS_IsNull(v)) {
return ptr;
}
auto obj_class_id = JS_GetClassID(v);
if (obj_class_id == QJSClassId) {
// The JS object is of class T
void * opaque = JS_GetOpaque2(ctx, v, obj_class_id);
assert(opaque && "No opaque pointer in object");
ptr = *static_cast<std::shared_ptr<T> *>(opaque);
} else if (ptrCastFcnMap.count(obj_class_id)) {
// The JS object is of a class derived from T
ptr = ptrCastFcnMap[obj_class_id](ctx, v);
} else {
// The JS object does not derives from T
JS_ThrowTypeError(ctx, "Expected type %s, got object with classid %d",
QJSPP_TYPENAME(T), obj_class_id);
throw exception{ctx};
}
if(!ptr) {
JS_ThrowInternalError(ctx, "Object's opaque pointer is NULL");
throw exception{ctx};
}
return ptr;
}
};
/** Conversions for non-owning pointers to class T. nullptr corresponds to JS_NULL.
* @tparam T class type
*/