1 /**
2 * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #ifndef PANDA_PLUGINS_ETS_RUNTIME_INTRINSICS_HELPERS_
17 #define PANDA_PLUGINS_ETS_RUNTIME_INTRINSICS_HELPERS_
18
19 #include <charconv>
20 #include <cmath>
21 #include <cstdint>
22 #include <type_traits>
23 #include "libpandabase/utils/bit_helpers.h"
24 #include "libpandabase/utils/utils.h"
25 #include "intrinsics.h"
26 #include "plugins/ets/runtime/types/ets_string.h"
27 #include "plugins/ets/runtime/ets_exceptions.h"
28 #include "plugins/ets/runtime/ets_panda_file_items.h"
29
30 namespace ark::ets::intrinsics::helpers {
31
32 inline constexpr double MIN_RADIX = 2;
33 inline constexpr double MAX_RADIX = 36;
34 inline constexpr double MIN_FRACTION = 0;
35 inline constexpr double MAX_FRACTION = 100;
36
37 inline constexpr uint32_t MAX_PRECISION = 16;
38 inline constexpr uint8_t BINARY = 2;
39 inline constexpr uint8_t OCTAL = 8;
40 inline constexpr uint8_t DECIMAL = 10;
41 inline constexpr uint8_t HEXADECIMAL = 16;
42 inline constexpr double HALF = 0.5;
43 inline constexpr double EPSILON = std::numeric_limits<double>::epsilon();
44 inline constexpr double MAX_SAFE_INTEGER = 9007199254740991;
45 inline constexpr double MAX_VALUE = std::numeric_limits<double>::max();
46 inline constexpr double MIN_VALUE = std::numeric_limits<double>::min();
47 inline constexpr double POSITIVE_INFINITY = coretypes::TaggedValue::VALUE_INFINITY;
48 inline constexpr double NAN_VALUE = coretypes::TaggedValue::VALUE_NAN;
49
50 inline constexpr int DOUBLE_MAX_PRECISION = 17;
51 inline constexpr int FLOAT_MAX_PRECISION = 9;
52
53 // NOLINTNEXTLINE(modernize-avoid-c-arrays)
54 inline constexpr uint16_t SPACE_OR_LINE_TERMINAL[] = {
55 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x0020, 0x00A0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004,
56 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000, 0xFEFF,
57 };
58
59 // NOLINTNEXTLINE(modernize-avoid-c-arrays)
60 inline constexpr char CHARS[] = "0123456789abcdefghijklmnopqrstuvwxyz";
61 inline constexpr uint64_t MAX_MANTISSA = 0x1ULL << 52U;
62 inline constexpr size_t BUF_SIZE = 128;
63 inline constexpr size_t TEN = 10;
64
65 enum class Sign { NONE, NEG, POS };
66
67 union DoubleValUnion {
68 double fval;
69 uint64_t uval;
70 struct {
71 uint64_t significand : coretypes::DOUBLE_SIGNIFICAND_SIZE;
72 uint16_t exponent : coretypes::DOUBLE_EXPONENT_SIZE;
73 int sign : 1;
74 } bits __attribute__((packed));
75 } __attribute__((may_alias, packed));
76
77 template <typename T>
MaxSafeInteger()78 constexpr T MaxSafeInteger()
79 {
80 static_assert(std::is_same_v<T, float> || std::is_same_v<T, double>);
81 if (std::is_same_v<T, float>) {
82 return static_cast<float>((UINT32_C(1) << static_cast<uint32_t>(std::numeric_limits<float>::digits)) - 1);
83 }
84 return static_cast<double>((UINT64_C(1) << static_cast<uint32_t>(std::numeric_limits<double>::digits)) - 1);
85 }
86
SignedZero(Sign sign)87 inline double SignedZero(Sign sign)
88 {
89 return sign == Sign::NEG ? -0.0 : 0.0;
90 }
91
ToDigit(uint8_t c)92 inline uint8_t ToDigit(uint8_t c)
93 {
94 if (c >= '0' && c <= '9') {
95 return c - '0';
96 }
97 if (c >= 'A' && c <= 'Z') {
98 return c - 'A' + DECIMAL;
99 }
100 if (c >= 'a' && c <= 'z') {
101 return c - 'a' + DECIMAL;
102 }
103 return '$';
104 }
105
PowHelper(uint64_t number,int16_t exponent,uint8_t radix)106 inline double PowHelper(uint64_t number, int16_t exponent, uint8_t radix)
107 {
108 const double log2Radix {std::log2(radix)};
109
110 double expRem = log2Radix * exponent;
111 int expI = static_cast<int>(expRem);
112 expRem = expRem - expI;
113
114 // NOLINTNEXTLINE(readability-magic-numbers)
115 DoubleValUnion u = {static_cast<double>(number) * std::pow(2.0, expRem)};
116
117 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access)
118 expI = u.bits.exponent + expI;
119 if (((expI & ~coretypes::DOUBLE_EXPONENT_MAX) != 0) || expI == 0) { // NOLINT(hicpp-signed-bitwise)
120 if (expI > 0) {
121 return std::numeric_limits<double>::infinity();
122 }
123 if (expI <= -static_cast<int>(coretypes::DOUBLE_SIGNIFICAND_SIZE)) {
124 return 0;
125 }
126 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access)
127 u.bits.exponent = 0;
128 // NOLINTNEXTLINE(hicpp-signed-bitwise, cppcoreguidelines-pro-type-union-access)
129 u.bits.significand = (u.bits.significand | coretypes::DOUBLE_HIDDEN_BIT) >> (1 - expI);
130 } else {
131 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access)
132 u.bits.exponent = expI;
133 }
134
135 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access)
136 return u.fval;
137 }
138
IsNonspace(uint16_t c)139 inline bool IsNonspace(uint16_t c)
140 {
141 int i;
142 int len = sizeof(SPACE_OR_LINE_TERMINAL) / sizeof(SPACE_OR_LINE_TERMINAL[0]);
143 for (i = 0; i < len; i++) {
144 if (c == SPACE_OR_LINE_TERMINAL[i]) {
145 return false;
146 }
147 if (c < SPACE_OR_LINE_TERMINAL[i]) {
148 return true;
149 }
150 }
151 return true;
152 }
153
GotoNonspace(uint8_t ** ptr,const uint8_t * end)154 inline bool GotoNonspace(uint8_t **ptr, const uint8_t *end)
155 {
156 while (*ptr < end) {
157 uint16_t c = **ptr;
158 size_t size = 1;
159 if (c > INT8_MAX) {
160 size = 0;
161 uint16_t utf8Bit = INT8_MAX + 1; // equal 0b1000'0000
162 while (utf8Bit > 0 && (c & utf8Bit) == utf8Bit) {
163 ++size;
164 utf8Bit >>= 1UL;
165 }
166 if (utf::ConvertRegionUtf8ToUtf16(*ptr, &c, end - *ptr, 1, 0) <= 0) {
167 return true;
168 }
169 }
170 if (IsNonspace(c)) {
171 return true;
172 }
173 *ptr += size; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
174 }
175 return false;
176 }
177
IsEmptyString(const uint8_t * start,const uint8_t * end)178 inline bool IsEmptyString(const uint8_t *start, const uint8_t *end)
179 {
180 auto p = const_cast<uint8_t *>(start);
181 return !GotoNonspace(&p, end);
182 }
183
Strtod(const char * str,int exponent,uint8_t radix)184 inline double Strtod(const char *str, int exponent, uint8_t radix)
185 {
186 ASSERT(str != nullptr);
187 ASSERT(radix >= MIN_RADIX && radix <= MAX_RADIX);
188 auto p = const_cast<char *>(str);
189 Sign sign = Sign::NONE;
190 uint64_t number = 0;
191 uint64_t numberMax = (UINT64_MAX - (radix - 1)) / radix;
192 double result = 0.0;
193 if (*p == '-') {
194 sign = Sign::NEG;
195 ++p;
196 }
197 while (*p == '0') {
198 ++p;
199 }
200 while (*p != '\0') {
201 uint8_t digit = ToDigit(static_cast<uint8_t>(*p));
202 if (digit >= radix) {
203 break;
204 }
205 if (number < numberMax) {
206 number = number * radix + digit;
207 } else {
208 ++exponent;
209 }
210 ++p;
211 }
212 if (exponent < 0) {
213 result = number / std::pow(radix, -exponent);
214 } else {
215 result = number * std::pow(radix, exponent);
216 }
217 if (!std::isfinite(result) || (result == 0 && number != 0)) {
218 result = PowHelper(number, exponent, radix);
219 }
220 return sign == Sign::NEG ? -result : result;
221 }
222
Carry(char current,int radix)223 [[maybe_unused]] inline char Carry(char current, int radix)
224 {
225 int digit = static_cast<int>((current > '9') ? (current - 'a' + DECIMAL) : (current - '0'));
226 digit = (digit == (radix - 1)) ? 0 : digit + 1;
227 return CHARS[digit];
228 }
229
230 template <typename FpType, std::enable_if_t<std::is_floating_point_v<FpType>, bool> = true>
TruncateFp(FpType number)231 FpType TruncateFp(FpType number)
232 {
233 // -0 to +0
234 if (number == 0.0) {
235 return 0;
236 }
237 return (number >= 0) ? std::floor(number) : std::ceil(number);
238 }
239
240 template <typename FpType, std::enable_if_t<std::is_floating_point_v<FpType>, bool> = true>
DecimalsToString(FpType * numberInteger,FpType fraction,int radix,FpType delta)241 PandaString DecimalsToString(FpType *numberInteger, FpType fraction, int radix, FpType delta)
242 {
243 PandaString result;
244 while (fraction >= delta) {
245 fraction *= radix;
246 delta *= radix;
247 int64_t integer = std::floor(fraction);
248 fraction -= integer;
249 result += CHARS[integer];
250 if (fraction > HALF && fraction + delta > 1) {
251 size_t fractionEnd = result.size() - 1;
252 result[fractionEnd] = Carry(*result.rbegin(), radix);
253 for (; fractionEnd > 0 && result[fractionEnd] == '0'; fractionEnd--) {
254 result[fractionEnd - 1] = Carry(result[fractionEnd - 1], radix);
255 }
256 if (fractionEnd == 0) {
257 (*numberInteger)++;
258 }
259 break;
260 }
261 }
262 // delete 0 in the end
263 size_t found = result.find_last_not_of('0');
264 if (found != PandaString::npos) {
265 result.erase(found + 1);
266 }
267
268 return result;
269 }
270
271 template <typename FpType, std::enable_if_t<std::is_floating_point_v<FpType>, bool> = true>
IntegerToString(FpType number,int radix)272 PandaString IntegerToString(FpType number, int radix)
273 {
274 ASSERT(radix >= MIN_RADIX && radix <= MAX_RADIX);
275 ASSERT(number == std::round(number));
276 PandaString result;
277 while (TruncateFp(number / radix) > static_cast<FpType>(MAX_MANTISSA)) {
278 number /= radix;
279 TruncateFp(number);
280 result = PandaString("0").append(result);
281 }
282 do {
283 auto remainder = static_cast<uint8_t>(std::fmod(number, radix));
284 result = CHARS[remainder] + result;
285 number = TruncateFp((number - remainder) / radix);
286 } while (number > 0);
287 return result;
288 }
289
290 template <typename FpType, std::enable_if_t<std::is_floating_point_v<FpType>, bool> = true>
StrToFp(char * str,char ** strEnd)291 FpType StrToFp(char *str, char **strEnd)
292 {
293 if constexpr (std::is_same_v<FpType, double>) {
294 return std::strtod(str, strEnd);
295 } else {
296 return std::strtof(str, strEnd);
297 }
298 }
299
300 double StringToDouble(const uint8_t *start, const uint8_t *end, uint8_t radix, uint32_t flags);
301 double StringToDoubleWithRadix(const uint8_t *start, const uint8_t *end, int radix);
302 EtsString *DoubleToExponential(double number, int digit);
303 EtsString *DoubleToFixed(double number, int digit);
304 EtsString *DoubleToPrecision(double number, int digit);
305 double GetStdDoubleArgument(ObjectHeader *obj);
306
307 template <typename FpType, std::enable_if_t<std::is_floating_point_v<FpType>, bool> = true>
FpNonFiniteToString(FpType number)308 inline const char *FpNonFiniteToString(FpType number)
309 {
310 ASSERT(std::isnan(number) || !std::isfinite(number));
311 if (std::isnan(number)) {
312 return "NaN";
313 }
314 return std::signbit(number) ? "-Infinity" : "Infinity";
315 }
316
317 template <typename FpType>
318 char *SmallFpToString(FpType number, bool negative, char *buffer);
319
320 template <typename FpType>
321 Span<char> FpToStringDecimalRadixMainCase(FpType number, bool negative, Span<char> buffer);
322
323 // NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic)
324 template <typename FpType, std::enable_if_t<std::is_floating_point_v<FpType>, bool> = true, typename Cb>
FpToStringDecimalRadix(FpType number,Cb cb)325 auto FpToStringDecimalRadix(FpType number, Cb cb)
326 {
327 static constexpr FpType MIN_BOUND = 0.1;
328
329 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
330 std::array<char, BUF_SIZE + 2U> buffer;
331
332 if (INT_MIN < number && number < static_cast<FpType>(INT_MAX)) {
333 if (auto intVal = static_cast<int32_t>(number); number == static_cast<double>(intVal)) {
334 auto bufferEnd = std::to_chars(buffer.begin(), buffer.end(), intVal).ptr;
335 return cb({buffer.begin(), static_cast<size_t>(bufferEnd - buffer.begin())});
336 }
337 }
338
339 // isfinite checks if the number is normal, subnormal or zero, but not infinite or NaN.
340 if (!std::isfinite(number)) {
341 auto *str = FpNonFiniteToString(number);
342 return cb(str);
343 }
344
345 bool negative = false;
346 if (number < 0) {
347 negative = true;
348 number = -number;
349 }
350 if (!std::is_same_v<FpType, double> && MIN_BOUND <= number && number < 1) {
351 // Fast path. In this case, n==0, just need to calculate k and s.
352 auto bufferEnd = SmallFpToString(number, negative, buffer.begin());
353 return cb({buffer.begin(), static_cast<size_t>(bufferEnd - buffer.begin())});
354 }
355
356 auto newBuffer = FpToStringDecimalRadixMainCase(number, negative, Span(buffer));
357 return cb({newBuffer.begin(), newBuffer.size()});
358 }
359 // NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic)
360
361 template <typename FpType, std::enable_if_t<std::is_floating_point_v<FpType>, bool> = true>
FpDelta(FpType number)362 inline float FpDelta(FpType number)
363 {
364 using UnsignedIntType = ark::helpers::TypeHelperT<sizeof(FpType) * CHAR_BIT, false>;
365 auto value = bit_cast<FpType>(bit_cast<UnsignedIntType>(number) + 1U);
366 float delta = static_cast<FpType>(HALF) * (bit_cast<FpType>(value) - number);
367 return delta == 0 ? number : delta;
368 }
369
370 template <typename FpType, std::enable_if_t<std::is_floating_point_v<FpType>, bool> = true>
FpToString(FpType number,int radix)371 EtsString *FpToString(FpType number, int radix)
372 {
373 // check radix range
374 if (UNLIKELY(radix > helpers::MAX_RADIX || radix < helpers::MIN_RADIX)) {
375 constexpr size_t MAX_BUF_SIZE = 128;
376 std::array<char, MAX_BUF_SIZE> buf {};
377 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg)
378 snprintf_s(buf.data(), buf.size(), buf.size() - 1, "radix must be %.f to %.f", helpers::MIN_RADIX,
379 helpers::MAX_RADIX);
380 ThrowEtsException(EtsCoroutine::GetCurrent(),
381 panda_file_items::class_descriptors::ARGUMENT_OUT_OF_RANGE_EXCEPTION, buf.data());
382 return nullptr;
383 }
384
385 if (radix == helpers::DECIMAL) {
386 return helpers::FpToStringDecimalRadix(
387 number, [](std::string_view str) { return EtsString::CreateFromAscii(str.data(), str.length()); });
388 }
389
390 // isfinite checks if the number is normal, subnormal or zero, but not infinite or NaN.
391 if (!std::isfinite(number)) {
392 return EtsString::CreateFromMUtf8(FpNonFiniteToString(number));
393 }
394
395 PandaString result;
396 if (number < 0.0) {
397 result += "-";
398 number = -number;
399 }
400
401 float delta = FpDelta(number);
402 FpType integral;
403 FpType fractional = std::modf(number, &integral);
404 if (fractional != 0 && fractional >= delta) {
405 PandaString fraction(DecimalsToString<FpType>(&integral, fractional, radix, delta));
406 result += IntegerToString(integral, radix) + "." + fraction;
407 } else {
408 result += IntegerToString(integral, radix);
409 }
410
411 return EtsString::CreateFromMUtf8(result.c_str());
412 }
413
414 } // namespace ark::ets::intrinsics::helpers
415
416 namespace ark::ets::intrinsics::helpers::flags {
417
418 inline constexpr uint32_t NO_FLAGS = 0U;
419 inline constexpr uint32_t ALLOW_BINARY = 1U << 0U;
420 inline constexpr uint32_t ALLOW_OCTAL = 1U << 1U;
421 inline constexpr uint32_t ALLOW_HEX = 1U << 2U;
422 inline constexpr uint32_t IGNORE_TRAILING = 1U << 3U;
423 inline constexpr uint32_t EMPTY_IS_ZERO = 1U << 4U;
424 inline constexpr uint32_t ERROR_IN_EXPONENT_IS_NAN = 1U << 5U;
425
426 } // namespace ark::ets::intrinsics::helpers::flags
427
428 #endif // PANDA_PLUGINS_ETS_RUNTIME_INTRINSICS_HELPERS_
429