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
//! §14 — statements, each of which leaves the stack exactly as it found it.
//!
//! Whatever a statement pushes it consumes. The one thing it may leave behind is a new completion
//! value, and that lives in a register rather than on the stack — precisely so that a statement
//! in the middle of a block can replace it without disturbing anything below.
//!
//! # What is next door
//!
//! Two chapters used to be in here and are not: [`super::binding`] has §8.6.2's binding patterns
//! and [`super::pattern`] has §13.15.5's destructuring *assignment*. They read alike and are
//! different operations — one makes names, the other writes to references that already exist —
//! and `src/parser/` has always split them exactly this way. All three are one `impl Compiler`,
//! so what a statement compiles to is unchanged by where its helpers live.

use super::Environment;
use super::binding::Bind;
use super::{
    Closing, CompileError, Compiler, Crossing, Instruction, Unpatched, Unwind, unsupported,
};
use crate::ast::{
    BinaryOperator, Declaration, DeclarationKind, ExprKind, ForInOfKind, ForInOfStatement,
    ForInOfTarget, ForInit, ForStatement, LabelledStatement, Stmt, StmtKind, SwitchStatement,
    TryStatement,
};
use crate::span::Span;
use crate::value::Value;
use std::rc::Rc;

/// Which jump is leaving, and what it leaves.
///
/// The three abrupt completions that travel *out* of a statement without being an exception. They
/// differ in one place only — whether the target loop's own iterator is closed — and this is where
/// that one difference is written down, so that no caller has to remember it.
#[derive(Clone, Copy)]
pub(super) enum Exit {
    /// `break` — the statement whose break list is at this index is left, and everything in it.
    Break(usize),
    /// `continue` — the loop at this index is *not* left, so its iterator stays open.
    Continue(usize),
    /// `return` — every enclosing statement is left, whatever it is and however deep.
    Return,
}

impl Exit {
    /// The jump a `break` or a `continue` aimed at the statement at `depth` makes.
    fn of(leaving: bool, depth: usize) -> Self {
        match leaving {
            true => Self::Break(depth),
            false => Self::Continue(depth),
        }
    }
}

/// Whether §15.10 puts a call in **tail position** — the one thing a `return` tells its argument.
///
/// Two values rather than a `bool` so the call sites read as what they mean: `Position::Ordinary`
/// is every call in the language, and `Position::Tail` is the narrow case where the frame this call
/// is made from has nothing left to do. DR-0027.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Position {
    /// The call answers into the frame it was made from, which therefore has to still be there.
    Ordinary,
    /// §15.10.4 `PrepareForTailCall` — the frame goes down first, and the callee answers to
    /// whoever this one was answering to.
    Tail,
}

