php-rs-parser 0.25.0

Fast PHP parser producing a typed AST
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
use php_ast::*;
use php_lexer::TokenKind;

use crate::diagnostics::{ForbiddenRule, ParseError};
use crate::instrument;
use crate::parser::Parser;
use crate::precedence::{
    self, ASSIGNMENT_BP, MEMBER_ACCESS_BP, NULL_COALESCE_LEFT_BP, SCOPE_RESOLUTION_BP, TERNARY_BP,
};
use crate::version::PhpVersion;
use php_ast::span::Span;

mod atom;
pub(crate) mod interpolation;

// Re-exports so external callers' paths don't change
pub(crate) use atom::{
    parse_arg_list_or_callable, parse_arrow_function, parse_closure, ArgListResult,
};

use atom::{parse_atom, parse_function_call};

/// Returns the "chain group" binding power for a non-associative token, if applicable.
///
/// PHP 8.0+ rejects chaining non-associative operators within the same precedence group:
/// - Equality group (bp 25): `==`, `!=`, `===`, `!==`, `<=>`
/// - Comparison group (bp 27): `<`, `>`, `<=`, `>=`
///
/// `instanceof` is intentionally excluded: PHP allows `$a instanceof Foo instanceof Bar`
/// at parse time and does not reject cross-group chains like `$a > $b == $c`.
fn nonassoc_chain_level_for_token(kind: TokenKind) -> Option<u8> {
    match kind {
        TokenKind::EqualsEquals
        | TokenKind::BangEquals
        | TokenKind::EqualsEqualsEquals
        | TokenKind::BangEqualsEquals
        | TokenKind::Spaceship => Some(25),
        TokenKind::LessThan
        | TokenKind::GreaterThan
        | TokenKind::LessThanEquals
        | TokenKind::GreaterThanEquals => Some(27),
        _ => None,
    }
}

/// Returns the "chain group" binding power for a binary op produced by a non-associative token.
///
/// Mirrors `nonassoc_chain_level_for_token` but operates on the already-parsed binary op.
/// `instanceof` returns `None` for the same reasons described above.
fn nonassoc_chain_level_for_op(op: BinaryOp) -> Option<u8> {
    match op {
        BinaryOp::Equal
        | BinaryOp::NotEqual
        | BinaryOp::Identical
        | BinaryOp::NotIdentical
        | BinaryOp::Spaceship => Some(25),
        BinaryOp::Less | BinaryOp::Greater | BinaryOp::LessOrEqual | BinaryOp::GreaterOrEqual => {
            Some(27)
        }
        _ => None,
    }
}

/// Returns true if `kind` is a valid PHP assignment target (lvalue).
///
/// Valid targets: variable, variable-variable, array access, property access,
/// static property access and array/list destructuring.
/// Invalid targets emit a `ParseError::Forbidden` diagnostic at the assignment site.
fn is_valid_assignment_target(kind: &ExprKind<'_, '_>) -> bool {
    matches!(
        kind,
        ExprKind::Variable(_)
            | ExprKind::VariableVariable(_)
            | ExprKind::ArrayAccess(_)
            | ExprKind::PropertyAccess(_)
            | ExprKind::NullsafePropertyAccess(_)
            | ExprKind::StaticPropertyAccess(_)
            | ExprKind::StaticPropertyAccessDynamic { .. }
            | ExprKind::Array(_)
            | ExprKind::Error
    )
}

/// Report an operand of `++` or `--` that PHP cannot write to.
pub(crate) fn check_increment_operand(parser: &mut Parser<'_, '_>, operand: &Expr<'_, '_>) {
    let (rule, message) = if !matches!(
        operand.kind,
        ExprKind::Variable(_)
            | ExprKind::VariableVariable(_)
            | ExprKind::ArrayAccess(_)
            | ExprKind::PropertyAccess(_)
            | ExprKind::NullsafePropertyAccess(_)
            | ExprKind::StaticPropertyAccess(_)
            | ExprKind::StaticPropertyAccessDynamic { .. }
            | ExprKind::Error
    ) {
        (
            ForbiddenRule::IncDecNonVariable,
            "Cannot increment or decrement an expression that is not a variable",
        )
    } else if let Some(error) = temporary_write_message(&operand.kind, parser.version) {
        error
    } else if has_nullsafe_link(&operand.kind) {
        (
            ForbiddenRule::NullsafeWrite,
            "Can't use nullsafe operator in write context",
        )
    } else {
        return check_special_variable_write(parser, operand, WriteKind::Modify);
    };
    parser.forbid(rule, message, operand.span);
}

/// Report `target` where PHP writes to it (an `unset` argument, a `foreach`
/// target or a by-reference array element) unless it is writable;
/// `allow_list` permits a destructuring list.
pub(crate) fn check_write_target(
    parser: &mut Parser<'_, '_>,
    target: &Expr<'_, '_>,
    allow_list: bool,
) {
    let (rule, message) = if let Some(error) = temporary_write_message(&target.kind, parser.version)
    {
        error
    } else if has_nullsafe_link(&target.kind) {
        (
            ForbiddenRule::NullsafeWrite,
            "Can't use nullsafe operator in write context",
        )
    } else if !is_valid_assignment_target(&target.kind)
        || !allow_list && matches!(target.kind, ExprKind::Array(_))
    {
        (
            ForbiddenRule::InvalidWriteContext,
            "Can't use this expression in write context",
        )
    } else if !is_valid_destructure_element(&target.kind, parser.version) {
        (
            ForbiddenRule::UnwritableDestructuringElement,
            "Assignments can only happen to writable values",
        )
    } else {
        return;
    };
    parser.forbid(rule, message, target.span);
}

/// How a write reaches its target; PHP rejects different writes to `$this` and `$GLOBALS`.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum WriteKind {
    /// `=`, `=&`, `??=`, destructuring and `foreach` targets.
    Assign,
    /// Compound assignment, `++` / `--` and by-reference array elements.
    Modify,
    /// The source of `=&`.
    Reference,
    Unset,
}

/// Report a write PHP forbids to `$this` or `$GLOBALS`.
pub(crate) fn check_special_variable_write(
    parser: &mut Parser<'_, '_>,
    target: &Expr<'_, '_>,
    kind: WriteKind,
) {
    let (rule, message) = match &target.kind {
        ExprKind::Array(elems) if kind == WriteKind::Assign => {
            for el in elems.iter() {
                let mut value = el.value();
                while let ExprKind::Parenthesized(inner) = &value.kind {
                    value = inner;
                }
                // A by-reference element was checked as an array literal.
                if !el.is_by_ref() || is_variable_named(value, "this") {
                    check_special_variable_write(parser, value, kind);
                }
            }
            return;
        }
        ExprKind::Variable(name) => match (name.as_str(), kind) {
            ("this", WriteKind::Assign) => (ForbiddenRule::ReassignThis, "Cannot re-assign $this"),
            ("this", WriteKind::Unset) => (ForbiddenRule::UnsetThis, "Cannot unset $this"),
            ("GLOBALS", _) if parser.version < PhpVersion::Php81 => return,
            ("GLOBALS", WriteKind::Reference) => (
                ForbiddenRule::InvalidGlobalsWrite,
                "Cannot acquire reference to $GLOBALS",
            ),
            ("GLOBALS", _) => (
                ForbiddenRule::InvalidGlobalsWrite,
                "$GLOBALS can only be modified using the $GLOBALS[$name] = $value syntax",
            ),
            _ => return,
        },
        _ => return,
    };
    parser.forbid(rule, message, target.span);
}

fn is_variable_named(expr: &Expr<'_, '_>, name: &str) -> bool {
    matches!(&expr.kind, ExprKind::Variable(n) if n.as_str() == name)
}

/// Names PHP registers as auto-globals.
pub(crate) fn is_superglobal(name: &str) -> bool {
    matches!(
        name,
        "GLOBALS"
            | "_GET"
            | "_POST"
            | "_COOKIE"
            | "_FILES"
            | "_SERVER"
            | "_ENV"
            | "_REQUEST"
            | "_SESSION"
    )
}

/// True for the unqualified `clone` that the parser only produces from the keyword.
fn is_clone_keyword(name: &Expr<'_, '_>) -> bool {
    matches!(&name.kind, ExprKind::Name(Name::Simple { value, .. }) if value.eq_ignore_ascii_case("clone"))
}

/// Report `->`, `?->`, `::`, `[` or a call applied to an expression PHP cannot
/// dereference, such as `match (...) {...}[0]`, `1->a` or `function () {}()`.
fn check_dereferencable(parser: &mut Parser<'_, '_>, lhs: &Expr<'_, '_>, op: TokenKind) {
    let dereferencable = match lhs.kind {
        ExprKind::Match(_)
        | ExprKind::Closure(_)
        | ExprKind::ArrowFunction(_)
        | ExprKind::Int(_)
        | ExprKind::Float(_)
        | ExprKind::Heredoc { .. }
        | ExprKind::Nowdoc { .. }
        | ExprKind::ShellExec(_)
        | ExprKind::Isset(_)
        | ExprKind::Empty(_)
        | ExprKind::Exit(_)
        | ExprKind::Eval(_) => false,
        ExprKind::Array(_) => !is_list_syntax(parser.source(), lhs.span),
        ExprKind::MagicConst(_) => !matches!(op, TokenKind::DoubleColon | TokenKind::LeftParen),
        // The 8.5 call forms of `clone`; the plain `clone($a)` is grouped before it gets here.
        ExprKind::CloneWith(..) | ExprKind::Clone(_) => false,
        ExprKind::CallableCreate(CallableCreateExpr {
            kind: CallableCreateKind::Function(name),
        })
        | ExprKind::FunctionCall(FunctionCallExpr { name, .. }) => !is_clone_keyword(name),
        _ => true,
    };
    if !dereferencable {
        parser.forbid(
            ForbiddenRule::InvalidDereference,
            "Cannot dereference this expression",
            lhs.span,
        );
    } else if parser.version < PhpVersion::Php80 {
        let object_access = matches!(op, TokenKind::Arrow | TokenKind::NullsafeArrow);
        let feature = match lhs.kind {
            ExprKind::Name(_) if object_access => "object access on a constant",
            ExprKind::ClassConstAccess(_) if object_access || op == TokenKind::DoubleColon => {
                "class constant dereferencing"
            }
            ExprKind::MagicConst(_) => "magic constant dereferencing",
            ExprKind::InterpolatedString(_) => "interpolated string dereferencing",
            _ => return,
        };
        parser.require_version(PhpVersion::Php80, feature, lhs.span);
    }
}

