submilli-engine 0.4.2

Compiles Submilli programs, a TypeScript subset, to WebAssembly and runs them under capability policy
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
//! The Rust port of the prelude's `ObjectConstructor` statics —
//! `Object.keys`/`values`/`entries`/`hasOwn`/`is` — reading the `$ObjectShape`
//! field-name/field-value arrays directly. Every per-arity object subtype
//! subtypes `$ObjectShape`, so one `matches_ty` test covers them all. A string
//! or an array, which `{}` holds, lists its indices; any other value takes the
//! "no fields" path (`[]`/`false`), and a null receiver throws a catchable
//! `Error`, matching the Wasm bodies in `codegen/prelude/object_shape.rs`.

use crate::runtime::host::{abi_arg, abi_result};
mod assign;
mod dynamic;
mod from_entries;
mod group_by;
pub(crate) use group_by::map_group_by;
mod index;
mod static_value;

use wasmtime::{
    ArrayRef, ArrayRefPre, Caller, FuncType, HeapType, Linker, RefType, Rooted, StructRef,
    StructRefPre, StructType, Val, ValType,
};

use crate::MangledName;
use crate::runtime::StoreData;
use crate::runtime::array_storage::ArrayStorage;
use crate::runtime::host::{
    host_object_vtable, intrinsic_array_type, intrinsic_string_type, register_host_fn,
    register_host_fn_async, write_submilli_array_struct, write_submilli_string_struct,
    write_submilli_string_struct_units,
};
use crate::runtime::intrinsic_types::{build_intrinsic_types, intrinsic_types};
use crate::runtime::prelude::collection::{FIELD_NAME, is_a};
use crate::runtime::prelude::iterator::as_struct;
use crate::runtime::prelude::vtable::{dispatch_vtable_slot, read_string_units};
use crate::runtime::prelude::{MODULE_NAME, declare_method};
use crate::{PackageDeclaration, Param, Type};

fn ctor_key(method: &str) -> MangledName {
    crate::mangle::extend(&crate::mangle::prelude("ObjectConstructor"), method)
}

/// Canonical array-index property names, excluding 2^32 - 1.
fn integer_key(units: &[u16]) -> Option<u32> {
    if units.is_empty() || (units.len() > 1 && units.first() == Some(&48)) {
        return None;
    }
    let mut number = 0_u32;
    for &unit in units {
        let digit = unit.checked_sub(48).filter(|digit| *digit <= 9)?;
        number = number.checked_mul(10)?.checked_add(u32::from(digit))?;
    }
    (number < u32::MAX).then_some(number)
}

#[derive(Clone, Copy)]
enum Enumerate {
    Keys,
    Values,
    Entries,
}

impl Enumerate {
    fn method(self) -> &'static str {
        match self {
            Enumerate::Keys => "keys",
            Enumerate::Values => "values",
            Enumerate::Entries => "entries",
        }
    }
}

pub(super) fn find_data_slot(
    caller: &mut Caller<'_, StoreData>,
    object: &Val,
    key: &[u16],
) -> wasmtime::Result<Option<u32>> {
    let object = as_struct(caller, object, "object equality receiver")?;
    index::lookup(caller, &object, key, false, false)
}

pub(super) fn find_field_slot(
    caller: &mut Caller<'_, StoreData>,
    object: &Rooted<StructRef>,
    key: &[u16],
    accessor: bool,
) -> wasmtime::Result<Option<u32>> {
    index::lookup(caller, object, key, accessor, false)
}

pub(crate) fn data_field_count(
    caller: &mut Caller<'_, StoreData>,
    object: &Val,
) -> wasmtime::Result<usize> {
    let Some((names, values)) = shape_arrays(caller, object)? else {
        return Ok(0);
    };
    let count = field_count(caller, object)?;
    let mut present = 0;
    for slot in 0..count {
        let name = names.get(&mut *caller, slot)?;
        let value = values.get(&mut *caller, slot)?;
        if field_is_present(caller, &name, &value)? && !is_accessor_slot(caller, &name)? {
            present += 1;
        }
    }
    Ok(present)
}

pub(crate) fn field_count(
    caller: &mut Caller<'_, StoreData>,
    object: &Val,
) -> wasmtime::Result<u32> {
    let object = as_struct(caller, object, "object field count")?;
    index::len(caller, &object)
}

/// The `$ObjectShape` field arrays `(field_names, object_fields)` of `obj`, or
/// `None` when `obj` is any other (non-null) value — the "no fields" path.
fn shape_arrays(
    caller: &mut Caller<'_, StoreData>,
    obj: &Val,
) -> wasmtime::Result<Option<(Rooted<ArrayRef>, Rooted<ArrayRef>)>> {
    let Val::AnyRef(Some(any)) = obj else {
        return Ok(None);
    };
    let Some(st) = any.as_struct(&mut *caller)? else {
        return Ok(None);
    };
    let shape = intrinsic_types(&mut *caller)?.object_shape.clone();
    if !st.matches_ty(&*caller, &shape)? {
        return Ok(None);
    }
    let names = field_array(caller, &st, 1)?;
    let values = field_array(caller, &st, 2)?;
    Ok(Some((names, values)))
}

pub(super) fn field_array(
    caller: &mut Caller<'_, StoreData>,
    st: &Rooted<StructRef>,
    idx: usize,
) -> wasmtime::Result<Rooted<ArrayRef>> {
    match st.field(&mut *caller, idx)? {
        Val::AnyRef(Some(a)) => a.unwrap_array(&mut *caller),
        other => Err(wasmtime::Error::msg(format!(
            "$ObjectShape field {idx} is not an array: {other:?}"
        ))),
    }
}

/// An optional nullish slot has a separate presence flag on its field name.
pub(crate) fn field_is_present(
    caller: &mut Caller<'_, StoreData>,
    name: &Val,
    value: &Val,
) -> wasmtime::Result<bool> {
    if !super::undefined::is_nullish(caller, value)? {
        return Ok(true);
    }
    let name = as_struct(caller, name, "field name")?;
    let string = intrinsic_types(&mut *caller)?.string.clone();
    if StructType::eq(&name.ty(&*caller)?, &string) {
        return Ok(true);
    }
    Ok(matches!(name.field(&mut *caller, 3)?, Val::I32(value) if value != 0))
}

