viperjs 0.3.0

An embeddable JavaScript engine in safe Rust, with zero runtime dependencies.
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
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
//! The embedding surface — DR-0021.
//!
//! Everything else public in this crate is an *internal* of the engine that `examples/` and
//! `conformance/` happen to need. This module is the surface someone else builds on: one type that
//! owns both halves of the engine, runs source, moves values across the boundary, and lets the host
//! bind functions of its own.
//!
//! ```
//! use viperjs::api::Engine;
//!
//! let mut engine = Engine::new();
//! let answer = engine.eval("1 + 1").expect("it runs");
//! assert_eq!(engine.text(answer).as_deref(), Ok("2"));
//! ```
//!
//! # Why one type and not two
//!
//! A [`Vm`] and a [`Heap`] are separate objects inside, and every operation takes both. Nothing in
//! that shape says they belong together: two heaps and one machine compile, and the result is
//! *silently wrong* rather than refused, because a `Value` naming an object is an index into an
//! arena and the wrong arena has something else at it. `Engine` owning both makes that
//! unrepresentable — which is why [`Vm::to_string`](crate::vm::Vm) and its neighbours stay crate
//! -private and are wrapped here rather than exported.
//!
//! # What a value is, and how long it lasts
//!
//! [`Value`] is `Copy` and small, and an object one is a handle into this engine's heap. It is
//! **not** a garbage-collection root: [`Engine::collect`] keeps what the *program* can still reach,
//! and a value sitting in a Rust local is not that. To keep one across a collection, put it
//! somewhere the program reaches — [`Engine::set_global`] is that, and it is the same rule a script
//! lives under.
//!
//! Reading a value the collector has taken is **refused** — [`Error::Collected`] — and that refusal
//! is this module's rather than the heap's. DR-0019's generations stop a stale handle finding some
//! *other* value, but `[[Get]]` on an object that is not there degrades to `undefined`, which is
//! what an absent property gives too. Telling those apart is the reason there is a boundary here at
//! all, so every value the host passes in is checked first.
//!
//! # Stopping a script that will not stop
//!
//! [`Engine::set_time_budget`] does it, and exceeding the budget is **not a throw** — a budget a
//! script can `catch` is not a budget, so `try { while (true) {} } catch (e) {}` still ends.
//! DR-0022 is the record; this section said "there is no deadline and no interrupt, so
//! `while (true) {}` runs until the process does not", which was true of DR-0021 and was answered
//! by the very next record.
//!
//! What the budget does **not** reach is a §22.2 match already running and a host function that
//! blocks: `/(a+)+b/` against 22 `a`s takes about 700 ms against a 10 ms budget, which is a test
//! rather than a sentence.
//!
//! # What a host still cannot bind, measured against two real packages
//!
//! Running npm packages through the command line found exactly two things missing, and neither is
//! the engine — both are the *host's* to provide, and this surface cannot yet express either.
//! Written down here rather than left as a bug report, because each is a decision and not an
//! omission.
//!
//! **A constructor.** [`Engine::bind`] and [`Engine::bind_namespace`] make functions, and
//! `Heap::new_native_function` gives them no `[[Construct]]` — so a host cannot offer
//! `new TextEncoder()`. Nor can it build the `Uint8Array` such a thing would answer with: the view
//! constructors are crate-private, and an embedder holding [`Engine::heap_mut`] can make a buffer
//! and not a view over it. `pako` wants both. Neither is hard; both are public API, which is the
//! kind of thing that wants saying out loud before it is added rather than after.
//!
//! **Cryptographic randomness cannot be offered by *this* crate at all**, and that is the more
//! interesting of the two. `crypto.getRandomValues` needs the operating system's entropy, and the
//! two ways to reach it are a dependency (DR-0001 forbids it) and an `unsafe` FFI call (DR-0002
//! forbids that). `/dev/urandom` is a third and exists on one of the two platforms this is built
//! for. What is left is seeding a generator from the clock, and a predictable stream under the name
//! `crypto` is worse than an absent one: a library that finds the function missing says so, and one
//! that finds a fake generates keys with it. So it stays absent here **and belongs to the
//! embedder**, who links whatever they like and can bind it in three lines. `crypto-js` is the
//! package that wants it.

use crate::compile::{Chunk, compile_script};
use crate::heap::{Heap, Native, ObjectId, PropertyDescriptor, PropertyKey};
use crate::parser::parse_script;
use crate::value::{Completion, Value};
use crate::vm::{Fault, Outcome, Vm};
use std::rc::Rc;

/// One engine: a heap, a machine, and one realm's worth of intrinsics.
///
/// Two `Engine`s share nothing at all, which is how GOAL.md §3's advice — isolation comes from
/// running more engines — is actually true rather than merely intended.
pub struct Engine {
    /// The machine. Holds the realm, the module registry and the job queue.
    vm: Vm,
    /// Every value this engine has made.
    heap: Heap,
    /// The last chunk run, kept as [`Engine::collect`]'s root.
    ///
    /// A collection has to know which code is about to run, because a chunk's constant table holds
    /// Strings the machine will reach for and nothing else names them. An `Rc` rather than the
    /// chunk itself so that running it does not borrow `self` while `self.vm` is borrowed
    /// mutably — the clone is a refcount and the alternative is moving the chunk out and back.
    last: Rc<Chunk>,
}

/// The engine, as a **host function** sees it — the other half of [`Engine::bind`].
///
/// A [`Native`] is handed a `&mut Vm` and a `&mut Heap` because that is what the interpreter has,
/// and every operation on those is crate-private for the reason DR-0021 gives. So without this a
/// bound function could be installed and could do nothing with what it was passed: the surface
/// would let a host *register* I/O and not *implement* it.
///
/// Borrows both halves rather than owning them, which is the only difference from [`Engine`] — the
/// engine is mid-call, and the frames underneath belong to the script that is waiting.
///
/// Every operation answers a [`Completion`], not this module's [`Error`], so `?` in a native does
/// what a `throw` does: the failure becomes the script's to catch.
///
/// ```
/// use viperjs::api::{Engine, Host};
/// use viperjs::heap::{Heap, NativeCall};
/// use viperjs::value::{Completion, Value};
/// use viperjs::vm::Vm;
///
/// fn shout(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
///     let mut host = Host::new(vm, heap);
///     let said = host.text(call.argument(0))?;
///     Ok(host.string(&said.to_uppercase()))
/// }
///
/// let mut engine = Engine::new();
/// engine.bind("shout", 1, shout);
/// let answer = engine.eval("shout('hi')").expect("it runs");
/// assert_eq!(engine.text(answer).as_deref(), Ok("HI"));
/// ```
pub struct Host<'a> {
    /// The machine, mid-call.
    vm: &'a mut Vm,
    /// Its heap — the same one, which is the invariant DR-0021 exists to keep.
    heap: &'a mut Heap,
}

impl<'a> Host<'a> {
    /// The two halves a [`Native`] is handed, as one thing.
    pub fn new(vm: &'a mut Vm, heap: &'a mut Heap) -> Self {
        Self { vm, heap }
    }

    /// `String(value)` — §7.1.17, so an object's `toString` runs and may throw.
    ///
    /// # Errors
    ///
    /// Whatever the conversion threw, as the script's own throw: a Symbol always refuses, and an
    /// object may.
    pub fn text(&mut self, value: Value) -> Completion<String> {
        let id = self.vm.to_string(value, self.heap)?;
        Ok(self
            .heap
            .string(id)
            .map(String::from_utf16_lossy)
            .unwrap_or_default())
    }

    /// `Number(value)` — §7.1.4, so an object's `valueOf` runs and may throw.
    ///
    /// The other half of [`Host::text`], and it was missing until a host function wanted to take a
    /// duration: a native could be handed `$262.agent.sleep(100)` and had no way to find the 100
    /// except by converting to a String and parsing it back, which is a second implementation of
    /// §7.1.4 that agrees with the first only by luck.
    ///
    /// # Errors
    ///
    /// Whatever the conversion threw. A Symbol and a BigInt always refuse — §7.1.4 has no reading
    /// for either — and an object may, through its own `valueOf` or `toString`.
    pub fn number(&mut self, value: Value) -> Completion<f64> {
        self.vm.to_number(value, self.heap)
    }

    /// A JavaScript String from Rust text.
    ///
    /// Interned, so two natives answering the same word share one String rather than filling the
    /// arena with copies — which is the allocation a host loop makes most of.
    pub fn string(&mut self, text: &str) -> Value {
        let units: Vec<u16> = text.encode_utf16().collect();
        Value::String(self.heap.intern(&units))
    }

    /// Read `name` off `value`, exactly as `value.name` would — the whole chain, and a getter runs.
    ///
    /// # Errors
    ///
    /// Whatever the read threw, which reading a property of `undefined` or `null` does.
    pub fn get(&mut self, value: Value, name: &str) -> Completion<Value> {
        let units: Vec<u16> = name.encode_utf16().collect();
        let key = PropertyKey::from_units(self.heap, &units);
        self.vm.get_property_key(value, key, self.heap)
    }

    /// Call `callee` with `this_value` and `arguments`.
    ///
    /// This is how a native takes a callback — which is most of what a host API is: `setTimeout`,
    /// a comparator, a visitor.
    ///
    /// # Errors
    ///
    /// Whatever the call threw, including a callee that is not callable.
    pub fn call(
        &mut self,
        callee: Value,
        this_value: Value,
        arguments: &[Value],
    ) -> Completion<Value> {
        self.vm.call_value(callee, this_value, arguments, self.heap)
    }