pub(crate) const CURLY_OFFSET_REMOVED: &str =
    "Array and string offset access syntax with curly braces is no longer supported";

/// PHP's `class_name_reference`: a name, a parenthesized expression or a `new_variable`.
fn is_class_name_reference(expr: &Expr<'_, '_>) -> bool {
    matches!(
        expr.kind,
        ExprKind::Name(_) | ExprKind::Parenthesized(_) | ExprKind::Error
    ) || is_new_variable(expr)
}

fn is_new_variable(expr: &Expr<'_, '_>) -> bool {
    match &expr.kind {
        ExprKind::Variable(_) | ExprKind::VariableVariable(_) => true,
        ExprKind::ArrayAccess(a) => is_new_variable(a.array),
        ExprKind::PropertyAccess(p) | ExprKind::NullsafePropertyAccess(p) => {
            is_new_variable(p.object)
        }
        ExprKind::StaticPropertyAccess(StaticAccessExpr { class, .. })
        | ExprKind::StaticPropertyAccessDynamic { class, .. } => {
            matches!(class.kind, ExprKind::Name(_)) || is_new_variable(class)
        }
        _ => false,
    }
}

/// Report a class reference PHP folds to a value that is not a string, such as `(1)::A`.
pub(crate) fn check_class_name_literal(parser: &mut Parser<'_, '_>, class: &Expr<'_, '_>) {
    if is_literal(class) && literal_is_string(class, parser.version) == Some(false) {
        parser.forbid(
            ForbiddenRule::LiteralClassName,
            "Illegal class name",
            class.span,
        );
    }
}

/// `(1)::class` is an illegal class name, while `([])::class` names the type it cannot use.
fn check_class_name_fetch_literal(parser: &mut Parser<'_, '_>, class: &Expr<'_, '_>) {
    let (rule, message) = match &unparenthesized(class).kind {
        ExprKind::Int(_) | ExprKind::Float(_) => {
            (ForbiddenRule::LiteralClassName, "Illegal class name")
        }
        ExprKind::Bool(true) => (
            ForbiddenRule::ClassFetchOnLiteral,
            "Cannot use \"::class\" on true",
        ),
        ExprKind::Bool(false) => (
            ForbiddenRule::ClassFetchOnLiteral,
            "Cannot use \"::class\" on false",
        ),
        ExprKind::Null => (
            ForbiddenRule::ClassFetchOnLiteral,
            "Cannot use \"::class\" on null",
        ),
        ExprKind::Array(_) if is_literal(class) => (
            ForbiddenRule::ClassFetchOnLiteral,
            "Cannot use \"::class\" on array",
        ),
        _ => return,
    };
    parser.forbid(rule, message, class.span);
}

/// Whether a literal expression folds to a string, when that is known without evaluating it.
fn literal_is_string(expr: &Expr<'_, '_>, version: PhpVersion) -> Option<bool> {
    folded_type(expr, version).map(|t| matches!(t, Folded::Str { .. }))
}

/// The type PHP folds a literal expression to.
#[derive(Clone, Copy)]
enum Folded {
    Int,
    /// A float, or a number of either type.
    Number,
    Bool,
    Null,
    Str {
        numeric: bool,
    },
    Array,
}

impl Folded {
    /// Whether arithmetic on this operand folds without a TypeError.
    fn is_arithmetic(self) -> bool {
        !matches!(self, Folded::Array | Folded::Str { numeric: false })
    }

    /// Whether integer operations on this operand fold without a deprecation for a lost fraction.
    fn is_integral(self, version: PhpVersion) -> bool {
        matches!(self, Folded::Int | Folded::Bool | Folded::Null)
            || (matches!(self, Folded::Number) && version < PhpVersion::Php81)
    }
}

/// The folded type of `expr`, or `None` when it is unknown or PHP leaves the expression to run
/// time because folding it would raise an error or a diagnostic.
fn folded_type(expr: &Expr<'_, '_>, version: PhpVersion) -> Option<Folded> {
    let non_negative_int =
        |e: &Expr<'_, '_>| matches!(unparenthesized(e).kind, ExprKind::Int(n) if n >= 0);
    let folded = match &expr.kind {
        ExprKind::String(s) => Folded::Str {
            numeric: is_numeric_string(s.as_bytes()),
        },
        ExprKind::Nowdoc { value, .. } => Folded::Str {
            numeric: is_numeric_string(value.as_bytes()),
        },
        ExprKind::Heredoc { .. } => Folded::Str { numeric: false },
        ExprKind::Int(_) => Folded::Int,
        ExprKind::Float(_) => Folded::Number,
        ExprKind::Bool(_) => Folded::Bool,
        ExprKind::Null => Folded::Null,
        ExprKind::Array(_) => Folded::Array,
        ExprKind::Parenthesized(inner) => return folded_type(inner, version),
        ExprKind::UnaryPrefix(u) => {
            let operand = folded_type(u.operand, version)?;
            match u.op {
                UnaryPrefixOp::BooleanNot => Folded::Bool,
                UnaryPrefixOp::Negate | UnaryPrefixOp::Plus if operand.is_arithmetic() => {
                    Folded::Number
                }
                UnaryPrefixOp::BitwiseNot => match operand {
                    Folded::Str { .. } => Folded::Str { numeric: false },
                    Folded::Int => Folded::Int,
                    Folded::Number if version < PhpVersion::Php81 => Folded::Int,
                    _ => return None,
                },
                _ => return None,
            }
        }
        ExprKind::Binary(b) => {
            let (left, right) = (
                folded_type(b.left, version)?,
                folded_type(b.right, version)?,
            );
            match b.op {
                BinaryOp::Concat
                    if !matches!(left, Folded::Array) && !matches!(right, Folded::Array) =>
                {
                    Folded::Str { numeric: false }
                }
                BinaryOp::Add if matches!((left, right), (Folded::Array, Folded::Array)) => {
                    Folded::Array
                }
                BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul
                    if left.is_arithmetic() && right.is_arithmetic() =>
                {
                    Folded::Number
                }
                // Since 8.4 `0 ** -1` is deprecated, so only a non-negative exponent always folds.
                BinaryOp::Pow
                    if left.is_arithmetic()
                        && right.is_arithmetic()
                        && (version < PhpVersion::Php84 || non_negative_int(b.right)) =>
                {
                    Folded::Number
                }
                BinaryOp::ShiftLeft | BinaryOp::ShiftRight
                    if left.is_integral(version) && non_negative_int(b.right) =>
                {
                    Folded::Int
                }
                BinaryOp::BitwiseAnd | BinaryOp::BitwiseOr | BinaryOp::BitwiseXor => {
                    match (left, right) {
                        (Folded::Str { .. }, Folded::Str { .. }) => Folded::Str { numeric: false },
                        _ if left.is_integral(version) && right.is_integral(version) => Folded::Int,
                        _ => return None,
                    }
                }
                BinaryOp::Equal
                | BinaryOp::NotEqual
                | BinaryOp::Identical
                | BinaryOp::NotIdentical
                | BinaryOp::Less
                | BinaryOp::Greater
                | BinaryOp::LessOrEqual
                | BinaryOp::GreaterOrEqual
                | BinaryOp::BooleanAnd
                | BinaryOp::BooleanOr
                | BinaryOp::LogicalAnd
                | BinaryOp::LogicalOr
                | BinaryOp::LogicalXor => Folded::Bool,
                BinaryOp::Spaceship => Folded::Int,
                _ => return None,
            }
        }
        _ => return None,
    };
    Some(folded)
}

/// PHP's numeric string: optional surrounding whitespace around a decimal integer or float.
fn is_numeric_string(s: &[u8]) -> bool {
    let is_space = |b: &u8| matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'\x0B' | b'\x0C');
    let start = s.iter().position(|b| !is_space(b)).unwrap_or(s.len());
    let end = s
        .iter()
        .rposition(|b| !is_space(b))
        .map_or(start, |p| p + 1);
    let mut rest = s[start..end]
        .strip_prefix(b"-")
        .or_else(|| s[start..end].strip_prefix(b"+"))
        .unwrap_or(&s[start..end]);
    let digits = |rest: &mut &[u8]| {
        let n = rest.iter().take_while(|b| b.is_ascii_digit()).count();
        *rest = &rest[n..];
        n
    };
    let mut mantissa = digits(&mut rest);
    if let Some(after) = rest.strip_prefix(b".") {
        rest = after;
        mantissa += digits(&mut rest);
    }
    if mantissa == 0 {
        return false;
    }
    if let Some(after) = rest.strip_prefix(b"e").or_else(|| rest.strip_prefix(b"E")) {
        rest = after
            .strip_prefix(b"-")
            .or_else(|| after.strip_prefix(b"+"))
            .unwrap_or(after);
        if digits(&mut rest) == 0 {
            return false;
        }
    }
    rest.is_empty()
}

/// True if the fetch chain ending in `kind` passes through `?->`. Like PHP's
/// short-circuit chain, it runs through property, method, index and static
/// member links, but not through a class constant or a plain call.
fn has_nullsafe_link(kind: &ExprKind<'_, '_>) -> bool {
    nullsafe_link(kind, false)
}

/// PHP compiles `$this?->x` as `$this->x`, as `$this` is never null.
fn is_this(kind: &ExprKind<'_, '_>) -> bool {
    match kind {
        ExprKind::Variable(n) => n.as_str() == "this",
        ExprKind::Parenthesized(inner) => is_this(&inner.kind),
        _ => false,
    }
}

fn nullsafe_link(kind: &ExprKind<'_, '_>, this_is_exempt: bool) -> bool {
    let mut cur = kind;
    loop {
        cur = match cur {
            ExprKind::NullsafePropertyAccess(a) if this_is_exempt && is_this(&a.object.kind) => {
                return false;
            }
            ExprKind::NullsafeMethodCall(c) if this_is_exempt && is_this(&c.object.kind) => {
                return false;
            }
            ExprKind::NullsafePropertyAccess(_) | ExprKind::NullsafeMethodCall(_) => return true,
            ExprKind::PropertyAccess(a) => &a.object.kind,
            ExprKind::MethodCall(c) => &c.object.kind,
            ExprKind::ArrayAccess(a) => &a.array.kind,
            ExprKind::StaticPropertyAccess(a) => &a.class.kind,
            ExprKind::StaticPropertyAccessDynamic { class, .. } => &class.kind,
            ExprKind::StaticMethodCall(c) => &c.class.kind,
            ExprKind::StaticMethodCallDynamic(c) => &c.class.kind,
            ExprKind::Parenthesized(inner) => &inner.kind,
            _ => return false,
        };
    }
}

