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
//! A unit of compiled code, and the instruction set it is made of.
//!
//! Everything here is what the *interpreter* sees. The compiler's own working — how a name is
//! resolved, what it refuses — is next door; this is the surface between the two, and it is
//! deliberately small: an embedder holds a [`Chunk`], and a chunk holds instructions, constants,
//! a count of slots, and the bodies of the functions written inside it.

use crate::ast::{BinaryOperator, UnaryOperator, UpdateOperator};
use crate::compile::{CompileError, ErrorKind};
use crate::heap::Binding;
use crate::span::Span;
use crate::value::Value;
use std::rc::Rc;

/// One unit of compiled code — the instructions and the values they refer to.
///
/// Constants are held beside the code rather than inside it because a `Value` is 16 bytes and an
/// instruction should not be. It also means a String literal is put on the heap once, at compile
/// time, rather than each time the line runs.
#[derive(Debug, Default)]
pub struct Chunk {
    pub(super) code: Vec<Instruction>,
    pub(super) constants: Vec<Value>,
    pub(super) locals: usize,
    pub(super) parameters: usize,
    /// §10.2.3's `length` — the count *before* the first default or rest parameter.
    ///
    /// A second number because the two questions differ once a parameter list is not simple:
    /// `function f(a, b = 1, c)` has three slots to fill and a `length` of 1. `length` is what a
    /// caller is told to supply; `parameters` is how many places there are to put things.
    pub(super) length: usize,
    /// §10.2.9's `name`, if the compiler could tell what this function is called.
    ///
    /// The compiler and not the call, because a function has one name for its whole life and the
    /// position it was *written* in is what decides it: a declaration is named by its binding, a method
    /// by its key, and §8.6.3's `NamedEvaluation` gives an anonymous expression the name of whatever it
    /// is being assigned to. One syntactic position, one chunk, one name.
    ///
    /// `None` where §10.2.9 asks for the empty string — an anonymous function that is not in a named
    /// position — because a `None` and an interned `""` are the same thing to the only reader, and one
    /// of the two does not need a String on the heap per anonymous function in the program.
    pub(super) name: Option<crate::heap::StringId>,
    /// Whether this body is strict code — §11.2.1, as the parser computed it.
    ///
    /// Three things turn on it at run time and none of them can be decided anywhere else. §10.2.1.2
    /// step 3 does not substitute the global object for a strict function's `undefined` receiver;
    /// §6.2.5.6 step 6.d **throws** where a sloppy assignment silently does nothing; and §13.5.1.2
    /// does the same for a `delete` that was refused.
    ///
    /// On the chunk because strictness is a property of the *body*, which is what a call has to hand
    /// when it decides the receiver — and because a strict function called from sloppy code is still
    /// strict, so the caller cannot answer for it.
    pub(super) strict: bool,
    /// `IsSimpleParameterList` (§15.1.4) — whether every parameter is a plain name.
    ///
    /// Decides which arguments object §10.2.11 step 22 makes. A simple list gets the *mapped* one,
    /// where an index and its parameter are one variable; anything else gets an unmapped one,
    /// because a parameter initialised by running code is not a slot an index could stand for.
    pub(super) simple_parameters: bool,
    /// The slot a rest parameter's array goes in, if the list has one.
    ///
    /// Filled by the call rather than by the body, on the same terms as the arguments object: the
    /// arguments past the last named parameter are on the stack at entry and nowhere else.
    pub(super) rest: Option<u32>,
    /// Whether this body is an arrow's — §15.3.
    ///
    /// An arrow has no `this` of its own, no `prototype`, and no `[[Construct]]`. All three come
    /// from the same fact: §15.3 makes it a function *expression* over the scope it was written
    /// in rather than a thing you can be inside of, so `this` is whatever it was one line above.
    pub(super) arrow: bool,
    /// Whether this body is a `MethodDefinition` — §15.4.5 and §15.7.14.
    ///
    /// A method has **no `[[Construct]]`** and no `prototype`: `new o.m()` is a TypeError, and
    /// `'prototype' in o.m` is false. An arrow lacks both for a different reason (§15.3 gives it no
    /// `this` either), so the two flags are separate — a method has a `this` and is simply not
    /// constructible.
    ///
    /// A class *constructor* is not a method by this flag, whatever the grammar calls it: it is the
    /// one thing in a class body that constructs.
    pub(super) method: bool,
    /// Whether this body is a generator's — §15.5, the `*` after `function`.
    ///
    /// A generator function does not run its body when it is called: §15.5.4 binds the parameters,
    /// makes the generator object, and answers with it. So the *call* has to know, and the chunk
    /// is what still knows by then — the same argument as `strict` two fields up.
    ///
    /// It is not a constructor either (§15.5.3 gives it no `[[Construct]]`), and its `prototype`
    /// property is an object inheriting %GeneratorPrototype% rather than %Object.prototype%.
    pub(super) generator: bool,
    /// Whether this body is an `async` function's — §15.8, the `async` before `function`.
    ///
    /// The call has to know for the same reason a generator's does, and answers differently:
    /// §27.7.5.1 makes a promise, runs the body *now*, and answers with the promise however far the
    /// body got. A `return` from here resolves that promise and a throw rejects it, so both ways
    /// out of the body are decided by this flag and not by the shape of the value.
    pub(super) is_async: bool,
    /// Whether this body is a class constructor — §15.7.14.
    ///
    /// It has a `[[Construct]]` and no useful `[[Call]]`: written without `new` it is a TypeError.
    /// The flag lives on the body because by the time a call happens the chunk is the only thing
    /// left that could still know.
    pub(super) class_constructor: bool,
    /// Where a derived constructor's `this` lives, if this body is one — DR-0015.
    ///
    /// `None` for every other body, which is where `this` is the register the call set. Present, it
    /// is the slot §9.1.1.3's `[[ThisValue]]` occupies, and the *call* has to know: §10.2.2 does not
    /// create the receiver for a derived constructor, so what would otherwise be made on entry has
    /// to be left for `super()` to make.
    pub(super) derived_this: Option<u32>,
    /// The slot §10.4.4's arguments object goes in, if this body reaches for the name.
    ///
    /// `None` when it does not, and then no object is made: §10.2.11 makes one for every
    /// non-arrow function, and one nothing can read is one nothing can tell was never there. A
    /// call that made one anyway would allocate an object and its properties on every call in the
    /// program, which DR-0013 counts and a benchmark would notice.
    pub(super) arguments: Option<u32>,
    /// Whether this body reads the `arguments` of the function it is written *inside*.
    ///
    /// Only an arrow can: §15.3 gives it no `arguments` of its own, so the name resolves outward
    /// exactly as `this` does. The function around it has to know, because it is the one that has
    /// to build the object — and it finds out from here when the arrow's body comes back compiled.
    pub(super) outer_arguments: bool,
    /// Whether `new.target` means something in this body — §13.3.12's `[[NewTarget]]`.
    ///
    /// True for a function and for an **arrow written inside one**, which is the whole reason it is
    /// recorded: §15.3 makes an arrow transparent to `new.target` exactly as it is to `this`, so
    /// whether one is allowed depends on where the arrow was *written* and not on what it is. That
    /// is a lexical fact the parser has and a running arrow otherwise does not — the function object
    /// only says that it is an arrow.
    ///
    /// Read by a **direct `eval`**, which has to decide whether to parse `new.target` at all and
    /// can only ask the code it is running inside. Nothing else consults it: an ordinary body was
    /// judged by the parser when it was written.
    pub(super) lexical_new_target: bool,
    /// Whether this body is a class field's initialiser, or an arrow written inside one — §15.7.1.
    ///
    /// The clause forbids `arguments` there outright, and the parser applies it to source it can
    /// see. What it cannot see is a **direct `eval`** in the initialiser, whose text is parsed when
    /// the field runs — so the fact has to travel on the compiled body, which is the only thing
    /// still around by then. `Contains` stops at a function boundary and not at an arrow, which is
    /// why an arrow inherits this exactly as it inherits `lexical_new_target` above.
    pub(super) field_initializer: bool,
    /// The template objects' contents, one entry per tagged-template *site* in this chunk.
    ///
    /// Held here rather than built at compile time because the object is a frozen Array and belongs to
    /// a *realm*: the same chunk may run in two of them, and each needs its own. See
    /// [`Instruction::TemplateObject`], which builds one and caches it per site.
    pub(super) templates: Vec<Template>,
    /// The bodies of the functions written inside this one, in the order they were met.
    ///
    /// An `Rc` because a function object has to outlive the code that made it — `var f = g()`
    /// keeps a closure alive after `g` has returned — and because a chunk is immutable once
    /// compiled and holds only chunks *below* it. DR-0010 rejects reference counting for the
    /// *heap*, where cycles are made before user code runs; a tree of code has none, so the
    /// argument does not reach here.
    pub(super) functions: Vec<Rc<Chunk>>,
    /// What the source called the slots of this body's *own* environment — DR-0018.
    ///
    /// The one the call builds, holding the parameters, the `var`s and the body's top-level
    /// lexical bindings. A name's index is its slot. It may be **shorter** than
    /// [`Chunk::locals`], which is a high-water mark across every level this body compiled: a slot
    /// a nested scope needed and this level did not belongs to no name, and a resolver that finds
    /// no name for it is right.
    pub(super) bindings: Rc<[Binding]>,
    /// One entry per scope this body opens, which [`Instruction::PushScope`] names by index.
    ///
    /// The slot count and the names arrive together because they are learned together: a block's
    /// lexical names are known when it is entered, and the hidden slots its statements need are
    /// made as they are compiled — so both are written back once the block has been walked. A
    /// [`Instruction::CopyScope`] shares its scope's entry, which is what makes §14.7.4.7's copy
    /// the same shape as the environment it copies rather than a second description of it.
    pub(super) scopes: Vec<Scope>,
    /// §16.2.1.3's `ImportEntries` — what this module takes from other modules.
    ///
    /// Empty for every chunk but a module's. The *slot* is this module's; what it is bound to is
    /// decided when the graph is linked, because until then there is no environment to bind it to.
    pub(super) imports: Vec<ImportEntry>,
    /// §16.2.1.3's `ExportEntries` — what other modules may take from this one.
    /// The modules an `export * from "m"` re-exports everything of — §16.2.1.3's
    /// `[[StarExportEntries]]`.
    ///
    /// Apart from the list below because a star export contributes **no name**: which names
    /// it brings is a question about the other module, and §16.2.1.6.3 can only ask it once
    /// the graph exists.
    pub(super) star_exports: Vec<Box<str>>,
    pub(super) exports: Vec<ExportEntry>,
}