    /// Run `source` as a **Script** in this realm, from inside a host function.
    ///
    /// §16.1.7's goal and not §19.2.1.1's, which is one argument's worth of difference and is
    /// observable: a Script's `var` becomes a permanent property of the global object where an
    /// `eval`'s is deletable. That is what §INTERPRETING.md defines `$262.evalScript` as, and an
    /// `evalScript` written as `(0, eval)(source)` fails the tests that ask
    /// `verifyProperty(globalThis, 'f', {configurable: false})`.
    ///
    /// The run is *nested*: the frames underneath belong to the script that is waiting, and they
    /// come back untouched. [`Engine::eval`] cannot be used for this — it starts a fresh top-level
    /// run and clears the machine, which from inside a call would take the caller's stack with it.
    ///
    /// # Errors
    ///
    /// A **SyntaxError** for source that will not parse or that an early error refuses, and
    /// otherwise whatever the script threw. Both arrive as a `Completion`, so `?` in a native does
    /// what a `throw` does.
    pub fn eval_script(&mut self, source: &str) -> Completion<Value> {
        crate::builtins::eval::source_as(
            self.vm,
            self.heap,
            source,
            crate::builtins::eval::Goal::Script,
        )
    }

    /// A refusal, in the terms the language uses — the commonest thing a host says.
    ///
    /// A plain function rather than a method because it borrows nothing: `Abrupt::Raised` carries a
    /// `&'static str` and needs no realm until the machine turns it into a value.
    #[must_use]
    pub const fn type_error(message: &'static str) -> crate::value::Abrupt {
        crate::value::Abrupt::type_error(message)
    }
}

/// What went wrong, in terms an embedder can act on.
///
/// Three cases and not one, because the host's response to each differs: source it cannot compile
/// is a bug in what it was given, a throw is the script's own answer and often expected, and a
/// [`Fault`] is a bug in *this engine* — DR-0002 says a script cannot cause one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
    /// The source did not parse or did not compile.
    ///
    /// **Carries where, and it did not until 2026-08-09.** The variant was a bare `String`, so
    /// every host built on this surface — `viper` included — could say `expected an expression,
    /// found ';'` and not which line, while the parser had known the answer all along and
    /// `examples/parse` was already printing it with a caret. That is the house rule about errors
    /// carrying spans stopping at the one boundary where it is most useful, and it made a syntax
    /// error in a 286 KB bundle nearly unactionable.
    Syntax {
        /// What a `SyntaxError` would say.
        message: String,
        /// Where it went wrong. For an unexpected token this is the span of *that token* rather
        /// than of the construct it interrupted, because a caret under the surprise beats one
        /// under its context — the same choice [`crate::parser::ParseError`] makes.
        ///
        /// Turn it into a line and a column with [`crate::span::line_col`], which needs the source
        /// text: a span is a byte range and this type deliberately does not hold a copy of the
        /// program to resolve it against.
        span: crate::span::Span,
    },
    /// The script threw and nothing caught it, with the value spelled as `String(e)` would spell
    /// it.
    ///
    /// The value itself is deliberately not here: it belongs to the engine's heap and would outlive
    /// the borrow that produced it. [`Engine::eval_value`] hands back the value for a caller that
    /// wants to inspect it.
    Thrown(String),
    /// The engine reached a state its own types say is impossible. Not something a script can
    /// cause — see DR-0002 — so this is a bug report, not a condition to handle.
    Engine(Fault),
    /// The run spent the time budget [`Engine::set_time_budget`] set, and was stopped — DR-0022.
    ///
    /// Carries nothing, because there is nothing to carry: no value was produced and nothing was
    /// thrown. A script cannot catch this and no `finally` ran, which is what makes a budget a
    /// bound on untrusted code rather than a suggestion.
    ///
    /// The engine is usable afterwards — the next [`Engine::eval`] starts a fresh run — but what
    /// the interrupted script had already done to the global object is still done.
    Interrupted,
    /// The value names something [`Engine::collect`] has already freed.
    ///
    /// DR-0021: a `Value` the host is holding is not a garbage-collection root. Without this case
    /// the read would answer **`undefined`** — `[[Get]]` on an object that is not there degrades to
    /// exactly what an absent property gives, and the host could not tell "no such property" from
    /// "the object you are asking about is gone". That is the one shape a boundary exists to stop.
    Collected,
}

impl Default for Engine {
    fn default() -> Self {
        Self::new()
    }
}

impl Engine {
    /// A new engine with a fresh realm: the global object, the intrinsics, nothing of the host's.
    #[must_use]
    pub fn new() -> Self {
        let mut heap = Heap::new();
        let vm = Vm::new(&mut heap);
        // An empty chunk so that `collect` has a root before anything has been run. The
        // alternative is an `Option` whose `None` arm is reachable exactly once per engine, which
        // is a branch that exists to describe a moment rather than a state.
        let empty = parse_script("").map(|script| compile_script(&script, &mut heap));
        let chunk = match empty {
            Ok(Ok(chunk)) => chunk,
            // Neither can fail for the empty string — the grammar accepts an empty `StatementList`
            // and there is nothing to compile — so this is the engine's own bug, not an input's.
            _ => Chunk::default(),
        };
        Self {
            vm,
            heap,
            last: Rc::new(chunk),
        }
    }

    /// Run `source` as a Script and answer its completion value.
    ///
    /// §14.2.2's completion value, which is what the last statement produced — so `eval("1; 2")` is
    /// `2` and `eval("var x = 1")` is `undefined`. Jobs queued by the script run before this
    /// returns, because DR-0016 puts the job queue inside the run.
    ///
    /// # Errors
    ///
    /// [`Error::Syntax`] if it does not parse or compile, [`Error::Thrown`] if it threw and nothing
    /// caught it, [`Error::Engine`] for a fault the engine's own types say cannot happen.
    pub fn eval(&mut self, source: &str) -> Result<Value, Error> {
        match self.eval_value(source)? {
            Outcome::Value(value) => Ok(value),
            Outcome::Thrown(value) => Err(Error::Thrown(self.describe(value))),
            Outcome::Interrupted => Err(Error::Interrupted),
        }
    }

    /// The same, without turning a throw into text.
    ///
    /// For a host that wants the thrown *value* — to read its `name`, or to rethrow it into another
    /// call — rather than the sentence [`Engine::eval`] makes of it.
    ///
    /// # Errors
    ///
    /// [`Error::Syntax`] and [`Error::Engine`] as above. A throw is an `Ok(Outcome::Thrown)` here
    /// rather than an `Err`, which is the whole difference.
    pub fn eval_value(&mut self, source: &str) -> Result<Outcome, Error> {
        // Both failures already carry a span — see `parser::ParseError` and `compile::CompileError`
        // — and both are kept. §16's early errors reach here as the *compiler's*, because §22.2.1's
        // patterns are decided there, so a host that only carried the parser's would lose the
        // position of every bad regular expression.
        let script = parse_script(source).map_err(|error| Error::Syntax {
            message: error.kind.to_string(),
            span: error.span,
        })?;
        let chunk = compile_script(&script, &mut self.heap).map_err(|error| Error::Syntax {
            message: error.message(),
            span: error.span,
        })?;
        self.last = Rc::new(chunk);
        let chunk = Rc::clone(&self.last);
        self.vm.run(&chunk, &mut self.heap).map_err(Error::Engine)
    }

    /// §9.13 — every rejection of the last run that nothing ever asked for, oldest first.
    ///
    /// The reasons rather than the promises, because the reason is what a host reports and the
    /// promise is an identity it has no use for. Empty in a program that handles what it rejects.
    ///
    /// Two quite different things put entries here, and a host should say so differently:
    ///
    /// - **A program's own bug.** `Promise.reject(x)` with no `catch`, an `async` function whose
    ///   caller ignored it. Node prints a warning; a browser fires `unhandledrejection`. This is the
    ///   common case and it is not the engine's business to do more than report it.
    /// - **The engine giving up inside a job.** DR-0013's heap RangeError is thrown wherever the
    ///   allocation happened, and if that is inside a `then` handler then §9.5 step 3 discards the
    ///   completion — so [`Engine::eval`] answers `Ok`, the exit status is zero, and a program that
    ///   should have kept running has stopped. **This list is the only sign.** See DR-0029.
    ///
    /// Read it after a run and before the next one, which clears it: a rejection is unhandled only
    /// once the queue has drained and nothing can still attach a handler.
    #[must_use]
    pub fn unhandled_rejections(&self) -> Vec<Value> {
        self.vm
            .unhandled_rejections()
            .iter()
            .map(|promise| {
                self.heap
                    .promise(*promise)
                    .map_or(Value::Undefined, |found| found.result)
            })
            .collect()
    }

    /// `String(value)` — §7.1.17, so an object's `toString` runs and may itself throw.
    ///
    /// # Errors
    ///
    /// [`Error::Thrown`] if the conversion threw, which a `Symbol` always does and an object with a
    /// hostile `toString` may.
    pub fn text(&mut self, value: Value) -> Result<String, Error> {
        if !self.live(value) {
            return Err(Error::Collected);
        }
        match self.vm.to_string(value, &mut self.heap) {
            Ok(id) => Ok(self
                .heap
                .string(id)
                .map(String::from_utf16_lossy)
                // A String the heap does not hold is a handle the collector has taken, which
                // DR-0019 makes answerable rather than dangerous. Empty is the honest reading:
                // there is no text there.
                .unwrap_or_default()),
            Err(abrupt) => Err(self.raised(abrupt)),
        }
    }

    /// Read `name` off `value`, exactly as `value.name` would.
    ///
    /// The whole prototype chain, and a getter runs — so this can throw whatever the script's own
    /// read would.
    ///
    /// # Errors
    ///
    /// [`Error::Thrown`] if the read threw, which reading a property of `undefined` or `null` does.
    pub fn get(&mut self, value: Value, name: &str) -> Result<Value, Error> {
        if !self.live(value) {
            return Err(Error::Collected);
        }
        let key = self.key(name);
        self.vm
            .get_property_key(value, key, &mut self.heap)
            .map_err(|abrupt| self.raised(abrupt))
    }