/// True if a destructuring-element value is itself a writable target.
/// `Omit` (the gap slot in `[$a, , $c]`) is allowed; nested destructuring
/// (`Array`) recurses; everything else falls back to the lvalue rule.
fn is_valid_destructure_element(kind: &ExprKind<'_, '_>, version: PhpVersion) -> bool {
    match kind {
        ExprKind::Omit => true,
        ExprKind::Array(elems) => elems
            .iter()
            .all(|el| !el.is_spread() && is_valid_destructure_element(&el.value().kind, version)),
        // PHP rejects `($a) = …` but accepts `[($a)] = …`.
        ExprKind::Parenthesized(inner) => is_valid_destructure_element(&inner.kind, version),
        _ => {
            is_valid_assignment_target(kind)
                && !has_nullsafe_link(kind)
                && temporary_write_message(kind, version).is_none()
        }
    }
}

/// Report a `return` or `yield` of a nullsafe fetch in a function that returns by reference.
pub(crate) fn check_reference_return(parser: &mut Parser<'_, '_>, value: &Expr<'_, '_>) {
    if !parser.by_ref_function {
        return;
    }
    let mut kind = &value.kind;
    while let ExprKind::Parenthesized(inner) = kind {
        kind = &inner.kind;
    }
    let is_fetch = matches!(
        kind,
        ExprKind::ArrayAccess(_)
            | ExprKind::PropertyAccess(_)
            | ExprKind::NullsafePropertyAccess(_)
            | ExprKind::StaticPropertyAccess(_)
            | ExprKind::StaticPropertyAccessDynamic { .. }
    );
    if is_fetch && has_nullsafe_link(kind) {
        parser.forbid(
            ForbiddenRule::ReferenceToNullsafe,
            "Cannot take reference of a nullsafe chain",
            value.span,
        );
    }
}

/// True if `kind` is a variable, a fetch or a call: what PHP can take a reference of.
pub(crate) fn is_variable_or_call(kind: &ExprKind<'_, '_>) -> bool {
    matches!(
        kind,
        ExprKind::Variable(_)
            | ExprKind::VariableVariable(_)
            | ExprKind::ArrayAccess(_)
            | ExprKind::PropertyAccess(_)
            | ExprKind::NullsafePropertyAccess(_)
            | ExprKind::StaticPropertyAccess(_)
            | ExprKind::StaticPropertyAccessDynamic { .. }
            | ExprKind::FunctionCall(_)
            | ExprKind::MethodCall(_)
            | ExprKind::NullsafeMethodCall(_)
            | ExprKind::StaticMethodCall(_)
            | ExprKind::StaticMethodCallDynamic(_)
            | ExprKind::CallableCreate(_)
            | ExprKind::Error
    )
}

/// True if a destructuring list assigns any element by reference, as in `[&$a] = …`.
fn has_reference_element(kind: &ExprKind<'_, '_>) -> bool {
    let ExprKind::Array(elems) = kind else {
        return false;
    };
    elems
        .iter()
        .any(|el| el.is_by_ref() || has_reference_element(&el.value().kind))
}

const INVALID_CONST_EXPR: &str = "Constant expression contains invalid operations";

enum ConstExprError {
    Forbidden(&'static str, Span),
    Version(PhpVersion, &'static str, Span),
}

/// Report the first part of a constant expression PHP cannot evaluate at compile time.
pub(crate) fn check_const_expr(parser: &mut Parser<'_, '_>, expr: &Expr<'_, '_>, allow_new: bool) {
    let checker = ConstExprChecker {
        version: parser.version,
        allow_new,
    };
    match checker.check(expr) {
        Ok(()) => {}
        Err(ConstExprError::Forbidden(message, span)) => {
            parser.forbid(ForbiddenRule::InvalidConstantExpression, message, span)
        }
        Err(ConstExprError::Version(min, feature, span)) => {
            parser.require_version(min, feature, span)
        }
    }
}

struct ConstExprChecker {
    version: PhpVersion,
    allow_new: bool,
}

impl ConstExprChecker {
    fn require(
        &self,
        min: PhpVersion,
        feature: &'static str,
        span: Span,
    ) -> Result<(), ConstExprError> {
        if self.version < min {
            return Err(ConstExprError::Version(min, feature, span));
        }
        Ok(())
    }

    fn check(&self, expr: &Expr<'_, '_>) -> Result<(), ConstExprError> {
        use ConstExprError::Forbidden;
        match &expr.kind {
            ExprKind::Int(_)
            | ExprKind::Float(_)
            | ExprKind::String(_)
            | ExprKind::Bool(_)
            | ExprKind::Null
            | ExprKind::Nowdoc { .. }
            | ExprKind::MagicConst(_)
            | ExprKind::Name(_)
            | ExprKind::Identifier(_)
            | ExprKind::Omit
            | ExprKind::Error => Ok(()),
            ExprKind::Heredoc { parts, .. } if is_literal_parts(parts) => Ok(()),
            ExprKind::Parenthesized(inner) => self.check(inner),
            ExprKind::UnaryPrefix(u)
                if !matches!(
                    u.op,
                    UnaryPrefixOp::PreIncrement | UnaryPrefixOp::PreDecrement
                ) =>
            {
                self.check(u.operand)
            }
            ExprKind::Binary(b) if !matches!(b.op, BinaryOp::Instanceof | BinaryOp::Pipe) => {
                self.check(b.left)?;
                // PHP folds `false && $x` before checking, dropping the right operand.
                let folded_away = match (b.op, folded_truth(b.left)) {
                    (BinaryOp::BooleanAnd | BinaryOp::LogicalAnd, Some(truth)) => !truth,
                    (BinaryOp::BooleanOr | BinaryOp::LogicalOr, Some(truth)) => truth,
                    (
                        BinaryOp::BooleanAnd
                        | BinaryOp::BooleanOr
                        | BinaryOp::LogicalAnd
                        | BinaryOp::LogicalOr,
                        None,
                    ) => may_fold(b.left),
                    _ => false,
                };
                if folded_away {
                    return Ok(());
                }
                self.check(b.right)
            }
            ExprKind::Ternary(t) => {
                self.check(t.condition)?;
                match folded_truth(t.condition) {
                    Some(true) => t
                        .then_expr
                        .map_or(Ok(()), |then_expr| self.check(then_expr)),
                    Some(false) => self.check(t.else_expr),
                    None if may_fold(t.condition) => Ok(()),
                    None => {
                        if let Some(then_expr) = t.then_expr {
                            self.check(then_expr)?;
                        }
                        self.check(t.else_expr)
                    }
                }
            }
            ExprKind::NullCoalesce(n) => {
                self.check(n.left)?;
                let left_is_null = matches!(unparenthesized(n.left).kind, ExprKind::Null);
                if !left_is_null && may_fold(n.left) {
                    return Ok(());
                }
                self.check(n.right)
            }
            ExprKind::Array(elements) => {
                for el in elements.iter() {
                    if el.is_by_ref() {
                        return Err(Forbidden(INVALID_CONST_EXPR, el.span));
                    }
                    if let Some(key) = &el.key {
                        self.check(key)?;
                    }
                    self.check(el.value())?;
                }
                Ok(())
            }
            ExprKind::ArrayAccess(a) => {
                self.check(a.array)?;
                // `[]` reads are reported on their own.
                match a.index {
                    Some(index) => self.check(index),
                    None => Ok(()),
                }
            }
            ExprKind::Cast(kind, inner) => match kind {
                // Reported on their own wherever they appear.
                CastKind::Unset | CastKind::Void => Ok(()),
                _ => {
                    self.require(
                        PhpVersion::Php85,
                        "casts in constant expressions",
                        expr.span,
                    )?;
                    if *kind == CastKind::Object && !self.allow_new {
                        return Err(Forbidden(
                            "Object casts are not supported in this context",
                            expr.span,
                        ));
                    }
                    self.check(inner)
                }
            },
            ExprKind::PropertyAccess(p) | ExprKind::NullsafePropertyAccess(p) => {
                self.require(
                    PhpVersion::Php82,
                    "property fetch in constant expressions",
                    expr.span,
                )?;
                self.check(p.object)?;
                self.check(p.property)
            }
            ExprKind::ClassConstAccess(access) => {
                let class = access.class;
                let is_class_name = matches!(&access.member.kind, ExprKind::Identifier(name) if name.eq_ignore_ascii_case("class"));
                if !is_class_name {
                    return self.class_const_class(class);
                }
                match &class.kind {
                    // `static::class` is reported with the class scope checks.
                    ExprKind::Name(_) => Ok(()),
                    _ if is_literal(class) => Ok(()),
                    _ => Err(Forbidden(
                        "(expression)::class cannot be used in constant expressions",
                        expr.span,
                    )),
                }
            }
            ExprKind::ClassConstAccessDynamic { class, member } => {
                self.class_const_class(class)?;
                self.check(member)
            }
            ExprKind::New(new) => {
                if !self.allow_new {
                    return Err(Forbidden(
                        "New expressions are not supported in this context",
                        expr.span,
                    ));
                }
                self.require(PhpVersion::Php81, "new in initializers", expr.span)?;
                let class = new.class;
                match &class.kind {
                    ExprKind::Name(name) if is_static_name(name) => {
                        return Err(Forbidden(
                            "\"static\" is not allowed in compile-time constants",
                            class.span,
                        ))
                    }
                    ExprKind::Name(_) => {}
                    ExprKind::AnonymousClass(_) => {
                        return Err(Forbidden(
                            "Cannot use anonymous class in constant expression",
                            class.span,
                        ))
                    }
                    _ if may_fold(class) => {}
                    _ => {
                        return Err(Forbidden(
                            "Cannot use dynamic class name in constant expression",
                            class.span,
                        ))
                    }
                }
                for arg in new.args.iter() {
                    if arg.is_spread() {
                        return Err(Forbidden(
                            "Argument unpacking in constant expressions is not supported",
                            arg.span,
                        ));
                    }
                    if let Some(value) = arg.value() {
                        self.check(value)?;
                    }
                }
                Ok(())
            }
            // The body is not part of the expression; parameter defaults are checked on their own.
            ExprKind::Closure(closure) => {
                self.require(
                    PhpVersion::Php85,
                    "closures in constant expressions",
                    expr.span,
                )?;
                if !closure.is_static {
                    return Err(Forbidden(
                        "Closures in constant expressions must be static",
                        expr.span,
                    ));
                }
                if !closure.use_vars.is_empty() {
                    return Err(Forbidden(
                        "Cannot use(...) variables in constant expression",
                        expr.span,
                    ));
                }
                Ok(())
            }
            ExprKind::CallableCreate(cc) => {
                self.require(
                    PhpVersion::Php85,
                    "first-class callables in constant expressions",
                    expr.span,
                )?;
                match &cc.kind {
                    CallableCreateKind::Function(name) => self.callable_function(name),
                    CallableCreateKind::StaticMethod { class, method } => {
                        self.callable_static_method(class, method)
                    }
                    _ => Err(Forbidden(INVALID_CONST_EXPR, expr.span)),
                }
            }
            // PHP 8.6 partial function application.
            ExprKind::FunctionCall(call)
                if self.version >= PhpVersion::Php86
                    && call.args.iter().any(Arg::is_placeholder) =>
            {
                self.callable_function(call.name)?;
                self.partial_args(&call.args)
            }
            ExprKind::StaticMethodCall(call)
                if self.version >= PhpVersion::Php86
                    && call.args.iter().any(Arg::is_placeholder) =>
            {
                self.callable_static_method(call.class, call.method)?;
                self.partial_args(&call.args)
            }
            _ => Err(Forbidden(INVALID_CONST_EXPR, expr.span)),
        }
    }

    /// The function a constant expression makes a closure of.
    fn callable_function(&self, name: &Expr<'_, '_>) -> Result<(), ConstExprError> {
        if matches!(name.kind, ExprKind::Name(_)) || is_literal(name) {
            Ok(())
        } else {
            Err(ConstExprError::Forbidden(
                "Cannot use dynamic function name in constant expression",
                name.span,
            ))
        }
    }

    /// The static method a constant expression makes a closure of.
    fn callable_static_method(
        &self,
        class: &Expr<'_, '_>,
        method: &Expr<'_, '_>,
    ) -> Result<(), ConstExprError> {
        match &class.kind {
            ExprKind::Name(name) if is_static_name(name) => {
                return Err(ConstExprError::Forbidden(
                    "\"static\" is not allowed in compile-time constants",
                    class.span,
                ))
            }
            ExprKind::Name(_) => {}
            _ if may_fold(class) => {}
            _ => {
                return Err(ConstExprError::Forbidden(
                    "Cannot use dynamic class name in constant expression",
                    class.span,
                ))
            }
        }
        if matches!(method.kind, ExprKind::Identifier(_)) || is_literal(method) {
            Ok(())
        } else {
            Err(ConstExprError::Forbidden(
                "Cannot use dynamic method name in constant expression",
                method.span,
            ))
        }
    }

    /// The arguments of a partial application in a constant expression.
    fn partial_args(&self, args: &[Arg<'_, '_>]) -> Result<(), ConstExprError> {
        for arg in args {
            match &arg.kind {
                ArgKind::Value(value) => self.check(value)?,
                ArgKind::Placeholder | ArgKind::SpreadPlaceholder => {}
                ArgKind::Spread(_) => {
                    return Err(ConstExprError::Forbidden(
                        "Argument unpacking in constant expressions is not supported",
                        arg.span,
                    ))
                }
                _ => return Err(ConstExprError::Forbidden(INVALID_CONST_EXPR, arg.span)),
            }
        }
        Ok(())
    }

    /// The class of `X::C` or `X::{expr}`.
    fn class_const_class(&self, class: &Expr<'_, '_>) -> Result<(), ConstExprError> {
        match &class.kind {
            ExprKind::Name(name) if is_static_name(name) => Err(ConstExprError::Forbidden(
                "\"static::\" is not allowed in compile-time constants",
                class.span,
            )),
            ExprKind::Name(_) => Ok(()),
            _ if may_fold(class) => Ok(()),
            _ => Err(ConstExprError::Forbidden(
                "Dynamic class names are not allowed in compile-time class constant references",
                class.span,
            )),
        }
    }
}

fn is_class_keyword_name(name: &Name<'_, '_>) -> bool {
    matches!(name, Name::Simple { value, .. }
        if ["self", "parent", "static"].iter().any(|k| value.eq_ignore_ascii_case(k)))
}

fn is_static_name(name: &Name<'_, '_>) -> bool {
    matches!(name, Name::Simple { value, .. } if value.eq_ignore_ascii_case("static"))
}

fn is_literal_parts(parts: &[StringPart<'_, '_>]) -> bool {
    parts
        .iter()
        .all(|part| matches!(part, StringPart::Literal(_)))
}

/// Whether `expr` is built from literals only, which PHP always folds at compile time.
fn is_literal(expr: &Expr<'_, '_>) -> bool {
    foldable(expr, false)
}

/// Whether PHP may fold `expr` at compile time, substituting constants whose value it knows.
fn may_fold(expr: &Expr<'_, '_>) -> bool {
    foldable(expr, true)
}

fn unparenthesized<'e, 'arena, 'src>(mut expr: &'e Expr<'arena, 'src>) -> &'e Expr<'arena, 'src> {
    while let ExprKind::Parenthesized(inner) = &expr.kind {
        expr = inner;
    }
    expr
}