fn enumerate(
    caller: &mut Caller<'_, StoreData>,
    obj: &Val,
    kind: Enumerate,
) -> wasmtime::Result<Val> {
    if super::undefined::is_nullish(caller, obj)? {
        return Err(wasmtime::Error::msg(format!(
            "Object.{} called on null or undefined",
            kind.method()
        )));
    }
    if let Some(entries) = indexed_entries(caller, obj)? {
        return enumerated(caller, entries, kind);
    }
    let mut elems = Vec::new();
    if let Some((names, values)) = shape_arrays(caller, obj)? {
        let len = field_count(caller, obj)?;
        elems.reserve(len as usize);
        let error_slots = super::error::non_enumerable_slots(caller, obj)?;
        for i in 0..len {
            if error_slots.as_ref().is_some_and(|hidden| hidden.hides(i)) {
                continue;
            }
            let name = names.get(&mut *caller, i)?;
            let value = values.get(&mut *caller, i)?;
            if !field_is_present(caller, &name, &value)? || is_accessor_slot(caller, &name)? {
                continue;
            }
            let elem = match kind {
                Enumerate::Keys => names.get(&mut *caller, i)?,
                Enumerate::Values => values.get(&mut *caller, i)?,
                Enumerate::Entries => {
                    let name = names.get(&mut *caller, i)?;
                    let value = values.get(&mut *caller, i)?;
                    let pair = write_submilli_array_struct(caller, &[name, value])?;
                    Val::AnyRef(Some(pair.to_anyref()))
                }
            };
            elems.push(elem);
        }
    }
    let arr = write_submilli_array_struct(caller, &elems)?;
    Ok(Val::AnyRef(Some(arr.to_anyref())))
}

/// The `$Array` of `entries` that `Object.keys`, `values` or `entries` gives.
fn enumerated(
    caller: &mut Caller<'_, StoreData>,
    entries: Vec<(Val, Val)>,
    kind: Enumerate,
) -> wasmtime::Result<Val> {
    let mut elems = Vec::with_capacity(entries.len());
    for (name, value) in entries {
        elems.push(match kind {
            Enumerate::Keys => name,
            Enumerate::Values => value,
            Enumerate::Entries => {
                let pair = write_submilli_array_struct(caller, &[name, value])?;
                Val::AnyRef(Some(pair.to_anyref()))
            }
        });
    }
    let arr = write_submilli_array_struct(caller, &elems)?;
    Ok(Val::AnyRef(Some(arr.to_anyref())))
}

/// The index properties `"0"`, `"1"`, … of a string or an array, with their
/// one-unit strings or elements, or `None` for any other value. Neither is an
/// object shape, but `{}` holds both, as in TypeScript, and `Object.keys` and
/// spread list their indices as JavaScript does.
fn indexed_entries(
    caller: &mut Caller<'_, StoreData>,
    obj: &Val,
) -> wasmtime::Result<Option<Vec<(Val, Val)>>> {
    let intr = intrinsic_types(&mut *caller)?;
    let values = if is_a(caller, obj, &intr.string)? {
        let units = read_string_units(caller, obj, "indexed string")?;
        let mut values = Vec::with_capacity(units.len());
        for unit in units {
            let one = write_submilli_string_struct_units(caller, &[unit])?;
            values.push(Val::AnyRef(Some(one.to_anyref())));
        }
        values
    } else if is_a(caller, obj, &intr.array)? {
        ArrayStorage::read(caller, obj)?.snapshot(caller)?
    } else {
        return Ok(None);
    };
    let mut entries = Vec::with_capacity(values.len());
    for (index, value) in values.into_iter().enumerate() {
        let name = write_submilli_string_struct(caller, &index.to_string())?;
        entries.push((Val::AnyRef(Some(name.to_anyref())), value));
    }
    Ok(Some(entries))
}

/// The length of a string (in UTF-16 units) or an array, or `None` for any
/// other value.
fn indexed_len(caller: &mut Caller<'_, StoreData>, obj: &Val) -> wasmtime::Result<Option<u32>> {
    let intr = intrinsic_types(&mut *caller)?;
    if is_a(caller, obj, &intr.string)? {
        let units = read_string_units(caller, obj, "indexed string")?;
        return Ok(Some(u32::try_from(units.len()).unwrap_or(u32::MAX)));
    }
    if is_a(caller, obj, &intr.array)? {
        return Ok(Some(ArrayStorage::read(caller, obj)?.len));
    }
    Ok(None)
}

/// The array index `units` spells canonically ("0", "17", not "017" or "-1").
fn array_index(units: &[u16]) -> Option<u32> {
    if units.is_empty() || (units.len() > 1 && units[0] == u16::from(b'0')) {
        return None;
    }
    let mut index: u32 = 0;
    for &unit in units {
        let digit = char::from_u32(u32::from(unit))?.to_digit(10)?;
        index = index.checked_mul(10)?.checked_add(digit)?;
    }
    Some(index)
}

/// A marked name identifies an internal accessor slot independently of its
/// spelling or current value; user data named `get x` remains ordinary data.
pub(crate) fn is_accessor_slot(
    caller: &mut Caller<'_, StoreData>,
    name: &Val,
) -> wasmtime::Result<bool> {
    let name = as_struct(caller, name, "field name")?;
    let string = intrinsic_types(&mut *caller)?.string.clone();
    if StructType::eq(&name.ty(&*caller)?, &string) {
        return Ok(false);
    }
    Ok(matches!(name.field(&mut *caller, 3)?, Val::I32(-1)))
}

