quickjs-oxide 0.4.0

A safe Rust JavaScript engine targeting semantic parity with QuickJS
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
//! Expression precedence, references and assignments.

use crate::engine::api::error::Error;
use crate::engine::api::error::ErrorKind;
use crate::engine::code::bytecode::ApplyKind;
use crate::engine::code::bytecode::Instruction;
use crate::engine::code::function::metadata::FunctionKind as BytecodeFunctionKind;
use crate::engine::compiler::lexer::Keyword;
use crate::engine::compiler::lexer::Punctuator;
use crate::engine::compiler::lexer::Span;
use crate::engine::compiler::lexer::TokenKind;
use crate::engine::compiler::model::ir::CallArguments;
use crate::engine::compiler::model::ir::FunctionId;
use crate::engine::compiler::model::ir::IdentifierAccess;
use crate::engine::compiler::model::ir::IdentifierReferenceAccess;
use crate::engine::compiler::model::ir::IrConstant;
use crate::engine::compiler::model::ir::IrOp;
use crate::engine::compiler::model::ir::PrivateFieldAccess;
use crate::engine::compiler::model::ir::SpannedIrOp;
use crate::engine::compiler::model::scope::ScopeId;
use crate::engine::compiler::model::scope::ScopeKind;
use crate::engine::compiler::optional_chain;
use crate::engine::compiler::optional_chain::PendingOptionalChain;
use crate::engine::compiler::parser::context::IdentifierReference;
use crate::engine::compiler::parser::context::InMode;
use crate::engine::compiler::parser::context::LogicalAssignment;
use crate::engine::compiler::parser::context::MemberReference;
use crate::engine::compiler::parser::context::Parser;
use crate::engine::compiler::parser::context::PowerMode;
use crate::engine::compiler::parser::diagnostics::source_offset;
use crate::engine::compiler::stack_guard::ParserStackFrame;
use crate::engine::value::JsString;
use crate::engine::value::PrimitiveValue as Value;

impl<'source> Parser<'source> {
    pub(in crate::engine::compiler) fn consume_statement_terminator(
        &mut self,
    ) -> Result<(), Error> {
        if self.consume_punctuator(Punctuator::Semicolon)?
            || self.at_eof()
            || self.is_punctuator(Punctuator::RightBrace)
            || self.current().line_terminator_before
        {
            Ok(())
        } else {
            Err(self.syntax_here("expecting ';'"))
        }
    }

    pub(in crate::engine::compiler) fn parse_expression(&mut self) -> Result<(), Error> {
        self.with_in_mode(InMode::Allow, Self::parse_comma)
    }

    pub(in crate::engine::compiler) fn parse_expression_no_in(&mut self) -> Result<(), Error> {
        self.with_in_mode(InMode::Disallow, Self::parse_comma)
    }

    pub(in crate::engine::compiler) fn parse_assignment_allow_in(&mut self) -> Result<(), Error> {
        self.with_in_mode(InMode::Allow, Self::parse_assignment)
    }