fn is_short_circuit(op: BinaryOp) -> bool {
    matches!(
        op,
        BinaryOp::BooleanAnd | BinaryOp::BooleanOr | BinaryOp::LogicalAnd | BinaryOp::LogicalOr
    )
}

/// The truthiness PHP gives `expr` when it folds `?:`, `&&` and `||` at compile time.
fn folded_truth(expr: &Expr<'_, '_>) -> Option<bool> {
    let expr = unparenthesized(expr);
    match &expr.kind {
        ExprKind::Int(n) => Some(*n != 0),
        ExprKind::Float(f) => Some(*f != 0.0),
        ExprKind::String(s) => Some(!matches!(s.as_bytes(), b"" | b"0")),
        ExprKind::Nowdoc { value, .. } => Some(!matches!(*value, "" | "0")),
        ExprKind::Bool(b) => Some(*b),
        ExprKind::Null => Some(false),
        ExprKind::UnaryPrefix(u) if u.op == UnaryPrefixOp::BooleanNot => {
            folded_truth(u.operand).map(|truth| !truth)
        }
        ExprKind::Array(elements) if is_literal(expr) => {
            let mut truth = false;
            for el in elements.iter() {
                match &el.kind {
                    ArrayElementKind::Spread(inner) => truth |= folded_truth(inner)?,
                    _ => return Some(true),
                }
            }
            Some(truth)
        }
        // `A::class` is resolved at compile time unless it names `self`, `parent` or `static`.
        ExprKind::ClassConstAccess(access) => {
            let resolved = matches!(&access.member.kind, ExprKind::Identifier(m) if m.eq_ignore_ascii_case("class"))
                && matches!(&access.class.kind, ExprKind::Name(name) if !is_class_keyword_name(name));
            resolved.then_some(true)
        }
        ExprKind::Binary(b) if is_short_circuit(b.op) => {
            // Walk the left spine iteratively: chains are built in a loop and can be very long.
            let mut spine = vec![b];
            while let ExprKind::Binary(inner) = &unparenthesized(spine[spine.len() - 1].left).kind {
                if !is_short_circuit(inner.op) {
                    break;
                }
                spine.push(inner);
            }
            let mut truth = folded_truth(spine[spine.len() - 1].left)?;
            for link in spine.iter().rev() {
                let decided = match link.op {
                    BinaryOp::BooleanAnd | BinaryOp::LogicalAnd => !truth,
                    _ => truth,
                };
                if !decided {
                    truth = folded_truth(link.right)?;
                }
            }
            Some(truth)
        }
        _ => None,
    }
}

fn foldable(expr: &Expr<'_, '_>, constants: bool) -> bool {
    let operand = |e: &Expr<'_, '_>| foldable(e, constants);
    match &expr.kind {
        ExprKind::Int(_)
        | ExprKind::Float(_)
        | ExprKind::String(_)
        | ExprKind::Bool(_)
        | ExprKind::Null
        | ExprKind::Nowdoc { .. } => true,
        ExprKind::Heredoc { parts, .. } => is_literal_parts(parts),
        ExprKind::MagicConst(_) | ExprKind::Name(_) => constants,
        ExprKind::ClassConstAccess(access) => {
            constants
                && matches!(access.class.kind, ExprKind::Name(_))
                && matches!(access.member.kind, ExprKind::Identifier(_))
        }
        ExprKind::Parenthesized(inner) => operand(inner),
        ExprKind::UnaryPrefix(u) => {
            !matches!(
                u.op,
                UnaryPrefixOp::PreIncrement | UnaryPrefixOp::PreDecrement
            ) && operand(u.operand)
        }
        ExprKind::Binary(b) => {
            !matches!(b.op, BinaryOp::Instanceof | BinaryOp::Pipe)
                && operand(b.left)
                && operand(b.right)
        }
        ExprKind::Ternary(t) => {
            operand(t.condition) && t.then_expr.is_none_or(operand) && operand(t.else_expr)
        }
        ExprKind::NullCoalesce(n) => operand(n.left) && operand(n.right),
        ExprKind::Array(elements) => elements.iter().all(|el| {
            !el.is_by_ref() && el.key.as_ref().is_none_or(operand) && operand(el.value())
        }),
        ExprKind::ArrayAccess(a) => operand(a.array) && a.index.is_some_and(operand),
        _ => false,
    }
}