/// Visibility is carried only by compiler-created marked names. Host-created
/// names predate that metadata and describe public data properties.
pub(crate) fn field_is_private(
    caller: &mut Caller<'_, StoreData>,
    name: &Val,
) -> wasmtime::Result<bool> {
    let name = as_struct(caller, name, "field name")?;
    if name.ty(&*caller)?.fields().count() < 5 {
        return Ok(false);
    }
    Ok(matches!(name.field(&mut *caller, 4)?, Val::I32(1)))
}

/// Copy present own fields while preserving UTF-16 names and boxed values.
/// Each call snapshots its source before the next literal member is evaluated.
fn spread(
    caller: &mut Caller<'_, StoreData>,
    target: &Val,
    source: &Val,
    shape: &Val,
    mask: &Val,
) -> wasmtime::Result<Val> {
    let intr = intrinsic_types(&mut *caller)?;
    let mut entries = std::collections::BTreeMap::new();
    let omitted = spread_omitted_fields(caller, mask)?;
    for (source_index, object) in [target, source].into_iter().enumerate() {
        if let Some(indexed) = indexed_entries(caller, object)? {
            for (name, value) in indexed {
                let units = read_string_units(caller, &name, FIELD_NAME)?;
                entries.insert(units, (name, value));
            }
            continue;
        }
        let Some((names, values)) = shape_arrays(caller, object)? else {
            continue;
        };
        for index in 0..field_count(caller, object)? {
            let name = names.get(&mut *caller, index)?;
            let value = values.get(&mut *caller, index)?;
            if !field_is_present(caller, &name, &value)? || is_accessor_slot(caller, &name)? {
                continue;
            }
            let units = read_string_units(caller, &name, FIELD_NAME)?;
            if source_index == 1 && omitted.contains(&units) {
                continue;
            }
            entries.insert(units, (copy_field_name(caller, name, true)?, value));
        }
    }
    if let Some((names, _)) = shape_arrays(caller, shape)? {
        for index in 0..field_count(caller, shape)? {
            let name = names.get(&mut *caller, index)?;
            let units = read_string_units(caller, &name, FIELD_NAME)?;
            if let std::collections::btree_map::Entry::Vacant(entry) = entries.entry(units) {
                entry.insert((
                    copy_field_name(caller, name, false)?,
                    super::undefined::value(caller)?,
                ));
            }
        }
    }
    let (names, values): (Vec<_>, Vec<_>) = entries.into_values().unzip();
    let names_pre = ArrayRefPre::new(&mut *caller, intr.field_names.clone());
    let values_pre = ArrayRefPre::new(&mut *caller, intr.object_fields.clone());
    let shape_pre = StructRefPre::new(&mut *caller, intr.object_shape.clone());
    let names = ArrayRef::new_fixed(&mut *caller, &names_pre, &names)?;
    let values = ArrayRef::new_fixed(&mut *caller, &values_pre, &values)?;
    let vtable = host_object_vtable(caller)?;
    let object = StructRef::new(
        &mut *caller,
        &shape_pre,
        &[
            vtable,
            Val::AnyRef(Some(names.to_anyref())),
            Val::AnyRef(Some(values.to_anyref())),
            Val::AnyRef(None),
        ],
    )?;
    Ok(Val::AnyRef(Some(object.to_anyref())))
}

/// `value` as an object an object type's field reads can take. `{}` holds
/// any value, and TypeScript lets it into a type whose fields are all
/// optional; JavaScript then reads a primitive's fields through a wrapper
/// object and finds none of an exotic object's (a `Map`, a function) own. A
/// plain object or class instance stays itself; any other value becomes a
/// fresh object of its index entries (a string's or array's) or none.
fn to_object(caller: &mut Caller<'_, StoreData>, value: &Val) -> wasmtime::Result<Val> {
    if is_kept_as_object(caller, value)? {
        return Ok(*value);
    }
    let none = Val::AnyRef(None);
    spread(caller, &none, value, &none, &none)
}

/// Whether object-type field reads take `value` as it is: `null` or
/// `undefined` (read through an optional chain), or a plain object, which
/// class and error instances extend.
fn is_kept_as_object(caller: &mut Caller<'_, StoreData>, value: &Val) -> wasmtime::Result<bool> {
    if super::undefined::is_nullish(caller, value)? {
        return Ok(true);
    }
    let object_shape = intrinsic_types(&mut *caller)?.object_shape.clone();
    is_a(caller, value, &object_shape)
}

fn copy_field_name(
    caller: &mut Caller<'_, StoreData>,
    name: Val,
    present: bool,
) -> wasmtime::Result<Val> {
    let object = as_struct(caller, &name, "field name")?;
    let string = intrinsic_types(&mut *caller)?.string.clone();
    if StructType::eq(&object.ty(&*caller)?, &string) {
        return Ok(name);
    }
    let ty = if present {
        string
    } else {
        object.ty(&*caller)?
    };
    let mut fields = vec![
        object.field(&mut *caller, 0)?,
        object.field(&mut *caller, 1)?,
        object.field(&mut *caller, 2)?,
    ];
    if !present {
        fields.push(Val::I32(0));
        if ty.fields().count() > 4 {
            fields.push(object.field(&mut *caller, 4)?);
        }
    }
    let pre = StructRefPre::new(&mut *caller, ty);
    Ok(Val::AnyRef(Some(
        StructRef::new(&mut *caller, &pre, &fields)?.to_anyref(),
    )))
}

/// Append without replacing the receiver, so every alias sees the new slot.
/// Existing indices (including class payload and guard slots) stay unchanged.
/// A fresh object with `fields` (name, value) in order, for host code that
/// hands JavaScript an object (`replace`'s named groups).
pub(crate) fn object_from_fields(
    caller: &mut Caller<'_, StoreData>,
    fields: &[(Val, Val)],
) -> wasmtime::Result<Val> {
    let empty = Val::null_any_ref();
    let object = spread(caller, &empty, &empty, &empty, &empty)?;
    for (name, value) in fields {
        insert_field(caller, &object, name, value)?;
    }
    Ok(object)
}