/// One `import` binding — §16.2.1.3's `ImportEntry`.
#[derive(Debug, Clone)]
pub struct ImportEntry {
    /// The `ModuleSpecifier`, exactly as written. Where it points is the host's business.
    pub specifier: Box<str>,
    /// The name to ask that module for, or `None` for `import * as n` — a namespace rather than a
    /// binding, which is the one import that is a *value* and not another module's slot.
    pub import_name: Option<Box<str>>,
    /// The slot in *this* module's environment the import binding occupies, or `None` for
    /// `import "a";` — which binds nothing and is written for the other module being evaluated.
    pub slot: Option<u32>,
}

/// One `export` — §16.2.1.3's `ExportEntry`, in the one shape ViperJS resolves.
#[derive(Debug, Clone)]
pub struct ExportEntry {
    /// The name other modules ask for.
    pub export_name: Box<str>,
    /// Where the value comes from — this module, or one it names.
    pub from: ExportSource,
}

/// Where an exported name's value lives — §16.2.1.3's `[[LocalName]]` against its `[[Module]]`.
///
/// The two are genuinely different facts and not one with a hole in it. A *local* export is a slot
/// this module has, settled when it is compiled. An *indirect* one names a module and a name in it,
/// and what that resolves to is not knowable until the graph exists — §16.2.1.6.3 `ResolveExport`
/// is the walk, and it may pass through several modules or find nothing at all.
#[derive(Debug, Clone)]
pub enum ExportSource {
    /// `export var a`, `export { a }` — a slot in this module's own environment.
    Local(u32),
    /// `export { a } from "m"`, `export * as n from "m"` — a name in another module.
    ///
    /// This module gets **no binding**: §16.2.1.3 says an indirect export is not an import, so
    /// `export { a } from "m"; a;` is a ReferenceError here even though `a` leaves this module.
    Indirect {
        /// The `ModuleSpecifier` the value comes from.
        specifier: Box<str>,
        /// The name asked of it, or `None` for `export * as n from "m"` — whose value is that
        /// module's whole namespace object rather than one of its names.
        import_name: Option<Box<str>>,
    },
}

/// One scope a body opens: how many slots it has, and what the source called them.
#[derive(Debug, Clone)]
pub struct Scope {
    /// How many variables it holds.
    pub slots: u32,
    /// What they are called, in slot order — see [`Binding`].
    pub names: Rc<[Binding]>,
}

/// What a tagged template's object is made of — §13.2.8.3's two arrays.
///
/// The cooked strings and the raw ones, one of each per literal component. A cooked one is `None`
/// where the component holds a `NotEscapeSequence`: §12.9.6 leaves `TV` undefined there, which is
/// legal in a *tagged* template and a Syntax Error in an untagged one, and is why `String.raw` exists.
#[derive(Debug, Clone)]
pub struct Template {
    /// `TV` per component — `None` for one whose escape is not a valid escape.
    pub cooked: Vec<Option<crate::heap::StringId>>,
    /// `TRV` per component, escapes exactly as written.
    pub raw: Vec<crate::heap::StringId>,
}

impl Chunk {
    /// Whether `new.target` means anything in this body — §13.3.12, and see the field.
    #[must_use]
    pub fn lexical_new_target(&self) -> bool {
        self.lexical_new_target
    }

    /// Whether this body is a class field's initialiser — §15.7.1's `ContainsArguments` subject.
    #[must_use]
    pub fn field_initializer(&self) -> bool {
        self.field_initializer
    }

    /// Every heap value this chunk names, and every one the chunks inside it name.
    ///
    /// A compiled body holds Strings — its constants, its own name, the cooked and raw halves of
    /// each tagged template — and nothing outside `compile` knows that. So the walk is here rather
    /// than in the collector, where it would be a second copy of this struct's field list and the
    /// kind that goes quietly out of date: a field added above and forgotten here does not fail to
    /// compile, it frees a String something is still going to read.
    ///
    /// Nested functions are included because a closure's body is reachable through the outer chunk
    /// long before any function object for it exists — `MakeFunction` reads it out of here.
    pub fn names(&self, into: &mut Vec<Value>) {
        into.extend(self.constants.iter().copied());
        into.extend(self.name.map(Value::String));
        for template in &self.templates {
            into.extend(template.cooked.iter().flatten().copied().map(Value::String));
            into.extend(template.raw.iter().copied().map(Value::String));
        }
        for nested in &self.functions {
            nested.names(into);
        }
    }
}

/// Whether a binding created on the global object may be deleted again — §9.1.1.4.17's `D`.
///
/// One parameter, and the two callers of that operation disagree about it. §16.1.7 step 18 passes
/// `false` for a Script, which is what makes `var x` at the top level permanent and
/// `globalThis.x = 1` not; §19.2.1.1 step 8 passes `true` for an `eval`, because code that ran once
/// should not be able to fix a name on the global object for the life of the realm.
///
/// A named pair rather than a `bool` on the instruction: the two spellings read the same at a call
/// site, and getting it backwards makes `delete` answer the opposite of what it should — which no
/// program crashes on and every property-descriptor test sees.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Deletable {
    /// §16.1.7 — a Script's, which stands for the life of the realm.
    No,
    /// §19.2.1.1 — an `eval`'s, which `delete` may take away again.
    Yes,
}

/// §10.2.9's `prefix` argument — the word an accessor's name begins with.
///
/// Three values and not an `Option<&str>`, because an instruction carries data and not text: the
/// space between the prefix and the name is the clause's (step 5 concatenates prefix, U+0020 and
/// name) and belongs here rather than at each site that spells one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NamePrefix {
    /// No prefix — a method, or a function in a named position.
    Plain,
    /// §15.4.5's getter.
    Get,
    /// §15.4.5's setter.
    Set,
}