    /// Call `callee` with `this_value` and `arguments`, as a method call would.
    ///
    /// # Errors
    ///
    /// [`Error::Thrown`] if the callee is not callable or the call threw.
    pub fn call(
        &mut self,
        callee: Value,
        this_value: Value,
        arguments: &[Value],
    ) -> Result<Value, Error> {
        // Every value the host hands in, not only the callee: an argument that has been collected
        // would arrive in the script as `undefined` and be read as one the host chose to pass.
        if !self.live(callee) || !self.live(this_value) || !arguments.iter().all(|v| self.live(*v))
        {
            return Err(Error::Collected);
        }
        self.vm
            .call_value(callee, this_value, arguments, &mut self.heap)
            .map_err(|abrupt| self.raised(abrupt))
    }

    /// Bind a host function into the global object under `name`.
    ///
    /// `length` is what §10.3.3 puts on the function's own `length` property — how many arguments
    /// the host *documents*, not a limit on what it will be passed. The function receives every
    /// argument the call was given, through [`crate::heap::NativeCall::argument`].
    ///
    /// This is the operation GOAL.md §3 means by "the host binds functions in", and until it
    /// existed there was none: `conformance` binds its own `$262` by writing JavaScript source,
    /// because there was nothing else to write.
    pub fn bind(&mut self, name: &str, length: u32, native: Native) {
        let prototype = self.vm.realm().function_prototype();
        let realm = self.vm.realm().id();
        let function = self.heap.new_native_function(prototype, native, realm);
        crate::builtins::define_function_metadata(&mut self.heap, function, name, length);
        // Made a line ago, so it cannot have been collected — the `Result` is the host's concern
        // and not this one's.
        let _ = self.set_global(name, Value::Object(function));
    }

    /// Bind an object of host functions into the global object under `name`.
    ///
    /// `console`, and whatever else a host groups: each entry becomes a method of a plain object
    /// inheriting from `Object.prototype`, named `name.method` the way §10.3.3 names a built-in's,
    /// and the object goes on the global.
    ///
    /// # Why this is not a loop over [`Engine::bind`]
    ///
    /// It could not be. A host outside this crate can make an object and a native function — both
    /// are public on the heap — but not give the function the `name` and `length` §10.3.3 requires,
    /// because that operation is internal. So an embedder building `console` by hand got methods
    /// whose `name` was the empty string, and the only way to a correct one was to write JavaScript
    /// source and evaluate it. Our own command line hit exactly that, which is what
    /// `examples/embed.rs` is for.
    ///
    /// The methods are ordinary writable, enumerable, configurable properties — a namespace a host
    /// hands over belongs to the program, which may take it apart.
    pub fn bind_namespace(&mut self, name: &str, methods: &[(&str, u32, Native)]) {
        let object = self
            .heap
            .new_object(Some(self.vm.realm().object_prototype()));
        for (method, length, native) in methods {
            let prototype = self.vm.realm().function_prototype();
            let realm = self.vm.realm().id();
            let function = self.heap.new_native_function(prototype, *native, realm);
            // §10.3.3's name for a method of a namespace is the qualified one, which is what a
            // stack trace and `console.log.name` should both say.
            let spelled = format!("{name}.{method}");
            crate::builtins::define_function_metadata(&mut self.heap, function, &spelled, *length);
            let key = self.key(method);
            let _ = self.heap.define_own_property(
                object,
                key,
                &PropertyDescriptor::data(Value::Object(function)),
            );
        }
        // Made in this call, so it cannot have been collected.
        let _ = self.set_global(name, Value::Object(object));
    }

    /// Put `value` on the global object under `name`.
    ///
    /// Also the way to **root** a value: the global object is reachable from the program, so
    /// anything hanging off it survives [`Engine::collect`]. A `Value` held only in a Rust local
    /// does not — DR-0021.
    ///
    /// # Errors
    ///
    /// [`Error::Collected`] if `value` has already been freed — rooting a handle that names nothing
    /// would store `undefined` under the name and report success.
    pub fn set_global(&mut self, name: &str, value: Value) -> Result<(), Error> {
        if !self.live(value) {
            return Err(Error::Collected);
        }
        let key = self.key(name);
        let global = self.vm.realm().global();
        let _ = self
            .heap
            .define_own_property(global, key, &PropertyDescriptor::data(value));
        Ok(())
    }

    /// Say how much memory this engine may hand out before it refuses — DR-0013's number.
    ///
    /// [`crate::heap::MAX_HEAP_BYTES`] is the default and is 64 MiB, which is a policy rather than
    /// a fact about the machine: a runaway `while (true) { ({}); }` has to be stopped by something,
    /// and an abort is the one failure DR-0002 cannot answer. Which number is right is the
    /// **host's** question — a command line running one trusted script and a server running
    /// untrusted snippets want opposite answers.
    ///
    /// It is not a theoretical knob. A 1.9 MB bundle of `mathjs`, built the way an application
    /// would build one, needs more than 256 MiB here and runs at 512; the default refuses it, and
    /// before this there was no way for the host to say otherwise.
    ///
    /// Checked against what has already been taken, so lowering it below the current footprint
    /// refuses the next allocation rather than freeing anything.
    pub fn set_heap_budget(&mut self, bytes: usize) {
        self.heap.set_budget(bytes);
    }

    /// The global object, for a host that wants to define properties on it directly.
    #[must_use]
    pub fn global(&self) -> ObjectId {
        self.vm.realm().global()
    }

    /// Bound how long a single [`Engine::eval`] may take — DR-0022, and `None` to remove the bound.
    ///
    /// This is the answer to a script that will not stop. Exceeding the budget is **not a throw**:
    /// the machine stops reading instructions and the call answers [`Error::Interrupted`]. The
    /// script cannot catch it, no `finally` runs, and §9.5's job queue is not drained.
    ///
    /// ```
    /// use viperjs::api::{Engine, Error};
    /// use std::time::Duration;
    ///
    /// let mut engine = Engine::new();
    /// engine.set_time_budget(Some(Duration::from_millis(50)));
    /// assert_eq!(engine.eval("while (true) {}").unwrap_err(), Error::Interrupted);
    /// // …and the engine still works afterwards.
    /// let answer = engine.eval("1 + 1").expect("it runs");
    /// assert_eq!(engine.text(answer).as_deref(), Ok("2"));
    /// ```
    ///
    /// **It does not cover** the regular expression matcher — a pattern that backtracks
    /// catastrophically still runs to completion — nor a single long-running built-in, nor a host
    /// function that blocks. DR-0022 says why each is a separate piece of work.
    pub fn set_time_budget(&mut self, budget: Option<std::time::Duration>) {
        self.vm.set_time_budget(budget);
    }

    /// Say whether this agent may be **suspended** — §9.7's `[[CanBlock]]`.
    ///
    /// `false` is the default and is a claim about the shape of the embedding rather than caution:
    /// an engine running on its own has no second agent, so an `Atomics.wait` that parked here could
    /// never be woken and §25.4.3.14 step 12 is right to throw. A browser's main thread answers the
    /// same way.
    ///
    /// A host that runs several engines — one per thread, sharing memory through
    /// [`Engine::new_shared_buffer`] — turns it on. Whether to turn it on for the engine that
    /// *starts* the others is the decision worth thinking about, and it is a trade rather than a
    /// rule: leaving it off means that agent can never park itself with nobody left running to
    /// notify it, and it also means every `Atomics.wait` it makes throws — which some programs use
    /// as a *probe* rather than as a wait, and are then told the wrong thing. `conformance` turns it
    /// on everywhere and its `agent` module says what that cost.
    ///
    /// **`Atomics.wait` is the only thing that reads it**, and it blocks the calling thread. A host
    /// that sets this must be able to afford that thread stopping for as long as the script asked
    /// for — [`Engine::set_time_budget`] does not cover it, because the machine is not executing
    /// instructions while it waits. That is the whole of what turning this on costs: an engine every
    /// deadline could stop acquires one operation that no deadline can.
    pub fn set_can_block(&mut self, can: bool) {
        self.vm.set_can_block(can);
    }

    /// This engine's realm — its intrinsics, its global, and the identity a function is made in.
    ///
    /// An escape hatch like [`Engine::heap_mut`], and named as one: a [`Realm`](crate::realm::Realm)
    /// is an engine internal whose shape this record does not promise to keep. What it is for is a
    /// host building something this surface cannot express yet. [`Engine::bind`] makes a function on
    /// the global and [`Engine::bind_namespace`] an object of them; anything a level deeper than
    /// that needs the prototypes only a realm has, which is how `conformance` builds a `$262` with
    /// an `agent` inside it.
    #[must_use]
    pub fn realm(&self) -> crate::realm::Realm {
        self.vm.realm()
    }

    /// The bytes a `SharedArrayBuffer` holds, as something another engine can be given.
    ///
    /// `None` for every other value, an ordinary `ArrayBuffer` included: §25.1's bytes belong to one
    /// heap and there is no block underneath them to hand over.
    ///
    /// This is the whole of what one agent passes to another. A [`Value`] is a handle into *this*
    /// engine's heap and means nothing in another one, but a [`Block`](crate::heap::Block) is the
    /// memory itself — clone it, move the clone to the other thread, and
    /// [`Engine::new_shared_buffer`] grows an object over it there.
    #[must_use]
    pub fn shared_block(&self, value: Value) -> Option<crate::heap::Block> {
        let Value::Object(id) = value else {
            return None;
        };
        self.heap
            .object(id)
            .and_then(crate::heap::Object::buffer)
            .and_then(crate::heap::Buffer::block)
            .cloned()
    }