impl Compiler<'_> {
    /// Compile one statement, leaving the stack as it found it.
    ///
    /// Every statement is stack-neutral: whatever it pushes it consumes, and the one thing it may
    /// leave behind is a new completion value, which lives in a register rather than on the
    /// stack. That invariant is what [`crate::vm::Fault::UnbalancedStack`] checks at the end.
    pub(super) fn statement(&mut self, statement: &Stmt) -> Result<(), CompileError> {
        let span = statement.span;
        // §14.2.2 — every statement below whose clause begins "Let V be undefined" *produces* a
        // value even when nothing inside it does, so a preceding statement's value must not show
        // through: `eval("1; if (true) ;")` is `undefined` and not 1. Emitted before the statement
        // rather than after it, because anything inside that does produce a value overwrites this
        // one — which is exactly what `UpdateEmpty` says, from the other side.
        //
        // The three that are genuinely **empty** are not on the list and must not be: §14.2.2 gives
        // a `Block` with nothing in it, §14.4.1 an `EmptyStatement` and §14.3.2.1 a
        // `VariableStatement` the value EMPTY, so `eval("1; ;")` *is* 1. Getting that backwards
        // would be the same bug in the other direction and no test would look different.
        self.begin_completion(statement);
        match &statement.kind {
            // §14.4 and §14.16 — neither does anything, and neither is value-producing, so the
            // completion value of `1; ;` is 1 rather than `undefined`.
            StmtKind::Empty | StmtKind::Debugger => Ok(()),
            // §14.5.1 — the only statement whose value is its own.
            StmtKind::Expression(expression) => {
                self.expression(expression)?;
                // §14.2.2's completion value is the *script's*. What a statement inside a
                // function evaluates to is nobody's business but `return`'s, so its value is
                // discarded rather than allowed to overwrite the script's.
                if self.is_script {
                    self.chunk.emit(Instruction::SetCompletion);
                } else {
                    self.chunk.emit(Instruction::Pop);
                }
                Ok(())
            }
            // §14.2 — a block is its statements, and it gets a scope of its own exactly when
            // something lexical is declared inside it: `Compiler::block` emits the `PushScope`.
            // This said `let` and `const` were "refused below until they can throw on a use before
            // their declaration"; the temporal dead zone is implemented and nothing is refused.
            StmtKind::Block(body) => self.block(body),
            StmtKind::Declaration(declaration) => self.declaration(declaration, span),
            // §14.6 — the test is thrown away and exactly one branch runs. An `if` with no `else`
            // still jumps over nothing, which is one wasted instruction and no special case.
            StmtKind::If(statement) => {
                self.expression(&statement.test)?;
                let to_alternate = self.chunk.emit_jump(Instruction::JumpIfFalse);
                self.statement(&statement.consequent)?;
                let past_the_alternate = self.chunk.emit_jump(Instruction::Jump);
                self.chunk.patch(to_alternate)?;
                if let Some(alternate) = &statement.alternate {
                    self.statement(alternate)?;
                }
                self.chunk.patch(past_the_alternate)
            }
            // §14.7.2 — the test is at the top, so `while (0) x` never runs its body, and
            // `continue` goes back to that test.
            StmtKind::While(statement) => {
                let top = self.here()?;
                self.expression(&statement.test)?;
                let out = self.chunk.emit_jump(Instruction::JumpIfFalse);
                let compiled = self.loop_body(&statement.body, None, |compiler| {
                    compiler.chunk.emit(Instruction::Jump(top));
                    Ok(top)
                });
                compiled?;
                self.chunk.patch(out)
            }
            // §14.7.1 — the test is at the *bottom*, so the body always runs once, the jump back
            // is the opposite sense, and `continue` goes to the test rather than to the top.
            StmtKind::DoWhile(statement) => {
                let top = self.here()?;
                let compiled = self.loop_body(&statement.body, None, |compiler| {
                    let test = compiler.here()?;
                    compiler.expression(&statement.test)?;
                    compiler.chunk.emit(Instruction::JumpIfTrue(top));
                    Ok(test)
                });
                compiled?;
                Ok(())
            }
            // §14.7.4 — four parts, any of which may be missing. A missing test is `true`, which
            // is what makes `for (;;)` the shortest infinite loop.
            StmtKind::For(statement) => self.for_statement(statement, span),
            // §14.9 and §14.8 — a jump out of, or back to, the innermost loop.
            StmtKind::Break(None) => self.leave_loop(true, span),
            StmtKind::Continue(None) => self.leave_loop(false, span),
            StmtKind::Break(Some(label)) => self.leave_labelled(&label.name, true, span),
            StmtKind::Continue(Some(label)) => self.leave_labelled(&label.name, false, span),
            // §14.14 — throw. The value travels up until a handler wants it, or out of the
            // script; nothing looks at what it is.
            StmtKind::Throw(expression) => {
                self.expression(expression)?;
                self.chunk.emit(Instruction::Throw);
                Ok(())
            }
            // §14.15 — try, in its three shapes.
            StmtKind::Try(statement) => self.try_statement(statement, span),
            // §14.12 — switch.
            StmtKind::Switch(statement) => self.switch_statement(statement),
            StmtKind::ForInOf(statement) => match statement.kind {
                ForInOfKind::In => self.for_in_statement(statement, span),
                // §14.7.5.7 drives an iterator, which needs `Symbol.iterator` and the protocol
                // around it. Named apart from `for`-`in` so the conformance buckets say which of
                // the two is being waited on.
                ForInOfKind::Of => self.for_of_statement(statement, span),
            },
            // §14.13 — a label, which is a name a `break` or a `continue` can aim at.
            StmtKind::Labelled(statement) => self.labelled_statement(statement),
            StmtKind::With(statement) => self.with_statement(statement),
            // §15.2.6 — the function was already made by [`Compiler::hoist_functions`] before the
            // list it stands in ran, at a body's top level and at a block's alike, so the ordinary
            // answer here is to do nothing. And to produce no completion value either, which is
            // §14.2.2: `function f() {}` alone evaluates to `undefined`.
            //
            // §B.3.3 step 3 replaces that answer for the declarations it applies to, which is what
            // the call below is for.
            StmtKind::Function(function) => self.copy_block_function(function, span),
            // §15.7.11 — a declaration evaluates the class and initialises the binding its name
            // already has: the name is hoisted and left uninitialised, so a reference before this
            // point is the temporal dead zone rather than `undefined`.
            StmtKind::Class(class) => {
                // §10.2.9 — a class declaration names its constructor after its own binding.
                self.class(
                    class,
                    match &class.name {
                        Some(name) => super::function::Naming::of(&name.name),
                        None => super::function::Naming::default(),
                    },
                    span,
                )?;
                match &class.name {
                    Some(name) => self.bind_name(&name.name, Bind::Made),
                    None => {
                        self.chunk.emit(Instruction::Pop);
                        Ok(())
                    }
                }
            }
            // §14.10 — `return`, whose argument is optional and whose absence is `undefined`.
            StmtKind::Return(argument) => {
                if self.is_script {
                    return Err(unsupported("return outside a function", span));
                }
                // §15.10 — a `return` whose argument is a call may be a *tail* call, and this is
                // the only statement that can say so. What decides it is `tail_position`, and the
                // call is compiled through `call_at` rather than through `expression` because only
                // the outermost call is in tail position: `return f(g())` must not mark `g`.
                match argument {
                    Some(argument) => match (&argument.kind, self.tail_position()) {
                        (
                            ExprKind::Call {
                                optional,
                                callee,
                                arguments,
                            },
                            true,
                        ) => self.call_at(
                            callee,
                            arguments,
                            *optional,
                            argument.span,
                            Position::Tail,
                        )?,
                        _ => self.expression(argument)?,
                    },
                    None => self.constant(Value::Undefined)?,
                }
                // §14.15.3 and §7.4.9 — a `return` leaves *every* enclosing statement, so each
                // `finally` runs and each `for`-`of` iterator is told, innermost first. If a
                // `return` method throws, that throw wins over the return, which is §7.4.9 step 7;
                // if a `finally` returns something of its own, its `Return` runs and this one
                // never does, which is §14.15.3's `UpdateEmpty` seen from the other side.
                //
                // The value stays on the stack under whatever those blocks put above it, and
                // nothing saves it first. `Return` truncates to the frame it is leaving, so the one
                // case where this is not stack-neutral — a `finally` that jumps away instead of
                // falling through, abandoning the value — abandons it into a frame that is about to
                // go. Saving it in a slot was written first and then taken out: four mutants said
                // the slot decided nothing, and no test could be written that told them apart.
                self.unwind_across(Exit::Return)?;
                // §10.2.2 step 13 — a derived constructor's `return` is stricter than every other
                // one: an object is answered with, `undefined` is answered with the bound `this`, and
                // any other primitive is a **TypeError** where a base constructor would ignore it.
                // Emitted after the iterators are closed, because a `return` inside a `for`-`of` has
                // to close it whatever the value turns out to be.
                if let Some(slot) = self.chunk.derived_this {
                    self.chunk.emit(Instruction::CompleteDerivedReturn(slot));
                }
                self.chunk.emit(Instruction::Return);
                Ok(())
            }
        }
    }
    /// Whether a `return` written here can be §15.10's tail call — DR-0027's four conditions.
    ///
    /// Three of them are one line each and the fourth is the interesting one. §15.10.2's
    /// `HasCallInTailPosition` is thirty productions of static semantics, and what it computes is
    /// "is there anything left to do in this function after the call answers". This compiler
    /// already keeps that, because a `return` has to emit it: the [`Crossing`] entries. So the
    /// question is asked of those rather than of the grammar, and the two cannot disagree.
    ///
    /// `Crossing::Scope` and `Crossing::Operand` are crossed freely — a scope is popped before the
    /// call and an operand goes when the frame does. `Crossing::Finally` and `Crossing::Iterator`
    /// emit code that runs **after** the argument is evaluated, which is exactly what a tail call
    /// has thrown the frame away for. `Crossing::Handlers` is refused for a different reason and
    /// it is §14.6.1's: a `return` inside a `try` block is not in tail position however the block
    /// ends, because the `catch` beside it must still be able to catch.
    ///
    /// That gets `try { } finally { return f() }` right, which is a tail call, and
    /// `try { return f() } finally { }`, which is not — without either being written down as a
    /// case.
    fn tail_position(&self) -> bool {
        // §15.10.3 — only strict function code, which is what every one of test262's files sets.
        // A sloppy function may have an `arguments` object joined to its parameters and a `caller`
        // a program can walk, and neither survives the frame going down.
        if !self.chunk.strict || self.is_script {
            return false;
        }
        // §10.2.2 step 13 — a derived constructor's return emits `CompleteDerivedReturn` after the
        // value is in hand, which is code that runs after the call.
        if self.chunk.derived_this.is_some() {
            return false;
        }
        !self.unwinds.iter().any(|entry| match &entry.what {
            // Both emit code that runs *after* the argument is evaluated, which is exactly what a
            // tail call has thrown the frame away for.
            Crossing::Finally(..) | Crossing::Iterator(..) => true,
            // **The count and not the entry.** §14.6.1 refuses a `return` inside a `try` block
            // because the `catch` beside it must still be able to catch — and that is a handler
            // being *armed*, not a `try` being written. The entry outlives the block: entering a
            // catch sets the count to what is still armed there, which for a `try`/`catch` with no
            // `finally` is zero, because a handler that fired was taken off by the throw that found
            // it. So the catch block is a tail position and the try block is not, which is what
            // §14.6.1 says and what this asks in one comparison.
            Crossing::Handlers(armed) => *armed > 0,
            // A scope is popped before the call, and an operand goes when the frame does.
            Crossing::Scope | Crossing::Operand => false,
        })
    }

    /// §14.2.2 — start this statement's completion value at `undefined`, if its clause says to.
    ///
    /// Eight statement forms begin their evaluation with a `V` of `undefined` — `if` (§14.6.2's
    /// `UpdateEmpty(stmtCompletion, undefined)`), `switch` (§14.12.4's `CaseBlockEvaluation`), the
    /// four iteration statements (§14.7.2.2, §14.7.3.2, §14.7.4.7 and §14.7.5.6), `try` (§14.15.3),
    /// and a labelled statement, which is whichever of those it labels. So each of them replaces
    /// whatever value came before it whether or not anything inside produces one.
    ///
    /// Everything else is either value-producing on its own — an expression statement, which sets
    /// the value where it is evaluated — or **empty**, which is a third thing and not the same as
    /// `undefined`: `eval("1; ;")` and `eval("1; { }")` and `eval("1; var x;")` are all 1.
    ///
    /// Nothing at all outside Script code, where §14.2.2's value is not kept — see the expression
    /// statement above for the same test and the same reason.
    fn begin_completion(&mut self, statement: &Stmt) {
        if !self.is_script || !Self::starts_a_completion(&statement.kind) {
            return;
        }
        // Through the register rather than the stack: a statement is stack-neutral, and this runs
        // before one that may leave the stack as it found it in several different ways.
        self.chunk.emit(Instruction::CompletionUndefined);
    }

    /// Whether §14.2.2 makes this statement's own value start at `undefined` rather than empty.
    fn starts_a_completion(kind: &StmtKind) -> bool {
        match kind {
            StmtKind::If(_)
            | StmtKind::Switch(_)
            | StmtKind::While(_)
            | StmtKind::DoWhile(_)
            | StmtKind::For(_)
            | StmtKind::ForInOf(_)
            | StmtKind::Try(_)
            | StmtKind::With(_) => true,
            // §14.13.4 hands a label's value straight through, so a labelled `if` starts one and a
            // labelled `var` does not — asked of what is under the label rather than of the label.
            StmtKind::Labelled(statement) => Self::starts_a_completion(&statement.body.kind),
            _ => false,
        }
    }

    /// §14.2 — a block, which is a scope of its own because §14.3.1 puts `let` and `const` in one.
    ///
    /// The bindings are created here, all of them, before any statement runs — that is
    /// §14.2.3 `BlockDeclarationInstantiation` — and each is left uninitialised, which is what
    /// makes reading one above its declaration a ReferenceError rather than `undefined`.
    pub(super) fn block(&mut self, body: &[Stmt]) -> Result<(), CompileError> {
        // §14.2.2 makes a Declarative Environment Record for a block **only if it declares
        // something**. Not an optimisation: `{ }` and `if (c) { x; }` are most of the blocks in
        // any program, and an environment each would be an allocation per `if` for a scope holding
        // nothing. §8.3.2's chain would be longer everywhere and hold the same names.
        let lexical = Self::declares_something_lexical(body);
        let opened = lexical.then(|| self.enter_environment());
        let mark = self.enter_scope();
        self.declare_lexical_names(body)?;
        // §14.1 `BlockDeclarationInstantiation` step 3.a.ii — a function declaration in a block is
        // created *and initialised* before the block's first statement, so `{ f(); function f() {}
        // }` calls it. The slot goes in the block's own level, which since block environments
        // arrived is the block's own environment: a second entry makes a second function.
        //
        // Annex B.3.3's extra `var` binding in the enclosing function is **not** here — DR-0008
        // leaves Annex B out — so `{ function f() {} } f;` is a ReferenceError rather than the
        // function, which is what a strict-mode engine does and what §14.1 alone says.
        self.hoist_functions(body)?;
        self.statements(body)?;
        self.leave_scope(mark);
        if let Some(opened) = opened {
            self.leave_environment(opened)?;
        }
        Ok(())
    }

    /// Whether this body's *top level* declares anything a block scope has to keep — §8.2.6.
    ///
    /// The same question [`Compiler::declare_lexical_names`] answers by doing it, asked before any
    /// of it happens: an environment has to be pushed before the names go into it, and whether to
    /// push one depends on whether there are any. Kept beside that function so the two cannot
    /// drift — a `let` form it learned about and this did not would silently lose its scope.
    fn declares_something_lexical(body: &[Stmt]) -> bool {
        body.iter().any(|statement| match &statement.kind {
            StmtKind::Class(class) => class.name.is_some(),
            StmtKind::Declaration(declaration) => declaration.kind.is_lexical(),
            // §14.1 — a function declaration in a block belongs to the *block*, which is what
            // makes it the one declaration that is hoisted and lexical at once: created and
            // **initialised** when the block is entered, where a `let` is created and left in the
            // dead zone. Without it here the block gets no environment and the name would be a
            // slot in the function, shared by every entry.
            //
            // Through a label, for the reason [`Compiler::hoist_functions`] looks through one: the
            // two have to agree about what this list declares, and a block that hoisted a name
            // into an environment it never opened would put it in the enclosing one.
            StmtKind::Labelled(_) => super::annex_b::declared_function(statement).is_some(),
            StmtKind::Function(_) => true,
            _ => false,
        })
    }

    /// Create every `let` and `const` a body declares, uninitialised — §14.2.3 and §10.2.11.
    ///
    /// Only the *top level* of the body, because that is what §8.2.6's `LexicallyDeclaredNames`
    /// is: a `let` inside a nested block belongs to that block and is created when it is entered.
    pub(super) fn declare_lexical_names(&mut self, body: &[Stmt]) -> Result<(), CompileError> {
        for statement in body {
            // §15.7.11 — a class declaration is a lexical declaration: its name is hoisted and left
            // uninitialised, so a reference above it is the temporal dead zone rather than
            // `undefined`. That is the difference from a function declaration, which is hoisted
            // *initialised* and callable before its own line.
            if let StmtKind::Class(class) = &statement.kind {
                if let Some(name) = &class.name {
                    let slot = self.declare_lexical(&name.name, crate::heap::Mutability::Mutable);
                    self.chunk.emit(Instruction::Uninitialise(slot));
                }
                continue;
            }
            let StmtKind::Declaration(declaration) = &statement.kind else {
                continue;
            };
            if !declaration.kind.is_lexical() {
                continue;
            }
            let immutable = declaration.kind == DeclarationKind::Const;
            for declarator in &declaration.declarators {
                // §8.2.1 `BoundNames` of the binding, which for a pattern is every name inside it
                // — `let {a, b: [c]} = x` puts three in the dead zone, not one. The walk is the
                // static-semantics one rather than a second copy here, because a name it missed
                // would be a binding that never existed and a `ReferenceError` no source explains.
                for name in crate::static_semantics::bound_names(&declarator.binding) {
                    let slot =
                        self.declare_lexical(name.name, super::lexical_mutability(immutable));
                    self.chunk.emit(Instruction::Uninitialise(slot));
                }
            }
        }
        Ok(())
    }

    /// §14.3 — `var`, `let` and `const`.
    pub(super) fn declaration(
        &mut self,
        declaration: &Declaration,
        _span: Span,
    ) -> Result<(), CompileError> {
        if declaration.kind.is_lexical() {
            return self.lexical_declaration(declaration);
        }
        for declarator in &declaration.declarators {
            // A `var` with no initializer does nothing at all. The slot already holds `undefined`
            // from hoisting, and assigning it again would overwrite what an earlier `var x = 1`
            // put there: `var x = 1; var x;` leaves `x` as 1, which surprises people once.
            //
            // A *pattern* with no initializer cannot happen: §14.3.2.1 makes it a Syntax Error,
            // because there would be nothing to take apart.
            let Some(initializer) = &declarator.initializer else {
                continue;
            };
            // The value is evaluated first and the binding takes it apart — which is what makes
            // a `var` at the top level of a script a property of the global object rather than a
            // slot, decided per name inside [`Compiler::bind_name`] rather than here.
            self.initialiser(&declarator.binding, initializer)?;
            self.destructure(&declarator.binding, Bind::Var, declarator.span)?;
        }
        Ok(())
    }
    /// §14.7.4's four parts.
    fn for_statement(&mut self, statement: &ForStatement, span: Span) -> Result<(), CompileError> {
        // §14.7.4.4 — the head's `let` and `const` belong to the *loop*, not to the statement
        // around it, so the scope opens before the head is compiled and closes after the body.
        // §14.7.4.4 — and only a *lexical* head gets an environment: `for (var i = …)` declares
        // one binding for the whole function and `for (i = 0; …)` declares none at all, so an
        // environment for either would be a scope with nothing in it that has to be copied on
        // every pass.
        let lexical = matches!(
            &statement.init,
            Some(ForInit::Declaration(declaration)) if declaration.kind.is_lexical()
        );
        let mut opened = lexical.then(|| self.enter_environment());
        let mark = self.enter_scope();
        // §14.7.4.2 — the initialiser runs once, before anything else, and outside the loop it
        // starts. It is compiled here rather than inside `for_parts` because the environment it
        // fills has to exist first and the copies below have to come after it: `for (let i = f();
        // …)` calls `f` once, whatever the loop then does with `i`.
        let compiled = self
            .for_init(statement, span)
            .and_then(|()| self.for_parts(statement, opened.as_mut()));
        self.leave_scope(mark);
        if let Some(opened) = opened {
            self.leave_environment(opened)?;
        }
        compiled
    }

    /// §14.7.5 — `for (x in o)`, over the enumerable property names of `o` and its prototypes.
    ///
    /// The names are taken once, before the body runs, and then walked. §14.7.5.10 asks for
    /// exactly that: a property added while the loop runs need not be visited, and one deleted
    /// before it is reached must not be — so the list settles the first and
    /// [`Instruction::EnumerateNext`] asks the object again about each name, which settles the
    /// second.
    ///
    /// The name is put in a slot of its own before it is assigned anywhere. That is what lets one
    /// shape of code serve all three targets — a fresh binding, an existing name, a property —
    /// rather than each having to reach a value buried under whatever it needs on the stack.
    fn for_in_statement(
        &mut self,
        statement: &ForInOfStatement,
        span: Span,
    ) -> Result<(), CompileError> {
        // §14.7.5.5 — a `let` or `const` in the head belongs to the loop, so the scope opens
        // before the binding is made and closes after the body.
        let mark = self.enter_scope();
        let compiled = self.for_in_parts(statement, span);
        self.leave_scope(mark);
        compiled
    }

    /// §14.7.5.6 `ForIn/OfHeadEvaluation` step 2 — the dead zone the head's own names sit in.
    ///
    /// A lexical `for` head binds its names *around the expression it iterates*, uninitialised. So
    /// `let x = 1; for (let x in { x })` is a **ReferenceError** and not a walk of `{ x: 1 }`: the
    /// inner `x` shadows the outer one before the object literal is built, and reading it there is
    /// the temporal dead zone like any other.
    ///
    /// It is a separate environment from the per-pass ones below and it is gone before the loop
    /// starts — step 5 restores the old one, and §14.7.5.7's environment per pass is made from
    /// *that* rather than from this. Two levels rather than one because the two have different
    /// lifetimes: this one exists for the length of one expression.
    ///
    /// `None` when the head declares nothing lexical, which is `for (x in …)` and `for (var x in
    /// …)` — neither binds anything here, so an environment would hold no names and §14.7.5.6 step
    /// 2's condition is exactly that.
    pub(super) fn head_dead_zone(
        &mut self,
        target: &ForInOfTarget,
    ) -> Result<Option<(Environment, usize)>, CompileError> {
        let ForInOfTarget::Declaration(declaration) = target else {
            return Ok(None);
        };
        if !declaration.kind.is_lexical() {
            return Ok(None);
        }
        let opened = self.enter_environment();
        let mark = self.enter_scope();
        for declarator in &declaration.declarators {
            // §8.2.1 `BoundNames`, the static-semantics walk rather than a second copy — a pattern
            // head puts every name inside it in the dead zone, not only the first.
            //
            // Every one is **mutable**, and a `const` head is no exception: nothing may be assigned
            // to a binding in its dead zone whatever its mutability — §6.2.5.6 refuses the write for
            // being uninitialised, several steps before it would ask whether it is writable. So
            // carrying the `const` here would be a distinction no program could observe, which is
            // what mutation coverage said by surviving its removal.
            for name in crate::static_semantics::bound_names(&declarator.binding) {
                let slot = self.declare_lexical(name.name, crate::heap::Mutability::Mutable);
                self.chunk.emit(Instruction::Uninitialise(slot));
            }
        }
        Ok(Some((opened, mark)))
    }

    /// Close what [`Compiler::head_dead_zone`] opened, once the head expression has been evaluated.
    pub(super) fn leave_head_dead_zone(
        &mut self,
        opened: Option<(Environment, usize)>,
    ) -> Result<(), CompileError> {
        let Some((environment, mark)) = opened else {
            return Ok(());
        };
        self.leave_scope(mark);
        self.leave_environment(environment)
    }

    /// The rest of `for`-`in`, once its scope has been opened.
    fn for_in_parts(
        &mut self,
        statement: &ForInOfStatement,
        span: Span,
    ) -> Result<(), CompileError> {
        let keys = self.declare_hidden("keys");
        let object = self.declare_hidden("object");
        let index = self.declare_hidden("index");
        let current = self.declare_hidden("current");

        // §14.7.5.6 `ForIn/OfHeadEvaluation` — the object is evaluated once, and kept, because
        // every step has to ask it whether the name it is about to visit is still there. Step 2's
        // dead zone is around *this* evaluation and nothing else.
        let dead_zone = self.head_dead_zone(&statement.left)?;
        self.expression(&statement.right)?;
        self.leave_head_dead_zone(dead_zone)?;
        self.chunk.emit(Instruction::Duplicate);
        self.chunk.emit(Instruction::EnumerateProperties);
        self.chunk.emit(Instruction::StoreVariable(0, keys));
        self.chunk.emit(Instruction::Pop);
        self.chunk.emit(Instruction::StoreVariable(0, object));
        self.chunk.emit(Instruction::Pop);
        self.constant(Value::Number(0.0))?;
        self.chunk.emit(Instruction::StoreVariable(0, index));
        self.chunk.emit(Instruction::Pop);

        // The head's binding, if it declares one. §14.7.5.5 makes it a *fresh* binding per
        // iteration, which is only observable through a closure — so a lexical head opens an
        // environment of its own below, once per pass, rather than reusing one slot for the walk.
        let top = self.here()?;
        self.chunk.emit(Instruction::LoadVariable(0, object));
        self.chunk.emit(Instruction::EnumerateNext(keys, index));
        self.chunk.emit(Instruction::StoreVariable(0, current));
        self.chunk.emit(Instruction::Pop);
        // `undefined` is the end of the enumeration and cannot be a name — §14.7.5.10 yields
        // Strings and nothing else.
        self.chunk.emit(Instruction::LoadVariable(0, current));
        self.constant(Value::Undefined)?;
        self.chunk
            .emit(Instruction::Binary(BinaryOperator::StrictEqual));
        let out = self.chunk.emit_jump(Instruction::JumpIfTrue);

        // §14.7.5.7 step 3.g again, and simpler here: a `for`-`in` closes nothing, so there is no
        // iterator entry for the environment to have to sit inside.
        let lexical = matches!(
            &statement.left,
            ForInOfTarget::Declaration(declaration) if declaration.kind.is_lexical()
        );
        let opened = lexical.then(|| self.enter_iteration_environment());
        let binding = self.for_in_binding(&statement.left, span)?;
        let deep = u32::from(lexical);
        self.assign_enumerated(&statement.left, binding, current, deep, span)?;
        let body = self.loop_body(&statement.body, None, |compiler| {
            if lexical {
                compiler.chunk.emit(Instruction::PopScope);
            }
            compiler.chunk.emit(Instruction::Jump(top));
            Ok(top)
        });
        if let Some(opened) = opened {
            self.leave_environment_already_popped(opened)?;
        }
        body?;
        self.chunk.patch(out)
    }

    /// §14.7.5.7 — `for`-`of`, which drives an iterator rather than walking a list of keys.
    ///
    /// The difference from `for`-`in` is not the shape of the loop; it is that every step runs
    /// user code. `next` may throw, may answer something that is not an object, and may have side
    /// effects — so the loop is compiled out of ordinary calls and property reads rather than out
    /// of an instruction that walks something the engine already holds.
    fn for_of_statement(
        &mut self,
        statement: &ForInOfStatement,
        span: Span,
    ) -> Result<(), CompileError> {
        // §14.7.5.7 — `for await` walks an **async** iterator, which is a different loop and not a
        // flag on this one: every step is awaited before it is read.
        if statement.is_await {
            return self.for_await_statement(statement, span);
        }
        let mark = self.enter_scope();
        let compiled = self.for_of_parts(statement, span);
        self.leave_scope(mark);
        compiled
    }

    /// The rest of `for`-`of`, once its scope has been opened.
    fn for_of_parts(
        &mut self,
        statement: &ForInOfStatement,
        span: Span,
    ) -> Result<(), CompileError> {
        let iterator = self.declare_hidden("iterator");
        let next = self.declare_hidden("next");
        let current = self.declare_hidden("current");
        let closable = self.declare_hidden("closable");

        // §7.4.2 `GetIterator` — ask the iterable for its iterator, then read `next` **once**.
        // The handler goes on *after* the iterator exists, because a throw from the head has no
        // iterator to close — and comes off at every deliberate way out, which is why `break`
        // lands past it and `return` unwinds the frame that holds it.
        // Reading it once is observable: a `next` replaced on the iterator part-way through the
        // loop is not the one the rest of the loop calls.
        //
        // §14.7.5.6 step 2's dead zone wraps the *expression* and comes off before `GetIterator`
        // runs, which is what `for (let x of [x])` turns on.
        let dead_zone = self.head_dead_zone(&statement.left)?;
        self.expression(&statement.right)?;
        self.leave_head_dead_zone(dead_zone)?;
        self.chunk.emit(Instruction::Duplicate);
        self.chunk
            .emit(Instruction::LoadWellKnown(well_known("iterator")));
        self.chunk.emit(Instruction::GetProperty);
        self.chunk.emit(Instruction::CallMethod(0));
        // Step 5 — what came back must be an object, or the loop would read `next` off a
        // primitive's prototype and call something that was never there.
        self.chunk.emit(Instruction::RequireObject);
        self.chunk.emit(Instruction::StoreVariable(0, iterator));
        let name = self.name_of("next");
        self.constant(Value::String(name))?;
        self.chunk.emit(Instruction::GetProperty);
        self.chunk.emit(Instruction::StoreVariable(0, next));
        self.chunk.emit(Instruction::Pop);

        // §7.4.9 again, for the way out nothing can jump to: a throw from the body, or from
        // `next` itself. The handler closes the iterator and throws the same thing onward — and
        // does not look at what `return` answered, because step 5 has already decided.
        //
        // Emitted *above* the per-iteration environment below, which is what makes the throw path
        // simple: unwinding restores the environment a handler was installed in, so the closing
        // code here runs with the loop's own slots at depth zero however many passes had gone by.
        let unwind = self.chunk.emit_jump(Instruction::PushHandler);

        let top = self.here()?;
        // Cleared before every `next()`, so a throw from the step below is the shape that must not
        // close. Set again once a value is in hand, just above the binding.
        self.constant(Value::Number(0.0))?;
        self.chunk.emit(Instruction::StoreVariable(0, closable));
        self.chunk.emit(Instruction::Pop);
        // §7.4.5 `IteratorStep` — `next.call(iterator)`, and the result must be an object.
        self.chunk.emit(Instruction::LoadVariable(0, iterator));
        self.chunk.emit(Instruction::LoadVariable(0, next));
        self.chunk.emit(Instruction::CallMethod(0));
        self.chunk.emit(Instruction::RequireObject);
        self.chunk.emit(Instruction::Duplicate);
        let name = self.name_of("done");
        self.constant(Value::String(name))?;
        self.chunk.emit(Instruction::GetProperty);
        // `ToBoolean` of it, which is what the jump already does — §7.4.5 step 4 asks whether it
        // is truthy and not whether it is `true`.
        //
        // Jumping on *false* rather than on true, so that the result object is dropped before the
        // loop can be left. A `break` lands where the done path lands, and the two have to agree
        // about what is on the stack — leaving the result there for the done path to pop made a
        // `break` pop something that was never pushed.
        let going = self.chunk.emit_jump(Instruction::JumpIfFalse);
        self.chunk.emit(Instruction::Pop);
        let out = self.chunk.emit_jump(Instruction::Jump);
        self.chunk.patch(going)?;
        let name = self.name_of("value");
        self.constant(Value::String(name))?;
        self.chunk.emit(Instruction::GetProperty);
        self.chunk.emit(Instruction::StoreVariable(0, current));
        self.chunk.emit(Instruction::Pop);

        // §14.7.5.7 step 3 — the `?` on `next()`, on `IteratorComplete` and on `IteratorValue`
        // propagates **without** closing: an iterator whose own `next` threw is not one to tell the
        // walk is over, and the specification only reaches `IteratorClose` from step 3.n and 3.q,
        // which are the binding and the body. A flag rather than moving the handler, because the
        // handler covers a region `continue` jumps back into and `break` crosses — arming it per
        // iteration would need both of those taught about it, where this needs neither.
        self.constant(Value::Number(1.0))?;
        self.chunk.emit(Instruction::StoreVariable(0, closable));
        self.chunk.emit(Instruction::Pop);

        // §14.7.5.7 step 3.g — `NewDeclarativeEnvironment` **per pass**, holding the head's binding
        // and nothing else. Made here rather than around the whole loop because the loop's own
        // slots — the iterator, its `next`, the flag saying whether it may still be closed — have
        // to outlive one pass and be reachable from the handler above at a fixed depth.
        //
        // A closure made in one pass therefore keeps that pass's binding, which is the difference
        // between `for (const x of [1, 2, 3])` handing three closures three values and three ones.
        let lexical = matches!(
            &statement.left,
            ForInOfTarget::Declaration(declaration) if declaration.kind.is_lexical()
        );
        // §7.4.9's entry for this loop's iterator, pushed here rather than left to `loop_body`,
        // because the environment below sits **inside** it and the two have to be in that order.
        // `unwind_across` stops at the first entry a jump does not cross, and a `continue`
        // deliberately does not close the iterator — so with the iterator on top, a `continue`
        // would stop there and never reach the environment it is certainly leaving.
        let closes = self.unwinds.len();
        self.unwinds.push(Unwind {
            outer: self.breaks.len(),
            what: Crossing::Iterator(iterator, Closing::Sync),
        });
        let opened = lexical.then(|| self.enter_iteration_environment());
        let binding = self.for_in_binding(&statement.left, span)?;
        let deep = u32::from(lexical);
        self.assign_enumerated(&statement.left, binding, current, deep, span)?;
        let body = self.loop_body(&statement.body, None, |compiler| {
            // Falling off the end of the pass leaves its environment, exactly as `break` and
            // `continue` do — those emit their own on the way past, which is what recording it as
            // an iteration environment arranges.
            if lexical {
                compiler.chunk.emit(Instruction::PopScope);
            }
            compiler.chunk.emit(Instruction::Jump(top));
            Ok(top)
        });
        if let Some(opened) = opened {
            self.leave_environment_already_popped(opened)?;
        }
        self.unwinds.truncate(closes);
        body?;
        // Every `break` arrives here having already taken the handler down and closed for itself,
        // so this is the *done* path's business alone.
        let past = self.chunk.emit_jump(Instruction::Jump);

        // An iterator that has said it is done needs no closing — §7.4.5 is explicit that a done
        // iterator is already finished with, and this is where both ways out arrive.
        self.chunk.patch(out)?;
        self.chunk.emit(Instruction::PopHandler);
        let leaving = self.chunk.emit_jump(Instruction::Jump);
        self.chunk.patch(unwind)?;
        let thrown = self.declare_hidden("thrown");
        self.chunk.emit(Instruction::StoreVariable(0, thrown));
        self.chunk.emit(Instruction::Pop);
        // Only when a value had been handed over — see where `closable` is set.
        self.chunk.emit(Instruction::LoadVariable(0, closable));
        let unclosable = self.chunk.emit_jump(Instruction::JumpIfFalse);
        self.emit_close(iterator, Check::Unwind, Closing::Sync)?;
        self.chunk.patch(unclosable)?;
        self.chunk.emit(Instruction::LoadVariable(0, thrown));
        self.chunk.emit(Instruction::Throw);
        self.chunk.patch(past)?;
        self.chunk.patch(leaving)
    }

    /// §7.4.9 `IteratorClose` — tell an iterator the loop is leaving early.
    ///
    /// Emitted before every jump that leaves a `for`-`of` from inside it: a `break`, a labelled
    /// one crossing this loop, and a `return`. Not before a `continue`, which stays in the loop
    /// and has nothing to tell it.
    ///
    /// An iterator with no `return` is simply left; one that has it gets it called and the answer
    /// checked. §7.4.9 step 6 makes a non-object answer a **TypeError**, which is the one way
    /// closing an iterator can fail for a reason of its own.
    pub(super) fn emit_close(
        &mut self,
        iterator: u32,
        check: Check,
        closing: Closing,
    ) -> Result<(), CompileError> {
        // A deliberate exit is leaving the loop, so its handler comes down *first*. Left armed,
        // it would catch a `return` method that threw and close the same iterator a second time —
        // which is one call too many and is observable.
        if check == Check::Loop {
            self.chunk.emit(Instruction::PopHandler);
        }
        // §7.4.9 step 4 and §7.4.11 step 4 — on the way out of a *throw* the original completion
        // wins, so every failure of the close is discarded: the `return` method throwing when it is
        // called, the getter step 2 reads it with, and the rejection the `Await` below raises. A
        // handler around the whole close is the only way to say that, because by then the throw is
        // a value travelling and not a flag to consult.
        //
        // For a **synchronous** close as well as an awaited one, and it was only the awaited one.
        // The comment here already said "every failure", and the condition said `Awaited`; what
        // that cost is `[o.x] = iterable` where `o.x`'s setter throws and the iterator's `return`
        // throws too — the program sees the `return`'s error and §7.4.9 says it sees the setter's.
        let swallow =
            (check == Check::Unwind).then(|| self.chunk.emit_jump(Instruction::PushHandler));

        self.chunk.emit(Instruction::LoadVariable(0, iterator));
        self.chunk.emit(Instruction::Duplicate);
        let name = self.name_of("return");
        self.constant(Value::String(name))?;
        self.chunk.emit(Instruction::GetProperty);
        self.chunk.emit(Instruction::Duplicate);
        // `undefined` and `null` are both falsy and both mean "there is nothing to call", which
        // is exactly the pair step 4 tests for.
        let absent = self.chunk.emit_jump(Instruction::JumpIfFalse);
        self.chunk.emit(Instruction::CallMethod(0));
        // §7.4.11 step 3.d — an async iterator answers with a promise, and the loop may not leave
        // until it settles. Before the check below, because what has to be an object is what the
        // promise *settled with* and not the promise.

        if closing == Closing::Awaited {
            self.chunk.emit(Instruction::Await);
        }
        // §7.4.9 step 5 answers a throw completion *before* it looks at what `return` gave back,
        // so on the way out of a throw the answer is not examined at all. Only a deliberate exit
        // checks it.
        if check != Check::Unwind {
            self.chunk.emit(Instruction::RequireObject);
        }
        self.chunk.emit(Instruction::Pop);
        let done = self.chunk.emit_jump(Instruction::Jump);
        self.chunk.patch(absent)?;
        // The receiver and the absent method are still there; neither is wanted.
        self.chunk.emit(Instruction::Pop);
        self.chunk.emit(Instruction::Pop);
        self.chunk.patch(done)?;
        let Some(swallow) = swallow else {
            return Ok(());
        };
        self.chunk.emit(Instruction::PopHandler);
        let past = self.chunk.emit_jump(Instruction::Jump);
        self.chunk.patch(swallow)?;
        self.chunk.emit(Instruction::Pop);
        self.chunk.patch(past)
    }

    /// The interned name of a property this compiler emits for itself.
    pub(super) fn name_of(&mut self, name: &str) -> crate::heap::StringId {
        self.heap.intern(&name.encode_utf16().collect::<Vec<_>>())
    }

    /// Make the head's binding, if the head declares one, and answer where it lives.
    pub(super) fn for_in_binding(
        &mut self,
        target: &ForInOfTarget,
        span: Span,
    ) -> Result<Option<u32>, CompileError> {
        let ForInOfTarget::Declaration(declaration) = target else {
            return Ok(None);
        };
        let Some(declarator) = declaration.declarators.first() else {
            // `ForBinding` is singular and the parser produces exactly one, so this is a tree
            // nobody can write.
            return Err(unsupported("a `for`-`in` head with no binding", span));
        };
        if !declaration.kind.is_lexical() {
            // A `var` in the head is *not* the loop's. §14.7.5.5 gives it no per-iteration
            // binding and no scope of its own: it was hoisted with the rest of the body's, it
            // outlives the loop, and at the top level of a script it is a property of the global
            // object rather than a slot at all. So nothing is declared here and the assignment
            // goes by name, which is the one path that knows all of that.
            return Ok(None);
        }
        // §8.2.1 `BoundNames` — a pattern in the head declares every name inside it, and each
        // starts in the dead zone exactly as a single name does.
        let immutable = declaration.kind == DeclarationKind::Const;
        let mut first = None;
        for name in crate::static_semantics::bound_names(&declarator.binding) {
            let slot = self.declare_lexical(name.name, super::lexical_mutability(immutable));
            self.chunk.emit(Instruction::Uninitialise(slot));
            first.get_or_insert(slot);
        }
        let slot = first.unwrap_or_default();
        Ok(Some(slot))
    }

    /// The rest of `for`, once its scope has been opened.
    fn for_init(&mut self, statement: &ForStatement, span: Span) -> Result<(), CompileError> {
        match &statement.init {
            Some(ForInit::Expression(expression)) => {
                self.expression(expression)?;
                self.chunk.emit(Instruction::Pop);
            }
            Some(ForInit::Declaration(declaration)) => self.declaration(declaration, span)?,
            None => {}
        }
        Ok(())
    }

    /// The rest of `for`, once its head has run — §14.7.4.7 `ForBodyEvaluation`.
    fn for_parts(
        &mut self,
        statement: &ForStatement,
        mut per_iteration: Option<&mut Environment>,
    ) -> Result<(), CompileError> {
        // §14.7.4.7 step 2 — before the first test, so the initialiser's own environment is never
        // the one the body runs in. Without it the first pass shares its bindings with the
        // initialiser and every later pass does not, which is a difference no reader would expect
        // and only a closure made on the first pass can see.
        if let Some(environment) = per_iteration.as_mut() {
            self.copy_environment(environment);
        }
        let top = self.here()?;
        // A missing test is `true` — `for (;;)` — so there is simply no jump out of the top.
        let out = match &statement.test {
            Some(test) => {
                self.expression(test)?;
                Some(self.chunk.emit_jump(Instruction::JumpIfFalse))
            }
            None => None,
        };
        let update = statement.update.as_ref();
        self.loop_body(&statement.body, None, |compiler| {
            // `continue` goes to the *update*, not to the test: `for (i = 0; i < 3; i = i + 1) {
            // continue; }` still increments, which is the whole reason the third part exists.
            let target = compiler.here()?;
            // §14.7.4.7 step 3.d — **before** the update and at the `continue` target, because a
            // `continue` reaches step 3.d too. The update then runs against the next pass's copy,
            // so `i++` carries the count forward while the closure the last pass made keeps its
            // own `i`.
            if let Some(environment) = per_iteration.as_mut() {
                compiler.copy_environment(environment);
            }
            if let Some(update) = update {
                compiler.expression(update)?;
                compiler.chunk.emit(Instruction::Pop);
            }
            compiler.chunk.emit(Instruction::Jump(top));
            Ok(target)
        })?;
        match out {
            Some(out) => self.chunk.patch(out),
            None => Ok(()),
        }
    }
    /// Emit everything between here and the statement being left.
    ///
    /// The one place a `break`, a `continue` and a `return` agree: each leaves some run of
    /// enclosing statements, and each of those may have a `finally` to run (§14.15.3), an iterator
    /// to close (§7.4.9) or a handler to take down. They come off innermost first, which is what
    /// makes a throw inside a `finally` escape the `try` that owns it rather than being caught by
    /// its own `catch` — the handlers go down before the block that might throw runs.
    ///
    /// [`Exit`] says which jump this is and what it leaves — one argument rather than an index and
    /// a flag, because those two together can spell a `return` that leaves only *some* of them,
    /// which is not a thing that exists. A mutant that flipped that flag survived every test there
    /// was, for the good reason that nothing it changed was ever read.
    pub(super) fn unwind_across(&mut self, exit: Exit) -> Result<(), CompileError> {
        let stack = std::mem::take(&mut self.unwinds);
        let mut outcome = Ok(());
        // The compiler's own idea of which scopes are open has to follow the code being emitted,
        // because one of these crossings *compiles statements*: a `finally` is emitted again at
        // every exit that leaves it, and it is written outside the scopes this walk has just been
        // popping. Left as it was, a `break` out of a block inside a `try`/`finally` emitted the
        // `PopScope` and then resolved the finally's own names one hop too deep — reaching the
        // interpreter as `Fault::MissingLocal`, from ordinary source.
        //
        // Saved whole and put back at the end rather than unwound step by step, because the walk
        // may stop early and the caller is still standing exactly where it was.
        let held_locals = self.locals.clone();
        let held_outer = self.outer.clone();
        let held_marks = self.scope_marks.clone();
        let held_this = self.this_binding;
        for at in (0..stack.len()).rev() {
            let entry = &stack[at];
            let iterator = matches!(entry.what, Crossing::Iterator(..));
            let operand = matches!(entry.what, Crossing::Operand);
            let crossed = match exit {
                // A `return` leaves everything — except an *operand*. The value being returned is
                // already on the stack above it, so a `Pop` here would discard that instead; and
                // the frame's whole stack goes when the call returns, so what is left under it was
                // never a leak. The two other jumps stay inside the frame and do have to tidy.
                Exit::Return => !operand,
                // An iterator belongs to its own loop rather than sitting inside it, which is the
                // one place the two jumps differ: a `break` closes the target loop's own iterator
                // and a `continue` does not, while a `finally` at that same depth was written in
                // the body and runs for either.
                Exit::Break(depth) => entry.outer > depth || (iterator && entry.outer == depth),
                Exit::Continue(depth) => entry.outer > depth,
            };
            if !crossed {
                break;
            }
            // While this entry is being emitted, it and everything above it is already dealt with.
            // Without that, a `return` written inside a `finally` would emit the same `finally`
            // again, and again, for as long as the compiler had memory.
            self.unwinds = stack[..at].to_vec();
            outcome = match &stack[at].what {
                Crossing::Handlers(count) => {
                    for _ in 0..*count {
                        self.chunk.emit(Instruction::PopHandler);
                    }
                    Ok(())
                }
                Crossing::Operand => {
                    self.chunk.emit(Instruction::Pop);
                    Ok(())
                }
                // The instruction leaves the scope at run time, and the two lines under it leave
                // it for the *compiler* too — so that a `finally` emitted after this one resolves
                // its own names against the scope it was written in rather than one hop too deep.
                Crossing::Scope => {
                    self.chunk.emit(Instruction::PopScope);
                    if let Some(held) = self.outer.pop() {
                        self.locals = held;
                        self.scope_marks.pop();
                        if let Some(slot) = &mut self.this_binding {
                            slot.depth = slot.depth.saturating_sub(1);
                        }
                    }
                    Ok(())
                }
                Crossing::Finally(body) => self.block(body),
                Crossing::Iterator(slot, closing) => self.emit_close(*slot, Check::Loop, *closing),
            };
            if outcome.is_err() {
                break;
            }
        }
        self.unwinds = stack;
        self.locals = held_locals;
        self.outer = held_outer;
        self.scope_marks = held_marks;
        self.this_binding = held_this;
        outcome
    }
    /// Compile a loop body with somewhere for `break` and `continue` to go.
    ///
    /// `after` compiles whatever follows the body — the jump back, and a `for` loop's update —
    /// and answers where `continue` should land, which is not the same place in all three loops.
    /// Every `break` collected while the body was compiled is patched to just past everything.
    pub(super) fn loop_body(
        &mut self,
        body: &Stmt,
        iterator: Option<(u32, Closing)>,
        after: impl FnOnce(&mut Self) -> Result<u32, CompileError>,
    ) -> Result<(), CompileError> {
        self.breaks.push(Vec::new());
        self.continues.push(Some(Vec::new()));
        // §7.4.9 — the iterator this loop drives, if it drives one, recorded against this loop's
        // own index rather than against its body: a `continue` of *this* loop does not close it,
        // which is the one place an iterator differs from everything else on the stack. Taken as an
        // argument rather than pushed by the caller beforehand: the caller would have to know not to
        // push twice, and *that* was a branch nothing could pin.
        let mark = self.unwinds.len();
        if let Some((slot, closing)) = iterator {
            self.unwinds.push(Unwind {
                outer: self.breaks.len() - 1,
                what: Crossing::Iterator(slot, closing),
            });
        }
        let compiled = self.statement(body).and_then(|()| after(self));
        // The stacks come back down even when compilation failed, so that a later loop does
        // not inherit this one's pending jumps and patch them into its own end.
        let continues = self.continues.pop().flatten().unwrap_or_default();
        let breaks = self.breaks.pop().unwrap_or_default();
        self.unwinds.truncate(mark);
        let continue_target = compiled?;
        for jump in continues {
            self.chunk.patch_to(jump, continue_target);
        }
        for jump in breaks {
            self.chunk.patch(jump)?;
        }
        Ok(())
    }
    /// §14.12 — `switch`.
    ///
    /// # Why the tests come first and the bodies afterwards
    ///
    /// Because a `switch` is not a chain of `if`s. §14.12.4 evaluates the case tests **in order**
    /// until one is strictly equal to the discriminant, and *then* runs every statement from that
    /// case to the end of the switch — through the other cases, not into them. Fall-through is
    /// not a quirk of the syntax; it is what the algorithm says, and compiling the bodies as one
    /// run of statements with entry points into it is the shape that makes it true for free.
    ///
    /// `default` is not tried in that first pass. §14.12.4 runs the tests, and only if none
    /// matched does it come back to the default — so `switch (x) { default: a; case 1: b; }` with
    /// `x` of 1 runs `b` alone, and with `x` of 2 runs `a` and then `b`.
    fn switch_statement(&mut self, statement: &SwitchStatement) -> Result<(), CompileError> {
        self.expression(&statement.discriminant)?;
        // §14.12.4 — the `CaseBlock` is *one* scope over all of the cases, not one per case. So a
        // `let` in one case is in scope in the next, and its dead zone runs from the top of the
        // whole block: `switch (x) { case 1: y; break; case 2: let y; }` throws rather than
        // reading `undefined`. That is why the bindings are created here, before any test runs.
        //
        // And *one environment* over all of them, for the same reason — §14.12.4 step 3's
        // `NewDeclarativeEnvironment` around the whole `CaseBlock`. Entered **before** the switch's
        // own break list is pushed, which is what decides whether a `break` pops it: `unwind_across`
        // crosses a scope entry only when its `outer` is *greater* than the exit's depth, so an
        // entry recorded at the switch's own depth is left to the one `PopScope` below — where
        // falling off the last case, a `break`, and no case matching at all all converge. A
        // `continue` out to an enclosing loop has a smaller depth and does cross it, which is right.
        let lexical = statement
            .cases
            .iter()
            .any(|case| Self::declares_something_lexical(&case.body));
        let opened = lexical.then(|| self.enter_environment());
        // The discriminant stays on the stack for the whole `CaseBlock`, so a jump that leaves the
        // switch without landing on the convergence below has to drop it. Recorded at the same
        // depth as the environment and for the same reason: a `break` lands where it is popped
        // anyway, and a `continue` or a `return` jumps clean past — which left the value on the
        // stack and faulted the *next* pass of the enclosing loop with `UnbalancedStack`.
        let unwinds = self.unwinds.len();
        self.unwinds.push(Unwind {
            outer: self.breaks.len(),
            what: Crossing::Operand,
        });
        let mark = self.enter_scope();
        for case in statement.cases.iter() {
            self.declare_lexical_names(&case.body)?;
        }
        // §14.12.4 step 3 hands the whole `CaseBlock` to `BlockDeclarationInstantiation`, which
        // §14.2.3 step 3.a.ii **initialises** every function declaration in it — so
        // `switch (x) { case 1: function f() {} }` binds `f` for the whole block, and a case above
        // the declaration can call it. Left out until now, and the cost was not a refusal but a
        // wrong answer: the environment was opened, no slot was ever made for the name, and the
        // statement itself did nothing because hoisting was supposed to have.
        //
        // A second loop rather than a line in the one above, because §14.2.3 does both passes over
        // the whole list: `switch (x) { case 1: let a; case 2: function f() { return a; } }` needs
        // every `let` in the dead zone before any function is made.
        for case in statement.cases.iter() {
            self.hoist_functions(&case.body)?;
        }
        // A `break` inside a switch leaves the switch, so it is a breakable statement like a
        // loop — but not a *continuable* one. Both stacks are pushed all the same, with `None` for
        // the second: an exit's depth is one number indexing both, so a switch that pushed only one
        // of them would make that number mean something different on either side of itself.
        self.breaks.push(Vec::new());
        self.continues.push(None);

        // The tests, in order, each jumping to where its body begins.
        let mut entries = Vec::new();
        let mut to_default = None;
        for case in statement.cases.iter() {
            let Some(test) = &case.test else {
                to_default = Some(entries.len());
                entries.push(None);
                continue;
            };
            // The discriminant is compared once per test and has to survive each comparison.
            self.chunk.emit(Instruction::Duplicate);
            self.expression(test)?;
            self.chunk
                .emit(Instruction::Binary(BinaryOperator::StrictEqual));
            entries.push(Some(self.chunk.emit_jump(Instruction::JumpIfTrue)));
        }
        // Nothing matched: to the default if there is one, past everything if there is not.
        let fallback = self.chunk.emit_jump(Instruction::Jump);

        // The bodies, as one run of statements with an entry point at each case.
        let mut starts = Vec::new();
        for case in statement.cases.iter() {
            starts.push(self.here()?);
            self.statements(&case.body)?;
        }
        let after = self.here()?;
        // Every way out of the case bodies arrives here, so this is where the case block's
        // environment is left — once, on a path all three of them share.
        self.leave_scope(mark);
        self.unwinds.truncate(unwinds);
        if let Some(opened) = opened {
            self.leave_environment(opened)?;
        }
        for (entry, start) in entries.into_iter().zip(&starts) {
            if let Some(entry) = entry {
                self.chunk.patch_to(entry, *start);
            }
        }
        match to_default.and_then(|at| starts.get(at)) {
            Some(start) => self.chunk.patch_to(fallback, *start),
            // Aimed at `after` by name rather than at wherever the compiler has got to, because
            // the `PopScope` above now sits between the two and a no-match path must run it.
            None => self.chunk.patch_to(fallback, after),
        }

        // The discriminant is still under everything, and a `break` jumps here — so it is
        // discarded after the breaks land rather than before, or a break would leave it behind.
        let breaks = self.breaks.pop().unwrap_or_default();
        self.continues.pop();
        for jump in breaks {
            self.chunk.patch_to(jump, after);
        }
        self.chunk.emit(Instruction::Pop);
        Ok(())
    }

    /// §14.13 — a labelled statement.
    ///
    /// A label is a name attached to the statement that follows, and what it is *for* is being
    /// aimed at: `break outer` leaves the statement the label is on, and `continue outer` goes
    /// round it again. So the label is remembered for as long as that statement is being
    /// compiled, and a `break` that names it patches into the same list the statement's own
    /// breaks do.
    fn labelled_statement(&mut self, statement: &LabelledStatement) -> Result<(), CompileError> {
        // §14.13.1 — a label may not be nested inside one of the same name. The parser refuses
        // that, so this is not a duplicate check; it is what makes the innermost match the right
        // one when the names differ.
        let breakable = matches!(
            statement.body.kind,
            StmtKind::While(_) | StmtKind::DoWhile(_) | StmtKind::For(_) | StmtKind::ForInOf(_)
        );
        self.labels
            .push((statement.label.name.clone(), self.breaks.len()));
        if breakable {
            let compiled = self.statement(&statement.body);
            self.labels.pop();
            return compiled;
        }
        // §14.13.4 — a label on anything else is a break target and nothing more: `outer: { break
        // outer; }` leaves the block, and there is no loop under it for the jump to land in. So the
        // statement gets a break list of its own, exactly as a `switch` does, and the jumps patch to
        // the end of it. `continue outer` is a Syntax Error the parser has already refused, which is
        // why there is no continue list to go with it.
        self.breaks.push(Vec::new());
        let compiled = self.statement(&statement.body);
        let breaks = self.breaks.pop().unwrap_or_default();
        self.labels.pop();
        compiled?;
        let after = self.here()?;
        for jump in breaks {
            self.chunk.patch_to(jump, after);
        }
        Ok(())
    }

    /// `break name` or `continue name` — §14.9 and §14.8 with a label.
    ///
    /// The label names a *statement*, and the jump goes to that statement's end or its next turn
    /// — so the only thing that differs from an unlabelled one is which list the jump joins.
    fn leave_labelled(
        &mut self,
        name: &str,
        leaving: bool,
        span: Span,
    ) -> Result<(), CompileError> {
        let Some((_, depth)) = self.labels.iter().rev().find(|(label, _)| &**label == name) else {
            // The parser refuses a label that is not in scope, so this is unreachable from
            // source — and refusing rather than guessing keeps it that way.
            return Err(unsupported("a break or continue to an unknown label", span));
        };
        let depth = *depth;
        // A labelled jump may cross several statements at once, and each gets what it is owed on
        // the way past — which is the whole of what is special about it. An ordinary break leaves
        // one statement; this one leaves as many as the label is above.
        self.unwind_across(Exit::of(leaving, depth))?;
        // No "is there a list" check, because there always is: [`Compiler::labelled_statement`]
        // records a label only for a loop, and a loop pushes both lists before its body is
        // compiled. Written with a guard, that guard was a branch nothing could take.
        let jump = self.chunk.emit_jump(Instruction::Jump);
        let pending = if leaving {
            self.breaks.get_mut(depth)
        } else {
            self.continues.get_mut(depth).and_then(Option::as_mut)
        };
        if let Some(pending) = pending {
            pending.push(jump);
        }
        Ok(())
    }

    /// `break` or `continue` — a jump whose target is not compiled yet.
    ///
    /// The parser refuses either outside a loop, so an empty stack here is unreachable from
    /// source; refusing rather than emitting a jump to nowhere is what keeps it unreachable.
    fn leave_loop(&mut self, leaving: bool, span: Span) -> Result<(), CompileError> {
        // The target's depth, in the one scale everything else is measured in. A `break` leaves the
        // innermost breakable statement whatever it is; a `continue` leaves the innermost
        // *continuable* one, which is not the same thing the moment a switch is in between — and
        // taking the innermost breakable for both is what unwound a `continue` to the switch's
        // depth and left its discriminant behind.
        let depth = match leaving {
            true => self.breaks.len().checked_sub(1),
            false => self.continues.iter().rposition(Option::is_some),
        };
        let Some(depth) = depth else {
            return Err(unsupported("break or continue outside a loop", span));
        };
        // Everything between here and it is crossed: a `finally` in between runs, an iterator in
        // between is closed, a handler in between comes down, a scope in between is left.
        self.unwind_across(Exit::of(leaving, depth))?;
        let jump = self.chunk.emit_jump(Instruction::Jump);
        let pending = match leaving {
            true => self.breaks.get_mut(depth),
            false => self.continues.get_mut(depth).and_then(Option::as_mut),
        };
        if let Some(pending) = pending {
            pending.push(jump);
        }
        Ok(())
    }
    /// §14.15 — `try`, with or without each of its two tails.
    ///
    /// # Why the `finally` block is compiled twice
    ///
    /// It has to run on the way out however the `try` was left, and there are two ways: normally,
    /// and carrying a thrown value. The alternative to two copies is a subroutine that both paths
    /// call and that returns to a variable address — the shape that gave the JVM `jsr`/`ret` and
    /// then a decade of verifier bugs. Two copies of a block are larger and are obviously right.
    ///
    /// # The shape
    ///
    /// ```text
    ///   PushHandler(UNWIND)    ; only when there is a finally
    ///   PushHandler(CATCH)     ; only when there is a catch
    ///   <the try block>
    ///   PopHandler             ; the inner one
    ///   Jump(AFTER)
    /// CATCH:                   ; the thrown value is on the stack
    ///   StoreLocal(parameter); Pop
    ///   <the catch block>
    /// AFTER:
    ///   PopHandler             ; the outer one
    ///   <the finally block>
    ///   Jump(END)
    /// UNWIND:                  ; the thrown value is on the stack
    ///   StoreLocal(saved); Pop
    ///   <the finally block>
    ///   LoadLocal(saved)
    ///   Throw                  ; on to the next handler out
    /// END:
    /// ```
    ///
    /// The outer handler is what makes a throw *inside the catch block* still run the finally,
    /// which is the case a single handler gets wrong.
    fn try_statement(&mut self, statement: &TryStatement, span: Span) -> Result<(), CompileError> {
        let has_finally = statement.finalizer.is_some();
        let outer = self.breaks.len();
        let mark = self.unwinds.len();
        // §14.15.3 — the `finally` goes on first, so that a jump out of here meets it *after* the
        // handlers. A throw inside a `finally` is not caught by the `try` the `finally` belongs to,
        // and taking the handlers down before running the block is what makes that true.
        if let Some(finalizer) = &statement.finalizer {
            self.unwinds.push(Unwind {
                outer,
                what: Crossing::Finally(Rc::from(&**finalizer)),
            });
        }
        let unwind = has_finally.then(|| self.chunk.emit_jump(Instruction::PushHandler));
        let to_catch = statement
            .handler
            .as_ref()
            .map(|_| self.chunk.emit_jump(Instruction::PushHandler));
        // Both of them are armed over the try block, and a `break` out of it has to take down
        // exactly the ones it jumps past — a count rather than a flag, because the catch block
        // below is inside one of these two and not the other.
        let armed = u32::from(unwind.is_some()) + u32::from(to_catch.is_some());
        self.unwinds.push(Unwind {
            outer,
            what: Crossing::Handlers(armed),
        });

        let compiled = self.try_body(statement, to_catch);
        // Down before the `finally` is emitted below: the block belongs to whatever encloses this
        // `try` rather than to the `try`, so a `break` inside it does not run it a second time.
        self.unwinds.truncate(mark);
        compiled?;

        if let Some(unwind) = unwind {
            // The normal way out: forget the handler, then run the finally.
            self.chunk.emit(Instruction::PopHandler);
            if let Some(finalizer) = &statement.finalizer {
                self.block(finalizer)?;
            }
            let end = self.chunk.emit_jump(Instruction::Jump);
            // …and the other way out, carrying whatever was thrown. The value is parked in a
            // slot no source text can name, because the finally block may use the stack.
            self.chunk.patch(unwind)?;
            let saved = self.declare_hidden("thrown");
            self.chunk.emit(Instruction::StoreVariable(0, saved));
            self.chunk.emit(Instruction::Pop);
            if let Some(finalizer) = &statement.finalizer {
                self.block(finalizer)?;
            }
            self.chunk.emit(Instruction::LoadVariable(0, saved));
            self.chunk.emit(Instruction::Throw);
            self.chunk.patch(end)?;
        }
        let _ = span;
        Ok(())
    }
    /// The try block and its catch clause, up to the point where the finally would begin.
    fn try_body(
        &mut self,
        statement: &TryStatement,
        to_catch: Option<Unpatched>,
    ) -> Result<(), CompileError> {
        self.block(&statement.block)?;
        let Some(to_catch) = to_catch else {
            // No catch clause, so the try block's protection ends here and a throw inside it has
            // already gone to the finally's handler.
            return Ok(());
        };
        // The try block finished without throwing, so its handler is no longer wanted and the
        // catch block must be jumped over.
        self.chunk.emit(Instruction::PopHandler);
        let past_the_catch = self.chunk.emit_jump(Instruction::Jump);
        self.chunk.patch(to_catch)?;
        // From here on one fewer handler is armed: getting to a catch block means the throw found
        // this handler, and a handler that fires is taken off the stack by the throw that found it.
        // So a `break` out of the *catch* block owes one less than one out of the try block.
        if let Some(entry) = self.unwinds.last_mut()
            && let Crossing::Handlers(armed) = &mut entry.what
        {
            *armed = u32::from(statement.finalizer.is_some());
        }

        let Some(handler) = &statement.handler else {
            // Unreachable: `to_catch` exists only when the handler does. Saying so with a jump
            // that lands here rather than an assertion keeps this total.
            return self.chunk.patch(past_the_catch);
        };
        // §14.15.3 — the catch parameter is a *block-scoped* binding of its own, so it is given a
        // slot for the duration of the catch block and taken away again. `catch { }` with no
        // parameter is ES2019's optional binding: the value is simply discarded.
        //
        // §14.15.3 gives it an environment of its own, and **only** when there is a parameter:
        // `catch { }` evaluates its block in the scope around it, where `catch (e) { }` does not.
        // Without one the parameter was a slot in the level around it, kept out of sight by a
        // liveness flag only the compiler can read — which is invisible to compiled code and not
        // to a direct `eval`. DR-0018 is the long version.
        let opened = handler
            .parameter
            .is_some()
            .then(|| self.enter_environment());
        let outer_locals = self.enter_scope();
        match &handler.parameter {
            Some(parameter) => {
                // §14.15.3 makes every name in the parameter a binding of the catch block, so a
                // pattern declares all of them and then takes the thrown value apart. Declared
                // with `declare_shadowing` for the same reason a name is: the catch's binding is
                // its own, and an outer one of the same name is hidden rather than written to.
                for name in crate::static_semantics::bound_names(&parameter.binding) {
                    self.declare_shadowing(name.name);
                }
                self.destructure_catch(&parameter.binding, handler.span)?;
            }
            None => self.chunk.emit(Instruction::Pop),
        }
        self.block(&handler.body)?;
        self.leave_scope(outer_locals);
        // Left before a `finally` around it can run: a jump out takes the environment down on the
        // way past, and `unwind_across` walks from the top — so the `PopScope` is emitted ahead of
        // the `finally`'s statements, which are compiled against the scope outside the catch.
        if let Some(opened) = opened {
            self.leave_environment(opened)?;
        }
        self.chunk.patch(past_the_catch)
    }
    /// §B.3.3 step 3 — the block's binding, written into the variable scope's.
    ///
    /// > When the FunctionDeclaration f is evaluated, perform the following steps in place of the
    /// > FunctionDeclaration Evaluation algorithm: … Let fobj be `benv.GetBindingValue(F, false)`.
    /// > Perform `fenv.SetMutableBinding(F, fobj, false)`.
    ///
    /// `benv` is the running **Lexical**Environment and `fenv` the **Variable**Environment, and
    /// those are two different scopes with the same name in them — which is the whole of why the
    /// read resolves the name and the write does not. Resolving `F` for the write would find the
    /// block's own binding, the innermost one, and store the value back where it already was.
    ///
    /// A declaration the extension does not reach — every one at a variable scope's own top level,
    /// and every one a `let` or a parameter shadowed — is not in the list and does nothing here.
    fn copy_block_function(
        &mut self,
        function: &crate::ast::Function,
        span: Span,
    ) -> Result<(), CompileError> {
        let Some(&(_, target)) = self
            .block_functions
            .iter()
            .find(|(declared, _)| *declared == span)
        else {
            return Ok(());
        };
        let Some(name) = &function.name else {
            // A declaration in this list has a name — `block_functions` took it from one. An
            // anonymous one is `export default function () {}`, which is a module's and so is
            // never here at all, module code being strict.
            return Err(unsupported("an anonymous block-level function", span));
        };
        let Some(binding) = self.binding(&name.name) else {
            // `hoist_functions` gave the block a slot for this name before its first statement, so
            // this is a compiler that has lost its own binding rather than anything a source did.
            return Err(unsupported("a block-level function with no binding", span));
        };
        self.load(binding);
        match target {
            super::BlockFunctionTarget::Global(index) => {
                self.chunk.emit(Instruction::StoreGlobal(index));
            }
            // Out to the variable scope, however many blocks, `with`s and loop passes are in
            // between — every one of them is an environment, and `own_depth` counts exactly those.
            super::BlockFunctionTarget::Slot(slot) => {
                let depth = self.own_depth();
                self.chunk.emit(Instruction::StoreVariable(depth, slot));
            }
        }
        self.chunk.emit(Instruction::Pop);
        Ok(())
    }

    /// §14.11 — `with (o) stmt`, the one scope whose names are an object's properties.
    ///
    /// §11.2.1 makes this a Syntax Error in strict code and the parser has already refused it
    /// there, so anything arriving here is sloppy. What it costs is in
    /// [`Compiler::names_are_dynamic`]: every identifier in the body, and in every function written
    /// inside it, becomes a walk of the running scopes rather than a slot the compiler chose.
    pub(super) fn with_statement(
        &mut self,
        statement: &crate::ast::WithStatement,
    ) -> Result<(), CompileError> {
        // §14.11.2 step 1 — the object is evaluated in the scope *outside*, which is why this is
        // before the scope is opened and not after it.
        self.expression(&statement.object)?;
        let opened = self.enter_with_environment();
        let mark = self.enter_scope();
        let compiled = self.statement(&statement.body);
        self.leave_scope(mark);
        // Left even when the body was refused, so that a later statement is compiled against the
        // scope it is actually in — the same reason every other scope is closed on the failing path.
        self.leave_with_environment(opened)?;
        compiled
    }

    /// Make the function objects a list's declarations describe, before any of it runs.
    ///
    /// §10.2.11's `FunctionDeclarationInstantiation` and §14.2.3's `BlockDeclarationInstantiation`,
    /// in the part that separates a function declaration from every other kind. A `var` is
    /// *declared* early and assigned where it is written; a function is **initialised** early,
    /// which is why `f()` above `function f() {}` works and `g()` above `var g = function () {}`
    /// does not.
    ///
    /// Only the direct items of `body`, which is what both operations say: a declaration inside a
    /// nested block belongs to that block, and is made when it is entered. Where the binding goes
    /// is the caller's scope — a slot at a body's top level and in a block, a property of the
    /// global object at the top level of a script.
    pub(super) fn hoist_functions(&mut self, body: &[Stmt]) -> Result<(), CompileError> {
        // **Every binding before any body**, which is two passes and not one. §10.2.11 creates the
        // bindings for `functionsToInitialize` and only then instantiates the function objects, and
        // the difference is observable in the ordinary way sibling declarations are written:
        //
        //     function a() { return b(); }
        //     function b() { return 7; }
        //
        // Declared as it went, `a`'s body was compiled while `b` had no slot — so `b` resolved
        // outwards, found nothing, and became a global lookup that fails at run time. Reversing the
        // two declarations made it work, which is not something the order of two hoisted
        // declarations is allowed to decide.
        let mut placed: Vec<(Placement, &crate::ast::Function, Span)> = Vec::new();
        for statement in body {
            // Through any labels, because §B.3.2 lets one stand between the list and its
            // declaration and §8.2.6 declares the name here all the same — see
            // [`super::annex_b::declared_function`]. Without it `{ L: function f() {} }` parsed,
            // hoisted nothing, and left the block's own binding unmade.
            let Some((function, span)) = super::annex_b::declared_function(statement) else {
                continue;
            };
            let Some(name) = &function.name else {
                // A declaration without a name is `export default function () {}`, which is a
                // module thing and has no name to hoist under.
                return Err(unsupported("an anonymous function declaration", span));
            };
            // Remembered so the statement itself knows it was hoisted. Recorded under the
            // declaration's own span rather than the statement's, which differ when a label stands
            // in front of it.
            self.hoisted.push(span);
            // §9.1.1.4.16 `CreateGlobalFunctionBinding` at the top level of a script, and an
            // ordinary slot everywhere else. The declaration comes first so the property exists
            // with a script's attributes — writable, enumerable, not configurable — and the store
            // then puts the function in it. Assigning to a name that does not exist yet would
            // create it *configurable*, and `delete f` would then work on a function declaration.
            let placement = match self.at_global_scope() {
                true => {
                    let index = self.name(&name.name)?;
                    let deletable = self.deletable;
                    self.chunk.emit(Instruction::DeclareGlobal {
                        name: index,
                        deletable,
                    });
                    Placement::Global(index)
                }
                false => Placement::Slot(self.declare(&name.name)),
            };
            placed.push((placement, function, span));
        }
        for (placement, function, span) in placed {
            self.make_function(
                function,
                // §10.2.9 — a declaration is named by its own binding.
                match &function.name {
                    Some(written) => super::function::Naming::of(&written.name),
                    None => super::function::Naming::default(),
                },
                span,
            )?;
            match placement {
                Placement::Global(index) => self.chunk.emit(Instruction::StoreGlobal(index)),
                Placement::Slot(slot) => self.chunk.emit(Instruction::StoreVariable(0, slot)),
            }
            self.chunk.emit(Instruction::Pop);
        }
        Ok(())
    }

    pub(super) fn statements(&mut self, statements: &[Stmt]) -> Result<(), CompileError> {
        for statement in statements {
            self.statement(statement)?;
        }
        Ok(())
    }
}