/// One instruction.
///
/// Deliberately few. An operator is one instruction carrying which operator it is, rather than one
/// instruction per operator: the dispatch inside [`crate::value::apply_binary`] is a `match` on
/// the same value either way, and twenty opcodes would be twenty things to keep in step with the
/// abstract operations rather than one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Instruction {
    /// Push the constant at this index.
    Constant(u32),
    /// Replace a source and a flags string with a new `RegExp` object — §13.2.7.3.
    ///
    /// A **new** object every time, which is why a regular expression written inside a loop does
    /// not carry `lastIndex` from one turn to the next. ES3 shared one object per literal and the
    /// change is observable, so this is an instruction rather than a constant.
    RegExpLiteral,
    /// Replace the value on top of the stack with the result of a unary operator.
    Unary(UnaryOperator),
    /// §7.1.4 `ToNumeric` — what §13.4's four update productions coerce with.
    ///
    /// Not [`Instruction::Unary`] with a `+`, which is §13.5.4's `ToNumber` and turns a BigInt into
    /// a TypeError. The two agree on every value that is not a BigInt, which is how one stood in
    /// for the other until BigInts existed.
    ToNumeric,
    /// §13.4's "add one", in whichever numeric domain the operand already is.
    ///
    /// Separate from [`Instruction::ToNumeric`] because a postfix update keeps the **coerced** old
    /// value — `x = "1"; x++` evaluates to the number 1, not to `"1"` — so the duplication belongs
    /// between the two. And separate from a `Binary` against a constant 1, because that constant
    /// would have to be a Number or a BigInt and which one is not known until the operand is.
    Step(UpdateOperator),
    /// Replace the top two values with the result of a binary operator, left below right.
    Binary(BinaryOperator),
    /// Continue at this instruction instead of the next one.
    Jump(u32),
    /// Take the top value; if it is falsy, continue at this instruction instead.
    ///
    /// The value is consumed either way. This is the conditional operator's jump, where the test
    /// is asked about and then thrown away.
    JumpIfFalse(u32),
    /// Look at the top value; if the condition holds, continue at this instruction and **leave it
    /// where it is**. Otherwise take it and carry on.
    ///
    /// The short circuits' jump, and the reason they are not `if` in disguise: `a || b` is not
    /// `a ? true : b`, it is *`a` itself* when `a` is truthy. So the value that decided has to
    /// survive being the answer.
    JumpKeeping(ShortCircuit, u32),
    /// Take the top value; if it is truthy, continue at this instruction instead.
    ///
    /// The mirror of [`Instruction::JumpIfFalse`], and what a `do`/`while` loop jumps back with:
    /// its test is at the *bottom*, so the sense of the jump is reversed.
    JumpIfTrue(u32),
    /// Discard the top value.
    Pop,
    /// Push one of §6.1.5.1's well-known Symbols, by its position in the table.
    ///
    /// Not a constant, because a chunk outlives the realm it was compiled against: the same code
    /// may run in two realms, and each has its own `Symbol.iterator`. Reading it from the realm at
    /// the moment it is needed is what makes `for`-`of` reach the right one — and reading it from
    /// the *realm* rather than from the `Symbol` object is what stops a script moving it.
    LoadWellKnown(u32),
    /// Throw a **TypeError** unless the value on top is an Object, and leave it there.
    ///
    /// §7.4.4 step 3 and §7.4.9 step 6. An iterator whose `next` answers a primitive would
    /// otherwise have its `done` read off that primitive's prototype as `undefined` — falsy — and
    /// the loop would never end. A check that turns a hang into an error.
    RequireObject,
    /// §7.3.25 `CopyDataProperties` — a new object holding what a pattern did not name.
    ///
    /// Pops that many excluded keys and then the source, and pushes the object. The keys are
    /// popped rather than named at compile time because a computed one is a value: `{[k]: v,
    /// ...rest}` excludes whatever `k` came to, and evaluating `k` a second time to find out
    /// would run it twice.
    ///
    /// Own *enumerable* properties only, and it **gets** each one — so a getter on the source runs
    /// and its answer is what is copied, which is the same reading `Object.assign` takes.
    CopyRest(u32),
    /// §7.1.2 `RequireObjectCoercible` — throw a **TypeError** for `undefined` or `null`, and
    /// leave anything else where it is.
    ///
    /// Not [`Instruction::RequireObject`], which is stricter: a primitive *is* coercible, so
    /// `var {length: n} = "ab"` reads through the String's object and works. The two are only
    /// both needed because destructuring asks the weaker question and the iterator protocol asks
    /// the stronger one.
    ///
    /// A pattern with properties in it would raise this at its first read anyway. An empty one —
    /// `var {} = null` — would not, and is a TypeError all the same, which is the case this exists
    /// for.
    RequireCoercible,
    /// §7.1.17 `ToString` of the value on top, replacing it.
    ///
    /// Not `+ ""`, and the difference is observable. Addition takes `ToPrimitive` with the
    /// *default* hint, so an object with a `valueOf` answers through that; `ToString` uses the
    /// **string** hint and reaches `toString` first. A template substitution is specified as
    /// `ToString` (§13.2.8.6), so an object with both methods stringifies differently inside a
    /// template than beside a `+`, and no arrangement of existing instructions says that.
    Stringify,
    /// Push the value of a variable: this many environments out, at this index.
    ///
    /// One instruction rather than one per scope kind. The compiler built the chain of scopes, so
    /// it knows how far out a name is and nothing here searches for it — §9.1's environment
    /// records, resolved at compile time.
    LoadVariable(u32, u32),
    /// Store the top value into a variable, **without** taking it off the stack.
    ///
    /// Assignment is an expression: `a = (b = 1)` works because the inner one leaves its value
    /// behind. A statement that only wants the effect follows this with a [`Instruction::Pop`].
    StoreVariable(u32, u32),
    /// Put a local binding into §9.1.1.1's uninitialised state — the temporal dead zone.
    ///
    /// Emitted where a block is *entered*, once for each `let` or `const` it declares, because
    /// §14.2.3 `BlockDeclarationInstantiation` creates those bindings there and leaves them
    /// uninitialised until their declaration runs. Reading one in between is a ReferenceError.
    ///
    /// An instruction rather than a state the environment starts in, because a slot is not new
    /// each time its block is entered: a loop body's bindings occupy the same slots on every pass,
    /// and the second pass must find the dead zone rather than the first pass's value.
    Uninitialise(u32),
    /// Give a local binding its first value, **without** taking it off the stack.
    ///
    /// `InitializeBinding` (§9.1.1.1.4), which is a different operation from an assignment and
    /// has to be: an assignment to an uninitialised binding is a ReferenceError, and this is what
    /// stops being one. Only a declaration emits it, and only for its own binding, which is why
    /// there is no depth — a declaration initialises the binding it is written in.
    Initialise(u32),
    /// Throw a TypeError, because a `const` was assigned to — §9.1.1.1.5 step 3.
    ///
    /// The compiler resolved the binding and so already knows the assignment cannot stand. What is
    /// left for run time is only the throw, and it happens *here* rather than at compile time
    /// because §13.15.2 evaluates the right-hand side first: `const c = 1; c = f()` calls `f`.
    ThrowImmutableAssignment,
    /// Replace a value with the list of names a `for`-`in` over it visits — §14.7.5.10.
    ///
    /// The list is an ordinary Array of Strings, so the collector already knows how to keep it and
    /// nothing new has to be a `Value`. A value that is `undefined` or `null` enumerates *nothing*
    /// rather than failing: §14.7.5.6 step 2 leaves the loop before its body ever runs, and an
    /// empty list is that, exactly.
    EnumerateProperties,
    /// Take the next name from an enumeration, or `undefined` when there are none left.
    ///
    /// The object is popped from the stack; the two operands are the slots holding the list and
    /// the position in it, which the compiler owns and no source can name.
    ///
    /// `undefined` as the end marker is safe rather than convenient: §14.7.5.10 enumerates String
    /// keys and nothing else, so no name it could yield is `undefined`.
    ///
    /// Skipping is part of the step. §14.7.5.10 requires that a property deleted before it is
    /// reached is not visited, so each name is asked about again — on the object, not on the list
    /// — before it is handed back. A name added during the enumeration is not visited, which the
    /// same clause explicitly allows.
    EnumerateNext(u32, u32),
    /// Push the value of a global, named by the String constant at this index.
    ///
    /// The other half of §9.4.2's `ResolveBinding`. A name the compiler could not place in any
    /// scope is not an error — it is a question for the global object, and one whose answer can
    /// change between one line and the next. A name that is not there when it is *read* is a
    /// **ReferenceError** (§6.2.5.5 `GetValue` on an unresolvable reference), which is the one
    /// thing that separates `missing` from `o.missing`.
    LoadGlobal(u32),
    /// Store the top value into a global, **without** taking it off the stack.
    ///
    /// §6.2.5.6 `PutValue`, in the sloppy-mode half: assigning to a name that is nowhere creates
    /// it on the global object. Strict code throws a ReferenceError instead, and it does — the
    /// strictness reaches here and step 6 is implemented. This said "nothing carries a strictness
    /// this far yet, so this is the answer that is right for a Script's default", which was true
    /// when it was written and had stopped being true well before it was read again.
    StoreGlobal(u32),
    /// Push the `typeof` of a global, or `"undefined"` when there is no such global.
    ///
    /// §13.5.1.1 step 2: `typeof` is the one operator that takes an unresolvable reference and
    /// answers rather than throwing. It is how a program asks whether a feature exists at all —
    /// `typeof JSON !== "undefined"` is in test262's own harness — so a plain
    /// [`Instruction::LoadGlobal`] would turn the question into the error it was asked to avoid.
    TypeofGlobal(u32),
    /// Give the global object this name as a `var` binding, if it has not got one.
    ///
    /// §9.1.1.4.17 `CreateGlobalVarBinding(N, D)`: writable and enumerable like an ordinary
    /// property, and configurable exactly when `D` says — see [`Deletable`], which is the whole of
    /// what a Script and an `eval` disagree about here. An existing property is left alone: `var x`
    /// after `x` already holds something does not put `undefined` back, and that is hoisting.
    DeclareGlobal {
        /// The constant index of the name.
        name: u32,
        /// The clause's `D`.
        deletable: Deletable,
    },
    /// Settle a property reference's key, in §6.2.5.5's order — for a reference read *and* written.
    ///
    /// The stack holds a base and a key, and this replaces the key with the one `ToPropertyKey`
    /// makes of it, leaving the base alone. Two things about it are the whole reason it exists,
    /// and both are steps of `GetValue` and `PutValue` rather than of any operator:
    ///
    /// - **`ToObject` of the base comes first.** So `null[prop] += 1` is a TypeError before
    ///   `prop.toString()` is called, where converting the key on the way to the base calls it and
    ///   then throws.
    /// - **The Reference Record is mutated**, so the conversion happens *once*. A compound
    ///   assignment reads and writes one reference, and without this each end converts the key
    ///   again — `o[p] += 1` called `p.toString()` twice, which §13.15.2's own test262 file
    ///   asserts it must not.
    ///
    /// Emitted only where a reference is both read and written — a compound assignment, a logical
    /// assignment, an update. A plain `o[p] = v` converts once anyway, and `o.x` has a key that is
    /// a constant.
    PrepareKey {
        /// How deep the base sits under the key: one for `o[p]`, two for `super[p]`, whose
        /// receiver is pushed under its base.
        base: u32,
    },
    /// Refuse now if this name could not become a global `var` — §9.1.1.4.15 `CanDeclareGlobalVar`.
    ///
    /// §16.1.7 asks about **every** declaration before it creates **any**, which is the whole
    /// reason this is a separate instruction rather than a check inside `DeclareGlobal`. A script
    /// that cannot declare one of its names must not have declared the others either, and a check
    /// folded into the creation would leave the ones before it standing.
    CheckGlobalVar(u32),
    /// The same question for a function declaration — §9.1.1.4.16 `CanDeclareGlobalFunction`.
    ///
    /// Stricter than the `var` one and not by a little: a `var` may name any property that already
    /// exists, where a function needs one that is configurable, or writable *and* enumerable. That
    /// is why `var NaN;` at the top level is allowed and `function NaN() {}` is a TypeError — the
    /// second would have to replace a property §19.1.1 fixed in place, and the first only has to
    /// leave it alone.
    CheckGlobalFunction(u32),
    /// Push a new empty ordinary object, inheriting from `Object.prototype`.
    NewObject,
    /// Push a new empty Array of this length, inheriting from `Array.prototype`.
    ///
    /// The length is the literal's *element count*, holes included — §13.2.4.1 gives
    /// `[, , 1]` a length of 3 with one element in it. So the length is set once here rather
    /// than being raised element by element, which is also what makes a trailing hole count.
    NewArray(u32),
    /// Push a copy of the top two values, in the same order.
    ///
    /// A compound assignment to a property reads it and then writes it, and both need the base
    /// and the key. Evaluating them twice would call `f` twice in `o[f()] += 1`, so they are
    /// evaluated once and copied — which is what makes the once-only guarantee an instruction
    /// rather than a promise.
    DuplicateTop(u32),
    /// Take the top value and put it back this many places further down.
    ///
    /// `Bury(3)` turns `[a, b, c, v]` into `[v, a, b, c]`. There is one thing that needs it:
    /// `o.p++` has to keep the **old** value somewhere the store cannot reach, and the base, the
    /// key and the copy it is about to add one to are all sitting above it.
    ///
    /// Recovering the old value from the new one afterwards would need no instruction at all and
    /// would be wrong: `x = 2 ** 53; x++` leaves `x` unchanged, so `new - 1` is not the old
    /// value — and nothing is, once `NaN` is in play.
    Bury(u32),
    /// Take a value and a key and file the value under it, leaving the object where it is.
    ///
    /// `CreateDataPropertyOrThrow` (§7.3.5): an object literal *defines* its properties rather
    /// than assigning them, which is why `{__proto__: 1}` in a literal is special and
    /// `o.__proto__ = 1` is not, and why a literal can shadow a non-writable inherited property.
    DefineField,
    /// Take a function and a key and give the object under them a getter, keeping any setter.
    ///
    /// §15.4.5's `DefineMethod` half of an accessor. Not a [`Instruction::DefineField`] with a
    /// descriptor: a getter and a setter are two halves of *one* property, so defining one must
    /// leave the other where it is — which is why `{get a() {}, set a(v) {}}` is one property
    /// with both and not the second overwriting the first.
    DefineGetter,
    /// The same for a setter.
    DefineSetter,
    /// §15.7.14 `ClassDefinitionEvaluation` — the constructor and its prototype, made as a pair.
    ///
    /// One instruction rather than a sequence because neither half is observable on its own: the
    /// prototype cannot be reached until the constructor holds it, and the constructor is not usable
    /// until the prototype points back. There is no intermediate state worth naming in bytecode.
    ///
    /// The operand indexes the constructor's body. Leaves the constructor on the stack.
    /// Call with the arguments in the array on top of the stack — §13.3.8's spread.
    ///
    /// A separate instruction because [`Instruction::Call`] fixes its argument count at compile time
    /// and a spread does not have one until it has been iterated. The array is built first, by the
    /// same code an array literal uses, and this expands it: `f(...a, 1)` and `f.apply` differ only
    /// in who writes the array.
    /// §13.2.5 `...o` in an object literal — every own enumerable property of the value on top of
    /// the stack, added to the object beneath it.
    ///
    /// Pops the source and leaves the target, because a literal is built with one object on the stack
    /// throughout, the same way [`Instruction::DefineField`] does.
    SpreadProperties,
    /// Call with the arguments in the array on top of the stack — §13.3.8's spread.
    ///
    /// A separate instruction because [`Instruction::Call`] fixes its argument count at compile time
    /// and a spread does not have one until it has been iterated. The array is built first, by the
    /// same code an array literal uses, and this expands it.
    CallSpread(SpreadCall),
    /// §15.7.14 `ClassDefinitionEvaluation` — the constructor and its prototype, made as a pair.
    ///
    /// One instruction rather than a sequence because neither half is observable on its own: the
    /// prototype cannot be reached until the constructor holds it, and the constructor is not usable
    /// until the prototype points back.
    ///
    /// The operand indexes the constructor's body. Leaves the constructor on the stack.
    MakeClass {
        /// Which of this chunk's nested bodies is the constructor.
        body: u32,
        /// Whether the value of an `extends` clause is on the stack, waiting to be inherited from.
        ///
        /// §15.7.14 steps 8 to 11 read it three ways — `null` is a case of its own, a
        /// non-constructor is a TypeError, and otherwise both the constructor and its prototype are
        /// pointed at the parent's. A flag rather than a second instruction because everything after
        /// those steps is identical, and written twice one copy would be a branch no test reaches.
        derived: bool,
    },
    /// Replace the constructor on top of the stack with the prototype it was made with.
    ///
    /// Reads the object rather than the `prototype` property. At this point in a class definition the
    /// property is already non-writable and no getter could have been installed, so the two agree —
    /// and reading the object means a method definition cannot be intercepted.
    ClassPrototype,
    /// §15.7.14's method definition — a data property or one half of an accessor, **not** enumerable.
    ///
    /// The single runtime difference between a class body and an object literal: §15.4.5 makes a
    /// literal's methods enumerable and §15.7.14 does not, so `for (k in new C)` finds nothing. That
    /// one attribute is why this cannot be [`Instruction::DefineField`] with a flag.
    ///
    /// Pops the value, then the key, then the target.
    DefineClassMethod(crate::ast::MethodKind),
    /// `delete x` where `x` is a property of the global object — §13.5.1.2 step 5.
    ///
    /// The operand names it, exactly as [`Instruction::LoadGlobal`] does. A name the global object
    /// does not have answers **true**: §6.2.5.6 makes an unresolvable reference a delete of nothing,
    /// which succeeded vacuously. One it has answers whether the property was configurable.
    ///
    /// Only a *global* reaches this. A name the compiler could place is a declarative binding, and
    /// §9.1.1.1.5 makes every one of those non-deletable — so that answer is a constant `false` and
    /// needs no instruction at all.
    DeleteGlobal(u32),
    /// Take a key and a base and push the property's value — `[[Get]]`, §10.1.8.
    GetProperty,
    /// Take a value, a key and a base; store the value and leave it on the stack — §10.1.9.
    SetProperty,
    /// Take a constructor and a value and push whether the value is an instance of it.
    ///
    /// §13.10.2's `InstanceofOperator`. An instruction rather than a row in `apply_binary` for
    /// the same reason `in` is one: it asks an object a question instead of converting a value,
    /// and answering needs the prototype chain.
    Instanceof,
    /// Take a key and a base and push whether the property was there to remove — §13.5.1.
    DeleteProperty,
    /// Take a base and a key and push whether the base has it — §13.10.1's `in`.
    HasProperty,
    /// Take the top value and throw it — §14.14.
    ///
    /// Any value, not only an Error: `throw 1` is legal, and the specification never asks what
    /// was thrown. Where it lands is [`Instruction::PushHandler`]'s business.
    Throw,
    /// Remember that a throw from here until the matching pop should continue at this instruction.
    ///
    /// The operand stack's depth is remembered with it. A throw in the middle of an expression
    /// leaves whatever it had pushed behind, and unwinding has to put the stack back where the
    /// handler expects it — otherwise a caught exception would leave rubbish under every
    /// subsequent value.
    PushHandler(u32),
    /// Forget the innermost handler, because its protected region finished normally.
    PopHandler,
    /// Push a new function object over the nested body at this index.
    ///
    /// `InstantiateOrdinaryFunctionExpression` (§15.2.5) in the part that matters here: the
    /// object is made when the expression is *evaluated*, so two visits to the same `function`
    /// keyword make two objects, and `f !== f` across calls is the whole reason closures work.
    MakeFunction(u32),
    /// Take a callee and this many arguments and call it, leaving what it returned — §13.3.6.
    ///
    /// The callee gets no receiver, so its `this` is §10.2.1.2's substitution: the global object.
    Call(u32),
    /// The same call, made where the callee was written as the bare name `eval` — §13.3.6.1.
    ///
    /// A separate instruction because whether a call is a **direct** eval is a property of the
    /// *syntax* that only the compiler can see, and of the callee's *identity* that only the
    /// interpreter can. This carries the first half to the second: everything else about it is
    /// [`Instruction::Call`], and it behaves as one whenever the callee turns out to be anything
    /// but `%eval%` — which is exactly what makes `var eval = f; eval(x)` an ordinary call.
    CallDirectEval(u32),
    /// The same call, with §9.1.1.2.10's `WithBaseObject` pushed under the callee.
    ///
    /// `with (o) { eval("x") }` is still a **direct** eval — §13.3.6.1 asks how the callee was
    /// *written*, and a bare `eval` inside a `with` is written the same way as one anywhere else.
    /// What the `with` adds is a receiver, and ViperJS decided the call's shape and its directness
    /// with one `match`: a receiver made it `CallMethod` and the direct-eval question was dropped.
    /// So the text ran as an **indirect** eval, in the global scope, and read the wrong variables
    /// without refusing anything.
    CallDirectEvalMethod(u32),
    /// Take a receiver, a callee and this many arguments, and call the callee *on* the receiver.
    ///
    /// A method call is not a plain call of a property's value. `o.m()` and `var f = o.m; f()`
    /// call the same function with different `this`, which is the whole reason the receiver
    /// travels with the call rather than with the function.
    CallMethod(u32),
    /// [`Instruction::Call`] in §15.10's **tail position** — the frame goes down before the call.
    ///
    /// The call itself is identical; what differs is that the frame this body is running in is
    /// taken down first, so `frames` gains one entry and loses one and the depth does not grow.
    /// A `Return` is still emitted after it and is simply never reached, because the callee's frame
    /// returns to wherever *this* one was going to. DR-0027.
    ///
    /// Emitted only where the source says it is safe — strict code, no derived constructor, and no
    /// `finally`, iterator close or handler left to cross. The machine declines it for the two
    /// things the source cannot see, a construction and a suspendable body, and then this behaves
    /// exactly as [`Instruction::Call`].
    CallTail(u32),
    /// [`Instruction::CallMethod`] in §15.10's tail position — see [`Instruction::CallTail`].
    ///
    /// A separate instruction for the reason the pair it mirrors is: the receiver is one more stack
    /// entry to carry down, and the count alone does not say whether it is there.
    CallTailMethod(u32),
    /// Take a constructor and this many arguments and construct — §13.3.5.
    ///
    /// Not a call with a different receiver: the receiver is *made* here, out of the
    /// constructor's own `prototype` property, and the result is that object unless the body
    /// returned one of its own.
    Construct(u32),
    /// Push the running function's `this`.
    LoadThis,
    /// `super(…)` — construct the parent and leave the object it made on the stack (§13.3.7.1).
    ///
    /// Not [`Instruction::Construct`] with a different callee, and the differences are the whole of
    /// what a derived construction is. The callee is not named in the source: it is the running
    /// function's `[[Prototype]]`, read now rather than captured at the class definition, because
    /// `Object.setPrototypeOf(D, Other)` changes what `super()` reaches. And `new.target` is
    /// *inherited* rather than becoming the parent, which is what makes `new E()` produce an `E`
    /// however many `extends` clauses it passes through.
    ///
    /// The operand is the argument count; the arguments are on the stack above nothing else.
    SuperCall(u32),
    /// §9.1.1.3's `MakeMethod` — tell the function on top of the stack which object it was defined on.
    ///
    /// Nothing is popped and nothing is observable: `[[HomeObject]]` is not a property and no script
    /// can read it. Only `super` consults it, which is why an ordinary function expression never gets
    /// one — `{ m: function () { return super.x; } }` is a Syntax Error, and the parser says so.
    ///
    /// The operand is how far below the top the home object sits, because the definition that follows
    /// needs its own operands in place: a method definition has `[home, key, function]` on the stack
    /// and a synthesised initialiser has `[home, function]`.
    MakeMethod(u32),
    /// §9.1.1.3's `GetSuperBase` — push the running method's home object's `[[Prototype]]`.
    ///
    /// One level *above* where the method was defined, which is the whole point: a method that read
    /// its own home would find itself and recurse. `undefined` when the running function has no home,
    /// which no `super` the parser accepts can reach.
    LoadSuperBase,
    /// `super.x` — read a property of the super base with `this` as the receiver (§13.3.7.1).
    ///
    /// Two objects, which is what makes this its own instruction. The property is *found* on the
    /// super base and an accessor is called with **`this`**, so a getter inherited from a parent sees
    /// the instance rather than the prototype it was found on. [`Instruction::GetProperty`] uses one
    /// value for both and cannot express it.
    ///
    /// Pops the key, the base and the receiver, in that order down the stack.
    GetSuperProperty,
    /// `super.x = v` — write through the super base with `this` as the receiver (§13.3.7.1).
    ///
    /// The receiver decides where the value *lands*: an inherited setter is called with `this`, and a
    /// write with no setter creates an own property of `this` rather than of the base. So
    /// `super.x = 1` in a method leaves an own `x` on the instance, which is the same rule as an
    /// ordinary assignment through a prototype and reads oddly only because the base is named.
    ///
    /// Pops the value, the key, the base and the receiver, leaving the value.
    SetSuperProperty,
    /// `delete super.x` — §13.5.1.1 step 3's unconditional **ReferenceError**.
    ///
    /// A run-time throw and not an early error, because the reference is evaluated first: `delete
    /// super[k]` runs `ToPropertyKey(k)` and only then refuses, so a `toString` on the key has
    /// already had its effect. The base and the key are on the stack and go with the throw.
    ThrowSuperDelete,
    /// Give the function on top of the stack the running function's `[[HomeObject]]`.
    ///
    /// For the bodies ViperJS synthesises to stand in for inline code — a derived class's instance
    /// field initialisers, which §15.7.14 runs from `super()` rather than on entry. Written inline
    /// those statements would see the constructor's home; as a body of their own they have none, so
    /// this is what an arrow's capture does, for a function that is not an arrow and needs its own
    /// `this`.
    InheritHome,
    /// Push a **fresh** Private Name — §9.2's `PrivateEnvironment`, one entry at a time.
    ///
    /// Fresh per execution, which is the whole reason it is an instruction rather than a constant: a
    /// class evaluated twice has two sets of private names, so an instance of one evaluation is not a
    /// brand of the other. That is what every `multiple-evaluations-of-class` test in the suite is
    /// about, and a constant in the chunk would make them all pass by accident and be wrong.
    ///
    /// The name is a Symbol, because §6.2.12 asks for exactly what a Symbol has — an identity that is
    /// itself and a description only a debugger reads — and for nothing a Symbol lacks. It goes into a
    /// compiler slot no source can spell and never reaches a property table.
    NewPrivateName(u32),
    /// `{__proto__: v}` — B.3.1, which sets the prototype instead of making a property.
    ///
    /// An **Annex B** rule and the one ViperJS implements, for the reasons in DR-0008: it is not
    /// conditioned on strictness, and leaving it out is a silent wrong answer rather than a refusal —
    /// the grammar already accepts `__proto__: x`, so there is nothing to reject.
    ///
    /// A value that is neither an Object nor `null` is **ignored**: `({__proto__: 1})` has no
    /// prototype-setting effect *and* no `__proto__` property, which is the one shape that surprises
    /// people. Pops the value and peeks the target, as a definition does.
    SetLiteralPrototype,
    /// §7.3.29 `PrivateFieldAdd` — add a private field to an object.
    ///
    /// A **TypeError** if the object already carries the name, which is step 3 rather than a
    /// defensive check: a constructor re-entered on an object it already initialised reaches it.
    ///
    /// Pops the value and the name, and *peeks* the target — an instance is given one field after
    /// another, exactly as [`Instruction::DefineField`] does it.
    DefinePrivateField,
    /// §7.3.30 `PrivateMethodOrAccessorAdd` — give an object a private method or accessor.
    ///
    /// One function object is shared by every instance and each instance carries an *entry* for it,
    /// which is what makes `#m in o` a brand rather than a lookup up a prototype chain. So the method
    /// is made once at the class definition and this is what runs per construction.
    ///
    /// A **TypeError** if the object already carries the name, on the same terms as §7.3.29.
    ///
    /// Pops the value — one function, or a getter and a setter for
    /// [`Instruction::AddPrivateAccessor`] — then the name, and *peeks* the target.
    AddPrivateMethod,
    /// The same for an accessor, whose two halves are **one** element (§7.3.30).
    ///
    /// Either half may be `undefined`, and then that direction is a TypeError rather than silently
    /// doing nothing — which is where a private accessor differs from a public one. Two halves written
    /// separately still make one element, so the second must merge into the first rather than replace
    /// it, and that is why this is not two adds.
    ///
    /// Pops the setter, the getter and the name, and peeks the target.
    AddPrivateAccessor,
    /// §7.3.31 `PrivateGet` — read a private field, or throw.
    ///
    /// A **TypeError** when the object does not carry the name, and that is what makes a private name
    /// a *brand*: there is no way to ask without risking the throw except [`Instruction::HasPrivate`],
    /// which exists for exactly that reason.
    ///
    /// Pops the name and the target.
    GetPrivate,
    /// §7.3.32 `PrivateSet` — write a private field that is already there, or throw.
    ///
    /// It does not create one. `this.#x = 1` on an object with no `#x` is a TypeError, which is what
    /// fixes an object's set of private names at construction.
    ///
    /// Pops the value, the name and the target, and leaves the value: an assignment is an expression.
    SetPrivate,
    /// `#x in o` — §13.10.1, the one way to ask without risking the throw.
    ///
    /// Pops the name and the target and pushes a Boolean. It exists because §7.3.31 throws: without
    /// it, asking whether an object is one of yours would mean catching a TypeError.
    HasPrivate,
    /// §10.2.2's `BindThisValue` — bind the derived constructor's `this` to the top value.
    ///
    /// Peeked rather than popped, because §13.3.7.1 step 8 makes the object the value of the
    /// `super()` expression as well. Binding a second time is a **ReferenceError**, which is what
    /// makes two `super()` calls in one constructor an error rather than two constructions — so this
    /// cannot be [`Instruction::Initialise`], which writes whatever it finds.
    BindThis {
        /// How many environments out the binding is — see [`Instruction::LoadThisBinding`].
        ///
        /// Carried for the same reason the *read* carries one, and it was missing here: the write
        /// went to whatever environment was current, so a `super()` written inside any scope of its
        /// own reached for a slot that scope has not got. `class D extends B { constructor() { {
        /// let q = 1; super(); } } }` faulted with `MissingLocal`.
        depth: u32,
        /// Which slot, in that environment.
        index: u32,
    },
    /// Read a derived constructor's `this` — §9.1.1.3's `ResolveThisBinding` (DR-0015).
    ///
    /// Its own instruction rather than [`Instruction::LoadVariable`] for the message alone: the
    /// binding is in the same uninitialised state a `let` above its declaration is in, and reporting
    /// it as one would send a reader looking for a declaration there is not.
    LoadThisBinding {
        /// How many environments out — non-zero for an arrow written inside the constructor.
        depth: u32,
        /// Which slot, in that environment.
        index: u32,
    },
    /// Turn the top value into what a derived constructor returns — §10.2.2 step 13.
    ///
    /// Stricter than a base constructor's, which is why it cannot be left to
    /// [`Instruction::Return`]: an object is answered with, `undefined` is answered with the bound
    /// `this` — a ReferenceError if `super()` never ran — and **any other primitive is a
    /// TypeError**, where a base constructor ignores it and answers with the object it made.
    ///
    /// The operand is the `this` binding's slot, always in the running environment: a `return` is
    /// compiled inside the constructor whose binding it is, however many blocks deep.
    CompleteDerivedReturn(u32),
    /// Push §13.2.8.3's template object for the tagged template at this index.
    ///
    /// A frozen Array of the cooked strings with a frozen `raw` Array of the raw ones. **Cached per
    /// site**: the same tagged template evaluated twice hands the tag the *same* object, which is what
    /// lets a tag use it as a key and is the one thing about it a program can detect. So the identity
    /// is per site and per realm rather than per evaluation, and building a fresh one each time would
    /// pass every test about its contents and fail every test about its identity.
    TemplateObject(u32),
    /// Push the running function's `new.target` — §13.3.12.
    ///
    /// `undefined` unless the running call was a `new`, which is the whole of what the expression
    /// is for: a function cannot otherwise tell `f()` from `new f()`. Its own instruction rather
    /// than a property of anything, because it is a property of the *call* — the same function
    /// object answers differently on two successive calls, so there is nowhere else to read it
    /// from.
    LoadNewTarget,
    /// §9.4.2 `ResolveBinding` — resolve a name once and keep the Reference for a later write.
    ///
    /// The three that follow are one operation split across the right-hand side that sits between
    /// them. §13.15.2 evaluates the *target reference* first, reads through it, evaluates the value,
    /// and writes back through the **same** reference — so a getter that deletes the property
    /// between the read and the write must not send the write somewhere else.
    ResolveName(u32),
    /// Read through the Reference on top of the reference stack, leaving it there.
    ///
    /// Carries the name because a `with` object's binding is a *property*, and reading one needs
    /// the key — the Reference records which object, not which name.
    LoadThrough(u32),
    /// Write the top of the operand stack through the Reference, and drop the Reference.
    StoreThrough(u32),
    /// §13.2.5.5 and §15.7.11 — turn the computed key on top of the stack into a property key.
    ///
    /// Evaluating a `PropertyName` *is* `ToPropertyKey`, and it happens before the value it names is
    /// evaluated. Leaving it to the define at the end runs the key's own `toString` after the
    /// value's expression, which is the wrong order and is observable; it also runs it a second time
    /// once anything else needs to look at the key. Settled here, the define finds a String or a
    /// Symbol and converting one of those again calls nothing.
    SettleKey,
    /// §10.2.9 `SetFunctionName` — name the function on top of the stack after the key beneath it.
    ///
    /// Emitted only where §8.6.3 puts a `NamedEvaluation`: a method, an accessor, or an anonymous
    /// function definition given a **computed** key. A literal key is known while compiling and is
    /// baked into the body, so this is the run-time half of the same rule and not a second one.
    NameFunction(NamePrefix),
    /// §13.3.12 `import.meta` — the module's own metadata object, made once and cached.
    ///
    /// Takes no operand: *which* module is a question about the environment the running code is
    /// closed over, not about the code, and only the machine can answer it. §10.2.1.1 gives a call
    /// its callee's `[[ScriptOrModule]]` rather than its caller's, so a function declared in one
    /// module and called from another still answers with the module it was written in — which is
    /// what walking out to the root of the environment chain gives for free.
    ImportMeta,
    /// Push a copy of the top value.
    ///
    /// A method call needs the base twice — once to find the method on and once to call it with —
    /// and evaluating it twice would run its side effects twice.
    Duplicate,
    /// Leave the current function, taking the top value with it — §14.10.
    Return,
    /// Park the running generator and answer `{ value, done: false }` — §27.5.3.7's
    /// `GeneratorYield`.
    ///
    /// The top value is what was yielded. It is wrapped where a [`Instruction::Return`] would have
    /// left the returned value, because the call being answered is the *resumption* — `gen.next()`
    /// gets an iterator result, and the value itself would be indistinguishable from a generator
    /// that yielded `{ value: 1, done: true }`.
    ///
    /// Which generator to park into is not an operand: it is the frame's, because §27.5.3.7
    /// suspends *the generator's own execution context* and there is no other one a `yield` could
    /// mean. What comes back the other way — the argument to the next resumption — is left on the
    /// stack, so the `yield` expression evaluates to it.
    Yield,
    /// §8.3.2 — push a fresh Declarative Environment Record of this many slots and run inside it.
    ///
    /// What makes a block's `let` a binding *per execution of the block* rather than a slot in the
    /// function. Without it a closure made on one pass through a loop body and one made on the next
    /// read the same variable, which is the single most visible thing an engine can get wrong about
    /// ES2015 scoping.
    ///
    /// Emitted only for a block that declares something lexical. A block that declares nothing has
    /// no bindings to keep apart, and an environment per `{ }` would cost an allocation on every
    /// `if` in the program.
    ///
    /// The operand names a [`Scope`] of this chunk — [`Chunk::scope`] — rather than being the slot
    /// count, because a scope carries its names as well; see [`Binding`]. One index and not two
    /// operands: a scope's size and its names are one fact learned at one moment, and an
    /// instruction that carried them apart could be patched with half of it.
    PushScope(u32),
    /// Leave it again, running in its parent — the other half of [`Instruction::PushScope`].
    ///
    /// Emitted on every path out of the block, which is what `unwind_across` is for: a `break`, a
    /// `continue` and a `return` each leave as many scopes as they cross. A **throw** does not need
    /// one, because the handler records the environment it was installed in and unwinding restores
    /// it — there is no instruction to run on a path that jumps.
    PopScope,
    /// §14.7.4.7 `CreatePerIterationEnvironment` — a *sibling* holding copies of the same bindings.
    ///
    /// The loop variable of `for (let i = 0; …)` is one binding per iteration, and each iteration
    /// starts from the last one's value. So this makes a new environment beside the current one —
    /// same parent, not a child — copies the slots across, and runs in it. Nesting instead would
    /// deepen the chain by one per iteration, and a loop of a million would be a chain of a
    /// million.
    ///
    /// The operand names a [`Scope`] — [`Chunk::scope`] — and it is the *same* one the
    /// [`Instruction::PushScope`] it copies names: a pass's environment is the same shape and holds
    /// the same names as the one before it, which is what makes it a copy.
    CopyScope(u32),
    /// §14.11 — take the value on top, make it an object, and run inside a scope of its properties.
    ///
    /// The operand names a [`Scope`] exactly as [`Instruction::PushScope`] does, and for the same
    /// reason: the compiler still needs a level of its own for the temporaries a body's statements
    /// make. §9.1.1.2's record has only the object; ViperJS's has the object *and* those slots, and
    /// nothing can tell — a temporary is spelled with a `%` no source can write, and the name walk
    /// that a `with` body's identifiers go through asks the object and never the slots.
    ///
    /// Left by an ordinary [`Instruction::PopScope`]. There is nothing to undo but the hop.
    PushWithScope(u32),
    /// Read `name` by walking the running scopes — §9.4.2 `ResolveBinding` at run time.
    ///
    /// What a name inside a `with` body compiles to, and only there. Everywhere else the compiler
    /// knows which scope and which slot, and says so in [`Instruction::LoadVariable`]; inside a
    /// `with` the answer depends on what the object holds at the moment of the read, so there is no
    /// index that could be right. The operand indexes the constant table, and the constant is the
    /// name.
    LoadName(u32),
    /// Write it — the same walk, and §6.2.5.6's rule that a name found nowhere becomes a property
    /// of the global object.
    StoreName(u32),
    /// §13.5.1.1 — its type, and `"undefined"` rather than a throw when the walk finds nothing.
    TypeofName(u32),
    /// §13.3.10 `ImportCall` — `import(x)`, which answers a promise and loads in a job.
    ///
    /// Takes the specifier off the stack and leaves the promise there. Everything else happens
    /// later and elsewhere: `ToString` of the specifier is the last thing that can throw
    /// *synchronously*, and §13.3.10 step 6 makes even that a rejection rather than a throw — so
    /// this instruction cannot fail, which is what lets `import()` be a value like any other.
    DynamicImport,
    /// §13.5.1.2 — delete it, when where it lives is only known at run time.
    ///
    /// The same walk as [`Instruction::LoadName`], and the answer depends on what the walk lands on
    /// rather than on the name: a declarative binding is **non-deletable** (§9.1.1.1.5) and answers
    /// false, a `with` object's property is deleted (§9.1.1.2.7), and a name found nowhere is the
    /// global object's business. Three answers one instruction has to be able to give, which is why
    /// the compiler cannot settle this one inside a `with` the way it settles it outside.
    DeleteName(u32),
    /// Read it *for a call*, pushing §9.1.1.2.10's `WithBaseObject` under it as the receiver.
    ///
    /// The one place a call written as a bare name has a `this`: `with (o) { m() }` calls `o.m`
    /// with `o`, where `m()` anywhere else is called with none. That is the whole of why a `with`
    /// is not sugar for a block of property reads, and it is why this is a separate instruction
    /// rather than a [`Instruction::LoadName`] with a `Call` after it.
    LoadNameForCall(u32),
    /// §15.5.4 `GeneratorStart` — make the generator, park everything after this, and answer it.
    ///
    /// Emitted once, at the point where the parameters have been initialised and the body has not
    /// begun. That position *is* the clause: §15.5.4 runs `FunctionDeclarationInstantiation` and
    /// only then creates the object, so a destructuring parameter that throws — `function* g([x])`
    /// called with something that is not iterable — throws **at the call**, before there is a
    /// generator to hold anything.
    ///
    /// Deciding it in `enter` instead, which is what this replaces, put the whole parameter list
    /// inside the parked body and so ran it at the first `next`. Nothing about that is visible
    /// until a parameter can fail or be observed, and then all of it is at once.
    GeneratorStart,
    /// Push whether the resumption that just revived this body asked for a `return` — §27.5.1.3.
    ///
    /// Emitted straight after every [`Instruction::Yield`], because that is the only place it can
    /// be read: a generator resumed by `gen.return(v)` has to behave as though `return v` were
    /// written at the `yield`, and only the compiler standing at that `yield` knows which `finally`
    /// blocks and which open iterators lie between it and the end of the body.
    ///
    /// So the *value* travels as an ordinary resumption and this says what it meant. The
    /// alternative — a return completion travelling through the unwinder past `catch` handlers and
    /// stopping at `finally` ones — needs a second kind of throw and a handler that can tell them
    /// apart, to arrive at the sequence the compiler can already emit.
    ResumeMode,
    /// The same, with the top value **already** an iterator result — §27.5.3.7 step 7.a.vii.
    ///
    /// A `yield*` passes the inner iterator's result object out whole rather than taking its
    /// `value` and wrapping it again, and the difference is observable: extra properties on the
    /// object reach the outer caller, and a `done` that is truthy without being `true` stays as it
    /// was. Wrapping twice would also make `{ value: 1, done: false }` come out as
    /// `{ value: { value: 1, done: false }, done: false }`.
    YieldDelegated,
    /// Hand the top value to a promise and stop until it settles — §27.7.5.3 `Await`.
    ///
    /// The park is a `yield`'s in every respect; what differs is who puts the body back. Two
    /// functions are attached to the promise, one per way it can settle, and a job calls whichever
    /// applies. What is left where a return value goes is the `async` function's **own** promise,
    /// because that is what its caller has been waiting for since the first of these.
    Await,
    /// Reject an `async` function's promise with the top value and leave the body — §27.7.5.2.
    ///
    /// The target of a handler the compiler arms over the whole body, which is how a throw that
    /// nothing inside caught becomes a rejected promise rather than an exception the caller sees.
    /// Doing it in the unwinder instead would mean teaching every throw about `async` functions;
    /// this way the ordinary machinery carries it to one instruction that knows.
    AsyncReject,
    /// Replace an iterable with its **async** iterator and that iterator's `next` — §7.4.3.
    ///
    /// Two values pushed where one was taken, because §7.4.2's Iterator Record is two things and
    /// reading `next` once is part of what it promises: replacing `next` on the iterator part-way
    /// through a `for await` does not change the walk.
    ///
    /// The whole of §7.4.3's `async` hint lives behind this, including the case that makes the
    /// protocol usable at all — an object with only a `[@@iterator]` is wrapped by §27.1.4.1 so the
    /// loop above only ever talks to one protocol.
    GetAsyncIterator,
    /// Refuse a `throw` that an inner iterator has no way to receive — §27.5.3.7 step 7.b.iii.
    ///
    /// Its own instruction for the reason [`Instruction::ThrowSuperDelete`] is one: the message is
    /// fixed, the error kind is fixed, and building it out of the global `TypeError` would let a
    /// script that replaced that name change what the engine throws.
    ThrowNoThrowMethod,
    /// Take the top value and make it the script's completion value.
    ///
    /// §14.2.2 — a Script evaluates to the value of its last *value-producing* statement, which
    /// is what makes `eval("1; 2")` be 2 and `eval("var x = 1")` be `undefined`. A register
    /// rather than the stack, because a statement in the middle of a block has to be able to
    /// replace it without anything below being disturbed.
    SetCompletion,
    /// Set §14.2.2's completion value to `undefined`, taking nothing from the stack.
    ///
    /// What eight statement forms begin with — see `Compiler::begin_completion`. Its own
    /// instruction rather than a constant and a [`Instruction::SetCompletion`], because a statement
    /// is stack-neutral and this runs where pushing a value would have to be balanced by whatever
    /// the statement does next, on every path out of it.
    CompletionUndefined,
}