    /// A `SharedArrayBuffer` in **this** engine over bytes another engine already has.
    ///
    /// The receiving half of [`Engine::shared_block`]. The object is this realm's — its prototype,
    /// its brand, its identity — and the bytes are the ones the block names, so a write through one
    /// agent's view is a read through the other's.
    ///
    /// The bytes are **not** charged to this engine's heap budget, because they were charged where
    /// they were allocated: a second name for one allocation is not a second allocation, and
    /// charging both would refuse the sharing at half the memory it appears to be using.
    pub fn new_shared_buffer(&mut self, block: &crate::heap::Block) -> Value {
        let object = self
            .heap
            .new_object(Some(self.vm.realm().shared_buffer_prototype()));
        if let Some(found) = self.heap.object_mut(object) {
            found.set_buffer(crate::heap::Buffer::over(block));
        }
        Value::Object(object)
    }

    /// Free everything the program can no longer reach, and answer how much that was.
    ///
    /// **A `Value` the host is holding is not a root.** See the module documentation: put it on the
    /// global with [`Engine::set_global`] if it has to survive, or call this only at a moment when
    /// nothing is held. Reading a value that has been collected is safe and answers nothing.
    pub fn collect(&mut self) -> crate::heap::Collected {
        let root = Rc::clone(&self.last);
        self.vm.collect(&root, &mut self.heap)
    }

    /// How many bytes this engine's heap has handed out — DR-0013's budget, as a number to watch.
    #[must_use]
    pub fn footprint(&self) -> usize {
        self.heap.footprint()
    }

    /// The heap, for a host reaching an operation this surface does not wrap yet.
    ///
    /// An escape hatch and named as one: everything reachable through it is an engine internal
    /// whose shape this record does not promise to keep.
    pub fn heap_mut(&mut self) -> &mut Heap {
        &mut self.heap
    }

    /// Whether `value`'s handle still names something in this heap.
    ///
    /// Every variant that carries one is asked, not only objects: a String, a Symbol and a BigInt
    /// live in arenas of their own and are swept on the same terms. The four that are wholly
    /// contained in the `Value` — `undefined`, `null`, a Boolean, a Number — are always live,
    /// because there is nothing for them to point at.
    fn live(&self, value: Value) -> bool {
        match value {
            Value::Object(id) => self.heap.object(id).is_some(),
            Value::String(id) => self.heap.string(id).is_some(),
            Value::Symbol(id) => self.heap.symbol(id).is_some(),
            Value::BigInt(id) => self.heap.bigint(id).is_some(),
            Value::Undefined | Value::Null | Value::Boolean(_) | Value::Number(_) => true,
        }
    }

    /// An [`Abrupt`] as the [`Error`] a host sees.
    ///
    /// Through [`Vm::thrown_value`] rather than a spelling of its own, so the sentence is the one a
    /// script catching the same failure would read. §6.2.4's throw completion comes in two shapes —
    /// an error the engine names and a value already built — and only the machine knows how to turn
    /// the first into the second, because it owns the realm the constructor lives in.
    fn raised(&mut self, abrupt: crate::value::Abrupt) -> Error {
        let value = self.vm.thrown_value(abrupt, &mut self.heap);
        Error::Thrown(self.describe(value))
    }

    /// A property key for `name`, interned so that two reads of one name share a String.
    fn key(&mut self, name: &str) -> PropertyKey {
        let units: Vec<u16> = name.encode_utf16().collect();
        PropertyKey::from_units(&mut self.heap, &units)
    }

    /// What a thrown value says about itself — `name: message` for an Error, `String(v)` otherwise.
    ///
    /// Never itself throws: a `toString` that fails is reported as the value refusing to be spelled
    /// rather than replacing one error with another, because the caller is already being told
    /// something went wrong and a second failure buried inside the first helps nobody.
    fn describe(&mut self, value: Value) -> String {
        let Value::Object(_) = value else {
            return self.spell(value);
        };
        let name = self.field(value, "name");
        let message = self.field(value, "message");
        match (name, message) {
            (Some(name), Some(message)) if !name.is_empty() && !message.is_empty() => {
                format!("{name}: {message}")
            }
            (Some(name), _) if !name.is_empty() => name,
            _ => self.spell(value),
        }
    }

    /// The text of `value.name`, or `None` when there is no such property.
    ///
    /// **`undefined` is absent.** `[[Get]]` cannot tell a missing property from one holding
    /// `undefined`, and for a diagnostic they mean the same thing — so spelling the answer
    /// unconditionally put the word into every message about a thrown object that was not an Error:
    /// `throw ({})` read as `"undefined: undefined"`. Mutation coverage found it, by way of two
    /// guards below that no test could distinguish while every field was `Some`.
    fn field(&mut self, value: Value, name: &str) -> Option<String> {
        match self.get(value, name) {
            Ok(Value::Undefined) | Err(_) => None,
            Ok(found) => Some(self.spell(found)),
        }
    }

    /// `String(value)`, with a conversion that throws reported rather than propagated.
    fn spell(&mut self, value: Value) -> String {
        match self.vm.to_string(value, &mut self.heap) {
            Ok(id) => self
                .heap
                .string(id)
                .map(String::from_utf16_lossy)
                .unwrap_or_default(),
            Err(_) => "a value that will not print".to_string(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::heap::NativeCall;
    use crate::value::Completion;

    #[test]
    fn the_heap_budget_is_the_hosts_to_choose_and_defaults_to_something_useful() {
        // DR-0013's number is a policy rather than a fact about the machine, and which policy is
        // right belongs to the embedder. A default of zero would refuse every allocation, which is
        // the mistake `heap::Budget` exists to make unwritable — this row is what would notice.
        let mut engine = Engine::new();
        let answer = engine
            .eval("var a = []; for (var i = 0; i < 5000; i++) a.push({x: i}); a.length")
            .expect("the default budget allows an ordinary program");
        assert_eq!(engine.text(answer).as_deref(), Ok("5000"));

        // Lowered below what a program needs, the program is refused rather than the process dying
        // — which is the whole of what DR-0013 is for.
        let mut small = Engine::new();
        small.set_heap_budget(1 << 16);
        let refused = small.eval("var a = []; for (var i = 0; i < 200000; i++) a.push({x: i}); 1");
        assert!(
            matches!(&refused, Err(Error::Thrown(said)) if said.contains("heap has grown past")),
            "{refused:?}"
        );

        // …and raising it is what lets a program that legitimately wants the memory have it. The
        // pair matters more than either: a budget that only ever refuses is indistinguishable from
        // a broken engine, and one that never refuses is not a budget.
        let mut large = Engine::new();
        large.set_heap_budget(1 << 28);
        let answer = large
            .eval("var a = []; for (var i = 0; i < 200000; i++) a.push({x: i}); a.length")
            .expect("a raised budget allows it");
        assert_eq!(large.text(answer).as_deref(), Ok("200000"));
    }

    #[test]
    fn a_namespace_of_host_functions_is_an_ordinary_object_with_named_methods() {
        fn answer(_: &mut Vm, _: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
            Ok(call.argument(0))
        }
        let mut engine = Engine::new();
        engine.bind_namespace("host", &[("echo", 1, answer), ("also", 2, answer)]);
        // An ordinary object with ordinary properties: the program owns it and may take it apart.
        let answer = engine
            .eval("typeof host + ',' + Object.keys(host).join('|')")
            .expect("runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("object,echo|also"));
        let answer = engine.eval("host.echo(7)").expect("runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("7"));
        // §10.3.3's metadata, which is the whole reason this is not a loop over `bind`: a host
        // outside the crate can make the function but cannot name it, and an unnamed method is
        // what every hand-built namespace used to have.
        let answer = engine
            .eval("host.echo.name + ',' + host.echo.length + ',' + host.also.name")
            .expect("runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("host.echo,1,host.also"));
        // It inherits from `Object.prototype`, so the ordinary object protocol works on it.
        let answer = engine
            .eval("host.hasOwnProperty('echo') + ',' + ('toString' in host)")
            .expect("runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("true,true"));
    }

    #[test]
    fn a_script_answers_its_completion_value_and_the_host_reads_it_as_text() {
        let mut engine = Engine::new();
        let answer = engine.eval("1 + 1").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("2"));
        // §14.2.2's completion value, which is the last statement's: a declaration produces nothing
        // and leaves `undefined` behind rather than the value it bound.
        let answer = engine.eval("1; 2").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("2"));
        let answer = engine.eval("var x = 1").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("undefined"));
    }

    #[test]
    fn a_syntax_error_says_where_and_not_only_what() {
        // The span is the point of the variant, so it is asserted as a *position* rather than as
        // "some span": a message carrying the wrong offset is worse than one carrying none, because
        // a host will print a caret under the wrong token and be believed.
        let mut engine = Engine::new();
        let source = "var a = 1;\nvar b = ;\nvar c = 3;";
        let Err(Error::Syntax { message, span }) = engine.eval(source) else {
            panic!("that does not parse");
        };
        let at = crate::span::line_col(source, span.start);
        assert_eq!((at.line, at.column), (2, 9), "{message}");
        assert_eq!(&source[span.start as usize..span.end as usize], ";");

        // §16's early errors are the compiler's rather than the parser's — §22.2.1's patterns are
        // read after the literal's shape — so this is the other construction site, and it would be
        // the one to lose its span if only the parser's were carried.
        let source = "var re = /(?<a>x)(?<a>y)/;";
        let Err(Error::Syntax { span, .. }) = engine.eval(source) else {
            panic!("a duplicate group name is an early error");
        };
        let at = crate::span::line_col(source, span.start);
        assert_eq!(at.line, 1);
        assert!(at.column > 1, "the pattern is not at the start of the line");

        // A failure at the very end of input still has a position — the one *past* the last
        // character, which is a legal column and the place a missing `}` is missing from.
        let source = "function f() {";
        let Err(Error::Syntax { span, .. }) = engine.eval(source) else {
            panic!("an unclosed body does not parse");
        };
        assert!(span.start as usize >= source.len() - 1);
    }

    #[test]
    fn the_three_failures_are_told_apart_because_a_host_answers_them_differently() {
        let mut engine = Engine::new();
        // Source that cannot be read is the host's own bug — it gave the engine nonsense.
        assert!(matches!(engine.eval("1 +"), Err(Error::Syntax { .. })));
        // A throw is the script's answer and is often the expected one, so it is a different case
        // and carries what a `catch` would have seen.
        assert_eq!(
            engine.eval("throw new TypeError('no')").unwrap_err(),
            Error::Thrown("TypeError: no".to_string())
        );
        // …and a thrown value that is not an Error at all still says something: §7.1.17 spells it.
        assert_eq!(
            engine.eval("throw 7").unwrap_err(),
            Error::Thrown("7".to_string())
        );
        // An engine-raised error reads the same as a script-thrown one, because it goes through the
        // realm's constructor rather than a spelling of this surface's own.
        assert_eq!(
            engine.eval("null.x").unwrap_err(),
            Error::Thrown(
                "TypeError: cannot read a property of something that is not an object".to_string()
            )
        );
    }

    /// Answers its first argument's length, so a test can tell it ran *and* that it was handed what
    /// the call passed.
    fn measure(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
        let text = vm.to_string(call.argument(0), heap)?;
        let length = heap.string(text).map_or(0, <[u16]>::len);
        Ok(Value::Number(length as f64))
    }

    /// A native's `Err` is a throw in the language and not a Rust failure.
    fn refuse(_: &mut Vm, _: &mut Heap, _: &NativeCall<'_>) -> Completion<Value> {
        Err(crate::value::Abrupt::type_error("the host said no"))
    }

    #[test]
    fn a_host_function_is_reachable_from_script_and_sees_its_arguments() {
        let mut engine = Engine::new();
        engine.bind("measure", 1, measure);
        let answer = engine.eval("measure('abcd')").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("4"));
        // §10.3.3's two properties, which every built-in has and which diagnostics read. A host
        // function without them is not the same kind of thing as one of ours.
        let answer = engine
            .eval("measure.name + '/' + measure.length")
            .expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("measure/1"));
        // It is an ordinary function, so the language reaches it the way it reaches any other.
        let answer = engine
            .eval("[1, 22, 333].map(function (n) { return measure(String(n)) }).join(',')")
            .expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("1,2,3"));
    }

    #[test]
    fn a_host_function_that_throws_is_caught_by_the_script() {
        let mut engine = Engine::new();
        engine.bind("refuse", 0, refuse);
        let answer = engine
            .eval("try { refuse() } catch (e) { e.constructor.name + ': ' + e.message }")
            .expect("it runs");
        assert_eq!(
            engine.text(answer).as_deref(),
            Ok("TypeError: the host said no")
        );
        // …and uncaught it reaches the host as a throw rather than as a fault.
        assert_eq!(
            engine.eval("refuse()").unwrap_err(),
            Error::Thrown("TypeError: the host said no".to_string())
        );
    }

    #[test]
    fn a_value_crosses_the_boundary_in_both_directions() {
        let mut engine = Engine::new();
        let object = engine
            .eval("({ a: 1, greet: function (who) { return 'hi ' + who } })")
            .expect("it runs");
        // Reading a property walks the whole prototype chain and runs a getter, so it is the
        // script's own read rather than a peek at a table.
        let a = engine.get(object, "a").expect("a is there");
        assert_eq!(engine.text(a).as_deref(), Ok("1"));
        // Calling back in: the receiver is the host's to choose, which is what makes this a method
        // call rather than a bare one.
        let greet = engine.get(object, "greet").expect("greet is there");
        let name = engine.eval("'world'").expect("it runs");
        let said = engine.call(greet, object, &[name]).expect("it calls");
        assert_eq!(engine.text(said).as_deref(), Ok("hi world"));
        // A value the host holds can be handed back to the script by name.
        engine.set_global("held", object).expect("it is live");
        let answer = engine.eval("held.a").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("1"));
    }