/// Report PHP's compile errors for the destructuring list `target` and its nested lists.
pub(crate) fn check_list_entries(parser: &mut Parser<'_, '_>, target: &Expr<'_, '_>) {
    let ExprKind::Array(elems) = &target.kind else {
        return;
    };
    if elems
        .iter()
        .all(|el| matches!(el.value().kind, ExprKind::Omit))
    {
        parser.forbid(
            ForbiddenRule::EmptyList,
            "Cannot use empty list",
            target.span,
        );
        return;
    }
    // PHP takes the list's style from its first non-empty entry and stops at the first mismatch.
    let is_keyed = elems
        .iter()
        .find(|el| !matches!(el.value().kind, ExprKind::Omit))
        .is_some_and(|el| el.key.is_some());
    for el in elems.iter() {
        if matches!(el.value().kind, ExprKind::Omit) {
            if is_keyed {
                parser.forbid(
                    ForbiddenRule::EmptyKeyedArrayEntry,
                    "Cannot use empty array entries in keyed array assignment",
                    el.span,
                );
                return;
            }
            continue;
        }
        if el.is_spread() {
            return;
        }
        if el.key.is_some() != is_keyed {
            parser.forbid(
                ForbiddenRule::MixedKeyedEntries,
                "Cannot mix keyed and unkeyed array entries in assignments",
                el.span,
            );
            return;
        }
        check_list_entries(parser, el.value());
    }
}

/// True if the array-literal at `span` was written with `list(...)` syntax
/// rather than the short `[...]` form. Determined by the first source byte
/// at the span start.
fn is_list_syntax(source: &str, span: Span) -> bool {
    source
        .as_bytes()
        .get(span.start as usize)
        .map(|b| b.eq_ignore_ascii_case(&b'l'))
        .unwrap_or(false)
}

/// Walk the destructure target (top-level `Array(_)`) and report mixing of
/// `list(...)` and `[...]` syntax — PHP fatals "Cannot mix [] and list()".
fn check_mixed_list_short_syntax<'arena, 'src>(
    parser: &mut Parser<'arena, 'src>,
    lhs: &Expr<'arena, 'src>,
) {
    let ExprKind::Array(_) = lhs.kind else {
        return;
    };
    let outer_is_list = is_list_syntax(parser.source(), lhs.span);
    fn walk<'arena, 'src>(
        parser: &mut Parser<'arena, 'src>,
        expr: &Expr<'arena, 'src>,
        outer_is_list: bool,
    ) {
        if let ExprKind::Array(elems) = &expr.kind {
            if is_list_syntax(parser.source(), expr.span) != outer_is_list {
                parser.forbid(
                    ForbiddenRule::MixedListSyntax,
                    "Cannot mix [] and list()",
                    expr.span,
                );
                return;
            }
            for el in elems.iter() {
                walk(parser, el.value(), outer_is_list);
            }
        }
    }
    if let ExprKind::Array(elems) = &lhs.kind {
        for el in elems.iter() {
            walk(parser, el.value(), outer_is_list);
        }
    }
}

/// True if `kind` is an index or property fetch chain whose base is not a variable or a
/// call, such as `[0, 1][0]`, `FOO->a` or `(new A)->b`. PHP rejects writes to these with
/// "Cannot use temporary expression in write context"; for `clone $a` and `f(...)` bases the
/// message is "Cannot use result of built-in function in write context".
fn temporary_write_message(
    kind: &ExprKind<'_, '_>,
    version: PhpVersion,
) -> Option<(ForbiddenRule, &'static str)> {
    let mut cur = kind;
    let mut saw_access = false;
    let mut saw_property = false;
    loop {
        match cur {
            ExprKind::ArrayAccess(a) => {
                saw_access = true;
                cur = &a.array.kind;
            }
            ExprKind::PropertyAccess(p) => {
                saw_access = true;
                saw_property = true;
                cur = &p.object.kind;
            }
            // Reported as a nullsafe write instead.
            ExprKind::NullsafePropertyAccess(_) => return None,
            ExprKind::Parenthesized(inner) => cur = &inner.kind,
            _ => break,
        }
    }
    if !saw_access {
        return None;
    }
    // From 8.6 PHP fetches a constant's object to write one of its properties.
    let constant = match cur {
        ExprKind::Name(_) | ExprKind::Bool(_) | ExprKind::Null => true,
        ExprKind::ClassConstAccess(access) => !matches!(
            &access.member.kind,
            ExprKind::Identifier(m) if m.eq_ignore_ascii_case("class")
        ),
        ExprKind::ClassConstAccessDynamic { .. } => true,
        _ => false,
    };
    if constant && saw_property && version >= PhpVersion::Php86 {
        return None;
    }
    match cur {
        ExprKind::Clone(_) | ExprKind::CallableCreate(_) => Some((
            ForbiddenRule::BuiltinResultWrite,
            "Cannot use result of built-in function in write context",
        )),
        ExprKind::Variable(_)
        | ExprKind::VariableVariable(_)
        | ExprKind::StaticPropertyAccess(_)
        | ExprKind::StaticPropertyAccessDynamic { .. }
        | ExprKind::FunctionCall(_)
        | ExprKind::MethodCall(_)
        | ExprKind::NullsafeMethodCall(_)
        | ExprKind::StaticMethodCall(_)
        | ExprKind::StaticMethodCallDynamic(_)
        | ExprKind::CloneWith(..)
        | ExprKind::Error => None,
        _ => Some((
            ForbiddenRule::TemporaryExpressionWrite,
            "Cannot use temporary expression in write context",
        )),
    }
}

/// Parse an assignment operator and its RHS, treating `lhs` as the assignment target.
///
/// PHP grammar quirk: assignment operators bind tighter than prefix unary operators,
/// the `??` right operand, `@`, and casts. For example:
/// - `-$x += 1`       parses as `-(($x += 1))`,   not `(-$x) += 1`
/// - `$a ?? $b = $c`  parses as `$a ?? ($b = $c)`, not `($a ?? $b) = $c`
/// - `@$a = 1`        parses as `@($a = 1)`,       not `(@$a) = 1`
///
/// **Deliberate deviation from standard Pratt semantics**: this function is called
/// *after* `parse_expr_bp` returns, meaning it consumes the assignment regardless of
/// whatever `min_bp` the surrounding context passed to `parse_expr_bp`. This is
/// intentional: PHP's grammar allows assignment to "escape" prefix unary / `??` / `@`
/// / ternary-else context. Callers must opt-in via an explicit
/// `if parser.current_kind().is_assignment_op()` guard rather than relying on `min_bp`
/// to block it.
fn parse_assign_continuation<'arena, 'src>(
    parser: &mut Parser<'arena, 'src>,
    lhs: Expr<'arena, 'src>,
) -> Expr<'arena, 'src> {
    debug_assert!(parser.current_kind().is_assignment_op());
    let span = parser.current_span();
    let is_plain_assign = parser.current_kind() == TokenKind::Equals;
    // PHP rejects pre/post-increment/decrement as an assignment target at parse time.
    if matches!(
        lhs.kind,
        ExprKind::UnaryPrefix(UnaryPrefixExpr {
            op: UnaryPrefixOp::PreIncrement | UnaryPrefixOp::PreDecrement,
            ..
        }) | ExprKind::UnaryPostfix(UnaryPostfixExpr {
            op: UnaryPostfixOp::PostIncrement | UnaryPostfixOp::PostDecrement,
            ..
        })
    ) {
        parser.forbid(
            ForbiddenRule::IncDecAsAssignTarget,
            "Cannot use increment/decrement as an assignment target.",
            span,
        );
    } else if let Some((rule, message)) = temporary_write_message(&lhs.kind, parser.version) {
        parser.forbid(rule, message, lhs.span);
    } else if matches!(lhs.kind, ExprKind::Array(_)) && !is_plain_assign {
        parser.forbid(
            ForbiddenRule::CompoundAssignToDestructuring,
            "Cannot use a destructuring pattern with a compound assignment operator",
            span,
        );
    } else if !is_valid_assignment_target(&lhs.kind) {
        parser.forbid(
            ForbiddenRule::InvalidAssignTarget,
            "Cannot use expression as assignment target.",
            span,
        );
    } else if has_nullsafe_link(&lhs.kind) {
        parser.forbid(
            ForbiddenRule::NullsafeWrite,
            "Can't use nullsafe operator in write context",
            lhs.span,
        );
    }
    if let ExprKind::Array(elems) = &lhs.kind {
        // This array is a destructuring target, so empty slots are legal here —
        // retract the eager "empty array element" errors emitted while parsing it.
        parser.retract_destructuring_errors_within(lhs.span);
        if is_plain_assign {
            check_list_entries(parser, &lhs);
            // Each non-omitted element must itself be a writable target. PHP
            // rejects e.g. `[null, $b] = …` and `list(1 + 1) = …` with
            // "Assignments can only happen to writable values".
            for el in elems.iter() {
                if el.is_spread() {
                    parser.forbid(
                        ForbiddenRule::SpreadInDestructuring,
                        "Spread operator is not supported in assignments",
                        el.span,
                    );
                } else if !is_valid_destructure_element(&el.value().kind, parser.version) {
                    parser.forbid(
                        ForbiddenRule::UnwritableDestructuringElement,
                        "Assignments can only happen to writable values",
                        el.value().span,
                    );
                }
            }
        }
    }
    check_mixed_list_short_syntax(parser, &lhs);
    let op_token = parser.advance();
    let write_kind = if matches!(op_token.kind, TokenKind::Equals | TokenKind::CoalesceEquals) {
        WriteKind::Assign
    } else {
        WriteKind::Modify
    };
    check_special_variable_write(parser, &lhs, write_kind);
    let by_ref_span = parser.current_span();
    let by_ref = op_token.kind == TokenKind::Equals && parser.eat(TokenKind::Ampersand).is_some();
    if by_ref && matches!(lhs.kind, ExprKind::Array(_)) {
        parser.forbid(
            ForbiddenRule::ReferenceAssignToDestructuring,
            "Cannot assign by reference to a destructuring pattern",
            by_ref_span,
        );
    }
    let op = match op_token.kind {
        TokenKind::Equals => AssignOp::Assign,
        TokenKind::PlusEquals => AssignOp::Plus,
        TokenKind::MinusEquals => AssignOp::Minus,
        TokenKind::StarEquals => AssignOp::Mul,
        TokenKind::SlashEquals => AssignOp::Div,
        TokenKind::PercentEquals => AssignOp::Mod,
        TokenKind::StarStarEquals => AssignOp::Pow,
        TokenKind::DotEquals => AssignOp::Concat,
        TokenKind::AmpersandEquals => AssignOp::BitwiseAnd,
        TokenKind::PipeEquals => AssignOp::BitwiseOr,
        TokenKind::CaretEquals => AssignOp::BitwiseXor,
        TokenKind::ShiftLeftEquals => AssignOp::ShiftLeft,
        TokenKind::ShiftRightEquals => AssignOp::ShiftRight,
        TokenKind::CoalesceEquals => AssignOp::Coalesce,
        _ => unreachable!(
            "is_assignment_op() guarantees one of the listed variants, got {:?}",
            op_token.kind
        ),
    };
    // `&` takes a single variable, so `$a = &$b + 1` is `($a = &$b) + 1`.
    let rhs = parse_expr_bp(
        parser,
        if by_ref {
            MEMBER_ACCESS_BP
        } else {
            ASSIGNMENT_BP
        },
    );
    if by_ref && matches!(rhs.kind, ExprKind::New(..)) {
        parser.forbid(
            ForbiddenRule::ReferenceAssignNew,
            "Cannot use by-reference assignment with 'new' expression",
            rhs.span,
        );
    } else if by_ref && has_nullsafe_link(&rhs.kind) {
        parser.forbid(
            ForbiddenRule::ReferenceToNullsafe,
            "Cannot take reference of a nullsafe chain",
            rhs.span,
        );
    } else if by_ref && matches!(rhs.kind, ExprKind::Parenthesized(_)) {
        parser.forbid(
            ForbiddenRule::ReferenceToParenthesized,
            "Cannot take reference of a parenthesized expression",
            rhs.span,
        );
    } else if by_ref && !is_variable_or_call(&rhs.kind) {
        parser.forbid(
            ForbiddenRule::ReferenceToNonReferenceable,
            "Cannot assign reference to non referenceable value",
            rhs.span,
        );
    } else if by_ref && matches!(rhs.kind, ExprKind::CallableCreate(_)) {
        parser.forbid(
            ForbiddenRule::BuiltinResultWrite,
            "Cannot use result of built-in function in write context",
            rhs.span,
        );
    } else if let Some((rule, message)) = by_ref
        .then(|| temporary_write_message(&rhs.kind, parser.version))
        .flatten()
    {
        parser.forbid(rule, message, rhs.span);
    } else if by_ref {
        check_special_variable_write(parser, &rhs, WriteKind::Reference);
    } else if op == AssignOp::Assign && has_reference_element(&lhs.kind) {
        let mut source = &rhs.kind;
        while let ExprKind::Parenthesized(inner) = source {
            source = &inner.kind;
        }
        let error = if has_nullsafe_link(source) {
            Some((
                ForbiddenRule::ReferenceToNullsafe,
                "Cannot take reference of a nullsafe chain",
            ))
        } else if !is_variable_or_call(source) {
            Some((
                ForbiddenRule::ReferenceToNonReferenceable,
                "Cannot assign reference to non referenceable value",
            ))
        } else {
            None
        };
        if let Some((rule, message)) = error {
            parser.forbid(rule, message, rhs.span);
        }
    }
    let span = lhs.span.merge(rhs.span);
    Expr {
        kind: ExprKind::Assign(AssignExpr {
            target: parser.alloc(lhs),
            op,
            value: parser.alloc(rhs),
            by_ref,
        }),
        span,
    }
}

