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

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 +1677 -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 +2594 -0
  10. package/native/runtime_agent.c +1693 -0
  11. package/native/runtime_arguments.c +355 -0
  12. package/native/runtime_array.c +5742 -0
  13. package/native/runtime_array_buffer.c +1724 -0
  14. package/native/runtime_async_generator.c +948 -0
  15. package/native/runtime_atomics.c +1259 -0
  16. package/native/runtime_bigint.c +1363 -0
  17. package/native/runtime_bigint_object.c +602 -0
  18. package/native/runtime_binding.c +1005 -0
  19. package/native/runtime_boolean.c +296 -0
  20. package/native/runtime_clock.c +157 -0
  21. package/native/runtime_clock_posix.c +575 -0
  22. package/native/runtime_core.c +464 -0
  23. package/native/runtime_data_view.c +1111 -0
  24. package/native/runtime_date.c +1973 -0
  25. package/native/runtime_descriptor.c +1080 -0
  26. package/native/runtime_disposal.c +1643 -0
  27. package/native/runtime_enumeration.c +612 -0
  28. package/native/runtime_error.c +973 -0
  29. package/native/runtime_event_loop.c +629 -0
  30. package/native/runtime_function.c +3643 -0
  31. package/native/runtime_generator.c +1096 -0
  32. package/native/runtime_internal.h +5554 -0
  33. package/native/runtime_iterator.c +5355 -0
  34. package/native/runtime_json.c +1968 -0
  35. package/native/runtime_map.c +1539 -0
  36. package/native/runtime_math.c +894 -0
  37. package/native/runtime_memory.c +1341 -0
  38. package/native/runtime_module.c +860 -0
  39. package/native/runtime_number.c +2053 -0
  40. package/native/runtime_object.c +399 -0
  41. package/native/runtime_object_builtin.c +3877 -0
  42. package/native/runtime_primitive.c +2244 -0
  43. package/native/runtime_process.c +720 -0
  44. package/native/runtime_promise.c +3354 -0
  45. package/native/runtime_property.c +791 -0
  46. package/native/runtime_proxy.c +1533 -0
  47. package/native/runtime_realm.c +411 -0
  48. package/native/runtime_reflect.c +624 -0
  49. package/native/runtime_regexp.c +3495 -0
  50. package/native/runtime_regexp_matcher.c +3535 -0
  51. package/native/runtime_regexp_symbol.c +1471 -0
  52. package/native/runtime_set.c +1751 -0
  53. package/native/runtime_string.c +2862 -0
  54. package/native/runtime_string_match.c +1161 -0
  55. package/native/runtime_symbol.c +986 -0
  56. package/native/runtime_typed_array.c +5113 -0
  57. package/native/runtime_unicode_tables.h +14647 -0
  58. package/native/runtime_uri.c +676 -0
  59. package/native/runtime_weak_collection.c +1275 -0
  60. package/package.json +38 -3