/// When a [`Instruction::JumpKeeping`] jumps — one per short-circuiting operator (§13.13, §13.14).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShortCircuit {
    /// `&&` — stop at the first falsy operand, which becomes the answer.
    WhenFalsy,
    /// `||` — stop at the first truthy one.
    WhenTruthy,
    /// `??` — stop at the first that is neither `null` nor `undefined`.
    ///
    /// A different test from `||`, and the whole reason `??` exists: `0 || 1` is `1` and
    /// `0 ?? 1` is `0`, because `0` is falsy and is not nullish.
    WhenNotNullish,
}

/// A jump that has been emitted and does not know where it goes yet.
///
/// Exists to make forgetting one impossible rather than unlikely. It is `#[must_use]`, it is not
/// `Copy`, and [`Chunk::patch`] takes it by value — so the only way to obtain one is to emit a
/// jump and the only way to be rid of one is to patch it. A dangling jump becomes a build failure
/// under the gate's denied warnings, which is a stronger claim than any test could make.
#[must_use = "a jump that is never patched jumps nowhere"]
pub(super) struct Unpatched(usize);

impl Chunk {
    /// The instructions, in order.
    pub fn code(&self) -> &[Instruction] {
        &self.code
    }

    /// The constant at `index`, or `None` if there is none.
    ///
    /// Fallible because a `Chunk` can be built by hand, and a hand-built one may point anywhere.
    /// The compiler never produces such a chunk; the VM still has to answer for one, which is
    /// DR-0002 applied to the engine's own output rather than to a script's input.
    pub fn constant(&self, index: u32) -> Option<Value> {
        self.constants.get(index as usize).copied()
    }