    pub(in crate::engine::compiler) fn with_in_mode<T>(
        &mut self,
        mode: InMode,
        parse: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<T, Error> {
        let previous = std::mem::replace(&mut self.in_mode, mode);
        let result = parse(self);
        self.in_mode = previous;
        result
    }

    pub(in crate::engine::compiler) fn parse_comma(&mut self) -> Result<(), Error> {
        self.parse_assignment()?;
        let mut has_comma = false;
        while self.is_punctuator(Punctuator::Comma) {
            self.advance()?;
            has_comma = true;
            self.emit_instruction(Instruction::Drop)?;
            self.parse_assignment()?;
        }
        if has_comma {
            self.anonymous_function_definition = None;
            self.current_ir_mut().context.last_member_reference = None;
            self.current_ir_mut().context.last_identifier_reference = None;
            self.current_ir_mut().context.last_optional_chain = None;
        }
        Ok(())
    }

    /// Parse assignment targets through typed unresolved References. Keeping
    /// identifier writes unresolved lets the late resolver select argument,
    /// local, closure, global and private-function-name behavior after the
    /// complete nested scope tree is known.
    pub(in crate::engine::compiler) fn parse_assignment(&mut self) -> Result<(), Error> {
        if matches!(self.current().kind, TokenKind::Keyword(Keyword::Yield)) {
            return self.parse_recursion(ParserStackFrame::Yield, Self::parse_yield_expression);
        }
        if let Some(head) = self.async_arrow_ahead() {
            return self.parse_async_arrow_function(head);
        }
        if let Some(head) = self.arrow_head_ahead() {
            return self.parse_arrow_function(head);
        }
        // Destructuring assignment is recognized only after every arrow-head
        // probe has had its say. Like pinned QuickJS, the Array form takes a
        // control-inverted path only when the matching `]` is immediately
        // followed by `=`; otherwise this remains an ordinary Array literal.
        if self.object_assignment_pattern_ahead() {
            return self.parse_object_assignment_expression();
        }
        if self.array_assignment_pattern_ahead() {
            return self.parse_array_assignment_expression();
        }
        // QuickJS's `name0` is captured only when the AssignmentExpression
        // starts with the identifier token itself. Parenthesized lvalues are
        // valid References but intentionally do not trigger NamedEvaluation.
        let direct_identifier_start = matches!(self.current().kind, TokenKind::Identifier(_))
            .then_some(self.current().span.start.byte_offset);
        self.parse_conditional()?;
        if self.current_ir().context.last_optional_chain.is_some()
            && matches!(
                self.current().kind,
                TokenKind::Punctuator(
                    Punctuator::Equal
                        | Punctuator::PlusAssign
                        | Punctuator::MinusAssign
                        | Punctuator::MultiplyAssign
                        | Punctuator::DivideAssign
                        | Punctuator::RemainderAssign
                        | Punctuator::ExponentAssign
                        | Punctuator::ShiftLeftAssign
                        | Punctuator::ShiftRightAssign
                        | Punctuator::UnsignedShiftRightAssign
                        | Punctuator::BitAndAssign
                        | Punctuator::BitOrAssign
                        | Punctuator::BitXorAssign
                        | Punctuator::LogicalAndAssign
                        | Punctuator::LogicalOrAssign
                        | Punctuator::NullishAssign
                )
            )
        {
            // QuickJS consumes every assignment operator before get_lvalue
            // rejects an optional-chain Reference, so the diagnostic points
            // at the first RHS token.
            self.advance()?;
            return Err(self.syntax_here("invalid assignment left-hand side"));
        }
        let logical = match self.current().kind {
            TokenKind::Punctuator(Punctuator::LogicalAndAssign) => Some(LogicalAssignment::And),
            TokenKind::Punctuator(Punctuator::LogicalOrAssign) => Some(LogicalAssignment::Or),
            TokenKind::Punctuator(Punctuator::NullishAssign) => Some(LogicalAssignment::Nullish),
            _ => None,
        };
        if let Some(logical) = logical {
            if let Some(target) =
                self.promote_tail_identifier_get(IdentifierReferenceAccess::Get)?
            {
                let infer_name = direct_identifier_start == Some(target.span.start.byte_offset);
                return self.parse_logical_identifier_assignment(target, logical, infer_name);
            }
            return self.parse_logical_member_assignment(logical);
        }

        let assignment_span = self.current().span;
        let compound = match self.current().kind {
            TokenKind::Punctuator(Punctuator::Equal) => None,
            TokenKind::Punctuator(Punctuator::PlusAssign) => Some(Instruction::Add),
            TokenKind::Punctuator(Punctuator::MinusAssign) => Some(Instruction::Sub),
            TokenKind::Punctuator(Punctuator::MultiplyAssign) => Some(Instruction::Mul),
            TokenKind::Punctuator(Punctuator::DivideAssign) => Some(Instruction::Div),
            TokenKind::Punctuator(Punctuator::RemainderAssign) => Some(Instruction::Mod),
            TokenKind::Punctuator(Punctuator::ExponentAssign) => Some(Instruction::Pow),
            TokenKind::Punctuator(Punctuator::ShiftLeftAssign) => Some(Instruction::Shl),
            TokenKind::Punctuator(Punctuator::ShiftRightAssign) => Some(Instruction::Sar),
            TokenKind::Punctuator(Punctuator::UnsignedShiftRightAssign) => Some(Instruction::Shr),
            TokenKind::Punctuator(Punctuator::BitAndAssign) => Some(Instruction::BitAnd),
            TokenKind::Punctuator(Punctuator::BitXorAssign) => Some(Instruction::BitXor),
            TokenKind::Punctuator(Punctuator::BitOrAssign) => Some(Instruction::BitOr),
            _ => return Ok(()),
        };

        if let Some(operation) = compound {
            if let Some(target) =
                self.promote_tail_identifier_get(IdentifierReferenceAccess::Get)?
            {
                self.advance()?;
                self.validate_identifier_assignment_target(&target)?;
                self.parse_assignment_rhs()?;
                self.emit_instruction_at(operation, source_offset(assignment_span)?)?;
                self.anonymous_function_definition = None;
                if target.object_environment {
                    self.emit_identifier_reference_inherited(
                        target.name,
                        target.span,
                        target.scope,
                        IdentifierReferenceAccess::Set,
                    )?;
                } else {
                    self.emit_identifier_inherited(
                        target.name,
                        target.span,
                        target.scope,
                        IdentifierAccess::Set,
                    )?;
                }
                return Ok(());
            }
            let Some(target) = self.promote_tail_member_get_for_compound()? else {
                // QuickJS consumes the assignment operator before rejecting
                // a non-Reference left side, so the diagnostic points at the
                // first RHS token rather than the operator.
                self.advance()?;
                return Err(self.syntax_here("invalid assignment left-hand side"));
            };
            self.advance()?;
            self.parse_assignment_rhs()?;
            self.emit_instruction_at(operation, source_offset(assignment_span)?)?;
            self.anonymous_function_definition = None;
            self.emit_member_put(target)?;
            return Ok(());
        }

        if let Some(target) = self.take_tail_identifier_reference()? {
            self.advance()?;
            self.validate_identifier_assignment_target(&target)?;
            let rhs_start = self.current_ir().ops.len();
            self.parse_assignment_rhs()?;
            self.inherit_source_marker_at(rhs_start, source_offset(target.span)?)?;
            let anonymous_rhs = self.take_anonymous_function_definition();
            if direct_identifier_start == Some(target.span.start.byte_offset)
                && let Some(definition) = anonymous_rhs
            {
                let name_constant = self.add_constant(IrConstant::Primitive(Value::String(
                    JsString::try_from_utf8(self.names.name(target.name))?,
                )))?;
                self.emit_anonymous_set_name(definition, Instruction::SetName(name_constant))?;
            }
            // QuickJS emits no source position for ordinary `=`. The Set
            // inherits the LHS marker for an unmarked RHS or the last marker
            // produced while evaluating the RHS.
            if target.object_environment {
                self.emit_identifier_reference_inherited(
                    target.name,
                    target.span,
                    target.scope,
                    IdentifierReferenceAccess::Set,
                )?;
            } else {
                self.emit_identifier_inherited(
                    target.name,
                    target.span,
                    target.scope,
                    IdentifierAccess::Set,
                )?;
            }
            self.anonymous_function_definition = None;
            return Ok(());
        }

        let Some(target) = self.take_tail_member_reference()? else {
            // As with compound assignment, QuickJS has already advanced to
            // the RHS before reporting a non-Reference left side.
            self.advance()?;
            return Err(self.syntax_here("invalid assignment left-hand side"));
        };
        self.advance()?;
        let rhs_start = self.current_ir().ops.len();
        self.parse_assignment_rhs()?;
        let site = match &target {
            MemberReference::Field { site, .. }
            | MemberReference::Computed { site }
            | MemberReference::Super { site }
            | MemberReference::Private { site, .. } => *site,
        };
        self.inherit_source_marker_at(rhs_start, site)?;

        // QuickJS does not apply NamedEvaluation to member assignment. The
        // anonymous function marker also must not escape to an enclosing
        // identifier assignment such as `x = obj.p = function(){}`.
        self.anonymous_function_definition = None;
        self.emit_member_put(target)
    }

    /// Identifier logical assignment is QuickJS's depth-zero lvalue case. The
    /// short branch already contains only the old value, while the write branch
    /// replaces it with the RHS and resolves one preserving Set operation.
    pub(in crate::engine::compiler) fn parse_logical_identifier_assignment(
        &mut self,
        target: IdentifierReference,
        logical: LogicalAssignment,
        infer_name: bool,
    ) -> Result<(), Error> {
        self.advance()?;
        self.validate_identifier_assignment_target(&target)?;
        self.emit_instruction(Instruction::Dup)?;
        if logical == LogicalAssignment::Nullish {
            self.emit_instruction(Instruction::IsUndefinedOrNull)?;
        }
        let short_circuit = self.emit_instruction(match logical {
            LogicalAssignment::Or => Instruction::IfTrue(u32::MAX),
            LogicalAssignment::And | LogicalAssignment::Nullish => Instruction::IfFalse(u32::MAX),
        })?;
        let short_circuit_depth = self.current_ir().context.stack_depth;

        self.emit_instruction(Instruction::Drop)?;
        self.parse_assignment_rhs()?;
        let anonymous_rhs = self.take_anonymous_function_definition();
        if infer_name && let Some(definition) = anonymous_rhs {
            let name_constant = self.add_constant(IrConstant::Primitive(Value::String(
                JsString::try_from_utf8(self.names.name(target.name))?,
            )))?;
            self.emit_anonymous_set_name(definition, Instruction::SetName(name_constant))?;
        }
        if target.object_environment {
            self.emit_identifier_reference_inherited(
                target.name,
                target.span,
                target.scope,
                IdentifierReferenceAccess::Set,
            )?;
        } else {
            self.emit_identifier_inherited(
                target.name,
                target.span,
                target.scope,
                IdentifierAccess::Set,
            )?;
        }
        let end = self.emit_instruction(Instruction::Goto(u32::MAX))?;
        let joined_depth = self.current_ir().context.stack_depth;

        let short_target = self.current_ir().ops.len();
        self.patch_jump(short_circuit, short_target)?;
        if target.object_environment {
            self.current_ir_mut().context.stack_depth = short_circuit_depth;
            self.emit_instruction(Instruction::Nip)?;
        }
        if self.current_ir().context.stack_depth != joined_depth {
            return Err(Error::internal(
                "identifier logical assignment branches have unequal stack depth",
            ));
        }
        self.patch_jump(end, self.current_ir().ops.len())?;
        self.anonymous_function_definition = None;
        self.current_ir_mut().context.last_member_reference = None;
        self.current_ir_mut().context.last_identifier_reference = None;
        self.current_ir_mut().context.last_optional_chain = None;
        Ok(())
    }

    pub(in crate::engine::compiler) fn validate_identifier_assignment_target(
        &self,
        target: &IdentifierReference,
    ) -> Result<(), Error> {
        if self.current_ir().strict && matches!(self.names.name(target.name), "eval" | "arguments")
        {
            return Err(self.syntax_here("invalid lvalue in strict mode"));
        }
        Ok(())
    }

    /// Lower a logical member assignment with the same two-branch stack shape
    /// as QuickJS `js_parse_assign_expr2`. The kept member Reference is used
    /// only by the assignment branch; the short-circuit branch removes its
    /// base/key operands with `Nip` and returns the original property value.
    pub(in crate::engine::compiler) fn parse_logical_member_assignment(
        &mut self,
        logical: LogicalAssignment,
    ) -> Result<(), Error> {
        let Some(target) = self.promote_tail_member_get_for_compound()? else {
            // As with every other assignment operator, QuickJS advances to
            // the RHS before get_lvalue rejects a non-Reference left side.
            self.advance()?;
            return Err(self.syntax_here("invalid assignment left-hand side"));
        };
        let lvalue_depth = match &target {
            MemberReference::Field { .. } => 1,
            MemberReference::Computed { .. } => 2,
            MemberReference::Super { .. } => 3,
            MemberReference::Private { .. } => 1,
        };

        self.advance()?;
        self.emit_instruction(Instruction::Dup)?;
        if logical == LogicalAssignment::Nullish {
            self.emit_instruction(Instruction::IsUndefinedOrNull)?;
        }
        let short_circuit = self.emit_instruction(match logical {
            LogicalAssignment::Or => Instruction::IfTrue(u32::MAX),
            LogicalAssignment::And | LogicalAssignment::Nullish => Instruction::IfFalse(u32::MAX),
        })?;
        let short_circuit_depth = self.current_ir().context.stack_depth;

        self.emit_instruction(Instruction::Drop)?;
        self.parse_assignment_rhs()?;
        // Member assignment never applies NamedEvaluation to an anonymous RHS.
        self.anonymous_function_definition = None;
        self.emit_member_put(target)?;
        let end = self.emit_instruction(Instruction::Goto(u32::MAX))?;
        let joined_depth = self.current_ir().context.stack_depth;

        self.patch_jump(short_circuit, self.current_ir().ops.len())?;
        self.current_ir_mut().context.stack_depth = short_circuit_depth;
        for _ in 0..lvalue_depth {
            self.emit_instruction(Instruction::Nip)?;
        }
        if self.current_ir().context.stack_depth != joined_depth {
            return Err(Error::internal(
                "logical assignment branches have unequal stack depth",
            ));
        }
        self.patch_jump(end, self.current_ir().ops.len())?;
        self.current_ir_mut().context.last_member_reference = None;
        self.current_ir_mut().context.last_identifier_reference = None;
        self.current_ir_mut().context.last_optional_chain = None;
        Ok(())
    }

    pub(in crate::engine::compiler) fn parse_conditional(&mut self) -> Result<(), Error> {
        self.parse_coalesce()?;
        if !self.is_punctuator(Punctuator::Question) {
            return Ok(());
        }
        self.advance()?;
        self.anonymous_function_definition = None;

        let false_jump = self.emit_instruction(Instruction::IfFalse(u32::MAX))?;
        let branch_stack = self.current_ir().context.stack_depth;
        // QuickJS parses the consequent with ordinary AssignmentExpression
        // even when the surrounding classic-for initializer is NoIn.
        self.parse_recursion(
            ParserStackFrame::Conditional,
            Self::parse_assignment_allow_in,
        )?;
        self.expect_punctuator(Punctuator::Colon)?;
        let end_jump = self.emit_instruction(Instruction::Goto(u32::MAX))?;
        let joined_stack = self.current_ir().context.stack_depth;

        self.patch_jump(false_jump, self.current_ir().ops.len())?;
        self.current_ir_mut().context.stack_depth = branch_stack;
        self.parse_recursion(ParserStackFrame::Conditional, Self::parse_assignment)?;
        self.anonymous_function_definition = None;
        if self.current_ir().context.stack_depth != joined_stack {
            return Err(Error::internal(
                "conditional branches have unequal stack depth",
            ));
        }
        self.patch_jump(end_jump, self.current_ir().ops.len())?;
        self.current_ir_mut().context.last_member_reference = None;
        self.current_ir_mut().context.last_identifier_reference = None;
        self.current_ir_mut().context.last_optional_chain = None;
        Ok(())
    }

    fn parse_assignment_rhs(&mut self) -> Result<(), Error> {
        self.parse_recursion(ParserStackFrame::Assignment, Self::parse_assignment)
    }

    /// QuickJS lowers a nullish-coalescing chain to one shared short-circuit
    /// label. Each segment preserves the selected value, and the RHS enters
    /// below the logical-and/or grammar level so unparenthesized mixing remains
    /// a syntax error instead of changing precedence.
    pub(in crate::engine::compiler) fn parse_coalesce(&mut self) -> Result<(), Error> {
        self.parse_logical_or()?;
        let mut short_circuits = Vec::new();
        while self.is_punctuator(Punctuator::NullishCoalesce) {
            self.advance()?;
            self.emit_instruction(Instruction::Dup)?;
            self.emit_instruction(Instruction::IsUndefinedOrNull)?;
            short_circuits.push(self.emit_instruction(Instruction::IfFalse(u32::MAX))?);
            self.emit_instruction(Instruction::Drop)?;
            self.parse_bitwise_or()?;
            self.anonymous_function_definition = None;
        }
        if !short_circuits.is_empty() {
            let end = self.current_ir().ops.len();
            for short_circuit in short_circuits {
                self.patch_jump(short_circuit, end)?;
            }
            self.current_ir_mut().context.last_member_reference = None;
            self.current_ir_mut().context.last_identifier_reference = None;
            self.current_ir_mut().context.last_optional_chain = None;
        }
        Ok(())
    }

    pub(in crate::engine::compiler) fn parse_logical_or(&mut self) -> Result<(), Error> {
        self.parse_logical_and()?;
        let mut composed = false;
        while self.is_punctuator(Punctuator::LogicalOr) {
            composed = true;
            self.advance()?;
            self.emit_instruction(Instruction::Dup)?;
            let end_jump = self.emit_instruction(Instruction::IfTrue(u32::MAX))?;
            self.emit_instruction(Instruction::Drop)?;
            self.parse_logical_and()?;
            self.patch_jump(end_jump, self.current_ir().ops.len())?;
            self.anonymous_function_definition = None;
        }
        if composed && self.is_punctuator(Punctuator::NullishCoalesce) {
            return Err(self.syntax_here("cannot mix ?? with && or ||"));
        }
        if composed {
            self.current_ir_mut().context.last_member_reference = None;
            self.current_ir_mut().context.last_identifier_reference = None;
            self.current_ir_mut().context.last_optional_chain = None;
        }
        Ok(())
    }

    pub(in crate::engine::compiler) fn parse_logical_and(&mut self) -> Result<(), Error> {
        self.parse_bitwise_or()?;
        let mut composed = false;
        while self.is_punctuator(Punctuator::LogicalAnd) {
            composed = true;
            self.advance()?;
            self.emit_instruction(Instruction::Dup)?;
            let end_jump = self.emit_instruction(Instruction::IfFalse(u32::MAX))?;
            self.emit_instruction(Instruction::Drop)?;
            self.parse_bitwise_or()?;
            self.patch_jump(end_jump, self.current_ir().ops.len())?;
            self.anonymous_function_definition = None;
        }
        if composed && self.is_punctuator(Punctuator::NullishCoalesce) {
            return Err(self.syntax_here("cannot mix ?? with && or ||"));
        }
        if composed {
            self.current_ir_mut().context.last_member_reference = None;
            self.current_ir_mut().context.last_identifier_reference = None;
            self.current_ir_mut().context.last_optional_chain = None;
        }
        Ok(())
    }

    pub(in crate::engine::compiler) fn parse_bitwise_or(&mut self) -> Result<(), Error> {
        self.parse_binary(1)
    }

    // Private-brand checks have a ShiftExpression RHS, not another relational
    // head. Keep that grammar boundary explicit in the precedence entry point.
    pub(in crate::engine::compiler) fn parse_shift(&mut self) -> Result<(), Error> {
        self.parse_binary(6)
    }

    fn parse_binary(&mut self, minimum: u8) -> Result<(), Error> {
        if minimum > 5 || !self.parse_private_in_head()? {
            self.parse_unary()?;
        }
        while let Some((precedence, operation)) = self.binary_operator() {
            if precedence < minimum {
                break;
            }
            let operation_span = self.current().span;
            self.advance()?;
            self.parse_binary(precedence + 1)?;
            self.emit_instruction_at(operation, source_offset(operation_span)?)?;
            self.anonymous_function_definition = None;
        }
        Ok(())
    }

    fn binary_operator(&self) -> Option<(u8, Instruction)> {
        use Punctuator::*;
        Some(match self.current().kind {
            TokenKind::Punctuator(operator) => match operator {
                BitOr => (1, Instruction::BitOr),
                BitXor => (2, Instruction::BitXor),
                BitAnd => (3, Instruction::BitAnd),
                EqualEqual => (4, Instruction::Eq),
                StrictEqual => (4, Instruction::StrictEq),
                NotEqual => (4, Instruction::Neq),
                StrictNotEqual => (4, Instruction::StrictNeq),
                Less => (5, Instruction::Lt),
                LessEqual => (5, Instruction::Lte),
                Greater => (5, Instruction::Gt),
                GreaterEqual => (5, Instruction::Gte),
                ShiftLeft => (6, Instruction::Shl),
                ShiftRight => (6, Instruction::Sar),
                UnsignedShiftRight => (6, Instruction::Shr),
                Plus => (7, Instruction::Add),
                Minus => (7, Instruction::Sub),
                Multiply => (8, Instruction::Mul),
                Divide => (8, Instruction::Div),
                Remainder => (8, Instruction::Mod),
                _ => return None,
            },
            TokenKind::Keyword(Keyword::Instanceof) => (5, Instruction::InstanceOf),
            TokenKind::Keyword(Keyword::In) if self.in_mode == InMode::Allow => {
                (5, Instruction::In)
            }
            _ => return None,
        })
    }

    pub(in crate::engine::compiler) fn parse_unary(&mut self) -> Result<(), Error> {
        self.parse_unary_with_power(PowerMode::Allowed)
    }

    fn parse_unary_operand(&mut self) -> Result<(), Error> {
        self.parse_recursion(ParserStackFrame::Unary, |parser| {
            parser.parse_unary_with_power(PowerMode::Forbidden)
        })
    }

    pub(in crate::engine::compiler) fn parse_unary_with_power(
        &mut self,
        power_mode: PowerMode,
    ) -> Result<(), Error> {
        if matches!(
            self.current().kind,
            TokenKind::Punctuator(Punctuator::Increment | Punctuator::Decrement)
        ) {
            let operator_span = self.current().span;
            let increment = self.is_punctuator(Punctuator::Increment);
            self.advance()?;
            // QuickJS passes no power flag for a prefix-update operand. This
            // leaves `**` for the outer update expression, so `++x ** 2` is
            // valid while the operand itself must still be an lvalue.
            self.parse_unary_with_power(PowerMode::None)?;
            self.lower_update_expression(operator_span, increment, false)?;
            return self.parse_power_suffix(power_mode);
        }
        if matches!(self.current().kind, TokenKind::Keyword(Keyword::Await)) {
            if !matches!(
                self.current_ir().execution_kind,
                BytecodeFunctionKind::Async | BytecodeFunctionKind::AsyncGenerator
            ) {
                return Err(self.syntax_here("unexpected 'await' keyword"));
            }
            if !self.current_ir().context.in_function_body {
                return Err(self.syntax_here("await in default expression"));
            }
            self.advance()?;
            self.parse_unary_operand()?;
            self.emit_instruction(Instruction::Await)?;
            self.anonymous_function_definition = None;
            self.current_ir_mut().context.last_member_reference = None;
            self.current_ir_mut().context.last_identifier_reference = None;
            self.current_ir_mut().context.last_optional_chain = None;
            return Ok(());
        }
        if matches!(self.current().kind, TokenKind::Keyword(Keyword::Typeof)) {
            self.advance()?;
            let operand_start = self.current_ir().ops.len();
            self.parse_unary_operand()?;

            // Parentheses do not change an IdentifierReference into a value
            // expression, so both `typeof missing` and `typeof (missing)` use
            // QuickJS' non-throwing global lookup.  Calls, comma expressions,
            // binary operators, and every other composed expression emit
            // additional IR and therefore retain ordinary throwing lookup.
            if self.current_ir().ops.len() == operand_start + 1
                && let Some(SpannedIrOp {
                    op: IrOp::Identifier { access, .. },
                    ..
                }) = self.current_ir_mut().ops.get_mut(operand_start)
                && *access == IdentifierAccess::Get
            {
                *access = IdentifierAccess::GetOrUndefined;
            }
            self.emit_instruction(Instruction::TypeOf)?;
            self.anonymous_function_definition = None;
            return self.parse_power_suffix(power_mode);
        }
        if matches!(self.current().kind, TokenKind::Keyword(Keyword::Delete)) {
            self.advance()?;
            let operand_start = self.current_ir().ops.len();
            self.parse_unary_operand()?;
            // Chain close deliberately clears a terminal private Reference,
            // so optional private delete falls through to the ordinary
            // value-delete path: it performs the branded read when live and
            // returns true without deleting. Only public terminal References
            // retain metadata for the Delete-specific branch rewrite.
            let terminal_optional_chain = {
                let function = self.current_ir_mut();
                if function
                    .context
                    .last_optional_chain
                    .as_ref()
                    .is_some_and(|chain| {
                        chain.terminal_member_get == function.context.last_member_reference
                            && chain.terminal_member_get == function.ops.len().checked_sub(1)
                    })
                {
                    function.context.last_optional_chain.take()
                } else {
                    None
                }
            };
            if let Some(target) = self.take_tail_member_reference()? {
                match target {
                    MemberReference::Field { key, site } => {
                        self.emit_with_site(IrOp::PushConstant(key), Some(site))?;
                        self.emit_instruction(Instruction::Delete)?;
                    }
                    MemberReference::Computed { site } => {
                        self.emit_instruction_at(Instruction::Delete, site)?;
                    }
                    MemberReference::Super { site } => {
                        self.emit_instruction_at(Instruction::ThrowDeleteSuper, site)?;
                    }
                    MemberReference::Private { .. } => {
                        // QuickJS diagnoses after the complete operand has
                        // been parsed, so the current token is the one after
                        // the private reference.
                        return Err(self.syntax_here("cannot delete a private class field"));
                    }
                }
                if let Some(chain) = terminal_optional_chain {
                    self.rewrite_optional_chain_delete_fallback(chain)?;
                }
            } else if self.current_ir().ops.len() == operand_start + 1
                && matches!(
                    self.current_ir().ops[operand_start].op,
                    IrOp::Identifier {
                        access: IdentifierAccess::Get,
                        ..
                    }
                )
            {
                if self.current_ir().strict {
                    return Err(self.syntax_here("cannot delete a direct reference in strict mode"));
                }
                let Some(SpannedIrOp {
                    op: IrOp::Identifier { access, .. },
                    ..
                }) = self.current_ir_mut().ops.get_mut(operand_start)
                else {
                    return Err(Error::internal(
                        "direct delete identifier operation disappeared",
                    ));
                };
                *access = IdentifierAccess::Delete;
                self.current_ir_mut().context.last_identifier_reference = None;
            } else {
                self.emit_instruction(Instruction::Drop)?;
                self.emit_instruction(Instruction::PushTrue)?;
            }
            self.anonymous_function_definition = None;
            return self.parse_power_suffix(power_mode);
        }
        let operation_span = self.current().span;
        let operation = match self.current().kind {
            TokenKind::Punctuator(Punctuator::Plus) => Some(Instruction::Plus),
            TokenKind::Punctuator(Punctuator::Minus) => Some(Instruction::Neg),
            TokenKind::Punctuator(Punctuator::BitNot) => Some(Instruction::BitNot),
            TokenKind::Punctuator(Punctuator::Not) => Some(Instruction::Not),
            TokenKind::Keyword(Keyword::Void) => {
                self.advance()?;
                self.parse_unary_operand()?;
                self.emit_instruction(Instruction::Drop)?;
                self.emit_instruction(Instruction::Undefined)?;
                self.anonymous_function_definition = None;
                return self.parse_power_suffix(power_mode);
            }
            _ => None,
        };
        if let Some(operation) = operation {
            self.advance()?;
            self.parse_unary_operand()?;
            if matches!(
                operation,
                Instruction::Plus | Instruction::Neg | Instruction::BitNot
            ) {
                self.emit_instruction_at(operation, source_offset(operation_span)?)?;
            } else {
                self.emit_instruction(operation)?;
            }
            self.anonymous_function_definition = None;
            return self.parse_power_suffix(power_mode);
        }
        self.parse_postfix()?;
        self.parse_power_suffix(power_mode)
    }

    pub(in crate::engine::compiler) fn parse_power_suffix(
        &mut self,
        power_mode: PowerMode,
    ) -> Result<(), Error> {
        if !self.is_punctuator(Punctuator::Exponent) {
            return Ok(());
        }
        match power_mode {
            PowerMode::None => return Ok(()),
            PowerMode::Forbidden => {
                return Err(Error::new(
                    ErrorKind::Syntax,
                    "unparenthesized unary expression can't appear on the left-hand side of '**'",
                ));
            }
            PowerMode::Allowed => {}
        }

        let operation_span = self.current().span;
        self.advance()?;
        self.parse_recursion(ParserStackFrame::Exponentiation, |parser| {
            parser.parse_unary_with_power(PowerMode::Allowed)
        })?;
        self.emit_instruction_at(Instruction::Pow, source_offset(operation_span)?)?;
        self.anonymous_function_definition = None;
        Ok(())
    }

    pub(in crate::engine::compiler) fn parse_postfix(&mut self) -> Result<(), Error> {
        self.parse_left_hand_side_expression()?;
        if !self.current().line_terminator_before
            && matches!(
                self.current().kind,
                TokenKind::Punctuator(Punctuator::Increment | Punctuator::Decrement)
            )
        {
            let operator_span = self.current().span;
            let increment = self.is_punctuator(Punctuator::Increment);
            self.lower_update_expression(operator_span, increment, true)?;
            self.advance()?;
        }
        Ok(())
    }

    /// Parse the LeftHandSideExpression subset shared by assignment and a
    /// for-of assignment target, deliberately stopping before postfix update.
    pub(in crate::engine::compiler) fn parse_left_hand_side_expression(
        &mut self,
    ) -> Result<(), Error> {
        self.parse_primary(true)?;
        let mut optional_chain: Option<PendingOptionalChain> = None;
        loop {
            let optional_call = if self.is_punctuator(Punctuator::OptionalChain) {
                let optional_span = self.current().span;
                self.advance()?;
                let chain = optional_chain.get_or_insert_default();
                if !self.is_punctuator(Punctuator::LeftParen) {
                    self.emit_optional_chain_test(chain, 1)?;
                    self.parse_optional_member_suffix(optional_span)?;
                    continue;
                }
                true
            } else {
                false
            };

            if self.parse_member_suffix()? {
                continue;
            }

            if optional_call || self.is_punctuator(Punctuator::LeftParen) {
                let call_span = self.current().span;
                let member_method = self.promote_last_member_get_for_call()?;
                // QuickJS selects OP_eval from the syntactic callee before
                // binding resolution. Parentheses preserve IdentifierReference,
                // while comma/member/other composed expressions have already
                // cleared this marker. Runtime identity still decides whether
                // this is original eval or an ordinary replacement call.
                //
                // `eval?.()` is deliberately indirect: the optional call
                // consumes the identifier marker as an ordinary callable
                // Reference and never emits EvalCall.
                let direct_eval_scope = if member_method || optional_call {
                    None
                } else {
                    self.take_direct_eval_scope()?
                };
                // An authored `with` may turn an identifier call into a method
                // call whose receiver is the selected object environment. The
                // unresolved Reference keeps the same two-slot call shape even
                // when resolution later proves the receiver is `undefined`.
                let identifier_method = if member_method || direct_eval_scope.is_some() {
                    false
                } else {
                    self.promote_tail_identifier_get(IdentifierReferenceAccess::Call)?
                        .is_some_and(|reference| reference.object_environment)
                };
                if optional_call && identifier_method {
                    // Pinned QuickJS 2026-06-04 promotes an authored-with
                    // identifier to a two-slot Reference, then applies the
                    // optional-call test with the one-slot accounting used by
                    // ordinary identifier calls. Its verifier rejects the
                    // resulting function before execution.
                    return Err(Error::new(ErrorKind::JsInternal, "inconsistent stack size"));
                }
                if optional_call {
                    self.emit_optional_chain_test(
                        optional_chain
                            .as_mut()
                            .ok_or_else(|| Error::internal("optional call lost its chain"))?,
                        if member_method || identifier_method {
                            2
                        } else {
                            1
                        },
                    )?;
                }
                self.advance()?;
                let arguments = self.parse_call_arguments()?;
                if let Some(scope) = direct_eval_scope {
                    self.emit_at(
                        IrOp::EvalCall {
                            arguments,
                            scope,
                            environment: None,
                        },
                        source_offset(call_span)?,
                    )?;
                } else {
                    match arguments {
                        CallArguments::Fixed(argument_count) => {
                            let instruction = if member_method || identifier_method {
                                Instruction::CallMethod(argument_count)
                            } else {
                                Instruction::Call(argument_count)
                            };
                            self.emit_instruction_at(instruction, source_offset(call_span)?)?;
                        }
                        CallArguments::Spread => {
                            if member_method || identifier_method {
                                // QuickJS `obj func array -> func obj array`.
                                self.emit_instruction(Instruction::Perm3)?;
                            } else {
                                // QuickJS `func array -> func undefined array`.
                                self.emit_instruction(Instruction::Undefined)?;
                                self.emit_instruction(Instruction::Insert2)?;
                                self.emit_instruction(Instruction::Drop)?;
                            }
                            self.emit_instruction_at(
                                Instruction::Apply(ApplyKind::Call),
                                source_offset(call_span)?,
                            )?;
                        }
                    }
                }
                self.anonymous_function_definition = None;
                continue;
            }
            if optional_chain.is_some() && matches!(self.current().kind, TokenKind::Template(_)) {
                return Err(self.syntax_here("template literal cannot appear in an optional chain"));
            }
            if self.parse_tagged_template_suffix()? {
                continue;
            }
            break;
        }
        if let Some(optional_chain) = optional_chain {
            self.finish_optional_chain(optional_chain)?;
        }
        Ok(())
    }

    /// Lower QuickJS's `get_lvalue(..., keep = TRUE)` followed by one of
    /// `inc`, `dec`, `post_inc`, or `post_dec`, then its matching
    /// `put_lvalue` keep mode. Prefix updates preserve the replacement value;
    /// postfix updates preserve the old, already-converted numeric value.
    pub(in crate::engine::compiler) fn lower_update_expression(
        &mut self,
        operator_span: Span,
        increment: bool,
        postfix: bool,
    ) -> Result<(), Error> {
        if self.current_ir().context.last_optional_chain.is_some() {
            return Err(self.syntax_here("invalid increment/decrement operand"));
        }
        let operation = match (postfix, increment) {
            (false, true) => Instruction::Inc,
            (false, false) => Instruction::Dec,
            (true, true) => Instruction::PostInc,
            (true, false) => Instruction::PostDec,
        };

        if let Some(target) = self.promote_tail_identifier_get(IdentifierReferenceAccess::Get)? {
            self.validate_identifier_assignment_target(&target)?;
            self.emit_instruction_at(operation, source_offset(operator_span)?)?;
            if target.object_environment {
                self.emit_identifier_reference_inherited(
                    target.name,
                    target.span,
                    target.scope,
                    if postfix {
                        IdentifierReferenceAccess::PostPut
                    } else {
                        IdentifierReferenceAccess::Set
                    },
                )?;
            } else {
                self.emit_identifier_inherited(
                    target.name,
                    target.span,
                    target.scope,
                    if postfix {
                        IdentifierAccess::Put
                    } else {
                        IdentifierAccess::Set
                    },
                )?;
            }
            self.anonymous_function_definition = None;
            return Ok(());
        }

        let Some(target) = self.promote_tail_member_get_for_compound()? else {
            return Err(self.syntax_here("invalid increment/decrement operand"));
        };
        self.emit_instruction_at(operation, source_offset(operator_span)?)?;
        self.anonymous_function_definition = None;
        if postfix {
            self.emit_member_post_put(target)
        } else {
            self.emit_member_put(target)
        }
    }

    /// Parse one member suffix without accepting a call. This is shared by
    /// ordinary postfix chains and constructor heads after `new`, matching
    /// QuickJS's `PF_POSTFIX_CALL` split.
    pub(in crate::engine::compiler) fn parse_member_suffix(&mut self) -> Result<bool, Error> {
        if self.is_punctuator(Punctuator::Dot) {
            let member_span = self.current().span;
            self.advance()?;
            let token = *self.current();
            let name = match token.kind {
                TokenKind::PrivateIdentifier(identifier) => {
                    let name = self.intern_private_identifier(&identifier);
                    self.advance()?;
                    let operation =
                        self.emit_private_field_get(name, token.span, source_offset(member_span)?)?;
                    self.current_ir_mut().context.last_member_reference = Some(operation);
                    self.anonymous_function_definition = None;
                    return Ok(true);
                }
                TokenKind::Identifier(identifier) => self.intern_identifier(&identifier),
                TokenKind::Keyword(keyword) => self.intern_name(keyword.as_str()),
                _ => return Err(self.syntax_here("expecting field name")),
            };
            self.advance()?;
            let value = self.names.js_string(name)?;
            let key = self.add_constant(IrConstant::Primitive(Value::String(value)))?;
            let operation =
                self.emit_instruction_at(Instruction::GetField(key), source_offset(member_span)?)?;
            self.current_ir_mut().context.last_member_reference = Some(operation);
            self.anonymous_function_definition = None;
            return Ok(true);
        }

        if self.is_punctuator(Punctuator::LeftBracket) {
            let member_span = self.current().span;
            self.advance()?;
            self.parse_recursion(ParserStackFrame::MemberAccess, Self::parse_expression)?;
            self.expect_punctuator(Punctuator::RightBracket)?;
            let operation =
                self.emit_instruction_at(Instruction::GetArrayEl, source_offset(member_span)?)?;
            self.current_ir_mut().context.last_member_reference = Some(operation);
            self.anonymous_function_definition = None;
            return Ok(true);
        }
        Ok(false)
    }

    /// QuickJS rewrites the immediately preceding member getter when `(`
    /// proves that its Reference is being called. The keep form leaves the
    /// original base below the function so `CallMethod` receives the exact
    /// receiver without re-evaluating either base or computed key.
    pub(in crate::engine::compiler) fn promote_last_member_get_for_call(
        &mut self,
    ) -> Result<bool, Error> {
        let function = self.current_ir_mut();
        if function.context.last_member_reference != function.ops.len().checked_sub(1) {
            return Ok(false);
        }
        let terminal_get = function.context.last_member_reference;
        let Some(last) = function.ops.last_mut() else {
            return Ok(false);
        };
        let promoted = match &mut last.op {
            IrOp::Bytecode(instruction @ Instruction::GetField(_)) => {
                let Instruction::GetField(key) = *instruction else {
                    unreachable!();
                };
                *instruction = Instruction::GetField2(key);
                true
            }
            IrOp::Bytecode(instruction @ Instruction::GetArrayEl) => {
                *instruction = Instruction::GetArrayEl2;
                true
            }
            IrOp::Bytecode(instruction @ Instruction::GetSuperValue) => {
                *instruction = Instruction::GetSuperValueForCall;
                true
            }
            IrOp::PrivateField { access, .. } if *access == PrivateFieldAccess::Get => {
                *access = PrivateFieldAccess::GetKeepReceiver;
                true
            }
            _ => false,
        };
        if promoted {
            function.context.stack_depth = function
                .context
                .stack_depth
                .checked_add(1)
                .ok_or_else(|| Error::new(ErrorKind::JsInternal, "stack overflow"))?;
            optional_chain::pad_grouped_method_receiver(function, terminal_get)?;
        }
        function.context.last_member_reference = None;
        Ok(promoted)
    }

    /// Keep the final identifier read in place while exposing its unresolved
    /// binding metadata to compound-assignment lowering. Parentheses preserve
    /// this marker; every operation that turns the Reference into a value
    /// clears it through `emit_with_site` or the composing parser level.
    pub(in crate::engine::compiler) fn promote_tail_identifier_get(
        &mut self,
        reference_access: IdentifierReferenceAccess,
    ) -> Result<Option<IdentifierReference>, Error> {
        let function_id = self.current_function;
        let function = self.current_ir();
        if function.context.last_identifier_reference != function.ops.len().checked_sub(1) {
            return Ok(None);
        }
        let Some(SpannedIrOp {
            op:
                IrOp::Identifier {
                    name,
                    span,
                    scope,
                    access: IdentifierAccess::Get,
                },
            ..
        }) = function.ops.last()
        else {
            return Err(Error::internal(
                "identifier Reference marker did not point to a getter",
            ));
        };
        let object_environment = self.parser_scope_has_authored_with(function_id, *scope)?;
        let span_id = *span;
        let reference = IdentifierReference {
            name: *name,
            span: function.operands.span(span_id),
            scope: *scope,
            object_environment,
        };
        let function = self.current_ir_mut();
        function.context.last_identifier_reference = None;
        if object_environment {
            let Some(SpannedIrOp { op, .. }) = function.ops.last_mut() else {
                return Err(Error::internal(
                    "identifier Reference marker did not point to a getter",
                ));
            };
            *op = IrOp::IdentifierReference {
                name: reference.name,
                span: span_id,
                scope: reference.scope,
                access: reference_access,
            };
            function.context.stack_depth = function
                .context
                .stack_depth
                .checked_add(1)
                .ok_or_else(|| Error::new(ErrorKind::JsInternal, "stack overflow"))?;
        }
        Ok(Some(reference))
    }

    pub(in crate::engine::compiler) fn parser_scope_has_authored_with(
        &self,
        mut function_id: FunctionId,
        mut scope: ScopeId,
    ) -> Result<bool, Error> {
        loop {
            loop {
                let current = self.functions[function_id]
                    .scopes
                    .get(scope.0)
                    .ok_or_else(|| Error::internal("identifier use scope is out of bounds"))?;
                if current.kind == ScopeKind::With {
                    return Ok(true);
                }
                let Some(parent) = current.parent else {
                    break;
                };
                scope = parent;
            }
            let Some(parent) = self.functions[function_id].parent else {
                return Ok(false);
            };
            function_id = parent.function;
            scope = parent.definition_scope;
        }
    }

    /// Consume only the parser marker for a syntactic direct-eval callee. The
    /// getter itself deliberately remains an ordinary Identifier operation so
    /// `EvalCall` retains QuickJS's undefined-receiver fallback when the
    /// resolved function is not the realm's original `%eval%`.
    pub(in crate::engine::compiler) fn take_direct_eval_scope(
        &mut self,
    ) -> Result<Option<ScopeId>, Error> {
        let (name, scope) = {
            let function = self.current_ir_mut();
            if function.context.last_identifier_reference != function.ops.len().checked_sub(1) {
                return Ok(None);
            }
            let Some(SpannedIrOp {
                op:
                    IrOp::Identifier {
                        name,
                        scope,
                        access: IdentifierAccess::Get,
                        ..
                    },
                ..
            }) = function.ops.last()
            else {
                return Err(Error::internal(
                    "identifier Reference marker did not point to a getter",
                ));
            };
            (*name, *scope)
        };
        if self.names.name(name) != "eval" {
            return Ok(None);
        }
        self.current_ir_mut().context.last_identifier_reference = None;
        Ok(Some(scope))
    }

    /// Turn the final getter into a base-only Reference preparation for `=`.
    /// Both operations push one abstract value, so no stack-depth correction
    /// is needed while the late resolver decides whether that value is a
    /// selected object or the static `undefined` sentinel.
    pub(in crate::engine::compiler) fn take_tail_identifier_reference(
        &mut self,
    ) -> Result<Option<IdentifierReference>, Error> {
        let function_id = self.current_function;
        let function = self.current_ir();
        if function.context.last_identifier_reference != function.ops.len().checked_sub(1) {
            return Ok(None);
        }
        let Some(SpannedIrOp {
            op:
                IrOp::Identifier {
                    name,
                    span,
                    scope,
                    access: IdentifierAccess::Get,
                },
            ..
        }) = function.ops.last()
        else {
            return Err(Error::internal(
                "identifier Reference operation disappeared",
            ));
        };
        let object_environment = self.parser_scope_has_authored_with(function_id, *scope)?;
        let span_id = *span;
        let reference = IdentifierReference {
            name: *name,
            span: function.operands.span(span_id),
            scope: *scope,
            object_environment,
        };
        let function = self.current_ir_mut();
        function.context.last_identifier_reference = None;
        if object_environment {
            let Some(SpannedIrOp { op, .. }) = function.ops.last_mut() else {
                return Err(Error::internal(
                    "identifier Reference operation disappeared",
                ));
            };
            *op = IrOp::IdentifierReference {
                name: reference.name,
                span: span_id,
                scope: reference.scope,
                access: IdentifierReferenceAccess::Prepare,
            };
        } else {
            function
                .ops
                .pop()
                .ok_or_else(|| Error::internal("identifier Reference operation disappeared"))?;
            function.context.stack_depth =
                function.context.stack_depth.checked_sub(1).ok_or_else(|| {
                    Error::internal("identifier lvalue removal underflowed the stack")
                })?;
        }
        Ok(Some(reference))
    }

    /// Remove the final getter while leaving its already-evaluated base/key
    /// operands on the abstract stack. This mirrors QuickJS `get_lvalue` and
    /// is shared by assignment and `delete` rewrites.
    pub(in crate::engine::compiler) fn take_tail_member_reference(
        &mut self,
    ) -> Result<Option<MemberReference>, Error> {
        let function = self.current_ir_mut();
        if function.context.last_member_reference != function.ops.len().checked_sub(1) {
            return Ok(None);
        }
        function.context.last_member_reference = None;
        let SpannedIrOp { op, pc_site } = function
            .ops
            .pop()
            .ok_or_else(|| Error::internal("member Reference operation disappeared"))?;
        let site = pc_site.ok_or_else(|| Error::internal("member getter has no source site"))?;
        match op {
            IrOp::Bytecode(Instruction::GetField(key)) => {
                Ok(Some(MemberReference::Field { key, site }))
            }
            IrOp::Bytecode(Instruction::GetArrayEl) => {
                // Removing a 2 -> 1 getter restores the raw `[base, key]`
                // operands produced by the preceding IR.
                function.context.stack_depth = function
                    .context
                    .stack_depth
                    .checked_add(1)
                    .ok_or_else(|| Error::new(ErrorKind::JsInternal, "stack overflow"))?;
                Ok(Some(MemberReference::Computed { site }))
            }
            IrOp::Bytecode(Instruction::GetSuperValue) => {
                // Removing a 3 -> 1 getter restores the authenticated method
                // receiver, frozen super base, and raw property key.
                function.context.stack_depth = function
                    .context
                    .stack_depth
                    .checked_add(2)
                    .ok_or_else(|| Error::new(ErrorKind::JsInternal, "stack overflow"))?;
                Ok(Some(MemberReference::Super { site }))
            }
            IrOp::PrivateField {
                name,
                span,
                scope,
                access: PrivateFieldAccess::Get,
            } => Ok(Some(MemberReference::Private {
                name,
                span: function.operands.span(span),
                scope,
                site,
            })),
            _ => Err(Error::internal(
                "member Reference marker did not point to a getter",
            )),
        }
    }

    /// Keep both the lvalue operands and the old value for compound
    /// assignment. The computed form also retains the already-converted key,
    /// exactly matching QuickJS `get_array_el3`.
    pub(in crate::engine::compiler) fn promote_tail_member_get_for_compound(
        &mut self,
    ) -> Result<Option<MemberReference>, Error> {
        let super_site = {
            let function = self.current_ir();
            if function.context.last_member_reference == function.ops.len().checked_sub(1) {
                function.ops.last().and_then(|last| {
                    matches!(last.op, IrOp::Bytecode(Instruction::GetSuperValue))
                        .then_some(last.pc_site)
                        .flatten()
                })
            } else {
                None
            }
        };
        if let Some(site) = super_site {
            {
                let function = self.current_ir_mut();
                function.context.last_member_reference = None;
                let last = function
                    .ops
                    .last_mut()
                    .ok_or_else(|| Error::internal("super Reference operation disappeared"))?;
                last.op = IrOp::Bytecode(Instruction::ToPropKey);
                last.pc_site = None;
                // Replacing 3 -> 1 with 1 -> 1 restores the three Reference
                // operands before QuickJS's dup3/get_super_value keep form.
                function.context.stack_depth = function
                    .context
                    .stack_depth
                    .checked_add(2)
                    .ok_or_else(|| Error::new(ErrorKind::JsInternal, "stack overflow"))?;
            }
            self.emit_instruction(Instruction::Dup3)?;
            self.emit_instruction_at(Instruction::GetSuperValue, site)?;
            return Ok(Some(MemberReference::Super { site }));
        }

        let function = self.current_ir_mut();
        if function.context.last_member_reference != function.ops.len().checked_sub(1) {
            return Ok(None);
        }
        function.context.last_member_reference = None;
        let operands = &function.ir.operands;
        let last = function
            .ir
            .ops
            .last_mut()
            .ok_or_else(|| Error::internal("member Reference operation disappeared"))?;
        let site = last
            .pc_site
            .ok_or_else(|| Error::internal("member getter has no source site"))?;
        let (target, extra_depth) = match &mut last.op {
            IrOp::Bytecode(instruction @ Instruction::GetField(_)) => {
                let Instruction::GetField(key) = *instruction else {
                    unreachable!();
                };
                *instruction = Instruction::GetField2(key);
                (MemberReference::Field { key, site }, 1)
            }
            IrOp::Bytecode(instruction @ Instruction::GetArrayEl) => {
                *instruction = Instruction::GetArrayEl3;
                (MemberReference::Computed { site }, 2)
            }
            IrOp::PrivateField {
                name,
                span,
                scope,
                access,
            } if *access == PrivateFieldAccess::Get => {
                *access = PrivateFieldAccess::GetKeepReceiver;
                (
                    MemberReference::Private {
                        name: *name,
                        span: operands.span(*span),
                        scope: *scope,
                        site,
                    },
                    1,
                )
            }
            _ => {
                return Err(Error::internal(
                    "member Reference marker did not point to a getter",
                ));
            }
        };
        function.context.stack_depth = function
            .context
            .stack_depth
            .checked_add(extra_depth)
            .ok_or_else(|| Error::new(ErrorKind::JsInternal, "stack overflow"))?;
        Ok(Some(target))
    }

    pub(in crate::engine::compiler) fn emit_member_put(
        &mut self,
        target: MemberReference,
    ) -> Result<(), Error> {
        match target {
            MemberReference::Field { key, .. } => {
                self.emit_instruction(Instruction::Insert2)?;
                self.emit_instruction(Instruction::PutField(key))?;
            }
            MemberReference::Computed { .. } => {
                self.emit_instruction(Instruction::Insert3)?;
                self.emit_instruction(Instruction::PutArrayEl)?;
            }
            MemberReference::Super { .. } => {
                self.emit_instruction(Instruction::Insert4)?;
                self.emit_instruction(Instruction::PutSuperValue)?;
            }
            MemberReference::Private {
                name,
                span,
                scope,
                site,
            } => {
                self.emit_instruction(Instruction::Insert2)?;
                self.emit_private_field_operation(
                    name,
                    span,
                    scope,
                    PrivateFieldAccess::Put,
                    site,
                )?;
            }
        }
        Ok(())
    }

    /// QuickJS `PUT_LVALUE_KEEP_SECOND`: move the old numeric value below the
    /// kept member Reference, then consume the Reference and replacement.
    pub(in crate::engine::compiler) fn emit_member_post_put(
        &mut self,
        target: MemberReference,
    ) -> Result<(), Error> {
        match target {
            MemberReference::Field { key, .. } => {
                self.emit_instruction(Instruction::Perm3)?;
                self.emit_instruction(Instruction::PutField(key))?;
            }
            MemberReference::Computed { .. } => {
                self.emit_instruction(Instruction::Perm4)?;
                self.emit_instruction(Instruction::PutArrayEl)?;
            }
            MemberReference::Super { .. } => {
                self.emit_instruction(Instruction::Perm5)?;
                self.emit_instruction(Instruction::PutSuperValue)?;
            }
            MemberReference::Private {
                name,
                span,
                scope,
                site,
            } => {
                self.emit_instruction(Instruction::Perm3)?;
                self.emit_private_field_operation(
                    name,
                    span,
                    scope,
                    PrivateFieldAccess::Put,
                    site,
                )?;
            }
        }
        Ok(())
    }
}