    #[test]
    fn calling_something_that_is_not_a_function_throws_rather_than_faulting() {
        let mut engine = Engine::new();
        let not_callable = engine.eval("({})").expect("it runs");
        assert!(matches!(
            engine.call(not_callable, Value::Undefined, &[]),
            Err(Error::Thrown(_))
        ));
        // Reading a property of `undefined` is the same: the host is given the script's error and
        // not a Rust one, because DR-0002 says nothing a caller does may panic.
        assert!(matches!(
            engine.get(Value::Undefined, "anything"),
            Err(Error::Thrown(_))
        ));
    }

    /// Uppercases its argument through [`Host`] alone — the operations an *out-of-crate* native has.
    ///
    /// The whole of this test's point: fourteen tests passed while a bound function could not
    /// convert its own arguments, because a test inside the crate can reach `Vm::to_string` and a
    /// real host cannot. `examples/embed.rs` found it; this pins it.
    fn shout(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
        let mut host = Host::new(vm, heap);
        let said = host.text(call.argument(0))?;
        Ok(host.string(&said.to_uppercase()))
    }

    /// Calls its first argument with its second, so a callback crosses the boundary both ways.
    fn apply_to(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
        let mut host = Host::new(vm, heap);
        host.call(call.argument(0), Value::Undefined, &[call.argument(1)])
    }

    /// Reads `.width` off its argument and refuses what has none.
    fn width_of(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
        let mut host = Host::new(vm, heap);
        let width = host.get(call.argument(0), "width")?;
        match width {
            Value::Number(_) => Ok(width),
            _ => Err(Host::type_error("that has no numeric width")),
        }
    }

    #[test]
    fn a_native_can_do_its_work_with_only_what_a_host_can_reach() {
        let mut engine = Engine::new();
        engine.bind("shout", 1, shout);
        engine.bind("applyTo", 2, apply_to);
        engine.bind("widthOf", 1, width_of);

        let answer = engine.eval("shout('hi') + shout(42)").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("HI42"));