    /// A chunk built by hand, out of instructions and constants that need not agree.
    ///
    /// The compiler does not use this — it emits as it goes — and nothing in the engine does. It
    /// is here so that a chunk the compiler would never produce can be *written*, which is the
    /// only way to reach [`crate::vm::Fault`] and therefore the only way to test that a malformed
    /// chunk is answered rather than crashed on.
    /// Everything but the code and the constants is left at its default, and *deliberately* not
    /// restated: a hand-built chunk is never a callee, so a field like `arrow` could be set to
    /// anything here without any test being able to tell. Written twice, the second copy would be
    /// a value no test can reach — so it is written once, where the compiler also gets it.
    pub fn from_parts(code: Vec<Instruction>, constants: Vec<Value>) -> Self {
        Self {
            code,
            constants,
            ..Self::default()
        }
    }

    /// How many named parameters the function this code belongs to declares.
    ///
    /// How many slots the parameters occupy — every named one, the rest parameter aside.
    ///
    /// What a call fills from its arguments. Not `length`: see [`Chunk::length`].
    pub fn parameters(&self) -> usize {
        self.parameters
    }

    /// §10.2.3's `length` — the count before the first default or rest parameter.
    ///
    /// `function f(a, b = 1, c)` has a length of 1, and a reader who expects 3 is reading the
    /// number of *slots*. What this reports is how many arguments the function says it needs.
    pub fn length(&self) -> usize {
        self.length
    }