fn insert_field(
    caller: &mut Caller<'_, StoreData>,
    obj: &Val,
    name: &Val,
    value: &Val,
) -> wasmtime::Result<()> {
    let object = as_struct(caller, obj, "field insertion receiver")?;
    let old_names = field_array(caller, &object, 1)?;
    let old_values = field_array(caller, &object, 2)?;
    let count = index::len(caller, &object)?;
    let capacity = old_names.len(&mut *caller)?;
    let new_count = count
        .checked_add(1)
        .filter(|n| *n <= i32::MAX as u32)
        .ok_or_else(|| crate::runtime::host::range_error("object field count limit exceeded"))?;
    let name = inserted_field_name(caller, name)?;
    let (names, values, table) = if count == capacity {
        let (names, values) = grow_fields(caller, &old_names, &old_values, &name)?;
        let new_capacity = names.len(&mut *caller)?;
        let table = index::build(caller, &names, count, new_capacity)?;
        (names, values, table)
    } else {
        let table = match index::cached(caller, &object)? {
            Some(table) => table,
            None => index::build(caller, &old_names, count, capacity)?,
        };
        (old_names, old_values, table)
    };
    let bucket = index::empty_bucket(caller, &table, &name)?;
    // All fuel and allocation checks precede publication. Guard rows use the
    // backing capacity as their stride, so spare named slots need no reshuffle.
    names.set(&mut *caller, count, name)?;
    values.set(&mut *caller, count, *value)?;
    table.set(&mut *caller, bucket, Val::I32(new_count as i32))?;
    table.set(&mut *caller, 0, Val::I32(new_count as i32))?;
    table.set(&mut *caller, 1, Val::I32(1))?;
    object.set_field(&mut *caller, 1, Val::AnyRef(Some(names.to_anyref())))?;
    object.set_field(&mut *caller, 2, Val::AnyRef(Some(values.to_anyref())))?;
    object.set_field(
        &mut *caller,
        index::INDEX_FIELD,
        Val::AnyRef(Some(table.to_anyref())),
    )?;
    Ok(())
}

fn grow_fields(
    caller: &mut Caller<'_, StoreData>,
    names: &Rooted<ArrayRef>,
    values: &Rooted<ArrayRef>,
    filler: &Val,
) -> wasmtime::Result<(Rooted<ArrayRef>, Rooted<ArrayRef>)> {
    let capacity = names.len(&mut *caller)?;
    let value_len = values.len(&mut *caller)?;
    let width = capacity
        .checked_add(1)
        .ok_or_else(|| crate::runtime::host::fatal_host_error("object guard row width overflow"))?;
    let hidden = value_len
        .checked_sub(capacity)
        .filter(|n| n % width == 0)
        .ok_or_else(|| crate::runtime::host::fatal_host_error("malformed object guard rows"))?;
    let rows = hidden / width;
    let new_capacity = capacity
        .checked_mul(2)
        .map(|n| n.max(8))
        .filter(|n| *n < i32::MAX as u32)
        .ok_or_else(|| crate::runtime::host::range_error("object field capacity limit exceeded"))?;
    let new_width = new_capacity + 1;
    let new_value_len = rows
        .checked_mul(new_width)
        .and_then(|n| n.checked_add(new_capacity))
        .ok_or_else(|| {
            crate::runtime::host::range_error("object payload capacity limit exceeded")
        })?;
    crate::runtime::fuel::charge(
        &mut *caller,
        crate::runtime::fuel::ELEM,
        u64::from(new_capacity)
            + u64::from(new_value_len)
            + u64::from(capacity)
            + u64::from(value_len),
    )?;
    let intr = intrinsic_types(&mut *caller)?;
    let names_pre = ArrayRefPre::new(&mut *caller, intr.field_names.clone());
    let values_pre = ArrayRefPre::new(&mut *caller, intr.object_fields.clone());
    let new_names = ArrayRef::new(&mut *caller, &names_pre, filler, new_capacity)?;
    let new_values = ArrayRef::new(&mut *caller, &values_pre, &Val::AnyRef(None), new_value_len)?;
    for slot in 0..capacity {
        let name = names.get(&mut *caller, slot)?;
        let value = values.get(&mut *caller, slot)?;
        new_names.set(&mut *caller, slot, name)?;
        new_values.set(&mut *caller, slot, value)?;
    }
    for row in 0..rows {
        let old_start = capacity + row * width;
        let new_start = new_capacity + row * new_width;
        for slot in 0..capacity {
            let guard = values.get(&mut *caller, old_start + slot)?;
            new_values.set(&mut *caller, new_start + slot, guard)?;
        }
        let context = values.get(&mut *caller, old_start + capacity)?;
        new_values.set(&mut *caller, new_start + new_capacity, context)?;
    }
    Ok((new_names, new_values))
}

/// A present inserted name also tells typed serializers that the original
/// static shape no longer describes all of this object's fields.
fn inserted_field_name(caller: &mut Caller<'_, StoreData>, name: &Val) -> wasmtime::Result<Val> {
    use wasmtime::{FieldType, Finality, Mutability, StorageType};
    let intr = intrinsic_types(&mut *caller)?;
    let mut fields: Vec<_> = intr.string.fields().collect();
    fields.push(FieldType::new(
        Mutability::Var,
        StorageType::ValType(ValType::I32),
    ));
    let ty = crate::runtime::gc_singleton::singleton_struct(
        caller.engine(),
        Finality::Final,
        Some(intr.string.clone()),
        fields,
    )?;
    let name = as_struct(caller, name, "inserted field name")?;
    let values = [
        name.field(&mut *caller, 0)?,
        name.field(&mut *caller, 1)?,
        name.field(&mut *caller, 2)?,
        Val::I32(2),
    ];
    let pre = StructRefPre::new(&mut *caller, ty);
    Ok(Val::AnyRef(Some(
        StructRef::new(&mut *caller, &pre, &values)?.to_anyref(),
    )))
}

/// `object[name]` as JavaScript reads it: a data field, a getter's result, or
/// `undefined` when the object has neither.
pub(crate) async fn read_property(
    caller: &mut Caller<'_, StoreData>,
    object: &Val,
    name: &str,
) -> wasmtime::Result<Val> {
    let key = crate::runtime::host::write_submilli_string_struct(caller, name)?;
    dynamic::get(caller, object, &Val::AnyRef(Some(key.to_anyref()))).await
}

