forked from microsoft/hermes-windows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Operations.cpp
1863 lines (1687 loc) · 64 KB
/
Operations.cpp
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
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "hermes/VM/Operations.h"
#include "hermes/Support/Conversions.h"
#include "hermes/Support/OSCompat.h"
#include "hermes/VM/Callable.h"
#include "hermes/VM/Casting.h"
#include "hermes/VM/JSArray.h"
#include "hermes/VM/JSCallableProxy.h"
#include "hermes/VM/JSError.h"
#include "hermes/VM/JSObject.h"
#include "hermes/VM/JSRegExp.h"
#include "hermes/VM/PrimitiveBox.h"
#include "hermes/VM/PropertyAccessor.h"
#include "hermes/VM/Runtime.h"
#include "hermes/VM/StringBuilder.h"
#include "hermes/VM/StringPrimitive.h"
#include "hermes/VM/StringView.h"
#include "dtoa/dtoa.h"
#include "llvh/ADT/SmallString.h"
#include <cfloat>
#include <cmath>
namespace hermes {
namespace vm {
CallResult<Handle<SymbolID>> stringToSymbolID(
Runtime *runtime,
PseudoHandle<StringPrimitive> strPrim) {
// Unique the string.
return runtime->getIdentifierTable().getSymbolHandleFromPrimitive(
runtime, std::move(strPrim));
}
CallResult<Handle<SymbolID>> valueToSymbolID(
Runtime *runtime,
Handle<> nameValHnd) {
if (nameValHnd->isSymbol()) {
return Handle<SymbolID>::vmcast(nameValHnd);
}
// Convert the value to a string.
auto res = toString_RJS(runtime, nameValHnd);
if (res == ExecutionStatus::EXCEPTION)
return ExecutionStatus::EXCEPTION;
// Unique the string.
return stringToSymbolID(runtime, std::move(*res));
}
HermesValue typeOf(Runtime *runtime, Handle<> valueHandle) {
switch (valueHandle->getTag()) {
case UndefinedNullTag:
return HermesValue::encodeStringValue(runtime->getPredefinedString(
valueHandle->isUndefined() ? Predefined::undefined
: Predefined::object));
case StrTag:
return HermesValue::encodeStringValue(
runtime->getPredefinedString(Predefined::string));
case BoolTag:
return HermesValue::encodeStringValue(
runtime->getPredefinedString(Predefined::boolean));
case SymbolTag:
return HermesValue::encodeStringValue(
runtime->getPredefinedString(Predefined::symbol));
case ObjectTag:
if (vmisa<Callable>(*valueHandle))
return HermesValue::encodeStringValue(
runtime->getPredefinedString(Predefined::function));
return HermesValue::encodeStringValue(
runtime->getPredefinedString(Predefined::object));
default:
assert(valueHandle->isNumber() && "Invalid type.");
return HermesValue::encodeStringValue(
runtime->getPredefinedString(Predefined::number));
}
}
OptValue<uint32_t> toArrayIndex(
Runtime *runtime,
Handle<StringPrimitive> strPrim) {
auto view = StringPrimitive::createStringView(runtime, strPrim);
return toArrayIndex(view);
}
OptValue<uint32_t> toArrayIndex(StringView str) {
auto len = str.length();
if (str.isASCII()) {
const char *ptr = str.castToCharPtr();
return hermes::toArrayIndex(ptr, ptr + len);
}
const char16_t *ptr = str.castToChar16Ptr();
return hermes::toArrayIndex(ptr, ptr + len);
}
bool isSameValue(HermesValue x, HermesValue y) {
if (x.getTag() != y.getTag()) {
// If the tags are different, they must be different.
return false;
}
assert(
!x.isEmpty() && !x.isNativeValue() &&
"Empty and Native Value cannot be compared");
// Strings are the only type that requires deep comparison.
if (x.isString()) {
// For strings, we compare each character in sequence.
return x.getString()->equals(y.getString());
}
// Otherwise they are identical if the raw bits are the same.
return x.getRaw() == y.getRaw();
}
bool isSameValueZero(HermesValue x, HermesValue y) {
if (x.isNumber() && y.isNumber() && x.getNumber() == y.getNumber()) {
// Takes care of +0 == -0.
return true;
}
return isSameValue(x, y);
}
bool isPrimitive(HermesValue val) {
assert(val.getTag() != EmptyInvalidTag && "empty value encountered");
assert(val.getTag() != NativeValueTag && "native value encountered");
return !val.isObject();
}
CallResult<HermesValue> ordinaryToPrimitive(
Handle<JSObject> selfHandle,
Runtime *runtime,
PreferredType preferredType) {
GCScope gcScope{runtime};
assert(
preferredType != PreferredType::NONE &&
"OrdinaryToPrimitive requires a type hint");
for (int i = 0; i < 2; ++i) {
if (preferredType == PreferredType::STRING) {
auto propRes = JSObject::getNamed_RJS(
selfHandle, runtime, Predefined::getSymbolID(Predefined::toString));
if (propRes == ExecutionStatus::EXCEPTION)
return ExecutionStatus::EXCEPTION;
if (auto funcHandle = Handle<Callable>::dyn_vmcast(
runtime->makeHandle(std::move(*propRes)))) {
auto callRes =
funcHandle->executeCall0(funcHandle, runtime, selfHandle);
if (callRes == ExecutionStatus::EXCEPTION)
return ExecutionStatus::EXCEPTION;
if (isPrimitive(callRes->get()))
return callRes.toCallResultHermesValue();
}
// This method failed. Try the other one.
preferredType = PreferredType::NUMBER;
} else {
auto propRes = JSObject::getNamed_RJS(
selfHandle, runtime, Predefined::getSymbolID(Predefined::valueOf));
if (propRes == ExecutionStatus::EXCEPTION)
return ExecutionStatus::EXCEPTION;
if (auto funcHandle = Handle<Callable>::dyn_vmcast(
runtime->makeHandle(std::move(*propRes)))) {
auto callRes =
funcHandle->executeCall0(funcHandle, runtime, selfHandle);
if (callRes == ExecutionStatus::EXCEPTION)
return ExecutionStatus::EXCEPTION;
if (isPrimitive(callRes->get()))
return callRes.toCallResultHermesValue();
}
// This method failed. Try the other one.
preferredType = PreferredType::STRING;
}
}
// Nothing succeeded, time to give up.
return runtime->raiseTypeError("Cannot determine default value of object");
}
/// ES5.1 9.1
CallResult<HermesValue>
toPrimitive_RJS(Runtime *runtime, Handle<> valueHandle, PreferredType hint) {
assert(
valueHandle->getTag() != EmptyInvalidTag && "empty value is not allowed");
assert(
valueHandle->getTag() != NativeValueTag && "native value is not allowed");
if (valueHandle->getTag() != ObjectTag)
return *valueHandle;
// 4. Let exoticToPrim be GetMethod(input, @@toPrimitive).
auto exoticToPrim = getMethod(
runtime,
valueHandle,
runtime->makeHandle(
Predefined::getSymbolID(Predefined::SymbolToPrimitive)));
if (LLVM_UNLIKELY(exoticToPrim == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
// 6. If exoticToPrim is not undefined, then
if (vmisa<Callable>(exoticToPrim->getHermesValue())) {
auto callable = runtime->makeHandle<Callable>(
dyn_vmcast<Callable>(exoticToPrim->getHermesValue()));
CallResult<PseudoHandle<>> resultRes = Callable::executeCall1(
callable,
runtime,
valueHandle,
HermesValue::encodeStringValue(runtime->getPredefinedString(
hint == PreferredType::NONE ? Predefined::defaultStr
: hint == PreferredType::STRING ? Predefined::string
: Predefined::number)));
if (LLVM_UNLIKELY(resultRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
PseudoHandle<> result = std::move(*resultRes);
if (!result->isObject()) {
return result.getHermesValue();
}
return runtime->raiseTypeError(
"Symbol.toPrimitive function must return a primitive");
}
// 7. If hint is "default", let hint be "number".
// 8. Return OrdinaryToPrimitive(input,hint).
return ordinaryToPrimitive(
Handle<JSObject>::vmcast(valueHandle),
runtime,
hint == PreferredType::NONE ? PreferredType::NUMBER : hint);
}
bool toBoolean(HermesValue value) {
switch (value.getTag()) {
case EmptyInvalidTag:
llvm_unreachable("empty value");
case NativeValueTag:
llvm_unreachable("native value");
case UndefinedNullTag:
return false;
case BoolTag:
return value.getBool();
case SymbolTag:
case ObjectTag:
return true;
case StrTag:
return value.getString()->getStringLength() != 0;
default: {
auto m = value.getNumber();
return !(m == 0 || std::isnan(m));
}
}
}
/// ES5.1 9.8.1
static CallResult<PseudoHandle<StringPrimitive>> numberToString(
Runtime *runtime,
double m) LLVM_NO_SANITIZE("float-cast-overflow");
static CallResult<PseudoHandle<StringPrimitive>> numberToString(
Runtime *runtime,
double m) {
char buf8[hermes::NUMBER_TO_STRING_BUF_SIZE];
// Optimization: Fast-case for positive integers < 2^31
int32_t n = static_cast<int32_t>(m);
if (m == static_cast<double>(n) && n > 0) {
// Write base 10 digits in reverse from end of buf8.
char *p = buf8 + sizeof(buf8);
do {
*--p = '0' + (n % 10);
n /= 10;
} while (n);
size_t len = buf8 + sizeof(buf8) - p;
// Temporarily stop the propagation of removing.
auto result = StringPrimitive::create(runtime, ASCIIRef(p, len));
if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
return createPseudoHandle(vmcast<StringPrimitive>(*result));
}
auto getPredefined = [runtime](Predefined::Str predefinedID) {
return createPseudoHandle(runtime->getPredefinedString(predefinedID));
};
if (std::isnan(m))
return getPredefined(Predefined::NaN);
if (m == 0)
return getPredefined(Predefined::zero);
if (m == std::numeric_limits<double>::infinity())
return getPredefined(Predefined::Infinity);
if (m == -std::numeric_limits<double>::infinity())
return getPredefined(Predefined::NegativeInfinity);
// After special cases, run the generic routine to convert.
size_t len = hermes::numberToString(m, buf8, sizeof(buf8));
auto result = StringPrimitive::create(runtime, ASCIIRef(buf8, len));
if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
return createPseudoHandle(vmcast<StringPrimitive>(*result));
}
CallResult<PseudoHandle<StringPrimitive>> toString_RJS(
Runtime *runtime,
Handle<> valueHandle) {
HermesValue value = valueHandle.get();
StringPrimitive *result;
switch (value.getTag()) {
case EmptyInvalidTag:
llvm_unreachable("empty value");
case NativeValueTag:
llvm_unreachable("native value");
case StrTag:
result = vmcast<StringPrimitive>(value);
break;
case UndefinedNullTag:
result = runtime->getPredefinedString(
value.isUndefined() ? Predefined::undefined : Predefined::null);
break;
case BoolTag:
result = value.getBool()
? runtime->getPredefinedString(Predefined::trueStr)
: runtime->getPredefinedString(Predefined::falseStr);
break;
case ObjectTag: {
auto res = toPrimitive_RJS(runtime, valueHandle, PreferredType::STRING);
if (res == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
return toString_RJS(runtime, runtime->makeHandle(res.getValue()));
}
case SymbolTag:
return runtime->raiseTypeError("Cannot convert Symbol to string");
default:
return numberToString(runtime, value.getNumber());
}
return createPseudoHandle(result);
}
double parseIntWithRadix(const StringView str, int radix) {
auto res =
hermes::parseIntWithRadix</* AllowNumericSeparator */ false>(str, radix);
return res ? res.getValue() : std::numeric_limits<double>::quiet_NaN();
}
/// ES5.1 9.3.1
static inline double stringToNumber(
Runtime *runtime,
Handle<StringPrimitive> strPrim) {
auto &idTable = runtime->getIdentifierTable();
// Fast check for special values (no extraneous whitespace).
if (runtime->symbolEqualsToStringPrim(
Predefined::getSymbolID(Predefined::Infinity), *strPrim)) {
return std::numeric_limits<double>::infinity();
}
if (runtime->symbolEqualsToStringPrim(
Predefined::getSymbolID(Predefined::PositiveInfinity), *strPrim)) {
return std::numeric_limits<double>::infinity();
}
if (runtime->symbolEqualsToStringPrim(
Predefined::getSymbolID(Predefined::NegativeInfinity), *strPrim)) {
}
if (runtime->symbolEqualsToStringPrim(
Predefined::getSymbolID(Predefined::NaN), *strPrim)) {
return std::numeric_limits<double>::quiet_NaN();
}
// Trim string to the interval [begin, end).
auto orig = StringPrimitive::createStringView(runtime, strPrim);
auto begin = orig.begin();
auto end = orig.end();
// Move begin and end to ignore whitespace.
while (begin != end &&
(isWhiteSpaceChar(*begin) || isLineTerminatorChar(*begin))) {
++begin;
}
while (begin != end &&
(isWhiteSpaceChar(*(end - 1)) || isLineTerminatorChar(*(end - 1)))) {
--end;
}
// Early return for empty strings (strings only containing whitespace).
if (begin == end) {
return 0;
}
// Trim the string.
StringView str16 = orig.slice(begin, end);
// Slow check for special values.
// This should only run if user created a string with extra whitespace,
// since normal uses would get caught by the initial check.
if (LLVM_UNLIKELY(str16.equals(idTable.getStringView(
runtime, Predefined::getSymbolID(Predefined::Infinity))))) {
return std::numeric_limits<double>::infinity();
}
if (LLVM_UNLIKELY(str16.equals(idTable.getStringView(
runtime, Predefined::getSymbolID(Predefined::PositiveInfinity))))) {
return std::numeric_limits<double>::infinity();
}
if (LLVM_UNLIKELY(str16.equals(idTable.getStringView(
runtime, Predefined::getSymbolID(Predefined::NegativeInfinity))))) {
return -std::numeric_limits<double>::infinity();
}
if (LLVM_UNLIKELY(str16.equals(idTable.getStringView(
runtime, Predefined::getSymbolID(Predefined::NaN))))) {
return std::numeric_limits<double>::quiet_NaN();
}
auto len = str16.length();
// Parse hex codes, since dtoa doesn't do it.
// FIXME: May be inaccurate for some hex values.
// We need to check other sources first.
if (len > 2) {
if (str16[0] == u'0' && letterToLower(str16[1]) == u'x') {
return parseIntWithRadix(str16.slice(2), 16);
}
if (str16[0] == u'0' && letterToLower(str16[1]) == u'o') {
return parseIntWithRadix(str16.slice(2), 8);
}
if (str16[0] == u'0' && letterToLower(str16[1]) == u'b') {
return parseIntWithRadix(str16.slice(2), 2);
}
}
// Finally, copy 16 bit chars into 8 bit chars and call dtoa.
llvh::SmallVector<char, 32> str8(len + 1);
uint32_t i = 0;
for (auto c16 : str16) {
// Check to ensure we only have valid number characters now.
if ((u'0' <= c16 && c16 <= u'9') || c16 == u'.' ||
letterToLower(c16) == u'e' || c16 == u'+' || c16 == u'-') {
str8[i] = static_cast<char>(c16);
} else {
return std::numeric_limits<double>::quiet_NaN();
}
++i;
}
str8[len] = '\0';
char *endPtr;
double result = ::hermes_g_strtod(str8.data(), &endPtr);
if (endPtr == str8.data() + len) {
return result;
}
// If everything failed, return NaN.
return std::numeric_limits<double>::quiet_NaN();
}
CallResult<HermesValue> toNumber_RJS(Runtime *runtime, Handle<> valueHandle) {
auto value = valueHandle.get();
double result;
switch (value.getTag()) {
case EmptyInvalidTag:
llvm_unreachable("empty value");
case NativeValueTag:
llvm_unreachable("native value");
case ObjectTag: {
auto res = toPrimitive_RJS(runtime, valueHandle, PreferredType::NUMBER);
if (res == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
return toNumber_RJS(runtime, runtime->makeHandle(res.getValue()));
}
case StrTag:
result =
stringToNumber(runtime, Handle<StringPrimitive>::vmcast(valueHandle));
break;
case UndefinedNullTag:
result =
value.isUndefined() ? std::numeric_limits<double>::quiet_NaN() : +0.0;
break;
case BoolTag:
result = value.getBool();
break;
case SymbolTag:
return runtime->raiseTypeError("Cannot convert Symbol to number");
default:
// Already have a number, just return it.
return value;
}
return HermesValue::encodeDoubleValue(result);
}
CallResult<HermesValue> toLength(Runtime *runtime, Handle<> valueHandle) {
constexpr double maxLength = 9007199254740991.0; // 2**53 - 1
auto res = toInteger(runtime, valueHandle);
if (res == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto len = res->getNumber();
if (len <= 0) {
len = 0;
} else if (len > maxLength) {
len = maxLength;
}
return HermesValue::encodeDoubleValue(len);
}
CallResult<uint64_t> toLengthU64(Runtime *runtime, Handle<> valueHandle) {
constexpr double highestIntegralDouble =
((uint64_t)1 << std::numeric_limits<double>::digits) - 1;
auto res = toInteger(runtime, valueHandle);
if (res == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto len = res->getNumber();
if (len <= 0) {
len = 0;
} else if (len > highestIntegralDouble) {
len = highestIntegralDouble;
}
return len;
}
CallResult<HermesValue> toIndex(Runtime *runtime, Handle<> valueHandle) {
auto value = (valueHandle->isUndefined())
? runtime->makeHandle(HermesValue::encodeDoubleValue(0))
: valueHandle;
auto res = toInteger(runtime, value);
if (res == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto integerIndex = res->getNumber();
if (integerIndex < 0) {
return runtime->raiseRangeError("A negative value cannot be an index");
}
auto integerIndexHandle =
runtime->makeHandle(HermesValue::encodeDoubleValue(integerIndex));
res = toLength(runtime, integerIndexHandle);
if (res == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto index = res.getValue();
if (index.getNumber() != integerIndex) {
return runtime->raiseRangeError(
"The value given for the index must be between 0 and 2 ^ 53 - 1");
}
return res;
}
CallResult<HermesValue> toInteger(Runtime *runtime, Handle<> valueHandle) {
auto res = toNumber_RJS(runtime, valueHandle);
if (res == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
double num = res->getNumber();
double result;
if (std::isnan(num)) {
result = 0;
} else {
result = std::trunc(num);
}
return HermesValue::encodeDoubleValue(result);
}
/// Conversion of HermesValues to integers.
template <typename T>
static inline CallResult<HermesValue> toInt(
Runtime *runtime,
Handle<> valueHandle) {
auto res = toNumber_RJS(runtime, valueHandle);
if (res == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
double num = res->getNumber();
T result = static_cast<T>(hermes::truncateToInt32(num));
return HermesValue::encodeNumberValue(result);
}
CallResult<HermesValue> toInt8(Runtime *runtime, Handle<> valueHandle) {
return toInt<int8_t>(runtime, valueHandle);
}
CallResult<HermesValue> toInt16(Runtime *runtime, Handle<> valueHandle) {
return toInt<int16_t>(runtime, valueHandle);
}
CallResult<HermesValue> toInt32_RJS(Runtime *runtime, Handle<> valueHandle) {
return toInt<int32_t>(runtime, valueHandle);
}
CallResult<HermesValue> toUInt8(Runtime *runtime, Handle<> valueHandle) {
return toInt<uint8_t>(runtime, valueHandle);
}
uint8_t toUInt8Clamp(double number) {
// 3. If number is NaN, return +0.
// 4. If number <= 0, return +0.
// Not < so that NaN coerces to 0.
// NOTE: this check correctly rounds numbers less than 0.5
if (!(number >= 0.5)) {
return 0;
}
// 5. If number >= 255, return 255.
if (number > 255) {
return 255;
}
// The next steps are the equivalent of the spec's round-to-even requirement.
// Round up and then do the even/odd check.
double toTruncate = number + 0.5;
uint8_t x = static_cast<uint8_t>(toTruncate);
// If it was a tie (i.e. it ended in 0.5) then
if (x == toTruncate) {
// number ended in 0.5 and was rounded up, reduce by 1 if odd,
// else leave the same.
// That is the same as unsetting the least significant bit.
return (x & ~1);
} else {
// number did not end in 0.5, don't need to check the parity.
return x;
}
}
CallResult<HermesValue> toUInt8Clamp(Runtime *runtime, Handle<> valueHandle) {
// 1. Let number be toNumber_RJS(argument)
auto res = toNumber_RJS(runtime, valueHandle);
if (res == ExecutionStatus::EXCEPTION) {
// 2. ReturnIfAbrupt(number)
return ExecutionStatus::EXCEPTION;
}
return HermesValue::encodeNumberValue(toUInt8Clamp(res->getNumber()));
}
CallResult<HermesValue> toUInt16(Runtime *runtime, Handle<> valueHandle) {
return toInt<uint16_t>(runtime, valueHandle);
}
CallResult<HermesValue> toUInt32_RJS(Runtime *runtime, Handle<> valueHandle) {
return toInt<uint32_t>(runtime, valueHandle);
}
CallResult<Handle<JSObject>> getPrimitivePrototype(
Runtime *runtime,
Handle<> base) {
switch (base->getTag()) {
case EmptyInvalidTag:
llvm_unreachable("empty value");
case NativeValueTag:
llvm_unreachable("native value");
case ObjectTag:
llvm_unreachable("object value");
case UndefinedNullTag:
return runtime->raiseTypeError(
base->isUndefined() ? "Cannot convert undefined value to object"
: "Cannot convert null value to object");
case StrTag:
return Handle<JSObject>::vmcast(&runtime->stringPrototype);
case BoolTag:
return Handle<JSObject>::vmcast(&runtime->booleanPrototype);
case SymbolTag:
return Handle<JSObject>::vmcast(&runtime->symbolPrototype);
default:
assert(base->isNumber() && "Unknown tag in getPrimitivePrototype.");
return Handle<JSObject>::vmcast(&runtime->numberPrototype);
}
}
CallResult<HermesValue> toObject(Runtime *runtime, Handle<> valueHandle) {
auto value = valueHandle.get();
switch (value.getTag()) {
case EmptyInvalidTag:
llvm_unreachable("empty value");
case NativeValueTag:
llvm_unreachable("native value");
case UndefinedNullTag:
return runtime->raiseTypeError(
value.isUndefined() ? "Cannot convert undefined value to object"
: "Cannot convert null value to object");
case ObjectTag:
return value;
case BoolTag:
return JSBoolean::create(
runtime,
value.getBool(),
Handle<JSObject>::vmcast(&runtime->booleanPrototype))
.getHermesValue();
case StrTag: {
auto res = JSString::create(
runtime,
runtime->makeHandle(value.getString()),
Handle<JSObject>::vmcast(&runtime->stringPrototype));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
return res->getHermesValue();
}
case SymbolTag:
return JSSymbol::create(
runtime,
*Handle<SymbolID>::vmcast(valueHandle),
Handle<JSObject>::vmcast(&runtime->symbolPrototype))
.getHermesValue();
default:
assert(valueHandle->isNumber() && "Unknown tag in toObject.");
return JSNumber::create(
runtime,
value.getNumber(),
Handle<JSObject>::vmcast(&runtime->numberPrototype))
.getHermesValue();
}
}
ExecutionStatus amendPropAccessErrorMsgWithPropName(
Runtime *runtime,
Handle<> valueHandle,
llvh::StringRef operationStr,
SymbolID id) {
if (!valueHandle->isNull() && !valueHandle->isUndefined()) {
// If value is not null/undefined, fall back to the original exception.
return ExecutionStatus::EXCEPTION;
}
assert(!runtime->getThrownValue().isEmpty() && "Error must have been thrown");
// Clear the error first because we will re-throw.
runtime->clearThrownValue();
// Construct an error message that contains the property name.
llvh::StringRef valueStr = valueHandle->isNull() ? "null" : "undefined";
return runtime->raiseTypeError(
TwineChar16("Cannot ") + operationStr + " property '" +
runtime->getIdentifierTable().getStringView(runtime, id) + "' of " +
valueStr);
}
/// Implement a comparison operator. First both operands a converted to
/// primitives. If they both end up being strings, a lexicographical comparison
/// is performed. Otherwise both operands are converted to numbers and the
/// values are compared.
/// \param oper is the comparison operator to use when comparing numbers.
#define IMPLEMENT_COMPARISON_OP(name, oper) \
CallResult<bool> name( \
Runtime *runtime, Handle<> leftHandle, Handle<> rightHandle) { \
auto resLeft = \
toPrimitive_RJS(runtime, leftHandle, PreferredType::NUMBER); \
if (resLeft == ExecutionStatus::EXCEPTION) \
return ExecutionStatus::EXCEPTION; \
MutableHandle<> left(runtime, resLeft.getValue()); \
\
auto resRight = \
toPrimitive_RJS(runtime, rightHandle, PreferredType::NUMBER); \
if (resRight == ExecutionStatus::EXCEPTION) \
return ExecutionStatus::EXCEPTION; \
MutableHandle<> right(runtime, resRight.getValue()); \
\
/* If both are strings, we must do a string comparison.*/ \
if (left->isString() && right->isString()) { \
return left->getString()->compare(right->getString()) oper 0; \
} \
\
/* Convert both to a number and compare the numbers. */ \
resLeft = toNumber_RJS(runtime, left); \
if (resLeft == ExecutionStatus::EXCEPTION) \
return ExecutionStatus::EXCEPTION; \
left = resLeft.getValue(); \
resRight = toNumber_RJS(runtime, right); \
if (resRight == ExecutionStatus::EXCEPTION) \
return ExecutionStatus::EXCEPTION; \
right = resRight.getValue(); \
\
return left->getNumber() oper right->getNumber(); \
}
IMPLEMENT_COMPARISON_OP(lessOp_RJS, <);
IMPLEMENT_COMPARISON_OP(greaterOp_RJS, >);
IMPLEMENT_COMPARISON_OP(lessEqualOp_RJS, <=);
IMPLEMENT_COMPARISON_OP(greaterEqualOp_RJS, >=);
CallResult<HermesValue>
abstractEqualityTest_RJS(Runtime *runtime, Handle<> xHandle, Handle<> yHandle) {
MutableHandle<> x{runtime, xHandle.get()};
MutableHandle<> y{runtime, yHandle.get()};
abstractEqualityTailCall:
// Same type comparison.
if (x->getTag() == y->getTag() || (x->isNumber() && y->isNumber())) {
bool result;
switch (x->getTag()) {
case EmptyInvalidTag:
llvm_unreachable("can't compare empties");
case NativeValueTag:
llvm_unreachable("native value");
case UndefinedNullTag:
result = true;
break;
case StrTag:
result = x->getString()->equals(y->getString());
break;
case ObjectTag:
// Return true if x and y refer to the same object.
result = x->getPointer() == y->getPointer();
break;
case BoolTag:
result = x->getBool() == y->getBool();
break;
case SymbolTag:
result = x->getSymbol() == y->getSymbol();
break;
default: {
result = x->getNumber() == y->getNumber();
break;
}
}
return HermesValue::encodeBoolValue(result);
}
// If the types are different, combine tags for use in the switch statement.
// Use NativeValueTag as a placeholder for numbers.
assert(
!x->isNativeValue() && !x->isEmpty() && "invalid value for comparison");
assert(
!y->isNativeValue() && !y->isEmpty() && "invalid value for comparison");
constexpr TagKind NumberTag = NativeValueTag;
// Tag numbers as numbers, and use default tag values for everything else.
TagKind xType = x->isNumber() ? NumberTag : x->getTag();
TagKind yType = y->isNumber() ? NumberTag : y->getTag();
switch (HermesValue::combineTags(xType, yType)) {
case HermesValue::combineTags(UndefinedNullTag, UndefinedNullTag):
return HermesValue::encodeBoolValue(true);
case HermesValue::combineTags(NumberTag, StrTag):
return HermesValue::encodeBoolValue(
x->getNumber() ==
stringToNumber(runtime, Handle<StringPrimitive>::vmcast(y)));
case HermesValue::combineTags(StrTag, NumberTag):
return HermesValue::encodeBoolValue(
stringToNumber(runtime, Handle<StringPrimitive>::vmcast(x)) ==
y->getNumber());
case HermesValue::combineTags(BoolTag, NumberTag):
// Do both conversions and check numerical equality.
return HermesValue::encodeBoolValue(x->getBool() == y->getNumber());
case HermesValue::combineTags(BoolTag, StrTag):
// Do string parsing and check double equality.
return HermesValue::encodeBoolValue(
x->getBool() ==
stringToNumber(runtime, Handle<StringPrimitive>::vmcast(y)));
case HermesValue::combineTags(BoolTag, ObjectTag):
x = HermesValue::encodeDoubleValue(x->getBool());
goto abstractEqualityTailCall;
case HermesValue::combineTags(NumberTag, BoolTag):
return HermesValue::encodeBoolValue(x->getNumber() == y->getBool());
case HermesValue::combineTags(StrTag, BoolTag):
return HermesValue::encodeBoolValue(
stringToNumber(runtime, Handle<StringPrimitive>::vmcast(x)) ==
y->getBool());
case HermesValue::combineTags(ObjectTag, BoolTag):
y = HermesValue::encodeDoubleValue(y->getBool());
goto abstractEqualityTailCall;
case HermesValue::combineTags(StrTag, ObjectTag):
case HermesValue::combineTags(SymbolTag, ObjectTag):
case HermesValue::combineTags(NumberTag, ObjectTag): {
auto status = toPrimitive_RJS(runtime, y, PreferredType::NONE);
if (status == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
y = status.getValue();
goto abstractEqualityTailCall;
}
case HermesValue::combineTags(ObjectTag, StrTag):
case HermesValue::combineTags(ObjectTag, SymbolTag):
case HermesValue::combineTags(ObjectTag, NumberTag): {
auto status = toPrimitive_RJS(runtime, x, PreferredType::NONE);
if (status == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
x = status.getValue();
goto abstractEqualityTailCall;
}
default:
// Final case, return false.
return HermesValue::encodeBoolValue(false);
} // namespace vm
} // namespace hermes
bool strictEqualityTest(HermesValue x, HermesValue y) {
// Numbers are special because they can have different tags and they don't
// obey bit-exact equality (because of NaN).
if (x.isNumber())
return y.isNumber() && x.getNumber() == y.getNumber();
// If they are not numbers and are bit exact, they must be the same.
if (x.getRaw() == y.getRaw())
return true;
// All the rest of the cases need to have the same tags.
if (x.getTag() != y.getTag())
return false;
// The only remaining case is string, which needs a deep comparison.
return x.isString() && x.getString()->equals(y.getString());
}
CallResult<HermesValue>
addOp_RJS(Runtime *runtime, Handle<> xHandle, Handle<> yHandle) {
auto resX = toPrimitive_RJS(runtime, xHandle, PreferredType::NONE);
if (resX == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto x = runtime->makeHandle(resX.getValue());
auto resY = toPrimitive_RJS(runtime, yHandle, PreferredType::NONE);
if (resY == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto y = runtime->makeHandle(resY.getValue());
// If one of the values is a string, concatenate as strings.
if (x->isString() || y->isString()) {
auto resX = toString_RJS(runtime, x);
if (resX == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto xStr = runtime->makeHandle(std::move(*resX));
auto resY = toString_RJS(runtime, y);
if (resY == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
auto yStr = runtime->makeHandle(std::move(*resY));
return StringPrimitive::concat(runtime, xStr, yStr);
}
// Add the numbers since neither are strings.
resX = toNumber_RJS(runtime, x);
if (LLVM_UNLIKELY(resX == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto xNum = resX.getValue().getNumber();
resY = toNumber_RJS(runtime, y);
if (LLVM_UNLIKELY(resY == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
auto yNum = resY.getValue().getNumber();
return HermesValue::encodeDoubleValue(xNum + yNum);
}
static const size_t MIN_RADIX = 2;
static const size_t MAX_RADIX = 36;
static inline char toRadixChar(unsigned x, unsigned radix) {
const char chars[] = "0123456789abcdefghijklmnopqrstuvwxyz";
static_assert(sizeof(chars) - 1 == MAX_RADIX, "Invalid chars array");
assert(
x < radix && x < std::strlen(chars) &&
"invalid number to radix conversion");
return chars[x];
}
/// \return the exponent component of the double \p x.
static inline int doubleExponent(double x) {
int e;
std::frexp(x, &e);
return e;
}
Handle<StringPrimitive>
numberToStringWithRadix(Runtime *runtime, double number, unsigned radix) {
(void)MIN_RADIX;
(void)MAX_RADIX;
assert(MIN_RADIX <= radix && radix <= MAX_RADIX && "Invalid radix");
// Two parts of the final result: integer part and fractional part.
llvh::SmallString<64> result{};
// Used to store just the fractional part of the string (not including '.').
llvh::SmallString<32> fStr{};
// If negative, treat as if positive and add a '-' later.
bool negative = false;
if (number < 0) {
negative = true;
number = -number;
}
// Split number into integer and fractional parts.
double iPart;
double fPart = std::modf(number, &iPart);
// If there's a fractional part, convert it and store in fStr.