    /// §10.2.9's `name`, or `None` where the specification asks for the empty string.
    pub fn name(&self) -> Option<crate::heap::StringId> {
        self.name
    }

    /// Whether this body is strict code — §11.2.1.
    pub fn is_strict(&self) -> bool {
        self.strict
    }

    /// Whether this body belongs to a generator function — §15.5.
    pub fn is_generator(&self) -> bool {
        self.generator
    }

    /// Whether this body belongs to an `async` function — §15.8.
    pub fn is_async(&self) -> bool {
        self.is_async
    }

    /// Whether the parameter list is simple — §15.1.4, and which arguments object to build.
    pub fn simple_parameters(&self) -> bool {
        self.simple_parameters
    }

    /// The slot a rest parameter's array goes in, if there is one.
    pub fn rest(&self) -> Option<u32> {
        self.rest
    }

    /// The template at this index, if there is one.
    pub fn template(&self, index: u32) -> Option<&Template> {
        self.templates.get(index as usize)
    }

    /// The body of the nested function at this index, if there is one.
    pub fn function(&self, index: u32) -> Option<&Rc<Chunk>> {
        self.functions.get(index as usize)
    }

    /// How many local-variable slots the code addresses.
    ///
    /// The VM gives a frame this many slots, each starting as `undefined` — which is what makes a
    /// `var` readable before its declaration and holding nothing.
    pub fn locals(&self) -> usize {
        self.locals
    }

