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
//! §13 — expressions, each of which leaves exactly one value on the stack.
//!
//! The one invariant every function here keeps: compiling an expression adds one value and
//! consumes whatever it needed. That is what lets a statement be stack-neutral by construction
//! and what [`crate::vm::Fault::UnbalancedStack`] checks at the end of a chunk.
use super::function::{Keep, Naming};
use super::{
CompileError, Compiler, ErrorKind, Instruction, MAX_EXPRESSION_DEPTH, ShortCircuit, unsupported,
};
use crate::ast::ArrayElement;
use crate::ast::MethodKind;
use crate::ast::PropertyKey as AstPropertyKey;
use crate::ast::{
Argument, AssignmentOperator, AssignmentTarget, BinaryOperator, Expr, ExprKind,
LogicalOperator, PropertyDefinition, TemplateElement, TemplateLiteral, UnaryOperator,
UpdateOperator,
};
use crate::span::Span;
use crate::value::Value;
/// §8.6.3 `IsAnonymousFunctionDefinition` — whether this expression is a function with no name.
///
/// The three productions the clause covers, and each has its own reason for the guard: a
/// `FunctionExpression` and a `ClassExpression` may carry a name and keep it, and an arrow has no
/// production for one so it is always anonymous. Anything else is not a function definition at all
/// and is left alone — `{ [k]: someOtherFunction }` does not rename what it was given.
pub(super) fn is_anonymous_definition(value: &Expr) -> bool {
match &value.kind {
ExprKind::Function(function) => function.name.is_none(),
ExprKind::Class(class) => class.name.is_none(),
ExprKind::Arrow(_) => true,
_ => false,
}
}
impl Compiler<'_> {
/// Compile `expression` so that it leaves exactly one value on the stack.
pub(super) fn expression(&mut self, expression: &Expr) -> Result<(), CompileError> {
let span = expression.span;
// The tree is walked by recursing, so a nested expression is as deep as it is nested and
// the Rust stack is what runs out. Counting is DR-0006's argument again: a count is
// portable and a measurement of the remaining stack is not.
//
// One increment and one decrement, with the refusal *between* them rather than beside
// them. Written with an early return it needed a second decrement on the error path — a
// line that could be anything at all, since a failed compilation is discarded whole and
// nothing ever reads the depth again.
self.depth += 1;
let compiled = if self.depth > MAX_EXPRESSION_DEPTH {
Err(CompileError {
kind: ErrorKind::TooDeep,
span,
})
} else {
self.expression_inner(expression, span)
};
self.depth -= 1;
compiled
}
/// Compile `expression`, with the depth already counted.
fn expression_inner(&mut self, expression: &Expr, span: Span) -> Result<(), CompileError> {
match &expression.kind {
// The literals. `undefined` is not among them because it is not a literal: it is an
// identifier that happens to resolve to a property of the global object, which is why
// `void 0` exists and why minifiers use it.
ExprKind::Null => self.constant(Value::Null),
ExprKind::Boolean(value) => self.constant(Value::Boolean(*value)),
ExprKind::Number(value) => self.constant(Value::Number(*value)),
ExprKind::String(units) => {
let id = self.heap.new_string(units.to_vec());
self.constant(Value::String(id))
}
ExprKind::Unary { operator, argument } => {
// §13.5.1 — `delete` does not evaluate its operand to a *value*; it wants the
// reference. For a property that is the base and the key, and for anything else
// there is nothing to delete.
if *operator == UnaryOperator::Delete {
return self.delete(argument);
}
// §13.5.1.1 step 2 — `typeof` is the one operator that takes an *unresolvable*
// reference and answers instead of throwing. `typeof JSON !== "undefined"` is
// how a program asks whether something exists at all, and it is in test262's own
// harness; evaluating the operand first would turn the question into the very
// error it was written to avoid. Only a bare name can be unresolvable, so only a
// bare name takes this path.
if *operator == UnaryOperator::Typeof
&& let ExprKind::Identifier(name) = &argument.kind
&& (self.binding(name).is_none() || self.names_are_dynamic())
{
// §10.2.11 step 19 — a `typeof arguments` is a read like any other, and this
// path does not go through `load_name`. Left out, the name resolves to a slot
// the call was never asked to fill, and `with (o) { typeof arguments }` answers
// `"undefined"` where the object is right there.
let binding = self.binding(name);
self.note_arguments(name, binding);
let index = self.name(name)?;
// §14.11 — inside a `with` even a name the compiler *can* place takes this
// path, because the object may have it and the object is asked first.
let sought = match self.names_are_dynamic() {
true => Instruction::TypeofName(index),
false => Instruction::TypeofGlobal(index),
};
self.chunk.emit(sought);
return Ok(());
}
self.expression(argument)?;
self.chunk.emit(Instruction::Unary(*operator));
Ok(())
}
// §13.15 — a binary operator, and its whole left-leaning chain at once.
//
// `a + b + c` is `((a + b) + c)`, so a chain is a tree as deep as it is long, and
// minified code chains thousands of terms. Recursing once per term would run out of
// Rust stack long before the source ran out of terms — which is exactly how the
// parser handles the same shape, with a loop rather than recursion (DR-0006).
//
// So the left spine is walked flat: down to the innermost operand, then back out
// emitting each right operand and its operator. The order is unchanged, which is what
// matters — §13.15.1 evaluates the left operand first, and that is what the emitted
// order still says.
ExprKind::Binary { .. } => {
let mut spine = Vec::new();
let mut innermost = expression;
while let ExprKind::Binary {
operator,
left,
right,
} = &innermost.kind
{
spine.push((*operator, &**right));
innermost = left;
}
self.expression(innermost)?;
for (operator, right) in spine.into_iter().rev() {
self.expression(right)?;
// Two of them are not value operations: they ask an object a question
// rather than converting one, so each is an instruction of its own rather
// than a row in `apply_binary`.
match operator {
BinaryOperator::In => self.chunk.emit(Instruction::HasProperty),
BinaryOperator::Instanceof => self.chunk.emit(Instruction::Instanceof),
_ => self.chunk.emit(Instruction::Binary(operator)),
}
}
Ok(())
}
// §13.13 and §13.14 — the operators that may not evaluate their right operand at all.
// The left one is evaluated, looked at, and *kept* if it decides the answer: `a || b` is
// `a` itself when `a` is truthy, not `true`.
ExprKind::Logical {
operator,
left,
right,
} => {
let condition = match operator {
LogicalOperator::And => ShortCircuit::WhenFalsy,
LogicalOperator::Or => ShortCircuit::WhenTruthy,
LogicalOperator::NullishCoalescing => ShortCircuit::WhenNotNullish,
};
self.expression(left)?;
let over_the_right = self
.chunk
.emit_jump(|target| Instruction::JumpKeeping(condition, target));
self.expression(right)?;
self.chunk.patch(over_the_right)
}
// §13.14 — the conditional operator, where the test *is* thrown away and exactly one of
// the two branches runs.
ExprKind::Conditional {
test,
consequent,
alternate,
} => {
self.expression(test)?;
let to_alternate = self.chunk.emit_jump(Instruction::JumpIfFalse);
self.expression(consequent)?;
let past_the_alternate = self.chunk.emit_jump(Instruction::Jump);
self.chunk.patch(to_alternate)?;
self.expression(alternate)?;
self.chunk.patch(past_the_alternate)
}
// §13.16 — the comma operator: evaluate each, keep the last. Every earlier value is
// discarded, which is the only reason it is ever written.
ExprKind::Sequence(expressions) => {
let Some((last, earlier)) = expressions.split_last() else {
// A comma expression with no operands has no production. The parser cannot build
// one; if the tree ever holds one, an empty chunk would leave the VM with an
// unbalanced stack, so saying so here is the honest answer.
return Err(unsupported("an empty comma expression", span));
};
for expression in earlier {
self.expression(expression)?;
self.chunk.emit(Instruction::Pop);
}
self.expression(last)
}
// §13.2.5 — an object literal.
ExprKind::Object(properties) => self.object_literal(properties, span),
// §13.3.2 and §13.3.3 — `o.x` and `o[k]`. The name is a constant where the key is
// an expression, which is the whole difference between the two forms.
ExprKind::Member { .. } | ExprKind::ComputedMember { .. } => {
let reference = self.property_reference(expression, Keep::Nothing)?;
self.chunk.emit(reference.get());
Ok(())
}
// Everything else, named as the specification names it so that the message says which
// clause is missing rather than which Rust variant.
// §13.1.3 — a name is a slot when the compiler can place it and a property of the
// global object when it cannot. Which of the two is decided here; whether the global
// is *there* is decided at run time, because a script can make one at any moment.
ExprKind::Identifier(name) => self.load_name(name),
// §13.2.1 — `this`, which the call decided and the frame is holding, unless DR-0015
// moved it into a binding because a derived constructor can change it.
ExprKind::This => {
self.load_this();
Ok(())
}
// §13.10.1 — `#x in o`, the one way to ask whether an object carries a private field
// without §7.3.31's TypeError. The name is not an expression and has no production that
// would let it stand alone, which is why it is part of this node.
ExprKind::PrivateIn { name, object } => {
self.expression(object)?;
self.load_private_name(name)?;
self.chunk.emit(Instruction::HasPrivate);
Ok(())
}
// §12.9.3's `BigIntLiteral`, read at compile time and carried as a constant — the same
// treatment a Number literal gets, and for the same reason: the digits do not change.
ExprKind::BigInt(literal) => {
let Some(value) =
crate::bigint::BigInt::from_digits(&literal.digits, literal.radix)
else {
// The lexer read these digits *in this radix*, so a refusal here is a magnitude
// past what the engine will hold rather than a character that is not a digit.
return Err(unsupported("a BigInt literal this large", span));
};
let id = self.heap.new_bigint(value);
self.constant(Value::BigInt(id))
}
ExprKind::Call {
optional,
callee,
arguments,
} => self.call(callee, arguments, *optional, span),
// §13.3.5 — `new f(a)`. The callee is an ordinary expression and never a method:
// `new o.m()` constructs with `o.m`, and the `o` plays no part.
ExprKind::New { callee, arguments } => {
self.expression(callee)?;
// §13.3.5 with a spread: gathered into one array and expanded by the call, exactly as
// an ordinary call's are. `new` differs only in who makes the receiver.
if arguments
.iter()
.any(|argument| matches!(argument, Argument::Spread(_)))
{
self.argument_array(arguments)?;
self.chunk.emit(Instruction::CallSpread(
crate::compile::chunk::SpreadCall::Construct,
));
return Ok(());
}
for argument in arguments.iter() {
let Argument::Value(value) = argument else {
return Err(unsupported("a spread argument", span));
};
self.expression(value)?;
}
let count = u32::try_from(arguments.len()).map_err(|_| CompileError {
kind: ErrorKind::TooLong,
span,
})?;
self.chunk.emit(Instruction::Construct(count));
Ok(())
}
// §13.4 — `++a` and `a++`, which differ in what they *evaluate to* and in nothing
// else. Both read, coerce, add one and write back.
ExprKind::Update {
operator,
prefix,
argument,
} => self.update(*operator, *prefix, argument, span),
// §13.15 — assignment, whose *value* is the value assigned. That is why the store
// leaves it on the stack rather than taking it: `a = b = 1` and `f(a = 1)` both
// need it.
ExprKind::Assignment {
operator,
target,
value,
} => {
let AssignmentTarget::Simple(target) = &**target else {
// §13.15.5 — a destructuring assignment. Only `=` has one: `[a] += b` is a
// Syntax Error the parser has already refused, so there is no operator to
// apply and the value is simply taken apart.
let AssignmentTarget::Pattern(pattern) = &**target else {
return Err(unsupported("a destructuring assignment", span));
};
self.expression(value)?;
// §13.15.2 — the *value* of the assignment is what was assigned, and a
// pattern consumes it. So a copy is kept underneath for whatever wanted the
// expression's value.
self.chunk.emit(Instruction::Duplicate);
return self.assign_pattern(pattern, span);
};
if let ExprKind::Member { .. } | ExprKind::ComputedMember { .. } = &target.kind {
return self.assign_to_property(*operator, target, value, span);
}
let ExprKind::Identifier(name) = &target.kind else {
return Err(unsupported(
"an assignment to something that is not a name",
target.span,
));
};
match compound_operator(*operator) {
// `a = v`, which is one of §8.6.3's named positions: `f = function () {}` gives
// the function the name `f`. The three *logical* forms are named positions too
// — see the arm below — and only the arithmetic ones are not, because
// `f += function () {}` has no production that mentions `NamedEvaluation`.
None if *operator == AssignmentOperator::Assign => {
self.named_evaluation(name, value)?;
}
// `a += v` is `a = a + v`, with `a` read once — which matters not at all for
// a slot and matters a great deal for `o[f()] += 1`, where the property key
// is evaluated once. The shape is the same either way.
//
// The read is an ordinary one, so `undeclared += 1` is a ReferenceError from
// the *read* — §13.15.2 evaluates the target's value before the operator.
Some(binary) => {
// §13.15.2 evaluates the target **reference** first, reads through it,
// evaluates the value, and writes back through the *same* reference. When
// names are dynamic that is not the same as resolving twice: a getter on a
// `with` object may delete the property between the two, and the second
// resolution then finds a different binding — so `with (o) { x *= 3 }` wrote
// to whatever `x` meant outside `o`.
//
// A slot needs none of this. The compiler resolved it once already, and
// nothing a right-hand side does can change which slot a depth and an index
// name.
if self.names_are_dynamic() {
let index = self.name(name)?;
self.chunk.emit(Instruction::ResolveName(index));
self.chunk.emit(Instruction::LoadThrough(index));
self.expression(value)?;
self.chunk.emit(Instruction::Binary(binary));
self.chunk.emit(Instruction::StoreThrough(index));
return Ok(());
}
self.load_name(name)?;
self.expression(value)?;
self.chunk.emit(Instruction::Binary(binary));
}
// §13.15.2 — `a ||= v` and its two siblings assign *only* when the short circuit
// does not fire, so the store is inside the jump rather than after the match. The
// value the whole expression answers is the old one when it fires and the new one
// when it does not, which is exactly what `JumpKeeping` leaves behind.
None if short_circuit_operator(*operator).is_some() => {
let condition = match short_circuit_operator(*operator) {
Some(condition) => condition,
// Unreachable: the guard above just asked. Written out rather than
// unwrapped because a panic here would be an engine bug the types cannot
// encode, and there is a real answer to give instead.
None => return Err(unsupported("a logical assignment", span)),
};
self.load_name(name)?;
let over_the_store = self
.chunk
.emit_jump(|target| Instruction::JumpKeeping(condition, target));
// No `Pop` for the old value: `JumpKeeping` keeps it only on the path that
// jumps, and consumes it on the one that falls through — which is the whole
// reason `a || b` answers `b` rather than leaving both behind.
//
// §13.15.2's evaluation for the three logical forms has a step 5 that the
// arithmetic ones do not: `IsAnonymousFunctionDefinition(rhs)` and
// `IsIdentifierRef(lhs)` together make this a `NamedEvaluation` position,
// so `value ||= () => {}` names the arrow `"value"`. Grouping it with
// `+=` because both are spelled "compound" is the mistake to avoid — the
// list §8.6.3 draws on is per-production, not per-category.
self.named_evaluation(name, value)?;
self.store_name(name)?;
return self.chunk.patch(over_the_store);
}
None => return Err(unsupported("a logical assignment", span)),
}
self.store_name(name)
}
// §13.2.4 — an array literal. The length is the element count *including holes*, so
// it is known here and set once; each element that was written is then defined at its
// own index, and each one that was not is simply never defined. That absence is what
// a hole is: `[, 1]` has a length of 2 and one property, and `0 in [, 1]` is false
// where `0 in [undefined, 1]` is true.
ExprKind::Array(elements) => {
// A spread makes the length unknowable here — `[...a]` is as long as `a` turns out
// to be — so the count moves into a slot and the whole literal is built by
// running rather than by placing. Kept apart from the ordinary path because that
// one knows its length and should go on saying so.
if elements
.iter()
.any(|element| matches!(element, ArrayElement::Spread { .. }))
{
return self.spread_array(elements, span);
}
let count = u32::try_from(elements.len()).map_err(|_| CompileError {
kind: ErrorKind::TooLong,
span,
})?;
self.chunk.emit(Instruction::NewArray(count));
for (at, element) in elements.iter().enumerate() {
let value = match element {
ArrayElement::Hole => continue,
ArrayElement::Spread { .. } => {
return Err(unsupported("a spread element", span));
}
ArrayElement::Value(value) => value,
};
// The index as a *name*, because that is what a property key is: an array
// holds `"0"` and not `0`, which is why `a["0"]` and `a[0]` are one property.
let id = self
.heap
.new_string(at.to_string().encode_utf16().collect());
self.constant(Value::String(id))?;
self.expression(value)?;
self.chunk.emit(Instruction::DefineField);
}
Ok(())
}
// §15.2.5 — a function expression. The object is made where the expression is
// *evaluated*, so a `function` keyword inside a loop makes one object per iteration.
// Unnamed unless something above named it; §8.6.3 reaches only the positions that do,
// and [`Compiler::named_evaluation`] is where each of those is listed.
ExprKind::Function(function) => {
self.make_function_expression(function, Naming::default(), span)
}
// §15.3 — an arrow, which is a function expression that keeps the `this` around it.
ExprKind::Arrow(arrow) => self.make_arrow(arrow, Naming::default(), span),
// §15.7.12 — an expression leaves the constructor where it was evaluated. Its own name,
// if it has one, binds only inside the body and is not created yet.
ExprKind::Class(class) => self.class(class, Naming::default(), span),
ExprKind::Template(template) => self.template(template),
ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi, span),
// §12.9.5 read the literal's *shape* without reading it as a pattern, so the source
// and flags travel as text and are parsed when the instruction runs. That is also when
// a bad pattern becomes the SyntaxError §22.2.3.1 throws.
ExprKind::RegExp(literal) => {
// §22.2.1.1's early errors, checked **here** rather than when the literal is
// evaluated. A pattern that does not parse makes the whole script a SyntaxError,
// so a bad one inside a branch that never runs still stops the program — which is
// the difference between an early error and an ordinary one.
//
// A pattern this engine has not *built* is a different answer from one the
// specification forbids, even though a script sees the same SyntaxError for both:
// the first is a gap and the second is this engine agreeing with the standard.
// Only the second may be judged as an early error — see `regexp::Error`.
let refused = |error: crate::regexp::Error| CompileError {
kind: match error.unimplemented {
true => ErrorKind::Unsupported(error.message),
false => ErrorKind::BadPattern(error.message),
},
span,
};
let flags = crate::regexp::Flags::parse(&literal.flags).map_err(refused)?;
crate::regexp::parse(&literal.body, flags).map_err(refused)?;
let source = self
.heap
.new_string(literal.body.encode_utf16().collect::<Vec<_>>());
self.constant(Value::String(source))?;
let spelled = self
.heap
.new_string(literal.flags.encode_utf16().collect::<Vec<_>>());
self.constant(Value::String(spelled))?;
self.chunk.emit(Instruction::RegExpLiteral);
Ok(())
}
// §27.7.5.3 — `await x` is a suspension like `yield`, and an expression like it: what
// the promise settles with is what it evaluates to.
ExprKind::Await(operand) => {
// §16.2.1.5.3 — a module may `await` at its top level, and a module that does is
// **asynchronous**: its evaluation answers a promise and everything importing it
// waits. The instruction below needs an execution to park, and a module body that
// is not async has none — so meeting one here is how `compile_module` learns that it
// has to give the body that execution, and it compiles the body again.
//
// Recorded rather than refused, and recorded rather than *decided*: whether a body
// contains a top-level `await` is a question about every expression in it, and this
// walk is already the one that visits them all. A second walk beside it would be a
// second answer to keep in step.
if !self.chunk.is_async {
self.saw_top_level_await = true;
}
self.expression(operand)?;
self.chunk.emit(Instruction::Await);
Ok(())
}
// §15.5.5 `YieldExpression : yield AssignmentExpression`. A bare `yield` yields
// `undefined`, which is the first production's whole meaning — and `yield` is an
// *expression*, so what a resumption sends back is what it evaluates to.
ExprKind::Yield(yielded) => {
// §27.5.3.7 step 7 — `yield*` is a loop rather than an expression, and a long
// enough one to want its own file.
if let (true, Some(operand)) = (yielded.delegate, &yielded.argument) {
return self.yield_delegated(operand);
}
match &yielded.argument {
Some(argument) => self.expression(argument)?,
None => {
let index = self.chunk.add_constant(Value::Undefined)?;
self.chunk.emit(Instruction::Constant(index));
}
}
// §27.6.3.8 step 5 — `AsyncGeneratorYield` **awaits the value before yielding it**,
// which an ordinary generator's §27.5.3.7 does not. So `yield Promise.reject(e)` in
// an `async function*` rejects the promise `next()` answered, where without this
// the promise object itself is handed out as the value and the rejection is never
// seen. `yield` with no argument awaits `undefined`, which is a job and not a
// no-op: it is a turn of the queue whose order a program can observe.
//
// Asked of asynchrony **alone**, with no test that this is a generator: `yield` is
// an expression only where §15.5's `[Yield]` parameter is set, which is a generator
// body and nothing else — an arrow written inside one does not inherit it, and a
// field initialiser does not either. So a chunk compiling this is always a
// generator, and a second half to the condition would be one no input could flip.
if self.chunk.is_async() {
self.chunk.emit(Instruction::Await);
}
self.chunk.emit(Instruction::Yield);
// §27.5.1.3 — `gen.return(v)` resumes the body *at this `yield`* with a return
// completion, so every `finally` between here and the end runs and every open
// iterator is closed. That is exactly what a `return` written on this line would
// emit, and `unwind_across` is the same walk it uses.
self.chunk.emit(Instruction::ResumeMode);
let carry_on = self.chunk.emit_jump(Instruction::JumpIfFalse);
// The value the resumption sent *is* the value returned, and it is already where a
// `return`'s operand would be.
self.unwind_across(super::statement::Exit::Return)?;
self.chunk.emit(Instruction::Return);
self.chunk.patch(carry_on)?;
Ok(())
}
ExprKind::Super => Err(unsupported("super", span)),
// §13.3.12 — `GetNewTarget()`, which the running call decided and which the parser has
// already refused anywhere there is no call to have decided it.
ExprKind::NewTarget => {
self.chunk.emit(Instruction::LoadNewTarget);
Ok(())
}
// §13.3.12. The parser has already refused one outside a Module (§13.3.12's early
// error), so reaching here means the goal symbol allows it.
ExprKind::ImportMeta => {
self.chunk.emit(Instruction::ImportMeta);
Ok(())
}
// §13.3.10 — the specifier is an expression, which is the whole point of the form. The
// second argument is §13.3.10's `options`, and ViperJS has no import attribute it acts
// on: it is evaluated for its effects and dropped, because a getter written there must
// still run.
ExprKind::ImportCall { specifier, options } => {
self.expression(specifier)?;
if let Some(options) = options {
self.expression(options)?;
self.chunk.emit(Instruction::Pop);
}
self.chunk.emit(Instruction::DynamicImport);
Ok(())
}
// §13.3.9 — the wrapper is where the short circuit lands, and the only thing it compiles
// to is that landing site. Everything else is the ordinary chain underneath it.
ExprKind::OptionalChain(inner) => {
self.chains.push(Vec::new());
let compiled = self.expression(inner);
let jumps = self.chains.pop().unwrap_or_default();
compiled?;
for jump in jumps {
self.chunk.patch(jump)?;
}
Ok(())
}
}
}
/// §13.2.5 — an object literal.
///
/// Every property is *defined* rather than assigned, so nothing inherited can refuse one and
/// no setter can intercept it. Its own method rather than an arm of [`Compiler::expression`]
/// because that function recurses once per level of an expression, and every arm's locals are
/// part of every frame: a long `a + b + c` chain is as deep as it is long, and the frame it
/// walks with should be no larger than it has to be.
/// Kept out of line, deliberately.
///
/// [`Compiler::expression_inner`] recurses, so its stack frame is paid once per level of a
/// nested expression — and DR-0006's depth limit bounds the levels, not the bytes. A helper
/// inlined into it adds its locals to *every* level, which is how a change that touched
/// neither the limit nor the recursion overflowed a smaller stack than this machine's.
#[inline(never)]
fn object_literal(
&mut self,
properties: &[PropertyDefinition],
span: Span,
) -> Result<(), CompileError> {
self.chunk.emit(Instruction::NewObject);
for property in properties.iter() {
// §13.2.5 — `...o` contributes properties rather than *a* property, so it has no key to
// push and nothing for the match below to describe. Its own enumerable properties are
// copied onto the literal being built, by the same walk §14.3.3's object rest uses.
if let PropertyDefinition::Spread { value, .. } = property {
self.expression(value)?;
self.chunk.emit(Instruction::SpreadProperties);
continue;
}
// B.3.1 — `__proto__: v` sets the prototype rather than making a property, and this is
// the one Annex B rule ViperJS implements (DR-0008 says why). The production is exactly
// `PropertyName : AssignmentExpression`, so every other way of writing the same spelling
// is an ordinary property and those exclusions are the whole difficulty:
//
// `{ __proto__: p }` sets the prototype
// `{ '__proto__': p }` sets it too — a String literal key has the same StringValue
// `{ ['__proto__']: p }` does **not**: a computed key is a different production
// `{ __proto__ }` does not: a shorthand is a different production
// `{ __proto__() {} }` does not: a method is a different production
if let PropertyDefinition::KeyValue { key, value } = property
&& is_proto_key(key)
{
self.expression(value)?;
self.chunk.emit(Instruction::SetLiteralPrototype);
continue;
}
// §13.2.5's four productions that make a property, reduced to a key and something to
// put under it. A shorthand is `{a: a}` — the name is both — and a method is a
// function expression with the property's name; only an *accessor* is a different
// kind of property rather than a different way of writing a value.
let (key, value, accessor) = match property {
PropertyDefinition::KeyValue { key, value } => (key, Element::Value(value), None),
PropertyDefinition::Shorthand { name, span } => (
&AstPropertyKey::Identifier(name.clone()),
Element::Name(name, *span),
None,
),
PropertyDefinition::Method {
key,
kind,
function,
} => (key, Element::Function(function), Some(*kind)),
// §13.2.5.1 — `{a = 1}` is a Syntax Error wherever the literal stays a literal,
// and the parser has already refused every position where it does. Reaching it
// here would mean a tree no source produces.
PropertyDefinition::ShorthandWithDefault { .. } => {
return Err(unsupported("a shorthand with an initializer", span));
}
// Handled above: a spread has no key, so it cannot produce the triple this match is
// for. Listed rather than swept into a catch-all so that a fourth kind of property
// cannot arrive here unnoticed.
PropertyDefinition::Spread { .. } => {
return Err(unsupported("a spread in an object literal", span));
}
};
// A key is pushed once and used twice for an accessor pair, so it is emitted here
// whatever kind of property follows.
match key {
AstPropertyKey::Identifier(name) => {
let units: Vec<u16> = name.encode_utf16().collect();
let id = self.heap.new_string(units);
self.constant(Value::String(id))?;
}
AstPropertyKey::String(units) => {
let id = self.heap.new_string(units.to_vec());
self.constant(Value::String(id))?;
}
// §13.2.5.5 — a numeric key becomes the String `ToString` writes, at
// compile time because the number is already known: `{1.0: x}` and
// `{1: x}` are one property, and `{1e21: x}` is the key `"1e+21"`.
AstPropertyKey::Number(number) => {
let value = Value::Number(*number);
let id = value
.to_string(self.heap)
.map_err(|_| unsupported("a key that cannot be written down", span))?;
self.constant(Value::String(id))?;
}
// §13.2.5.5 — evaluating a `PropertyName` *is* `ToPropertyKey`, and it happens
// before the value beside it. Settled here rather than at the define, so a key
// whose `toString` has an effect has it in the order the clause writes and exactly
// once — and so that the naming below has a key to read rather than an expression's
// answer.
AstPropertyKey::Computed(expression) => {
self.expression(expression)?;
self.chunk.emit(Instruction::SettleKey);
}
// §13.2.5.1 — a numeric `PropertyName` is its *ToString*, and a BigInt's is its
// digits without the `n`. So `{ 1n: 'a' }` and `{ '1': 'a' }` name one property.
AstPropertyKey::BigInt(literal) => {
let Some(value) =
crate::bigint::BigInt::from_digits(&literal.digits, literal.radix)
else {
return Err(unsupported("a BigInt key this large", span));
};
// A key is the *decimal* spelling of the value, so one this engine cannot divide
// has no name to be. Refused beside the size check above rather than spelled
// `"0"`, which would make two different keys the same property.
let Ok(spelled) = value.to_digits(10) else {
return Err(unsupported("a BigInt property key this large", span));
};
let id = self.name_of(&spelled);
self.constant(Value::String(id))?;
}
AstPropertyKey::Private(_) => {
return Err(unsupported("a private key", span));
}
}
match value {
Element::Value(expression) => match key {
// §13.2.5.5 — a property definition is one of §8.6.3's named positions, so
// `{ a: function () {} }` and `{ a: () => {} }` are both called `a`.
AstPropertyKey::Identifier(name) => {
self.named_evaluation(name, expression)?;
}
// Every other key shape is the same named position and none of them was
// reaching it: a computed key is not known here, and a string, numeric or
// BigInt one is known and was being thrown away. Still only for an *anonymous*
// definition — `{ [k]: function named() {} }` keeps the name it wrote.
_ if is_anonymous_definition(expression) => {
self.expression(expression)?;
self.chunk
.emit(Instruction::NameFunction(super::NamePrefix::Plain));
}
_ => self.expression(expression)?,
},
Element::Name(name, at) => {
let _ = at;
self.load_name(name)?;
}
// §15.4.5 `MethodDefinitionEvaluation` — a *method* gets `MakeMethod` and a function
// written as a value does not: `{ m() { return super.x; } }` is legal and
// `{ m: function () { return super.x; } }` is a Syntax Error, which is the only place
// the two shapes differ at all. The object is under the key, two down.
Element::Function(function) => {
// §10.2.9 — a literal's method is named by its key, and an accessor carries the
// prefix. A **computed** key is not known here, so the name is set at run time
// from the key sitting under the function; see `Instruction::NameFunction`.
let at_run_time = match accessor {
Some(MethodKind::Get) => super::NamePrefix::Get,
Some(MethodKind::Set) => super::NamePrefix::Set,
_ => super::NamePrefix::Plain,
};
// §15.4.5 — a literal's method is not a constructor either, which is the one
// thing that distinguishes `{ m() {} }` from `{ m: function () {} }` beyond the
// name. `new o.m()` is a TypeError for the first and an object for the second.
self.make_method_function(function, Naming::default(), true, span)?;
self.chunk.emit(Instruction::MakeMethod(2));
self.chunk.emit(Instruction::NameFunction(at_run_time));
}
}
match accessor {
// §15.4.5 — a getter and a setter are *halves* of one property, so defining one
// must not wipe the other. That is `DefineOwnProperty` with only the half that
// was written, which is not what `CreateDataProperty` does.
Some(MethodKind::Get) => self.chunk.emit(Instruction::DefineGetter),
Some(MethodKind::Set) => self.chunk.emit(Instruction::DefineSetter),
// §15.4.4's ordinary method is a data property like any other. What makes it a
// method rather than a function *expression* is the `name` and the missing
// `prototype` — both of which it has: `({ m(){} }).m.name` is `"m"` and its
// `prototype` is `undefined`. The comment here said "neither is here yet".
_ => self.chunk.emit(Instruction::DefineField),
}
}
Ok(())
}
/// §13.3.11 — a tagged template, which is a call whose first argument is the template object.
///
/// `f\`a${b}c\`` is `f(templateObject, b)`, and the tag is called as a *method* when it is written
/// as one: `` o.m`x` `` has `o` for its receiver, exactly as `o.m()` would. So this is the ordinary
/// call path with an argument list nobody wrote.
fn tagged_template(
&mut self,
tag: &Expr,
quasi: &TemplateLiteral,
span: Span,
) -> Result<(), CompileError> {
let method = matches!(
tag.kind,
ExprKind::Member { .. } | ExprKind::ComputedMember { .. }
);
if method {
let reference = self.property_reference(tag, Keep::Receiver)?;
self.chunk.emit(reference.get());
} else {
self.expression(tag)?;
}
// §13.2.8.3's object first, then the substitutions in order — which is the argument list
// §13.3.11 builds, and the reason a tag with no substitutions still takes one argument.
let index = self.template_object(quasi, span)?;
self.chunk.emit(Instruction::TemplateObject(index));
for expression in quasi.expressions.iter() {
self.expression(expression)?;
}
let count = u32::try_from(quasi.expressions.len() + 1).map_err(|_| CompileError {
kind: ErrorKind::TooLong,
span,
})?;
self.chunk.emit(match method {
true => Instruction::CallMethod(count),
false => Instruction::Call(count),
});
Ok(())
}
/// File this site's template strings and answer their index.
///
/// Interned, because the components of a template are fixed text and the same one may appear in
/// a hundred sites — and because the key a property is filed under has to be the interned one.
fn template_object(
&mut self,
quasi: &TemplateLiteral,
span: Span,
) -> Result<u32, CompileError> {
let mut cooked = Vec::with_capacity(quasi.quasis.len());
let mut raw = Vec::with_capacity(quasi.quasis.len());
for element in quasi.quasis.iter() {
cooked.push(element.cooked.as_ref().map(|units| self.heap.intern(units)));
raw.push(self.heap.intern(&element.raw));
}
let index = u32::try_from(self.chunk.templates.len()).map_err(|_| CompileError {
kind: ErrorKind::TooLong,
span,
})?;
self.chunk
.templates
.push(crate::compile::chunk::Template { cooked, raw });
Ok(index)
}
/// §8.6.3 `NamedEvaluation` — compile `value`, and name it `name` if it is anonymous.
///
/// The positions this applies to are a closed list in the specification, and every caller of this
/// is one of them: a variable declaration, an assignment to a name, a property definition, a class
/// field, and a destructuring default. It reaches an **anonymous** function, arrow or class and
/// nothing else — `var a = function f() {}` is called `f`, and `var a = (0, function () {})` is
/// called nothing at all, because a parenthesised comma expression is not a function.
pub(super) fn named_evaluation(
&mut self,
name: &str,
value: &Expr,
) -> Result<(), CompileError> {
let span = value.span;
match &value.kind {
ExprKind::Function(function) if function.name.is_none() => {
self.make_function(function, Naming::of(name), span)
}
// An arrow has no name of its own to prefer — there is no production for one.
ExprKind::Arrow(arrow) => self.make_arrow(arrow, Naming::of(name), span),
ExprKind::Class(class) if class.name.is_none() => {
self.class(class, Naming::of(name), span)
}
_ => self.expression(value),
}
}
/// The object half of a property reference, and the receiver a call would want with it.
///
/// Two shapes, and `super` is the one that needs a name. An ordinary base *is* the receiver, so a
/// call copies it. §13.3.7.1's super reference has two different objects: the property is looked
/// up on the home object's prototype and the receiver stays `this`, so the receiver is pushed
/// first and the base after it. Everything above this — reading, calling, assigning, deleting —
/// then works on a stack of `[receiver?, base, key]` either way.
fn base(
&mut self,
object: &Expr,
optional: bool,
keep: Keep,
) -> Result<Reference, CompileError> {
if matches!(object.kind, ExprKind::Super) {
// The receiver §13.3.7.1 keeps, and a copy of it if a call is going to want one under the
// callee. `keep.receiver` is the same `Duplicate` an ordinary base uses, applied to the
// receiver rather than to the base — which is precisely the difference.
self.load_this();
keep.receiver(self);
self.chunk.emit(Instruction::LoadSuperBase);
return Ok(Reference::Super);
}
self.expression(object)?;
// §13.3.9 — tested here, *before* the copy a call would want, so that the chain leaves one
// value behind whichever kind of link this is. After the copy it would strand a receiver.
if optional {
self.optional_link()?;
}
keep.receiver(self);
Ok(Reference::Ordinary)
}
/// §13.3.9 — leave the chain with `undefined` if what is on top of the stack is nullish.
///
/// Nothing at all when the value is fine, which is what `JumpKeeping` is for: it *keeps* the value
/// on the branch that carries on and takes it on the branch that does not, so the short circuit
/// starts with an empty-handed stack and pushes the one value the whole chain evaluates to.
pub(super) fn optional_call_link(&mut self, method: bool) -> Result<(), CompileError> {
let carry_on = self
.chunk
.emit_jump(|target| Instruction::JumpKeeping(ShortCircuit::WhenNotNullish, target));
// The callee has already gone with the jump's own pop; a method call's *receiver* is still
// under it and would be left behind, which is the one asymmetry between the two link kinds.
if method {
self.chunk.emit(Instruction::Pop);
}
self.constant(Value::Undefined)?;
let out = self.chunk.emit_jump(Instruction::Jump);
match self.chains.last_mut() {
Some(chain) => chain.push(out),
None => {
return Err(unsupported(
"`?.` outside an optional chain",
Span::new(0, 0),
));
}
}
self.chunk.patch(carry_on)
}
fn optional_link(&mut self) -> Result<(), CompileError> {
let carry_on = self
.chunk
.emit_jump(|target| Instruction::JumpKeeping(ShortCircuit::WhenNotNullish, target));
self.constant(Value::Undefined)?;
let out = self.chunk.emit_jump(Instruction::Jump);
// The parser refuses `?.` outside an `OptionalExpression`, so there is always a chain to
// leave. A tree built by hand could reach this, and dropping the jump would leave it pointing
// at the unpatched placeholder — a fault rather than a wrong answer, which is worse than a
// refusal with nowhere to point.
match self.chains.last_mut() {
Some(chain) => chain.push(out),
None => {
return Err(unsupported(
"`?.` outside an optional chain",
Span::new(0, 0),
));
}
}
self.chunk.patch(carry_on)
}
/// The base and the key of a property reference, pushed in that order.
///
/// Shared by reading, writing and deleting, which all need the same two values and all refuse
/// the same two things. Written out three times it was the same guard three times, and two of
/// them were unreachable: `o?.a = 1` and `#x` outside a class are refused by the parser long
/// before they reach a compiler.
pub(super) fn property_reference(
&mut self,
target: &Expr,
keep: Keep,
) -> Result<Reference, CompileError> {
match &target.kind {
ExprKind::Member {
private,
optional,
object,
property,
} => {
let reference = self.base(object, *optional, keep)?;
// §13.3.7 — `a.#b`'s key is the Private Name the enclosing class minted, read out of
// the class scope by the same walk that reaches the class's own name. The parser has
// already refused a `#b` no enclosing class binds, so the slot is there.
if *private {
self.load_private_name(property)?;
return Ok(Reference::Private);
}
let units: Vec<u16> = property.encode_utf16().collect();
let id = self.heap.new_string(units);
self.constant(Value::String(id))?;
Ok(reference)
}
ExprKind::ComputedMember {
optional,
object,
property,
} => {
let reference = self.base(object, *optional, keep)?;
self.expression(property)?;
Ok(reference)
}
_ => Err(unsupported(
"a reference to something that is not a property",
target.span,
)),
}
}
/// §13.5.1 — `delete`.
///
/// Answers whether the property is gone, which is not the same as whether it was there:
/// `delete o.nothing` is `true`. Deleting anything that is not a property reference is also
/// `true` and does nothing at all, which is why `delete 1` is legal outside strict mode.
fn delete(&mut self, argument: &Expr) -> Result<(), CompileError> {
match &argument.kind {
ExprKind::Member { .. } | ExprKind::ComputedMember { .. } => {
let reference = self.property_reference(argument, Keep::Nothing)?;
// §13.5.1.1 step 3 — `delete super.x` is a **ReferenceError**, always, and there is
// no super reference it is legal for. A run-time throw rather than an early error
// because the reference is evaluated first: `delete super[k]` runs `ToPropertyKey(k)`
// and *then* refuses, so a `toString` on the key has already had its effect.
self.chunk.emit(match reference {
Reference::Super => Instruction::ThrowSuperDelete,
// §15.7.1 makes `delete this.#x` an *early* error, so the parser has already
// refused it and this arm is unreachable from source. `DeleteProperty` is the
// honest thing for a hand-built tree: the name is a Symbol that no property table
// holds, so the delete finds nothing and answers `true`.
Reference::Ordinary | Reference::Private => Instruction::DeleteProperty,
});
Ok(())
}
// §13.5.1.2 step 5 — deleting a *name*, which the parser has already refused in strict
// code (§13.5.1.1 makes it an early error there). What is left is sloppy, and the answer
// depends on where the name lives rather than on anything at run time:
//
// A name the compiler can place is a declarative binding — a `var`, a parameter, a `let`,
// a function's own slot — and §9.1.1.1.5 makes every one of those **non-deletable**. So
// the answer is `false` and there is nothing to emit but the constant.
//
// A name it cannot place is a property of the global object, which may or may not be
// configurable and may not be there at all. That one needs the object, at run time.
// …and inside a `with` it may be a property of the object, which is a third answer and
// is the one this cannot decide: which of the three applies depends on what the object
// holds at the moment of the delete. So the walk is emitted instead, exactly as a read
// of the same name would be.
ExprKind::Identifier(name) if self.names_are_dynamic() => {
let index = self.name(name)?;
self.chunk.emit(Instruction::DeleteName(index));
Ok(())
}
ExprKind::Identifier(name) => match self.binding(name) {
Some(_) => self.constant(Value::Boolean(false)),
None => {
let index = self.name(name)?;
self.chunk.emit(Instruction::DeleteGlobal(index));
Ok(())
}
},
_ => {
self.expression(argument)?;
self.chunk.emit(Instruction::Pop);
self.constant(Value::Boolean(true))
}
}
}
/// `o.x = v` and `o[k] = v`, and their compound forms — §13.15.2.
///
/// The base and the key are evaluated **once**, which is what makes `o[f()] += 1` call `f`
/// once rather than twice. For a compound operator that means the two have to be on the stack
/// twice over — once for the read and once for the write — which is what `DuplicateTwo` is
/// for.
/// Kept out of line, deliberately.
///
/// [`Compiler::expression_inner`] recurses, so its stack frame is paid once per level of a
/// nested expression — and DR-0006's depth limit bounds the levels, not the bytes. A helper
/// inlined into it adds its locals to *every* level, which is how a change that touched
/// neither the limit nor the recursion overflowed a smaller stack than this machine's.
#[inline(never)]
fn assign_to_property(
&mut self,
operator: AssignmentOperator,
target: &Expr,
value: &Expr,
span: Span,
) -> Result<(), CompileError> {
// §13.3.7.1 leaves a reference with *three* values — the receiver as well as the base and the
// key — and every compound form below reads the old value with `DuplicateTwo`, which copies
// two. Rather than a three-deep copy for one construct, the plain assignment is compiled here
// and the rest is refused by name: `super.x += 1` is legal and rare, and a refusal with a span
// is better than an unbalanced stack.
// The reference is compiled once, and it decides everything below: how wide it is, how the old
// value is read back, and how the new one is written. `super.x` is three values and `o.#x` is
// two with a Private Name where a key would be, and both used to be refused here for exactly
// that — a compound form that copied two values could not read either of them back.
let reference = self.property_reference(target, Keep::Nothing)?;
let width = reference.width();
// §6.2.5.5 — a reference that is going to be read *and* written settles its key first, so
// that `o[p] += 1` calls `p.toString()` once and `null[p] += 1` throws before it calls it
// at all. A plain `=` reads nothing, so it converts once anyway and needs none of this.
let computed = matches!(target.kind, ExprKind::ComputedMember { .. });
let settle = reference.prepare(computed);
match compound_operator(operator) {
None if operator == AssignmentOperator::Assign => self.expression(value)?,
Some(binary) => {
if let Some(settle) = settle {
self.chunk.emit(settle);
}
self.chunk.emit(Instruction::DuplicateTop(width));
self.chunk.emit(reference.get());
self.expression(value)?;
self.chunk.emit(Instruction::Binary(binary));
}
// The same rule as for a name, with the reference to clear up. On the path where the
// circuit fires it is still under the old value, so the value is buried beneath it and it
// is dropped — both paths have to leave the stack one deep or the chunk is unbalanced.
None if short_circuit_operator(operator).is_some() => {
let condition = match short_circuit_operator(operator) {
Some(condition) => condition,
None => return Err(unsupported("a logical assignment", span)),
};
if let Some(settle) = settle {
self.chunk.emit(settle);
}
self.chunk.emit(Instruction::DuplicateTop(width));
self.chunk.emit(reference.get());
let circuit_fired = self
.chunk
.emit_jump(|target| Instruction::JumpKeeping(condition, target));
self.expression(value)?;
self.chunk.emit(reference.set());
let done = self.chunk.emit_jump(Instruction::Jump);
self.chunk.patch(circuit_fired)?;
self.chunk.emit(Instruction::Bury(width));
for _ in 0..width {
self.chunk.emit(Instruction::Pop);
}
return self.chunk.patch(done);
}
None => return Err(unsupported("a logical assignment", span)),
}
self.chunk.emit(reference.set());
Ok(())
}
/// §13.4 — `++a`, `a++`, `--a` and `a--`.
///
/// # Why the operand is coerced before anything is added
///
/// §13.4.4.1 step 3 applies `ToNumeric` to the *old* value and then adds one to the result.
/// That is not the same as adding one and coercing afterwards: `x = "1"; x++` leaves `x` as
/// the number 2 and evaluates to the number **1**, not to the string `"1"`. So the coercion
/// is an instruction of its own — `+x` is exactly `ToNumber` (§13.5.4) — and once it has run
/// the addition cannot be string concatenation, whatever was there before.
///
/// `ToNumeric` rather than `ToNumber` is what the specification says, and the difference is
/// BigInt: `1n++` is `2n` and never becomes a Number. This used to add "there are no BigInt
/// values yet, so the two agree on every value that exists" — they exist, and the two no
/// longer agree, which is why the instruction has to be the one the clause names.
/// Kept out of line, deliberately.
///
/// [`Compiler::expression_inner`] recurses, so its stack frame is paid once per level of a
/// nested expression — and DR-0006's depth limit bounds the levels, not the bytes. A helper
/// inlined into it adds its locals to *every* level, which is how a change that touched
/// neither the limit nor the recursion overflowed a smaller stack than this machine's.
#[inline(never)]
fn update(
&mut self,
operator: UpdateOperator,
prefix: bool,
argument: &Expr,
span: Span,
) -> Result<(), CompileError> {
match &argument.kind {
ExprKind::Identifier(name) => {
// §13.4.4.1 step 1 evaluates the `LeftHandSideExpression` **once**, and steps 2
// and 5 read and write through that one reference — exactly as §13.15.2's compound
// assignment does, and the identical reason applies. Inside a `with` the
// resolution is observable: it runs `HasBinding`, which reads the object's
// `@@unscopables`, and a getter that answers differently the second time sends the
// write to a different binding entirely. `x++` resolved twice and `x += 1` once,
// which is the same clause implemented two ways in one file.
//
// A slot needs none of it — the compiler resolved that when it compiled — so the
// ordinary path below stays the ordinary path.
if self.names_are_dynamic() {
let index = self.name(name)?;
self.chunk.emit(Instruction::ResolveName(index));
self.chunk.emit(Instruction::LoadThrough(index));
self.chunk.emit(Instruction::ToNumeric);
if !prefix {
self.chunk.emit(Instruction::Duplicate);
}
self.chunk.emit(Instruction::Step(operator));
self.chunk.emit(Instruction::StoreThrough(index));
if !prefix {
self.chunk.emit(Instruction::Pop);
}
return Ok(());
}
self.load_name(name)?;
self.chunk.emit(Instruction::ToNumeric);
// The old value has to outlive the store, and only a postfix one needs it.
if !prefix {
self.chunk.emit(Instruction::Duplicate);
}
self.chunk.emit(Instruction::Step(operator));
self.store_name(name)?;
// The store leaves the *new* value behind. A postfix one wants the old, which is
// underneath it, so the new one goes.
if !prefix {
self.chunk.emit(Instruction::Pop);
}
Ok(())
}
ExprKind::Member { .. } | ExprKind::ComputedMember { .. } => {
// §13.4.4.1 step 1 evaluates the reference *once*, so `o[f()]++` calls `f` once —
// the same guarantee `o[f()] += 1` needs, and the same instructions.
let reference = self.property_reference(argument, Keep::Nothing)?;
let width = reference.width();
// The same settling a compound assignment does, and for the same reason: this
// reference is read and then written, so `o[p]++` must convert `p` once.
if let Some(settle) =
reference.prepare(matches!(argument.kind, ExprKind::ComputedMember { .. }))
{
self.chunk.emit(settle);
}
self.chunk.emit(Instruction::DuplicateTop(width));
self.chunk.emit(reference.get());
self.chunk.emit(Instruction::ToNumeric);
if !prefix {
// Under the base, the key and the copy that is about to become the new value
// — the three the store is going to consume. It surfaces again when the new
// value the store leaves behind is discarded.
self.chunk.emit(Instruction::Duplicate);
// Under the whole reference and the copy that is about to become the new value —
// everything the store is going to consume. `width + 1` and not a literal, because
// a `super` reference is one value wider than the other two.
self.chunk.emit(Instruction::Bury(width + 1));
}
self.chunk.emit(Instruction::Step(operator));
self.chunk.emit(reference.set());
if !prefix {
self.chunk.emit(Instruction::Pop);
}
Ok(())
}
// §13.4.1 — the parser has already refused anything that is not a simple assignment
// target, so what is left is a target this compiler has not learned yet.
_ => Err(unsupported(
"an update of something that is not a name",
span,
)),
}
}
/// Emit a constant and the instruction that pushes it.
/// §13.2.4.1 — an array literal with a spread in it, built one element at a time.
///
/// The ordinary path knows its length before it starts and defines each element at a written
/// index. A spread has no such number: `[...a]` is as long as `a` turns out to be, and the
/// elements after it sit wherever that left off. So the index is a slot the loop moves, and
/// `length` is written at the end — which is also what makes a trailing hole count.
///
/// §13.2.4.1 spreads by *iterating*, not by reading indices, so `[..."ab"]` is two one-character
/// strings and `[...someSet]` works. That is the same `@@iterator` a `for`-`of` asks for, and
/// an object without one is a TypeError here as it is there.
fn spread_array(&mut self, elements: &[ArrayElement], span: Span) -> Result<(), CompileError> {
let at = self.declare_hidden("at");
self.chunk.emit(Instruction::NewArray(0));
self.constant(Value::Number(0.0))?;
self.chunk.emit(Instruction::StoreVariable(0, at));
self.chunk.emit(Instruction::Pop);
for element in elements {
match element {
// A hole defines nothing and still takes a place, which is what makes `[, 1]` two
// long with one property.
ArrayElement::Hole => self.bump(at)?,
ArrayElement::Value(value) => {
// No copy of the array: `DefineField` takes the key and the value and leaves
// the object it defined on, which is what lets the whole literal be built
// with one of them on the stack throughout.
self.chunk.emit(Instruction::LoadVariable(0, at));
self.expression(value)?;
self.chunk.emit(Instruction::DefineField);
self.bump(at)?;
}
ArrayElement::Spread { value, .. } => {
self.expression(value)?;
self.spread_into(at)?;
}
}
}
// §13.2.4.1 sets the length from the count, which matters when the last element was a
// hole: nothing was defined there, so nothing grew the array to reach it.
self.chunk.emit(Instruction::Duplicate);
let name = self.name_of("length");
self.constant(Value::String(name))?;
self.chunk.emit(Instruction::LoadVariable(0, at));
self.chunk.emit(Instruction::SetProperty);
self.chunk.emit(Instruction::Pop);
let _ = span;
Ok(())
}
/// Move the running index on by one.
pub(super) fn bump(&mut self, at: u32) -> Result<(), CompileError> {
self.chunk.emit(Instruction::LoadVariable(0, at));
self.constant(Value::Number(1.0))?;
self.chunk.emit(Instruction::Binary(BinaryOperator::Add));
self.chunk.emit(Instruction::StoreVariable(0, at));
self.chunk.emit(Instruction::Pop);
Ok(())
}
/// Iterate whatever is on top of the stack into the array beneath it.
///
/// Leaves the array where it found it. Nothing is closed on the way out because there is no
/// way out until the iterator says it is done — §13.2.4.1 spreads to exhaustion, so the only
/// abrupt end is one the iterator itself raised, and §7.4.9 has nothing to add to that.
pub(super) fn spread_into(&mut self, at: u32) -> Result<(), CompileError> {
let iterator = self.declare_hidden("iterator");
let next = self.declare_hidden("next");
let done = self.declare_hidden("done");
self.chunk.emit(Instruction::Duplicate);
self.chunk
.emit(Instruction::LoadWellKnown(super::statement::well_known(
"iterator",
)));
self.chunk.emit(Instruction::GetProperty);
self.chunk.emit(Instruction::CallMethod(0));
self.chunk.emit(Instruction::RequireObject);
self.chunk.emit(Instruction::StoreVariable(0, iterator));
let name = self.name_of("next");
self.constant(Value::String(name))?;
self.chunk.emit(Instruction::GetProperty);
self.chunk.emit(Instruction::StoreVariable(0, next));
self.chunk.emit(Instruction::Pop);
self.constant(Value::Boolean(false))?;
self.chunk.emit(Instruction::StoreVariable(0, done));
self.chunk.emit(Instruction::Pop);
let top = self.here()?;
self.emit_step(iterator, next, done)?;
let current = self.declare_hidden("current");
self.chunk.emit(Instruction::StoreVariable(0, current));
self.chunk.emit(Instruction::Pop);
self.chunk.emit(Instruction::LoadVariable(0, done));
let out = self.chunk.emit_jump(Instruction::JumpIfTrue);
self.chunk.emit(Instruction::LoadVariable(0, at));
self.chunk.emit(Instruction::LoadVariable(0, current));
self.chunk.emit(Instruction::DefineField);
self.bump(at)?;
self.chunk.emit(Instruction::Jump(top));
self.chunk.patch(out)
}
/// §13.2.8.6 — a template literal, which is its pieces joined in the order they are written.
///
/// Each substitution is `ToString`ed the moment it is evaluated, not at the end. That ordering
/// is observable: a `toString` that throws must do so before the *next* substitution is
/// evaluated, and one with a side effect must see only what came before it.
///
/// `ToString` and not `+ ""`, which is the other thing that looks like it would work. Addition
/// asks an object with the default hint and reaches `valueOf`; a template asks with the string
/// hint and reaches `toString`. An object with both answers differently in the two places, and
/// that is a difference the specification means.
///
/// The cooked strings are joined with `+` rather than through a second `ToString`, because
/// they are Strings already and adding two Strings is exact concatenation.
/// Kept out of line, deliberately.
///
/// [`Compiler::expression_inner`] recurses, so its stack frame is paid once per level of a
/// nested expression — and DR-0006's depth limit bounds the levels, not the bytes. A helper
/// inlined into it adds its locals to *every* level, which is how a change that touched
/// neither the limit nor the recursion overflowed a smaller stack than this machine's.
#[inline(never)]
fn template(&mut self, template: &TemplateLiteral) -> Result<(), CompileError> {
let mut quasis = template.quasis.iter();
// A template always has one more component than it has substitutions, so the first is
// there even when the template is empty — `` is one empty component and no substitutions.
self.cooked(quasis.next())?;
for expression in template.expressions.iter() {
self.expression(expression)?;
self.chunk.emit(Instruction::Stringify);
self.chunk.emit(Instruction::Binary(BinaryOperator::Add));
self.cooked(quasis.next())?;
self.chunk.emit(Instruction::Binary(BinaryOperator::Add));
}
Ok(())
}
/// Push one cooked component of a template, or the empty String if it has none.
///
/// A component with no cooked value holds a `NotEscapeSequence`, which §13.2.8.1 permits only
/// in a *tagged* template — where the tag may read the raw text instead. An untagged one with
/// such a component is a SyntaxError the parser raises, so reaching here with `None` would
/// mean a tree no source can produce; the empty String is what that would have joined to.
fn cooked(&mut self, element: Option<&TemplateElement>) -> Result<(), CompileError> {
let units = element
.and_then(|found| found.cooked.as_deref())
.unwrap_or(&[]);
let id = self.heap.intern(units);
self.constant(Value::String(id))
}
pub(super) fn constant(&mut self, value: Value) -> Result<(), CompileError> {
let index = self.chunk.add_constant(value)?;
self.chunk.emit(Instruction::Constant(index));
Ok(())
}
}
/// The binary operator a compound assignment applies, if it is one.
///
/// `+=` is `+`, and so on for the eleven that pair up. The three logical ones — `&&=`, `||=`,
/// `??=` — do not: they are short circuits, so they may not assign at all, and there is no
/// binary operator that describes them.
/// The short circuit `&&=`, `||=` and `??=` test before they assign, if this is one of them.
///
/// Separate from [`compound_operator`] because these three are not compound assignments at all:
/// §13.15.2 gives them their own evaluation, in which the value is never computed and the store never
/// happens unless the test fails. `a ||= f()` does not call `f` when `a` is truthy, where `a += f()`
/// always calls it.
fn short_circuit_operator(operator: AssignmentOperator) -> Option<ShortCircuit> {
Some(match operator {
AssignmentOperator::LogicalAnd => ShortCircuit::WhenFalsy,
AssignmentOperator::LogicalOr => ShortCircuit::WhenTruthy,
AssignmentOperator::NullishCoalescing => ShortCircuit::WhenNotNullish,
_ => return None,
})
}
fn compound_operator(operator: AssignmentOperator) -> Option<BinaryOperator> {
Some(match operator {
AssignmentOperator::Add => BinaryOperator::Add,
AssignmentOperator::Subtract => BinaryOperator::Subtract,
AssignmentOperator::Multiply => BinaryOperator::Multiply,
AssignmentOperator::Divide => BinaryOperator::Divide,
AssignmentOperator::Remainder => BinaryOperator::Remainder,
AssignmentOperator::Exponent => BinaryOperator::Exponent,
AssignmentOperator::ShiftLeft => BinaryOperator::ShiftLeft,
AssignmentOperator::ShiftRight => BinaryOperator::ShiftRight,
AssignmentOperator::ShiftRightUnsigned => BinaryOperator::ShiftRightUnsigned,
AssignmentOperator::BitwiseAnd => BinaryOperator::BitwiseAnd,
AssignmentOperator::BitwiseXor => BinaryOperator::BitwiseXor,
AssignmentOperator::BitwiseOr => BinaryOperator::BitwiseOr,
AssignmentOperator::Assign
| AssignmentOperator::LogicalAnd
| AssignmentOperator::LogicalOr
| AssignmentOperator::NullishCoalescing => return None,
})
}
/// What an object literal puts under a key.
///
/// Three shapes and one destination: a shorthand reads the name it also files under, and a method
/// is a function made where the literal is evaluated — so `{m() {}}` inside a loop makes one
/// function object per turn, exactly as `{m: function () {}}` does.
enum Element<'a> {
/// `a: 1` — an ordinary expression.
Value(&'a Expr),
/// `{a}` — the name is both the key and the value.
Name(&'a str, Span),
/// `a() {}`, `get a() {}`, `set a(v) {}`.
Function(&'a crate::ast::Function),
}
/// Whether this key is B.3.1's `__proto__`, in one of the two spellings the rule covers.
///
/// An `IdentifierName` or a `StringLiteral`, because B.3.1 asks about the key's **StringValue** — so
/// `{ '__proto__': p }` is in and `{ ['__proto__']: p }` is out, the latter being a computed key and a
/// different production. A numeric or BigInt key cannot spell it at all.
fn is_proto_key(key: &AstPropertyKey) -> bool {
let wanted = "__proto__";
match key {
AstPropertyKey::Identifier(name) => &**name == wanted,
// Compared as code units, because that is what the key is (DR-0004) and because a lone
// surrogate in a key is representable where a `str` would not be.
AstPropertyKey::String(units) => units.iter().copied().eq(wanted.encode_utf16()),
_ => false,
}
}
/// Which of §13.3's two property references was compiled, and so which instruction reads it.
///
/// Answered by the code that pushed the values rather than asked about the tree afterwards. A second
/// walk over the tree is a second copy of the rule, and the copy nothing reads is the one that would
/// disagree — the first attempt at this was such a walk, with a catch-all arm for a shape it could
/// never be handed, which mutation coverage duly reported as unpinnable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Reference {
/// `o.x` — one object, which is both where the property is found and the receiver.
Ordinary,
/// `super.x` — §13.3.7.1's two, with the receiver pushed under the base.
Super,
/// `o.#x` — one object and a **Private Name**, which is not a property key at all.
Private,
}
impl Reference {
/// The instruction that reads this reference.
pub(super) fn get(self) -> Instruction {
match self {
Self::Ordinary => Instruction::GetProperty,
Self::Super => Instruction::GetSuperProperty,
Self::Private => Instruction::GetPrivate,
}
}
/// The instruction that writes this reference, with the value pushed on top of it.
///
/// All three consume the whole reference and leave the value, so every caller balances without
/// knowing which it got — which is the point. Writing `SetProperty` for all of them was a silent
/// wrong answer for two of the three: a Private Name *is* a valid property key, so a private
/// write through this path quietly made a Symbol-keyed property instead of throwing, and a
/// `super` write left its receiver stranded on the stack.
pub(super) fn set(self) -> Instruction {
match self {
Self::Ordinary => Instruction::SetProperty,
Self::Super => Instruction::SetSuperProperty,
Self::Private => Instruction::SetPrivate,
}
}
/// The instruction that settles this reference's key, for one that is read *and* written.
///
/// `None` for `o.#x`, whose Private Name is not a property key and needs no conversion, and
/// for a reference whose key is written down — see [`Instruction::PrepareKey`] for what the
/// conversion happening twice costs.
pub(super) fn prepare(self, computed: bool) -> Option<Instruction> {
match self {
Self::Private => None,
// The base sits directly under the key for `o[p]`, and under the receiver as well for
// `super[p]` — which is `width` minus the key itself.
Self::Ordinary | Self::Super if computed => Some(Instruction::PrepareKey {
base: self.width() - 1,
}),
Self::Ordinary | Self::Super => None,
}
}
/// How many values this reference occupies on the stack.
///
/// What a compound assignment, an update and §13.15.5.5 step 1 need: the first two read the old
/// value and then write, and the third parks the whole reference in slots while the iterator is
/// stepped. In every case the reference is evaluated once and
/// §13.15.2 evaluates the reference once — so the whole of it has to be copied, and how much that
/// is depends on which reference it is. Two for `o.x` and for `o.#x`, three for `super.x`, whose
/// receiver sits under the base.
pub(super) fn width(self) -> u32 {
match self {
Self::Ordinary | Self::Private => 2,
Self::Super => 3,
}
}
}