-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcore.js
More file actions
1770 lines (1689 loc) · 108 KB
/
Copy pathcore.js
File metadata and controls
1770 lines (1689 loc) · 108 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { OPTF } from '../src/ctx.js'
/**
* Core module — NaN-boxing, bump allocator, property dispatch.
*
* Foundation for all heap types. Every module depends on this.
* NaN-boxing: see LAYOUT in src/ctx.js for the canonical bit layout.
*
* Auto-included by array/object/string modules.
*
* @module core
*/
import { typed, asF64, asI32, asI64, NULL_NAN, UNDEF_NAN, TOMB_NAN, FALSE_NAN, TRUE_NAN, temp, usesDynProps, ptrOffsetIR, isNullish, valKindToPtr, sidecarOverride, undefExpr, cloneIR } from '../src/ir.js'
import { emit, spread, deps, wat } from '../src/bridge.js'
import { reconstructArgsWithSpreads } from '../src/ir.js'
import { valTypeOf, shapeOf } from '../src/kind.js'
import { T } from '../src/ast.js'
import { inlineArraySid, inlineArrayUnion } from '../src/static.js'
import { packedI32, structInline } from '../src/abi/index.js'
import { VAL, lookupValType, lookupNotString, repOf, updateRep } from '../src/reps.js'
import { ctx, err, inc, PTR, LAYOUT, HEAP, FORWARDING_MASK, emitArity, followForwardingWat, declGlobal } from '../src/ctx.js'
import { ptrOffsetFwdWat, STR_INTERN_BIT } from '../layout.js'
import { nanPrefixHex, nanPrefixMaskHex, ssoBitI64Hex, encodePtrHi, i64Hex } from '../layout.js'
import { initSchema } from './schema.js'
import { strHashLiteral, heapResetWat, LENGTH_SSO_I64 } from './collection.js'
const NAN_BITS = nanPrefixHex()
export default (ctx) => {
deps({
__eq: ['__str_eq', '__ptr_type', '__is_nullish'],
__eq_strict: ['__eq', '__is_nullish'],
__typeof: ['__ptr_type', '__is_nullish'],
__len: ['__typed_shift', '__ptr_offset', '__ptr_offset_fwd'],
__cap: ['__typed_shift', '__ptr_type', '__ptr_offset', '__ptr_aux'],
__typed_data: ['__ptr_offset', '__ptr_aux'],
__typed_idx: () => (ctx.features.f16 ? ['__f16_to_f64'] : []),
__ptr_offset: ['__ptr_offset_fwd'],
__ptr_offset_fwd: [],
__is_str_key: ['__ptr_type'],
__str_len: ['__ptr_type', '__ptr_offset', '__ptr_aux'],
__set_len: ['__ptr_offset_fwd'],
// Property-fallback arm (`.length` as an ordinary own key on OBJECT/HASH
// receivers) needs the dyn dispatcher — but only when the program can even
// HOLD such a property (a schema'd object or dyn/hash machinery exists);
// string/array-only programs keep the lean undefined arm.
__length: () => ['__ptr_type', '__str_len', '__len',
...(lengthNeedsDynArm() ? ['__dyn_get_expr_t_h'] : [])],
__alloc: ['__memgrow'],
__alloc_hdr: ['__alloc'],
__alloc_hdr_n: ['__alloc'],
__coll_order: ['__alloc'],
__hash_keys_ro: ['__ptr_offset', '__coll_order', '__alloc_hdr', '__mkptr'],
// Durable-receiver global-table merge (see __obj_clone's body) pulls in
// __ihash_get_local/__is_nullish only when collection.js's dyn-props
// machinery is actually part of this build (mirrors json.js's __json_obj
// and array.js's needsArrayDynMove-gated deps thunks).
__obj_clone: () => ['__ptr_type', '__ptr_aux', '__ptr_offset', '__len', '__cap', '__alloc_hdr', '__alloc_hdr_n', '__mkptr',
...(ctx.scope.globals.has('__dyn_props') ? ['__ihash_get_local', '__is_nullish'] : [])],
__durable_fwd_log: ['__alloc'],
__durable_fwd_heal: [],
__durable_slot_log: ['__alloc'],
__durable_slot_heal: [],
__is_eph_bits: [],
})
ctx.core.stdlib['__is_nullish'] = `(func $__is_nullish (param $v i64) (result i32)
(i32.or
(i64.eq (local.get $v) (i64.const ${NULL_NAN}))
(i64.eq (local.get $v) (i64.const ${UNDEF_NAN}))))`
ctx.core.stdlib['__eq'] = `(func $__eq (param $a i64) (param $b i64) (result i32)
(local $fa f64) (local $fb f64) (local $ta i32) (local $tb i32)
;; Fast path: bit equality covers identical pointers AND interned/SSO strings (same content
;; → same bits). Failing universal-NaN test catches NaN===NaN→false. Saves the NaN-check
;; pair (4 f64.eq) on the hottest case in watr (op === 'literal-string'). A number-NaN is
;; *only ever* the canonical NAN_BITS here: math ops canonicalize at the source (the
;; canon helper in module/math.js), so a non-canonical 0xFFF8.. pattern can only be a
;; negative BigInt carrier — bit-identical to itself and correctly equal.
(if (result i32) (i64.eq (local.get $a) (local.get $b))
(then (i64.ne (local.get $a) (i64.const ${NAN_BITS})))
(else
;; Bits differ. JS loose ==: null == undefined is TRUE even though they're
;; bit-DISTINCT NaN-box sentinels (NULL_NAN ≠ UNDEF_NAN) — the fast bit-equality
;; check above can't catch it, and neither can the numeric/string paths below
;; (both operands read back as NaN, neither is a STRING pointer, so without this
;; check they fall through to the final "unequal" default). Checked before the
;; numeric path so a nullish/nullish pair never even computes fa/fb.
(if (result i32)
(i32.and (call $__is_nullish (local.get $a)) (call $__is_nullish (local.get $b)))
(then (i32.const 1))
(else
;; Numeric path covers -0/+0 and any normal numeric inequality.
(local.set $fa (f64.reinterpret_i64 (local.get $a)))
(local.set $fb (f64.reinterpret_i64 (local.get $b)))
(if (result i32)
(i32.and
(f64.eq (local.get $fa) (local.get $fa))
(f64.eq (local.get $fb) (local.get $fb)))
(then (f64.eq (local.get $fa) (local.get $fb)))
(else
;; At least one operand is a NaN-box (the && above failed). For both to
;; be strings BOTH must be NaN-boxed: tag bits are only meaningful on a
;; NaN-box, so a normal number whose exponent bits happen to alias the
;; STRING tag (e.g. ASCII content read as f64) must NOT route to __str_eq
;; — that would deref garbage. number-vs-string is simply false.
(local.set $ta (i32.wrap_i64 (i64.and (i64.shr_u (local.get $a) (i64.const ${LAYOUT.TAG_SHIFT})) (i64.const ${LAYOUT.TAG_MASK}))))
(local.set $tb (i32.wrap_i64 (i64.and (i64.shr_u (local.get $b) (i64.const ${LAYOUT.TAG_SHIFT})) (i64.const ${LAYOUT.TAG_MASK}))))
(if (result i32)
(i32.and
(i32.and (f64.ne (local.get $fa) (local.get $fa)) (i32.eq (local.get $ta) (i32.const ${PTR.STRING})))
(i32.and (f64.ne (local.get $fb) (local.get $fb)) (i32.eq (local.get $tb) (i32.const ${PTR.STRING}))))
(then
;; both canonical interned (bit-ne already known) ⇒ unequal —
;; skip the __str_eq call entirely (see STR_INTERN_BIT, layout.js)
(if (result i32)
(i32.and
(i32.eq (i32.and (i32.wrap_i64 (i64.shr_u (local.get $a) (i64.const ${LAYOUT.AUX_SHIFT}))) (i32.const ${LAYOUT.SSO_BIT | LAYOUT.SLICE_BIT | STR_INTERN_BIT})) (i32.const ${STR_INTERN_BIT}))
(i32.eq (i32.and (i32.wrap_i64 (i64.shr_u (local.get $b) (i64.const ${LAYOUT.AUX_SHIFT}))) (i32.const ${LAYOUT.SSO_BIT | LAYOUT.SLICE_BIT | STR_INTERN_BIT})) (i32.const ${STR_INTERN_BIT})))
(then (i32.const 0))
(else (call $__str_eq (local.get $a) (local.get $b)))))
(else (i32.const 0))))))))))`
// Strict `===` fallback for the fully-dynamic (neither-side-a-literal) case
// emitStrictEq delegates to — everywhere ELSE strict and loose equality agree
// bit-for-bit (that's why the delegation exists at all), EXCEPT the one loose-
// only exception __eq implements: null == undefined. A thin wrapper, not a
// duplicate of __eq's body: defer to __eq for every case, but intercept
// "bits differ, both nullish" (the exact condition __eq's own exception
// fires on) and force it back to unequal.
ctx.core.stdlib['__eq_strict'] = `(func $__eq_strict (param $a i64) (param $b i64) (result i32)
(if (result i32) (i64.eq (local.get $a) (local.get $b))
(then (call $__eq (local.get $a) (local.get $b)))
(else
(if (result i32)
(i32.and (call $__is_nullish (local.get $a)) (call $__is_nullish (local.get $b)))
(then (i32.const 0))
(else (call $__eq (local.get $a) (local.get $b)))))))`
ctx.core.stdlib['__is_null'] = `(func $__is_null (param $v i64) (result i32)
(i64.eq (local.get $v) (i64.const ${NULL_NAN})))`
// Truthy check: handles regular numbers AND NaN-boxed pointers
// Falsy: 0, -0, NaN, null, undefined, "" (empty SSO)
ctx.core.stdlib['__is_truthy'] = `(func $__is_truthy (param $v i64) (result i32)
(local $f f64)
(local.set $f (f64.reinterpret_i64 (local.get $v)))
(if (result i32) (f64.eq (local.get $f) (local.get $f))
(then (f64.ne (local.get $f) (f64.const 0)))
(else
(i32.and
(i32.and
(i32.and
(i64.ne (local.get $v) (i64.const ${NAN_BITS}))
(i64.ne (local.get $v) (i64.const ${NULL_NAN})))
(i32.and
(i64.ne (local.get $v) (i64.const ${UNDEF_NAN}))
(i64.ne (local.get $v) (i64.const 0x7FFA400000000000))))
(i64.ne (local.get $v) (i64.const ${FALSE_NAN}))))))`
ctx.core.stdlib['__is_str_key'] = `(func $__is_str_key (param $v i64) (result i32)
(local $f f64)
(local.set $f (f64.reinterpret_i64 (local.get $v)))
(if (result i32) (f64.eq (local.get $f) (local.get $f))
(then (i32.const 0))
(else
(i32.eq (call $__ptr_type (i64.reinterpret_f64 (local.get $f))) (i32.const ${PTR.STRING})))))`
// Default dynamic-property helpers are harmless stubs. The collection module
// overrides them with the real sidecar-property implementation.
ctx.core.stdlib['__dyn_get'] = `(func $__dyn_get (param $obj i64) (param $key i64) (result i64)
(i64.const ${UNDEF_NAN}))`
ctx.core.stdlib['__dyn_get_or'] = `(func $__dyn_get_or (param $obj i64) (param $key i64) (param $fallback i64) (result i64)
(local.get $fallback))`
// Sidecar probe entry (sidecarOverride / the builtin-shadow method fork): with
// no dyn-props module there are no own props — the probe always misses and the
// builtin arm runs, which is exactly the stub-world semantics.
ctx.core.stdlib['__dyn_get_expr'] = `(func $__dyn_get_expr (param $obj i64) (param $key i64) (result i64)
(i64.const ${UNDEF_NAN}))`
ctx.core.stdlib['__dyn_set'] = `(func $__dyn_set (param $obj i64) (param $key i64) (param $val i64) (result i64)
(local.get $val))`
// Signature must match collection.js's real __dyn_move (i32 result: 1 = an
// entry was found+rekeyed, 0 = no-op) — array.js's grow/shift call sites are
// built once and call whichever version ends up registered.
ctx.core.stdlib['__dyn_move'] = `(func $__dyn_move (param $oldOff i32) (param $newOff i32) (result i32)
(i32.const 0))`
// Memory section auto-enabled: compile.js checks ctx.module.modules.ptr
// === NaN-boxing: encode/decode ===
ctx.core.stdlib['__mkptr'] = `(func $__mkptr (param $type i32) (param $aux i32) (param $offset i32) (result f64)
(f64.reinterpret_i64 (i64.or
(i64.const ${NAN_BITS})
(i64.or
(i64.shl (i64.and (i64.extend_i32_u (local.get $type)) (i64.const ${LAYOUT.TAG_MASK})) (i64.const ${LAYOUT.TAG_SHIFT}))
(i64.or
(i64.shl (i64.and (i64.extend_i32_u (local.get $aux)) (i64.const ${LAYOUT.AUX_MASK})) (i64.const ${LAYOUT.AUX_SHIFT}))
(i64.and (i64.extend_i32_u (local.get $offset)) (i64.const ${LAYOUT.OFFSET_MASK})))))))`
// Relative-index clamp to `[0, len]` — the JS `RelativeIndex`/`ToIntegerOrInfinity`
// bounds dance shared by slice/subarray/fill/copyWithin (string + typed + array).
// Single shared body so N method bodies don't each inline the same six branches.
wat('__clamp_idx', `(func $__clamp_idx (param $v i32) (param $len i32) (result i32)
(if (i32.lt_s (local.get $v) (i32.const 0)) (then (local.set $v (i32.add (local.get $v) (local.get $len)))))
(if (i32.lt_s (local.get $v) (i32.const 0)) (then (local.set $v (i32.const 0))))
(if (i32.gt_s (local.get $v) (local.get $len)) (then (local.set $v (local.get $len))))
(local.get $v))`)
// Polymorphic element read for any heap-indexable (ARRAY or TYPED). The one
// home for `arr[i]` lowering: ARRAY and typed reads both route here, plain-array
// programs get the ARRAY-only collapse, typed programs the full elem dispatch.
ctx.core.stdlib['__typed_idx'] = () => {
if (!ctx.features.typedarray && !ctx.features.external) {
return `(func $__typed_idx (param $ptr i64) (param $i i32) (result f64)
(local $len i32)
(local.set $len (call $__len (local.get $ptr)))
(if (result f64)
(i32.or
(i32.lt_s (local.get $i) (i32.const 0))
(i32.ge_u (local.get $i) (local.get $len)))
(then (f64.const nan:${UNDEF_NAN}))
(else (f64.load (i32.add (call $__ptr_offset (local.get $ptr)) (i32.shl (local.get $i) (i32.const 3)))))))`
}
// Hot (~37M calls in watr self-host). Type/aux/offset extracted once from $ptr.
return `(func $__typed_idx (param $ptr i64) (param $i i32) (result f64)
(local $t i32) (local $off i32) (local $et i32) (local $len i32) (local $aux i32)
(local.set $t (i32.wrap_i64 (i64.and (i64.shr_u (local.get $ptr) (i64.const ${LAYOUT.TAG_SHIFT})) (i64.const ${LAYOUT.TAG_MASK}))))
(local.set $off (i32.wrap_i64 (i64.and (local.get $ptr) (i64.const ${LAYOUT.OFFSET_MASK}))))
;; ARRAY fast path: follow forwarding inline, bounds-check against header len, f64.load — no $__len call.
(if (i32.and (i32.eq (local.get $t) (i32.const ${PTR.ARRAY})) (i32.ge_u (local.get $off) (i32.const 8)))
(then
${followForwardingWat('$off', { lowGuard: false })}
(return (if (result f64)
(i32.and (i32.ge_s (local.get $i) (i32.const 0)) (i32.lt_u (local.get $i) (i32.load (i32.sub (local.get $off) (i32.const 8)))))
(then (f64.load (i32.add (local.get $off) (i32.shl (local.get $i) (i32.const 3)))))
(else (f64.const nan:${UNDEF_NAN}))))))
(local.set $aux (i32.wrap_i64 (i64.and (i64.shr_u (local.get $ptr) (i64.const ${LAYOUT.AUX_SHIFT})) (i64.const ${LAYOUT.AUX_MASK}))))
(if
(i32.and
(i32.eq (local.get $t) (i32.const ${PTR.TYPED}))
(i32.ne (i32.and (local.get $aux) (i32.const 8)) (i32.const 0)))
(then (local.set $off (i32.load (i32.add (local.get $off) (i32.const 4))))))
(local.set $len (call $__len (local.get $ptr)))
(if (result f64)
(i32.or
(i32.lt_s (local.get $i) (i32.const 0))
(i32.ge_u (local.get $i) (local.get $len)))
(then (f64.const nan:${UNDEF_NAN}))
(else
(if (result f64) (i32.eq (local.get $t) (i32.const ${PTR.TYPED}))
(then
(local.set $et (i32.and (local.get $aux) (i32.const 7)))
(if (result f64) (i32.ge_u (local.get $et) (i32.const 6))
(then (if (result f64) (i32.eq (local.get $et) (i32.const 7))
(then (if (result f64) (i32.and (local.get $aux) (i32.const 16))
(then (f64.reinterpret_i64 (i64.load (i32.add (local.get $off) (i32.shl (local.get $i) (i32.const 3))))))
(else (f64.load (i32.add (local.get $off) (i32.shl (local.get $i) (i32.const 3)))))))
(else (f64.promote_f32 (f32.load (i32.add (local.get $off) (i32.shl (local.get $i) (i32.const 2))))))))
(else (if (result f64) (i32.ge_u (local.get $et) (i32.const 4))
(then (if (result f64) (i32.and (local.get $et) (i32.const 1))
(then (f64.convert_i32_u (i32.load (i32.add (local.get $off) (i32.shl (local.get $i) (i32.const 2))))))
(else (f64.convert_i32_s (i32.load (i32.add (local.get $off) (i32.shl (local.get $i) (i32.const 2))))))))
(else (if (result f64) (i32.ge_u (local.get $et) (i32.const 2))
(then ${ctx.features.f16 ? `(if (result f64) (i32.and (local.get $aux) (i32.const 32))
(then (call $__f16_to_f64 (i32.load16_u (i32.add (local.get $off) (i32.shl (local.get $i) (i32.const 1))))))
(else ` : ''}(if (result f64) (i32.and (local.get $et) (i32.const 1))
(then (f64.convert_i32_u (i32.load16_u (i32.add (local.get $off) (i32.shl (local.get $i) (i32.const 1))))))
(else (f64.convert_i32_s (i32.load16_s (i32.add (local.get $off) (i32.shl (local.get $i) (i32.const 1)))))))${ctx.features.f16 ? '))' : ''})
(else (if (result f64) (i32.and (local.get $et) (i32.const 1))
(then (f64.convert_i32_u (i32.load8_u (i32.add (local.get $off) (local.get $i)))))
(else (f64.convert_i32_s (i32.load8_s (i32.add (local.get $off) (local.get $i)))))))))))))
(else (f64.load (i32.add (local.get $off) (i32.shl (local.get $i) (i32.const 3)))))))))`
}
ctx.core.stdlib['__ptr_offset_fwd'] = ptrOffsetFwdWat()
ctx.core.stdlib['__ptr_offset'] = `(func $__ptr_offset (param $ptr i64) (result i32)
(local $bits i64) (local $off i32) (local $t i32)
(local.set $bits (local.get $ptr))
(local.set $off (i32.wrap_i64 (i64.and (local.get $bits) (i64.const ${LAYOUT.OFFSET_MASK}))))
;; ARRAY/SET/MAP/HASH can be reallocated on growth; follow the forwarding pointer
;; (cap=-1 sentinel at -4, new offset at -8). Other types never forward, so they skip
;; the loop; a well-formed ptr without forwarding pays one bounds + cap check per hop.
(local.set $t (i32.wrap_i64 (i64.and (i64.shr_u (local.get $bits) (i64.const ${LAYOUT.TAG_SHIFT})) (i64.const ${LAYOUT.TAG_MASK}))))
(if (i32.and (i32.shl (i32.const 1) (local.get $t)) (i32.const ${FORWARDING_MASK}))
(then
${followForwardingWat('$off', { lowGuard: true })}))
(local.get $off))`
ctx.core.stdlib['__ptr_aux'] = `(func $__ptr_aux (param $ptr i64) (result i32)
(i32.wrap_i64 (i64.and (i64.shr_u (local.get $ptr) (i64.const ${LAYOUT.AUX_SHIFT})) (i64.const ${LAYOUT.AUX_MASK}))))`
// Exact JS `%` (fmod) for the f64 path. wasm has no f64 remainder, and the
// textbook `a - b*trunc(a/b)` is both INEXACT (rounding in trunc/mul/sub for
// large a/b) and WRONG on the IEEE edges. This does the spec exactly:
// NaN if a or b is NaN, a is ±Inf, or b is 0; a if b is ±Inf or |a|<|b|;
// otherwise binary long division — scale |b| up to ≤|a|, then subtract-and-
// halve back down to |b|. Every step (×2, ×0.5, aligned subtraction) is
// exact in f64, so the remainder is bit-identical to JS. Sign follows the
// dividend (copysign), matching `(-5)%3 === -2`, `5%(-3) === 2`, `-0%3 === -0`.
ctx.core.stdlib['__rem'] = `(func $__rem (param $a f64) (param $b f64) (result f64)
(local $x f64) (local $y f64)
(if (f64.ne (local.get $a) (local.get $a)) (then (return (local.get $a))))
(if (f64.ne (local.get $b) (local.get $b)) (then (return (local.get $b))))
(local.set $x (f64.abs (local.get $a)))
(local.set $y (f64.abs (local.get $b)))
(if (i32.or (f64.eq (local.get $x) (f64.const inf)) (f64.eq (local.get $y) (f64.const 0)))
(then (return (f64.div (f64.const 0) (f64.const 0)))))
(if (i32.or (f64.eq (local.get $y) (f64.const inf)) (f64.lt (local.get $x) (local.get $y)))
(then (return (local.get $a))))
(block $up (loop $ul
(br_if $up (f64.gt (f64.mul (local.get $y) (f64.const 2)) (local.get $x)))
(local.set $y (f64.mul (local.get $y) (f64.const 2)))
(br $ul)))
(block $dn (loop $dl
(br_if $dn (f64.lt (local.get $y) (f64.abs (local.get $b))))
(if (f64.ge (local.get $x) (local.get $y)) (then (local.set $x (f64.sub (local.get $x) (local.get $y)))))
(local.set $y (f64.mul (local.get $y) (f64.const 0.5)))
(br $dl)))
(f64.copysign (local.get $x) (local.get $a)))`
ctx.core.stdlib['__ptr_type'] = `(func $__ptr_type (param $ptr i64) (result i32)
(i32.wrap_i64 (i64.and (i64.shr_u (local.get $ptr) (i64.const ${LAYOUT.TAG_SHIFT})) (i64.const ${LAYOUT.TAG_MASK}))))`
// True iff a NaN-boxed value is a non-primitive (heap object) — tag is neither
// ATOM (null/undefined/boolean/symbol) nor STRING. A genuine f64 Number is
// never NaN-boxed, so `f64.eq(x,x)` holding proves it a primitive. Drives the
// ES `OrdinaryToPrimitive` method-fallback chain (src/ir.js toPrimitiveChain).
ctx.core.stdlib['__is_object'] = `(func $__is_object (param $p i64) (result i32)
(local $t i32)
(if (f64.eq (f64.reinterpret_i64 (local.get $p)) (f64.reinterpret_i64 (local.get $p)))
(then (return (i32.const 0))))
(local.set $t (call $__ptr_type (local.get $p)))
(i32.and
(i32.ne (local.get $t) (i32.const ${PTR.ATOM}))
(i32.ne (local.get $t) (i32.const ${PTR.STRING}))))`
// === Bump allocator ===
// Heap-base watermark: gates header-backed propsPtr fast paths so static-data
// OBJECT slots (offsets < heap base) don't misread arbitrary memory at off-16.
// Updated by optimizeModule() when data segment exceeds HEAP.START bytes.
declGlobal('__heap_start', 'i32', HEAP.START)
// Current memory limit in BYTES — __alloc's inline fast-path check
// (`next > __heap_end` → slow __memgrow call) replaces a per-alloc call whose
// page math always concluded "no grow" (jessie: 1.1M entries/run). __memgrow
// updates it after any growth; stale-LOW is safe (one extra slow call) and
// wasm memory never shrinks. 65536-page (4 GiB) memories wrap the shl to 0 —
// every alloc slow-paths there, still correct. Seeded 0: first alloc pays once.
declGlobal('__heap_end', 'i32', 0)
// i64 twin of __heap_end, for the CORRECTNESS-sensitive forwarding-chase bound
// (layout.js's followForwardingWat/ptrOffsetFwdWat, and their inline collection.js
// dyn-props copies): those checks gate whether a relocated ARRAY/SET/MAP/HASH's
// forwarding header gets followed at all, so the __heap_end wraparound-to-0 at the
// wasm32 4 GiB ceiling — benign for __alloc's slow-path retry — would there instead
// silently disable forwarding forever (every off > 0 reads as "out of bounds", so the
// cap=-1 sentinel of an abandoned block is never re-chased and gets misread as a real
// capacity). __memgrow updates this alongside __heap_end so every hot dereference site
// pays one $__heap_end64 global read instead of recomputing i64.shl(memory.size,16).
declGlobal('__heap_end64', 'i64', 0)
// Shared memory keeps the heap pointer in linear memory (memory[HEAP.PTR_ADDR]):
// wasm globals are per-instance, so threads sharing one memory must share one
// pointer cell. Non-shared memory (incl. alloc:false) uses the `$__heap`
// global — exported so the JS-side adapter (memory.String etc) bumps the same
// pointer. Storing it in memory would collide with the static data section
// whenever the data exceeds HEAP.PTR_ADDR bytes.
// Geometric memory growth shared by `__alloc` and the in-place string
// bump-extend paths (string.js). Ensures linear memory covers byte offset
// `$next`, growing when short. Growing one page at a time turns a long-running
// embedding (watr called thousands of times) into O(n²) — each memory.grow may
// relocate and copy the whole heap — so we request at least the current size
// (≥2× total) in one shot; only on hitting the declared maximum do we fall back
// to the bare minimum. `$need` is the TOTAL pages required to cover $next; the
// byte size of memory ((memory.size)<<16) is computed in i64 because it
// overflows i32 at the wasm32 max of 65536 pages (4 GiB) — without that,
// capacity reads as 0 and every allocation spuriously tries to grow past the
// ceiling, trapping near 4 GiB.
ctx.core.stdlib['__memgrow'] = `(func $__memgrow (param $next i32)
(local $cur i32) (local $need i32)
(local.set $need (i32.wrap_i64 (i64.shr_u (i64.add (i64.extend_i32_u (local.get $next)) (i64.const 65535)) (i64.const 16))))
(if (i32.gt_u (local.get $need) (memory.size))
(then
(if (i64.gt_u (i64.extend_i32_u (local.get $need)) (i64.const 65536)) (then (unreachable)))
(local.set $cur (i32.sub (local.get $need) (memory.size))) ;; minimum delta
(if (i32.lt_u (local.get $cur) (memory.size)) (then (local.set $cur (memory.size)))) ;; geometric
(if (i32.gt_u (i32.add (local.get $cur) (memory.size)) (i32.const 65536))
(then (local.set $cur (i32.sub (i32.const 65536) (memory.size))))) ;; cap at wasm32 max
(if (i32.eq (memory.grow (local.get $cur)) (i32.const -1))
(then (if (i32.eq (memory.grow (i32.sub (local.get $need) (memory.size))) (i32.const -1))
(then (unreachable)))))))
(global.set $__heap_end (i32.shl (memory.size) (i32.const 16)))
(global.set $__heap_end64 (i64.shl (i64.extend_i32_u (memory.size)) (i64.const 16))))`
if (ctx.memory.shared) {
// Heap offset stored at memory[HEAP.PTR_ADDR] (i32), just before heap start at
// HEAP.START. Threads sharing one memory must share one pointer cell.
// TRULY-shared memory (opts.sharedMemory → ctx.memory.atomic): the bump is a
// CAS retry loop — a plain load/store pair would hand two racing threads the
// same block. Plain imported memory keeps the cheap non-atomic bump.
ctx.core.stdlib['__alloc'] = ctx.memory.atomic ? `(func $__alloc (param $bytes i32) (result i32)
(local $ptr i32) (local $next i32)
(block $done (loop $retry
(local.set $ptr (i32.atomic.load (i32.const ${HEAP.PTR_ADDR})))
(local.set $next (i32.and (i32.add (i32.add (local.get $ptr) (local.get $bytes)) (i32.const 7)) (i32.const -8)))
(if (i32.gt_u (local.get $next) (global.get $__heap_end))
(then (call $__memgrow (local.get $next))))
(br_if $done (i32.eq
(i32.atomic.rmw.cmpxchg (i32.const ${HEAP.PTR_ADDR}) (local.get $ptr) (local.get $next))
(local.get $ptr)))
(br $retry)))
(local.get $ptr))` : `(func $__alloc (param $bytes i32) (result i32)
(local $ptr i32) (local $next i32)
(local.set $ptr (i32.load (i32.const ${HEAP.PTR_ADDR})))
(local.set $next (i32.and (i32.add (i32.add (local.get $ptr) (local.get $bytes)) (i32.const 7)) (i32.const -8)))
(if (i32.gt_u (local.get $next) (global.get $__heap_end))
(then (call $__memgrow (local.get $next))))
(i32.store (i32.const ${HEAP.PTR_ADDR}) (local.get $next))
(local.get $ptr))`
// NOTE: shared memory rewinds to the raw HEAP.START, NOT a post-init high-water
// mark — so a shared module whose `__start` heap-allocates (strPool memory.init,
// module-init state) loses that state on `_clear`. Pre-existing; unlike the owned
// path below it has no `__heap_reset` analogue because the rewind target would need
// a reserved low-memory cell (the [0,HEAP.START) region is already spoken for —
// clock at 0, heap ptr at HEAP.PTR_ADDR). Owned memory (the self-host + default
// case) is the one fixed below; revisit shared if a thread-pooled reset hits it.
ctx.core.stdlib['__clear'] = `(func $__clear
(${ctx.memory.atomic ? 'i32.atomic.store' : 'i32.store'} (i32.const ${HEAP.PTR_ADDR}) (i32.const ${HEAP.START})))`
} else {
// Own memory: heap offset in a global, exported so the JS-side adapter
// (alloc:false, no `_alloc` export) shares the pointer.
declGlobal('__heap', 'i32', HEAP.START, { export: '__heap' })
// `__clear` rewinds to the *post-module-init* high-water mark, not the static
// data end: a module whose top-level code heap-allocates (e.g. the self-host
// compiler building its GLOBALS/atom tables in `__start`) leaves live state
// above the data segment that a reset must preserve. `__heap_reset` is seeded
// to the data end (assemble.js heapBase patch) and overwritten by `__start`'s
// tail with the heap top after init runs (buildStartFn) — so for a module with
// no init allocations it equals the data end, and for self-host it spares the
// compiler's init state. (Distinct from `__heap_start`, the propsPtr watermark,
// which must stay at the data end or init-time heap objects misread as static.)
declGlobal('__heap_reset', 'i32', HEAP.START)
ctx.core.stdlib['__alloc'] = `(func $__alloc (param $bytes i32) (result i32)
(local $ptr i32) (local $next i32)
(local.set $ptr (global.get $__heap))
(local.set $next (i32.and (i32.add (i32.add (local.get $ptr) (local.get $bytes)) (i32.const 7)) (i32.const -8)))
(if (i32.gt_u (local.get $next) (global.get $__heap_end))
(then (call $__memgrow (local.get $next))))
(global.set $__heap (local.get $next))
(local.get $ptr))`
// __clear rewinds the bump arena, but __dyn_props/__dyn_get_cache_* (declared
// unconditionally whenever the collection module loads — module/collection.js)
// cache pointers/offsets INTO that arena across calls, so a warm compile-clear-
// compile loop needs them reset too — see the post-hoc patch in
// src/wat/assemble.js (search "__dyn_props reset") for WHY this can't gate on
// `ctx.scope.globals.has(...)` at declaration time: that's true whenever
// collection is loaded AT ALL, even for a program that never touches dynamic
// props, and __clear's own resolved text is scanned by reachableStdlib — an
// unconditional `global.set $__dyn_props` line here would leak that (dead,
// for this program) name into non-dyn-prop output, both wasting bytes and
// (worse) tripping WAT-substring test assertions like
// `!/__dyn_get/.test(wat)` (test/closures.js) since __dyn_get_cache_off/props
// contain that substring. The real gate — whether __dyn_set (the only writer
// of __dyn_props) is actually reachable — isn't known until AFTER
// reachableStdlib runs, so the reset is injected post-hoc once that's settled.
ctx.core.stdlib['__clear'] = `(func $__clear
(global.set $__heap (global.get $__heap_reset)))`
// Durable relocation log — see collection.js's durableFwdLogIR for the full
// rationale (array/hash/set/map growth forwards a DURABLE header into an
// EPHEMERAL new block; `_clear` must heal that back before rewinding the arena
// or the durable alias dangles forever). `__durable_fwd_buf` is allocated
// lazily (raw `__alloc`, no forwarding-capable header of its own — it must
// never recurse into the bug it exists to fix) on the first durable grow of a
// round; `__durable_fwd_heal` (wired into `__clear` post-hoc, see
// src/wat/assemble.js) restores every logged header to its pre-grow (len, cap)
// and resets both globals to 0 so the buffer is re-allocated fresh next round —
// it only needs to survive from "logged this round" to "healed at this round's
// `_clear`", never across a reset. 256 entries is a trap-on-overflow ceiling
// for a count that is 0 in the overwhelmingly common program (real durable-
// growth sites are a handful of compiler-internal structures, not user data).
declGlobal('__durable_fwd_buf', 'i32')
declGlobal('__durable_fwd_n', 'i32')
ctx.core.stdlib['__durable_fwd_log'] = `(func $__durable_fwd_log (param $off i32) (param $len i32) (param $cap i32)
(local $base i32) (local $n i32)
(if (i32.eqz (global.get $__durable_fwd_buf))
(then (global.set $__durable_fwd_buf (call $__alloc (i32.const 3072)))))
(local.set $n (global.get $__durable_fwd_n))
(if (i32.ge_s (local.get $n) (i32.const 256)) (then (unreachable)))
(local.set $base (i32.add (global.get $__durable_fwd_buf) (i32.mul (local.get $n) (i32.const 12))))
(i32.store (local.get $base) (local.get $off))
(i32.store (i32.add (local.get $base) (i32.const 4)) (local.get $len))
(i32.store (i32.add (local.get $base) (i32.const 8)) (local.get $cap))
(global.set $__durable_fwd_n (i32.add (local.get $n) (i32.const 1))))`
ctx.core.stdlib['__durable_fwd_heal'] = `(func $__durable_fwd_heal
(local $i i32) (local $n i32) (local $base i32) (local $off i32)
(local.set $n (global.get $__durable_fwd_n))
(block $done (loop $l
(br_if $done (i32.ge_s (local.get $i) (local.get $n)))
(local.set $base (i32.add (global.get $__durable_fwd_buf) (i32.mul (local.get $i) (i32.const 12))))
(local.set $off (i32.load (local.get $base)))
(i32.store (i32.sub (local.get $off) (i32.const 8)) (i32.load (i32.add (local.get $base) (i32.const 4))))
(i32.store (i32.sub (local.get $off) (i32.const 4)) (i32.load (i32.add (local.get $base) (i32.const 8))))
(local.set $i (i32.add (local.get $i) (i32.const 1)))
(br $l)))
(global.set $__durable_fwd_n (i32.const 0))
(global.set $__durable_fwd_buf (i32.const 0)))`
// Durable SLOT log — the value-write sibling of the relocation log above. A
// collection whose storage is DURABLE (init-created dict, off < __heap_reset)
// can receive an EPHEMERAL boxed value at runtime (a memo caching this round's
// parsed node, a registry entry) — the slot then dangles across \`_clear\` and
// the next round reads reused-arena garbage through it (the corpus-wide warm
// trap: a durable literal-text→node dict handing round-1 node arrays into
// round-2's tree). Writers call \`__durable_slot_log(addr)\` when storing an
// ephemeral value into a durable slot (see collection.js durableSlotLogIR);
// \`__durable_slot_heal\` (wired into \`__clear\` post-hoc, like the fwd heal)
// overwrites every logged slot with \`undefined\` — the pointed-at data dies
// with the arena, so entry-death is the only sound semantics. Same lazy-buffer
// + trap-ceiling design as the fwd log; slots are 4 bytes each so one page
// covers 1024 writes (durable-receiver writes are rare by construction).
declGlobal('__durable_slot_buf', 'i32')
declGlobal('__durable_slot_n', 'i32')
ctx.core.stdlib['__is_eph_bits'] = `(func $__is_eph_bits (param $b i64) (result i32)
(local $t i32)
;; boxed heap pointer: quiet-NaN prefix, heap-kind tag, non-SSO, offset past the durable watermark
(if (i64.ne (i64.and (local.get $b) (i64.const ${nanPrefixMaskHex()})) (i64.const ${nanPrefixHex()}))
(then (return (i32.const 0))))
(local.set $t (i32.wrap_i64 (i64.and (i64.shr_u (local.get $b) (i64.const ${LAYOUT.TAG_SHIFT})) (i64.const ${LAYOUT.TAG_MASK}))))
;; heap kinds {ARRAY,BUFFER,TYPED,STRING,OBJECT,HASH,SET,MAP,CLOSURE} = bits 1-4,6-10 → 0x7DE
(if (i32.eqz (i32.and (i32.shl (i32.const 1) (local.get $t)) (i32.const 0x7DE)))
(then (return (i32.const 0))))
(if (i32.and (i32.eq (local.get $t) (i32.const ${PTR.STRING}))
(i64.ne (i64.and (local.get $b) (i64.const ${ssoBitI64Hex()})) (i64.const 0)))
(then (return (i32.const 0))))
(i32.ge_u (i32.wrap_i64 (i64.and (local.get $b) (i64.const 0xFFFFFFFF))) (global.get $__heap_reset)))`
ctx.core.stdlib['__durable_slot_log'] = `(func $__durable_slot_log (param $addr i32) (param $tbl i32)
(local $n i32) (local $base i32)
(if (i32.eqz (global.get $__durable_slot_buf))
(then (global.set $__durable_slot_buf (call $__alloc (i32.const 8192)))))
(local.set $n (global.get $__durable_slot_n))
(if (i32.ge_s (local.get $n) (i32.const 1024)) (then (unreachable)))
(local.set $base (i32.add (global.get $__durable_slot_buf) (i32.shl (local.get $n) (i32.const 3))))
(i32.store (local.get $base) (local.get $addr))
(i32.store (i32.add (local.get $base) (i32.const 4)) (local.get $tbl))
(global.set $__durable_slot_n (i32.add (local.get $n) (i32.const 1))))`
ctx.core.stdlib['__durable_slot_heal'] = `(func $__durable_slot_heal
(local $i i32) (local $n i32) (local $a i32) (local $base i32) (local $tbl i32)
(local.set $n (global.get $__durable_slot_n))
(block $done (loop $l
(br_if $done (i32.ge_s (local.get $i) (local.get $n)))
(local.set $base (i32.add (global.get $__durable_slot_buf) (i32.shl (local.get $i) (i32.const 3))))
(local.set $a (i32.load (local.get $base)))
(local.set $tbl (i32.load (i32.add (local.get $base) (i32.const 4))))
(if (i32.and (local.get $a) (i32.const 1))
;; bit0: ENTRY heal — this round INSERTED the entry into durable storage; a
;; fresh instance would not have it. Zombie it (key TOMB, value undefined —
;; probes pass over, __coll_order skips) and decrement the table len so
;; len-sized iteration and .size agree. Runs AFTER __durable_fwd_heal, so a
;; grown-then-healed table's len is already its restored pre-grow value.
(then
(local.set $a (i32.and (local.get $a) (i32.const -2)))
(i64.store (i32.add (local.get $a) (i32.const 8)) (i64.const ${TOMB_NAN}))
(i64.store (i32.add (local.get $a) (i32.const 16)) (i64.const ${UNDEF_NAN}))
(i32.store (i32.sub (local.get $tbl) (i32.const 8))
(i32.sub (i32.load (i32.sub (local.get $tbl) (i32.const 8))) (i32.const 1))))
;; plain: VALUE heal — the entry pre-existed durably; its old value is
;; unrecoverable, undefined is the honest read.
(else (i64.store (local.get $a) (i64.const ${UNDEF_NAN}))))
(local.set $i (i32.add (local.get $i) (i32.const 1)))
(br $l)))
(global.set $__durable_slot_n (i32.const 0))
(global.set $__durable_slot_buf (i32.const 0)))`
}
// Build an insertion-ordered list of live slot offsets for a Set/Map/HASH
// backing table at $off (cap slots of $stride bytes). Returns a fresh i32 array
// (live-count entries) of slot offsets sorted by packed sequence (the insertion
// counter rides in each entry's hash-word high 32 bits — see collection.js's
// seqStore). Every order-sensitive iteration (keys/values/entries, for-in,
// spread, JSON, Map copy) walks this instead of raw slot order, so jz matches
// the JS spec's insertion order. Lives in core (not collection) because object
// and json iterate HASH tables without pulling the collection module. Insertion
// sort: enumerated collections are small, and it stays branch-light when sorted.
ctx.core.stdlib['__coll_order'] = `(func $__coll_order (param $off i32) (param $cap i32) (param $stride i32) (result i32)
(local $i i32) (local $n i32) (local $slot i32) (local $buf i32)
(local $j i32) (local $k i32) (local $cur i32) (local $sq i32)
;; A null/empty backing pointer (off below the heap base) has no live slots —
;; ordering it yields the empty list. Guard before the $off-8 length read so a
;; degenerate receiver returns an empty buffer instead of faulting on load(-8).
(if (i32.lt_u (local.get $off) (i32.const ${HEAP.START})) (then (return (call $__alloc (i32.const 0)))))
(local.set $buf (call $__alloc (i32.shl (i32.load (i32.sub (local.get $off) (i32.const 8))) (i32.const 2))))
;; gather live slot offsets (occupied ⇔ hash word ≠ 0)
(block $gd (loop $gl
(br_if $gd (i32.ge_s (local.get $i) (local.get $cap)))
(local.set $slot (i32.add (local.get $off) (i32.mul (local.get $i) (local.get $stride))))
(if (i32.and
(i64.ne (i64.load (local.get $slot)) (i64.const 0))
;; skip healed zombie entries (durable-slot heal: key = TOMB sentinel)
(i64.ne (i64.load (i32.add (local.get $slot) (i32.const 8))) (i64.const ${TOMB_NAN})))
(then
(i32.store (i32.add (local.get $buf) (i32.shl (local.get $n) (i32.const 2))) (local.get $slot))
(local.set $n (i32.add (local.get $n) (i32.const 1)))))
(local.set $i (i32.add (local.get $i) (i32.const 1)))
(br $gl)))
;; insertion-sort buf[0..n) ascending by sequence = hash-word high 32 bits
(local.set $j (i32.const 1))
(block $sd (loop $sl
(br_if $sd (i32.ge_s (local.get $j) (local.get $n)))
(local.set $cur (i32.load (i32.add (local.get $buf) (i32.shl (local.get $j) (i32.const 2)))))
(local.set $sq (i32.wrap_i64 (i64.shr_u (i64.load (local.get $cur)) (i64.const 32))))
(local.set $k (i32.sub (local.get $j) (i32.const 1)))
(block $id (loop $il
(br_if $id (i32.lt_s (local.get $k) (i32.const 0)))
(br_if $id (i32.le_u
(i32.wrap_i64 (i64.shr_u (i64.load (i32.load (i32.add (local.get $buf) (i32.shl (local.get $k) (i32.const 2))))) (i64.const 32)))
(local.get $sq)))
(i32.store (i32.add (local.get $buf) (i32.shl (i32.add (local.get $k) (i32.const 1)) (i32.const 2)))
(i32.load (i32.add (local.get $buf) (i32.shl (local.get $k) (i32.const 2)))))
(local.set $k (i32.sub (local.get $k) (i32.const 1)))
(br $il)))
(i32.store (i32.add (local.get $buf) (i32.shl (i32.add (local.get $k) (i32.const 1)) (i32.const 2))) (local.get $cur))
(local.set $j (i32.add (local.get $j) (i32.const 1)))
(br $sl)))
(local.get $buf))`
// for-in's HASH key enumeration with a 1-slot enum cache (V8's EnumCache analog).
// A for-in over an unchanged dict re-derives the same key array every entry —
// __coll_order buffer + out-array alloc + cap scan + sort per loop entry (the
// dominant cost of any per-call `for (k in cfg)` pattern: jessie's comment
// wrapper paid this per TOKEN). Cache the boxed key array keyed by
// (table off, live len): an insert changes len, so it misses naturally with no
// insert-side hook; the only len-preserving key-set change is delete-then-insert,
// so the HASH delete (genDelete, collection.js) clears the cache unconditionally;
// `__clear` resets it (arena rewind can re-issue the cached off to a new table).
// Grow/remint relocation is safe hook-free: reads resolve forwarding to the new
// off (≠ cached), and a husk off is never re-issued within an arena epoch.
// ONLY sound for for-in (`__keys_ro`), whose result is read-only by construction —
// Object.keys must keep fresh-array semantics (callers may mutate the result).
ctx.core.stdlib['__hash_keys_ro'] = `(func $__hash_keys_ro (param $hbits i64) (result f64)
(local $off i32) (local $n i32) (local $ord i32) (local $i i32) (local $out i32)
(local.set $off (call $__ptr_offset (local.get $hbits)))
;; degenerate/null backing (off below heap base): empty result, uncached
(if (i32.lt_u (local.get $off) (i32.const ${HEAP.START}))
(then (return (call $__mkptr (i32.const ${PTR.ARRAY}) (i32.const 0) (call $__alloc_hdr (i32.const 0) (i32.const 0))))))
(local.set $n (i32.load (i32.sub (local.get $off) (i32.const 8))))
(if (i32.and (i32.eq (local.get $off) (global.get $__enumc_off))
(i32.eq (local.get $n) (global.get $__enumc_len)))
(then (return (global.get $__enumc_arr))))
(local.set $ord (call $__coll_order (local.get $off)
(i32.load (i32.sub (local.get $off) (i32.const 4))) (i32.const 24)))
(local.set $out (call $__alloc_hdr (local.get $n) (local.get $n)))
(block $brk (loop $l
(br_if $brk (i32.ge_s (local.get $i) (local.get $n)))
(i64.store (i32.add (local.get $out) (i32.shl (local.get $i) (i32.const 3)))
(i64.load (i32.add (i32.load (i32.add (local.get $ord) (i32.shl (local.get $i) (i32.const 2)))) (i32.const 8))))
(local.set $i (i32.add (local.get $i) (i32.const 1)))
(br $l)))
(global.set $__enumc_off (local.get $off))
(global.set $__enumc_len (local.get $n))
(global.set $__enumc_arr (call $__mkptr (i32.const ${PTR.ARRAY}) (i32.const 0) (local.get $out)))
(global.get $__enumc_arr))`
// === Memory-based length/cap helpers (C-style headers) ===
// Array/TypedArray/Buffer: [-8:len(i32)][-4:cap(i32)][data...]
// For ARRAY/HASH/SET/MAP: len is element count.
// For BUFFER: len is byte count. For owned TYPED: header stores byte count; len
// is derived as byteLen >> log2(stride) so reinterpret views share their parent
// BUFFER's header (zero-copy aliasing).
// For TYPED subviews (aux bit 3 set): offset points to a 16-byte descriptor
// [0:byteLen(i32)][4:dataOff(i32)][8:parentOff(i32)][12:pad]
// elemType = aux & 7, isView = aux & 8.
ctx.core.stdlib['__typed_shift'] = `(func $__typed_shift (param $et i32) (result i32)
(if (result i32) (i32.eq (local.get $et) (i32.const 7))
(then (i32.const 3))
(else (if (result i32) (i32.ge_u (local.get $et) (i32.const 4))
(then (i32.const 2))
(else (i32.shr_u (local.get $et) (i32.const 1)))))))`
// Real data address for any TYPED ptr: owned → offset, view → [offset+4].
ctx.core.stdlib['__typed_data'] = `(func $__typed_data (param $ptr i64) (result i32)
(local $off i32)
(local.set $off (call $__ptr_offset (local.get $ptr)))
(if (result i32) (i32.and (call $__ptr_aux (local.get $ptr)) (i32.const 8))
(then (i32.load (i32.add (local.get $off) (i32.const 4))))
(else (local.get $off))))`
// === binary16 ↔ f64 (Float16Array / DataView.getFloat16 / Math.f16round) ===
// Pure-integer, exactly rounded — f64 → f16 rounds DIRECTLY off the f64 bits
// (an f32 hop double-rounds at the overflow boundary: 65519.999… must round
// to 65504, not Inf). f16 → f64 is exact by construction (every half is a
// double). NaN canonicalizes (sign/payload dropped) so `v !== v` stays sound
// on jz's canonical-NaN model.
ctx.core.stdlib['__f16_to_f64'] = `(func $__f16_to_f64 (param $b i32) (result f64)
(local $h i32) (local $e i32) (local $m i32) (local $r f64)
(local.set $h (i32.and (local.get $b) (i32.const 0x7FFF)))
(local.set $e (i32.shr_u (local.get $h) (i32.const 10)))
(local.set $m (i32.and (local.get $h) (i32.const 0x3FF)))
(if (i32.eq (local.get $e) (i32.const 31))
(then
(if (local.get $m)
(then (return (f64.reinterpret_i64 (i64.const ${nanPrefixHex()}))))
(else (return (f64.reinterpret_i64 (i64.or (i64.const 0x7FF0000000000000)
(i64.shl (i64.extend_i32_u (i32.and (local.get $b) (i32.const 0x8000))) (i64.const 48)))))))))
(if (i32.eqz (local.get $e))
;; subnormal: mant · 2^-24 (exact — integer times a power of two)
(then (local.set $r (f64.mul (f64.convert_i32_u (local.get $m)) (f64.const 5.960464477539063e-8))))
(else (local.set $r (f64.reinterpret_i64 (i64.or
(i64.shl (i64.extend_i32_u (i32.add (local.get $e) (i32.const 1008))) (i64.const 52))
(i64.shl (i64.extend_i32_u (local.get $m)) (i64.const 42)))))))
(f64.reinterpret_i64 (i64.or (i64.reinterpret_f64 (local.get $r))
(i64.shl (i64.extend_i32_u (i32.and (local.get $b) (i32.const 0x8000))) (i64.const 48)))))`
ctx.core.stdlib['__f64_to_f16'] = `(func $__f64_to_f16 (param $v f64) (result i32)
(local $u i64) (local $sign i32) (local $ne i32) (local $half i32)
(local $m i64) (local $full i64) (local $sh i64) (local $rb i64) (local $hp i64)
(local.set $u (i64.reinterpret_f64 (local.get $v)))
(local.set $sign (i32.wrap_i64 (i64.and (i64.shr_u (local.get $u) (i64.const 48)) (i64.const 0x8000))))
(local.set $u (i64.and (local.get $u) (i64.const 0x7FFFFFFFFFFFFFFF)))
(if (i64.ge_u (local.get $u) (i64.const 0x7FF0000000000000))
(then (return (i32.or (local.get $sign)
(select (i32.const 0x7E00) (i32.const 0x7C00) (i64.gt_u (local.get $u) (i64.const 0x7FF0000000000000)))))))
(local.set $m (i64.and (local.get $u) (i64.const 0xFFFFFFFFFFFFF)))
(local.set $ne (i32.sub (i32.wrap_i64 (i64.shr_u (local.get $u) (i64.const 52))) (i32.const 1008)))
(if (i32.ge_s (local.get $ne) (i32.const 31))
(then (return (i32.or (local.get $sign) (i32.const 0x7C00)))))
(if (i32.ge_s (local.get $ne) (i32.const 1))
(then ;; normal: 42 dropped mantissa bits round ties-to-even; a mantissa
;; carry overflows into the exponent or into infinity — both exact
(local.set $half (i32.or (i32.shl (local.get $ne) (i32.const 10))
(i32.wrap_i64 (i64.shr_u (local.get $m) (i64.const 42)))))
(local.set $rb (i64.and (local.get $m) (i64.const 0x3FFFFFFFFFF)))
(if (i32.or (i64.gt_u (local.get $rb) (i64.const 0x20000000000))
(i32.and (i64.eq (local.get $rb) (i64.const 0x20000000000)) (i32.and (local.get $half) (i32.const 1))))
(then (local.set $half (i32.add (local.get $half) (i32.const 1)))))
(return (i32.or (local.get $sign) (local.get $half)))))
(if (i32.lt_s (local.get $ne) (i32.const -10))
(then (return (local.get $sign)))) ;; underflow → ±0
;; subnormal: shift the 53-bit significand by 43-ne (43…53), ties-to-even
(local.set $full (i64.or (local.get $m) (i64.const 0x10000000000000)))
(local.set $sh (i64.extend_i32_u (i32.sub (i32.const 43) (local.get $ne))))
(local.set $half (i32.wrap_i64 (i64.shr_u (local.get $full) (local.get $sh))))
(local.set $rb (i64.and (local.get $full) (i64.sub (i64.shl (i64.const 1) (local.get $sh)) (i64.const 1))))
(local.set $hp (i64.shl (i64.const 1) (i64.sub (local.get $sh) (i64.const 1))))
(if (i32.or (i64.gt_u (local.get $rb) (local.get $hp))
(i32.and (i64.eq (local.get $rb) (local.get $hp)) (i32.and (local.get $half) (i32.const 1))))
(then (local.set $half (i32.add (local.get $half) (i32.const 1)))))
(i32.or (local.get $sign) (local.get $half)))`
// ToUint8Clamp (Uint8ClampedArray stores): NaN → 0, clamp [0,255],
// round-half-to-even — f64.nearest IS ties-to-even.
ctx.core.stdlib['__u8_clamp'] = `(func $__u8_clamp (param $v f64) (result i32)
(if (f64.ne (local.get $v) (local.get $v)) (then (return (i32.const 0))))
(i32.trunc_sat_f64_u (f64.nearest (f64.min (f64.max (local.get $v) (f64.const 0)) (f64.const 255)))))`
// Hot (~85M calls in watr self-host). Type/offset extraction inlined; forwarding
// loop only entered for ARRAY. ARRAY fast path dominates (nodes?.length, out.length …).
ctx.core.stdlib['__len'] = `(func $__len (param $ptr i64) (result i32)
(local $bits i64) (local $t i32) (local $off i32) (local $aux i32)
(local.set $bits (local.get $ptr))
(local.set $t (i32.wrap_i64 (i64.and (i64.shr_u (local.get $bits) (i64.const ${LAYOUT.TAG_SHIFT})) (i64.const ${LAYOUT.TAG_MASK}))))
(local.set $off (i32.wrap_i64 (i64.and (local.get $bits) (i64.const ${LAYOUT.OFFSET_MASK}))))
;; ARRAY fast path: follow forwarding inline, then load len at off-8.
(if (result i32)
(i32.and (i32.eq (local.get $t) (i32.const 1)) (i32.ge_u (local.get $off) (i32.const 8)))
(then
${followForwardingWat('$off', { lowGuard: false })}
(i32.load (i32.sub (local.get $off) (i32.const 8))))
(else
(if (result i32)
(i32.and
(i32.ge_u (local.get $off) (i32.const 8))
(i32.or
(i32.eq (local.get $t) (i32.const 3))
(i32.or (i32.eq (local.get $t) (i32.const ${PTR.BUFFER}))
(i32.or (i32.eq (local.get $t) (i32.const 7))
(i32.or (i32.eq (local.get $t) (i32.const 8)) (i32.eq (local.get $t) (i32.const 9)))))))
(then
(if (result i32) (i32.eq (local.get $t) (i32.const 3))
(then
(local.set $aux (i32.wrap_i64 (i64.and (i64.shr_u (local.get $bits) (i64.const ${LAYOUT.AUX_SHIFT})) (i64.const ${LAYOUT.AUX_MASK}))))
(if (result i32) (i32.and (local.get $aux) (i32.const 8))
(then (i32.shr_u (i32.load (local.get $off))
(call $__typed_shift (i32.and (local.get $aux) (i32.const 7)))))
(else (i32.shr_u (i32.load (i32.sub (local.get $off) (i32.const 8)))
(call $__typed_shift (i32.and (local.get $aux) (i32.const 7)))))))
;; HASH/SET/MAP/BUFFER: re-resolve offset so grown SET/MAP follow the
;; forwarding chain (HASH/BUFFER never forward → same inline offset).
(else (i32.load (i32.sub (call $__ptr_offset (local.get $ptr)) (i32.const 8))))))
(else (i32.const 0))))))`
ctx.core.stdlib['__cap'] = `(func $__cap (param $ptr i64) (result i32)
(local $t i32) (local $off i32) (local $aux i32)
(local.set $t (call $__ptr_type (local.get $ptr)))
(local.set $off (call $__ptr_offset (local.get $ptr)))
(if (result i32)
(i32.and
(i32.ge_u (local.get $off) (i32.const 4))
(i32.or
(i32.or
(i32.or (i32.eq (local.get $t) (i32.const 1)) (i32.eq (local.get $t) (i32.const 3)))
(i32.eq (local.get $t) (i32.const ${PTR.BUFFER})))
(i32.or (i32.eq (local.get $t) (i32.const 7))
(i32.or (i32.eq (local.get $t) (i32.const 8)) (i32.eq (local.get $t) (i32.const 9))))))
(then
(if (result i32) (i32.eq (local.get $t) (i32.const 3))
(then
(local.set $aux (call $__ptr_aux (local.get $ptr)))
(if (result i32) (i32.and (local.get $aux) (i32.const 8))
;; views are non-growable: cap = len (byteLen at [off])
(then (i32.shr_u (i32.load (local.get $off))
(call $__typed_shift (i32.and (local.get $aux) (i32.const 7)))))
(else (i32.shr_u (i32.load (i32.sub (local.get $off) (i32.const 4)))
(call $__typed_shift (i32.and (local.get $aux) (i32.const 7)))))))
(else (i32.load (i32.sub (local.get $off) (i32.const 4))))))
(else (i32.const 0))))`
// String length (UTF-8 byte count). Heap: [-4:len(i32)][chars...]; SSO (7-bit codec):
// len at aux bits 10-12 (= payload bits 42-44). See module/string.js codec.
ctx.core.stdlib['__str_len'] = `(func $__str_len (param $ptr i64) (result i32)
(local $off i32) (local $aux i32)
(if (i32.ne (call $__ptr_type (local.get $ptr)) (i32.const ${PTR.STRING}))
(then (return (i32.const 0))))
(local.set $aux (call $__ptr_aux (local.get $ptr)))
(if (i32.and (local.get $aux) (i32.const ${LAYOUT.SSO_BIT}))
(then (return (i32.and (i32.shr_u (local.get $aux) (i32.const 10)) (i32.const 7)))))
(local.set $off (call $__ptr_offset (local.get $ptr)))
(if (result i32) (i32.ge_u (local.get $off) (i32.const 4))
(then (i32.load (i32.sub (local.get $off) (i32.const 4))))
(else (i32.const 0))))`
// Set len in memory (for push/pop). Hot (~42M calls in watr self-host).
// Type/offset extraction inlined; forwarding loop only entered for ARRAY.
ctx.core.stdlib['__set_len'] = `(func $__set_len (param $ptr i64) (param $len i32)
(local $bits i64) (local $t i32) (local $off i32)
(local.set $bits (local.get $ptr))
(local.set $t (i32.wrap_i64 (i64.and (i64.shr_u (local.get $bits) (i64.const ${LAYOUT.TAG_SHIFT})) (i64.const ${LAYOUT.TAG_MASK}))))
(local.set $off (i32.wrap_i64 (i64.and (local.get $bits) (i64.const ${LAYOUT.OFFSET_MASK}))))
;; Only ARRAY (1), TYPED (3), HASH (7), SET (8), MAP (9) carry an 8-byte header.
;; Of those, only ARRAY can be forwarded — follow the chain inline.
(if
(i32.and
(i32.ge_u (local.get $off) (i32.const 8))
(i32.or
(i32.or (i32.eq (local.get $t) (i32.const 1)) (i32.eq (local.get $t) (i32.const 3)))
(i32.or (i32.eq (local.get $t) (i32.const 7))
(i32.or (i32.eq (local.get $t) (i32.const 8)) (i32.eq (local.get $t) (i32.const 9))))))
(then
(if (i32.eq (local.get $t) (i32.const 1))
(then
${followForwardingWat('$off', { lowGuard: true })}))
(i32.store (i32.sub (local.get $off) (i32.const 8)) (local.get $len)))))`
// Alloc header(16) + data(cap*stride). Layout: [propsPtr@-16(f64=0), len@-8, cap@-4],
// data starts at returned offset. propsPtr at -16 holds a per-object dynamic-property hash
// (NaN-boxed PTR.HASH) for ARRAY/HASH/MAP/SET; 0 means "no dyn props yet". This lets
// __dyn_get_t / __dyn_set sidestep the global __dyn_props lookup on the hot path.
// Read offsets relative to the returned data ptr stay unchanged (-8 len, -4 cap).
// Default stride=8 (f64 NaN-boxed slot) — used by every Array/HASH/OBJECT alloc.
// Specialized over a generic (len, cap, stride) helper to drop a fat (i32.const 8)
// immediate at every call site (~20+) plus a param/local.get pair in the body.
// Non-8 strides (Set: 16, Map/HASH probe: 24, TypedArray raw: 1) use __alloc_hdr_n.
ctx.core.stdlib['__alloc_hdr'] = `(func $__alloc_hdr (param $len i32) (param $cap i32) (result i32)
(local $ptr i32)
(local.set $ptr (call $__alloc (i32.add (i32.const 16) (i32.shl (local.get $cap) (i32.const 3)))))
(i64.store (local.get $ptr) (i64.const 0))
(i32.store (i32.add (local.get $ptr) (i32.const 8)) (local.get $len))
(i32.store (i32.add (local.get $ptr) (i32.const 12)) (local.get $cap))
(i32.add (local.get $ptr) (i32.const 16)))`
// Generic header allocator for non-8 strides: Set (16), Map probe (24), TypedArray raw (1).
// Same 16-byte header layout as __alloc_hdr; per-entry stride is passed dynamically.
// Header (16B) + cap*stride slots. Collections (Set/Map/HASH) key "empty slot"
// off a zero hash word, so the slot region MUST start zeroed. The bump allocator
// reuses memory after a heap reset (__clear) without re-zeroing, so we cannot
// lean on fresh-page zeroing here — clear the slots explicitly. Also covers the
// grow path, which rehashes into a freshly-allocated table expecting empties.
ctx.core.stdlib['__alloc_hdr_n'] = `(func $__alloc_hdr_n (param $len i32) (param $cap i32) (param $stride i32) (result i32)
(local $ptr i32)
(local.set $ptr (call $__alloc (i32.add (i32.const 16) (i32.mul (local.get $cap) (local.get $stride)))))
(i64.store (local.get $ptr) (i64.const 0))
(i32.store (i32.add (local.get $ptr) (i32.const 8)) (local.get $len))
(i32.store (i32.add (local.get $ptr) (i32.const 12)) (local.get $cap))
(memory.fill (i32.add (local.get $ptr) (i32.const 16)) (i32.const 0) (i32.mul (local.get $cap) (local.get $stride)))
(i32.add (local.get $ptr) (i32.const 16)))`
// Shallow clone of an OBJECT or HASH, preserving its runtime type — the copy
// semantics of a single unknown spread `{ ...src }` (module/object.js). Without
// this, `{ ...src }` aliases src, so any later write to the result mutates the
// source (a real bug: jz's own narrow.js had to route around it). Per JS spread,
// the clone is SHALLOW: scalar slots are copied by value; nested object/string
// pointers are shared (immutable strings; nested objects are aliased as in V8).
//
// - OBJECT: alloc a fresh header'd object with the same schemaId and copy its N
// schema slots (N = key count of __schema_tbl[sid], robust to static-segment
// sources that carry no len/cap header). Then deep-copy the per-instance
// dyn-props HASH (base-16) so `o[k]=v` keys added before the spread carry over
// independently — heap objects only; static-segment objects have no header.
// - HASH: copy header + every probe slot wholesale (entries hold immutable
// string keys + scalar/pointer values — a byte copy is an independent dict).
// - anything else (primitive): nothing to clone, return as-is.
// Thunked (not a plain template string) so heapResetWat()/the __dyn_props
// presence check below read the FINAL declaration state — see collection.js's
// heapResetWat comment for why.
ctx.core.stdlib['__obj_clone'] = () => `(func $__obj_clone (param $v f64) (result f64)
(local $bits i64) (local $t i32) (local $sid i32) (local $n i32) (local $cap i32)
(local $src i32) (local $dst i32) (local $props i64)
(local.set $bits (i64.reinterpret_f64 (local.get $v)))
(local.set $t (call $__ptr_type (local.get $bits)))
(if (i32.eq (local.get $t) (i32.const ${PTR.OBJECT}))
(then
(local.set $sid (call $__ptr_aux (local.get $bits)))
(local.set $src (call $__ptr_offset (local.get $bits)))
(local.set $n (i32.const 0))
(if (i32.ne (global.get $__schema_tbl) (i32.const 0))
(then (local.set $n (call $__len
(i64.load (i32.add (global.get $__schema_tbl) (i32.shl (local.get $sid) (i32.const 3))))))))
(local.set $cap (i32.add (local.get $n) (i32.eqz (local.get $n))))
(local.set $dst (call $__alloc_hdr (i32.const 0) (local.get $cap)))
(memory.copy (local.get $dst) (local.get $src) (i32.shl (local.get $n) (i32.const 3)))
;; Dyn-props (off-schema keys added by o[k]=v): heap-allocated sources
;; (src >= __heap_start) carry them at src-16 as a HASH sidecar
;; (populated by an init-time write, or by any write at all on an
;; EPHEMERAL source) and/or in the global __dyn_props table (populated
;; by a RUNTIME/post-init write on a DURABLE source — see
;; collection.js's heapResetWat for the full policy). Static-segment
;; sources (src < __heap_start) have no header — both checks below
;; are gated on src >= __heap_start so neither reads neighbor static
;; data. Prefers the sidecar when present (authoritative for a
;; DURABLE source's untouched init-time keys, and the only source for
;; an ephemeral one); falls back to the global entry otherwise. A
;; source with keys split across BOTH (some at init, more added at
;; runtime) clones only the sidecar's — a known narrow gap versus
;; Object.keys/JSON.stringify's full merge, accepted here because a
;; spread of such a genuinely mixed durable dict is materially rarer.
(local.set $props (i64.load (i32.sub (local.get $src) (i32.const 16))))
(if (i32.and (i32.ge_u (local.get $src) (global.get $__heap_start))
(i32.eq (call $__ptr_type (local.get $props)) (i32.const ${PTR.HASH})))
(then (i64.store (i32.sub (local.get $dst) (i32.const 16))
(i64.reinterpret_f64 (call $__obj_clone (f64.reinterpret_i64 (local.get $props))))))${ctx.scope.globals.has('__dyn_props') ? `
(else
(if (i32.and (i32.ge_u (local.get $src) (global.get $__heap_start))
(i32.lt_u (local.get $src) ${heapResetWat()}))
(then
(if (f64.ne (global.get $__dyn_props) (f64.const 0))
(then
(local.set $props (call $__ihash_get_local (i64.reinterpret_f64 (global.get $__dyn_props)) (i64.reinterpret_f64 (f64.convert_i32_s (local.get $src)))))
(if (i32.eqz (call $__is_nullish (local.get $props)))
(then (i64.store (i32.sub (local.get $dst) (i32.const 16))
(i64.reinterpret_f64 (call $__obj_clone (f64.reinterpret_i64 (local.get $props)))))))))))` : ''}))
(return (call $__mkptr (i32.const ${PTR.OBJECT}) (local.get $sid) (local.get $dst)))))
(if (i32.eq (local.get $t) (i32.const ${PTR.HASH}))
(then
(local.set $cap (call $__cap (local.get $bits)))
(local.set $src (call $__ptr_offset (local.get $bits)))
;; 28 = MAP_ENTRY + the probe hash lane (collection.js) — the wholesale
;; copy must carry the lane or the clone's probes see stale zeros
(local.set $dst (call $__alloc_hdr_n (i32.const 0) (local.get $cap) (i32.const 28)))
(memory.copy
(i32.sub (local.get $dst) (i32.const 16))
(i32.sub (local.get $src) (i32.const 16))
(i32.add (i32.const 16) (i32.mul (local.get $cap) (i32.const 28))))
(return (call $__mkptr (i32.const ${PTR.HASH}) (i32.const 0) (local.get $dst)))))
(local.get $v))`
// Allocator + exports are deferred: only included when memory is actually needed.
// Any module using allocPtr/inc('__alloc') pulls these in via ctx.core.stdlibDeps.
// compile.js emits _alloc/_clear exports + memory section only when __alloc is in includes.
ctx.core._allocRawFuncs = [
'(func (export "_alloc") (param $bytes i32) (result i32) (call $__alloc (local.get $bytes)))',
'(func (export "_clear") (call $__clear))',
]
// Not-nullish check: f64 WAT node is neither NULL_NAN nor UNDEF_NAN.
// Routes through isNullish() so peepholes (ptrKind, NaN-boxed literal, local.get inline)
// apply — otherwise this would always emit a __is_nullish call even for provable cases.
const notNullish = v => ['i32.eqz', isNullish(v)]
// Optional-chain wrapper: eval guard, if non-nullish emit access, else `undefined`.
// Per spec, `null?.a` and `undefined?.a` both short-circuit to undefined, not null.
const emitNullishGuarded = (guard, access) => typed(['if', ['result', 'f64'],
notNullish(guard),
['then', access],
['else', ['f64.const', `nan:${UNDEF_NAN}`]]], 'f64')
// === Shared dispatch helpers ===
/** Emit .length access for a WASM f64 node. Monomorphize by vt, or runtime dispatch.
* ARRAY length is i32 at offset-8 — inline that load directly instead of calling
* __len which re-dispatches on type. ptrOffsetIR handles
* ARRAY forwarding (non-ARRAY skips the forwarding loop). TYPED has a variable-width
* layout depending on the aux typed-element shift, so it still routes through __len.
* `notString` (from rep.notString — write-shape evidence rules out primitive string)
* routes the otherwise-unknown case through __len directly, eliding the STRING arm
* of __length. __len returns 0 on tags it doesn't recognize, matching JS's
* `undefined` semantics on non-pointer .length (the binding writes through xs[i]