    /// Where a derived constructor's `this` lives, if this body is one — DR-0015.
    ///
    /// `None` means the call binds `this` and makes the receiver, which is every other body. The
    /// call reads this to decide *not* to make one: §10.2.2 leaves that to `super()`.
    pub fn derived_this(&self) -> Option<u32> {
        self.derived_this
    }

    /// Whether this body is a `MethodDefinition`, and so has no `[[Construct]]` — §15.4.5.
    pub fn is_method(&self) -> bool {
        self.method
    }

    /// Whether this body is a class constructor, and so refuses a call without `new`.
    pub fn is_class_constructor(&self) -> bool {
        self.class_constructor
    }

    /// Whether this body is an arrow's, and so has no `this` of its own.
    pub fn is_arrow(&self) -> bool {
        self.arrow
    }

    /// The slot a call should put §10.4.4's arguments object in, if this body reads the name.
    pub fn arguments(&self) -> Option<u32> {
        self.arguments
    }

    /// Point a jump at a target that is already known, which a backward jump's is.
    pub(super) fn patch_to(&mut self, jump: Unpatched, target: u32) {
        let Unpatched(at) = jump;
        if let Some(instruction) = self.code.get_mut(at) {
            *instruction = retarget(*instruction, target);
        }
    }

    /// Record what a scope turned out to be, and answer the index that names it.
    ///
    /// Neither half is known when the [`Instruction::PushScope`] is emitted: a block's lexical
    /// names are, but the hidden slots its statements need are made as they are compiled, and the
    /// two have to agree on their order. So the whole entry is written once the block has been
    /// walked, and the instructions that opened it are patched to point at it.
    pub(super) fn add_scope(&mut self, scope: Scope) -> Result<u32, CompileError> {
        let index = u32::try_from(self.scopes.len()).map_err(|_| CompileError {
            kind: ErrorKind::TooLong,
            span: Span::new(0, 0),
        })?;
        self.scopes.push(scope);
        Ok(index)
    }

