@oseo/runtime-c 0.0.0-stage → 0.1.0-canary.370

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +674 -0
  2. package/MIT-LICENSE.txt +21 -0
  3. package/README.md +28 -2
  4. package/UNICODE-LICENSE.txt +39 -0
  5. package/dist/index.d.ts +7 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +269 -0
  8. package/dist/index.js.map +1 -0
  9. package/native/oseo_runtime.h +2618 -0
  10. package/native/runtime_agent.c +1717 -0
  11. package/native/runtime_arguments.c +379 -0
  12. package/native/runtime_array.c +5766 -0
  13. package/native/runtime_array_buffer.c +1748 -0
  14. package/native/runtime_async_generator.c +972 -0
  15. package/native/runtime_atomics.c +1283 -0
  16. package/native/runtime_bigint.c +1387 -0
  17. package/native/runtime_bigint_object.c +626 -0
  18. package/native/runtime_binding.c +1029 -0
  19. package/native/runtime_boolean.c +320 -0
  20. package/native/runtime_clock.c +181 -0
  21. package/native/runtime_clock_posix.c +599 -0
  22. package/native/runtime_core.c +488 -0
  23. package/native/runtime_data_view.c +1135 -0
  24. package/native/runtime_date.c +1997 -0
  25. package/native/runtime_descriptor.c +1104 -0
  26. package/native/runtime_disposal.c +1667 -0
  27. package/native/runtime_enumeration.c +636 -0
  28. package/native/runtime_error.c +997 -0
  29. package/native/runtime_event_loop.c +653 -0
  30. package/native/runtime_function.c +3667 -0
  31. package/native/runtime_generator.c +1120 -0
  32. package/native/runtime_internal.h +5578 -0
  33. package/native/runtime_iterator.c +5379 -0
  34. package/native/runtime_json.c +1992 -0
  35. package/native/runtime_map.c +1563 -0
  36. package/native/runtime_math.c +918 -0
  37. package/native/runtime_memory.c +1365 -0
  38. package/native/runtime_module.c +884 -0
  39. package/native/runtime_number.c +2077 -0
  40. package/native/runtime_object.c +423 -0
  41. package/native/runtime_object_builtin.c +3901 -0
  42. package/native/runtime_primitive.c +2268 -0
  43. package/native/runtime_process.c +744 -0
  44. package/native/runtime_promise.c +3378 -0
  45. package/native/runtime_property.c +815 -0
  46. package/native/runtime_proxy.c +1557 -0
  47. package/native/runtime_realm.c +435 -0
  48. package/native/runtime_reflect.c +648 -0
  49. package/native/runtime_regexp.c +3519 -0
  50. package/native/runtime_regexp_matcher.c +3559 -0
  51. package/native/runtime_regexp_symbol.c +1495 -0
  52. package/native/runtime_set.c +1775 -0
  53. package/native/runtime_string.c +2886 -0
  54. package/native/runtime_string_match.c +1185 -0
  55. package/native/runtime_symbol.c +1010 -0
  56. package/native/runtime_typed_array.c +5137 -0
  57. package/native/runtime_unicode_tables.h +14670 -0
  58. package/native/runtime_uri.c +700 -0
  59. package/native/runtime_weak_collection.c +1299 -0
  60. package/package.json +38 -3