        // A callback handed to a native and called back into the script — most of what a host API
        // is, and it needs `Host::call` rather than anything the interpreter exposes.
        let answer = engine
            .eval("applyTo(function (n) { return n * 3 }, 7)")
            .expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("21"));

        // Reading a property, and refusing with a message the script catches as its own TypeError.
        let answer = engine.eval("widthOf({ width: 5 })").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("5"));
        let answer = engine
            .eval("try { widthOf({}) } catch (e) { e.constructor.name + ': ' + e.message }")
            .expect("it runs");
        assert_eq!(
            engine.text(answer).as_deref(),
            Ok("TypeError: that has no numeric width")
        );

        // A conversion that throws inside a native travels out as the script's throw, not as a
        // Rust failure — which is what makes `?` the right thing to write in one.
        let answer = engine
            .eval("try { shout(Symbol()) } catch (e) { e.constructor.name }")
            .expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("TypeError"));
    }

    #[test]
    fn a_string_a_native_makes_is_interned_rather_than_copied() {
        // `Host::string` goes through the intern table, so a host loop answering one word does not
        // fill the arena with copies of it. Measured as a footprint that does not grow rather than
        // as an identity, because two equal Strings are equal either way and only the cost differs.
        let mut engine = Engine::new();
        engine.bind("shout", 1, shout);
        engine.eval("shout('warm')").expect("it runs");
        let before = engine.footprint();
        engine
            .eval("for (var i = 0; i < 200; i++) { shout('warm') }")
            .expect("it runs");
        let grew = engine.footprint() - before;
        assert!(
            grew < 200 * std::mem::size_of::<u16>() * 4,
            "200 answers of one word grew the heap by {grew} bytes"
        );
    }

    /// A budget small enough that a runaway is stopped quickly, and large enough that an ordinary
    /// script finishes well inside it. Every row below runs one loop that never ends, so the test
    /// costs about this much wall-clock each time it is reached.
    const BUDGET: std::time::Duration = std::time::Duration::from_millis(50);

    #[test]
    fn a_script_that_will_not_stop_is_stopped() {
        let mut engine = Engine::new();
        engine.set_time_budget(Some(BUDGET));
        assert_eq!(
            engine.eval("while (true) {}").unwrap_err(),
            Error::Interrupted
        );
        // The machine is usable again, because DR-0022 clears the flag when a run *begins* rather
        // than when one ends — the flag has to survive unwinding every nested execution above it.
        let answer = engine.eval("1 + 1").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("2"));
        // …and the budget is still in force, so the next runaway is stopped too. Set once, applied
        // per run: a deadline fixed when the host set it would have passed by now.
        assert_eq!(engine.eval("for (;;) {}").unwrap_err(), Error::Interrupted);
    }

    #[test]
    fn a_stopped_run_cannot_be_caught_and_runs_no_finally() {
        // The decision the whole record turns on. A budget a script can catch is not a budget:
        // `catch` would swallow it and the loop would resume, and the check meant to stop a runaway
        // would fire again for ever.
        let mut engine = Engine::new();
        engine.set_time_budget(Some(BUDGET));
        engine.eval("var reached = 'no'").expect("it runs");
        assert_eq!(
            engine
                .eval("try { while (true) {} } catch (e) { reached = 'catch' }")
                .unwrap_err(),
            Error::Interrupted
        );
        let answer = engine.eval("reached").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("no"));
        // A `finally` is the same answer for the same reason: it is code, and the machine reads no
        // more instructions. A host that needs cleanup has to do it in Rust, and DR-0022 says so.
        assert_eq!(
            engine
                .eval("try { while (true) {} } finally { reached = 'finally' }")
                .unwrap_err(),
            Error::Interrupted
        );
        let answer = engine.eval("reached").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("no"));
    }

    #[test]
    fn a_stop_underneath_a_call_stops_the_caller_too() {
        // Why the flag is read before *every* instruction and not only where the deadline is
        // checked. When a nested execution stops it simply returns, and the call it was serving is
        // left with a frame it never popped and a value it never produced — so the caller carries
        // on as though the call had answered. Without this check the outer loop runs on for another
        // whole check interval, which is a thousand instructions of a script that was supposed to
        // have been stopped.
        //
        // **It is not enough to wrap the call in `try`/`catch`.** A stopped nested execution does
        // not throw — that was the first guess and it left this row passing with the check removed,
        // because the `catch` was never reached in either case. What distinguishes them is an
        // ordinary statement *after* the call.
        let mut engine = Engine::new();
        engine.set_time_budget(Some(BUDGET));
        engine.eval("var reached = 'no'").expect("it runs");
        assert_eq!(
            engine
                .eval("[1].map(function () { while (true) {} }); reached = 'after the callback'")
                .unwrap_err(),
            Error::Interrupted
        );
        let answer = engine.eval("reached").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("no"));
        // The same one level down through a coercion, which enters the loop from the middle of an
        // instruction rather than from a native — a different way in and the same answer.
        assert_eq!(
            engine
                .eval("({ valueOf: function () { while (true) {} } }) + 1; reached = 'after the coercion'")
                .unwrap_err(),
            Error::Interrupted
        );
        let answer = engine.eval("reached").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("no"));
    }

    #[test]
    fn a_stopped_run_drains_no_jobs() {
        // §9.5's queue is drained at the end of a run, and a job is code like any other — a `then`
        // handler that loops for ever is the same problem wearing a promise. So an interrupted run
        // answers without draining.
        let mut engine = Engine::new();
        engine.set_time_budget(Some(BUDGET));
        engine.eval("var ran = 'no'").expect("it runs");
        assert_eq!(
            engine
                .eval("Promise.resolve().then(function () { ran = 'yes' }); while (true) {}")
                .unwrap_err(),
            Error::Interrupted
        );
        let answer = engine.eval("ran").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("no"));
    }

    #[test]
    fn a_waiters_timeout_never_outlasts_the_runs_budget() {
        // The one place the engine sleeps is the end of a drain with a `waitAsync` still owed an
        // answer, and it is the one place a *program* could otherwise decide how long the host waits
        // for control back. It cannot: the sleep ends at the earlier of the two deadlines, and the
        // waiter stays parked.
        //
        // Written as an elapsed time rather than as a settled value because the value is the same
        // either way — a waiter that has not timed out and one the run gave up on both leave the
        // promise pending. What tells them apart is the clock.
        let mut engine = Engine::new();
        engine.set_time_budget(Some(BUDGET));
        let started = std::time::Instant::now();
        engine
            .eval(
                "var a = new Int32Array(new SharedArrayBuffer(32)); \
                 Atomics.waitAsync(a, 0, 0, 5000);",
            )
            .expect("parking is not itself a runaway");
        // Five seconds asked for, a budget of milliseconds, and a second between them. Two orders of
        // magnitude either side, so the row says which of the two bounded the wait without being a
        // race — and five rather than sixty because a mutant that inverts the choice makes every
        // sandboxed run of this test wait out the whole of it.
        assert!(
            started.elapsed() < std::time::Duration::from_secs(1),
            "the run came back in {:?}, so it waited on the script's timeout",
            started.elapsed()
        );
    }

    #[test]
    fn a_loop_inside_a_coercion_or_a_callback_is_stopped_too() {
        // The reason the flag is read before an instruction rather than checked once per run: a
        // coercion re-enters the interpreter from the *middle* of an instruction, and a callback
        // enters it from inside a native. Both are executions of their own and both must stop.
        let mut engine = Engine::new();
        engine.set_time_budget(Some(BUDGET));
        assert_eq!(
            engine
                .eval("({ valueOf: function () { while (true) {} } }) + 1")
                .unwrap_err(),
            Error::Interrupted
        );
        assert_eq!(
            engine
                .eval("[1, 2, 3].map(function () { while (true) {} })")
                .unwrap_err(),
            Error::Interrupted
        );
        // A generator resumed from a `for`-`of` is a third way in, and parks and revives an
        // execution rather than nesting one.
        assert_eq!(
            engine
                .eval("function* g() { while (true) { yield 1 } } for (var x of g()) {}")
                .unwrap_err(),
            Error::Interrupted
        );
    }

    #[test]
    fn no_budget_is_the_default_and_removing_one_restores_it() {
        // Off unless a host asks, which is what leaves the conformance suite, the examples and
        // every existing caller exactly as they were.
        let mut engine = Engine::new();
        let answer = engine
            .eval("var n = 0; for (var i = 0; i < 200000; i++) { n += i } n")
            .expect("no budget, so it finishes however long it takes");
        assert_eq!(engine.text(answer).as_deref(), Ok("19999900000"));
        // A budget that is generous does not stop ordinary work either — the check is a deadline
        // and not a step count, so a loop that finishes in time finishes.
        engine.set_time_budget(Some(std::time::Duration::from_secs(30)));
        let answer = engine
            .eval("var n = 0; for (var i = 0; i < 200000; i++) { n += i } n")
            .expect("well inside thirty seconds");
        assert_eq!(engine.text(answer).as_deref(), Ok("19999900000"));
        // …and it can be taken off again.
        engine.set_time_budget(None);
        let answer = engine.eval("1 + 1").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("2"));
    }

    #[test]
    fn the_budget_does_not_reach_the_regular_expression_matcher() {
        // DR-0022 says this in its "what this does not stop", and a limitation stated only in prose
        // is one nobody finds out has changed. §22.2's backtracking is its own loop and does not
        // read the stop flag, so a hostile pattern runs to completion however small the budget is.
        //
        // `/(a+)+b/` against a subject of `a`s that can never match is the classic: every extra `a`
        // doubles the work. Measured here at 52 ms, 210 ms and 689 ms for widths 18, 20 and 22
        // against a 10 ms budget — so 22 leaves a margin of about seventy times over, which is what
        // keeps this from being a test about how fast the machine is.
        //
        // **If this fails, the matcher has gained a check and that is good news** — update
        // DR-0022's list and this row rather than the budget.
        let mut engine = Engine::new();
        engine.set_time_budget(Some(std::time::Duration::from_millis(10)));
        let answer = engine
            .eval("/(a+)+b/.test('aaaaaaaaaaaaaaaaaaaaaa')")
            .expect("the matcher runs to the end, budget or no budget");
        assert_eq!(engine.text(answer).as_deref(), Ok("false"));
        // …and the machine was never stopped, so the very next statement runs in the same breath.
        let answer = engine.eval("1 + 1").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("2"));
    }

    #[test]
    fn a_thrown_object_is_described_by_the_fields_it_actually_has() {
        // What a host prints when a script throws, and the three shapes are genuinely different
        // rather than an ordering of one rule. An Error has both fields; an object may have one,
        // the other, or neither, and `throw` accepts all of them.
        let mut engine = Engine::new();
        let said = |engine: &mut Engine, source: &str| match engine.eval(source) {
            Err(Error::Thrown(text)) => text,
            other => panic!("expected a throw, got {other:?}"),
        };
        assert_eq!(
            said(&mut engine, "throw new TypeError('no')"),
            "TypeError: no"
        );
        // §20.5.3.3's `message` defaults to the **empty string**, so an Error made without one is
        // its name alone. Written as `name` and not `"name: "` — the separator belongs to the
        // message, and a trailing colon is what joining them unconditionally produces.
        assert_eq!(said(&mut engine, "throw new TypeError()"), "TypeError");
        // A name and no message at all. `undefined` is *absent* here rather than a value to spell,
        // which is the distinction `[[Get]]` cannot draw and this layer must.
        assert_eq!(said(&mut engine, "throw ({ name: 'Weird' })"), "Weird");
        // …and with no name there is nothing to lead with, so the object speaks for itself through
        // §7.1.17 rather than being announced as `undefined`.
        assert_eq!(
            said(&mut engine, "throw ({ message: 'lonely' })"),
            "[object Object]"
        );
        assert_eq!(said(&mut engine, "throw ({})"), "[object Object]");
        // An empty name is present and useless, which is the same case as absent.
        assert_eq!(
            said(&mut engine, "throw ({ name: '', message: 'm' })"),
            "[object Object]"
        );
        // A thrown primitive never had fields to read.
        assert_eq!(said(&mut engine, "throw 7"), "7");
        assert_eq!(said(&mut engine, "throw 'plain'"), "plain");
        // A subclass keeps its own name, which is the reason to read the field rather than the
        // constructor: `name` is what the object says it is.
        assert_eq!(
            said(
                &mut engine,
                "class Mine extends Error { constructor() { super('detail'); this.name = 'Mine' } } throw new Mine()"
            ),
            "Mine: detail"
        );
    }

    #[test]
    fn a_collected_value_is_refused_and_never_read_as_undefined() {
        // DR-0021's rule, and the reason it is a record rather than a doc line: a `Value` the host
        // holds is not a root, and `collect` keeps only what the *program* can reach.
        //
        // **The refusal is this surface's and not the heap's**, which is what the first draft got
        // wrong. `[[Get]]` on an object that is no longer there degrades to `undefined` — the same
        // answer an absent property gives — so without a check the host cannot tell "no such
        // property" from "the object you are asking about is gone". Measured before it was written:
        // the read answered `Ok(undefined)`.
        let mut engine = Engine::new();
        let held = engine.eval("({ a: 1 })").expect("it runs");
        // Enough other work that nothing the machine happens to be holding — §14.2.2's completion
        // register, the operand stack — still names it. Which of those root a value is not part of
        // any promise, and a test that relied on one would be pinning an accident.
        for _ in 0..50 {
            engine.eval("({ junk: 1 })").expect("it runs");
        }
        assert!(engine.collect().objects > 0, "the collector did something");
        assert_eq!(engine.get(held, "a").unwrap_err(), Error::Collected);
        assert_eq!(engine.text(held), Err(Error::Collected));
        assert_eq!(
            engine.call(held, Value::Undefined, &[]).unwrap_err(),
            Error::Collected
        );
        assert_eq!(engine.set_global("x", held), Err(Error::Collected));
        // An argument is checked too, and not only the callee — a collected one would arrive in the
        // script as `undefined` and read as a value the host chose to pass.
        let live = engine.eval("(function (x) { return x })").expect("it runs");
        assert_eq!(
            engine.call(live, Value::Undefined, &[held]).unwrap_err(),
            Error::Collected
        );
    }

    #[test]
    fn the_global_object_is_how_a_host_roots_a_value() {
        // The escape hatch, and it is the one the language already has rather than a second
        // lifetime discipline: anything the program can reach survives, so anything on the global
        // does.
        let mut engine = Engine::new();
        let held = engine.eval("({ a: 1 })").expect("it runs");
        engine.set_global("held", held).expect("it is live");
        for _ in 0..50 {
            engine.eval("({ junk: 1 })").expect("it runs");
        }
        engine.collect();
        let a = engine.get(held, "a").expect("it survived");
        assert_eq!(engine.text(a).as_deref(), Ok("1"));
        // …and the script sees the same object, which is what makes it a root rather than a copy.
        let answer = engine.eval("held.a = 2; held.a").expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("2"));
        let a = engine.get(held, "a").expect("still there");
        assert_eq!(engine.text(a).as_deref(), Ok("2"));
    }

    #[test]
    fn a_value_with_nothing_to_point_at_is_never_collected() {
        // The four that live wholly inside the `Value` have no handle to go stale, so they must not
        // be refused after a collection — a liveness check that asked about them would answer for a
        // slot that does not exist.
        let mut engine = Engine::new();
        let number = engine.eval("42").expect("it runs");
        let boolean = engine.eval("true").expect("it runs");
        let nothing = engine.eval("null").expect("it runs");
        let missing = engine.eval("undefined").expect("it runs");
        for _ in 0..50 {
            engine.eval("({ junk: 1 })").expect("it runs");
        }
        engine.collect();
        assert_eq!(engine.text(number).as_deref(), Ok("42"));
        assert_eq!(engine.text(boolean).as_deref(), Ok("true"));
        assert_eq!(engine.text(nothing).as_deref(), Ok("null"));
        assert_eq!(engine.text(missing).as_deref(), Ok("undefined"));
    }

    #[test]
    fn two_engines_share_nothing() {
        // GOAL.md §3 says isolation comes from running more engines, which is only true if this is.
        let mut first = Engine::new();
        let mut second = Engine::new();
        first.eval("var shared = 1").expect("it runs");
        assert!(matches!(second.eval("shared"), Err(Error::Thrown(_))));
        let answer = first.eval("shared").expect("it runs");
        assert_eq!(first.text(answer).as_deref(), Ok("1"));
    }

    #[test]
    fn two_agents_read_and_write_one_block() {
        // §25.2 exists so that more than one agent can reach the same bytes, and until a host could
        // start a second one that was a claim nothing could test: a `SharedArrayBuffer` whose bytes
        // sat inside a single heap was shared in name only. The two engines here share *this* and
        // nothing else — two heaps, two realms, two of every intrinsic, one allocation.
        let mut main = Engine::new();
        main.eval("var sab = new SharedArrayBuffer(8); var i32 = new Int32Array(sab)")
            .expect("it runs");
        let sab = main.eval("sab").expect("it runs");
        let block = main.shared_block(sab).expect("a shared buffer has one");
        let agent = std::thread::spawn(move || {
            let mut engine = Engine::new();
            let sab = engine.new_shared_buffer(&block);
            engine.set_global("sab", sab).expect("it is live");
            engine
                .eval("new Int32Array(sab)[1] = 7")
                .expect("it runs in the other agent");
        });
        agent.join().expect("the agent finished");
        let answer = main.eval("i32[1]").expect("it runs");
        assert_eq!(main.text(answer).as_deref(), Ok("7"));
    }

    #[test]
    fn an_ordinary_array_buffer_has_no_block_to_share() {
        // §25.1's bytes belong to the heap that made them. Answering a block for one would let a
        // host hand another agent memory the first agent may `transfer` away underneath it.
        let mut engine = Engine::new();
        let unshared = engine.eval("new ArrayBuffer(8)").expect("it runs");
        assert!(engine.shared_block(unshared).is_none());
        let number = engine.eval("42").expect("it runs");
        assert!(engine.shared_block(number).is_none());
        let shared = engine.eval("new SharedArrayBuffer(8)").expect("it runs");
        assert!(engine.shared_block(shared).is_some());
    }

    #[test]
    fn an_engine_no_host_has_spoken_for_refuses_to_block() {
        // §25.4.3.14 step 12 with `[[CanBlock]]` false, which is the default and is the right
        // answer for an engine running on its own: nothing else could ever notify it.
        let mut engine = Engine::new();
        let answer = engine
            .eval(
                "try { Atomics.wait(new Int32Array(new SharedArrayBuffer(8)), 0, 0, 0) } \
                 catch (e) { e.message }",
            )
            .expect("it runs");
        assert_eq!(
            engine.text(answer).as_deref(),
            Ok("this agent cannot be suspended")
        );
    }

    /// Run `source` and answer what it evaluated to, as text — what every row about waiting wants.
    fn answered(engine: &mut Engine, source: &str) -> String {
        let value = engine.eval(source).expect("it runs");
        engine.text(value).expect("a string")
    }

    /// A second agent: an engine of its own on a thread of its own, sharing `block` and nothing
    /// else, which evaluates `source` and answers what it came to as text.
    ///
    /// `sab` is the received `SharedArrayBuffer` — the only thing that crosses between the two.
    fn agent(block: crate::heap::Block, source: &'static str) -> std::thread::JoinHandle<String> {
        std::thread::spawn(move || {
            let mut engine = Engine::new();
            // §9.7 — an agent something else started may be suspended, because that something else
            // is still running and can notify it.
            engine.set_can_block(true);
            let sab = engine.new_shared_buffer(&block);
            engine.set_global("sab", sab).expect("it is live");
            let value = engine.eval(source).expect("it runs in the other agent");
            engine.text(value).expect("a string")
        })
    }

    /// Ask `source` of `engine` until it answers `wanted`, and fail rather than hang if it will not.
    ///
    /// What a test that has started another agent uses instead of sleeping: there is no moment at
    /// which this thread can be *told* the other has reached its wait, so an answer that only the
    /// other agent could have produced is the evidence, and asking again is how it is waited for.
    fn until(engine: &mut Engine, source: &str, wanted: &str, why: &str) {
        for _ in 0..5_000 {
            if answered(engine, source) == wanted {
                return;
            }
            std::thread::sleep(std::time::Duration::from_millis(1));
        }
        panic!("{why}");
    }

    #[test]
    fn a_native_can_convert_what_it_was_given_to_a_number() {
        // §7.1.4 across the boundary, which is what a host function taking a duration or a count
        // wants. The object row is the one that matters: `valueOf` runs, so this is the language's
        // own conversion and not a parse of whatever `String(value)` happened to produce.
        fn doubled(vm: &mut Vm, heap: &mut Heap, call: &NativeCall<'_>) -> Completion<Value> {
            let mut host = Host::new(vm, heap);
            let given = host.number(call.argument(0))?;
            Ok(Value::Number(given * 2.0))
        }
        let mut engine = Engine::new();
        engine.bind("doubled", 1, doubled);
        assert_eq!(answered(&mut engine, "doubled('21')"), "42");
        assert_eq!(
            answered(
                &mut engine,
                "doubled({ valueOf: function () { return 4 } })"
            ),
            "8"
        );
        // Absent is `NaN` and not zero, which is the difference every caller has to decide what to
        // do about — this one doubles it and gets `NaN` back, which is §6.1.6.1 working.
        assert_eq!(answered(&mut engine, "doubled()"), "NaN");
        // A Symbol has no reading at all, and the refusal arrives as the script's to catch.
        assert_eq!(
            answered(
                &mut engine,
                "try { doubled(Symbol()) } catch (e) { e.constructor.name }"
            ),
            "TypeError"
        );
    }

    #[test]
    fn a_wait_ends_at_its_timeout_and_a_stale_expectation_does_not_wait_at_all() {
        // Both of §25.4.3.14's answers that need no second agent, which is why they are together:
        // one engine can measure them and a hang is what a wrong answer looks like.
        let mut engine = Engine::new();
        engine.set_can_block(true);
        engine
            .eval("var i32 = new Int32Array(new SharedArrayBuffer(8))")
            .expect("it runs");
        // A finite timeout that nobody notifies. DR-0024's gap was exactly this and it was the
        // *asynchronous* half that could not be closed — a parked thread has a clock to wake it.
        let started = std::time::Instant::now();
        assert_eq!(
            answered(&mut engine, "Atomics.wait(i32, 0, 0, 30)"),
            "timed-out"
        );
        assert!(started.elapsed() >= std::time::Duration::from_millis(20));
        // And the comparison, on an **infinite** timeout: the slot no longer holds what the caller
        // expected, so there is nothing to wait for. This row hangs rather than fails if that
        // comparison is dropped, which is the shape of the bug it exists to catch.
        engine.eval("i32[0] = 1").expect("it runs");
        assert_eq!(
            answered(&mut engine, "Atomics.wait(i32, 0, 0)"),
            "not-equal"
        );
    }

    #[test]
    fn a_wait_reads_the_byte_its_index_names_and_the_value_as_the_slot_stores_it() {
        let mut engine = Engine::new();
        engine.set_can_block(true);
        engine
            .eval("var i32 = new Int32Array(new SharedArrayBuffer(16)); i32[0] = 5")
            .expect("it runs");
        // §25.4.1 keys a position by **byte**, so index 1 of an `Int32Array` is byte 4. A wait that
        // read byte 0 instead would find the 5 that was put there to notice it, and would answer
        // the other way round on both of these rows.
        assert_eq!(
            answered(&mut engine, "Atomics.wait(i32, 1, 5, 0)"),
            "not-equal"
        );
        assert_eq!(
            answered(&mut engine, "Atomics.wait(i32, 0, 5, 0)"),
            "timed-out"
        );
        // Step 17 compares against the value **as the slot stores it**, and storing into an
        // `Int32Array` wraps rather than clamps: 2**31 lands there as -2147483648, so a wait
        // expecting 2**31 of a slot holding that matches and gets as far as its timeout. §7.1.11's
        // clamping would encode the same expectation as 255 and it would never match anything.
        engine.eval("i32[2] = -Math.pow(2, 31)").expect("it runs");
        assert_eq!(
            answered(&mut engine, "Atomics.wait(i32, 2, Math.pow(2, 31), 0)"),
            "timed-out"
        );
    }

    #[test]
    fn a_wait_that_timed_out_has_taken_itself_off_the_list() {
        // Nobody else can take it off — that is what timing out means — so it does so on its way
        // past, and a notify afterwards has to find nothing. A list that kept it would report
        // having woken a thread that stopped waiting long ago, and the count is a number a program
        // reads and asserts on.
        let mut engine = Engine::new();
        engine.set_can_block(true);
        engine
            .eval("var i32 = new Int32Array(new SharedArrayBuffer(16))")
            .expect("it runs");
        assert_eq!(
            answered(&mut engine, "Atomics.wait(i32, 1, 0, 5)"),
            "timed-out"
        );
        assert_eq!(answered(&mut engine, "Atomics.notify(i32, 1)"), "0");
    }

    #[test]
    fn an_agent_that_may_block_waits_until_another_notifies_it() {
        // The pair that only two agents can show, and the reason the waiter list had to move out of
        // the machine and into the block: this waiter is a parked *thread*, and the notify that
        // ends it is made by an engine that has never heard of it.
        let mut main = Engine::new();
        main.eval("var sab = new SharedArrayBuffer(8); var i32 = new Int32Array(sab)")
            .expect("it runs");
        let sab = main.eval("sab").expect("it runs");
        let block = main.shared_block(sab).expect("a shared buffer has one");
        let other = agent(block, "Atomics.wait(new Int32Array(sab), 0, 0)");
        until(
            &mut main,
            "Atomics.notify(i32, 0)",
            "1",
            "the other agent never reached its wait",
        );
        assert_eq!(other.join().expect("the agent finished"), "ok");
    }

    #[test]
    fn a_notify_wakes_only_the_position_it_names_and_only_as_many_as_it_was_asked_for() {
        let mut main = Engine::new();
        main.eval("var sab = new SharedArrayBuffer(16); var i32 = new Int32Array(sab)")
            .expect("it runs");
        let sab = main.eval("sab").expect("it runs");
        let block = main.shared_block(sab).expect("a shared buffer has one");
        let other = agent(block, "Atomics.wait(new Int32Array(sab), 1, 0, 30000)");
        // Asked over and over for about a tenth of a second, and that is the point rather than
        // impatience: both of these answer `0` whether or not the other agent has parked yet, so a
        // single call proves nothing and a call repeated across the moment it parks proves both. A
        // notify at another position must wake nobody, and a count of zero must wake nobody however
        // many are there to be woken.
        for _ in 0..100 {
            assert_eq!(
                answered(&mut main, "Atomics.notify(i32, 0)"),
                "0",
                "a notify at another position"
            );
            assert_eq!(
                answered(&mut main, "Atomics.notify(i32, 1, 0)"),
                "0",
                "a notify of nobody at this one"
            );
            std::thread::sleep(std::time::Duration::from_millis(1));
        }
        until(
            &mut main,
            "Atomics.notify(i32, 1, 1)",
            "1",
            "the other agent never reached its wait",
        );
        assert_eq!(other.join().expect("the agent finished"), "ok");
    }

    #[test]
    fn two_agents_adding_to_one_slot_lose_nothing() {
        // §25.4.1.2's read-modify-write is **one** step, and with a single agent nothing can tell
        // that from a read followed by a write. With two, everything can: this row counted 39,997
        // of 40,000 the first time it was run against a version that read and wrote separately.
        //
        // It is not an academic number. `atomicsHelper.js` waits for agents to start by spinning
        // until `Atomics.add(i32a, RUNNING, 1)` has reached the number of them — so a lost update
        // there is not a wrong answer but a test that never finishes, which is how this was found.
        const EACH: usize = 20_000;
        let mut main = Engine::new();
        main.eval("var sab = new SharedArrayBuffer(8); var i32 = new Int32Array(sab)")
            .expect("it runs");
        let sab = main.eval("sab").expect("it runs");
        let block = main.shared_block(sab).expect("a shared buffer has one");
        let other = agent(
            block,
            "var a = new Int32Array(sab); \
             for (var i = 0; i < 20000; i++) { Atomics.add(a, 0, 1); } 'done'",
        );
        main.eval("for (var i = 0; i < 20000; i++) { Atomics.add(i32, 0, 1); }")
            .expect("it runs");
        assert_eq!(other.join().expect("the agent finished"), "done");
        assert_eq!(
            answered(&mut main, "Atomics.load(i32, 0)"),
            (EACH * 2).to_string()
        );
    }

    #[test]
    fn two_agents_incrementing_by_compare_exchange_lose_nothing() {
        // The same claim about §25.4.3.3, and it took two attempts to state it in a way that could
        // fail. The first built a mutual-exclusion lock out of `compareExchange` and counted inside
        // it; that passed against a version where the compare and the write were separate steps,
        // because both agents entering needed a *second* collision on the unprotected counter and
        // two thousand rounds never produced one. It was a test that asserted what the code did.
        //
        // This one puts the collision where the bug is. A compare-exchange increment loop retries
        // until the slot still holds what it read, so if two agents can both find the same `old`
        // and both write `old + 1`, one increment is gone — and the window for that is the exchange
        // itself, the same window the `Atomics.add` row above loses four hundred updates in.
        const EACH: usize = 10_000;
        let mut main = Engine::new();
        main.eval("var sab = new SharedArrayBuffer(8); var i32 = new Int32Array(sab)")
            .expect("it runs");
        let sab = main.eval("sab").expect("it runs");
        let block = main.shared_block(sab).expect("a shared buffer has one");
        let other = agent(
            block,
            "var a = new Int32Array(sab); \
             for (var i = 0; i < 10000; i++) { \
                 var old; \
                 do { old = Atomics.load(a, 0); } \
                 while (Atomics.compareExchange(a, 0, old, old + 1) !== old); \
             } 'done'",
        );
        main.eval(
            "for (var i = 0; i < 10000; i++) { \
                 var old; \
                 do { old = Atomics.load(i32, 0); } \
                 while (Atomics.compareExchange(i32, 0, old, old + 1) !== old); \
             }",
        )
        .expect("it runs");
        assert_eq!(other.join().expect("the agent finished"), "done");
        assert_eq!(
            answered(&mut main, "Atomics.load(i32, 0)"),
            (EACH * 2).to_string()
        );
    }

    #[test]
    fn a_notify_spends_its_count_on_parked_threads_before_its_own_promises() {
        // The seam DR-0024's amendment names. A blocking waiter is another agent's thread and an
        // asynchronous one is this agent's promise, and this agent settles its own promises at its
        // own convenience — so a count spent on the promise while the thread stayed parked is a
        // right number and a program that never finishes.
        let mut main = Engine::new();
        main.eval("var sab = new SharedArrayBuffer(16); var i32 = new Int32Array(sab)")
            .expect("it runs");
        let sab = main.eval("sab").expect("it runs");
        let block = main.shared_block(sab).expect("a shared buffer has one");
        // Slot 1 says "about to wait", which is `atomicsHelper.js`'s own idiom and carries its
        // caveat: it is the last statement *before* the wait and not the wait itself, so what reads
        // it waits a little afterwards rather than trusting it.
        let other = agent(
            block,
            "var a = new Int32Array(sab); Atomics.store(a, 1, 1); Atomics.wait(a, 0, 0, 30000)",
        );
        until(
            &mut main,
            "Atomics.load(i32, 1)",
            "1",
            "the other agent never started",
        );
        std::thread::sleep(std::time::Duration::from_millis(50));
        // Parked *after* the thread is, so that a notify of one waiter has two to choose between.
        main.eval("var parked = Atomics.waitAsync(i32, 0, 0)")
            .expect("it runs");
        assert_eq!(answered(&mut main, "Atomics.notify(i32, 0, 1)"), "1");
        assert_eq!(other.join().expect("the agent finished"), "ok");
        // …and the promise is still parked, which is the other half of the same claim: the one wake
        // went to the thread and none of it went here.
        assert_eq!(answered(&mut main, "Atomics.notify(i32, 0)"), "1");
    }

    #[test]
    fn the_job_queue_has_run_by_the_time_eval_returns() {
        // DR-0016 — jobs run inside `run`, so a promise settled by the script has had its reactions
        // delivered when the host is handed the answer. Without that a host would have to be told
        // to drain a queue it cannot see.
        let mut engine = Engine::new();
        let answer = engine
            .eval("var seen = 'pending'; Promise.resolve(7).then(function (v) { seen = v }); 0")
            .expect("it runs");
        assert_eq!(engine.text(answer).as_deref(), Ok("0"));
        let seen = engine.eval("seen").expect("it runs");
        assert_eq!(engine.text(seen).as_deref(), Ok("7"));
    }
    #[test]
    fn probe_completion_register_rooting() {
        let mut e = Engine::new();
        let a = e.eval("({ n: 1 })").expect("runs");
        for _ in 0..50 {
            e.eval("({ junk: 1 })").expect("runs");
        }
        let freed = e.collect();
        println!("freed {:?}", freed.objects);
        match e.get(a, "n") {
            Ok(v) => println!("read gave Ok: {}", e.text(v).unwrap_or_default()),
            Err(err) => println!("read gave Err: {err:?}"),
        }
    }
}