    /// Point an already-emitted scope instruction at the entry [`Chunk::add_scope`] made.
    ///
    /// Written like a jump's target — a placeholder now, the real index once the block has been
    /// walked. Separate from [`Chunk::patch_to`] rather than folded into `retarget`, because that
    /// function is about *targets* and its exhaustiveness is what stops a new jump being
    /// forgotten. A scope index arriving there would make "not a jump" a lie.
    pub(super) fn patch_scope(&mut self, scope: Unpatched, index: u32) {
        let Unpatched(at) = scope;
        if let Some(instruction) = self.code.get_mut(at) {
            *instruction = match *instruction {
                Instruction::PushScope(_) => Instruction::PushScope(index),
                Instruction::CopyScope(_) => Instruction::CopyScope(index),
                Instruction::PushWithScope(_) => Instruction::PushWithScope(index),
                other => other,
            };
        }
    }

    /// The scope at `index`, if there is one.
    ///
    /// Fallible on the same terms as [`Chunk::constant`]: the compiler never emits an index it did
    /// not make an entry for, and a hand-built chunk may point anywhere.
    pub fn scope(&self, index: u32) -> Option<&Scope> {
        self.scopes.get(index as usize)
    }

    /// What the source called the slots of this body's own environment — DR-0018.
    pub fn bindings(&self) -> &Rc<[Binding]> {
        &self.bindings
    }

    /// What this module takes from others — §16.2.1.3's `ImportEntries`.
    pub fn imports(&self) -> &[ImportEntry] {
        &self.imports
    }

    /// What others may take from it — §16.2.1.3's `ExportEntries`.
    pub fn exports(&self) -> &[ExportEntry] {
        &self.exports
    }

    /// The specifiers this module re-exports everything of — §16.2.1.3's `[[StarExportEntries]]`.
    #[must_use]
    pub fn star_exports(&self) -> &[Box<str>] {
        &self.star_exports
    }

    /// Add an instruction.
    pub(super) fn emit(&mut self, instruction: Instruction) {
        self.code.push(instruction);
    }

    /// Emit a jump whose target is not known yet.
    ///
    /// The target of a forward jump is decided by code that has not been compiled — that is what
    /// makes it forward — so a placeholder goes in and [`Chunk::patch`] replaces it once the
    /// destination exists.
    ///
    /// The placeholder is never seen, and not by luck: [`Unpatched`] is `#[must_use]` and is
    /// consumed by `patch`, so a jump left dangling is a warning and the gate denies warnings.
    /// It is `u32::MAX` anyway, so that if that ever stops being true the answer is a loud
    /// [`crate::vm::Fault::JumpOutOfRange`] rather than a quiet jump to the beginning.
    pub(super) fn emit_jump(&mut self, make: impl FnOnce(u32) -> Instruction) -> Unpatched {
        let at = self.code.len();
        self.emit(make(u32::MAX));
        Unpatched(at)
    }

    /// Point a jump at wherever the next instruction will go.
    pub(super) fn patch(&mut self, jump: Unpatched) -> Result<(), CompileError> {
        let target = u32::try_from(self.code.len()).map_err(|_| CompileError {
            kind: ErrorKind::TooLong,
            span: Span::new(0, 0),
        })?;
        self.patch_to(jump, target);
        Ok(())
    }

    /// Add a constant and answer where it went.
    ///
    /// Does not look for an existing equal constant. Deduplicating would need `SameValue`, which
    /// needs the heap, and would save a few words per chunk — an M8 experiment with a measurement,
    /// not a guess.
    pub(super) fn add_constant(&mut self, value: Value) -> Result<u32, CompileError> {
        let index = u32::try_from(self.constants.len());
        self.constants.push(value);
        // A chunk with more than four billion constants is not a program anyone wrote, and the
        // index has to fit somewhere. Refusing is the only answer that is neither a panic nor a
        // wrong constant.
        index.map_err(|_| CompileError {
            kind: ErrorKind::TooManyConstants,
            span: Span::new(0, 0),
        })
    }
}

/// Which of §13.3's three ways in a spread call takes.
///
/// One operand rather than a flag per way: `f(...a)`, `o.m(...a)` and `new f(...a)` differ only in
/// where the receiver comes from, and a second boolean beside the first would leave a fourth
/// combination that means nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpreadCall {
    /// `f(...a)` — no receiver.
    Plain,
    /// `o.m(...a)` — the receiver sits under the callee.
    Method,
    /// `new f(...a)` — the receiver is made by the call.
    Construct,
    /// `super(...a)` — the callee is the running function's `[[Prototype]]`, not on the stack.
    Super,
}

/// The same jump, pointed somewhere else.
///
/// Exhaustive on purpose. Written with a catch-all arm it silently did nothing to a `PushHandler`,
/// whose target then stayed at the unpatched placeholder — so every `try` jumped off the end of
/// its chunk. Listing every instruction means the next one that carries a target cannot be
/// forgotten here: leaving it out is a compile error.
pub(super) fn retarget(instruction: Instruction, target: u32) -> Instruction {
    match instruction {
        Instruction::Jump(_) => Instruction::Jump(target),
        Instruction::JumpIfFalse(_) => Instruction::JumpIfFalse(target),
        Instruction::JumpIfTrue(_) => Instruction::JumpIfTrue(target),
        Instruction::JumpKeeping(condition, _) => Instruction::JumpKeeping(condition, target),
        Instruction::PushHandler(_) => Instruction::PushHandler(target),
        // Not a jump. An `Unpatched` can only ever name one, since `emit_jump` is the only way
        // to make one — so these are unreachable, and are listed rather than swept into a
        // catch-all so that a new jump cannot hide among them.
        Instruction::ToNumeric
        | Instruction::Step(_)
        | Instruction::PushScope(_)
        | Instruction::CopyScope(_)
        | Instruction::PushWithScope(_)
        | Instruction::LoadName(_)
        | Instruction::StoreName(_)
        | Instruction::TypeofName(_)
        | Instruction::DeleteName(_)
        | Instruction::DynamicImport
        | Instruction::LoadNameForCall(_)
        | Instruction::Constant(_)
        | Instruction::RegExpLiteral
        | Instruction::Unary(_)
        | Instruction::Binary(_)
        | Instruction::Pop
        | Instruction::Stringify
        | Instruction::LoadWellKnown(_)
        | Instruction::RequireObject
        | Instruction::RequireCoercible
        | Instruction::CopyRest(_)
        | Instruction::LoadVariable(_, _)
        | Instruction::StoreVariable(_, _)
        | Instruction::Uninitialise(_)
        | Instruction::Initialise(_)
        | Instruction::ThrowImmutableAssignment
        | Instruction::EnumerateProperties
        | Instruction::EnumerateNext(_, _)
        | Instruction::LoadGlobal(_)
        | Instruction::StoreGlobal(_)
        | Instruction::TypeofGlobal(_)
        | Instruction::DeclareGlobal { .. }
        | Instruction::PrepareKey { .. }
        | Instruction::CheckGlobalVar(_)
        | Instruction::CheckGlobalFunction(_)
        | Instruction::DeleteGlobal(_)
        | Instruction::SetCompletion
        | Instruction::CompletionUndefined
        | Instruction::Throw
        | Instruction::PopHandler
        | Instruction::MakeFunction(_)
        | Instruction::Call(_)
        | Instruction::CallDirectEval(_)
        | Instruction::CallDirectEvalMethod(_)
        | Instruction::Construct(_)
        | Instruction::CallMethod(_)
        | Instruction::CallTail(_)
        | Instruction::CallTailMethod(_)
        | Instruction::LoadThis
        | Instruction::LoadNewTarget
        | Instruction::LoadThrough(_)
        | Instruction::ResolveName(_)
        | Instruction::StoreThrough(_)
        | Instruction::SettleKey
        | Instruction::NameFunction(_)
        | Instruction::ImportMeta
        | Instruction::TemplateObject(_)
        | Instruction::SuperCall(_)
        | Instruction::MakeMethod(_)
        | Instruction::NewPrivateName(_)
        | Instruction::SetLiteralPrototype
        | Instruction::DefinePrivateField
        | Instruction::AddPrivateMethod
        | Instruction::AddPrivateAccessor
        | Instruction::GetPrivate
        | Instruction::SetPrivate
        | Instruction::HasPrivate
        | Instruction::ThrowSuperDelete
        | Instruction::InheritHome
        | Instruction::LoadSuperBase
        | Instruction::GetSuperProperty
        | Instruction::SetSuperProperty
        | Instruction::BindThis { .. }
        | Instruction::LoadThisBinding { .. }
        | Instruction::CompleteDerivedReturn(_)
        | Instruction::Duplicate
        | Instruction::Return
        | Instruction::Yield
        | Instruction::YieldDelegated
        | Instruction::ResumeMode
        | Instruction::GeneratorStart
        | Instruction::PopScope
        | Instruction::Await
        | Instruction::AsyncReject
        | Instruction::GetAsyncIterator
        | Instruction::ThrowNoThrowMethod
        | Instruction::NewObject
        | Instruction::NewArray(_)
        | Instruction::DuplicateTop(_)
        | Instruction::Bury(_)
        | Instruction::DefineField
        | Instruction::DefineGetter
        | Instruction::DefineSetter
        | Instruction::SpreadProperties
        | Instruction::CallSpread(_)
        | Instruction::MakeClass { .. }
        | Instruction::ClassPrototype
        | Instruction::DefineClassMethod(_)
        | Instruction::GetProperty
        | Instruction::SetProperty
        | Instruction::DeleteProperty
        | Instruction::HasProperty
        | Instruction::Instanceof => instruction,
    }
}