@@ -0,0 +1,2077 @@
1
+ /* SPDX-License-Identifier: MIT */
2
+ /*
3
+ * Oseo C runtime library.
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2026 Hong Minhee <https://hongminhee.org/>
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ * of this software and associated documentation files (the "Software"), to deal
11
+ * in the Software without restriction, including without limitation the rights
12
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ * copies of the Software, and to permit persons to whom the Software is
14
+ * furnished to do so, subject to the following conditions:
15
+ *
16
+ * The above copyright notice and this permission notice shall be included in
17
+ * all copies or substantial portions of the Software.
18
+ *
19
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ * SOFTWARE.
26
+ */
27
+
28
+ #include "runtime_internal.h"
29
+
30
+ #include <float.h>
31
+ #include <math.h>
32
+ #include <stdio.h>
33
+ #include <stdlib.h>
34
+ #include <string.h>
35
+
36
+ /* Number constructor, wrapper state, constants, and static operations. */
37
+
38
+ #define OSEO_MAX_SAFE_INTEGER 9007199254740991.0
39
+
40
+ static bool number_whitespace(uint16_t unit) {
41
+ return unit == UINT16_C(0x0009) || unit == UINT16_C(0x000a) ||
42
+ unit == UINT16_C(0x000b) || unit == UINT16_C(0x000c) ||
43
+ unit == UINT16_C(0x000d) || unit == UINT16_C(0x0020) ||
44
+ unit == UINT16_C(0x00a0) || unit == UINT16_C(0x1680) ||
45
+ (unit >= UINT16_C(0x2000) && unit <= UINT16_C(0x200a)) ||
46
+ unit == UINT16_C(0x2028) || unit == UINT16_C(0x2029) ||
47
+ unit == UINT16_C(0x202f) || unit == UINT16_C(0x205f) ||
48
+ unit == UINT16_C(0x3000) || unit == UINT16_C(0xfeff);
49
+ }
50
+
51
+ static int number_digit(uint16_t unit) {
52
+ if (unit >= UINT16_C('0') && unit <= UINT16_C('9')) {
53
+ return (int)(unit - UINT16_C('0'));
54
+ }
55
+ if (unit >= UINT16_C('a') && unit <= UINT16_C('z')) {
56
+ return (int)(unit - UINT16_C('a')) + 10;
57
+ }
58
+ if (unit >= UINT16_C('A') && unit <= UINT16_C('Z')) {
59
+ return (int)(unit - UINT16_C('A')) + 10;
60
+ }
61
+ return -1;
62
+ }
63
+
64
+ static OseoResult number_argument(
65
+ OseoContext *context,
66
+ size_t argument_count,
67
+ const OseoValue *arguments
68
+ ) {
69
+ if (argument_count == 0u) return normal(oseo_number(0.0));
70
+ OseoResult result = oseo_to_numeric(context, arguments[0]);
71
+ if (result.status != OSEO_STATUS_NORMAL) return result;
72
+ if (is_bigint(result.value)) {
73
+ return normal(oseo_number(
74
+ oseo_internal_bigint_to_number(result.value)
75
+ ));
76
+ }
77
+ return result;
78
+ }
79
+
80
+ /*
81
+ * 21.1.1.1. The argument conversion runs first and
82
+ * OrdinaryCreateFromConstructor follows it, so a new target whose
83
+ * `prototype` is an accessor observes that order: a valueOf on the
84
+ * argument runs before the getter, and an abrupt getter reports after
85
+ * the conversion rather than before it. The read is a real Get because
86
+ * `Reflect.construct` can name a bound function, which owns no
87
+ * synthetic `prototype` slot to read.
88
+ */
89
+ static OseoResult number_construct(
90
+ OseoContext *context,
91
+ OseoValue new_target,
92
+ size_t argument_count,
93
+ const OseoValue *arguments,
94
+ bool constructing
95
+ ) {
96
+ /* Slots: 0 the new target, 1 the prototype the read produced. The
97
+ * argument conversion is a safepoint and can run arbitrary code, so
98
+ * the new target is rooted across it; the converted number stays a
99
+ * local because a Number is an immediate value. */
100
+ OseoValue slots[2] = {new_target, oseo_undefined()};
101
+ OseoRootFrame frame = {NULL, slots, 2u};
102
+ oseo_roots_push(context, &frame);
103
+ OseoResult result = number_argument(context, argument_count, arguments);
104
+ OseoValue data = result.value;
105
+ if (result.status == OSEO_STATUS_NORMAL && constructing) {
106
+ result = oseo_internal_constructor_prototype(context, slots[0]);
107
+ slots[1] = result.value;
108
+ if (result.status == OSEO_STATUS_NORMAL && !is_object(slots[1])) {
109
+ result = oseo_internal_constructor_realm_default(
110
+ context,
111
+ slots[0],
112
+ OSEO_INTRINSIC_NUMBER_PROTOTYPE
113
+ );
114
+ slots[1] = result.value;
115
+ }
116
+ if (result.status == OSEO_STATUS_NORMAL) {
117
+ result = oseo_object_create(context, slots[1]);
118
+ }
119
+ if (result.status == OSEO_STATUS_NORMAL) {
120
+ OseoOrdinaryObject *object = ordinary_object(result.value);
121
+ object->number_data = true;
122
+ object->number_value = data;
123
+ object->primitive_data = true;
124
+ object->primitive_value = data;
125
+ }
126
+ }
127
+ oseo_roots_pop(context, &frame);
128
+ return result;
129
+ }
130
+
131
+ static OseoResult number_is_finite(
132
+ size_t argument_count,
133
+ const OseoValue *arguments
134
+ ) {
135
+ if (argument_count == 0u || !is_number(arguments[0])) {
136
+ return normal(oseo_boolean(false));
137
+ }
138
+ return normal(oseo_boolean(isfinite(number_value(arguments[0]))));
139
+ }
140
+
141
+ static OseoResult number_is_integer(
142
+ size_t argument_count,
143
+ const OseoValue *arguments,
144
+ bool safe
145
+ ) {
146
+ if (argument_count == 0u || !is_number(arguments[0])) {
147
+ return normal(oseo_boolean(false));
148
+ }
149
+ double value = number_value(arguments[0]);
150
+ bool integer = isfinite(value) && trunc(value) == value;
151
+ if (safe) integer = integer && fabs(value) <= OSEO_MAX_SAFE_INTEGER;
152
+ return normal(oseo_boolean(integer));
153
+ }
154
+
155
+ static OseoResult number_is_nan(
156
+ size_t argument_count,
157
+ const OseoValue *arguments
158
+ ) {
159
+ bool result = argument_count > 0u && is_number(arguments[0]) &&
160
+ isnan(number_value(arguments[0]));
161
+ return normal(oseo_boolean(result));
162
+ }
163
+
164
+ /*
165
+ * The global isFinite and isNaN functions, 19.2.2 and 19.2.3. Unlike the
166
+ * Number statics of the same names, each converts its operand with
167
+ * ToNumber first, so an object's ToPrimitive protocol runs and a Symbol
168
+ * or BigInt operand throws the TypeError that conversion raises.
169
+ */
170
+ static OseoResult global_is_finite(
171
+ OseoContext *context,
172
+ size_t argument_count,
173
+ const OseoValue *arguments
174
+ ) {
175
+ OseoResult converted = oseo_internal_to_number(
176
+ context,
177
+ argument_count == 0u ? oseo_undefined() : arguments[0]
178
+ );
179
+ if (converted.status != OSEO_STATUS_NORMAL) return converted;
180
+ return normal(oseo_boolean(isfinite(number_value(converted.value))));
181
+ }
182
+
183
+ static OseoResult global_is_nan(
184
+ OseoContext *context,
185
+ size_t argument_count,
186
+ const OseoValue *arguments
187
+ ) {
188
+ OseoResult converted = oseo_internal_to_number(
189
+ context,
190
+ argument_count == 0u ? oseo_undefined() : arguments[0]
191
+ );
192
+ if (converted.status != OSEO_STATUS_NORMAL) return converted;
193
+ return normal(oseo_boolean(isnan(number_value(converted.value))));
194
+ }
195
+
196
+ static bool number_matches(
197
+ const OseoString *string,
198
+ size_t start,
199
+ const char *text
200
+ ) {
201
+ size_t length = strlen(text);
202
+ if (start > string->length || length > string->length - start) {
203
+ return false;
204
+ }
205
+ for (size_t index = 0u; index < length; index += 1u) {
206
+ if (string->units[start + index] !=
207
+ (uint16_t)(unsigned char)text[index]) {
208
+ return false;
209
+ }
210
+ }
211
+ return true;
212
+ }
213
+
214
+ static OseoResult number_parse_float(
215
+ OseoContext *context,
216
+ size_t argument_count,
217
+ const OseoValue *arguments
218
+ ) {
219
+ OseoValue input = argument_count == 0u
220
+ ? oseo_undefined()
221
+ : arguments[0];
222
+ OseoResult converted = oseo_internal_value_string(context, input);
223
+ if (converted.status != OSEO_STATUS_NORMAL) return converted;
224
+ const OseoString *string = string_object(converted.value);
225
+ size_t start = 0u;
226
+ while (start < string->length &&
227
+ number_whitespace(string->units[start])) {
228
+ start += 1u;
229
+ }
230
+ size_t cursor = start;
231
+ bool negative = false;
232
+ if (cursor < string->length &&
233
+ (string->units[cursor] == UINT16_C('+') ||
234
+ string->units[cursor] == UINT16_C('-'))) {
235
+ negative = string->units[cursor] == UINT16_C('-');
236
+ cursor += 1u;
237
+ }
238
+ if (number_matches(string, cursor, "Infinity")) {
239
+ return normal(oseo_number(negative ? -INFINITY : INFINITY));
240
+ }
241
+ size_t integer_start = cursor;
242
+ while (cursor < string->length &&
243
+ number_digit(string->units[cursor]) >= 0 &&
244
+ number_digit(string->units[cursor]) < 10) {
245
+ cursor += 1u;
246
+ }
247
+ bool has_digits = cursor > integer_start;
248
+ if (cursor < string->length &&
249
+ string->units[cursor] == UINT16_C('.')) {
250
+ cursor += 1u;
251
+ size_t fraction_start = cursor;
252
+ while (cursor < string->length &&
253
+ number_digit(string->units[cursor]) >= 0 &&
254
+ number_digit(string->units[cursor]) < 10) {
255
+ cursor += 1u;
256
+ }
257
+ has_digits = has_digits || cursor > fraction_start;
258
+ }
259
+ if (!has_digits) return normal(oseo_number(NAN));
260
+ size_t exponent_start = cursor;
261
+ if (cursor < string->length &&
262
+ (string->units[cursor] == UINT16_C('e') ||
263
+ string->units[cursor] == UINT16_C('E'))) {
264
+ cursor += 1u;
265
+ if (cursor < string->length &&
266
+ (string->units[cursor] == UINT16_C('+') ||
267
+ string->units[cursor] == UINT16_C('-'))) {
268
+ cursor += 1u;
269
+ }
270
+ size_t digits = cursor;
271
+ while (cursor < string->length &&
272
+ number_digit(string->units[cursor]) >= 0 &&
273
+ number_digit(string->units[cursor]) < 10) {
274
+ cursor += 1u;
275
+ }
276
+ if (cursor == digits) cursor = exponent_start;
277
+ }
278
+ size_t length = cursor - start;
279
+ char *text = malloc(length + 1u);
280
+ if (text == NULL) {
281
+ return failure(context, "OSEO2001", "Number parsing failed.");
282
+ }
283
+ for (size_t index = 0u; index < length; index += 1u) {
284
+ text[index] = (char)string->units[start + index];
285
+ }
286
+ text[length] = '\0';
287
+ double value = strtod(text, NULL);
288
+ free(text);
289
+ return normal(oseo_number(value));
290
+ }
291
+
292
+ static int32_t number_to_int32(double value) {
293
+ if (!isfinite(value) || value == 0.0) return 0;
294
+ double modulo = fmod(trunc(value), 4294967296.0);
295
+ if (modulo < 0.0) modulo += 4294967296.0;
296
+ uint32_t bits = (uint32_t)modulo;
297
+ if (bits < UINT32_C(0x80000000)) return (int32_t)bits;
298
+ return (int32_t)((int64_t)bits - INT64_C(4294967296));
299
+ }
300
+
301
+ static OseoResult number_parse_int(
302
+ OseoContext *context,
303
+ size_t argument_count,
304
+ const OseoValue *arguments
305
+ ) {
306
+ OseoValue slots[2] = {
307
+ argument_count == 0u ? oseo_undefined() : arguments[0],
308
+ argument_count < 2u ? oseo_undefined() : arguments[1],
309
+ };
310
+ OseoRootFrame frame = {NULL, slots, 2u};
311
+ oseo_roots_push(context, &frame);
312
+ OseoResult result = oseo_internal_value_string(context, slots[0]);
313
+ slots[0] = result.value;
314
+ int32_t requested_radix = 0;
315
+ if (result.status == OSEO_STATUS_NORMAL &&
316
+ tag_of(slots[1]) != OSEO_TAG_UNDEFINED) {
317
+ result = oseo_internal_to_number(context, slots[1]);
318
+ if (result.status == OSEO_STATUS_NORMAL) {
319
+ requested_radix = number_to_int32(number_value(result.value));
320
+ }
321
+ }
322
+ if (result.status != OSEO_STATUS_NORMAL) {
323
+ oseo_roots_pop(context, &frame);
324
+ return result;
325
+ }
326
+ const OseoString *string = string_object(slots[0]);
327
+ size_t cursor = 0u;
328
+ while (cursor < string->length &&
329
+ number_whitespace(string->units[cursor])) {
330
+ cursor += 1u;
331
+ }
332
+ bool negative = false;
333
+ if (cursor < string->length &&
334
+ (string->units[cursor] == UINT16_C('+') ||
335
+ string->units[cursor] == UINT16_C('-'))) {
336
+ negative = string->units[cursor] == UINT16_C('-');
337
+ cursor += 1u;
338
+ }
339
+ int radix = requested_radix;
340
+ bool strip_prefix = true;
341
+ if (radix != 0) {
342
+ if (radix < 2 || radix > 36) {
343
+ oseo_roots_pop(context, &frame);
344
+ return normal(oseo_number(NAN));
345
+ }
346
+ strip_prefix = radix == 16;
347
+ } else {
348
+ radix = 10;
349
+ }
350
+ if (strip_prefix && cursor + 1u < string->length &&
351
+ string->units[cursor] == UINT16_C('0') &&
352
+ (string->units[cursor + 1u] == UINT16_C('x') ||
353
+ string->units[cursor + 1u] == UINT16_C('X'))) {
354
+ cursor += 2u;
355
+ radix = 16;
356
+ }
357
+ size_t digits = 0u;
358
+ size_t digit_start = cursor;
359
+ while (cursor < string->length) {
360
+ int digit = number_digit(string->units[cursor]);
361
+ if (digit < 0 || digit >= radix) break;
362
+ digits += 1u;
363
+ cursor += 1u;
364
+ }
365
+ double value = oseo_internal_integer_digits_to_number(
366
+ &string->units[digit_start],
367
+ digits,
368
+ (uint32_t)radix
369
+ );
370
+ oseo_roots_pop(context, &frame);
371
+ if (digits == 0u) return normal(oseo_number(NAN));
372
+ return normal(oseo_number(negative ? -value : value));
373
+ }
374
+
375
+ /* ---- Exact rational arithmetic for Number.prototype formatting ---- */
376
+
377
+ /*
378
+ * A non-negative arbitrary-precision integer stored as decimal digits,
379
+ * least-significant digit first. Every formatting method below builds a
380
+ * numerator and denominator of this type from a double's exact mantissa
381
+ * and binary exponent, so toFixed, toExponential, and toPrecision round
382
+ * to the correctly-rounded decimal value instead of drifting through
383
+ * repeated floating-point arithmetic.
384
+ */
385
+ typedef struct {
386
+ uint8_t *digits;
387
+ size_t length;
388
+ size_t capacity;
389
+ } NumberBignum;
390
+
391
+ static bool number_bignum_reserve(NumberBignum *bignum, size_t needed) {
392
+ if (needed <= bignum->capacity) return true;
393
+ size_t capacity = bignum->capacity == 0u ? 32u : bignum->capacity;
394
+ while (capacity < needed) capacity *= 2u;
395
+ uint8_t *digits = realloc(bignum->digits, capacity);
396
+ if (digits == NULL) return false;
397
+ bignum->digits = digits;
398
+ bignum->capacity = capacity;
399
+ return true;
400
+ }
401
+
402
+ static void number_bignum_release(NumberBignum *bignum) {
403
+ free(bignum->digits);
404
+ bignum->digits = NULL;
405
+ bignum->length = 0u;
406
+ bignum->capacity = 0u;
407
+ }
408
+
409
+ static void number_bignum_trim(NumberBignum *bignum) {
410
+ while (bignum->length > 1u && bignum->digits[bignum->length - 1u] == 0u) {
411
+ bignum->length -= 1u;
412
+ }
413
+ }
414
+
415
+ static bool number_bignum_from_u64(NumberBignum *bignum, uint64_t value) {
416
+ if (!number_bignum_reserve(bignum, 20u)) return false;
417
+ size_t length = 0u;
418
+ do {
419
+ bignum->digits[length] = (uint8_t)(value % 10u);
420
+ value /= 10u;
421
+ length += 1u;
422
+ } while (value != 0u);
423
+ bignum->length = length;
424
+ return true;
425
+ }
426
+
427
+ static bool number_bignum_copy(
428
+ NumberBignum *destination,
429
+ const NumberBignum *source
430
+ ) {
431
+ if (!number_bignum_reserve(destination, source->length)) return false;
432
+ memcpy(destination->digits, source->digits, source->length);
433
+ destination->length = source->length;
434
+ return true;
435
+ }
436
+
437
+ static bool number_bignum_is_zero(const NumberBignum *bignum) {
438
+ return bignum->length == 1u && bignum->digits[0] == 0u;
439
+ }
440
+
441
+ static int number_bignum_compare(
442
+ const NumberBignum *left,
443
+ const NumberBignum *right
444
+ ) {
445
+ if (left->length != right->length) {
446
+ return left->length < right->length ? -1 : 1;
447
+ }
448
+ for (size_t step = left->length; step > 0u; step -= 1u) {
449
+ uint8_t a = left->digits[step - 1u];
450
+ uint8_t b = right->digits[step - 1u];
451
+ if (a != b) return a < b ? -1 : 1;
452
+ }
453
+ return 0;
454
+ }
455
+
456
+ static bool number_bignum_multiply_small(
457
+ NumberBignum *bignum,
458
+ unsigned multiplier
459
+ ) {
460
+ if (!number_bignum_reserve(bignum, bignum->length + 8u)) return false;
461
+ unsigned carry = 0u;
462
+ size_t length = bignum->length;
463
+ for (size_t index = 0u; index < length; index += 1u) {
464
+ unsigned product = (unsigned)bignum->digits[index] * multiplier +
465
+ carry;
466
+ bignum->digits[index] = (uint8_t)(product % 10u);
467
+ carry = product / 10u;
468
+ }
469
+ while (carry != 0u) {
470
+ if (!number_bignum_reserve(bignum, length + 1u)) return false;
471
+ bignum->digits[length] = (uint8_t)(carry % 10u);
472
+ carry /= 10u;
473
+ length += 1u;
474
+ }
475
+ bignum->length = length;
476
+ number_bignum_trim(bignum);
477
+ return true;
478
+ }
479
+
480
+ /* bignum *= multiplier, both non-negative. Schoolbook long multiply. */
481
+ static bool number_bignum_multiply_bignum(
482
+ NumberBignum *bignum,
483
+ const NumberBignum *multiplier
484
+ ) {
485
+ if (number_bignum_is_zero(bignum) || number_bignum_is_zero(multiplier)) {
486
+ return number_bignum_from_u64(bignum, 0u);
487
+ }
488
+ size_t result_length = bignum->length + multiplier->length;
489
+ uint32_t *accumulator = calloc(result_length, sizeof(uint32_t));
490
+ if (accumulator == NULL) return false;
491
+ for (size_t i = 0u; i < bignum->length; i += 1u) {
492
+ unsigned carry = 0u;
493
+ for (size_t j = 0u; j < multiplier->length; j += 1u) {
494
+ uint32_t product = (uint32_t)bignum->digits[i] *
495
+ (uint32_t)multiplier->digits[j] +
496
+ accumulator[i + j] + carry;
497
+ accumulator[i + j] = product % 10u;
498
+ carry = product / 10u;
499
+ }
500
+ size_t index = i + multiplier->length;
501
+ while (carry != 0u) {
502
+ uint32_t sum = accumulator[index] + carry;
503
+ accumulator[index] = sum % 10u;
504
+ carry = sum / 10u;
505
+ index += 1u;
506
+ }
507
+ }
508
+ if (!number_bignum_reserve(bignum, result_length)) {
509
+ free(accumulator);
510
+ return false;
511
+ }
512
+ for (size_t index = 0u; index < result_length; index += 1u) {
513
+ bignum->digits[index] = (uint8_t)accumulator[index];
514
+ }
515
+ bignum->length = result_length;
516
+ number_bignum_trim(bignum);
517
+ free(accumulator);
518
+ return true;
519
+ }
520
+
521
+ /* bignum += addend, both non-negative. */
522
+ static bool number_bignum_add(
523
+ NumberBignum *bignum,
524
+ const NumberBignum *addend
525
+ ) {
526
+ size_t original_length = bignum->length;
527
+ size_t length = original_length > addend->length
528
+ ? original_length
529
+ : addend->length;
530
+ if (!number_bignum_reserve(bignum, length + 1u)) return false;
531
+ unsigned carry = 0u;
532
+ for (size_t index = 0u; index < length; index += 1u) {
533
+ unsigned a = index < original_length ? bignum->digits[index] : 0u;
534
+ unsigned b = index < addend->length ? addend->digits[index] : 0u;
535
+ unsigned sum = a + b + carry;
536
+ bignum->digits[index] = (uint8_t)(sum % 10u);
537
+ carry = sum / 10u;
538
+ }
539
+ if (carry != 0u) {
540
+ bignum->digits[length] = (uint8_t)carry;
541
+ length += 1u;
542
+ }
543
+ bignum->length = length;
544
+ number_bignum_trim(bignum);
545
+ return true;
546
+ }
547
+
548
+ /* bignum -= subtrahend in place. Requires bignum >= subtrahend. */
549
+ static void number_bignum_subtract(
550
+ NumberBignum *bignum,
551
+ const NumberBignum *subtrahend
552
+ ) {
553
+ int borrow = 0;
554
+ for (size_t index = 0u; index < bignum->length; index += 1u) {
555
+ int a = (int)bignum->digits[index];
556
+ int b = index < subtrahend->length
557
+ ? (int)subtrahend->digits[index]
558
+ : 0;
559
+ int difference = a - b - borrow;
560
+ if (difference < 0) {
561
+ difference += 10;
562
+ borrow = 1;
563
+ } else {
564
+ borrow = 0;
565
+ }
566
+ bignum->digits[index] = (uint8_t)difference;
567
+ }
568
+ number_bignum_trim(bignum);
569
+ }
570
+
571
+ /*
572
+ * Divides bignum in place by a small divisor (2 to 36) and returns the
573
+ * remainder. This is ordinary base-10 long division by a small number, so
574
+ * it stays correct regardless of the divisor's relationship to the
575
+ * decimal storage base, which is what lets it extract a target-radix
576
+ * integer-part digit at a time.
577
+ */
578
+ static unsigned number_bignum_divide_small(
579
+ NumberBignum *bignum,
580
+ unsigned divisor
581
+ ) {
582
+ unsigned remainder = 0u;
583
+ for (size_t step = 0u; step < bignum->length; step += 1u) {
584
+ size_t index = bignum->length - 1u - step;
585
+ unsigned value = remainder * 10u + bignum->digits[index];
586
+ bignum->digits[index] = (uint8_t)(value / divisor);
587
+ remainder = value % divisor;
588
+ }
589
+ number_bignum_trim(bignum);
590
+ return remainder;
591
+ }
592
+
593
+ /*
594
+ * Computes quotient = floor(numerator / denominator) and remainder =
595
+ * numerator - quotient * denominator, by schoolbook long division with
596
+ * denominator's nine multiples precomputed once and reused for every
597
+ * quotient digit. denominator must be nonzero.
598
+ */
599
+ static bool number_bignum_divmod(
600
+ const NumberBignum *numerator,
601
+ const NumberBignum *denominator,
602
+ NumberBignum *quotient,
603
+ NumberBignum *remainder
604
+ ) {
605
+ NumberBignum multiples[10];
606
+ memset(multiples, 0, sizeof(multiples));
607
+ bool ok = number_bignum_from_u64(&multiples[0], 0u);
608
+ for (unsigned digit = 1u; ok && digit <= 9u; digit += 1u) {
609
+ ok = number_bignum_copy(&multiples[digit], &multiples[digit - 1u]) &&
610
+ number_bignum_add(&multiples[digit], denominator);
611
+ }
612
+ size_t capacity = numerator->length;
613
+ uint8_t *quotient_digits = ok ? malloc(capacity) : NULL;
614
+ if (ok && quotient_digits == NULL) ok = false;
615
+ if (ok) ok = number_bignum_from_u64(remainder, 0u);
616
+ for (size_t step = 0u; ok && step < numerator->length; step += 1u) {
617
+ size_t index = numerator->length - 1u - step;
618
+ NumberBignum single = {NULL, 0u, 0u};
619
+ ok = number_bignum_multiply_small(remainder, 10u) &&
620
+ number_bignum_from_u64(&single, numerator->digits[index]) &&
621
+ number_bignum_add(remainder, &single);
622
+ number_bignum_release(&single);
623
+ if (!ok) break;
624
+ unsigned chosen = 0u;
625
+ for (unsigned digit = 9u;; digit -= 1u) {
626
+ if (number_bignum_compare(&multiples[digit], remainder) <= 0) {
627
+ chosen = digit;
628
+ break;
629
+ }
630
+ if (digit == 0u) break;
631
+ }
632
+ if (chosen != 0u) {
633
+ number_bignum_subtract(remainder, &multiples[chosen]);
634
+ }
635
+ quotient_digits[step] = (uint8_t)chosen;
636
+ }
637
+ for (unsigned digit = 0u; digit <= 9u; digit += 1u) {
638
+ number_bignum_release(&multiples[digit]);
639
+ }
640
+ if (ok) {
641
+ ok = number_bignum_reserve(quotient, capacity);
642
+ if (ok) {
643
+ for (size_t index = 0u; index < capacity; index += 1u) {
644
+ quotient->digits[index] =
645
+ quotient_digits[capacity - 1u - index];
646
+ }
647
+ quotient->length = capacity;
648
+ number_bignum_trim(quotient);
649
+ }
650
+ }
651
+ free(quotient_digits);
652
+ return ok;
653
+ }
654
+
655
+ static size_t number_bignum_digit_string(
656
+ const NumberBignum *bignum,
657
+ char *out
658
+ ) {
659
+ for (size_t index = 0u; index < bignum->length; index += 1u) {
660
+ out[index] = (char)('0' + bignum->digits[bignum->length - 1u - index]);
661
+ }
662
+ return bignum->length;
663
+ }
664
+
665
+ /*
666
+ * Decomposes a finite value >= 0 into an exact mantissa and binary
667
+ * exponent: value == (double)mantissa * exp2(exponent). frexp/ldexp
668
+ * handle subnormals, so this stays exact at every magnitude a double can
669
+ * hold, including Number.MIN_VALUE.
670
+ */
671
+ static uint64_t number_decompose(double value, int *exponent) {
672
+ if (value == 0.0) {
673
+ *exponent = 0;
674
+ return 0u;
675
+ }
676
+ int raw_exponent;
677
+ double fraction = frexp(value, &raw_exponent);
678
+ uint64_t mantissa = (uint64_t)ldexp(fraction, 53);
679
+ *exponent = raw_exponent - 53;
680
+ while (mantissa != 0u && (mantissa & 1u) == 0u) {
681
+ mantissa >>= 1;
682
+ *exponent += 1;
683
+ }
684
+ return mantissa;
685
+ }
686
+
687
+ /*
688
+ * Builds numerator/denominator bignums whose exact ratio is
689
+ * value * 10^decimal_shift, for a finite value >= 0. toFixed scales by
690
+ * 10^fractionDigits; toExponential and toPrecision scale by
691
+ * 10^(precision - 1 - exponent).
692
+ */
693
+ static bool number_scaled_ratio(
694
+ double value,
695
+ int decimal_shift,
696
+ NumberBignum *numerator,
697
+ NumberBignum *denominator
698
+ ) {
699
+ int exponent;
700
+ uint64_t mantissa = number_decompose(value, &exponent);
701
+ bool ok = number_bignum_from_u64(numerator, mantissa) &&
702
+ number_bignum_from_u64(denominator, 1u);
703
+ for (int step = 0; ok && step < exponent; step += 1) {
704
+ ok = number_bignum_multiply_small(numerator, 2u);
705
+ }
706
+ for (int step = 0; ok && step < -exponent; step += 1) {
707
+ ok = number_bignum_multiply_small(denominator, 2u);
708
+ }
709
+ for (int step = 0; ok && step < decimal_shift; step += 1) {
710
+ ok = number_bignum_multiply_small(numerator, 10u);
711
+ }
712
+ for (int step = 0; ok && step < -decimal_shift; step += 1) {
713
+ ok = number_bignum_multiply_small(denominator, 10u);
714
+ }
715
+ return ok;
716
+ }
717
+
718
+ /*
719
+ * Computes n = round(value * 10^decimal_shift) as an exact bignum, with
720
+ * ties broken away from zero, matching the toFixed, toExponential, and
721
+ * toPrecision rounding rule: "as close to zero as possible; if there are
722
+ * two such n, pick the larger n". value must be finite and non-negative.
723
+ */
724
+ static bool number_round_scaled(
725
+ double value,
726
+ int decimal_shift,
727
+ NumberBignum *rounded
728
+ ) {
729
+ NumberBignum numerator = {NULL, 0u, 0u};
730
+ NumberBignum denominator = {NULL, 0u, 0u};
731
+ NumberBignum quotient = {NULL, 0u, 0u};
732
+ NumberBignum remainder = {NULL, 0u, 0u};
733
+ bool ok = number_scaled_ratio(
734
+ value,
735
+ decimal_shift,
736
+ &numerator,
737
+ &denominator
738
+ );
739
+ if (ok) {
740
+ ok = number_bignum_divmod(
741
+ &numerator,
742
+ &denominator,
743
+ &quotient,
744
+ &remainder
745
+ );
746
+ }
747
+ if (ok) {
748
+ NumberBignum doubled = {NULL, 0u, 0u};
749
+ ok = number_bignum_copy(&doubled, &remainder) &&
750
+ number_bignum_multiply_small(&doubled, 2u);
751
+ if (ok && number_bignum_compare(&doubled, &denominator) >= 0) {
752
+ NumberBignum one = {NULL, 0u, 0u};
753
+ ok = number_bignum_from_u64(&one, 1u) &&
754
+ number_bignum_add(&quotient, &one);
755
+ number_bignum_release(&one);
756
+ }
757
+ number_bignum_release(&doubled);
758
+ }
759
+ if (ok) ok = number_bignum_copy(rounded, &quotient);
760
+ number_bignum_release(&numerator);
761
+ number_bignum_release(&denominator);
762
+ number_bignum_release(&quotient);
763
+ number_bignum_release(&remainder);
764
+ return ok;
765
+ }
766
+
767
+ static bool number_bignum_pow10(NumberBignum *out, int exponent) {
768
+ bool ok = number_bignum_from_u64(out, 1u);
769
+ for (int step = 0; ok && step < exponent; step += 1) {
770
+ ok = number_bignum_multiply_small(out, 10u);
771
+ }
772
+ return ok;
773
+ }
774
+
775
+ /*
776
+ * Finds the unique integer e for which 10^e <= magnitude < 10^(e + 1),
777
+ * for a finite magnitude > 0. A floating-point log10 estimate only seeds
778
+ * the search: every candidate is confirmed by exact bignum cross-
779
+ * multiplication (10^e * denominator against numerator) rather than
780
+ * trusted, because log10 can read on the wrong side of a power-of-ten
781
+ * boundary by a margin far smaller than double precision resolves.
782
+ */
783
+ static bool number_exact_decimal_exponent(double magnitude, int *out_e) {
784
+ NumberBignum numerator = {NULL, 0u, 0u};
785
+ NumberBignum denominator = {NULL, 0u, 0u};
786
+ bool ok = number_scaled_ratio(magnitude, 0, &numerator, &denominator);
787
+ int e = (int)floor(log10(magnitude));
788
+ for (int attempt = 0; ok && attempt < 64; attempt += 1) {
789
+ /*
790
+ * Test 10^e <= numerator / denominator < 10^(e + 1) without
791
+ * division. A non-negative e scales the two bounds by the
792
+ * denominator; a negative one instead scales the numerator by
793
+ * 10^-e, which turns the same test into
794
+ * denominator <= numerator * 10^-e < denominator * 10.
795
+ */
796
+ NumberBignum low = {NULL, 0u, 0u};
797
+ NumberBignum high = {NULL, 0u, 0u};
798
+ NumberBignum scaled = {NULL, 0u, 0u};
799
+ if (e >= 0) {
800
+ ok = number_bignum_pow10(&low, e) &&
801
+ number_bignum_multiply_bignum(&low, &denominator) &&
802
+ number_bignum_pow10(&high, e + 1) &&
803
+ number_bignum_multiply_bignum(&high, &denominator) &&
804
+ number_bignum_copy(&scaled, &numerator);
805
+ } else {
806
+ ok = number_bignum_copy(&low, &denominator) &&
807
+ number_bignum_copy(&high, &denominator) &&
808
+ number_bignum_multiply_small(&high, 10u) &&
809
+ number_bignum_pow10(&scaled, -e) &&
810
+ number_bignum_multiply_bignum(&scaled, &numerator);
811
+ }
812
+ bool too_low = ok && number_bignum_compare(&scaled, &low) < 0;
813
+ bool too_high = ok && !too_low &&
814
+ number_bignum_compare(&scaled, &high) >= 0;
815
+ number_bignum_release(&low);
816
+ number_bignum_release(&high);
817
+ number_bignum_release(&scaled);
818
+ if (!ok) break;
819
+ if (too_low) {
820
+ e -= 1;
821
+ } else if (too_high) {
822
+ e += 1;
823
+ } else {
824
+ break;
825
+ }
826
+ }
827
+ number_bignum_release(&numerator);
828
+ number_bignum_release(&denominator);
829
+ *out_e = e;
830
+ return ok;
831
+ }
832
+
833
+ /*
834
+ * Computes p significant decimal digits of a positive, finite magnitude
835
+ * and the decimal exponent e of its leading digit, such that
836
+ * digit_buffer[0..p) interpreted as an integer, times 10^(e - p + 1), is
837
+ * the correctly-rounded value. Shared by toExponential's fixed-precision
838
+ * branch and toPrecision. e is found exactly first (never guessed from a
839
+ * digit count after rounding, which a power-of-ten boundary can make
840
+ * self-consistently wrong on either side); the one remaining case is
841
+ * rounding carrying p nines up to a leading 1 followed by zeros, which
842
+ * simply moves e up by one and truncates the known result.
843
+ */
844
+ static bool number_significant_digits(
845
+ double magnitude,
846
+ int p,
847
+ char digit_buffer[128],
848
+ int *out_e
849
+ ) {
850
+ int e;
851
+ if (!number_exact_decimal_exponent(magnitude, &e)) return false;
852
+ NumberBignum rounded = {NULL, 0u, 0u};
853
+ bool ok = number_round_scaled(magnitude, p - 1 - e, &rounded);
854
+ size_t count = ok ? number_bignum_digit_string(&rounded, digit_buffer) : 0u;
855
+ number_bignum_release(&rounded);
856
+ if (!ok) return false;
857
+ if ((int)count == p + 1) {
858
+ e += 1;
859
+ digit_buffer[0] = '1';
860
+ for (int index = 1; index < p; index += 1) digit_buffer[index] = '0';
861
+ count = (size_t)p;
862
+ }
863
+ *out_e = e;
864
+ return count == (size_t)p;
865
+ }
866
+
867
+ static const char number_radix_digit_glyphs[37] =
868
+ "0123456789abcdefghijklmnopqrstuvwxyz";
869
+
870
+ /*
871
+ * Formats a finite, non-negative value in the given radix (2 to 36), the
872
+ * way Number::toString's specification note permits its decimal algorithm
873
+ * to generalize. The integer part is always exact. The fractional part
874
+ * emits only the digits the double actually carries: the remaining tail
875
+ * advances alongside the distance to the rounding boundary, and the loop
876
+ * stops once the tail no longer exceeds it, raising the final digit when
877
+ * ordinary rounding selects it and the raised value still names this same
878
+ * double. Every quantity is an exact bignum rational over one shared
879
+ * power-of-two denominator, so a radix whose expansion never terminates
880
+ * stops at a digit string that reads back as this double rather than
881
+ * running to the buffer limit.
882
+ *
883
+ * This is the round-trip stopping rule, not a shortest-string search: a
884
+ * shorter string that also reads back can exist when ordinary rounding
885
+ * does not select the raised digit, and the tie test looks at the final
886
+ * digit rather than the parity of the whole coefficient, which are the
887
+ * same only in an even radix. ECMA-262 leaves a non-decimal radix
888
+ * implementation-approximated, and both choices match the decimal
889
+ * algorithm this generalizes.
890
+ */
891
+ static bool number_radix_text(
892
+ double magnitude,
893
+ unsigned radix,
894
+ char *output,
895
+ size_t capacity,
896
+ size_t *length
897
+ ) {
898
+ int exponent;
899
+ uint64_t mantissa = number_decompose(magnitude, &exponent);
900
+ /*
901
+ * The digits may stop as soon as they name this double rather than a
902
+ * neighbor, so the budget is the distance to the rounding boundary on
903
+ * each side: half the gap to the next double above, and half the gap
904
+ * to the one below. The two differ, because a power of two sits twice
905
+ * as far from its upper neighbor as from its lower one, so one shared
906
+ * budget would let a truncation cross the lower boundary. Truncating
907
+ * spends the lower budget and rounding up spends the upper one.
908
+ *
909
+ * Both gaps are exact powers of two, and only their exponents are
910
+ * used, so halving them here cannot underflow the way the value
911
+ * itself would at the smallest denormal. The gap above overflows to
912
+ * infinity only at the largest finite value, whose neighbor below is
913
+ * the same distance away.
914
+ */
915
+ double upper_gap = nextafter(magnitude, INFINITY) - magnitude;
916
+ double lower_gap = magnitude - nextafter(magnitude, 0.0);
917
+ if (!isfinite(upper_gap) || !(upper_gap > 0.0)) upper_gap = lower_gap;
918
+ if (!(lower_gap > 0.0)) lower_gap = upper_gap;
919
+ int upper_exponent = 0;
920
+ int lower_exponent = 0;
921
+ uint64_t upper_mantissa = number_decompose(upper_gap, &upper_exponent);
922
+ uint64_t lower_mantissa = number_decompose(lower_gap, &lower_exponent);
923
+ upper_exponent -= 1;
924
+ lower_exponent -= 1;
925
+ int fraction_bits = exponent < 0 ? -exponent : 0;
926
+ int shared_bits = fraction_bits;
927
+ if (upper_exponent < 0 && -upper_exponent > shared_bits) {
928
+ shared_bits = -upper_exponent;
929
+ }
930
+ if (lower_exponent < 0 && -lower_exponent > shared_bits) {
931
+ shared_bits = -lower_exponent;
932
+ }
933
+
934
+ NumberBignum integer_value = {NULL, 0u, 0u};
935
+ NumberBignum fraction = {NULL, 0u, 0u};
936
+ NumberBignum upper_budget = {NULL, 0u, 0u};
937
+ NumberBignum lower_budget = {NULL, 0u, 0u};
938
+ NumberBignum denominator = {NULL, 0u, 0u};
939
+ bool ok = number_bignum_from_u64(&integer_value, mantissa) &&
940
+ number_bignum_from_u64(&fraction, 0u) &&
941
+ number_bignum_from_u64(&denominator, 1u);
942
+ for (int step = 0; ok && step < shared_bits; step += 1) {
943
+ ok = number_bignum_multiply_small(&denominator, 2u);
944
+ }
945
+ if (ok && exponent >= 0) {
946
+ for (int step = 0; ok && step < exponent; step += 1) {
947
+ ok = number_bignum_multiply_small(&integer_value, 2u);
948
+ }
949
+ } else if (ok) {
950
+ NumberBignum split = {NULL, 0u, 0u};
951
+ NumberBignum quotient = {NULL, 0u, 0u};
952
+ ok = number_bignum_from_u64(&split, 1u);
953
+ for (int step = 0; ok && step < fraction_bits; step += 1) {
954
+ ok = number_bignum_multiply_small(&split, 2u);
955
+ }
956
+ if (ok) {
957
+ ok = number_bignum_divmod(
958
+ &integer_value,
959
+ &split,
960
+ &quotient,
961
+ &fraction
962
+ );
963
+ }
964
+ if (ok) ok = number_bignum_copy(&integer_value, &quotient);
965
+ /* Restate the fraction over the shared denominator. */
966
+ for (int step = 0; ok && step < shared_bits - fraction_bits;
967
+ step += 1) {
968
+ ok = number_bignum_multiply_small(&fraction, 2u);
969
+ }
970
+ number_bignum_release(&split);
971
+ number_bignum_release(&quotient);
972
+ }
973
+ if (ok) ok = number_bignum_from_u64(&upper_budget, upper_mantissa);
974
+ for (int step = 0; ok && step < shared_bits + upper_exponent; step += 1) {
975
+ ok = number_bignum_multiply_small(&upper_budget, 2u);
976
+ }
977
+ if (ok) ok = number_bignum_from_u64(&lower_budget, lower_mantissa);
978
+ for (int step = 0; ok && step < shared_bits + lower_exponent; step += 1) {
979
+ ok = number_bignum_multiply_small(&lower_budget, 2u);
980
+ }
981
+
982
+ char fraction_digits[1200];
983
+ size_t fraction_digit_count = 0u;
984
+ bool carry = false;
985
+ if (ok && !number_bignum_is_zero(&fraction)) {
986
+ NumberBignum multiples[36];
987
+ memset(multiples, 0, sizeof(multiples));
988
+ for (unsigned digit = 0u; ok && digit < radix; digit += 1u) {
989
+ if (digit == 0u) {
990
+ ok = number_bignum_from_u64(&multiples[0], 0u);
991
+ } else {
992
+ ok = number_bignum_copy(
993
+ &multiples[digit],
994
+ &multiples[digit - 1u]
995
+ ) &&
996
+ number_bignum_add(&multiples[digit], &denominator);
997
+ }
998
+ }
999
+ while (ok) {
1000
+ if (fraction_digit_count >= sizeof(fraction_digits)) {
1001
+ ok = false;
1002
+ break;
1003
+ }
1004
+ ok = number_bignum_multiply_small(&fraction, radix) &&
1005
+ number_bignum_multiply_small(&upper_budget, radix) &&
1006
+ number_bignum_multiply_small(&lower_budget, radix);
1007
+ if (!ok) break;
1008
+ unsigned digit = 0u;
1009
+ for (unsigned candidate = radix - 1u;; candidate -= 1u) {
1010
+ if (number_bignum_compare(
1011
+ &multiples[candidate],
1012
+ &fraction
1013
+ ) <= 0) {
1014
+ digit = candidate;
1015
+ break;
1016
+ }
1017
+ if (candidate == 0u) break;
1018
+ }
1019
+ if (digit != 0u) {
1020
+ number_bignum_subtract(&fraction, &multiples[digit]);
1021
+ }
1022
+ fraction_digits[fraction_digit_count] =
1023
+ number_radix_digit_glyphs[digit];
1024
+ fraction_digit_count += 1u;
1025
+ NumberBignum twice = {NULL, 0u, 0u};
1026
+ ok = number_bignum_copy(&twice, &fraction) &&
1027
+ number_bignum_multiply_small(&twice, 2u);
1028
+ int against_half = ok
1029
+ ? number_bignum_compare(&twice, &denominator)
1030
+ : 0;
1031
+ number_bignum_release(&twice);
1032
+ if (!ok) break;
1033
+ if (against_half > 0 ||
1034
+ (against_half == 0 && (digit & 1u) != 0u)) {
1035
+ NumberBignum raised = {NULL, 0u, 0u};
1036
+ ok = number_bignum_copy(&raised, &fraction) &&
1037
+ number_bignum_add(&raised, &upper_budget);
1038
+ bool inside = ok &&
1039
+ number_bignum_compare(&raised, &denominator) > 0;
1040
+ number_bignum_release(&raised);
1041
+ if (!ok) break;
1042
+ if (inside) {
1043
+ /* Round up, carrying through the emitted digits and,
1044
+ * if every one of them overflows, into the integer. */
1045
+ carry = true;
1046
+ while (fraction_digit_count > 0u) {
1047
+ char glyph =
1048
+ fraction_digits[fraction_digit_count - 1u];
1049
+ unsigned value = glyph <= '9'
1050
+ ? (unsigned)(glyph - '0')
1051
+ : (unsigned)(glyph - 'a') + 10u;
1052
+ if (value + 1u < radix) {
1053
+ fraction_digits[fraction_digit_count - 1u] =
1054
+ number_radix_digit_glyphs[value + 1u];
1055
+ carry = false;
1056
+ break;
1057
+ }
1058
+ fraction_digit_count -= 1u;
1059
+ }
1060
+ break;
1061
+ }
1062
+ }
1063
+ if (number_bignum_compare(&fraction, &lower_budget) < 0) break;
1064
+ }
1065
+ for (unsigned digit = 0u; digit < radix; digit += 1u) {
1066
+ number_bignum_release(&multiples[digit]);
1067
+ }
1068
+ while (fraction_digit_count > 0u &&
1069
+ fraction_digits[fraction_digit_count - 1u] == '0') {
1070
+ fraction_digit_count -= 1u;
1071
+ }
1072
+ }
1073
+ if (ok && carry) {
1074
+ NumberBignum one = {NULL, 0u, 0u};
1075
+ ok = number_bignum_from_u64(&one, 1u) &&
1076
+ number_bignum_add(&integer_value, &one);
1077
+ number_bignum_release(&one);
1078
+ }
1079
+ char integer_digits[1200];
1080
+ size_t integer_digit_count = 0u;
1081
+ if (ok && number_bignum_is_zero(&integer_value)) {
1082
+ integer_digits[0] = '0';
1083
+ integer_digit_count = 1u;
1084
+ }
1085
+ while (ok && !number_bignum_is_zero(&integer_value)) {
1086
+ if (integer_digit_count >= sizeof(integer_digits)) {
1087
+ ok = false;
1088
+ break;
1089
+ }
1090
+ unsigned digit = number_bignum_divide_small(&integer_value, radix);
1091
+ integer_digits[integer_digit_count] =
1092
+ number_radix_digit_glyphs[digit];
1093
+ integer_digit_count += 1u;
1094
+ }
1095
+ number_bignum_release(&integer_value);
1096
+ number_bignum_release(&fraction);
1097
+ number_bignum_release(&upper_budget);
1098
+ number_bignum_release(&lower_budget);
1099
+ number_bignum_release(&denominator);
1100
+ if (!ok) return false;
1101
+ size_t total = integer_digit_count +
1102
+ (fraction_digit_count > 0u ? 1u + fraction_digit_count : 0u);
1103
+ if (total >= capacity) return false;
1104
+ size_t position = 0u;
1105
+ for (size_t index = 0u; index < integer_digit_count; index += 1u) {
1106
+ output[position] = integer_digits[integer_digit_count - 1u - index];
1107
+ position += 1u;
1108
+ }
1109
+ if (fraction_digit_count > 0u) {
1110
+ output[position] = '.';
1111
+ position += 1u;
1112
+ memcpy(output + position, fraction_digits, fraction_digit_count);
1113
+ position += fraction_digit_count;
1114
+ }
1115
+ *length = position;
1116
+ return true;
1117
+ }
1118
+
1119
+ /* Assembles "d[.ddd]e[+-]EE" from already-computed significant digits. */
1120
+ static bool number_format_exponential_digits(
1121
+ const char *digit_buffer,
1122
+ size_t digit_count,
1123
+ int e,
1124
+ char *text,
1125
+ size_t capacity,
1126
+ size_t *length
1127
+ ) {
1128
+ size_t position = 0u;
1129
+ if (capacity < 1u) return false;
1130
+ text[position] = digit_buffer[0];
1131
+ position += 1u;
1132
+ if (digit_count > 1u) {
1133
+ if (position + 1u + (digit_count - 1u) > capacity) return false;
1134
+ text[position] = '.';
1135
+ position += 1u;
1136
+ memcpy(text + position, digit_buffer + 1u, digit_count - 1u);
1137
+ position += digit_count - 1u;
1138
+ }
1139
+ if (position + 2u > capacity) return false;
1140
+ text[position] = 'e';
1141
+ position += 1u;
1142
+ text[position] = e < 0 ? '-' : '+';
1143
+ position += 1u;
1144
+ char exponent_text[16];
1145
+ int written = snprintf(
1146
+ exponent_text,
1147
+ sizeof(exponent_text),
1148
+ "%d",
1149
+ e < 0 ? -e : e
1150
+ );
1151
+ if (written < 0 || position + (size_t)written > capacity) return false;
1152
+ memcpy(text + position, exponent_text, (size_t)written);
1153
+ position += (size_t)written;
1154
+ *length = position;
1155
+ return true;
1156
+ }
1157
+
1158
+ /*
1159
+ * Computes the exponential-notation body (without sign) for toExponential:
1160
+ * value 0 formats as fractionDigits (or one) zero digits with exponent 0;
1161
+ * a defined fractionDigits rounds to f + 1 significant digits; an
1162
+ * undefined fractionDigits reuses the shortest round-trip decimal digits,
1163
+ * matching the "as small a p as possible" free-precision rule.
1164
+ */
1165
+ static bool number_format_exponential(
1166
+ double magnitude,
1167
+ bool fraction_digits_defined,
1168
+ int f,
1169
+ char *text,
1170
+ size_t capacity,
1171
+ size_t *length
1172
+ ) {
1173
+ char digit_buffer[128];
1174
+ size_t digit_count;
1175
+ int e;
1176
+ if (magnitude == 0.0) {
1177
+ digit_count = fraction_digits_defined ? (size_t)f + 1u : 1u;
1178
+ for (size_t index = 0u; index < digit_count; index += 1u) {
1179
+ digit_buffer[index] = '0';
1180
+ }
1181
+ e = 0;
1182
+ } else if (fraction_digits_defined) {
1183
+ int p = f + 1;
1184
+ if (!number_significant_digits(magnitude, p, digit_buffer, &e)) {
1185
+ return false;
1186
+ }
1187
+ digit_count = (size_t)p;
1188
+ } else {
1189
+ char shortest[18];
1190
+ size_t count;
1191
+ int exponent;
1192
+ oseo_internal_number_shortest_digits(
1193
+ magnitude,
1194
+ shortest,
1195
+ &count,
1196
+ &exponent
1197
+ );
1198
+ memcpy(digit_buffer, shortest, count);
1199
+ digit_count = count;
1200
+ e = exponent - 1;
1201
+ }
1202
+ return number_format_exponential_digits(
1203
+ digit_buffer,
1204
+ digit_count,
1205
+ e,
1206
+ text,
1207
+ capacity,
1208
+ length
1209
+ );
1210
+ }
1211
+
1212
+ static OseoResult number_allocate_ascii(
1213
+ OseoContext *context,
1214
+ const char *text,
1215
+ size_t length
1216
+ ) {
1217
+ uint16_t units[2400];
1218
+ if (length > sizeof(units) / sizeof(*units)) {
1219
+ return failure(context, "OSEO2001", "Number formatting overflowed.");
1220
+ }
1221
+ for (size_t index = 0u; index < length; index += 1u) {
1222
+ units[index] = (uint16_t)(unsigned char)text[index];
1223
+ }
1224
+ return oseo_internal_allocate_string(context, units, length);
1225
+ }
1226
+
1227
+ /* thisNumberValue (21.1.3), the [[NumberData]] receiver brand check
1228
+ * shared by valueOf and every formatting method below. */
1229
+ static OseoResult number_this_value(OseoContext *context, OseoValue receiver) {
1230
+ if (is_number(receiver)) return normal(receiver);
1231
+ if (is_object(receiver) && ordinary_object(receiver)->number_data) {
1232
+ return normal(ordinary_object(receiver)->number_value);
1233
+ }
1234
+ return oseo_internal_throw_error(
1235
+ context,
1236
+ OSEO_ERROR_TYPE,
1237
+ "Number.prototype method requires a Number receiver."
1238
+ );
1239
+ }
1240
+
1241
+ /* ToIntegerOrInfinity over one already rooted input value. */
1242
+ static OseoResult number_integer_or_infinity(
1243
+ OseoContext *context,
1244
+ OseoValue value
1245
+ ) {
1246
+ OseoResult result = oseo_internal_to_number(context, value);
1247
+ if (result.status != OSEO_STATUS_NORMAL) return result;
1248
+ double number = number_value(result.value);
1249
+ if (isnan(number) || number == 0.0) number = 0.0;
1250
+ else if (isfinite(number)) number = trunc(number);
1251
+ return normal(oseo_number(number));
1252
+ }
1253
+
1254
+ /* Number.prototype.toString ( [ radix ] ), 21.1.3.6. */
1255
+ static OseoResult number_to_string(
1256
+ OseoContext *context,
1257
+ OseoValue receiver,
1258
+ size_t argument_count,
1259
+ const OseoValue *arguments
1260
+ ) {
1261
+ OseoRootFrame frame = {NULL, NULL, 0u};
1262
+ OseoResult result = oseo_roots_allocate(context, &frame, 2u);
1263
+ if (result.status != OSEO_STATUS_NORMAL) return result;
1264
+ frame.slots[0] = receiver;
1265
+ result = number_this_value(context, frame.slots[0]);
1266
+ frame.slots[1] = result.value;
1267
+ if (result.status != OSEO_STATUS_NORMAL) {
1268
+ oseo_roots_release(context, &frame);
1269
+ return result;
1270
+ }
1271
+ double x = number_value(frame.slots[1]);
1272
+ OseoValue radix_argument = argument_count > 0u
1273
+ ? arguments[0]
1274
+ : oseo_undefined();
1275
+ int radix = 10;
1276
+ if (tag_of(radix_argument) != OSEO_TAG_UNDEFINED) {
1277
+ result = number_integer_or_infinity(context, radix_argument);
1278
+ if (result.status != OSEO_STATUS_NORMAL) {
1279
+ oseo_roots_release(context, &frame);
1280
+ return result;
1281
+ }
1282
+ double radix_value = number_value(result.value);
1283
+ if (!(radix_value >= 2.0 && radix_value <= 36.0)) {
1284
+ oseo_roots_release(context, &frame);
1285
+ return oseo_internal_throw_error(
1286
+ context,
1287
+ OSEO_ERROR_RANGE,
1288
+ "Number.prototype.toString radix must be within 2..36."
1289
+ );
1290
+ }
1291
+ radix = (int)radix_value;
1292
+ }
1293
+ oseo_roots_release(context, &frame);
1294
+ char text[2400];
1295
+ if (radix == 10) {
1296
+ (void)oseo_internal_number_text(x, text, sizeof(text));
1297
+ return number_allocate_ascii(context, text, strlen(text));
1298
+ }
1299
+ if (isnan(x)) return number_allocate_ascii(context, "NaN", 3u);
1300
+ if (isinf(x)) {
1301
+ const char *infinity = signbit(x) ? "-Infinity" : "Infinity";
1302
+ return number_allocate_ascii(context, infinity, strlen(infinity));
1303
+ }
1304
+ bool negative = signbit(x) && x != 0.0;
1305
+ double magnitude = negative ? -x : x;
1306
+ size_t position = 0u;
1307
+ if (negative) {
1308
+ text[position] = '-';
1309
+ position += 1u;
1310
+ }
1311
+ size_t length = 0u;
1312
+ if (!number_radix_text(
1313
+ magnitude,
1314
+ (unsigned)radix,
1315
+ text + position,
1316
+ sizeof(text) - position,
1317
+ &length
1318
+ )) {
1319
+ return failure(context, "OSEO2001", "Number formatting failed.");
1320
+ }
1321
+ return number_allocate_ascii(context, text, position + length);
1322
+ }
1323
+
1324
+ /* Number.prototype.toFixed ( fractionDigits ), 21.1.3.3. */
1325
+ static OseoResult number_to_fixed(
1326
+ OseoContext *context,
1327
+ OseoValue receiver,
1328
+ size_t argument_count,
1329
+ const OseoValue *arguments
1330
+ ) {
1331
+ OseoRootFrame frame = {NULL, NULL, 0u};
1332
+ OseoResult result = oseo_roots_allocate(context, &frame, 2u);
1333
+ if (result.status != OSEO_STATUS_NORMAL) return result;
1334
+ frame.slots[0] = receiver;
1335
+ result = number_this_value(context, frame.slots[0]);
1336
+ frame.slots[1] = result.value;
1337
+ if (result.status != OSEO_STATUS_NORMAL) {
1338
+ oseo_roots_release(context, &frame);
1339
+ return result;
1340
+ }
1341
+ double x = number_value(frame.slots[1]);
1342
+ OseoValue digits_argument = argument_count > 0u
1343
+ ? arguments[0]
1344
+ : oseo_undefined();
1345
+ double f_value = 0.0;
1346
+ if (tag_of(digits_argument) != OSEO_TAG_UNDEFINED) {
1347
+ result = number_integer_or_infinity(context, digits_argument);
1348
+ if (result.status != OSEO_STATUS_NORMAL) {
1349
+ oseo_roots_release(context, &frame);
1350
+ return result;
1351
+ }
1352
+ f_value = number_value(result.value);
1353
+ if (!(f_value >= 0.0 && f_value <= 100.0)) {
1354
+ oseo_roots_release(context, &frame);
1355
+ return oseo_internal_throw_error(
1356
+ context,
1357
+ OSEO_ERROR_RANGE,
1358
+ "Number.prototype.toFixed digit count must be within "
1359
+ "0..100."
1360
+ );
1361
+ }
1362
+ }
1363
+ oseo_roots_release(context, &frame);
1364
+ int f = (int)f_value;
1365
+ if (isnan(x)) return number_allocate_ascii(context, "NaN", 3u);
1366
+ char text[256];
1367
+ size_t position = 0u;
1368
+ bool negative = x < 0.0;
1369
+ double magnitude = negative ? -x : x;
1370
+ if (negative) {
1371
+ text[position] = '-';
1372
+ position += 1u;
1373
+ }
1374
+ if (magnitude >= 1e21) {
1375
+ char decimal[64];
1376
+ (void)oseo_internal_number_text(magnitude, decimal, sizeof(decimal));
1377
+ size_t length = strlen(decimal);
1378
+ memcpy(text + position, decimal, length);
1379
+ position += length;
1380
+ return number_allocate_ascii(context, text, position);
1381
+ }
1382
+ NumberBignum rounded = {NULL, 0u, 0u};
1383
+ if (!number_round_scaled(magnitude, f, &rounded)) {
1384
+ return failure(context, "OSEO2001", "Number formatting failed.");
1385
+ }
1386
+ char digits[128];
1387
+ size_t digit_count = number_bignum_digit_string(&rounded, digits);
1388
+ number_bignum_release(&rounded);
1389
+ size_t pad = (f > 0 && digit_count <= (size_t)f)
1390
+ ? ((size_t)f + 1u - digit_count)
1391
+ : 0u;
1392
+ char m[160];
1393
+ size_t m_length = 0u;
1394
+ for (size_t index = 0u; index < pad; index += 1u) {
1395
+ m[m_length] = '0';
1396
+ m_length += 1u;
1397
+ }
1398
+ memcpy(m + m_length, digits, digit_count);
1399
+ m_length += digit_count;
1400
+ if (f == 0) {
1401
+ memcpy(text + position, m, m_length);
1402
+ position += m_length;
1403
+ } else {
1404
+ size_t a_length = m_length - (size_t)f;
1405
+ memcpy(text + position, m, a_length);
1406
+ position += a_length;
1407
+ text[position] = '.';
1408
+ position += 1u;
1409
+ memcpy(text + position, m + a_length, (size_t)f);
1410
+ position += (size_t)f;
1411
+ }
1412
+ return number_allocate_ascii(context, text, position);
1413
+ }
1414
+
1415
+ /* Number.prototype.toExponential ( fractionDigits ), 21.1.3.2. */
1416
+ static OseoResult number_to_exponential(
1417
+ OseoContext *context,
1418
+ OseoValue receiver,
1419
+ size_t argument_count,
1420
+ const OseoValue *arguments
1421
+ ) {
1422
+ OseoRootFrame frame = {NULL, NULL, 0u};
1423
+ OseoResult result = oseo_roots_allocate(context, &frame, 2u);
1424
+ if (result.status != OSEO_STATUS_NORMAL) return result;
1425
+ frame.slots[0] = receiver;
1426
+ result = number_this_value(context, frame.slots[0]);
1427
+ frame.slots[1] = result.value;
1428
+ if (result.status != OSEO_STATUS_NORMAL) {
1429
+ oseo_roots_release(context, &frame);
1430
+ return result;
1431
+ }
1432
+ double x = number_value(frame.slots[1]);
1433
+ OseoValue digits_argument = argument_count > 0u
1434
+ ? arguments[0]
1435
+ : oseo_undefined();
1436
+ bool digits_defined = tag_of(digits_argument) != OSEO_TAG_UNDEFINED;
1437
+ double f_value = 0.0;
1438
+ if (digits_defined) {
1439
+ result = number_integer_or_infinity(context, digits_argument);
1440
+ if (result.status != OSEO_STATUS_NORMAL) {
1441
+ oseo_roots_release(context, &frame);
1442
+ return result;
1443
+ }
1444
+ f_value = number_value(result.value);
1445
+ }
1446
+ oseo_roots_release(context, &frame);
1447
+ if (isnan(x)) return number_allocate_ascii(context, "NaN", 3u);
1448
+ bool negative = x < 0.0;
1449
+ double magnitude = negative ? -x : x;
1450
+ if (isinf(magnitude)) {
1451
+ const char *infinity = negative ? "-Infinity" : "Infinity";
1452
+ return number_allocate_ascii(context, infinity, strlen(infinity));
1453
+ }
1454
+ if (digits_defined && !(f_value >= 0.0 && f_value <= 100.0)) {
1455
+ return oseo_internal_throw_error(
1456
+ context,
1457
+ OSEO_ERROR_RANGE,
1458
+ "Number.prototype.toExponential digit count must be within "
1459
+ "0..100."
1460
+ );
1461
+ }
1462
+ int f = (int)f_value;
1463
+ char text[160];
1464
+ size_t position = 0u;
1465
+ if (negative) {
1466
+ text[position] = '-';
1467
+ position += 1u;
1468
+ }
1469
+ size_t length = 0u;
1470
+ if (!number_format_exponential(
1471
+ magnitude,
1472
+ digits_defined,
1473
+ f,
1474
+ text + position,
1475
+ sizeof(text) - position,
1476
+ &length
1477
+ )) {
1478
+ return failure(context, "OSEO2001", "Number formatting failed.");
1479
+ }
1480
+ return number_allocate_ascii(context, text, position + length);
1481
+ }
1482
+
1483
+ /* Number.prototype.toPrecision ( precision ), 21.1.3.5. */
1484
+ static OseoResult number_to_precision(
1485
+ OseoContext *context,
1486
+ OseoValue receiver,
1487
+ size_t argument_count,
1488
+ const OseoValue *arguments
1489
+ ) {
1490
+ OseoRootFrame frame = {NULL, NULL, 0u};
1491
+ OseoResult result = oseo_roots_allocate(context, &frame, 2u);
1492
+ if (result.status != OSEO_STATUS_NORMAL) return result;
1493
+ frame.slots[0] = receiver;
1494
+ result = number_this_value(context, frame.slots[0]);
1495
+ frame.slots[1] = result.value;
1496
+ if (result.status != OSEO_STATUS_NORMAL) {
1497
+ oseo_roots_release(context, &frame);
1498
+ return result;
1499
+ }
1500
+ double x = number_value(frame.slots[1]);
1501
+ OseoValue precision_argument = argument_count > 0u
1502
+ ? arguments[0]
1503
+ : oseo_undefined();
1504
+ if (tag_of(precision_argument) == OSEO_TAG_UNDEFINED) {
1505
+ oseo_roots_release(context, &frame);
1506
+ char text[64];
1507
+ (void)oseo_internal_number_text(x, text, sizeof(text));
1508
+ return number_allocate_ascii(context, text, strlen(text));
1509
+ }
1510
+ result = number_integer_or_infinity(context, precision_argument);
1511
+ if (result.status != OSEO_STATUS_NORMAL) {
1512
+ oseo_roots_release(context, &frame);
1513
+ return result;
1514
+ }
1515
+ double p_value = number_value(result.value);
1516
+ oseo_roots_release(context, &frame);
1517
+ if (isnan(x)) return number_allocate_ascii(context, "NaN", 3u);
1518
+ bool negative = x < 0.0;
1519
+ double magnitude = negative ? -x : x;
1520
+ if (isinf(magnitude)) {
1521
+ const char *infinity = negative ? "-Infinity" : "Infinity";
1522
+ return number_allocate_ascii(context, infinity, strlen(infinity));
1523
+ }
1524
+ if (!(p_value >= 1.0 && p_value <= 100.0)) {
1525
+ return oseo_internal_throw_error(
1526
+ context,
1527
+ OSEO_ERROR_RANGE,
1528
+ "Number.prototype.toPrecision precision must be within "
1529
+ "1..100."
1530
+ );
1531
+ }
1532
+ int p = (int)p_value;
1533
+ char digit_buffer[128];
1534
+ int e = 0;
1535
+ if (magnitude == 0.0) {
1536
+ for (int index = 0; index < p; index += 1) digit_buffer[index] = '0';
1537
+ } else if (!number_significant_digits(magnitude, p, digit_buffer, &e)) {
1538
+ return failure(context, "OSEO2001", "Number formatting failed.");
1539
+ }
1540
+ char text[256];
1541
+ size_t position = 0u;
1542
+ if (negative) {
1543
+ text[position] = '-';
1544
+ position += 1u;
1545
+ }
1546
+ if (e < -6 || e >= p) {
1547
+ size_t length = 0u;
1548
+ if (!number_format_exponential_digits(
1549
+ digit_buffer,
1550
+ (size_t)p,
1551
+ e,
1552
+ text + position,
1553
+ sizeof(text) - position,
1554
+ &length
1555
+ )) {
1556
+ return failure(context, "OSEO2001", "Number formatting failed.");
1557
+ }
1558
+ position += length;
1559
+ } else {
1560
+ int decimal_position = e + 1;
1561
+ if (decimal_position <= 0) {
1562
+ text[position] = '0';
1563
+ position += 1u;
1564
+ text[position] = '.';
1565
+ position += 1u;
1566
+ for (int index = 0; index < -decimal_position; index += 1) {
1567
+ text[position] = '0';
1568
+ position += 1u;
1569
+ }
1570
+ memcpy(text + position, digit_buffer, (size_t)p);
1571
+ position += (size_t)p;
1572
+ } else {
1573
+ memcpy(text + position, digit_buffer, (size_t)decimal_position);
1574
+ position += (size_t)decimal_position;
1575
+ if (decimal_position < p) {
1576
+ text[position] = '.';
1577
+ position += 1u;
1578
+ memcpy(
1579
+ text + position,
1580
+ digit_buffer + decimal_position,
1581
+ (size_t)(p - decimal_position)
1582
+ );
1583
+ position += (size_t)(p - decimal_position);
1584
+ }
1585
+ }
1586
+ }
1587
+ return number_allocate_ascii(context, text, position);
1588
+ }
1589
+
1590
+ /*
1591
+ * Number.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] ),
1592
+ * 21.1.3.4. Without the ECMA-402 Internationalization API, the base
1593
+ * specification's own recommended behavior is thisNumberValue followed by
1594
+ * ToString: the reserved parameter positions are ignored entirely rather
1595
+ * than read or coerced.
1596
+ */
1597
+ static OseoResult number_to_locale_string(
1598
+ OseoContext *context,
1599
+ OseoValue receiver
1600
+ ) {
1601
+ OseoResult result = number_this_value(context, receiver);
1602
+ if (result.status != OSEO_STATUS_NORMAL) return result;
1603
+ char text[64];
1604
+ (void)oseo_internal_number_text(
1605
+ number_value(result.value),
1606
+ text,
1607
+ sizeof(text)
1608
+ );
1609
+ return number_allocate_ascii(context, text, strlen(text));
1610
+ }
1611
+
1612
+ OseoResult oseo_internal_number_builtin_dispatch(
1613
+ OseoContext *context,
1614
+ size_t code_id,
1615
+ OseoValue callee,
1616
+ OseoValue receiver,
1617
+ size_t argument_count,
1618
+ const OseoValue *arguments,
1619
+ OseoValue new_target
1620
+ ) {
1621
+ (void)callee;
1622
+ if (code_id == OSEO_NUMBER_CONSTRUCTOR_CODE_ID) {
1623
+ return number_construct(
1624
+ context,
1625
+ new_target,
1626
+ argument_count,
1627
+ arguments,
1628
+ tag_of(new_target) != OSEO_TAG_UNDEFINED
1629
+ );
1630
+ }
1631
+ if (tag_of(new_target) != OSEO_TAG_UNDEFINED) {
1632
+ return oseo_internal_throw_error(
1633
+ context,
1634
+ OSEO_ERROR_TYPE,
1635
+ "Number method is not a constructor."
1636
+ );
1637
+ }
1638
+ if (code_id == OSEO_NUMBER_VALUE_OF_CODE_ID) {
1639
+ return number_this_value(context, receiver);
1640
+ }
1641
+ if (code_id == OSEO_NUMBER_TO_STRING_CODE_ID) {
1642
+ return number_to_string(context, receiver, argument_count, arguments);
1643
+ }
1644
+ if (code_id == OSEO_NUMBER_TO_FIXED_CODE_ID) {
1645
+ return number_to_fixed(context, receiver, argument_count, arguments);
1646
+ }
1647
+ if (code_id == OSEO_NUMBER_TO_EXPONENTIAL_CODE_ID) {
1648
+ return number_to_exponential(
1649
+ context,
1650
+ receiver,
1651
+ argument_count,
1652
+ arguments
1653
+ );
1654
+ }
1655
+ if (code_id == OSEO_NUMBER_TO_PRECISION_CODE_ID) {
1656
+ return number_to_precision(
1657
+ context,
1658
+ receiver,
1659
+ argument_count,
1660
+ arguments
1661
+ );
1662
+ }
1663
+ if (code_id == OSEO_NUMBER_TO_LOCALE_STRING_CODE_ID) {
1664
+ return number_to_locale_string(context, receiver);
1665
+ }
1666
+ if (code_id == OSEO_NUMBER_IS_FINITE_CODE_ID) {
1667
+ return number_is_finite(argument_count, arguments);
1668
+ }
1669
+ if (code_id == OSEO_NUMBER_IS_INTEGER_CODE_ID) {
1670
+ return number_is_integer(argument_count, arguments, false);
1671
+ }
1672
+ if (code_id == OSEO_NUMBER_IS_NAN_CODE_ID) {
1673
+ return number_is_nan(argument_count, arguments);
1674
+ }
1675
+ if (code_id == OSEO_NUMBER_IS_SAFE_INTEGER_CODE_ID) {
1676
+ return number_is_integer(argument_count, arguments, true);
1677
+ }
1678
+ if (code_id == OSEO_NUMBER_PARSE_FLOAT_CODE_ID) {
1679
+ return number_parse_float(context, argument_count, arguments);
1680
+ }
1681
+ if (code_id == OSEO_NUMBER_PARSE_INT_CODE_ID) {
1682
+ return number_parse_int(context, argument_count, arguments);
1683
+ }
1684
+ if (code_id == OSEO_GLOBAL_IS_FINITE_CODE_ID) {
1685
+ return global_is_finite(context, argument_count, arguments);
1686
+ }
1687
+ if (code_id == OSEO_GLOBAL_IS_NAN_CODE_ID) {
1688
+ return global_is_nan(context, argument_count, arguments);
1689
+ }
1690
+ return oseo_unknown_function(context, code_id);
1691
+ }
1692
+
1693
+ static OseoResult create_number_function(
1694
+ OseoContext *context,
1695
+ size_t code_id,
1696
+ const char *name,
1697
+ size_t length,
1698
+ OseoFunctionKind kind
1699
+ ) {
1700
+ size_t name_length = strlen(name);
1701
+ uint16_t units[31];
1702
+ if (name_length > sizeof(units) / sizeof(*units)) {
1703
+ return failure(context, "OSEO2001", "Built-in name is too long.");
1704
+ }
1705
+ for (size_t index = 0u; index < name_length; index += 1u) {
1706
+ units[index] = (uint16_t)(unsigned char)name[index];
1707
+ }
1708
+ OseoValue environment = oseo_undefined();
1709
+ OseoRootFrame frame = {NULL, &environment, 1u};
1710
+ oseo_roots_push(context, &frame);
1711
+ OseoResult result = oseo_environment_create(context, 0u);
1712
+ environment = result.value;
1713
+ if (result.status == OSEO_STATUS_NORMAL) {
1714
+ result = oseo_function_create(
1715
+ context,
1716
+ code_id,
1717
+ environment,
1718
+ units,
1719
+ name_length,
1720
+ length,
1721
+ kind,
1722
+ oseo_undefined(),
1723
+ oseo_undefined(),
1724
+ OSEO_FUNCTION_NAME_PREFIX_NONE
1725
+ );
1726
+ }
1727
+ oseo_roots_pop(context, &frame);
1728
+ return result;
1729
+ }
1730
+
1731
+ static OseoResult define_number_property(
1732
+ OseoContext *context,
1733
+ OseoValue object,
1734
+ const char *name,
1735
+ OseoValue value,
1736
+ OseoPropertyAttributes attributes
1737
+ ) {
1738
+ OseoValue slots[3] = {object, value, oseo_undefined()};
1739
+ OseoRootFrame frame = {NULL, slots, 3u};
1740
+ oseo_roots_push(context, &frame);
1741
+ OseoResult result = oseo_internal_ascii_string(context, name);
1742
+ slots[2] = result.value;
1743
+ if (result.status == OSEO_STATUS_NORMAL) {
1744
+ result = oseo_object_define(
1745
+ context,
1746
+ slots[0],
1747
+ slots[2],
1748
+ slots[1],
1749
+ attributes
1750
+ );
1751
+ }
1752
+ oseo_roots_pop(context, &frame);
1753
+ return result;
1754
+ }
1755
+
1756
+ OseoResult oseo_internal_number_intrinsic(OseoContext *context) {
1757
+ OseoValue *marker =
1758
+ &context->realm->intrinsics[OSEO_INTRINSIC_NUMBER_PARSE_INT];
1759
+ if (is_function(*marker)) {
1760
+ return normal(context->realm->intrinsics[OSEO_INTRINSIC_NUMBER]);
1761
+ }
1762
+ if (is_object(*marker)) {
1763
+ return normal(context->realm->intrinsics[OSEO_INTRINSIC_NUMBER]);
1764
+ }
1765
+ size_t entry_allocations = context->allocations;
1766
+ OseoRootFrame frame = {NULL, NULL, 0u};
1767
+ OseoResult result = oseo_roots_allocate(context, &frame, 3u);
1768
+ if (result.status != OSEO_STATUS_NORMAL) return result;
1769
+ result = oseo_internal_intrinsic(
1770
+ context,
1771
+ OSEO_INTRINSIC_OBJECT_PROTOTYPE
1772
+ );
1773
+ frame.slots[0] = result.value;
1774
+ if (result.status == OSEO_STATUS_NORMAL) {
1775
+ result = oseo_object_create(context, frame.slots[0]);
1776
+ frame.slots[0] = result.value;
1777
+ }
1778
+ if (result.status == OSEO_STATUS_NORMAL) {
1779
+ OseoOrdinaryObject *prototype = ordinary_object(frame.slots[0]);
1780
+ prototype->number_data = true;
1781
+ prototype->number_value = oseo_number(0.0);
1782
+ prototype->primitive_data = true;
1783
+ prototype->primitive_value = oseo_number(0.0);
1784
+ context->realm->intrinsics[OSEO_INTRINSIC_NUMBER_PROTOTYPE] =
1785
+ frame.slots[0];
1786
+ *marker = frame.slots[0];
1787
+ result = create_number_function(
1788
+ context,
1789
+ OSEO_NUMBER_CONSTRUCTOR_CODE_ID,
1790
+ "Number",
1791
+ 1u,
1792
+ OSEO_FUNCTION_ORDINARY
1793
+ );
1794
+ frame.slots[1] = result.value;
1795
+ }
1796
+ if (result.status == OSEO_STATUS_NORMAL) {
1797
+ context->realm->intrinsics[OSEO_INTRINSIC_NUMBER] = frame.slots[1];
1798
+ OseoFunction *constructor = function_object(frame.slots[1]);
1799
+ constructor->prototype_object = frame.slots[0];
1800
+ constructor->prototype_writable = false;
1801
+ result = define_number_property(
1802
+ context,
1803
+ frame.slots[0],
1804
+ "constructor",
1805
+ frame.slots[1],
1806
+ (OseoPropertyAttributes){true, false, true, false}
1807
+ );
1808
+ }
1809
+ if (result.status == OSEO_STATUS_NORMAL) {
1810
+ result = create_number_function(
1811
+ context,
1812
+ OSEO_NUMBER_VALUE_OF_CODE_ID,
1813
+ "valueOf",
1814
+ 0u,
1815
+ OSEO_FUNCTION_INTERNAL
1816
+ );
1817
+ frame.slots[2] = result.value;
1818
+ }
1819
+ if (result.status == OSEO_STATUS_NORMAL) {
1820
+ result = define_number_property(
1821
+ context,
1822
+ frame.slots[0],
1823
+ "valueOf",
1824
+ frame.slots[2],
1825
+ (OseoPropertyAttributes){true, false, true, false}
1826
+ );
1827
+ }
1828
+ if (result.status == OSEO_STATUS_NORMAL) {
1829
+ result = create_number_function(
1830
+ context,
1831
+ OSEO_NUMBER_TO_STRING_CODE_ID,
1832
+ "toString",
1833
+ 1u,
1834
+ OSEO_FUNCTION_INTERNAL
1835
+ );
1836
+ frame.slots[2] = result.value;
1837
+ }
1838
+ if (result.status == OSEO_STATUS_NORMAL) {
1839
+ result = define_number_property(
1840
+ context,
1841
+ frame.slots[0],
1842
+ "toString",
1843
+ frame.slots[2],
1844
+ (OseoPropertyAttributes){true, false, true, false}
1845
+ );
1846
+ }
1847
+ static const size_t prototype_method_codes[] = {
1848
+ OSEO_NUMBER_TO_FIXED_CODE_ID,
1849
+ OSEO_NUMBER_TO_EXPONENTIAL_CODE_ID,
1850
+ OSEO_NUMBER_TO_PRECISION_CODE_ID,
1851
+ OSEO_NUMBER_TO_LOCALE_STRING_CODE_ID,
1852
+ };
1853
+ static const char *const prototype_method_names[] = {
1854
+ "toFixed",
1855
+ "toExponential",
1856
+ "toPrecision",
1857
+ "toLocaleString",
1858
+ };
1859
+ static const size_t prototype_method_lengths[] = {1u, 1u, 1u, 0u};
1860
+ for (size_t index = 0u;
1861
+ result.status == OSEO_STATUS_NORMAL && index < 4u;
1862
+ index += 1u) {
1863
+ result = create_number_function(
1864
+ context,
1865
+ prototype_method_codes[index],
1866
+ prototype_method_names[index],
1867
+ prototype_method_lengths[index],
1868
+ OSEO_FUNCTION_INTERNAL
1869
+ );
1870
+ frame.slots[2] = result.value;
1871
+ if (result.status == OSEO_STATUS_NORMAL) {
1872
+ result = define_number_property(
1873
+ context,
1874
+ frame.slots[0],
1875
+ prototype_method_names[index],
1876
+ frame.slots[2],
1877
+ (OseoPropertyAttributes){true, false, true, false}
1878
+ );
1879
+ }
1880
+ }
1881
+ static const OseoIntrinsic method_intrinsics[] = {
1882
+ OSEO_INTRINSIC_NUMBER_IS_FINITE,
1883
+ OSEO_INTRINSIC_NUMBER_IS_INTEGER,
1884
+ OSEO_INTRINSIC_NUMBER_IS_NAN,
1885
+ OSEO_INTRINSIC_NUMBER_IS_SAFE_INTEGER,
1886
+ OSEO_INTRINSIC_NUMBER_PARSE_FLOAT,
1887
+ OSEO_INTRINSIC_NUMBER_PARSE_INT,
1888
+ };
1889
+ static const size_t method_codes[] = {
1890
+ OSEO_NUMBER_IS_FINITE_CODE_ID,
1891
+ OSEO_NUMBER_IS_INTEGER_CODE_ID,
1892
+ OSEO_NUMBER_IS_NAN_CODE_ID,
1893
+ OSEO_NUMBER_IS_SAFE_INTEGER_CODE_ID,
1894
+ OSEO_NUMBER_PARSE_FLOAT_CODE_ID,
1895
+ OSEO_NUMBER_PARSE_INT_CODE_ID,
1896
+ };
1897
+ static const char *const method_names[] = {
1898
+ "isFinite",
1899
+ "isInteger",
1900
+ "isNaN",
1901
+ "isSafeInteger",
1902
+ "parseFloat",
1903
+ "parseInt",
1904
+ };
1905
+ static const size_t method_lengths[] = {1u, 1u, 1u, 1u, 1u, 2u};
1906
+ for (size_t index = 0u;
1907
+ result.status == OSEO_STATUS_NORMAL && index < 6u;
1908
+ index += 1u) {
1909
+ result = create_number_function(
1910
+ context,
1911
+ method_codes[index],
1912
+ method_names[index],
1913
+ method_lengths[index],
1914
+ OSEO_FUNCTION_INTERNAL
1915
+ );
1916
+ if (result.status == OSEO_STATUS_NORMAL) {
1917
+ context->realm->intrinsics[method_intrinsics[index]] = result.value;
1918
+ result = define_number_property(
1919
+ context,
1920
+ frame.slots[1],
1921
+ method_names[index],
1922
+ result.value,
1923
+ (OseoPropertyAttributes){true, false, true, false}
1924
+ );
1925
+ }
1926
+ }
1927
+ static const char *const constant_names[] = {
1928
+ "EPSILON",
1929
+ "MAX_SAFE_INTEGER",
1930
+ "MAX_VALUE",
1931
+ "MIN_SAFE_INTEGER",
1932
+ "MIN_VALUE",
1933
+ "NaN",
1934
+ "NEGATIVE_INFINITY",
1935
+ "POSITIVE_INFINITY",
1936
+ };
1937
+ static const double constant_values[] = {
1938
+ DBL_EPSILON,
1939
+ OSEO_MAX_SAFE_INTEGER,
1940
+ DBL_MAX,
1941
+ -OSEO_MAX_SAFE_INTEGER,
1942
+ DBL_TRUE_MIN,
1943
+ NAN,
1944
+ -INFINITY,
1945
+ INFINITY,
1946
+ };
1947
+ for (size_t index = 0u;
1948
+ result.status == OSEO_STATUS_NORMAL && index < 8u;
1949
+ index += 1u) {
1950
+ result = define_number_property(
1951
+ context,
1952
+ frame.slots[1],
1953
+ constant_names[index],
1954
+ oseo_number(constant_values[index]),
1955
+ (OseoPropertyAttributes){false, false, false, false}
1956
+ );
1957
+ }
1958
+ if (result.status != OSEO_STATUS_NORMAL) {
1959
+ for (size_t index = OSEO_INTRINSIC_NUMBER_PROTOTYPE;
1960
+ index <= OSEO_INTRINSIC_NUMBER_PARSE_INT;
1961
+ index += 1u) {
1962
+ context->realm->intrinsics[index] = oseo_undefined();
1963
+ }
1964
+ } else if (context->observe_specialization) {
1965
+ context->allocations = entry_allocations;
1966
+ }
1967
+ oseo_roots_release(context, &frame);
1968
+ return result.status == OSEO_STATUS_NORMAL
1969
+ ? normal(context->realm->intrinsics[OSEO_INTRINSIC_NUMBER])
1970
+ : result;
1971
+ }
1972
+
1973
+ OseoResult oseo_internal_install_number_global(
1974
+ OseoContext *context,
1975
+ OseoValue global
1976
+ ) {
1977
+ OseoValue slots[2] = {global, oseo_undefined()};
1978
+ OseoRootFrame frame = {NULL, slots, 2u};
1979
+ oseo_roots_push(context, &frame);
1980
+ OseoResult result = oseo_internal_number_intrinsic(context);
1981
+ slots[1] = result.value;
1982
+ if (result.status == OSEO_STATUS_NORMAL) {
1983
+ result = define_number_property(
1984
+ context,
1985
+ slots[0],
1986
+ "Number",
1987
+ slots[1],
1988
+ (OseoPropertyAttributes){true, false, true, false}
1989
+ );
1990
+ }
1991
+ oseo_roots_pop(context, &frame);
1992
+ return result.status == OSEO_STATUS_NORMAL
1993
+ ? normal(slots[0])
1994
+ : result;
1995
+ }
1996
+
1997
+ OseoResult oseo_internal_global_numeric_intrinsic(
1998
+ OseoContext *context,
1999
+ OseoIntrinsic intrinsic
2000
+ ) {
2001
+ OseoValue *slot = &context->realm->intrinsics[intrinsic];
2002
+ if (is_object(*slot)) return normal(*slot);
2003
+ bool finite = intrinsic == OSEO_INTRINSIC_IS_FINITE;
2004
+ if (!finite && intrinsic != OSEO_INTRINSIC_IS_NAN) {
2005
+ return failure(
2006
+ context,
2007
+ "OSEO2001",
2008
+ "Unknown global numeric intrinsic."
2009
+ );
2010
+ }
2011
+ size_t entry_allocations = context->allocations;
2012
+ OseoResult result = create_number_function(
2013
+ context,
2014
+ finite ? OSEO_GLOBAL_IS_FINITE_CODE_ID : OSEO_GLOBAL_IS_NAN_CODE_ID,
2015
+ finite ? "isFinite" : "isNaN",
2016
+ 1u,
2017
+ OSEO_FUNCTION_INTERNAL
2018
+ );
2019
+ if (result.status != OSEO_STATUS_NORMAL) return result;
2020
+ *slot = result.value;
2021
+ if (context->observe_specialization) {
2022
+ context->allocations = entry_allocations;
2023
+ }
2024
+ return normal(*slot);
2025
+ }
2026
+
2027
+ /*
2028
+ * The four global numeric function properties of 19.2 in the order the
2029
+ * clause lists them. `isFinite` and `isNaN` are this component's own
2030
+ * lazily created intrinsics; `parseFloat` and `parseInt` are the
2031
+ * %parseFloat% and %parseInt% objects `Number.parseFloat` and
2032
+ * `Number.parseInt` already name, so the global property and the static
2033
+ * are one function.
2034
+ */
2035
+ OseoResult oseo_internal_install_global_numeric_functions(
2036
+ OseoContext *context,
2037
+ OseoValue global
2038
+ ) {
2039
+ static const OseoIntrinsic intrinsics[] = {
2040
+ OSEO_INTRINSIC_IS_FINITE,
2041
+ OSEO_INTRINSIC_IS_NAN,
2042
+ OSEO_INTRINSIC_NUMBER_PARSE_FLOAT,
2043
+ OSEO_INTRINSIC_NUMBER_PARSE_INT,
2044
+ };
2045
+ static const char *const names[] = {
2046
+ "isFinite",
2047
+ "isNaN",
2048
+ "parseFloat",
2049
+ "parseInt",
2050
+ };
2051
+ _Static_assert(
2052
+ sizeof(intrinsics) / sizeof(intrinsics[0]) ==
2053
+ sizeof(names) / sizeof(names[0]),
2054
+ "Global numeric function tables must stay aligned."
2055
+ );
2056
+ OseoValue slots[2] = {global, oseo_undefined()};
2057
+ OseoRootFrame frame = {NULL, slots, 2u};
2058
+ oseo_roots_push(context, &frame);
2059
+ OseoResult result = normal(slots[0]);
2060
+ for (size_t index = 0u;
2061
+ result.status == OSEO_STATUS_NORMAL &&
2062
+ index < sizeof(names) / sizeof(names[0]);
2063
+ index += 1u) {
2064
+ result = oseo_internal_intrinsic(context, intrinsics[index]);
2065
+ slots[1] = result.value;
2066
+ if (result.status != OSEO_STATUS_NORMAL) break;
2067
+ result = define_number_property(
2068
+ context,
2069
+ slots[0],
2070
+ names[index],
2071
+ slots[1],
2072
+ (OseoPropertyAttributes){true, false, true, false}
2073
+ );
2074
+ }
2075
+ oseo_roots_pop(context, &frame);
2076
+ return result.status == OSEO_STATUS_NORMAL ? normal(slots[0]) : result;
2077
+ }