/// Parse an expression.
pub fn parse_expr<'arena, 'src>(parser: &'_ mut Parser<'arena, 'src>) -> Expr<'arena, 'src> {
    instrument::record_parse_expr();
    parse_expr_bp(parser, 0)
}

/// Pratt expression parser. Parses expressions with binding power >= min_bp.
pub fn parse_expr_bp<'arena, 'src>(
    parser: &'_ mut Parser<'arena, 'src>,
    min_bp: u8,
) -> Expr<'arena, 'src> {
    if min_bp != 0 {
        instrument::record_parse_expr_bp_recursive();
    }
    if !parser.enter_nesting() {
        return Expr {
            kind: ExprKind::Error,
            span: parser.current_span(),
        };
    }
    let lhs = parse_atom(parser);
    parse_expr_rest(parser, lhs, min_bp)
}

/// Continue an expression whose first operand `lhs` is already parsed.
pub(crate) fn parse_expr_continue<'arena, 'src>(
    parser: &'_ mut Parser<'arena, 'src>,
    lhs: Expr<'arena, 'src>,
    min_bp: u8,
) -> Expr<'arena, 'src> {
    if !parser.enter_nesting() {
        return Expr {
            kind: ExprKind::Error,
            span: parser.current_span(),
        };
    }
    parse_expr_rest(parser, lhs, min_bp)
}