/// Where a hoisted function declaration's binding lives — §9.1.1.4.16 or an ordinary slot.
///
/// Carried between the two passes of [`Compiler::hoist_functions`] so that the second one, which
/// compiles the bodies, does not have to ask again. Asking twice would be two answers to a question
/// whose answer is fixed by where the declaration is written.
#[derive(Debug, Clone, Copy)]
enum Placement {
    /// §9.1.1.4.16 — a property of the global object, named by an index into the chunk's names.
    Global(u32),
    /// An ordinary binding in the running scope.
    Slot(u32),
}

/// Where a well-known Symbol sits in the realm's table — see `crate::builtins::well_known_at`.
pub(super) fn well_known(name: &str) -> u32 {
    u32::try_from(crate::builtins::well_known_at(name)).unwrap_or(u32::MAX)
}

/// What an `IteratorClose` has to do besides closing — §7.4.9 steps 5 and 6.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Check {
    /// Leaving a `for`-`of` deliberately: the loop's handler comes down first, and a non-object
    /// answer is a TypeError.
    Loop,
    /// Leaving one on the way out of a throw: no handler to take down, because the throw already
    /// consumed it, and step 5 has already decided what the answer is.
    Unwind,
    /// Closing an iterator a pattern is finished with, where there is no handler in the way and
    /// the answer is examined as step 6 asks.
    Plain,
}