pub(crate) fn field_was_inserted(
    caller: &mut Caller<'_, StoreData>,
    name: &Val,
) -> wasmtime::Result<bool> {
    let name = as_struct(caller, name, "field name")?;
    let string = intrinsic_types(&mut *caller)?.string.clone();
    if StructType::eq(&name.ty(&*caller)?, &string) {
        return Ok(false);
    }
    Ok(matches!(name.field(&mut *caller, 3)?, Val::I32(2)))
}

/// The compiler marks rejected known fields with non-null mask slots.
fn spread_omitted_fields(
    caller: &mut Caller<'_, StoreData>,
    mask: &Val,
) -> wasmtime::Result<std::collections::BTreeSet<Vec<u16>>> {
    let mut omitted = std::collections::BTreeSet::new();
    if let Some((names, values)) = shape_arrays(caller, mask)? {
        for index in 0..field_count(caller, mask)? {
            if !matches!(values.get(&mut *caller, index)?, Val::AnyRef(None)) {
                let name = names.get(&mut *caller, index)?;
                omitted.insert(read_string_units(caller, &name, FIELD_NAME)?);
            }
        }
    }
    Ok(omitted)
}

fn has_own(caller: &mut Caller<'_, StoreData>, obj: &Val, key: &Val) -> wasmtime::Result<bool> {
    if super::undefined::is_nullish(caller, obj)? {
        return Err(wasmtime::Error::msg(
            "Object.hasOwn called on null or undefined",
        ));
    }
    let target = read_string_units(caller, key, FIELD_NAME)?;
    if let Some(len) = indexed_len(caller, obj)? {
        let length: Vec<u16> = "length".encode_utf16().collect();
        return Ok(target == length || array_index(&target).is_some_and(|index| index < len));
    }
    let Some((names, values)) = shape_arrays(caller, obj)? else {
        return Ok(false);
    };
    let Some(slot) = find_data_slot(caller, obj, &target)? else {
        return Ok(false);
    };
    let name = names.get(&mut *caller, slot)?;
    let value = values.get(&mut *caller, slot)?;
    field_is_present(caller, &name, &value)
}

/// SameValue on two `f64` bit patterns: any NaN equals any NaN (Wasm arithmetic
/// varies sign/payload bits), otherwise exact bit equality — which separates
/// `+0` from `-0` and compares ordinary values exactly.
fn same_value_bits(a: u64, b: u64) -> bool {
    (f64::from_bits(a).is_nan() && f64::from_bits(b).is_nan()) || a == b
}

fn boxed_number_bits(caller: &mut Caller<'_, StoreData>, val: &Val) -> wasmtime::Result<u64> {
    let st = as_struct(caller, val, "Object.is operand")?;
    match st.field(&mut *caller, 1)? {
        Val::F64(bits) => Ok(bits),
        other => Err(wasmtime::Error::msg(format!(
            "Object.is: boxed number payload is {other:?}, not f64"
        ))),
    }
}

async fn same_value(
    caller: &mut Caller<'_, StoreData>,
    a: &Val,
    b: &Val,
) -> wasmtime::Result<bool> {
    match (a, b) {
        (Val::AnyRef(None), Val::AnyRef(None)) => return Ok(true),
        (Val::AnyRef(None), _) | (_, Val::AnyRef(None)) => return Ok(false),
        _ => {}
    }
    // The number arm must run before vtable dispatch: the boxed-number `equals`
    // slot is `===` (`0 === -0`, `NaN !== NaN`), while SameValue distinguishes
    // both.
    let boxed_number = intrinsic_types(&mut *caller)?.boxed_number.clone();
    if is_a(caller, a, &boxed_number)? && is_a(caller, b, &boxed_number)? {
        let (a_bits, b_bits) = (boxed_number_bits(caller, a)?, boxed_number_bits(caller, b)?);
        return Ok(same_value_bits(a_bits, b_bits));
    }
    match dispatch_vtable_slot(caller, a, 2, std::slice::from_ref(b)).await? {
        Val::I32(v) => Ok(v != 0),
        other => Err(wasmtime::Error::msg(format!(
            "Object.is: equals returned {other:?}, expected i32"
        ))),
    }
}