fn parse_expr_rest<'arena, 'src>(
    parser: &'_ mut Parser<'arena, 'src>,
    mut lhs: Expr<'arena, 'src>,
    min_bp: u8,
) -> Expr<'arena, 'src> {
    // The folded truth of the last `&&`/`||` built here, so a long chain is not re-walked per link.
    let mut chain_truth: Option<(Span, Option<bool>)> = None;
    loop {
        let kind = parser.current_kind();

        // Fast-path: Direct token kind dispatch for most-common operators.
        // Compiler converts this to jump table (O(1)) instead of sequential branches.
        // This groups direct token comparisons that were scattered across if-statements.
        let should_continue = match kind {
            // Postfix operators (++, --)
            TokenKind::PlusPlus | TokenKind::MinusMinus => {
                if let Some(left_bp) = precedence::postfix_binding_power(kind) {
                    if left_bp < min_bp {
                        break;
                    }
                    let op_token = parser.advance();
                    let op = match op_token.kind {
                        TokenKind::PlusPlus => UnaryPostfixOp::PostIncrement,
                        TokenKind::MinusMinus => UnaryPostfixOp::PostDecrement,
                        _ => unreachable!(
                            "outer arm already matched PlusPlus/MinusMinus, got {:?}",
                            op_token.kind
                        ),
                    };
                    check_increment_operand(parser, &lhs);
                    let span = lhs.span.merge(op_token.span);
                    lhs = Expr {
                        kind: ExprKind::UnaryPostfix(UnaryPostfixExpr {
                            operand: parser.alloc(lhs),
                            op,
                        }),
                        span,
                    };
                    true
                } else {
                    false
                }
            }

            // Ternary operator (non-associative in PHP 8.0+)
            TokenKind::Question => {
                if TERNARY_BP < min_bp {
                    break;
                }
                // PHP 8.0+: unparenthesized `a ? b : c ? d : e` is a fatal parse error,
                // but chains of short ternaries (`a ?: b ?: c`) remain valid because `?:`
                // is left-associative and unambiguous.
                //
                // So: fire the error when LHS is an already-parsed ternary UNLESS both the
                // LHS ternary and the incoming ternary are short (then_expr=None and next
                // token after `?` is `:`).
                if parser.version >= PhpVersion::Php80 {
                    if let ExprKind::Ternary(lhs_tern) = &lhs.kind {
                        let lhs_is_short = lhs_tern.then_expr.is_none();
                        let incoming_is_short = parser.peek_kind() == Some(TokenKind::Colon);
                        if !(lhs_is_short && incoming_is_short) {
                            let span = parser.current_span();
                            parser.forbid(
                                ForbiddenRule::UnparenthesizedNestedTernary,
                                "Unparenthesized `a ? b : c ? d : e` is not supported. \
                                          Use parentheses to make the order explicit.",
                                span,
                            );
                        }
                    }
                }
                parser.advance(); // consume ?

                // Short ternary: `$x ?: $y`
                let then_expr = if parser.check(TokenKind::Colon) {
                    None
                } else {
                    let e = parse_expr_bp(parser, 0);
                    Some(parser.alloc(e))
                };

                parser.expect(TokenKind::Colon);
                // Non-associative in PHP 8.0+; use TERNARY_BP + 1 to prevent
                // the else branch from consuming another ternary at the same level.
                // PHP grammar quirk: assignment can still appear in the else branch.
                // e.g., $a ? $b : $c = $d  →  $a ? $b : ($c = $d)
                let mut else_expr = parse_expr_bp(parser, TERNARY_BP + 1);
                if parser.current_kind().is_assignment_op() {
                    else_expr = parse_assign_continuation(parser, else_expr);
                }
                let span = lhs.span.merge(else_expr.span);
                lhs = Expr {
                    kind: ExprKind::Ternary(TernaryExpr {
                        condition: parser.alloc(lhs),
                        then_expr,
                        else_expr: parser.alloc(else_expr),
                    }),
                    span,
                };
                true
            }

            // Arrow operators (property/method access)
            TokenKind::Arrow | TokenKind::NullsafeArrow => {
                if MEMBER_ACCESS_BP < min_bp {
                    break;
                }
                check_dereferencable(parser, &lhs, kind);
                let is_nullsafe = kind == TokenKind::NullsafeArrow;
                if is_nullsafe {
                    let span = parser.current_span();
                    parser.require_version(PhpVersion::Php80, "nullsafe operator (?->)", span);
                }
                parser.advance(); // consume -> or ?->

                // Parse member name (identifier or keyword or variable for dynamic)
                let member = parse_member_name(parser);

                // Check if it's a method call
                if parser.check(TokenKind::LeftParen) {
                    match parse_arg_list_or_callable(parser) {
                        ArgListResult::CallableMarker => {
                            let span = Span::new(lhs.span.start, parser.previous_end());
                            let nullsafe_lhs = nullsafe_link(&lhs.kind, true);
                            if (is_nullsafe && !is_this(&lhs.kind)) || nullsafe_lhs {
                                parser.forbid(
                                    ForbiddenRule::NullsafeClosureCreation,
                                    "Cannot combine nullsafe operator with Closure creation",
                                    span,
                                );
                            }
                            let callable_kind = if is_nullsafe {
                                CallableCreateKind::NullsafeMethod {
                                    object: parser.alloc(lhs),
                                    method: parser.alloc(member),
                                }
                            } else {
                                CallableCreateKind::Method {
                                    object: parser.alloc(lhs),
                                    method: parser.alloc(member),
                                }
                            };
                            lhs = Expr {
                                kind: ExprKind::CallableCreate(CallableCreateExpr {
                                    kind: callable_kind,
                                }),
                                span,
                            };
                        }
                        ArgListResult::Args(args) => {
                            let span = Span::new(lhs.span.start, parser.previous_end());
                            let call = parser.alloc(MethodCallExpr {
                                object: parser.alloc(lhs),
                                method: parser.alloc(member),
                                args,
                            });
                            let expr_kind = if is_nullsafe {
                                ExprKind::NullsafeMethodCall(call)
                            } else {
                                ExprKind::MethodCall(call)
                            };
                            lhs = Expr {
                                kind: expr_kind,
                                span,
                            };
                        }
                    }
                } else {
                    let span = Span::new(lhs.span.start, member.span.end);
                    let expr_kind = if is_nullsafe {
                        ExprKind::NullsafePropertyAccess(PropertyAccessExpr {
                            object: parser.alloc(lhs),
                            property: parser.alloc(member),
                        })
                    } else {
                        ExprKind::PropertyAccess(PropertyAccessExpr {
                            object: parser.alloc(lhs),
                            property: parser.alloc(member),
                        })
                    };
                    lhs = Expr {
                        kind: expr_kind,
                        span,
                    };
                }
                true
            }

            // Null coalescing operator (produces NullCoalesce node, not Binary)
            TokenKind::QuestionQuestion => {
                if NULL_COALESCE_LEFT_BP < min_bp {
                    break;
                }
                parser.advance();
                // PHP grammar quirk: the right operand of ?? can contain assignment but not
                // unparenthesized ternary.  Use TERNARY_BP + 1 to block ternary, then
                // explicitly consume any following assignment operator.
                // e.g. `$a ?? $b = $c`  →  `$a ?? ($b = $c)`
                // e.g. `$a ?? $b ? $c : $d`  →  `($a ?? $b) ? $c : $d`
                let mut rhs = parse_expr_bp(parser, TERNARY_BP + 1);
                if parser.current_kind().is_assignment_op() {
                    rhs = parse_assign_continuation(parser, rhs);
                }
                let span = lhs.span.merge(rhs.span);
                lhs = Expr {
                    kind: ExprKind::NullCoalesce(NullCoalesceExpr {
                        left: parser.alloc(lhs),
                        right: parser.alloc(rhs),
                    }),
                    span,
                };
                true
            }

            // Assignment operators (right-associative)
            _ if kind.is_assignment_op() => {
                if ASSIGNMENT_BP < min_bp {
                    break;
                }
                lhs = parse_assign_continuation(parser, lhs);
                true
            }

            _ => false,
        };

        if should_continue {
            continue;
        }

        // Double colon: Class::$prop, Class::method(), Class::CONST
        // bp=90: must parse through the bp=45 gate used by promoted-property defaults
        // (which only intends to block `{}` curly-brace subscript access, bp=44).
        if kind == TokenKind::DoubleColon {
            if SCOPE_RESOLUTION_BP < min_bp {
                break;
            }
            check_dereferencable(parser, &lhs, kind);
            parser.advance(); // consume ::
            if matches!(lhs.kind, ExprKind::Parenthesized(_) | ExprKind::Array(_)) {
                if parser.check(TokenKind::Class) {
                    check_class_name_fetch_literal(parser, &lhs);
                } else {
                    check_class_name_literal(parser, &lhs);
                }
            }

            // Check what follows ::
            if parser.check(TokenKind::Variable) {
                let token = parser.advance();
                let var_name = parser.variable_name(token);
                let var_span = token.span;

                if parser.check(TokenKind::LeftParen) {
                    // Dynamic static method call: Class::$method()
                    let method = parser.alloc(Expr {
                        kind: ExprKind::Variable(NameStr::from_source(var_name)),
                        span: var_span,
                    });
                    match parse_arg_list_or_callable(parser) {
                        ArgListResult::CallableMarker => {
                            let span = Span::new(lhs.span.start, parser.previous_end());
                            lhs = Expr {
                                kind: ExprKind::CallableCreate(CallableCreateExpr {
                                    kind: CallableCreateKind::StaticMethod {
                                        class: parser.alloc(lhs),
                                        method,
                                    },
                                }),
                                span,
                            };
                        }
                        ArgListResult::Args(args) => {
                            let span = Span::new(lhs.span.start, parser.previous_end());
                            lhs = Expr {
                                kind: ExprKind::StaticMethodCallDynamic(parser.alloc(
                                    StaticMethodCallDynamicExpr {
                                        class: parser.alloc(lhs),
                                        method,
                                        args,
                                    },
                                )),
                                span,
                            };
                        }
                    }
                } else {
                    // Static property: Class::$prop
                    let member = parser.alloc(Expr {
                        kind: ExprKind::Identifier(NameStr::from_source(var_name)),
                        span: var_span,
                    });
                    let span = Span::new(lhs.span.start, var_span.end);
                    lhs = Expr {
                        kind: ExprKind::StaticPropertyAccess(StaticAccessExpr {
                            class: parser.alloc(lhs),
                            member,
                        }),
                        span,
                    };
                }
            } else if parser.check(TokenKind::Dollar) {
                // Dynamic static property: A::$$b, A::${'b'}
                let member = atom::parse_atom_nested(parser);
                let span = Span::new(lhs.span.start, member.span.end);
                lhs = Expr {
                    kind: ExprKind::StaticPropertyAccessDynamic {
                        class: parser.alloc(lhs),
                        member: parser.alloc(member),
                    },
                    span,
                };
            } else if parser.check(TokenKind::LeftBrace) {
                // Dynamic class constant/method: A::{'b'}(), Foo::{bar()}
                let brace_span = parser.current_span();
                parser.advance(); // consume {
                let member = parse_expr(parser);
                parser.expect(TokenKind::RightBrace);
                if parser.check(TokenKind::LeftParen) {
                    // Dynamic static method call: A::{'b'}()
                    match parse_arg_list_or_callable(parser) {
                        ArgListResult::CallableMarker => {
                            let span = Span::new(lhs.span.start, parser.previous_end());
                            lhs = Expr {
                                kind: ExprKind::CallableCreate(CallableCreateExpr {
                                    kind: CallableCreateKind::StaticMethod {
                                        class: parser.alloc(lhs),
                                        method: parser.alloc(member),
                                    },
                                }),
                                span,
                            };
                        }
                        ArgListResult::Args(args) => {
                            let span = Span::new(lhs.span.start, parser.previous_end());
                            lhs = Expr {
                                kind: ExprKind::StaticMethodCallDynamic(parser.alloc(
                                    StaticMethodCallDynamicExpr {
                                        class: parser.alloc(lhs),
                                        method: parser.alloc(member),
                                        args,
                                    },
                                )),
                                span,
                            };
                        }
                    }
                } else {
                    // Dynamic class constant: Foo::{bar()}
                    parser.require_version(
                        PhpVersion::Php83,
                        "dynamic class constant fetch",
                        brace_span,
                    );
                    let span = Span::new(lhs.span.start, parser.previous_end());
                    lhs = Expr {
                        kind: ExprKind::ClassConstAccessDynamic {
                            class: parser.alloc(lhs),
                            member: parser.alloc(member),
                        },
                        span,
                    };
                }
            } else if parser.check(TokenKind::Class) {
                // Special: Class::class (class name resolution)
                if parser.version < PhpVersion::Php80 && !matches!(lhs.kind, ExprKind::Name(_)) {
                    parser.forbid(
                        ForbiddenRule::DynamicClassFetch,
                        "Cannot use ::class with dynamic class name",
                        lhs.span,
                    );
                }
                let token = parser.advance();
                let span = Span::new(lhs.span.start, token.span.end);
                lhs = Expr {
                    kind: ExprKind::ClassConstAccess(StaticAccessExpr {
                        class: parser.alloc(lhs),
                        member: parser.alloc(Expr {
                            kind: ExprKind::Identifier(NameStr::from_source("class")),
                            span: token.span,
                        }),
                    }),
                    span,
                };
            } else {
                // Static method call or class constant
                let (member_name, member_span) =
                    if let Some(result) = parser.eat_identifier_or_keyword() {
                        result
                    } else {
                        let err_span = parser.current_span();
                        parser.error(ParseError::Expected {
                            expected: "identifier".into(),
                            found: parser.current_kind().description().into(),
                            span: err_span,
                        });
                        let span = Span::new(lhs.span.start, err_span.end);
                        lhs = Expr {
                            kind: ExprKind::Error,
                            span,
                        };
                        continue;
                    };

                if parser.check(TokenKind::LeftParen) {
                    let method = parser.alloc(Expr {
                        kind: ExprKind::Identifier(NameStr::from_source(member_name)),
                        span: member_span,
                    });
                    match parse_arg_list_or_callable(parser) {
                        ArgListResult::CallableMarker => {
                            let span = Span::new(lhs.span.start, parser.previous_end());
                            lhs = Expr {
                                kind: ExprKind::CallableCreate(CallableCreateExpr {
                                    kind: CallableCreateKind::StaticMethod {
                                        class: parser.alloc(lhs),
                                        method,
                                    },
                                }),
                                span,
                            };
                        }
                        ArgListResult::Args(args) => {
                            let span = Span::new(lhs.span.start, parser.previous_end());
                            lhs = Expr {
                                kind: ExprKind::StaticMethodCall(parser.alloc(
                                    StaticMethodCallExpr {
                                        class: parser.alloc(lhs),
                                        method,
                                        args,
                                    },
                                )),
                                span,
                            };
                        }
                    }
                } else {
                    // Class constant
                    let member = parser.alloc(Expr {
                        kind: ExprKind::Identifier(NameStr::from_source(member_name)),
                        span: member_span,
                    });
                    let span = Span::new(lhs.span.start, parser.previous_end());
                    lhs = Expr {
                        kind: ExprKind::ClassConstAccess(StaticAccessExpr {
                            class: parser.alloc(lhs),
                            member,
                        }),
                        span,
                    };
                }
            }
            continue;
        }

        // Array access: $arr[index]
        if kind == TokenKind::LeftBracket {
            if MEMBER_ACCESS_BP < min_bp {
                break;
            }
            check_dereferencable(parser, &lhs, kind);
            parser.advance(); // consume [
            let index = if parser.check(TokenKind::RightBracket) {
                parser.empty_dim_count += 1;
                None
            } else {
                let e = parse_expr(parser);
                Some(parser.alloc(e))
            };
            parser.expect(TokenKind::RightBracket);
            let span = Span::new(lhs.span.start, parser.previous_end());
            lhs = Expr {
                kind: ExprKind::ArrayAccess(ArrayAccessExpr {
                    array: parser.alloc(lhs),
                    index,
                }),
                span,
            };
            continue;
        }

        // Curly brace array/string access: $a{'b'} — removed in PHP 8.0.
        if kind == TokenKind::LeftBrace {
            if MEMBER_ACCESS_BP < min_bp || parser.no_brace_subscript {
                break;
            }
            let brace_span = parser.current_span();
            parser.advance(); // consume {
            let index = if parser.check(TokenKind::RightBrace) {
                None
            } else {
                let e = parse_expr(parser);
                Some(parser.alloc(e))
            };
            parser.expect(TokenKind::RightBrace);
            // PHP 7.4 only deprecates the syntax, which it has for variables alone.
            if parser.version >= PhpVersion::Php80 {
                parser.forbid(
                    ForbiddenRule::CurlyOffsetAccess,
                    CURLY_OFFSET_REMOVED,
                    brace_span,
                );
            } else if matches!(
                lhs.kind,
                ExprKind::Name(_)
                    | ExprKind::ClassConstAccess(_)
                    | ExprKind::MagicConst(_)
                    | ExprKind::InterpolatedString(_)
            ) {
                parser.error(ParseError::Expected {
                    expected: "';'".into(),
                    found: "'{'".into(),
                    span: brace_span,
                });
            }
            let span = Span::new(lhs.span.start, parser.previous_end());
            lhs = Expr {
                kind: ExprKind::ArrayAccess(ArrayAccessExpr {
                    array: parser.alloc(lhs),
                    index,
                }),
                span,
            };
            continue;
        }

        // Function call: name(args)
        if kind == TokenKind::LeftParen {
            if MEMBER_ACCESS_BP < min_bp {
                break;
            }
            check_dereferencable(parser, &lhs, kind);
            lhs = parse_function_call(parser, lhs);
            continue;
        }

        // Infix binary operators
        if let Some((left_bp, right_bp)) = precedence::infix_binding_power(kind) {
            if left_bp < min_bp {
                break;
            }
            // Chaining non-associative operators within the same precedence group
            // is a syntax error (e.g. `1 < 2 < 3`, `$a === $b == $c`).
            // Cross-group chains (e.g. `$a > $b == $c`) and instanceof chains are
            // allowed by PHP and must not be flagged here.
            if let Some(current_level) = nonassoc_chain_level_for_token(kind) {
                if matches!(&lhs.kind, ExprKind::Binary(b) if nonassoc_chain_level_for_op(b.op) == Some(current_level))
                {
                    let span = parser.current_span();
                    parser.forbid(
                        ForbiddenRule::NonAssociativeChain,
                        "Chaining non-associative operators requires explicit parentheses.",
                        span,
                    );
                }
            }
            let op_token = parser.advance();
            if op_token.kind == TokenKind::PipeArrow {
                parser.require_version(PhpVersion::Php85, "pipe operator (|>)", op_token.span);
            }
            let op = token_to_binary_op(op_token.kind).unwrap_or_else(|| {
                unreachable!(
                    "infix_binding_power returned Some for {:?} but token_to_binary_op returned None",
                    op_token.kind
                )
            });
            // PHP grammar quirk: assignment escapes rightward through every binary operator.
            // e.g. `$a && $b = $c`   →  `$a && ($b = $c)`
            //      `$a + $b + $c = 5` → `$a + $b + ($c = 5)`
            // parse_expr_bp with right_bp > ASSIGNMENT_BP won't consume the assignment,
            // so we explicitly apply it here (same pattern as the `??` branch above).
            let lhs_truth = match chain_truth {
                _ if !is_short_circuit(op) => None,
                Some((span, truth)) if span == lhs.span => truth,
                _ => folded_truth(&lhs),
            };
            let short_circuits = match (op, lhs_truth) {
                (BinaryOp::BooleanAnd | BinaryOp::LogicalAnd, Some(truth)) => !truth,
                (BinaryOp::BooleanOr | BinaryOp::LogicalOr, Some(truth)) => truth,
                _ => false,
            };
            if op == BinaryOp::Instanceof && parser.check(TokenKind::LeftParen) {
                let span = parser.current_span();
                parser.require_version(PhpVersion::Php80, "instanceof with an expression", span);
            }
            // `instanceof static` names the class; `static` is no expression on its own.
            let instanceof_static = op == BinaryOp::Instanceof
                && parser.check(TokenKind::Static)
                && parser.peek_kind() != Some(TokenKind::DoubleColon);
            let mut rhs = if instanceof_static {
                let token = parser.advance();
                parser.has_class_keyword_ref = true;
                atom::simple_name_expr("static", token.span)
            } else {
                parse_expr_bp(parser, right_bp)
            };
            if parser.current_kind().is_assignment_op() {
                rhs = parse_assign_continuation(parser, rhs);
            }
            if short_circuits {
                parser.uncompiled_spans.push(rhs.span);
            }
            if op == BinaryOp::Instanceof {
                if is_class_name_reference(&rhs) {
                    check_class_name_literal(parser, &rhs);
                } else {
                    parser.forbid(ForbiddenRule::InvalidInstanceofOperand, "right side of instanceof must be a class name, a variable or a parenthesized expression", rhs.span);
                }
            }
            // Check if pipe operator has unparenthesized arrow function on RHS
            if op == BinaryOp::Pipe && matches!(rhs.kind, ExprKind::ArrowFunction(_)) {
                parser.forbid(
                    ForbiddenRule::UnparenthesizedArrowInPipe,
                    "arrow function on the right side of pipe operator must be parenthesized",
                    rhs.span,
                );
            }
            let span = lhs.span.merge(rhs.span);
            if is_short_circuit(op) {
                let truth = match lhs_truth {
                    Some(truth) if short_circuits => Some(truth),
                    Some(_) => folded_truth(&rhs),
                    None => None,
                };
                chain_truth = Some((span, truth));
            }
            lhs = Expr {
                kind: ExprKind::Binary(BinaryExpr {
                    left: parser.alloc(lhs),
                    op,
                    right: parser.alloc(rhs),
                }),
                span,
            };
            continue;
        }

        // Not an operator we handle — stop
        break;
    }

    parser.leave_nesting();
    lhs
}

