@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,1365 @@
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 <math.h>
31
+ #include <stdio.h>
32
+ #include <stdlib.h>
33
+ #include <string.h>
34
+
35
+ /*
36
+ * Heap allocation, publication, tracing, collection, and
37
+ * destruction for every runtime heap kind.
38
+ */
39
+
40
+ static bool mark_value(
41
+ OseoValue value,
42
+ OseoHeapObject **worklist
43
+ ) {
44
+ if (tag_of(value) != OSEO_TAG_HEAP) return false;
45
+ OseoHeapObject *object = heap_object(value);
46
+ if (object->marked) return false;
47
+ object->marked = true;
48
+ object->trace_next = *worklist;
49
+ *worklist = object;
50
+ return true;
51
+ }
52
+
53
+ /*
54
+ * Marks everything one realm owns: its intrinsic graph, its global
55
+ * object, and the literal-cache entries that keep a site's object alive.
56
+ */
57
+ static void mark_realm(const OseoRealm *realm, OseoHeapObject **worklist) {
58
+ for (size_t index = 0u; index < OSEO_INTRINSIC_COUNT; index += 1u) {
59
+ mark_value(realm->intrinsics[index], worklist);
60
+ }
61
+ mark_value(realm->global_this, worklist);
62
+ mark_value(realm->global_lexicals, worklist);
63
+ const OseoTemplateCacheEntry *template_cache = realm->template_cache;
64
+ for (size_t index = 0u; index < realm->template_cache_count; index += 1u) {
65
+ mark_value(template_cache[index].object, worklist);
66
+ }
67
+ const OseoRegExpLiteralCacheEntry *regexp_cache =
68
+ realm->regexp_literal_cache;
69
+ for (size_t index = 0u;
70
+ index < realm->regexp_literal_cache_capacity;
71
+ index += 1u) {
72
+ if (regexp_cache[index].literal == NULL) continue;
73
+ mark_value(regexp_cache[index].matcher, worklist);
74
+ }
75
+ }
76
+
77
+ /* Return the least set bit's index; callers pass a nonzero word. */
78
+ static size_t heap_bitmap_lowest_bit(uint64_t bits) {
79
+ size_t index = 0u;
80
+ if ((bits & UINT64_C(0xffffffff)) == 0u) {
81
+ index += 32u;
82
+ bits >>= 32u;
83
+ }
84
+ if ((bits & UINT64_C(0xffff)) == 0u) {
85
+ index += 16u;
86
+ bits >>= 16u;
87
+ }
88
+ if ((bits & UINT64_C(0xff)) == 0u) {
89
+ index += 8u;
90
+ bits >>= 8u;
91
+ }
92
+ if ((bits & UINT64_C(0xf)) == 0u) {
93
+ index += 4u;
94
+ bits >>= 4u;
95
+ }
96
+ if ((bits & UINT64_C(0x3)) == 0u) {
97
+ index += 2u;
98
+ bits >>= 2u;
99
+ }
100
+ if ((bits & UINT64_C(0x1)) == 0u) index += 1u;
101
+ return index;
102
+ }
103
+
104
+ static void trace_object(
105
+ OseoHeapObject *object,
106
+ OseoHeapObject **worklist
107
+ ) {
108
+ if (object->kind == OSEO_HEAP_BIGINT ||
109
+ object->kind == OSEO_HEAP_STRING ||
110
+ object->kind == OSEO_HEAP_PRIVATE_NAME) {
111
+ return;
112
+ }
113
+ if (object->kind == OSEO_HEAP_REALM) {
114
+ mark_realm(&((OseoRealmRecord *)object)->realm, worklist);
115
+ return;
116
+ }
117
+ if (object->kind == OSEO_HEAP_REGEXP_MATCHER) {
118
+ OseoRegExpMatcher *matcher = (OseoRegExpMatcher *)object;
119
+ mark_value(matcher->source, worklist);
120
+ mark_value(matcher->flags, worklist);
121
+ return;
122
+ }
123
+ if (object->kind == OSEO_HEAP_ENVIRONMENT) {
124
+ OseoEnvironment *environment = (OseoEnvironment *)object;
125
+ const uint64_t *bitmap = environment_heap_bitmap(environment);
126
+ for (size_t word = 0u;
127
+ word < environment->heap_word_count;
128
+ word += 1u) {
129
+ uint64_t bits = bitmap[word];
130
+ while (bits != 0u) {
131
+ size_t index = word * 64u + heap_bitmap_lowest_bit(bits);
132
+ mark_value(environment->slots[index], worklist);
133
+ bits &= bits - UINT64_C(1);
134
+ }
135
+ }
136
+ } else if (object->kind == OSEO_HEAP_CELL) {
137
+ OseoCell *cell = (OseoCell *)object;
138
+ mark_value(cell->value, worklist);
139
+ if (cell->object_environment) {
140
+ mark_value(cell->object, worklist);
141
+ mark_value(cell->key, worklist);
142
+ }
143
+ } else if (object->kind == OSEO_HEAP_SYMBOL) {
144
+ mark_value(((OseoSymbol *)object)->description, worklist);
145
+ } else if (object->kind == OSEO_HEAP_ARGUMENT_LIST) {
146
+ OseoArgumentList *list = (OseoArgumentList *)object;
147
+ for (size_t index = 0u; index < list->length; index += 1u) {
148
+ mark_value(list->values[index], worklist);
149
+ }
150
+ } else if (object->kind == OSEO_HEAP_EPHEMERON_TABLE) {
151
+ OseoEphemeronTable *table = (OseoEphemeronTable *)object;
152
+ mark_value(table->head, worklist);
153
+ mark_value(table->tail, worklist);
154
+ } else if (object->kind == OSEO_HEAP_EPHEMERON_ENTRY) {
155
+ /* `key` and `value` are processed by the fixed-point phase. */
156
+ mark_value(((OseoEphemeronEntry *)object)->next, worklist);
157
+ } else if (object->kind == OSEO_HEAP_WEAK_REFERENCE) {
158
+ /* `target` is cleared after the ephemeron fixed point. */
159
+ return;
160
+ } else if (object->kind == OSEO_HEAP_FINALIZATION_REGISTRY) {
161
+ OseoFinalizationRegistry *registry =
162
+ (OseoFinalizationRegistry *)object;
163
+ mark_value(registry->callback, worklist);
164
+ mark_value(registry->cell_head, worklist);
165
+ mark_value(registry->cell_tail, worklist);
166
+ } else if (object->kind == OSEO_HEAP_FINALIZATION_CELL) {
167
+ OseoFinalizationCell *cell = (OseoFinalizationCell *)object;
168
+ mark_value(cell->next, worklist);
169
+ mark_value(cell->queue_next, worklist);
170
+ mark_value(cell->registry, worklist);
171
+ if (!cell->processed) mark_value(cell->holdings, worklist);
172
+ /* `target` and `unregister_token` are weak and never enter
173
+ * ordinary tracing. */
174
+ } else if (object->kind == OSEO_HEAP_ENUMERATION) {
175
+ /* The receiver, candidates, and visited keys are reachable only
176
+ * through the record a for-in head roots, so a suspended body keeps
177
+ * all three alive. */
178
+ OseoEnumeration *enumeration = (OseoEnumeration *)object;
179
+ mark_value(enumeration->receiver, worklist);
180
+ mark_value(enumeration->candidates, worklist);
181
+ mark_value(enumeration->visited, worklist);
182
+ } else if (object->kind == OSEO_HEAP_OBJECT ||
183
+ object->kind == OSEO_HEAP_ARRAY ||
184
+ object->kind == OSEO_HEAP_FUNCTION ||
185
+ object->kind == OSEO_HEAP_PROMISE ||
186
+ object->kind == OSEO_HEAP_ARRAY_BUFFER ||
187
+ object->kind == OSEO_HEAP_MAP ||
188
+ object->kind == OSEO_HEAP_MAP_ITERATOR ||
189
+ object->kind == OSEO_HEAP_DATA_VIEW ||
190
+ object->kind == OSEO_HEAP_DATE ||
191
+ object->kind == OSEO_HEAP_REGEXP ||
192
+ object->kind == OSEO_HEAP_ITERATOR_HELPER ||
193
+ object->kind == OSEO_HEAP_PROXY ||
194
+ object->kind == OSEO_HEAP_SET ||
195
+ object->kind == OSEO_HEAP_SET_ITERATOR ||
196
+ object->kind == OSEO_HEAP_TYPED_ARRAY ||
197
+ object->kind == OSEO_HEAP_WEAK_MAP ||
198
+ object->kind == OSEO_HEAP_WEAK_SET ||
199
+ object->kind == OSEO_HEAP_WEAK_REF ||
200
+ object->kind == OSEO_HEAP_FINALIZATION_REGISTRY_OBJECT ||
201
+ object->kind == OSEO_HEAP_DISPOSABLE_STACK) {
202
+ OseoOrdinaryObject *ordinary = (OseoOrdinaryObject *)object;
203
+ mark_value(ordinary->prototype, worklist);
204
+ if (ordinary->primitive_data) {
205
+ mark_value(ordinary->primitive_value, worklist);
206
+ }
207
+ if (ordinary->iterator_kind != OSEO_ITERATOR_NONE) {
208
+ mark_value(ordinary->iterator_target, worklist);
209
+ }
210
+ if (ordinary->regexp_string_iterator) {
211
+ mark_value(ordinary->regexp_iterator_subject, worklist);
212
+ mark_value(ordinary->regexp_iterator_regexp, worklist);
213
+ }
214
+ if (ordinary->async_from_sync) {
215
+ mark_value(ordinary->async_sync_iterator, worklist);
216
+ }
217
+ if (ordinary->wrap_for_valid_iterator) {
218
+ mark_value(ordinary->wrapped_iterator, worklist);
219
+ mark_value(ordinary->wrapped_next, worklist);
220
+ }
221
+ if (ordinary->generator != NULL) {
222
+ OseoGenerator *generator = ordinary->generator;
223
+ mark_value(generator->callee, worklist);
224
+ mark_value(generator->receiver, worklist);
225
+ mark_value(generator->sent, worklist);
226
+ mark_value(generator->async_function_capability, worklist);
227
+ /* The pending AsyncGeneratorRequest queue is reachable only
228
+ * through the generator that accepted it. */
229
+ mark_value(generator->request_head, worklist);
230
+ mark_value(generator->request_tail, worklist);
231
+ /* The suspended body's roots, including its saved
232
+ * completion values, live only here. */
233
+ for (size_t index = 0u;
234
+ index < generator->slot_count;
235
+ index += 1u) {
236
+ mark_value(generator->slots[index], worklist);
237
+ }
238
+ }
239
+ for (size_t index = 0u; index < ordinary->property_count; index += 1u) {
240
+ mark_value(ordinary->properties[index].key, worklist);
241
+ mark_value(ordinary->properties[index].value, worklist);
242
+ mark_value(ordinary->properties[index].getter, worklist);
243
+ mark_value(ordinary->properties[index].setter, worklist);
244
+ }
245
+ /* [[PrivateElements]] is reachable only through the object that
246
+ * carries it, so nothing else keeps a private name or a private
247
+ * method alive once the instance dies. */
248
+ for (size_t index = 0u;
249
+ index < ordinary->private_element_count;
250
+ index += 1u) {
251
+ mark_value(ordinary->private_elements[index].key, worklist);
252
+ mark_value(ordinary->private_elements[index].value, worklist);
253
+ mark_value(ordinary->private_elements[index].getter, worklist);
254
+ mark_value(ordinary->private_elements[index].setter, worklist);
255
+ }
256
+ if (object->kind == OSEO_HEAP_FUNCTION) {
257
+ OseoFunction *function = (OseoFunction *)object;
258
+ mark_value(function->environment, worklist);
259
+ mark_value(function->lexical_this, worklist);
260
+ mark_value(function->lexical_new_target, worklist);
261
+ mark_value(function->lexical_super, worklist);
262
+ mark_value(function->prototype_object, worklist);
263
+ mark_value(function->home_object, worklist);
264
+ mark_value(function->initial_name, worklist);
265
+ mark_value(function->source_text, worklist);
266
+ mark_value(function->realm, worklist);
267
+ mark_value(function->bound_target, worklist);
268
+ mark_value(function->bound_this, worklist);
269
+ mark_value(function->bound_arguments, worklist);
270
+ for (size_t index = 0u;
271
+ index < function->element_count;
272
+ index += 1u) {
273
+ mark_value(function->elements[index].key, worklist);
274
+ mark_value(function->elements[index].value, worklist);
275
+ mark_value(function->elements[index].getter, worklist);
276
+ mark_value(function->elements[index].setter, worklist);
277
+ }
278
+ } else if (object->kind == OSEO_HEAP_PROMISE) {
279
+ OseoPromise *promise = (OseoPromise *)object;
280
+ mark_value(promise->result, worklist);
281
+ mark_value(promise->reaction_head, worklist);
282
+ mark_value(promise->reaction_tail, worklist);
283
+ mark_value(promise->unhandled_next, worklist);
284
+ mark_value(promise->realm, worklist);
285
+ } else if (object->kind == OSEO_HEAP_MAP) {
286
+ OseoMap *map = (OseoMap *)object;
287
+ for (size_t index = 0u; index < map->entry_count; index += 1u) {
288
+ if (!map->entries[index].live) continue;
289
+ mark_value(map->entries[index].key, worklist);
290
+ mark_value(map->entries[index].value, worklist);
291
+ }
292
+ } else if (object->kind == OSEO_HEAP_MAP_ITERATOR) {
293
+ mark_value(((OseoMapIterator *)object)->target, worklist);
294
+ } else if (object->kind == OSEO_HEAP_DATA_VIEW) {
295
+ /* A view holds no Data Block of its own; tracing its buffer
296
+ * is what keeps that buffer's block alive. */
297
+ mark_value(((OseoDataView *)object)->buffer, worklist);
298
+ } else if (object->kind == OSEO_HEAP_TYPED_ARRAY) {
299
+ mark_value(
300
+ ((OseoTypedArray *)object)->viewed_buffer,
301
+ worklist
302
+ );
303
+ } else if (object->kind == OSEO_HEAP_REGEXP) {
304
+ mark_value(((OseoRegExp *)object)->matcher, worklist);
305
+ } else if (object->kind == OSEO_HEAP_ITERATOR_HELPER) {
306
+ /* A helper's underlying iterator record, callback, and
307
+ * in-flight inner iterator are reachable only through the
308
+ * helper, so a collection at any safepoint inside one
309
+ * resumption keeps every one of them alive. */
310
+ OseoIteratorHelper *helper = (OseoIteratorHelper *)object;
311
+ mark_value(helper->underlying_iterator, worklist);
312
+ mark_value(helper->underlying_next, worklist);
313
+ mark_value(helper->callback, worklist);
314
+ mark_value(helper->inner_iterator, worklist);
315
+ mark_value(helper->inner_next, worklist);
316
+ } else if (object->kind == OSEO_HEAP_PROXY) {
317
+ OseoProxy *proxy = (OseoProxy *)object;
318
+ mark_value(proxy->target, worklist);
319
+ mark_value(proxy->handler, worklist);
320
+ } else if (object->kind == OSEO_HEAP_SET) {
321
+ OseoSet *set = (OseoSet *)object;
322
+ for (size_t index = 0u;
323
+ index < set->element_count;
324
+ index += 1u) {
325
+ if (set->elements[index].present) {
326
+ mark_value(set->elements[index].value, worklist);
327
+ }
328
+ }
329
+ } else if (object->kind == OSEO_HEAP_SET_ITERATOR) {
330
+ mark_value(((OseoSetIterator *)object)->set, worklist);
331
+ } else if (object->kind == OSEO_HEAP_WEAK_MAP ||
332
+ object->kind == OSEO_HEAP_WEAK_SET) {
333
+ /* The table is strong; its entries stay ephemerons. */
334
+ mark_value(((OseoWeakCollection *)object)->table, worklist);
335
+ } else if (object->kind == OSEO_HEAP_WEAK_REF) {
336
+ mark_value(((OseoWeakRef *)object)->reference, worklist);
337
+ } else if (object->kind == OSEO_HEAP_FINALIZATION_REGISTRY_OBJECT) {
338
+ mark_value(
339
+ ((OseoFinalizationRegistryObject *)object)->registry,
340
+ worklist
341
+ );
342
+ } else if (object->kind == OSEO_HEAP_DISPOSABLE_STACK) {
343
+ OseoDisposableStack *stack = (OseoDisposableStack *)object;
344
+ mark_value(stack->capability, worklist);
345
+ mark_value(stack->error, worklist);
346
+ mark_value(stack->await_value, worklist);
347
+ mark_value(stack->promise, worklist);
348
+ mark_value(stack->on_fulfilled, worklist);
349
+ mark_value(stack->on_rejected, worklist);
350
+ for (size_t index = 0u;
351
+ index < stack->resource_count;
352
+ index += 1u) {
353
+ mark_value(stack->resources[index], worklist);
354
+ }
355
+ }
356
+ } else if (object->kind == OSEO_HEAP_PROMISE_REACTION) {
357
+ OseoPromiseReaction *reaction = (OseoPromiseReaction *)object;
358
+ mark_value(reaction->next, worklist);
359
+ mark_value(reaction->on_fulfilled, worklist);
360
+ mark_value(reaction->on_rejected, worklist);
361
+ mark_value(reaction->capability, worklist);
362
+ mark_value(reaction->aggregate, worklist);
363
+ } else if (object->kind == OSEO_HEAP_JOB) {
364
+ OseoJob *job = (OseoJob *)object;
365
+ mark_value(job->next, worklist);
366
+ mark_value(job->primary, worklist);
367
+ mark_value(job->secondary, worklist);
368
+ mark_value(job->argument, worklist);
369
+ mark_value(job->realm, worklist);
370
+ } else if (object->kind == OSEO_HEAP_PROMISE_AGGREGATE) {
371
+ OseoPromiseAggregate *aggregate = (OseoPromiseAggregate *)object;
372
+ mark_value(aggregate->capability, worklist);
373
+ mark_value(aggregate->values, worklist);
374
+ } else if (object->kind == OSEO_HEAP_ASYNC_GENERATOR_REQUEST) {
375
+ OseoAsyncGeneratorRequest *request =
376
+ (OseoAsyncGeneratorRequest *)object;
377
+ mark_value(request->next, worklist);
378
+ mark_value(request->capability, worklist);
379
+ mark_value(request->value, worklist);
380
+ } else if (object->kind == OSEO_HEAP_TIMER) {
381
+ OseoTimer *timer = (OseoTimer *)object;
382
+ mark_value(timer->next, worklist);
383
+ mark_value(timer->callback, worklist);
384
+ mark_value(timer->arguments, worklist);
385
+ mark_value(timer->waiter, worklist);
386
+ } else if (object->kind == OSEO_HEAP_ATOMICS_WAITER) {
387
+ OseoAtomicsWaiter *waiter = (OseoAtomicsWaiter *)object;
388
+ mark_value(waiter->next, worklist);
389
+ mark_value(waiter->buffer, worklist);
390
+ mark_value(waiter->promise, worklist);
391
+ mark_value(waiter->timer, worklist);
392
+ }
393
+ }
394
+
395
+ static bool value_is_marked(OseoValue value) {
396
+ return tag_of(value) == OSEO_TAG_HEAP && heap_object(value)->marked;
397
+ }
398
+
399
+ static OseoValue heap_value(OseoHeapObject *object) {
400
+ return tagged(OSEO_TAG_HEAP, (uint64_t)(uintptr_t)object);
401
+ }
402
+
403
+ /*
404
+ * The collector never moves an object, so a key's heap address is a stable
405
+ * identity. Multiplicative hashing spreads the aligned low bits.
406
+ */
407
+ static size_t ephemeron_index_start(OseoValue key, size_t capacity) {
408
+ uint64_t hash = ((key & OSEO_PAYLOAD_MASK) >> 3u) *
409
+ UINT64_C(0x9e3779b97f4a7c15);
410
+ return (size_t)(hash >> 20u) & (capacity - 1u);
411
+ }
412
+
413
+ /* Returns the index slot holding `key`'s entry, or NULL. */
414
+ static OseoValue *ephemeron_index_find(
415
+ OseoEphemeronTable *table,
416
+ OseoValue key
417
+ ) {
418
+ if (table->index_capacity == 0u) return NULL;
419
+ size_t mask = table->index_capacity - 1u;
420
+ size_t slot = ephemeron_index_start(key, table->index_capacity);
421
+ for (size_t probe = 0u; probe < table->index_capacity; probe += 1u) {
422
+ OseoValue *candidate = &table->index[slot];
423
+ if (*candidate == 0u) return NULL;
424
+ if (*candidate != OSEO_EPHEMERON_INDEX_TOMBSTONE &&
425
+ ephemeron_entry_object(*candidate)->key == key) {
426
+ return candidate;
427
+ }
428
+ slot = (slot + 1u) & mask;
429
+ }
430
+ return NULL;
431
+ }
432
+
433
+ /*
434
+ * Inserts into a reserved index; the key must not be present. Returns
435
+ * whether the insertion consumed an empty slot rather than reusing a
436
+ * tombstone, which is the only case that grows the used-slot count.
437
+ */
438
+ static bool ephemeron_index_insert(
439
+ OseoValue *index,
440
+ size_t capacity,
441
+ OseoValue key,
442
+ OseoValue entry
443
+ ) {
444
+ size_t slot = ephemeron_index_start(key, capacity);
445
+ while (index[slot] != 0u &&
446
+ index[slot] != OSEO_EPHEMERON_INDEX_TOMBSTONE) {
447
+ slot = (slot + 1u) & (capacity - 1u);
448
+ }
449
+ bool empty = index[slot] == 0u;
450
+ index[slot] = entry;
451
+ return empty;
452
+ }
453
+
454
+ /* Activate entries that waited for this key to finish marking. */
455
+ static void activate_ephemeron_values(
456
+ OseoHeapObject *key,
457
+ OseoHeapObject **worklist
458
+ ) {
459
+ OseoHeapObject *pending = key->ephemeron_pending;
460
+ key->ephemeron_pending = NULL;
461
+ while (pending != NULL) {
462
+ OseoEphemeronEntry *entry = (OseoEphemeronEntry *)pending;
463
+ pending = entry->header.trace_next;
464
+ entry->header.trace_next = NULL;
465
+ mark_value(entry->value, worklist);
466
+ }
467
+ }
468
+
469
+ /*
470
+ * Drain strong edges and activate ephemeron values as their keys become
471
+ * reachable. An entry discovered before its key parks on the key object's
472
+ * collector-only pending list. Processing that key activates every waiting
473
+ * value, so the worklist computes the fixed point without repeated scans.
474
+ */
475
+ static void trace_ephemeron_fixed_point(OseoHeapObject **worklist) {
476
+ while (*worklist != NULL) {
477
+ OseoHeapObject *object = *worklist;
478
+ *worklist = object->trace_next;
479
+ object->trace_next = NULL;
480
+ trace_object(object, worklist);
481
+ if (object->kind == OSEO_HEAP_EPHEMERON_ENTRY) {
482
+ OseoEphemeronEntry *entry = (OseoEphemeronEntry *)object;
483
+ OseoHeapObject *key = heap_object(entry->key);
484
+ if (key->marked) {
485
+ mark_value(entry->value, worklist);
486
+ } else {
487
+ entry->header.trace_next = key->ephemeron_pending;
488
+ key->ephemeron_pending = &entry->header;
489
+ }
490
+ }
491
+ activate_ephemeron_values(object, worklist);
492
+ }
493
+ }
494
+
495
+ /*
496
+ * An entry is reachable only through its table's chain, so walking every
497
+ * marked table visits every marked entry exactly once. A dead-key entry is
498
+ * unlinked and unmarked here, which lets the same sweep reclaim it: weak
499
+ * tables must not retain per-entry records after their keys die.
500
+ */
501
+ static void clear_dead_weak_edges(OseoContext *context) {
502
+ for (OseoHeapObject *object = context->objects;
503
+ object != NULL;
504
+ object = object->next) {
505
+ if (!object->marked) continue;
506
+ if (object->kind == OSEO_HEAP_WEAK_REFERENCE) {
507
+ OseoWeakReference *reference = (OseoWeakReference *)object;
508
+ if (tag_of(reference->target) == OSEO_TAG_HEAP &&
509
+ !value_is_marked(reference->target)) {
510
+ reference->target = oseo_undefined();
511
+ }
512
+ } else if (object->kind == OSEO_HEAP_EPHEMERON_TABLE) {
513
+ OseoEphemeronTable *table = (OseoEphemeronTable *)object;
514
+ OseoValue *link = &table->head;
515
+ OseoHeapObject *last = NULL;
516
+ while (tag_of(*link) == OSEO_TAG_HEAP) {
517
+ OseoEphemeronEntry *entry = ephemeron_entry_object(*link);
518
+ if (value_is_marked(entry->key)) {
519
+ last = &entry->header;
520
+ link = &entry->next;
521
+ continue;
522
+ }
523
+ OseoValue *slot = ephemeron_index_find(table, entry->key);
524
+ if (slot != NULL) *slot = OSEO_EPHEMERON_INDEX_TOMBSTONE;
525
+ *link = entry->next;
526
+ if (tag_of(entry->next) == OSEO_TAG_HEAP) {
527
+ ephemeron_entry_object(entry->next)->previous =
528
+ last == NULL ? oseo_undefined() : heap_value(last);
529
+ }
530
+ entry->next = oseo_undefined();
531
+ entry->previous = oseo_undefined();
532
+ entry->key = oseo_undefined();
533
+ entry->value = oseo_undefined();
534
+ entry->header.marked = false;
535
+ if (table->live_count > 0u) table->live_count -= 1u;
536
+ }
537
+ table->tail =
538
+ last == NULL ? oseo_undefined() : heap_value(last);
539
+ } else if (object->kind == OSEO_HEAP_FINALIZATION_CELL) {
540
+ OseoFinalizationCell *cell = (OseoFinalizationCell *)object;
541
+ if (tag_of(cell->unregister_token) == OSEO_TAG_HEAP &&
542
+ !value_is_marked(cell->unregister_token)) {
543
+ cell->unregister_token = oseo_undefined();
544
+ }
545
+ }
546
+ }
547
+ }
548
+
549
+ /*
550
+ * A consumed cleanup cell has no further observable state, so unlinking
551
+ * it from its registry's chain and dropping its mark lets the sweep free
552
+ * it. Without this, a long-lived registry would retain one dead record
553
+ * per registration forever.
554
+ */
555
+ static void compact_finalization_registries(OseoContext *context) {
556
+ for (OseoHeapObject *object = context->objects;
557
+ object != NULL;
558
+ object = object->next) {
559
+ if (object->kind != OSEO_HEAP_FINALIZATION_REGISTRY ||
560
+ !object->marked) {
561
+ continue;
562
+ }
563
+ OseoFinalizationRegistry *registry =
564
+ (OseoFinalizationRegistry *)object;
565
+ OseoValue *link = &registry->cell_head;
566
+ OseoHeapObject *last = NULL;
567
+ while (tag_of(*link) == OSEO_TAG_HEAP) {
568
+ OseoFinalizationCell *cell = finalization_cell_object(*link);
569
+ if (cell->processed) {
570
+ *link = cell->next;
571
+ cell->next = oseo_undefined();
572
+ /* An unregistered record still on the cleanup FIFO stays
573
+ * alive until the dequeue skips it. */
574
+ if (!cell->queued) cell->header.marked = false;
575
+ } else {
576
+ last = &cell->header;
577
+ link = &cell->next;
578
+ }
579
+ }
580
+ registry->cell_tail =
581
+ last == NULL ? oseo_undefined() : heap_value(last);
582
+ }
583
+ }
584
+
585
+ /*
586
+ * Scheduling is allocation-free and deterministic: each collection sorts
587
+ * its newly eligible cells by registration order and appends that batch to
588
+ * the FIFO, so the order is by registration within a batch, not globally.
589
+ * The collector only publishes cleanup records; a later checkpoint decides
590
+ * when to invoke the JavaScript callback that will consume them. One pass
591
+ * gathers the newly eligible cells onto an ordinal-sorted list threaded
592
+ * through their free `trace_next` links, so the heap is scanned once
593
+ * rather than once per queued cell.
594
+ */
595
+ static void schedule_finalization(OseoContext *context) {
596
+ OseoHeapObject *candidates = NULL;
597
+ for (OseoHeapObject *object = context->objects;
598
+ object != NULL;
599
+ object = object->next) {
600
+ if (object->kind != OSEO_HEAP_FINALIZATION_CELL ||
601
+ !object->marked) {
602
+ continue;
603
+ }
604
+ OseoFinalizationCell *cell = (OseoFinalizationCell *)object;
605
+ if (cell->processed || cell->queued ||
606
+ tag_of(cell->target) != OSEO_TAG_HEAP ||
607
+ value_is_marked(cell->target)) {
608
+ continue;
609
+ }
610
+ OseoHeapObject **link = &candidates;
611
+ while (*link != NULL &&
612
+ ((OseoFinalizationCell *)*link)->registration_order <
613
+ cell->registration_order) {
614
+ link = &(*link)->trace_next;
615
+ }
616
+ cell->header.trace_next = *link;
617
+ *link = &cell->header;
618
+ }
619
+ while (candidates != NULL) {
620
+ OseoFinalizationCell *cell = (OseoFinalizationCell *)candidates;
621
+ candidates = cell->header.trace_next;
622
+ cell->header.trace_next = NULL;
623
+ OseoValue cell_value = heap_value(&cell->header);
624
+ cell->target = oseo_undefined();
625
+ cell->queue_next = oseo_undefined();
626
+ cell->queued = true;
627
+ if (tag_of(context->finalization_tail) == OSEO_TAG_HEAP) {
628
+ finalization_cell_object(context->finalization_tail)->queue_next =
629
+ cell_value;
630
+ } else {
631
+ context->finalization_head = cell_value;
632
+ }
633
+ context->finalization_tail = cell_value;
634
+ context->finalization_pending_count += 1u;
635
+ }
636
+ }
637
+
638
+ static void destroy_heap_object(OseoHeapObject *object) {
639
+ if (object->kind == OSEO_HEAP_OBJECT ||
640
+ object->kind == OSEO_HEAP_ARRAY ||
641
+ object->kind == OSEO_HEAP_FUNCTION ||
642
+ object->kind == OSEO_HEAP_PROMISE ||
643
+ object->kind == OSEO_HEAP_ARRAY_BUFFER ||
644
+ object->kind == OSEO_HEAP_MAP ||
645
+ object->kind == OSEO_HEAP_MAP_ITERATOR ||
646
+ object->kind == OSEO_HEAP_DATA_VIEW ||
647
+ object->kind == OSEO_HEAP_DATE ||
648
+ object->kind == OSEO_HEAP_REGEXP ||
649
+ object->kind == OSEO_HEAP_ITERATOR_HELPER ||
650
+ object->kind == OSEO_HEAP_PROXY ||
651
+ object->kind == OSEO_HEAP_SET ||
652
+ object->kind == OSEO_HEAP_SET_ITERATOR ||
653
+ object->kind == OSEO_HEAP_TYPED_ARRAY ||
654
+ object->kind == OSEO_HEAP_WEAK_MAP ||
655
+ object->kind == OSEO_HEAP_WEAK_SET ||
656
+ object->kind == OSEO_HEAP_WEAK_REF ||
657
+ object->kind == OSEO_HEAP_FINALIZATION_REGISTRY_OBJECT ||
658
+ object->kind == OSEO_HEAP_DISPOSABLE_STACK) {
659
+ OseoOrdinaryObject *ordinary = (OseoOrdinaryObject *)object;
660
+ free(ordinary->properties);
661
+ free(ordinary->private_elements);
662
+ free(ordinary->generator);
663
+ if (object->kind == OSEO_HEAP_FUNCTION) {
664
+ free(((OseoFunction *)object)->elements);
665
+ } else if (object->kind == OSEO_HEAP_ARRAY_BUFFER) {
666
+ /* The Data Block is owned by this buffer alone, and the
667
+ * release leaves the record detached, so a block already
668
+ * given up by a transfer is never freed a second time. */
669
+ oseo_internal_array_buffer_release(object);
670
+ } else if (object->kind == OSEO_HEAP_MAP) {
671
+ free(((OseoMap *)object)->entries);
672
+ } else if (object->kind == OSEO_HEAP_SET) {
673
+ free(((OseoSet *)object)->elements);
674
+ } else if (object->kind == OSEO_HEAP_DISPOSABLE_STACK) {
675
+ free(((OseoDisposableStack *)object)->resources);
676
+ }
677
+ } else if (object->kind == OSEO_HEAP_REALM) {
678
+ oseo_internal_realm_release(&((OseoRealmRecord *)object)->realm);
679
+ } else if (object->kind == OSEO_HEAP_ARGUMENT_LIST) {
680
+ free(((OseoArgumentList *)object)->values);
681
+ } else if (object->kind == OSEO_HEAP_EPHEMERON_TABLE) {
682
+ free(((OseoEphemeronTable *)object)->index);
683
+ } else if (object->kind == OSEO_HEAP_REGEXP_MATCHER) {
684
+ /* A dynamic pattern's compiled program is unmanaged memory this
685
+ * artifact alone owns, so its lifetime ends with the artifact.
686
+ * An ahead-of-time literal's program is static generated data
687
+ * this artifact only borrows. */
688
+ OseoRegExpMatcher *matcher = (OseoRegExpMatcher *)object;
689
+ if (matcher->owns_program) {
690
+ oseo_internal_regexp_program_release(matcher->program);
691
+ }
692
+ }
693
+ free(object);
694
+ }
695
+
696
+ /*
697
+ * These record kinds never change after publication. Count only objects
698
+ * linked to this context, not foreign objects the marking worklist visits.
699
+ * Publication and sweep are their only heap-membership transitions;
700
+ * unregistering or consuming a cleanup record does not remove the object.
701
+ */
702
+ static size_t *weak_record_count(OseoContext *context, OseoHeapKind kind) {
703
+ switch (kind) {
704
+ case OSEO_HEAP_EPHEMERON_TABLE:
705
+ return &context->ephemeron_table_count;
706
+ case OSEO_HEAP_WEAK_REFERENCE:
707
+ return &context->weak_reference_count;
708
+ case OSEO_HEAP_FINALIZATION_REGISTRY:
709
+ return &context->finalization_registry_count;
710
+ case OSEO_HEAP_FINALIZATION_CELL:
711
+ return &context->finalization_cell_count;
712
+ default:
713
+ return NULL;
714
+ }
715
+ }
716
+
717
+ /*
718
+ * Drops every mark this heap carries. A mark belongs to one collection of
719
+ * one context, but a context that holds a value another context owns in
720
+ * its roots marks that value while collecting, and only the owning
721
+ * context's sweep clears a mark on its own heap. Such a mark therefore
722
+ * survives until this heap sweeps again, which the final sweep of a
723
+ * destroyed context never does: the object would stay linked with nothing
724
+ * left to free it. Clearing the marks first makes that sweep unconditional.
725
+ */
726
+ void oseo_internal_clear_heap_marks(OseoContext *context) {
727
+ for (OseoHeapObject *object = context->objects;
728
+ object != NULL;
729
+ object = object->next) {
730
+ object->marked = false;
731
+ }
732
+ }
733
+
734
+ void oseo_collect(OseoContext *context) {
735
+ if (context->observe_specialization) context->collections += 1u;
736
+ OseoHeapObject *worklist = NULL;
737
+ for (OseoRootFrame *frame = context->roots;
738
+ frame != NULL;
739
+ frame = frame->previous) {
740
+ for (size_t index = 0u; index < frame->slot_count; index += 1u) {
741
+ mark_value(frame->slots[index], &worklist);
742
+ }
743
+ }
744
+ mark_value(context->microtask_head, &worklist);
745
+ mark_value(context->async_call_capability, &worklist);
746
+ mark_value(context->microtask_tail, &worklist);
747
+ mark_value(context->pending_rejections, &worklist);
748
+ mark_value(context->pending_rejection_tail, &worklist);
749
+ mark_realm(&context->initial_realm, &worklist);
750
+ mark_value(context->realm_record, &worklist);
751
+ /* Each record's values are also rooted by the frame that made its
752
+ * call; tracing them keeps that an optimization, not a requirement. */
753
+ for (const OseoActivation *activation = context->activation;
754
+ activation != NULL;
755
+ activation = activation->previous) {
756
+ mark_value(activation->function, &worklist);
757
+ mark_value(activation->caller, &worklist);
758
+ for (size_t index = 0u;
759
+ index < activation->argument_count;
760
+ index += 1u) {
761
+ mark_value(activation->arguments[index], &worklist);
762
+ }
763
+ }
764
+ mark_value(context->legacy_function_keys[0], &worklist);
765
+ mark_value(context->legacy_function_keys[1], &worklist);
766
+ for (size_t index = 0u;
767
+ index < OSEO_WELL_KNOWN_SYMBOL_COUNT;
768
+ index += 1u) {
769
+ mark_value(context->well_known_symbols[index], &worklist);
770
+ }
771
+ for (size_t index = 0u;
772
+ index < context->registered_symbol_capacity;
773
+ index += 1u) {
774
+ mark_value(context->registered_symbols[index], &worklist);
775
+ }
776
+ mark_value(context->timer_head, &worklist);
777
+ mark_value(context->atomics_waiter_head, &worklist);
778
+ mark_value(context->atomics_waiter_tail, &worklist);
779
+ mark_value(context->agent_broadcast_callback, &worklist);
780
+ mark_value(context->finalization_head, &worklist);
781
+ mark_value(context->finalization_tail, &worklist);
782
+ OseoValue *kept_objects = context->kept_objects;
783
+ for (size_t index = 0u;
784
+ index < context->kept_object_capacity;
785
+ index += 1u) {
786
+ mark_value(kept_objects[index], &worklist);
787
+ }
788
+ const OseoModuleTable *modules = context->module_table;
789
+ if (modules != NULL) {
790
+ for (size_t index = 0u; index < modules->count; index += 1u) {
791
+ const OseoModuleRecord *record = &modules->records[index];
792
+ mark_value(record->evaluator, &worklist);
793
+ mark_value(record->namespace_object, &worklist);
794
+ mark_value(record->top_level_capability, &worklist);
795
+ mark_value(record->evaluation_error, &worklist);
796
+ }
797
+ }
798
+ const OseoTailCall *tail_call = context->tail_call;
799
+ if (tail_call != NULL && tail_call->pending) {
800
+ mark_value(tail_call->callee, &worklist);
801
+ mark_value(tail_call->receiver, &worklist);
802
+ mark_value(tail_call->realm_record, &worklist);
803
+ mark_value(tail_call->this_cell, &worklist);
804
+ mark_value(tail_call->constructor_realm, &worklist);
805
+ mark_value(tail_call->caller, &worklist);
806
+ for (size_t index = 0u;
807
+ index < tail_call->argument_count;
808
+ index += 1u) {
809
+ mark_value(tail_call->arguments[index], &worklist);
810
+ }
811
+ }
812
+ trace_ephemeron_fixed_point(&worklist);
813
+ if (context->ephemeron_table_count != 0u ||
814
+ context->weak_reference_count != 0u ||
815
+ context->finalization_cell_count != 0u) {
816
+ clear_dead_weak_edges(context);
817
+ }
818
+ if (context->finalization_cell_count != 0u) {
819
+ schedule_finalization(context);
820
+ }
821
+ if (context->finalization_registry_count != 0u) {
822
+ compact_finalization_registries(context);
823
+ }
824
+ /* Marking is final here, so the table forgets exactly the strings the
825
+ * sweep below frees. */
826
+ oseo_internal_string_table_sweep(context);
827
+ OseoHeapObject **link = &context->objects;
828
+ while (*link != NULL) {
829
+ OseoHeapObject *object = *link;
830
+ if (object->marked) {
831
+ object->marked = false;
832
+ link = &object->next;
833
+ } else {
834
+ *link = object->next;
835
+ size_t *count = weak_record_count(context, object->kind);
836
+ if (count != NULL) *count -= 1u;
837
+ destroy_heap_object(object);
838
+ }
839
+ }
840
+ }
841
+
842
+ void *oseo_internal_allocate_heap_bytes(OseoContext *context, size_t size) {
843
+ if (context->collect_every_safepoint) oseo_collect(context);
844
+ context->allocation_attempts += 1u;
845
+ if (context->fail_allocation_at != 0u &&
846
+ context->allocation_attempts == context->fail_allocation_at) {
847
+ return NULL;
848
+ }
849
+ return malloc(size);
850
+ }
851
+
852
+ void *oseo_internal_allocate_work_bytes(OseoContext *context, size_t size) {
853
+ context->allocation_attempts += 1u;
854
+ if (context->fail_allocation_at != 0u &&
855
+ context->allocation_attempts == context->fail_allocation_at) {
856
+ return NULL;
857
+ }
858
+ return malloc(size);
859
+ }
860
+
861
+ void *oseo_internal_reallocate_work_bytes(
862
+ OseoContext *context,
863
+ void *block,
864
+ size_t size
865
+ ) {
866
+ context->allocation_attempts += 1u;
867
+ if (context->fail_allocation_at != 0u &&
868
+ context->allocation_attempts == context->fail_allocation_at) {
869
+ return NULL;
870
+ }
871
+ return realloc(block, size);
872
+ }
873
+
874
+ OseoResult oseo_internal_publish_heap(
875
+ OseoContext *context,
876
+ OseoHeapObject *object,
877
+ OseoHeapKind kind
878
+ ) {
879
+ uintptr_t address = (uintptr_t)object;
880
+ if (address == 0u || address > OSEO_PAYLOAD_MASK) {
881
+ free(object);
882
+ return failure(
883
+ context,
884
+ "OSEO3001",
885
+ "The host cannot represent a heap address in 48 bits."
886
+ );
887
+ }
888
+ size_t *count = weak_record_count(context, kind);
889
+ if (count != NULL && *count == SIZE_MAX) {
890
+ free(object);
891
+ return failure(context, "OSEO2001", "Too many weak heap records.");
892
+ }
893
+ object->next = context->objects;
894
+ object->trace_next = NULL;
895
+ object->ephemeron_pending = NULL;
896
+ object->kind = kind;
897
+ object->marked = false;
898
+ object->retained = false;
899
+ object->raw_json = false;
900
+ context->objects = object;
901
+ if (count != NULL) *count += 1u;
902
+ if (context->observe_specialization &&
903
+ kind != OSEO_HEAP_ENVIRONMENT && kind != OSEO_HEAP_CELL &&
904
+ kind != OSEO_HEAP_FUNCTION) {
905
+ context->allocations += 1u;
906
+ }
907
+ return normal(tagged(OSEO_TAG_HEAP, (uint64_t)address));
908
+ }
909
+
910
+ static bool has_heap_kind(OseoValue value, OseoHeapKind kind) {
911
+ return tag_of(value) == OSEO_TAG_HEAP && heap_object(value)->kind == kind;
912
+ }
913
+
914
+ OseoResult oseo_internal_ephemeron_table_create(OseoContext *context) {
915
+ OseoEphemeronTable *table =
916
+ oseo_internal_allocate_heap_bytes(context, sizeof(*table));
917
+ if (table == NULL) {
918
+ return failure(
919
+ context,
920
+ "OSEO2001",
921
+ "Ephemeron table allocation failed."
922
+ );
923
+ }
924
+ table->head = oseo_undefined();
925
+ table->tail = oseo_undefined();
926
+ table->live_count = 0u;
927
+ table->index = NULL;
928
+ table->index_capacity = 0u;
929
+ table->index_used = 0u;
930
+ return oseo_internal_publish_heap(
931
+ context,
932
+ &table->header,
933
+ OSEO_HEAP_EPHEMERON_TABLE
934
+ );
935
+ }
936
+
937
+ /*
938
+ * Keeps one free index slot for an insertion at a load factor, counting
939
+ * tombstones, of at most three quarters. The unmanaged allocation never
940
+ * collects, and a later collection only turns slots into tombstones, so
941
+ * the reservation survives the entry allocation that follows it.
942
+ */
943
+ static OseoResult ephemeron_index_reserve(
944
+ OseoContext *context,
945
+ OseoValue table_value
946
+ ) {
947
+ OseoEphemeronTable *table = ephemeron_table_object(table_value);
948
+ if (table->index_capacity != 0u &&
949
+ (table->index_used + 1u) <= table->index_capacity / 4u * 3u) {
950
+ return normal(table_value);
951
+ }
952
+ /* A rebuilt index is at most half full, so at least a quarter of its
953
+ * slots accept insertions before the next rebuild. */
954
+ size_t capacity = 8u;
955
+ while (capacity / 2u < table->live_count + 1u) {
956
+ if (capacity > SIZE_MAX / 2u / sizeof(OseoValue)) {
957
+ return failure(
958
+ context,
959
+ "OSEO2001",
960
+ "Ephemeron index is too large."
961
+ );
962
+ }
963
+ capacity *= 2u;
964
+ }
965
+ OseoValue *index = oseo_internal_allocate_work_bytes(
966
+ context,
967
+ capacity * sizeof(*index)
968
+ );
969
+ if (index == NULL) {
970
+ return failure(
971
+ context,
972
+ "OSEO2001",
973
+ "Ephemeron index allocation failed."
974
+ );
975
+ }
976
+ for (size_t slot = 0u; slot < capacity; slot += 1u) index[slot] = 0u;
977
+ size_t used = 0u;
978
+ for (OseoValue cursor = table->head;
979
+ tag_of(cursor) == OSEO_TAG_HEAP;
980
+ cursor = ephemeron_entry_object(cursor)->next) {
981
+ (void)ephemeron_index_insert(
982
+ index,
983
+ capacity,
984
+ ephemeron_entry_object(cursor)->key,
985
+ cursor
986
+ );
987
+ used += 1u;
988
+ }
989
+ free(table->index);
990
+ table->index = index;
991
+ table->index_capacity = capacity;
992
+ table->index_used = used;
993
+ return normal(table_value);
994
+ }
995
+
996
+ OseoResult oseo_internal_ephemeron_set(
997
+ OseoContext *context,
998
+ OseoValue table_value,
999
+ OseoValue key,
1000
+ OseoValue value
1001
+ ) {
1002
+ if (!has_heap_kind(table_value, OSEO_HEAP_EPHEMERON_TABLE)) {
1003
+ return failure(context, "OSEO2001", "Value is not an ephemeron table.");
1004
+ }
1005
+ if (tag_of(key) != OSEO_TAG_HEAP) {
1006
+ return failure(
1007
+ context,
1008
+ "OSEO2001",
1009
+ "Ephemeron key is not a heap value."
1010
+ );
1011
+ }
1012
+ OseoValue *existing =
1013
+ ephemeron_index_find(ephemeron_table_object(table_value), key);
1014
+ if (existing != NULL) {
1015
+ ephemeron_entry_object(*existing)->value = value;
1016
+ return normal(table_value);
1017
+ }
1018
+
1019
+ OseoValue roots[] = {table_value, key, value};
1020
+ OseoRootFrame frame = {NULL, roots, 3u};
1021
+ oseo_roots_push(context, &frame);
1022
+ OseoResult reserved = ephemeron_index_reserve(context, roots[0]);
1023
+ if (reserved.status != OSEO_STATUS_NORMAL) {
1024
+ oseo_roots_pop(context, &frame);
1025
+ return reserved;
1026
+ }
1027
+ OseoEphemeronEntry *entry =
1028
+ oseo_internal_allocate_heap_bytes(context, sizeof(*entry));
1029
+ if (entry == NULL) {
1030
+ oseo_roots_pop(context, &frame);
1031
+ return failure(
1032
+ context,
1033
+ "OSEO2001",
1034
+ "Ephemeron entry allocation failed."
1035
+ );
1036
+ }
1037
+ entry->next = oseo_undefined();
1038
+ entry->previous = oseo_undefined();
1039
+ entry->key = roots[1];
1040
+ entry->value = roots[2];
1041
+ OseoResult published = oseo_internal_publish_heap(
1042
+ context,
1043
+ &entry->header,
1044
+ OSEO_HEAP_EPHEMERON_ENTRY
1045
+ );
1046
+ if (published.status == OSEO_STATUS_NORMAL) {
1047
+ OseoEphemeronTable *table = ephemeron_table_object(roots[0]);
1048
+ if (has_heap_kind(table->tail, OSEO_HEAP_EPHEMERON_ENTRY)) {
1049
+ ephemeron_entry_object(table->tail)->next = published.value;
1050
+ entry->previous = table->tail;
1051
+ } else {
1052
+ table->head = published.value;
1053
+ }
1054
+ table->tail = published.value;
1055
+ table->live_count += 1u;
1056
+ if (ephemeron_index_insert(
1057
+ table->index,
1058
+ table->index_capacity,
1059
+ roots[1],
1060
+ published.value
1061
+ )) {
1062
+ table->index_used += 1u;
1063
+ }
1064
+ }
1065
+ oseo_roots_pop(context, &frame);
1066
+ return published.status == OSEO_STATUS_NORMAL
1067
+ ? normal(roots[0])
1068
+ : published;
1069
+ }
1070
+
1071
+ bool oseo_internal_ephemeron_get(
1072
+ OseoValue table_value,
1073
+ OseoValue key,
1074
+ OseoValue *value
1075
+ ) {
1076
+ if (!has_heap_kind(table_value, OSEO_HEAP_EPHEMERON_TABLE)) return false;
1077
+ OseoValue *slot =
1078
+ ephemeron_index_find(ephemeron_table_object(table_value), key);
1079
+ if (slot == NULL) return false;
1080
+ *value = ephemeron_entry_object(*slot)->value;
1081
+ return true;
1082
+ }
1083
+
1084
+ bool oseo_internal_ephemeron_delete(OseoValue table_value, OseoValue key) {
1085
+ if (!has_heap_kind(table_value, OSEO_HEAP_EPHEMERON_TABLE)) return false;
1086
+ OseoEphemeronTable *table = ephemeron_table_object(table_value);
1087
+ OseoValue *slot = ephemeron_index_find(table, key);
1088
+ if (slot == NULL) return false;
1089
+ OseoEphemeronEntry *entry = ephemeron_entry_object(*slot);
1090
+ *slot = OSEO_EPHEMERON_INDEX_TOMBSTONE;
1091
+ if (tag_of(entry->previous) == OSEO_TAG_HEAP) {
1092
+ ephemeron_entry_object(entry->previous)->next = entry->next;
1093
+ } else {
1094
+ table->head = entry->next;
1095
+ }
1096
+ if (tag_of(entry->next) == OSEO_TAG_HEAP) {
1097
+ ephemeron_entry_object(entry->next)->previous = entry->previous;
1098
+ } else {
1099
+ table->tail = entry->previous;
1100
+ }
1101
+ entry->next = oseo_undefined();
1102
+ entry->previous = oseo_undefined();
1103
+ entry->key = oseo_undefined();
1104
+ entry->value = oseo_undefined();
1105
+ if (table->live_count > 0u) table->live_count -= 1u;
1106
+ return true;
1107
+ }
1108
+
1109
+ size_t oseo_internal_ephemeron_live_count(OseoValue table_value) {
1110
+ if (!has_heap_kind(table_value, OSEO_HEAP_EPHEMERON_TABLE)) return 0u;
1111
+ return ephemeron_table_object(table_value)->live_count;
1112
+ }
1113
+
1114
+ OseoResult oseo_internal_weak_reference_create(
1115
+ OseoContext *context,
1116
+ OseoValue target
1117
+ ) {
1118
+ if (tag_of(target) != OSEO_TAG_HEAP) {
1119
+ return failure(context, "OSEO2001", "Weak target is not a heap value.");
1120
+ }
1121
+ OseoRootFrame frame = {NULL, &target, 1u};
1122
+ oseo_roots_push(context, &frame);
1123
+ OseoWeakReference *reference =
1124
+ oseo_internal_allocate_heap_bytes(context, sizeof(*reference));
1125
+ if (reference == NULL) {
1126
+ oseo_roots_pop(context, &frame);
1127
+ return failure(
1128
+ context,
1129
+ "OSEO2001",
1130
+ "Weak reference allocation failed."
1131
+ );
1132
+ }
1133
+ reference->target = target;
1134
+ OseoResult published = oseo_internal_publish_heap(
1135
+ context,
1136
+ &reference->header,
1137
+ OSEO_HEAP_WEAK_REFERENCE
1138
+ );
1139
+ oseo_roots_pop(context, &frame);
1140
+ return published;
1141
+ }
1142
+
1143
+ OseoValue oseo_internal_weak_reference_target(OseoValue reference) {
1144
+ if (!has_heap_kind(reference, OSEO_HEAP_WEAK_REFERENCE)) {
1145
+ return oseo_undefined();
1146
+ }
1147
+ return weak_reference_object(reference)->target;
1148
+ }
1149
+
1150
+ OseoResult oseo_internal_finalization_registry_create(
1151
+ OseoContext *context,
1152
+ OseoValue callback
1153
+ ) {
1154
+ OseoRootFrame frame = {NULL, &callback, 1u};
1155
+ oseo_roots_push(context, &frame);
1156
+ OseoFinalizationRegistry *registry =
1157
+ oseo_internal_allocate_heap_bytes(context, sizeof(*registry));
1158
+ if (registry == NULL) {
1159
+ oseo_roots_pop(context, &frame);
1160
+ return failure(
1161
+ context,
1162
+ "OSEO2001",
1163
+ "Finalization registry allocation failed."
1164
+ );
1165
+ }
1166
+ registry->callback = callback;
1167
+ registry->cell_head = oseo_undefined();
1168
+ registry->cell_tail = oseo_undefined();
1169
+ OseoResult published = oseo_internal_publish_heap(
1170
+ context,
1171
+ &registry->header,
1172
+ OSEO_HEAP_FINALIZATION_REGISTRY
1173
+ );
1174
+ oseo_roots_pop(context, &frame);
1175
+ return published;
1176
+ }
1177
+
1178
+ OseoResult oseo_internal_finalization_register(
1179
+ OseoContext *context,
1180
+ OseoValue registry_value,
1181
+ OseoValue target,
1182
+ OseoValue holdings
1183
+ ) {
1184
+ return oseo_internal_finalization_register_token(
1185
+ context,
1186
+ registry_value,
1187
+ target,
1188
+ holdings,
1189
+ oseo_undefined()
1190
+ );
1191
+ }
1192
+
1193
+ OseoResult oseo_internal_finalization_register_token(
1194
+ OseoContext *context,
1195
+ OseoValue registry_value,
1196
+ OseoValue target,
1197
+ OseoValue holdings,
1198
+ OseoValue unregister_token
1199
+ ) {
1200
+ if (!has_heap_kind(registry_value, OSEO_HEAP_FINALIZATION_REGISTRY)) {
1201
+ return failure(
1202
+ context,
1203
+ "OSEO2001",
1204
+ "Value is not a finalization registry."
1205
+ );
1206
+ }
1207
+ if (tag_of(target) != OSEO_TAG_HEAP || target == holdings) {
1208
+ return failure(context, "OSEO2001", "Finalization target is invalid.");
1209
+ }
1210
+ if (context->next_finalization_order == UINT64_MAX) {
1211
+ return failure(
1212
+ context,
1213
+ "OSEO2001",
1214
+ "Finalization registration limit exceeded."
1215
+ );
1216
+ }
1217
+ OseoValue roots[] = {registry_value, target, holdings, unregister_token};
1218
+ OseoRootFrame frame = {NULL, roots, 4u};
1219
+ oseo_roots_push(context, &frame);
1220
+ OseoFinalizationCell *cell =
1221
+ oseo_internal_allocate_heap_bytes(context, sizeof(*cell));
1222
+ if (cell == NULL) {
1223
+ oseo_roots_pop(context, &frame);
1224
+ return failure(
1225
+ context,
1226
+ "OSEO2001",
1227
+ "Finalization cell allocation failed."
1228
+ );
1229
+ }
1230
+ cell->next = oseo_undefined();
1231
+ cell->queue_next = oseo_undefined();
1232
+ cell->registry = roots[0];
1233
+ cell->target = roots[1];
1234
+ cell->holdings = roots[2];
1235
+ cell->unregister_token = roots[3];
1236
+ cell->registration_order = context->next_finalization_order;
1237
+ cell->queued = false;
1238
+ cell->processed = false;
1239
+ OseoResult published = oseo_internal_publish_heap(
1240
+ context,
1241
+ &cell->header,
1242
+ OSEO_HEAP_FINALIZATION_CELL
1243
+ );
1244
+ if (published.status == OSEO_STATUS_NORMAL) {
1245
+ OseoFinalizationRegistry *registry =
1246
+ finalization_registry_object(roots[0]);
1247
+ if (has_heap_kind(
1248
+ registry->cell_tail,
1249
+ OSEO_HEAP_FINALIZATION_CELL
1250
+ )) {
1251
+ finalization_cell_object(registry->cell_tail)->next =
1252
+ published.value;
1253
+ } else {
1254
+ registry->cell_head = published.value;
1255
+ }
1256
+ registry->cell_tail = published.value;
1257
+ context->next_finalization_order += 1u;
1258
+ }
1259
+ oseo_roots_pop(context, &frame);
1260
+ return published.status == OSEO_STATUS_NORMAL
1261
+ ? normal(roots[0])
1262
+ : published;
1263
+ }
1264
+
1265
+ bool oseo_internal_finalization_unregister(
1266
+ OseoContext *context,
1267
+ OseoValue registry_value,
1268
+ OseoValue unregister_token
1269
+ ) {
1270
+ if (!has_heap_kind(registry_value, OSEO_HEAP_FINALIZATION_REGISTRY) ||
1271
+ tag_of(unregister_token) != OSEO_TAG_HEAP) {
1272
+ return false;
1273
+ }
1274
+ bool removed = false;
1275
+ OseoValue cursor = finalization_registry_object(registry_value)->cell_head;
1276
+ while (has_heap_kind(cursor, OSEO_HEAP_FINALIZATION_CELL)) {
1277
+ OseoFinalizationCell *cell = finalization_cell_object(cursor);
1278
+ cursor = cell->next;
1279
+ if (cell->processed || cell->unregister_token != unregister_token) {
1280
+ continue;
1281
+ }
1282
+ cell->processed = true;
1283
+ cell->target = oseo_undefined();
1284
+ cell->holdings = oseo_undefined();
1285
+ cell->unregister_token = oseo_undefined();
1286
+ if (cell->queued && context->finalization_pending_count > 0u) {
1287
+ context->finalization_pending_count -= 1u;
1288
+ }
1289
+ removed = true;
1290
+ }
1291
+ return removed;
1292
+ }
1293
+
1294
+ /*
1295
+ * Unlinks and consumes the oldest queued record, restricted to `registry`
1296
+ * unless it is undefined. A record an unregister already consumed has
1297
+ * given back its pending count, so the scan unlinks it without a callback.
1298
+ */
1299
+ static bool take_queued_cleanup(
1300
+ OseoContext *context,
1301
+ OseoValue registry,
1302
+ OseoValue *registry_out,
1303
+ OseoValue *holdings
1304
+ ) {
1305
+ OseoValue previous = oseo_undefined();
1306
+ OseoValue cursor = context->finalization_head;
1307
+ while (has_heap_kind(cursor, OSEO_HEAP_FINALIZATION_CELL)) {
1308
+ OseoFinalizationCell *cell = finalization_cell_object(cursor);
1309
+ OseoValue next = cell->queue_next;
1310
+ bool matches = !cell->processed &&
1311
+ (tag_of(registry) == OSEO_TAG_UNDEFINED ||
1312
+ cell->registry == registry);
1313
+ if (!cell->processed && !matches) {
1314
+ previous = cursor;
1315
+ cursor = next;
1316
+ continue;
1317
+ }
1318
+ if (has_heap_kind(previous, OSEO_HEAP_FINALIZATION_CELL)) {
1319
+ finalization_cell_object(previous)->queue_next = next;
1320
+ } else {
1321
+ context->finalization_head = next;
1322
+ }
1323
+ if (context->finalization_tail == cursor) {
1324
+ context->finalization_tail = previous;
1325
+ }
1326
+ cell->queue_next = oseo_undefined();
1327
+ cell->queued = false;
1328
+ if (!matches) {
1329
+ cursor = next;
1330
+ continue;
1331
+ }
1332
+ cell->processed = true;
1333
+ *registry_out = cell->registry;
1334
+ *holdings = cell->holdings;
1335
+ cell->holdings = oseo_undefined();
1336
+ if (context->finalization_pending_count > 0u) {
1337
+ context->finalization_pending_count -= 1u;
1338
+ }
1339
+ return true;
1340
+ }
1341
+ return false;
1342
+ }
1343
+
1344
+ bool oseo_internal_finalization_take_cleanup(
1345
+ OseoContext *context,
1346
+ OseoValue *registry,
1347
+ OseoValue *holdings
1348
+ ) {
1349
+ return take_queued_cleanup(
1350
+ context,
1351
+ oseo_undefined(),
1352
+ registry,
1353
+ holdings
1354
+ );
1355
+ }
1356
+
1357
+ bool oseo_internal_finalization_take_registry_cleanup(
1358
+ OseoContext *context,
1359
+ OseoValue registry,
1360
+ OseoValue *holdings
1361
+ ) {
1362
+ OseoValue taken = oseo_undefined();
1363
+ return has_heap_kind(registry, OSEO_HEAP_FINALIZATION_REGISTRY) &&
1364
+ take_queued_cleanup(context, registry, &taken, holdings);
1365
+ }