pub fn install(linker: &mut Linker<StoreData>) -> wasmtime::Result<()> {
    dynamic::install(linker)?;
    let engine = linker.engine().clone();
    let intr = build_intrinsic_types(&engine)?;
    let obj = ValType::Ref(RefType::new(
        true,
        HeapType::ConcreteStruct(intr.object.clone()),
    ));
    let string = ValType::Ref(RefType::new(
        false,
        HeapType::ConcreteStruct(intrinsic_string_type(&engine)?),
    ));
    let array = ValType::Ref(RefType::new(
        false,
        HeapType::ConcreteStruct(intrinsic_array_type(&engine)?),
    ));
    let boolean = ValType::I32;
    let ft = |params: Vec<ValType>, results: Vec<ValType>| FuncType::new(&engine, params, results);

    for kind in [Enumerate::Keys, Enumerate::Values, Enumerate::Entries] {
        register_host_fn(
            linker,
            MODULE_NAME,
            ctor_key(kind.method()),
            ft(vec![obj.clone()], vec![array.clone()]),
            true,
            move |caller, params, results| {
                *abi_result(results, 0)? = enumerate(caller, abi_arg(params, 0)?, kind)?;
                Ok(())
            },
        )?;
    }

    for method in ["assign", "groupBy"] {
        register_host_fn_async(
            linker,
            MODULE_NAME,
            ctor_key(method),
            ft(
                vec![
                    obj.clone(),
                    if method == "assign" {
                        ValType::Ref(RefType::new(
                            false,
                            HeapType::ConcreteStruct(intrinsic_array_type(&engine)?),
                        ))
                    } else {
                        obj.clone()
                    },
                ],
                vec![if method == "assign" {
                    obj.clone()
                } else {
                    ValType::Ref(RefType::new(
                        false,
                        HeapType::ConcreteStruct(intr.object_shape.clone()),
                    ))
                }],
            ),
            true,
            move |caller, params, results| {
                Box::pin(async move {
                    let first = abi_arg(params, 0)?;
                    let second = abi_arg(params, 1)?;
                    *abi_result(results, 0)? = match method {
                        "assign" => assign::assign(caller, first, second).await?,
                        "groupBy" => group_by::group_by(caller, first, second).await?,
                        _ => {
                            return Err(crate::runtime::host::fatal_host_error(
                                "invalid object static dispatch",
                            ));
                        }
                    };
                    Ok(())
                })
            },
        )?;
    }

    register_host_fn_async(
        linker,
        MODULE_NAME,
        ctor_key("fromEntries"),
        ft(
            vec![obj.clone()],
            vec![ValType::Ref(RefType::new(
                false,
                HeapType::ConcreteStruct(intr.object_shape.clone()),
            ))],
        ),
        true,
        |caller, params, results| {
            Box::pin(async move {
                *abi_result(results, 0)? =
                    from_entries::from_entries(caller, abi_arg(params, 0)?).await?;
                Ok(())
            })
        },
    )?;

    register_host_fn(
        linker,
        MODULE_NAME,
        ctor_key("hasOwn"),
        ft(vec![obj.clone(), string.clone()], vec![boolean.clone()]),
        true,
        |caller, params, results| {
            *abi_result(results, 0)? = Val::I32(i32::from(has_own(
                caller,
                abi_arg(params, 0)?,
                abi_arg(params, 1)?,
            )?));
            Ok(())
        },
    )?;

    register_host_fn(
        linker,
        MODULE_NAME,
        ctor_key("#insertField"),
        ft(vec![obj.clone(), string, obj.clone()], vec![]),
        true,
        |caller, params, _| {
            insert_field(
                caller,
                abi_arg(params, 0)?,
                abi_arg(params, 1)?,
                abi_arg(params, 2)?,
            )
        },
    )?;

    let shape = ValType::Ref(RefType::new(
        false,
        HeapType::ConcreteStruct(intr.object_shape.clone()),
    ));
    register_host_fn(
        linker,
        MODULE_NAME,
        ctor_key("#spread"),
        ft(
            vec![obj.clone(), obj.clone(), obj.clone(), obj.clone()],
            vec![shape],
        ),
        true,
        |caller, params, results| {
            *abi_result(results, 0)? = spread(
                caller,
                abi_arg(params, 0)?,
                abi_arg(params, 1)?,
                abi_arg(params, 2)?,
                abi_arg(params, 3)?,
            )?;
            Ok(())
        },
    )?;
    register_host_fn(
        linker,
        MODULE_NAME,
        ctor_key("#toObject"),
        ft(vec![obj.clone()], vec![obj.clone()]),
        true,
        |caller, params, results| {
            *abi_result(results, 0)? = to_object(caller, abi_arg(params, 0)?)?;
            Ok(())
        },
    )?;
    register_host_fn_async(
        linker,
        MODULE_NAME,
        ctor_key("#toJson"),
        ft(
            vec![obj.clone()],
            vec![ValType::Ref(RefType::new(
                false,
                HeapType::ConcreteStruct(intr.string.clone()),
            ))],
        ),
        true,
        |caller, params, results| {
            Box::pin(async move {
                let intr = intrinsic_types(&mut *caller)?;
                *abi_result(results, 0)? = super::vtable::object_to_json(
                    caller,
                    abi_arg(params, 0)?,
                    &intr.raw_string,
                    &intr.string,
                )
                .await?;
                Ok(())
            })
        },
    )?;
    register_host_fn(
        linker,
        MODULE_NAME,
        ctor_key("#staticValue"),
        ft(
            vec![ValType::Ref(RefType::new(
                false,
                HeapType::ConcreteStruct(intr.string.clone()),
            ))],
            vec![obj.clone()],
        ),
        true,
        |caller, params, results| {
            *abi_result(results, 0)? = static_value::static_value(caller, abi_arg(params, 0)?)?;
            Ok(())
        },
    )?;
    register_host_fn_async(
        linker,
        MODULE_NAME,
        ctor_key("is"),
        ft(vec![obj.clone(), obj], vec![boolean]),
        true,
        |caller, params, results| {
            Box::pin(async move {
                *abi_result(results, 0)? = Val::I32(i32::from(
                    same_value(caller, abi_arg(params, 0)?, abi_arg(params, 1)?).await?,
                ));
                Ok(())
            })
        },
    )
}