@@ -0,0 +1,894 @@
1
+ /* SPDX-License-Identifier: MIT */
2
+ /* Copyright (c) 2026 Hong Minhee; see ../MIT-LICENSE.txt. */
3
+
4
+ #include "runtime_internal.h"
5
+
6
+ #include <float.h>
7
+ #include <math.h>
8
+ #include <string.h>
9
+
10
+ /*
11
+ * The Math namespace object: the eight value properties of 21.3.1, the
12
+ * thirty-seven function properties of 21.3.2, and the realm's
13
+ * pseudorandom source. Math is an ordinary object, not a function, so
14
+ * it has neither [[Call]] nor [[Construct]] and its function properties
15
+ * are ordinary built-in functions that are not constructors either.
16
+ */
17
+
18
+ /*
19
+ * One Math function property. The array order is the ordering the
20
+ * namespace object creates its properties in and the order the code
21
+ * IDs count down from `OSEO_MATH_FUNCTION_CODE_ID_LAST`, so an entry's
22
+ * index is the only identity the builder and the dispatcher share.
23
+ */
24
+ typedef enum {
25
+ OSEO_MATH_ABS = 0,
26
+ OSEO_MATH_ACOS = 1,
27
+ OSEO_MATH_ACOSH = 2,
28
+ OSEO_MATH_ASIN = 3,
29
+ OSEO_MATH_ASINH = 4,
30
+ OSEO_MATH_ATAN = 5,
31
+ OSEO_MATH_ATANH = 6,
32
+ OSEO_MATH_ATAN2 = 7,
33
+ OSEO_MATH_CBRT = 8,
34
+ OSEO_MATH_CEIL = 9,
35
+ OSEO_MATH_CLZ32 = 10,
36
+ OSEO_MATH_COS = 11,
37
+ OSEO_MATH_COSH = 12,
38
+ OSEO_MATH_EXP = 13,
39
+ OSEO_MATH_EXPM1 = 14,
40
+ OSEO_MATH_F16ROUND = 15,
41
+ OSEO_MATH_FLOOR = 16,
42
+ OSEO_MATH_FROUND = 17,
43
+ OSEO_MATH_HYPOT = 18,
44
+ OSEO_MATH_IMUL = 19,
45
+ OSEO_MATH_LOG = 20,
46
+ OSEO_MATH_LOG1P = 21,
47
+ OSEO_MATH_LOG10 = 22,
48
+ OSEO_MATH_LOG2 = 23,
49
+ OSEO_MATH_MAX = 24,
50
+ OSEO_MATH_MIN = 25,
51
+ OSEO_MATH_POW = 26,
52
+ OSEO_MATH_RANDOM = 27,
53
+ OSEO_MATH_ROUND = 28,
54
+ OSEO_MATH_SIGN = 29,
55
+ OSEO_MATH_SIN = 30,
56
+ OSEO_MATH_SINH = 31,
57
+ OSEO_MATH_SQRT = 32,
58
+ OSEO_MATH_TAN = 33,
59
+ OSEO_MATH_TANH = 34,
60
+ OSEO_MATH_TRUNC = 35,
61
+ /* ECMAScript 2026 appends sumPrecise after the earlier functions. */
62
+ OSEO_MATH_SUM_PRECISE = 36,
63
+ } OseoMathOperation;
64
+
65
+ typedef struct {
66
+ const char *name;
67
+ size_t length;
68
+ } OseoMathFunction;
69
+
70
+ static const OseoMathFunction math_functions[] = {
71
+ {"abs", 1u}, {"acos", 1u}, {"acosh", 1u}, {"asin", 1u},
72
+ {"asinh", 1u}, {"atan", 1u}, {"atanh", 1u}, {"atan2", 2u},
73
+ {"cbrt", 1u}, {"ceil", 1u}, {"clz32", 1u}, {"cos", 1u},
74
+ {"cosh", 1u}, {"exp", 1u}, {"expm1", 1u}, {"f16round", 1u},
75
+ {"floor", 1u}, {"fround", 1u}, {"hypot", 2u}, {"imul", 2u},
76
+ {"log", 1u}, {"log1p", 1u}, {"log10", 1u}, {"log2", 1u},
77
+ {"max", 2u}, {"min", 2u}, {"pow", 2u}, {"random", 0u},
78
+ {"round", 1u}, {"sign", 1u}, {"sin", 1u}, {"sinh", 1u},
79
+ {"sqrt", 1u}, {"tan", 1u}, {"tanh", 1u}, {"trunc", 1u},
80
+ {"sumPrecise", 1u},
81
+ };
82
+
83
+ _Static_assert(
84
+ sizeof(math_functions) / sizeof(math_functions[0]) ==
85
+ OSEO_MATH_FUNCTION_COUNT,
86
+ "The Math function table must match its reviewed code-ID range."
87
+ );
88
+
89
+ typedef struct {
90
+ const char *name;
91
+ double value;
92
+ } OseoMathConstant;
93
+
94
+ /*
95
+ * The eight value properties, each the Number value closest to the
96
+ * mathematical constant it names. They are non-writable,
97
+ * non-enumerable, and non-configurable.
98
+ */
99
+ static const OseoMathConstant math_constants[] = {
100
+ {"E", 2.7182818284590452354},
101
+ {"LN10", 2.302585092994046},
102
+ {"LN2", 0.6931471805599453},
103
+ {"LOG10E", 0.4342944819032518},
104
+ {"LOG2E", 1.4426950408889634},
105
+ {"PI", 3.1415926535897932},
106
+ {"SQRT1_2", 0.7071067811865476},
107
+ {"SQRT2", 1.4142135623730951},
108
+ };
109
+
110
+ #define OSEO_MATH_CONSTANT_COUNT \
111
+ (sizeof(math_constants) / sizeof(math_constants[0]))
112
+
113
+ /*
114
+ * Round one finite nonzero magnitude to the nearest value of a binary
115
+ * interchange format with `significand_bits` significant bits and
116
+ * `minimum_quantum` as the exponent of its subnormal quantum, with ties
117
+ * to even. The scaled operand stays below 2**significand_bits + 1, so
118
+ * both the scaling and the comparison are exact binary64 arithmetic and
119
+ * no narrowing floating conversion happens. A magnitude that rounds
120
+ * past `maximum_finite` becomes an infinity.
121
+ */
122
+ static double round_to_binary(
123
+ double magnitude,
124
+ int significand_bits,
125
+ int minimum_quantum,
126
+ double maximum_finite
127
+ ) {
128
+ int exponent;
129
+ (void)frexp(magnitude, &exponent);
130
+ int quantum = exponent - significand_bits;
131
+ if (quantum < minimum_quantum) quantum = minimum_quantum;
132
+ double scaled = ldexp(magnitude, -quantum);
133
+ double lower = floor(scaled);
134
+ double fraction = scaled - lower;
135
+ double rounded;
136
+ if (fraction > 0.5) {
137
+ rounded = lower + 1.0;
138
+ } else if (fraction < 0.5) {
139
+ rounded = lower;
140
+ } else {
141
+ rounded = fmod(lower, 2.0) == 0.0 ? lower : lower + 1.0;
142
+ }
143
+ double result = ldexp(rounded, quantum);
144
+ return result > maximum_finite ? (double)INFINITY : result;
145
+ }
146
+
147
+ /* Math.fround and Math.f16round over one already converted Number. */
148
+ static double math_round_to_format(double value, bool half) {
149
+ if (isnan(value) || isinf(value) || value == 0.0) return value;
150
+ double magnitude = round_to_binary(
151
+ fabs(value),
152
+ half ? 11 : 24,
153
+ half ? -24 : -149,
154
+ half ? 65504.0 : (double)FLT_MAX
155
+ );
156
+ return value < 0.0 ? -magnitude : magnitude;
157
+ }
158
+
159
+ /*
160
+ * Math.round, 21.3.2.28. The specification rounds to the closest
161
+ * integral Number and breaks a tie toward positive infinity, which is
162
+ * not what C `round` does for a negative tie, and it keeps a negative
163
+ * operand above -0.5 at -0. Comparing the fractional part against one
164
+ * half decides both, and an operand whose magnitude is at least 2**52
165
+ * is already integral, so its fractional part is exactly zero.
166
+ */
167
+ static double math_round(double value) {
168
+ if (isnan(value) || isinf(value) || value == 0.0) return value;
169
+ if (value > 0.0 && value < 0.5) return 0.0;
170
+ if (value < 0.0 && value >= -0.5) return -0.0;
171
+ double lower = floor(value);
172
+ return value - lower < 0.5 ? lower : lower + 1.0;
173
+ }
174
+
175
+ /* Math.sign, 21.3.2.29, which preserves both signed zeroes and NaN. */
176
+ static double math_sign(double value) {
177
+ if (isnan(value) || value == 0.0) return value;
178
+ return value < 0.0 ? -1.0 : 1.0;
179
+ }
180
+
181
+ /* Math.clz32, 21.3.2.11, over the operand's ToUint32 bit pattern. */
182
+ static double math_clz32(double value) {
183
+ uint32_t bits = oseo_internal_number_to_uint32(value);
184
+ if (bits == 0u) return 32.0;
185
+ int count = 0;
186
+ while ((bits & UINT32_C(0x80000000)) == 0u) {
187
+ bits <<= 1u;
188
+ count += 1;
189
+ }
190
+ return (double)count;
191
+ }
192
+
193
+ /* Math.imul, 21.3.2.20: the signed reading of a wrapped 32-bit product. */
194
+ static double math_imul(double left, double right) {
195
+ uint32_t product = oseo_internal_number_to_uint32(left) *
196
+ oseo_internal_number_to_uint32(right);
197
+ return product >= UINT32_C(0x80000000)
198
+ ? (double)((int64_t)product - INT64_C(4294967296))
199
+ : (double)product;
200
+ }
201
+
202
+ /*
203
+ * The realm's xorshift128+ draw. The state is the two words the context
204
+ * mixed from this realm's initialization ordinal, so the sequence is
205
+ * uniform, identical on every supported target, and distinct from every
206
+ * other realm's.
207
+ */
208
+ static double math_random(OseoContext *context) {
209
+ uint64_t first = context->realm->random_state[0];
210
+ const uint64_t second = context->realm->random_state[1];
211
+ context->realm->random_state[0] = second;
212
+ first ^= first << 23u;
213
+ first ^= first >> 17u;
214
+ first ^= second;
215
+ first ^= second >> 26u;
216
+ context->realm->random_state[1] = first;
217
+ /* The high 53 bits of the sum scale exactly onto [0, 1). */
218
+ return (double)((first + second) >> 11u) * (1.0 / 9007199254740992.0);
219
+ }
220
+
221
+ /* Every Math function property whose result needs one operand only. */
222
+ static double math_unary_value(size_t operation, double value) {
223
+ switch ((OseoMathOperation)operation) {
224
+ case OSEO_MATH_ABS: return fabs(value);
225
+ case OSEO_MATH_ACOS: return acos(value);
226
+ case OSEO_MATH_ACOSH: return acosh(value);
227
+ case OSEO_MATH_ASIN: return asin(value);
228
+ case OSEO_MATH_ASINH: return asinh(value);
229
+ case OSEO_MATH_ATAN: return atan(value);
230
+ case OSEO_MATH_ATANH: return atanh(value);
231
+ case OSEO_MATH_CBRT: return cbrt(value);
232
+ case OSEO_MATH_CEIL: return ceil(value);
233
+ case OSEO_MATH_CLZ32: return math_clz32(value);
234
+ case OSEO_MATH_COS: return cos(value);
235
+ case OSEO_MATH_COSH: return cosh(value);
236
+ case OSEO_MATH_EXP: return exp(value);
237
+ case OSEO_MATH_EXPM1: return expm1(value);
238
+ case OSEO_MATH_F16ROUND: return math_round_to_format(value, true);
239
+ case OSEO_MATH_FLOOR: return floor(value);
240
+ case OSEO_MATH_FROUND: return math_round_to_format(value, false);
241
+ case OSEO_MATH_LOG: return log(value);
242
+ case OSEO_MATH_LOG1P: return log1p(value);
243
+ case OSEO_MATH_LOG10: return log10(value);
244
+ case OSEO_MATH_LOG2: return log2(value);
245
+ case OSEO_MATH_ROUND: return math_round(value);
246
+ case OSEO_MATH_SIGN: return math_sign(value);
247
+ case OSEO_MATH_SIN: return sin(value);
248
+ case OSEO_MATH_SINH: return sinh(value);
249
+ case OSEO_MATH_SQRT: return sqrt(value);
250
+ case OSEO_MATH_TAN: return tan(value);
251
+ case OSEO_MATH_TANH: return tanh(value);
252
+ case OSEO_MATH_TRUNC: return trunc(value);
253
+ default: return NAN;
254
+ }
255
+ }
256
+
257
+ static bool math_is_unary(size_t operation) {
258
+ switch ((OseoMathOperation)operation) {
259
+ case OSEO_MATH_ATAN2:
260
+ case OSEO_MATH_HYPOT:
261
+ case OSEO_MATH_IMUL:
262
+ case OSEO_MATH_MAX:
263
+ case OSEO_MATH_MIN:
264
+ case OSEO_MATH_POW:
265
+ case OSEO_MATH_RANDOM:
266
+ case OSEO_MATH_SUM_PRECISE:
267
+ return false;
268
+ default:
269
+ return true;
270
+ }
271
+ }
272
+
273
+ /*
274
+ * ToNumber over one argument position, reading `undefined` when the
275
+ * call supplied no argument there. The operand stays rooted across the
276
+ * conversion because a ToPrimitive method can allocate and collect.
277
+ */
278
+ static OseoResult math_operand(
279
+ OseoContext *context,
280
+ size_t argument_count,
281
+ const OseoValue *arguments,
282
+ size_t index,
283
+ double *value
284
+ ) {
285
+ OseoValue slot =
286
+ index < argument_count ? arguments[index] : oseo_undefined();
287
+ OseoRootFrame frame = {NULL, &slot, 1u};
288
+ oseo_roots_push(context, &frame);
289
+ OseoResult result = oseo_internal_to_number(context, slot);
290
+ oseo_roots_pop(context, &frame);
291
+ if (result.status != OSEO_STATUS_NORMAL) return result;
292
+ *value = number_value(result.value);
293
+ return result;
294
+ }
295
+
296
+ /*
297
+ * Convert every argument of a variadic Math function in argument order,
298
+ * replacing each rooted operand with its Number. Every conversion can
299
+ * run user code, so the whole list stays rooted until the last one
300
+ * completes.
301
+ */
302
+ static OseoResult math_operand_list(
303
+ OseoContext *context,
304
+ size_t argument_count,
305
+ const OseoRootFrame *frame
306
+ ) {
307
+ OseoResult result = normal(oseo_undefined());
308
+ for (size_t index = 0u; index < argument_count; index += 1u) {
309
+ result = oseo_internal_to_number(context, frame->slots[index]);
310
+ if (result.status != OSEO_STATUS_NORMAL) return result;
311
+ frame->slots[index] = result.value;
312
+ }
313
+ return result;
314
+ }
315
+
316
+ /*
317
+ * Math.max and Math.min, 21.3.2.24 and 21.3.2.25. Every argument is
318
+ * converted first, a NaN among them wins over every comparison, and
319
+ * +0 is treated as larger than -0 in both directions.
320
+ */
321
+ static double math_extremum(
322
+ const OseoRootFrame *frame,
323
+ size_t argument_count,
324
+ bool maximum
325
+ ) {
326
+ double best = maximum ? -(double)INFINITY : (double)INFINITY;
327
+ for (size_t index = 0u; index < argument_count; index += 1u) {
328
+ double value = number_value(frame->slots[index]);
329
+ if (isnan(value)) return NAN;
330
+ if (value == 0.0 && best == 0.0) {
331
+ bool value_negative = signbit(value) != 0;
332
+ bool best_negative = signbit(best) != 0;
333
+ if (maximum ? (best_negative && !value_negative)
334
+ : (!best_negative && value_negative)) {
335
+ best = value;
336
+ }
337
+ continue;
338
+ }
339
+ if (maximum ? value > best : value < best) best = value;
340
+ }
341
+ return best;
342
+ }
343
+
344
+ /*
345
+ * Math.hypot, 21.3.2.18. An infinite operand wins over a NaN one, and a
346
+ * list of zeroes is +0. The finite case scales by the largest magnitude
347
+ * so a representable result cannot overflow an intermediate square.
348
+ */
349
+ static double math_hypot(
350
+ const OseoRootFrame *frame,
351
+ size_t argument_count
352
+ ) {
353
+ bool has_nan = false;
354
+ double largest = 0.0;
355
+ for (size_t index = 0u; index < argument_count; index += 1u) {
356
+ double value = number_value(frame->slots[index]);
357
+ if (isinf(value)) return (double)INFINITY;
358
+ if (isnan(value)) has_nan = true;
359
+ else if (fabs(value) > largest) largest = fabs(value);
360
+ }
361
+ if (has_nan) return NAN;
362
+ if (largest == 0.0) return 0.0;
363
+ double total = 0.0;
364
+ for (size_t index = 0u; index < argument_count; index += 1u) {
365
+ double scaled = number_value(frame->slots[index]) / largest;
366
+ total += scaled * scaled;
367
+ }
368
+ return largest * sqrt(total);
369
+ }
370
+
371
+ static OseoResult math_variadic(
372
+ OseoContext *context,
373
+ size_t operation,
374
+ size_t argument_count,
375
+ const OseoValue *arguments
376
+ ) {
377
+ if (argument_count > 0u && arguments == NULL) {
378
+ return failure(context, "OSEO2001", "Math arguments are missing.");
379
+ }
380
+ OseoRootFrame frame = {NULL, NULL, 0u};
381
+ /* One slot per argument and no more, so the count cannot overflow. */
382
+ OseoResult result =
383
+ oseo_roots_allocate(context, &frame, argument_count);
384
+ if (result.status != OSEO_STATUS_NORMAL) return result;
385
+ for (size_t index = 0u; index < argument_count; index += 1u) {
386
+ frame.slots[index] = arguments[index];
387
+ }
388
+ result = math_operand_list(context, argument_count, &frame);
389
+ if (result.status == OSEO_STATUS_NORMAL) {
390
+ double value = operation == OSEO_MATH_HYPOT
391
+ ? math_hypot(&frame, argument_count)
392
+ : math_extremum(
393
+ &frame,
394
+ argument_count,
395
+ operation == OSEO_MATH_MAX
396
+ );
397
+ result = normal(oseo_number(value));
398
+ }
399
+ oseo_roots_release(context, &frame);
400
+ return result;
401
+ }
402
+
403
+ /*
404
+ * Math.sumPrecise accumulates every finite operand exactly. A binary64
405
+ * value is an integer multiple of 2**-1074 below 2**1024, so the sum of
406
+ * fewer than 2**53 of them is an integer multiple of 2**-1074 below
407
+ * 2**1077 in magnitude. The accumulator holds that integer in two's
408
+ * complement over enough 64-bit limbs for 2**2151 plus a sign bit, so
409
+ * no addition can overflow and the only rounding is the final one.
410
+ */
411
+ #define OSEO_SUM_PRECISE_LIMBS ((size_t)35u)
412
+
413
+ typedef struct {
414
+ uint64_t limbs[OSEO_SUM_PRECISE_LIMBS];
415
+ } OseoExactSum;
416
+
417
+ /* Add or subtract `magnitude * 2**shift` units of 2**-1074. */
418
+ static void exact_sum_add(
419
+ OseoExactSum *sum,
420
+ uint64_t magnitude,
421
+ unsigned shift,
422
+ bool negative
423
+ ) {
424
+ size_t index = shift / 64u;
425
+ unsigned offset = shift % 64u;
426
+ uint64_t parts[2] = {
427
+ magnitude << offset,
428
+ offset == 0u ? 0u : magnitude >> (64u - offset),
429
+ };
430
+ uint64_t carry = 0u;
431
+ for (size_t limb = index; limb < OSEO_SUM_PRECISE_LIMBS; limb += 1u) {
432
+ bool in_parts = limb - index < 2u;
433
+ uint64_t part = in_parts ? parts[limb - index] : 0u;
434
+ if (!in_parts && carry == 0u) break;
435
+ uint64_t before = sum->limbs[limb];
436
+ if (negative) {
437
+ uint64_t after = before - part - carry;
438
+ carry = (before < part || before - part < carry) ? 1u : 0u;
439
+ sum->limbs[limb] = after;
440
+ } else {
441
+ uint64_t after = before + part + carry;
442
+ carry = (after < before || (carry != 0u && after == before))
443
+ ? 1u
444
+ : 0u;
445
+ sum->limbs[limb] = after;
446
+ }
447
+ }
448
+ }
449
+
450
+ static void exact_sum_add_number(OseoExactSum *sum, double value) {
451
+ uint64_t bits;
452
+ memcpy(&bits, &value, sizeof(bits));
453
+ uint64_t fraction = bits & ((UINT64_C(1) << 52) - 1u);
454
+ unsigned exponent = (unsigned)((bits >> 52) & 0x7ffu);
455
+ bool negative = (bits >> 63) != 0u;
456
+ if (exponent == 0u) {
457
+ exact_sum_add(sum, fraction, 0u, negative);
458
+ } else {
459
+ exact_sum_add(
460
+ sum,
461
+ fraction | (UINT64_C(1) << 52),
462
+ exponent - 1u,
463
+ negative
464
+ );
465
+ }
466
+ }
467
+
468
+ static bool exact_sum_bit(const OseoExactSum *sum, size_t bit) {
469
+ return ((sum->limbs[bit / 64u] >> (bit % 64u)) & 1u) != 0u;
470
+ }
471
+
472
+ /*
473
+ * Round the exact sum to the nearest Number with ties to even. A sum
474
+ * at or beyond 2**1024 - 2**970 rounds to an infinity, which is what
475
+ * the final scaling produces once the rounded significand reaches the
476
+ * binary64 overflow exponent. An exact zero is +0.
477
+ */
478
+ static double exact_sum_value(OseoExactSum *sum) {
479
+ bool negative =
480
+ (sum->limbs[OSEO_SUM_PRECISE_LIMBS - 1u] >> 63) != 0u;
481
+ if (negative) {
482
+ uint64_t carry = 1u;
483
+ for (size_t limb = 0u; limb < OSEO_SUM_PRECISE_LIMBS; limb += 1u) {
484
+ uint64_t inverted = ~sum->limbs[limb];
485
+ sum->limbs[limb] = inverted + carry;
486
+ carry = carry != 0u && sum->limbs[limb] == 0u ? 1u : 0u;
487
+ }
488
+ }
489
+ size_t top = OSEO_SUM_PRECISE_LIMBS * 64u;
490
+ while (top > 0u && !exact_sum_bit(sum, top - 1u)) top -= 1u;
491
+ if (top == 0u) return 0.0;
492
+ double magnitude;
493
+ if (top <= 53u) {
494
+ /* Below 2**53 units the value is exact as a subnormal or the
495
+ * smallest normal binade. */
496
+ magnitude = ldexp((double)sum->limbs[0], -1074);
497
+ } else {
498
+ size_t shift = top - 53u;
499
+ uint64_t significand = 0u;
500
+ for (size_t bit = 0u; bit < 53u; bit += 1u) {
501
+ if (exact_sum_bit(sum, shift + bit)) {
502
+ significand |= UINT64_C(1) << bit;
503
+ }
504
+ }
505
+ bool round = exact_sum_bit(sum, shift - 1u);
506
+ bool sticky = false;
507
+ for (size_t limb = 0u; !sticky && limb * 64u < shift - 1u;
508
+ limb += 1u) {
509
+ size_t low = shift - 1u - limb * 64u;
510
+ uint64_t mask = low >= 64u
511
+ ? ~UINT64_C(0)
512
+ : (UINT64_C(1) << low) - 1u;
513
+ sticky = (sum->limbs[limb] & mask) != 0u;
514
+ }
515
+ if (round && (sticky || (significand & 1u) != 0u)) {
516
+ significand += 1u;
517
+ if (significand == UINT64_C(1) << 53) {
518
+ significand >>= 1;
519
+ shift += 1u;
520
+ }
521
+ }
522
+ /* The shift stays below 2,200, so the int conversion is exact. */
523
+ magnitude = ldexp((double)significand, (int)shift - 1074);
524
+ }
525
+ return negative ? -magnitude : magnitude;
526
+ }
527
+
528
+ /* IteratorClose(iterator, throw) for an error raised by this function. */
529
+ static OseoResult sum_precise_close(
530
+ OseoContext *context,
531
+ OseoValue iterator,
532
+ OseoResult abrupt
533
+ ) {
534
+ if (abrupt.status != OSEO_STATUS_THROW || context->has_diagnostic) {
535
+ return abrupt;
536
+ }
537
+ OseoValue slots[2] = {iterator, abrupt.value};
538
+ OseoRootFrame frame = {NULL, slots, 2u};
539
+ oseo_roots_push(context, &frame);
540
+ oseo_context_clear_language_error(context);
541
+ OseoResult closed = oseo_iterator_close(context, slots[0], true);
542
+ OseoResult result = closed.status == OSEO_STATUS_NORMAL
543
+ ? (OseoResult){OSEO_STATUS_THROW, slots[1]}
544
+ : closed;
545
+ oseo_roots_pop(context, &frame);
546
+ return result;
547
+ }
548
+
549
+ typedef enum {
550
+ OSEO_SUM_MINUS_ZERO,
551
+ OSEO_SUM_FINITE,
552
+ OSEO_SUM_PLUS_INFINITY,
553
+ OSEO_SUM_MINUS_INFINITY,
554
+ OSEO_SUM_NOT_A_NUMBER,
555
+ } OseoSumPreciseState;
556
+
557
+ /*
558
+ * Math.sumPrecise, 21.3.2.34. The iterable is required to be neither
559
+ * undefined nor null before GetIterator, every value must already be a
560
+ * Number, and a non-Number closes the iterator before the TypeError
561
+ * propagates. NaN and opposite infinities make the result NaN, but the
562
+ * iteration still runs to completion so every later value is checked.
563
+ */
564
+ static OseoResult math_sum_precise(
565
+ OseoContext *context,
566
+ size_t argument_count,
567
+ const OseoValue *arguments
568
+ ) {
569
+ OseoValue items =
570
+ argument_count > 0u ? arguments[0] : oseo_undefined();
571
+ uint64_t items_tag = tag_of(items);
572
+ if (items_tag == OSEO_TAG_UNDEFINED || items_tag == OSEO_TAG_NULL) {
573
+ return oseo_internal_throw_error(
574
+ context,
575
+ OSEO_ERROR_TYPE,
576
+ "Math.sumPrecise requires an iterable."
577
+ );
578
+ }
579
+ OseoValue slots[3] = {items, oseo_undefined(), oseo_undefined()};
580
+ OseoRootFrame frame = {NULL, slots, 3u};
581
+ oseo_roots_push(context, &frame);
582
+ OseoValue next_method = oseo_undefined();
583
+ OseoResult result = oseo_iterator_get(context, slots[0], &next_method);
584
+ slots[0] = result.value;
585
+ if (result.status == OSEO_STATUS_NORMAL) slots[1] = next_method;
586
+ OseoExactSum sum;
587
+ memset(&sum, 0, sizeof(sum));
588
+ OseoSumPreciseState state = OSEO_SUM_MINUS_ZERO;
589
+ uint64_t count = 0u;
590
+ bool done = false;
591
+ while (result.status == OSEO_STATUS_NORMAL && !done) {
592
+ result = oseo_iterator_next(
593
+ context,
594
+ slots[0],
595
+ slots[1],
596
+ &slots[2],
597
+ &done
598
+ );
599
+ if (result.status != OSEO_STATUS_NORMAL || done) break;
600
+ count += 1u;
601
+ if (count >= UINT64_C(9007199254740992)) {
602
+ result = sum_precise_close(
603
+ context,
604
+ slots[0],
605
+ oseo_internal_throw_error(
606
+ context,
607
+ OSEO_ERROR_RANGE,
608
+ "Math.sumPrecise received too many values."
609
+ )
610
+ );
611
+ break;
612
+ }
613
+ if (!is_number(slots[2])) {
614
+ result = sum_precise_close(
615
+ context,
616
+ slots[0],
617
+ oseo_internal_throw_error(
618
+ context,
619
+ OSEO_ERROR_TYPE,
620
+ "Math.sumPrecise values must be Numbers."
621
+ )
622
+ );
623
+ break;
624
+ }
625
+ double value = number_value(slots[2]);
626
+ if (state == OSEO_SUM_NOT_A_NUMBER) continue;
627
+ if (isnan(value)) {
628
+ state = OSEO_SUM_NOT_A_NUMBER;
629
+ } else if (isinf(value)) {
630
+ OseoSumPreciseState same = value > 0.0
631
+ ? OSEO_SUM_PLUS_INFINITY
632
+ : OSEO_SUM_MINUS_INFINITY;
633
+ OseoSumPreciseState opposite = value > 0.0
634
+ ? OSEO_SUM_MINUS_INFINITY
635
+ : OSEO_SUM_PLUS_INFINITY;
636
+ state = state == opposite ? OSEO_SUM_NOT_A_NUMBER : same;
637
+ } else if (!(value == 0.0 && signbit(value)) &&
638
+ (state == OSEO_SUM_MINUS_ZERO ||
639
+ state == OSEO_SUM_FINITE)) {
640
+ state = OSEO_SUM_FINITE;
641
+ exact_sum_add_number(&sum, value);
642
+ }
643
+ }
644
+ oseo_roots_pop(context, &frame);
645
+ if (result.status != OSEO_STATUS_NORMAL) return result;
646
+ switch (state) {
647
+ case OSEO_SUM_NOT_A_NUMBER:
648
+ return normal(oseo_number(NAN));
649
+ case OSEO_SUM_PLUS_INFINITY:
650
+ return normal(oseo_number((double)INFINITY));
651
+ case OSEO_SUM_MINUS_INFINITY:
652
+ return normal(oseo_number(-(double)INFINITY));
653
+ case OSEO_SUM_MINUS_ZERO:
654
+ return normal(oseo_number(-0.0));
655
+ case OSEO_SUM_FINITE:
656
+ break;
657
+ }
658
+ return normal(oseo_number(exact_sum_value(&sum)));
659
+ }
660
+
661
+ static OseoResult math_call(
662
+ OseoContext *context,
663
+ size_t operation,
664
+ size_t argument_count,
665
+ const OseoValue *arguments
666
+ ) {
667
+ if (operation == OSEO_MATH_RANDOM) {
668
+ return normal(oseo_number(math_random(context)));
669
+ }
670
+ if (operation == OSEO_MATH_SUM_PRECISE) {
671
+ if (argument_count > 0u && arguments == NULL) {
672
+ return failure(
673
+ context,
674
+ "OSEO2001",
675
+ "Math arguments are missing."
676
+ );
677
+ }
678
+ return math_sum_precise(context, argument_count, arguments);
679
+ }
680
+ if (operation == OSEO_MATH_HYPOT || operation == OSEO_MATH_MAX ||
681
+ operation == OSEO_MATH_MIN) {
682
+ return math_variadic(context, operation, argument_count, arguments);
683
+ }
684
+ if (argument_count > 0u && arguments == NULL) {
685
+ return failure(context, "OSEO2001", "Math arguments are missing.");
686
+ }
687
+ double first = 0.0;
688
+ OseoResult result =
689
+ math_operand(context, argument_count, arguments, 0u, &first);
690
+ if (result.status != OSEO_STATUS_NORMAL) return result;
691
+ if (math_is_unary(operation)) {
692
+ return normal(oseo_number(math_unary_value(operation, first)));
693
+ }
694
+ double second = 0.0;
695
+ result = math_operand(context, argument_count, arguments, 1u, &second);
696
+ if (result.status != OSEO_STATUS_NORMAL) return result;
697
+ if (operation == OSEO_MATH_ATAN2) {
698
+ return normal(oseo_number(atan2(first, second)));
699
+ }
700
+ if (operation == OSEO_MATH_IMUL) {
701
+ return normal(oseo_number(math_imul(first, second)));
702
+ }
703
+ return normal(
704
+ oseo_number(oseo_internal_number_exponentiate(first, second))
705
+ );
706
+ }
707
+
708
+ OseoResult oseo_internal_math_builtin_dispatch(
709
+ OseoContext *context,
710
+ size_t code_id,
711
+ OseoValue callee,
712
+ OseoValue receiver,
713
+ size_t argument_count,
714
+ const OseoValue *arguments,
715
+ OseoValue new_target
716
+ ) {
717
+ (void)callee;
718
+ (void)receiver;
719
+ if (code_id < OSEO_MATH_FUNCTION_CODE_ID_FIRST ||
720
+ code_id > OSEO_MATH_FUNCTION_CODE_ID_LAST) {
721
+ return oseo_unknown_function(context, code_id);
722
+ }
723
+ if (tag_of(new_target) != OSEO_TAG_UNDEFINED) {
724
+ return oseo_internal_throw_error(
725
+ context,
726
+ OSEO_ERROR_TYPE,
727
+ "Math function is not a constructor."
728
+ );
729
+ }
730
+ size_t operation = OSEO_MATH_FUNCTION_CODE_ID_LAST - code_id;
731
+ return math_call(context, operation, argument_count, arguments);
732
+ }
733
+
734
+ static OseoResult create_math_function(
735
+ OseoContext *context,
736
+ size_t operation
737
+ ) {
738
+ const OseoMathFunction *entry = &math_functions[operation];
739
+ size_t name_length = strlen(entry->name);
740
+ uint16_t units[16];
741
+ if (name_length > sizeof(units) / sizeof(*units)) {
742
+ return failure(context, "OSEO2001", "Built-in name is too long.");
743
+ }
744
+ for (size_t index = 0u; index < name_length; index += 1u) {
745
+ units[index] = (uint16_t)(unsigned char)entry->name[index];
746
+ }
747
+ OseoValue environment = oseo_undefined();
748
+ OseoRootFrame frame = {NULL, &environment, 1u};
749
+ oseo_roots_push(context, &frame);
750
+ OseoResult result = oseo_environment_create(context, 0u);
751
+ environment = result.value;
752
+ if (result.status == OSEO_STATUS_NORMAL) {
753
+ result = oseo_function_create(
754
+ context,
755
+ OSEO_MATH_FUNCTION_CODE_ID_LAST - operation,
756
+ environment,
757
+ units,
758
+ name_length,
759
+ entry->length,
760
+ OSEO_FUNCTION_INTERNAL,
761
+ oseo_undefined(),
762
+ oseo_undefined(),
763
+ OSEO_FUNCTION_NAME_PREFIX_NONE
764
+ );
765
+ }
766
+ oseo_roots_pop(context, &frame);
767
+ return result;
768
+ }
769
+
770
+ static OseoResult define_math_property(
771
+ OseoContext *context,
772
+ OseoValue object,
773
+ const char *name,
774
+ OseoValue value,
775
+ OseoPropertyAttributes attributes
776
+ ) {
777
+ OseoValue slots[3] = {object, value, oseo_undefined()};
778
+ OseoRootFrame frame = {NULL, slots, 3u};
779
+ oseo_roots_push(context, &frame);
780
+ OseoResult result = oseo_internal_ascii_string(context, name);
781
+ slots[2] = result.value;
782
+ if (result.status == OSEO_STATUS_NORMAL) {
783
+ result = oseo_object_define(
784
+ context,
785
+ slots[0],
786
+ slots[2],
787
+ slots[1],
788
+ attributes
789
+ );
790
+ }
791
+ oseo_roots_pop(context, &frame);
792
+ return result;
793
+ }
794
+
795
+ OseoResult oseo_internal_math_intrinsic(OseoContext *context) {
796
+ OseoValue *slot = &context->realm->intrinsics[OSEO_INTRINSIC_MATH];
797
+ if (is_object(*slot)) return normal(*slot);
798
+ size_t entry_allocations = context->allocations;
799
+ OseoRootFrame frame = {NULL, NULL, 0u};
800
+ OseoResult result = oseo_roots_allocate(context, &frame, 3u);
801
+ if (result.status != OSEO_STATUS_NORMAL) return result;
802
+ result = oseo_internal_intrinsic(
803
+ context,
804
+ OSEO_INTRINSIC_OBJECT_PROTOTYPE
805
+ );
806
+ frame.slots[0] = result.value;
807
+ if (result.status == OSEO_STATUS_NORMAL) {
808
+ result = oseo_object_create(context, frame.slots[0]);
809
+ frame.slots[0] = result.value;
810
+ }
811
+ if (result.status == OSEO_STATUS_NORMAL) {
812
+ *slot = frame.slots[0];
813
+ }
814
+ static const OseoPropertyAttributes constant_attributes =
815
+ {false, false, false, false};
816
+ for (size_t index = 0u;
817
+ result.status == OSEO_STATUS_NORMAL &&
818
+ index < OSEO_MATH_CONSTANT_COUNT;
819
+ index += 1u) {
820
+ result = define_math_property(
821
+ context,
822
+ frame.slots[0],
823
+ math_constants[index].name,
824
+ oseo_number(math_constants[index].value),
825
+ constant_attributes
826
+ );
827
+ }
828
+ static const OseoPropertyAttributes method_attributes =
829
+ {true, false, true, false};
830
+ for (size_t index = 0u;
831
+ result.status == OSEO_STATUS_NORMAL &&
832
+ index < OSEO_MATH_FUNCTION_COUNT;
833
+ index += 1u) {
834
+ result = create_math_function(context, index);
835
+ frame.slots[1] = result.value;
836
+ if (result.status != OSEO_STATUS_NORMAL) break;
837
+ result = define_math_property(
838
+ context,
839
+ frame.slots[0],
840
+ math_functions[index].name,
841
+ frame.slots[1],
842
+ method_attributes
843
+ );
844
+ }
845
+ if (result.status == OSEO_STATUS_NORMAL) {
846
+ result = oseo_internal_well_known_symbol(
847
+ context,
848
+ OSEO_WELL_KNOWN_TO_STRING_TAG
849
+ );
850
+ frame.slots[1] = result.value;
851
+ }
852
+ if (result.status == OSEO_STATUS_NORMAL) {
853
+ result = oseo_internal_ascii_string(context, "Math");
854
+ frame.slots[2] = result.value;
855
+ }
856
+ if (result.status == OSEO_STATUS_NORMAL) {
857
+ result = oseo_object_define(
858
+ context,
859
+ frame.slots[0],
860
+ frame.slots[1],
861
+ frame.slots[2],
862
+ (OseoPropertyAttributes){true, false, false, false}
863
+ );
864
+ }
865
+ if (result.status != OSEO_STATUS_NORMAL) {
866
+ *slot = oseo_undefined();
867
+ } else if (context->observe_specialization) {
868
+ context->allocations = entry_allocations;
869
+ }
870
+ oseo_roots_release(context, &frame);
871
+ return result.status == OSEO_STATUS_NORMAL ? normal(*slot) : result;
872
+ }
873
+
874
+ OseoResult oseo_internal_install_math_global(
875
+ OseoContext *context,
876
+ OseoValue global
877
+ ) {
878
+ OseoValue slots[2] = {global, oseo_undefined()};
879
+ OseoRootFrame frame = {NULL, slots, 2u};
880
+ oseo_roots_push(context, &frame);
881
+ OseoResult result = oseo_internal_math_intrinsic(context);
882
+ slots[1] = result.value;
883
+ if (result.status == OSEO_STATUS_NORMAL) {
884
+ result = define_math_property(
885
+ context,
886
+ slots[0],
887
+ "Math",
888
+ slots[1],
889
+ (OseoPropertyAttributes){true, false, true, false}
890
+ );
891
+ }
892
+ oseo_roots_pop(context, &frame);
893
+ return result.status == OSEO_STATUS_NORMAL ? normal(slots[0]) : result;
894
+ }