/// Parse a member name after -> or ?->. Accepts identifiers and semi-reserved keywords.
pub(crate) fn parse_member_name<'arena, 'src>(
    parser: &'_ mut Parser<'arena, 'src>,
) -> Expr<'arena, 'src> {
    // After `->` PHP's lexer reads any label as a name, `__halt_compiler` included.
    if parser.check(TokenKind::Identifier)
        || parser.is_semi_reserved_keyword()
        || parser.check(TokenKind::HaltCompiler)
    {
        let token = parser.advance();
        let text = &parser.source[token.span.start as usize..token.span.end as usize];
        return Expr {
            kind: ExprKind::Identifier(NameStr::from_source(text)),
            span: token.span,
        };
    }
    match parser.current_kind() {
        // Dynamic: $obj->$var
        TokenKind::Variable => {
            let token = parser.advance();
            let name = parser.variable_name(token);
            Expr {
                kind: ExprKind::Variable(NameStr::from_source(name)),
                span: token.span,
            }
        }
        // Dynamic: $obj->{expr}
        TokenKind::LeftBrace => {
            parser.advance();
            let inner = parse_expr(parser);
            parser.expect(TokenKind::RightBrace);
            inner
        }
        // Dynamic: $obj->${expr} — variable-variable as member name.
        // Also bare $obj->$$var chain.
        TokenKind::Dollar => {
            let start = parser.start_span();
            parser.advance(); // consume $
            let inner = if parser.eat(TokenKind::LeftBrace).is_some() {
                let e = parse_expr(parser);
                parser.expect(TokenKind::RightBrace);
                e
            } else {
                atom::parse_variable_variable_name(parser)
            };
            let span = Span::new(start, parser.previous_end());
            Expr {
                kind: ExprKind::VariableVariable(parser.alloc(inner)),
                span,
            }
        }
        _ => {
            let span = parser.current_span();
            parser.error(ParseError::Expected {
                expected: "member name".into(),
                found: parser.current_kind().description().into(),
                span,
            });
            Expr {
                kind: ExprKind::Error,
                span,
            }
        }
    }
}

fn token_to_binary_op(kind: TokenKind) -> Option<BinaryOp> {
    match kind {
        TokenKind::Plus => Some(BinaryOp::Add),
        TokenKind::Minus => Some(BinaryOp::Sub),
        TokenKind::Star => Some(BinaryOp::Mul),
        TokenKind::Slash => Some(BinaryOp::Div),
        TokenKind::Percent => Some(BinaryOp::Mod),
        TokenKind::StarStar => Some(BinaryOp::Pow),
        TokenKind::Dot => Some(BinaryOp::Concat),
        TokenKind::EqualsEquals => Some(BinaryOp::Equal),
        TokenKind::BangEquals => Some(BinaryOp::NotEqual),
        TokenKind::EqualsEqualsEquals => Some(BinaryOp::Identical),
        TokenKind::BangEqualsEquals => Some(BinaryOp::NotIdentical),
        TokenKind::LessThan => Some(BinaryOp::Less),
        TokenKind::GreaterThan => Some(BinaryOp::Greater),
        TokenKind::LessThanEquals => Some(BinaryOp::LessOrEqual),
        TokenKind::GreaterThanEquals => Some(BinaryOp::GreaterOrEqual),
        TokenKind::Spaceship => Some(BinaryOp::Spaceship),
        TokenKind::AmpersandAmpersand => Some(BinaryOp::BooleanAnd),
        TokenKind::PipePipe => Some(BinaryOp::BooleanOr),
        TokenKind::Ampersand => Some(BinaryOp::BitwiseAnd),
        TokenKind::Pipe => Some(BinaryOp::BitwiseOr),
        TokenKind::Caret => Some(BinaryOp::BitwiseXor),
        TokenKind::ShiftLeft => Some(BinaryOp::ShiftLeft),
        TokenKind::ShiftRight => Some(BinaryOp::ShiftRight),
        TokenKind::And => Some(BinaryOp::LogicalAnd),
        TokenKind::Or => Some(BinaryOp::LogicalOr),
        TokenKind::Xor => Some(BinaryOp::LogicalXor),
        TokenKind::Instanceof => Some(BinaryOp::Instanceof),
        TokenKind::PipeArrow => Some(BinaryOp::Pipe),
        _ => None,
    }
}