pub fn declare(defs: &mut PackageDeclaration) {
    dynamic::declare(defs);
    declare_method(
        defs,
        "#toJson",
        ctor_key("#toJson"),
        vec![Param::new("object", Type::Unknown)],
        Type::String,
    );
    // Compiler-only helper: a `{}` value as the object an object type reads.
    declare_method(
        defs,
        "#toObject",
        ctor_key("#toObject"),
        vec![Param::new("value", Type::Unknown)],
        Type::Unknown,
    );
    // Compiler-only helper: the value a static-dispatch binding reads as.
    declare_method(
        defs,
        "#staticValue",
        ctor_key("#staticValue"),
        vec![Param::new("tag", Type::String)],
        Type::Unknown,
    );
    declare_method(
        defs,
        "#insertField",
        ctor_key("#insertField"),
        vec![
            Param::new("object", Type::Unknown),
            Param::new("name", Type::String),
            Param::new("value", Type::Unknown),
        ],
        Type::Void,
    );
    // Compiler-only helper: deliberately absent from ObjectConstructor's public surface.
    declare_method(
        defs,
        "#spread",
        ctor_key("#spread"),
        vec![
            Param::new("target", Type::Unknown),
            Param::new("source", Type::Unknown),
            Param::new("shape", Type::Unknown),
            Param::new("mask", Type::Unknown),
        ],
        // Lowers to the non-null `$ObjectShape` the host function returns.
        Type::any_object(),
    );
    // `Dispatch::Static` drops the constructor receiver, so no receiver param.
    // Types mirror the prelude MethodSigs: `Type::Array`/`Type::Tuple` lower to
    // `(ref $Array)`, matching the registered FuncTypes above.
    let obj = || Param::new("obj", Type::Unknown);
    declare_method(
        defs,
        "keys",
        ctor_key("keys"),
        vec![obj()],
        Type::Array(Box::new(Type::String)),
    );
    declare_method(
        defs,
        "values",
        ctor_key("values"),
        vec![obj()],
        Type::Array(Box::new(Type::Unknown)),
    );
    declare_method(
        defs,
        "entries",
        ctor_key("entries"),
        vec![obj()],
        Type::Array(Box::new(Type::Tuple(
            vec![Type::String, Type::Unknown].into(),
        ))),
    );
    declare_method(
        defs,
        "assign",
        ctor_key("assign"),
        assign_params(),
        Type::TypeVar("T".into()),
    );
    declare_method(
        defs,
        "groupBy",
        ctor_key("groupBy"),
        vec![
            Param::new("items", Type::Unknown),
            Param::new("keySelector", Type::Unknown),
        ],
        group_by_output(),
    );
    declare_method(
        defs,
        "fromEntries",
        ctor_key("fromEntries"),
        vec![Param::new("entries", from_entries_input())],
        from_entries_output(),
    );
    declare_method(
        defs,
        "hasOwn",
        ctor_key("hasOwn"),
        vec![obj(), Param::new("key", Type::String)],
        Type::Boolean,
    );
    declare_method(
        defs,
        "is",
        ctor_key("is"),
        vec![
            Param::new("a", Type::Unknown),
            Param::new("b", Type::Unknown),
        ],
        Type::Boolean,
    );
}

fn assign_params() -> Vec<Param> {
    vec![
        Param::new("target", Type::TypeVar("T".into())),
        Param::rest("sources", Type::Array(Box::new(Type::Unknown))),
    ]
}

fn group_by_params() -> Vec<Param> {
    let element = Type::TypeVar("T".into());
    vec![
        Param::new(
            "items",
            Type::union(vec![
                Type::Readonly(Box::new(Type::Array(Box::new(element.clone())))),
                Type::prelude_interface("Iterable", vec![element.clone()]),
                Type::prelude_interface("Iterator", vec![element.clone()]),
            ]),
        ),
        Param::new(
            "keySelector",
            Type::Function {
                params: vec![element, Type::Number],
                optional: 0,
                ret: Box::new(Type::TypeVar("K".into())),
                predicate: None,
                has_rest: false,
            },
        ),
    ]
}

fn group_by_output() -> Type {
    Type::Object {
        fields: std::collections::BTreeMap::new(),
        index: Some(crate::types::IndexSignature {
            value: Box::new(Type::Array(Box::new(Type::TypeVar("T".into())))),
            readonly: false,
        }),
    }
}

fn from_entries_input() -> Type {
    let entry = Type::Readonly(Box::new(Type::Tuple(
        vec![
            Type::union(vec![Type::String, Type::Number]),
            Type::TypeVar("T".to_string()),
        ]
        .into(),
    )));
    Type::union(vec![
        Type::Readonly(Box::new(Type::Array(Box::new(entry.clone())))),
        Type::prelude_interface("Iterable".to_string(), vec![entry.clone()]),
        Type::prelude_interface("Iterator".to_string(), vec![entry]),
    ])
}

fn from_entries_output() -> Type {
    Type::Object {
        fields: std::collections::BTreeMap::new(),
        index: Some(crate::types::IndexSignature {
            value: Box::new(Type::TypeVar("T".to_string())),
            readonly: false,
        }),
    }
}

