forked from dhilip89/njs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnjs-engine-v8.h
More file actions
2150 lines (1736 loc) · 83.4 KB
/
njs-engine-v8.h
File metadata and controls
2150 lines (1736 loc) · 83.4 KB
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
// [NJS-API]
// Native JavaScript API for Bindings.
//
// [License]
// Public Domain <http://unlicense.org>
// This file implements a NJS <-> V8 engine bridge.
#ifndef NJS_ENGINE_V8_H
#define NJS_ENGINE_V8_H
#include "./njs-base.h"
#include <v8.h>
#if defined(NJS_INTEGRATE_NODE)
# include <node.h>
# include <node_buffer.h>
#endif // NJS_INTEGRATE_NODE
namespace njs {
// ============================================================================
// [njs::Globals]
// ============================================================================
namespace Globals {
static const size_t kMaxStringSize = static_cast<size_t>(v8::String::kMaxLength);
} // Globals namespace
// ============================================================================
// [njs::TypeDefs]
// ============================================================================
typedef v8::FunctionCallback NativeFunction;
// ============================================================================
// [Forward Declarations]
// ============================================================================
// These are needed to make things a bit simpler and minimize the number of
// functions that have to be forward-declared.
namespace Internal {
// Provided after `Context`. This is just a convenience function that
// allows to get V8's `v8::Isolate` from `njs::Context` before it's defined.
static NJS_INLINE v8::Isolate* v8IsolateOfContext(Context& ctx) noexcept;
// Provided after `Value`. These are just a convenience functions that allow
// to get the V8' `v8::Local<v8::Value>` from `njs::Value` before it's defined.
static NJS_INLINE v8::Local<v8::Value>& v8HandleOfValue(Value& value) noexcept;
static NJS_INLINE const v8::Local<v8::Value>& v8HandleOfValue(const Value& value) noexcept;
} // {Internal}
// ============================================================================
// [njs::ResultOf]
// ============================================================================
// V8 specializations of `njs::resultOf<>`.
template<typename T>
NJS_INLINE Result resultOf(const v8::Local<T>& in) noexcept {
return in.IsEmpty() ? Globals::kResultInvalidHandle : Globals::kResultOk;
}
template<typename T>
NJS_INLINE Result resultOf(const v8::MaybeLocal<T>& in) noexcept {
return in.IsEmpty() ? Globals::kResultInvalidHandle : Globals::kResultOk;
}
template<typename T>
NJS_INLINE Result resultOf(const v8::Persistent<T>& in) noexcept {
return in.IsEmpty() ? Globals::kResultInvalidHandle : Globals::kResultOk;
}
template<typename T>
NJS_INLINE Result resultOf(const v8::Global<T>& in) noexcept {
return in.IsEmpty() ? Globals::kResultInvalidHandle : Globals::kResultOk;
}
template<typename T>
NJS_INLINE Result resultOf(const v8::Eternal<T>& in) noexcept {
return in.IsEmpty() ? Globals::kResultInvalidHandle : Globals::kResultOk;
}
template<>
NJS_INLINE Result resultOf(const Value& in) noexcept {
return resultOf(Internal::v8HandleOfValue(in));
}
// ============================================================================
// [njs::Internal::V8 Helpers]
// ============================================================================
namespace Internal {
static NJS_INLINE uintptr_t nativeTagFromObjectTag(uint32_t objectTag) noexcept {
if (sizeof(uintptr_t) > sizeof(uint32_t))
return (uintptr_t(objectTag) << 34) | uintptr_t(0x00000002u);
else
return (uintptr_t(objectTag) << 2) | uintptr_t(0x00000002u);
}
static NJS_INLINE uint32_t objectTagFromNativeTag(uintptr_t nativeTag) noexcept {
if (sizeof(uintptr_t) > sizeof(uint32_t))
return uint32_t(nativeTag >> 34);
else
return uint32_t(nativeTag >> 2);
}
} // {Internal}
// ============================================================================
// [njs::Internal::V8 Helpers]
// ============================================================================
namespace Internal {
// V8 specific destroy callback.
typedef void (*V8WrapDestroyCallback)(const v8::WeakCallbackInfo<void>& data);
// Helper to convert a V8's `MaybeLocal<Type>` to V8's `Local<Type>`.
//
// NOTE: This performs an unchecked operation. Converting an invalid handle will
// keep the handle invalid without triggering assertion failure. The purpose is to
// keep things simple and to check for invalid handles instead of introduction yet
// another handle type in NJS.
template<typename Type>
static NJS_INLINE const v8::Local<Type>& v8LocalFromMaybe(const v8::MaybeLocal<Type>& in) noexcept {
// Implements the following pattern:
//
// v8::Local<Type> out;
// in.ToLocal(&out);
// return out;
//
// However, this produces a warning about unused return value, which is
// useless in our case as we always check whether the handle is valid.
return reinterpret_cast<const v8::Local<Type>&>(in);
}
// Helper that creates a new string based on `StrRef` type. It can create
// string for all input types that match `Globals::kTraitIdStrRef`. Each
// specialization uses a different V8 constructor. The `type` argument
// matches V8's `NewStringType` and can be used to create internalized strings.
template<typename StrRef>
NJS_INLINE v8::Local<v8::Value> v8NewString(Context& ctx, const StrRef& str, v8::NewStringType type) noexcept = delete;
template<>
NJS_INLINE v8::Local<v8::Value> v8NewString(Context& ctx, const Latin1Ref& str, v8::NewStringType type) noexcept {
if (str.size() > Globals::kMaxStringSize)
return v8::Local<v8::Value>();
return v8LocalFromMaybe<v8::String>(
v8::String::NewFromOneByte(
v8IsolateOfContext(ctx),
reinterpret_cast<const uint8_t*>(str.data()), type, static_cast<int>(str.size())));
}
template<>
NJS_INLINE v8::Local<v8::Value> v8NewString(Context& ctx, const Utf8Ref& str, v8::NewStringType type) noexcept {
if (str.size() > Globals::kMaxStringSize)
return v8::Local<v8::Value>();
return v8LocalFromMaybe<v8::String>(
v8::String::NewFromUtf8(
v8IsolateOfContext(ctx),
str.data(), type, static_cast<int>(str.size())));
}
template<>
NJS_INLINE v8::Local<v8::Value> v8NewString(Context& ctx, const Utf16Ref& str, v8::NewStringType type) noexcept {
if (str.size() > Globals::kMaxStringSize)
return v8::Local<v8::Value>();
return v8LocalFromMaybe<v8::String>(
v8::String::NewFromTwoByte(
v8IsolateOfContext(ctx),
str.data(), type, static_cast<int>(str.size())));
}
// Conversion from `T` to V8's `Local<Value>`. Conversions are only possible
// between known types (basically all types defined by NJS's type-traits) and
// V8 handles. These won't automatically convert from one type to another.
// In addition, it's very important to check whether the input value can be
// safely converted to the output type. For example int64_t to double conversion
// is no safe and must be checked, whereas int32_t to double is always safe.
template<typename T, int Id>
struct V8ConvertImpl {};
template<typename T>
struct V8ConvertImpl<T, Globals::kTraitIdBool> {
static NJS_INLINE Result pack(Context& ctx, const T& in, v8::Local<v8::Value>& out) noexcept {
out = v8::Boolean::New(v8IsolateOfContext(ctx), in);
return Globals::kResultOk;
}
static NJS_INLINE Result unpack(Context& ctx, const v8::Local<v8::Value>& in, T& out) noexcept {
if (!in->IsBoolean())
return Globals::kResultInvalidValue;
out = v8::Boolean::Cast(*in)->Value();
return Globals::kResultOk;
}
};
template<typename T>
struct V8ConvertImpl<T, Globals::kTraitIdSafeInt> {
static NJS_INLINE Result pack(Context& ctx, const T& in, v8::Local<v8::Value>& out) noexcept {
out = v8::Integer::New(v8IsolateOfContext(ctx), in);
return !out.IsEmpty() ? Globals::kResultOk : Globals::kResultBypass;
}
static NJS_INLINE Result unpack(Context& ctx, const v8::Local<v8::Value>& in, T& out) noexcept {
if (!in->IsInt32())
return Globals::kResultInvalidValue;
int32_t value = v8::Int32::Cast(*in)->Value();
return IntUtils::intCast(value, out);
}
};
template<typename T>
struct V8ConvertImpl<T, Globals::kTraitIdSafeUint> {
static NJS_INLINE Result pack(Context& ctx, const T& in, v8::Local<v8::Value>& out) noexcept {
out = v8::Integer::New(v8IsolateOfContext(ctx), in);
return !out.IsEmpty() ? Globals::kResultOk : Globals::kResultBypass;
}
static NJS_INLINE Result unpack(Context& ctx, const v8::Local<v8::Value>& in, T& out) noexcept {
if (!in->IsUint32())
return Globals::kResultInvalidValue;
uint32_t value = v8::Uint32::Cast(*in)->Value();
return IntUtils::intCast(value, out);
}
};
template<typename T>
struct V8ConvertImpl<T, Globals::kTraitIdUnsafeInt> {
static NJS_INLINE Result pack(Context& ctx, const T& in, v8::Local<v8::Value>& out) noexcept {
// Fast-case: Most of the time if we hit packing int64_t to JS value it's
// because of `size_t` and similar types. These types will hardly contain
// value that is only representable as `int64_t` so we prefer this path
// that creates a JavaScript integer, which can be then optimized by V8.
if (in >= static_cast<T>(std::numeric_limits<int32_t>::lowest()) &&
in <= static_cast<T>(std::numeric_limits<int32_t>::max())) {
out = v8::Integer::New(v8IsolateOfContext(ctx), static_cast<int32_t>(in));
}
else {
if (!IntUtils::isSafeInt<T>(in))
return Globals::kResultUnsafeInt64Conversion;
out = v8::Number::New(v8IsolateOfContext(ctx), static_cast<double>(in));
}
return !out.IsEmpty() ? Globals::kResultOk : Globals::kResultBypass;
}
static NJS_INLINE Result unpack(Context& ctx, const v8::Local<v8::Value>& in, T& out) noexcept {
if (!in->IsNumber())
return Globals::kResultInvalidValue;
else
return IntUtils::doubleToInt64(v8::Number::Cast(*in)->Value(), out);
}
};
template<typename T>
struct V8ConvertImpl<T, Globals::kTraitIdUnsafeUint> {
static NJS_INLINE Result pack(Context& ctx, const T& in, v8::Local<v8::Value>& out) noexcept {
// The same trick as in kTraitIdUnsafeInt.
if (in <= static_cast<T>(TypeTraits<uint32_t>::maxValue())) {
out = v8::Integer::NewFromUnsigned(v8IsolateOfContext(ctx), static_cast<uint32_t>(in));
}
else {
if (!IntUtils::isSafeInt<T>(in))
return Globals::kResultUnsafeInt64Conversion;
out = v8::Number::New(v8IsolateOfContext(ctx), static_cast<double>(in));
}
return !out.IsEmpty() ? Globals::kResultOk : Globals::kResultBypass;
}
static NJS_INLINE Result unpack(Context& ctx, const v8::Local<v8::Value>& in, T& out) noexcept {
if (!in->IsNumber())
return Globals::kResultInvalidValue;
else
return IntUtils::doubleToUint64(v8::Number::Cast(*in)->Value(), out);
}
};
template<typename T>
struct V8ConvertImpl<T, Globals::kTraitIdFloat> {
static NJS_INLINE Result pack(Context& ctx, const T& in, v8::Local<v8::Value>& out) noexcept {
out = v8::Number::New(v8IsolateOfContext(ctx), static_cast<double>(in));
return Globals::kResultOk;
}
static NJS_INLINE Result unpack(Context& ctx, const v8::Local<v8::Value>& in, T& out) noexcept {
if (!in->IsNumber())
return Globals::kResultInvalidValue;
out = static_cast<T>(v8::Number::Cast(*in)->Value());
return Globals::kResultOk;
}
};
template<typename T>
struct V8ConvertImpl<T, Globals::kTraitIdDouble> {
static NJS_INLINE Result pack(Context& ctx, const T& in, v8::Local<v8::Value>& out) noexcept {
out = v8::Number::New(v8IsolateOfContext(ctx), in);
return Globals::kResultOk;
}
static NJS_INLINE Result unpack(Context& ctx, const v8::Local<v8::Value>& in, T& out) noexcept {
if (!in->IsNumber())
return Globals::kResultInvalidValue;
out = v8::Number::Cast(*in)->Value();
return Globals::kResultOk;
}
};
template<typename T, typename Concept, unsigned int ConceptType>
struct V8ConvertWithConceptImpl {
};
template<typename T, typename Concept>
struct V8ConvertWithConceptImpl<T, Concept, Globals::kConceptSerializer> {
static NJS_INLINE Result pack(Context& ctx, const T& in, Value& out, const Concept& concept) noexcept {
return concept.serialize(ctx, in, out);
}
static NJS_INLINE Result unpack(Context& ctx, const Value& in, T& out, const Concept& concept) noexcept {
return concept.deserialize(ctx, in, out);
}
};
template<typename T, typename Concept>
struct V8ConvertWithConceptImpl<T, Concept, Globals::kConceptValidator> {
static NJS_INLINE Result pack(Context& ctx, const T& in, Value& out, const Concept& concept) noexcept {
NJS_CHECK(concept.validate(in));
return V8ConvertImpl<T, TypeTraits<T>::kTraitId>::pack(ctx, in, out);
}
static NJS_INLINE Result unpack(Context& ctx, const Value& in, T& out, const Concept& concept) noexcept {
NJS_CHECK(V8ConvertImpl<T, TypeTraits<T>::kTraitId>::unpack(ctx, v8HandleOfValue(in), out));
return concept.validate(out);
}
};
// Helpers to unpack a primitive value of type `T` from V8's `Value` handle. All
// specializations MUST BE forward-declared here.
template<typename T>
NJS_INLINE Result v8UnpackValue(Context& ctx, const v8::Local<v8::Value>& in, T& out) noexcept {
return V8ConvertImpl<T, TypeTraits<T>::kTraitId>::unpack(ctx, in, out);
}
// Handle to handle (no conversion).
template<>
NJS_INLINE Result v8UnpackValue(Context& ctx, const v8::Local<v8::Value>& in, Value& out) noexcept {
v8HandleOfValue(out) = in;
return Globals::kResultOk;
}
// Handle to handle (no conversion).
template<>
NJS_INLINE Result v8UnpackValue(Context& ctx, const v8::Local<v8::Value>& in, v8::Local<v8::Value>& out) noexcept {
out = in;
return Globals::kResultOk;
}
template<typename T, typename Concept>
NJS_INLINE Result v8UnpackWithConcept(Context& ctx, const Value& in, T& out, const Concept& concept) noexcept {
return V8ConvertWithConceptImpl<T, Concept, Concept::kConceptType>::unpack(ctx, in, out, concept);
}
template<typename T>
struct V8ReturnImpl {
static NJS_INLINE Result set(Context& ctx, v8::ReturnValue<v8::Value>& rv, const T& value) noexcept {
v8::Local<v8::Value> intermediate;
NJS_CHECK(V8ConvertImpl<T, TypeTraits<T>::kTraitId>::pack(ctx, value, intermediate));
rv.Set(intermediate);
return Globals::kResultOk;
}
};
template<>
struct V8ReturnImpl< v8::Local<v8::Value> > {
static NJS_INLINE Result set(Context& ctx, v8::ReturnValue<v8::Value>& rv, const v8::Local<v8::Value>& value) noexcept {
rv.Set(value);
return Globals::kResultOk;
}
};
template<>
struct V8ReturnImpl<Value> {
static NJS_INLINE Result set(Context& ctx, v8::ReturnValue<v8::Value>& rv, const Value& value) noexcept {
rv.Set(v8HandleOfValue(value));
return Globals::kResultOk;
}
};
template<>
struct V8ReturnImpl<NullType> {
static NJS_INLINE Result set(Context& ctx, v8::ReturnValue<v8::Value>& rv, const NullType&) noexcept {
rv.SetNull();
return Globals::kResultOk;
}
};
template<>
struct V8ReturnImpl<UndefinedType> {
static NJS_INLINE Result set(Context& ctx, v8::ReturnValue<v8::Value>& rv, const UndefinedType&) noexcept {
rv.SetUndefined();
return Globals::kResultOk;
}
};
template<typename T>
NJS_INLINE Result v8Return(Context& ctx, v8::ReturnValue<v8::Value>& rv, const T& value) noexcept {
return V8ReturnImpl<T>::set(ctx, rv, value);
}
template<typename T, typename Concept>
NJS_INLINE Result v8ReturnWithConcept(Context& ctx, v8::ReturnValue<v8::Value>& rv, const T& value, const Concept& concept) noexcept;
template<typename NativeT>
NJS_INLINE Result v8WrapNative(Context& ctx, v8::Local<v8::Object> obj, NativeT* self, uint32_t objectTag) noexcept;
template<typename NativeT>
NJS_INLINE NativeT* v8UnwrapNativeUnsafe(Context& ctx, v8::Local<v8::Object> obj) noexcept;
template<typename NativeT>
NJS_INLINE Result v8UnwrapNativeChecked(Context& ctx, NativeT** pOut, v8::Local<v8::Value> obj, uint32_t objectTag) noexcept;
} // {Internal}
// ============================================================================
// [njs::Runtime]
// ============================================================================
class Runtime {
public:
NJS_INLINE Runtime() noexcept : _isolate(nullptr) {}
NJS_INLINE Runtime(const Runtime& other) noexcept : _isolate(other._isolate) {}
explicit NJS_INLINE Runtime(v8::Isolate* isolate) noexcept : _isolate(isolate) {}
// --------------------------------------------------------------------------
// [V8-Specific]
// --------------------------------------------------------------------------
NJS_INLINE v8::Isolate* v8Isolate() const noexcept { return _isolate; }
// --------------------------------------------------------------------------
// [Members]
// --------------------------------------------------------------------------
v8::Isolate* _isolate;
};
// ============================================================================
// [njs::Value]
// ============================================================================
class Value {
public:
typedef v8::Local<v8::Value> HandleType;
NJS_INLINE Value() noexcept : _handle() {}
NJS_INLINE Value(const Value& other) noexcept : _handle(other._handle) {}
template<typename T>
explicit NJS_INLINE Value(const v8::Local<T>& handle) noexcept : _handle(handle) {}
// --------------------------------------------------------------------------
// [Assignment]
// --------------------------------------------------------------------------
NJS_INLINE Value& operator=(const Value& other) noexcept {
_handle = other._handle;
return *this;
}
template<typename T>
NJS_INLINE Value& operator=(const v8::Local<T>& handle) noexcept {
_handle = handle;
return *this;
}
// --------------------------------------------------------------------------
// [V8-Specific]
// --------------------------------------------------------------------------
// Get the V8's handle.
NJS_INLINE HandleType& v8Handle() noexcept { return _handle; }
NJS_INLINE const HandleType& v8Handle() const noexcept { return _handle; }
template<typename T>
NJS_INLINE v8::Local<T> v8HandleAs() const noexcept { return v8::Local<T>::Cast(_handle); }
template<typename T = v8::Value>
NJS_INLINE T* v8Value() const noexcept { return T::Cast(*_handle); }
// --------------------------------------------------------------------------
// [Handle]
// --------------------------------------------------------------------------
// Get whether the handle is valid and can be used. If the handle is invalid
// then no member function can be called on it. There are asserts that check
// this in debug mode.
NJS_INLINE bool isValid() const noexcept { return !_handle.IsEmpty(); }
// Reset the handle.
//
// NOTE: `isValid()` will return `false` after `reset()` is called.
NJS_INLINE void reset() noexcept { _handle.Clear(); }
// --------------------------------------------------------------------------
// [Type System]
// --------------------------------------------------------------------------
NJS_INLINE bool isUndefined() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsUndefined();
}
NJS_INLINE bool isNull() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsNull();
}
NJS_INLINE bool isBool() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsBoolean();
}
NJS_INLINE bool isTrue() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsTrue();
}
NJS_INLINE bool isFalse() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsFalse();
}
NJS_INLINE bool isInt32() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsInt32();
}
NJS_INLINE bool isUint32() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsUint32();
}
NJS_INLINE bool isNumber() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsNumber();
}
NJS_INLINE bool isString() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsString();
}
NJS_INLINE bool isSymbol() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsSymbol();
}
NJS_INLINE bool isArray() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsArray();
}
NJS_INLINE bool isObject() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsObject();
}
NJS_INLINE bool isDate() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsDate();
}
NJS_INLINE bool isRegExp() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsRegExp();
}
NJS_INLINE bool isFunction() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsFunction();
}
NJS_INLINE bool isExternal() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsExternal();
}
NJS_INLINE bool isPromise() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsPromise();
}
NJS_INLINE bool isArrayBuffer() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsArrayBuffer();
}
NJS_INLINE bool isArrayBufferView() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsArrayBufferView();
}
NJS_INLINE bool isDataView() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsDataView();
}
NJS_INLINE bool isTypedArray() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsTypedArray();
}
NJS_INLINE bool isInt8Array() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsInt8Array();
}
NJS_INLINE bool isInt16Array() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsInt16Array();
}
NJS_INLINE bool isInt32Array() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsInt32Array();
}
NJS_INLINE bool isUint8Array() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsUint8Array();
}
NJS_INLINE bool isUint8ClampedArray() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsUint8ClampedArray();
}
NJS_INLINE bool isUint16Array() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsUint16Array();
}
NJS_INLINE bool isUint32Array() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsUint32Array();
}
NJS_INLINE bool isFloat32Array() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsFloat32Array();
}
NJS_INLINE bool isFloat64Array() const noexcept {
NJS_ASSERT(isValid());
return _handle->IsFloat64Array();
}
// --------------------------------------------------------------------------
// [Members]
// --------------------------------------------------------------------------
HandleType _handle;
};
namespace Internal {
static NJS_INLINE v8::Local<v8::Value>& v8HandleOfValue(Value& value) noexcept { return value._handle; }
static NJS_INLINE const v8::Local<v8::Value>& v8HandleOfValue(const Value& value) noexcept { return value._handle; }
} // Internal namsepace
// ============================================================================
// [njs::Persistent]
// ============================================================================
class Persistent {
public:
NJS_INLINE Persistent() noexcept
: _handle() {}
// --------------------------------------------------------------------------
// [V8-Specific]
// --------------------------------------------------------------------------
// Get the V8's handle.
NJS_INLINE v8::Persistent<v8::Value>& v8Handle() noexcept {
return _handle;
}
NJS_INLINE const v8::Persistent<v8::Value>& v8Handle() const noexcept {
return _handle;
}
// Get the V8's `Persistent<T>` handle.
template<typename T>
NJS_INLINE v8::Persistent<T>& v8HandleAs() noexcept {
return reinterpret_cast<v8::Persistent<T>&>(_handle);
}
template<typename T>
NJS_INLINE const v8::Persistent<T>& v8HandleAs() const noexcept {
return reinterpret_cast<const v8::Persistent<T>&>(_handle);
}
/*
template<typename T = v8::Value>
NJS_INLINE T* v8Value() const noexcept {
return T::Cast(*_handle);
}
*/
// --------------------------------------------------------------------------
// [Handle]
// --------------------------------------------------------------------------
// Get whether the handle is valid and can be used. If the handle is invalid
// then no member function can be called on it. There are asserts that check
// this in debug mode.
NJS_INLINE bool isValid() const noexcept { return !_handle.IsEmpty(); }
// Reset the handle to its construction state.
//
// NOTE: `isValid()` returns return `false` after `reset()` is called.
NJS_INLINE void reset() noexcept { _handle.Empty(); }
// --------------------------------------------------------------------------
// [Members]
// --------------------------------------------------------------------------
v8::Persistent<v8::Value> _handle;
};
// ============================================================================
// [njs::Context]
// ============================================================================
class Context {
// No assignment.
NJS_INLINE Context& operator=(const Context& other) noexcept = delete;
public:
NJS_INLINE Context() noexcept {}
NJS_INLINE Context(const Context& other) noexcept
: _runtime(other._runtime),
_context(other._context) {}
explicit NJS_INLINE Context(const Runtime& runtime) noexcept
: _runtime(runtime),
_context(runtime.v8Isolate()->GetCurrentContext()) {}
NJS_INLINE Context(v8::Isolate* isolate, const v8::Local<v8::Context>& context) noexcept
: _runtime(isolate),
_context(context) {}
// --------------------------------------------------------------------------
// [V8-Specific]
// --------------------------------------------------------------------------
NJS_INLINE v8::Isolate* v8Isolate() const noexcept { return _runtime._isolate; }
NJS_INLINE v8::Local<v8::Context>& v8Context() noexcept { return _context; }
NJS_INLINE const v8::Local<v8::Context>& v8Context() const noexcept { return _context; }
// --------------------------------------------------------------------------
// [Runtime]
// --------------------------------------------------------------------------
NJS_INLINE const Runtime& runtime() const noexcept { return _runtime; }
// --------------------------------------------------------------------------
// [Built-Ins]
// --------------------------------------------------------------------------
NJS_INLINE Value undefined() const noexcept { return Value(v8::Undefined(v8Isolate())); }
NJS_INLINE Value null() const noexcept { return Value(v8::Null(v8Isolate())); }
NJS_INLINE Value true_() const noexcept { return Value(v8::True(v8Isolate())); }
NJS_INLINE Value false_() const noexcept { return Value(v8::False(v8Isolate())); }
// --------------------------------------------------------------------------
// [New]
// --------------------------------------------------------------------------
NJS_INLINE Value newBool(bool value) noexcept { return Value(v8::Boolean::New(v8Isolate(), value)); }
NJS_INLINE Value newInt32(int32_t value) noexcept { return Value(v8::Integer::New(v8Isolate(), value)); }
NJS_INLINE Value newUint32(uint32_t value) noexcept { return Value(v8::Integer::New(v8Isolate(), value)); }
NJS_INLINE Value newDouble(double value) noexcept { return Value(v8::Number::New(v8Isolate(), value)); }
NJS_INLINE Value newArray() noexcept { return Value(v8::Array::New(v8Isolate())); }
NJS_INLINE Value newArray(uint32_t size) noexcept { return Value(v8::Array::New(v8Isolate(), int(size))); }
NJS_INLINE Value newObject() noexcept { return Value(v8::Object::New(v8Isolate())); }
NJS_INLINE Value newString() const noexcept { return Value(v8::String::Empty(v8Isolate())); }
template<typename StrRefT>
NJS_INLINE Value newString(const StrRefT& data) noexcept {
return Value(Internal::v8NewString<StrRefT>(*this, data, v8::NewStringType::kNormal));
}
template<typename StrRefT>
NJS_INLINE Value newInternalizedString(const StrRefT& data) noexcept {
return Value(Internal::v8NewString<StrRefT>(*this, data, v8::NewStringType::kInternalized));
}
template<typename T>
NJS_INLINE Value newValue(const T& value) noexcept {
Value result;
Internal::V8ConvertImpl<T, Internal::TypeTraits<T>::kTraitId>::pack(*this, value, result._handle);
return result;
}
NJS_INLINE Value newFunction(NativeFunction nativeFunction, const Value& data) noexcept {
return Value(
Internal::v8LocalFromMaybe<v8::Function>(
v8::Function::New(v8Context(), nativeFunction, data.v8Handle(), 0, v8::ConstructorBehavior::kThrow)));
//v8::Local<v8::FunctionTemplate> fnTemplate = v8::FunctionTemplate::New(
// ctx.v8Isolate(), (v8::FunctionCallback)item.data, data);
//NJS_CHECK(fnTemplate);
//if (name.isValid())
// fnTemplate->SetClassName(name.v8HandleAs<v8::String>());
}
// --------------------------------------------------------------------------
// [Unpacking]
// --------------------------------------------------------------------------
// These don't perform any conversion, the type of the JS value has to match
// the type of the `out` argument. Some types are internally convertible as
// JS doesn't differentiate between integer and floating point types.
template<typename T>
NJS_INLINE Result unpack(const Value& in, T& out) noexcept {
return Internal::v8UnpackValue<T>(*this, in._handle, out);
}
template<typename T, typename Concept>
NJS_INLINE Result unpack(const Value& in, T& out, const Concept& concept) noexcept {
return Internal::v8UnpackWithConcept<T, Concept>(*this, in, out, concept);
}
// --------------------------------------------------------------------------
// [Wrap / Unwrap]
// --------------------------------------------------------------------------
template<typename NativeT>
NJS_INLINE Result wrap(Value obj, NativeT* native) noexcept {
return wrap<NativeT>(obj, native, NativeT::kObjectTag);
}
template<typename NativeT>
NJS_INLINE Result wrap(Value obj, NativeT* native, uint32_t objectTag) noexcept {
NJS_ASSERT(obj.isObject());
return Internal::v8WrapNative<NativeT>(*this, obj.v8HandleAs<v8::Object>(), native, objectTag);
}
template<typename NativeT, typename... ARGS>
NJS_INLINE Result wrapNew(Value obj, ARGS&&... args) noexcept {
NJS_ASSERT(obj.isObject());
NativeT* native = new (std::nothrow) NativeT(std::forward<ARGS>(args)...);
if (!native)
return Globals::kResultOutOfMemory;
return Internal::v8WrapNative<NativeT>(*this, obj.v8HandleAs<v8::Object>(), native, NativeT::kObjectTag);
}
template<typename NativeT>
NJS_INLINE NativeT* unwrapUnsafe(Value obj) noexcept {
NJS_ASSERT(obj.isValid());
NJS_ASSERT(obj.isObject());
return Internal::v8UnwrapNativeUnsafe<NativeT>(*this, obj.v8HandleAs<v8::Object>());
}
template<typename NativeT>
NJS_INLINE Result unwrap(NativeT** pOut, Value obj) noexcept {
return Internal::v8UnwrapNativeChecked(*this, pOut, obj, NativeT::kObjectTag);
}
template<typename NativeT>
NJS_INLINE Result unwrap(NativeT** pOut, Value obj, uint32_t objectTag) noexcept {
return Internal::v8UnwrapNativeChecked(*this, pOut, obj, objectTag);
}
NJS_INLINE bool isWrapped(Value obj, uint32_t objectTag) noexcept {
// This must be checked before.
NJS_ASSERT(obj.isValid());
if (!obj.isObject())
return false;
v8::Local<v8::Object> handle = obj.v8HandleAs<v8::Object>();
return handle->InternalFieldCount() > 1 &&
(uintptr_t)handle->GetAlignedPointerFromInternalField(1) == Internal::nativeTagFromObjectTag(objectTag);
}
template<typename NativeT>
NJS_INLINE bool isWrapped(Value obj) noexcept {
return isWrapped(obj, NativeT::kObjectTag);
}
// --------------------------------------------------------------------------
// [Value]
// --------------------------------------------------------------------------
// IMPORTANT: These can only be called if the value can be casted to such types,
// casting improper type will fail assertion in debug mode and cause apocalypse
// in release mode.
NJS_INLINE bool boolValue(const Value& value) noexcept {
NJS_ASSERT(value.isValid());
NJS_ASSERT(value.isBool());
return value._handle->BooleanValue(v8Isolate());
}
NJS_INLINE int32_t int32Value(const Value& value) const noexcept {
NJS_ASSERT(value.isValid());
NJS_ASSERT(value.isInt32());
v8::Maybe<int32_t> result = value._handle->Int32Value(_context);
return result.FromMaybe(0);
}
NJS_INLINE uint32_t uint32Value(const Value& value) const noexcept {
NJS_ASSERT(value.isValid());
NJS_ASSERT(value.isUint32());
v8::Maybe<uint32_t> result = value._handle->Uint32Value(_context);
return result.FromMaybe(0);
}
NJS_INLINE double doubleValue(const Value& value) const noexcept {
NJS_ASSERT(value.isValid());
NJS_ASSERT(value.isNumber());
v8::Maybe<double> result = value._handle->NumberValue(_context);
return result.FromMaybe(std::numeric_limits<double>::quiet_NaN());
}
// --------------------------------------------------------------------------
// [Language]
// --------------------------------------------------------------------------
NJS_INLINE Maybe<bool> equals(const Value& aAny, const Value& bAny) noexcept {
NJS_ASSERT(aAny.isValid());
NJS_ASSERT(bAny.isValid());
v8::Maybe<bool> result = aAny._handle->Equals(_context, bAny._handle);
return Maybe<bool>(result.IsJust() ? Globals::kResultOk : Globals::kResultBypass, result.FromMaybe(false));
}
NJS_INLINE bool strictEquals(const Value& aAny, const Value& bAny) const noexcept {
NJS_ASSERT(aAny.isValid());
NJS_ASSERT(bAny.isValid());
return aAny._handle->StrictEquals(bAny._handle);
}
NJS_INLINE bool isSameValue(const Value& aAny, const Value& bAny) const noexcept {
NJS_ASSERT(aAny.isValid());
NJS_ASSERT(bAny.isValid());
return aAny._handle->SameValue(bAny._handle);
}
// --------------------------------------------------------------------------
// [String]
// --------------------------------------------------------------------------
NJS_INLINE bool isLatin1(const Value& value) const noexcept {
NJS_ASSERT(value.isValid());
NJS_ASSERT(value.isString());
return value.v8Value<v8::String>()->ContainsOnlyOneByte();
}
NJS_INLINE bool isLatin1Guess(const Value& value) const noexcept {
NJS_ASSERT(value.isValid());
NJS_ASSERT(value.isString());
return value.v8Value<v8::String>()->IsOneByte();
}
// Length of the string if represented as UTF-16 or LATIN-1 (if representable).
NJS_INLINE size_t stringLength(const Value& value) const noexcept {
NJS_ASSERT(value.isValid());
NJS_ASSERT(value.isString());
return value.v8Value<v8::String>()->Length();
}
// Length of the string if represented as UTF-8.
NJS_INLINE size_t utf8Length(const Value& value) const noexcept {
NJS_ASSERT(value.isValid());
NJS_ASSERT(value.isString());
return value.v8Value<v8::String>()->Utf8Length(v8Isolate());
}
NJS_INLINE int readLatin1(const Value& value, char* out, int size = -1) const noexcept {
NJS_ASSERT(value.isValid());
NJS_ASSERT(value.isString());
return value.v8Value<v8::String>()->WriteOneByte(v8Isolate(), reinterpret_cast<uint8_t*>(out), 0, size, v8::String::NO_NULL_TERMINATION);
}
NJS_INLINE int readUtf8(const Value& value, char* out, int size = -1) const noexcept {