/// The type/interface surface this module implements — its slice of the
/// prelude declaration (see `declaration::prelude_package_declaration`).
#[allow(clippy::too_many_lines)]
pub(crate) fn declare_types(defs: &mut crate::PackageDeclaration) {
    use crate::runtime::prelude::declaration::doc;
    use crate::{
        Dispatch, MethodSig, Param, Span, Type, TypeKind, TypeSymbol, ValueKind, ValueSymbol,
    };
    use std::collections::BTreeMap;
    defs.types.insert(
        "Object".to_string(),
        TypeSymbol {
            name: "Object".to_string(),
            mangled_name: crate::mangle::prelude("Object"),
            declaration_span: Span::at(crate::FileId::PRELUDE),
            kind: TypeKind::Interface { index: None,
                generics: Vec::new(),
                methods: BTreeMap::from([
                    (
                        "toString".to_string(),
                        MethodSig {
                            optional: false,
                            generics: Vec::new(),
                            params: Vec::new(),
                            ret: Type::String,
                            predicate: None,
                            doc: doc("/** Returns `\"[object Object]\"`. */"),
                        },
                    ),
                    (
                        "toJson".to_string(),
                        MethodSig {
                            optional: false,
                            generics: Vec::new(),
                            params: Vec::new(),
                            ret: Type::String,
                            predicate: None,
                            doc: doc(
                                "/** Returns the JSON representation of this object — `\"{\"` + `\"key\":value-json` pairs joined with `\",\"` + `\"}\"`. Field iteration order matches the type's struct layout. */",
                            ),
                        },
                    ),
                ]),
                properties: BTreeMap::new(),
                // Object opts OUT of direct dispatch — `obj.toString()`
                // and `obj.toJson()` route through the per-shape vtable
                // (slots 0 / 1). Each user-object shape generates its
                // own per-type body.
                dispatch: Dispatch::VTable,
                doc: doc("/** Universal base type for every object shape. */"),
            },
        },
    );
    defs.types.insert(
        "ObjectConstructor".to_string(),
        TypeSymbol {
            name: "ObjectConstructor".to_string(),
            mangled_name: crate::mangle::prelude("ObjectConstructor"),
            declaration_span: Span::at(crate::FileId::PRELUDE),
            kind: TypeKind::Interface { index: None,
                generics: Vec::new(),
                methods: BTreeMap::from([
                    (
                        "keys".to_string(),
                        MethodSig {
                            optional: false,
                            generics: Vec::new(),
                            params: vec![Param::new("obj", Type::Unknown)],
                            ret: Type::Array(Box::new(Type::String)),
                            predicate: None,
                            doc: doc(
                                "/**\n * Returns the object's field names in canonical sorted order (the same order JSON output uses).\n * An omitted optional field is not listed; one set to `undefined` or `null` is. Non-object values yield `[]`; `null` or `undefined` throws a catchable `Error`.\n * @param obj The object to enumerate.\n */",
                            ),
                        },
                    ),
                    (
                        "values".to_string(),
                        MethodSig {
                            optional: false,
                            generics: Vec::new(),
                            params: vec![Param::new("obj", Type::Unknown)],
                            ret: Type::Array(Box::new(Type::Unknown)),
                            predicate: None,
                            doc: doc(
                                "/**\n * Returns the object's field values, aligned with `Object.keys` order. Element types are erased to `unknown` — narrow with `typeof` / `as`.\n * Non-object values yield `[]`; `null` or `undefined` throws a catchable `Error`.\n * @param obj The object to enumerate.\n */",
                            ),
                        },
                    ),
                    (
                        "entries".to_string(),
                        MethodSig {
                            optional: false,
                            generics: Vec::new(),
                            params: vec![Param::new("obj", Type::Unknown)],
                            ret: Type::Array(Box::new(Type::Tuple(vec![
                                Type::String,
                                Type::Unknown,
                            ].into()))),
                            predicate: None,
                            doc: doc(
                                "/**\n * Returns `[name, value]` pairs in canonical sorted key order. Values are erased to `unknown` — narrow with `typeof` / `as`.\n * Non-object values yield `[]`; `null` or `undefined` throws a catchable `Error`.\n * @param obj The object to enumerate.\n */",
                            ),
                        },
                    ),
                    ("assign".into(), MethodSig {
                        optional: false, generics: vec!["T".into()], params: assign_params(),
                        ret: Type::TypeVar("T".into()), predicate: None,
                        doc: doc("/** Copies own enumerable values from sources to the original target, in source order. Nullish sources are ignored. */"),
                    }),
                    ("groupBy".into(), MethodSig {
                        optional: false, generics: vec!["K".into(), "T".into()], params: group_by_params(),
                        ret: group_by_output(), predicate: None,
                        doc: doc("/** Groups iterable elements by the callback's property key. The callback receives the element and its index; missing groups read as undefined. */"),
                    }),
                    (
                        "fromEntries".to_string(),
                        MethodSig {
                            optional: false,
                            generics: vec!["T".to_string()],
                            params: vec![Param::new("entries", from_entries_input())],
                            ret: from_entries_output(),
                            predicate: None,
                            doc: doc(
                                "/** Creates a string-keyed object from entry pairs. Later entries replace earlier values with the same key. Numeric keys are converted to strings. Object.keys preserves entry insertion order; JSON output uses canonical key order. */",
                            ),
                        },
                    ),
                    (
                        "hasOwn".to_string(),
                        MethodSig {
                            optional: false,
                            generics: Vec::new(),
                            params: vec![
                                Param::new("obj", Type::Unknown),
                                Param::new("key", Type::String),
                            ],
                            ret: Type::Boolean,
                            predicate: None,
                            doc: doc(
                                "/**\n * Returns `true` when `obj` has a field named `key`: an omitted optional field answers `false`, one holding `undefined` answers `true`. Non-object values have no fields; `null` or `undefined` throws a catchable `Error`.\n * @param obj The object to test.\n * @param key The field name.\n */",
                            ),
                        },
                    ),
                    (
                        "is".to_string(),
                        MethodSig {
                            optional: false,
                            generics: Vec::new(),
                            params: vec![
                                Param::new("a", Type::Unknown),
                                Param::new("b", Type::Unknown),
                            ],
                            ret: Type::Boolean,
                            predicate: None,
                            doc: doc(
                                "/**\n * SameValue comparison: like `===` but `Object.is(NaN, NaN)` is `true` and `Object.is(0, -0)` is `false`.\n * Object comparison follows the language's structural `===`, not JS reference identity.\n */",
                            ),
                        },
                    ),
                ]),
                properties: BTreeMap::new(),
                dispatch: Dispatch::Static,
                doc: doc(
                    "/** Constructor object for `Object` — the enumeration statics (`keys`/`values`/`entries`/`hasOwn`), `assign`, `fromEntries`, `groupBy` and `is`. Accessed via the global `Object` binding. */",
                ),
            },
        },
    );

    defs.values.insert(
        "Object".to_string(),
        ValueSymbol {
            name: "Object".to_string(),
            mangled_name: crate::mangle::prelude("Object"),
            declaration_span: Span::at(crate::FileId::PRELUDE),
            kind: ValueKind::Const {
                ty: Type::prelude_interface("ObjectConstructor".to_string(), Vec::new()),
                doc: doc(
                    "/** The `Object` namespace — `Object.keys(o)`, `Object.values(o)`, `Object.entries(o)`, `Object.assign(target, ...sources)`, `Object.fromEntries(entries)`, `Object.groupBy(items, callback)`, `Object.hasOwn(o, k)`, `Object.is(a, b)`. */",
                ),
            },
        },
    );
}

#[cfg(test)]
mod tests {
    use super::same_value_bits;

    #[test]
    fn same_value_bit_rules() {
        assert!(same_value_bits(f64::NAN.to_bits(), (-f64::NAN).to_bits()));
        assert!(!same_value_bits(0f64.to_bits(), (-0f64).to_bits()));
        assert!(same_value_bits((-0f64).to_bits(), (-0f64).to_bits()));
        assert!(same_value_bits(1.5f64.to_bits(), 1.5f64.to_bits()));
        assert!(!same_value_bits(1f64.to_bits(), 2f64.to_bits()));
    }
}